Safe Code
Run a complete repo hygiene pass autonomously. Think before acting. Make decisions independently. Only ask the user when a decision cannot be reversed or when intent is genuinely unclear.
Apply $senior-dev discipline throughout the run: task list first, measure twice cut once, adversarial strategy critique, clean repo policy, small reversible slices, and verification before completion.
Scope Rule (Read This First)
Everything operates inside the current project root only.
- Never read from or write to paths outside the current project root
- Never use
~/,~/.safe-code/, or any home directory path - All paths are relative to the project root
- The project root is the directory where the agent was invoked
- Graph MCP bootstrap may create or update
<project-root>/.mcp.jsononly. Do not auto-edit global agent MCP config.
CORRECT: <project-root>/.safe-code/ACTIVE.md
WRONG: ~/.safe-code/ACTIVE.md
Doc Structure
<project-root>/
├── AGENTS.md <- canonical entry point + Read First order (source of truth)
├── CLAUDE.md <- ┐
├── GEMINI.md <- │ provider bridges: thin pointers to AGENTS.md so each
├── .github/copilot-instructions.md<- │ host auto-loads the same brain (no state, just redirect)
├── .cursor/rules/safe-code.mdc <- ┘
└── .safe-code/ <- the project brain + all session state (continuity)
├── ACTIVE.md <- saved resume point; written on /safe-code --save
├── SESSION.md <- working memory + draft doc/context updates
├── LOG.md <- append-only safe diary; no raw secrets/log dumps
├── BACKLOG.md <- operational task queue
├── MEMORY.md <- temporary audit/refactor architecture notes
├── safe-refactor-code.md <- refactor rules and flagged candidates
├── CHANGELOG.md <- release history (update on release only)
└── context/ <- project brain; canonical long-term context
├── project-overview.md <- what, who, goals, scope, success criteria
├── architecture.md <- stack, boundaries, storage, invariants
├── user-preferences.md <- user-approved preferences and hard dislikes
├── code-standards.md <- implementation conventions
├── ai-workflow-rules.md <- agent workflow and scoping rules
├── ui-context.md <- UI/design conventions (read only for UI work)
├── progress-tracker.md <- phase, current goal, decisions, safe session notes
├── current-issues.md <- issue tracker: user + AI-appended; local-only, gitignored
└── feature-specs/ <- AI-written specs w/ status field; suggestions + active units
└── 00-template.md
/safe-code keeps all continuity in one place — AGENTS.md + the .safe-code/ folder are the single source of truth. It also writes thin provider-bridge pointers (CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, .cursor/rules/safe-code.mdc) so hosts that do not auto-read AGENTS.md still load the same brain. Bridges hold no state — they only redirect to AGENTS.md and .safe-code/. Never store session/context docs in .codex/, .claude/, .cursor/, .windsurf/, or .agents/ — those are legacy layouts that get migrated into .safe-code/ and removed (the bridge pointers above are not session state and are preserved).
Everything lives in one shared .safe-code/ folder at the project root, regardless of which agent (Codex, Claude, Cursor, Windsurf, Copilot, Gemini) is running — continuity belongs to the project, not the tool. (Per-host bridge mechanics are defined once in the Provider Bridge section, Step 1.)
The six session files (ACTIVE.md, SESSION.md, LOG.md, BACKLOG.md, MEMORY.md, safe-refactor-code.md) sit directly inside .safe-code/. .safe-code/context/ is canonical project context; the six session files are operational session state.
Loading Layers
Layer 1 — Entry (every session)
AGENTS.md — root instructions and Read First order
.safe-code/context/project-overview.md — product/project definition
.safe-code/context/architecture.md — system boundaries and invariants
.safe-code/context/user-preferences.md — user-approved preferences and hard dislikes
.safe-code/context/code-standards.md — coding conventions
.safe-code/context/ai-workflow-rules.md — workflow rules
.safe-code/context/ui-context.md — only for UI/design work
.safe-code/context/progress-tracker.md — Current Phase, Current Goal, Next Up, Open Questions only
ACTIVE.md — Before/Current/Next blocks only, if present
SESSION.md — Carry Forward + draft updates only, if present
LOG.md — last 3 typed entries only, if present
Do not read .safe-code/context/current-issues.md during normal work. Read and append to it when the user reports an issue — trigger phrases like "fix this", "failed", "got error", "bug", "crash", "tak jalan", "rosak", or a pasted stack trace — or when the user references that file. See the Issue Tracking Rule.
Layer 2 — Resume (/safe-code --continue or auto-continue)
.safe-code/context/progress-tracker.md — full content
ACTIVE.md — full content
SESSION.md — full content
LOG.md — full content if Last Session.status = saved
/safe-code must auto-use Layer 2 when saved unfinished state exists, even if the user forgot --continue.
Layer 3 — Detail (triggered only)
.safe-code/context/feature-specs/<active>.md — feature/refactor work contract
.safe-code/context/architecture.md — audit/refactor/debug impact checks
MEMORY.md — old/migrated architecture notes or audit detail
safe-refactor-code.md — cleanup/refactor candidates and guardrails
BACKLOG.md — operational queue sync
.safe-code/CHANGELOG.md — releasable changes only
Do not load detail files unless the trigger condition is met.
Project Context vs Session State
.safe-code/context/ |
.safe-code/ |
|
|---|---|---|
| Purpose | Long-term project brain | Runtime/session memory |
| Updated | Draft during work, finalize on /safe-code --save |
SESSION.md during work; others on save |
| Canonical for | Product, architecture, standards, workflow, progress | Resume point, logs, cleanup/refactor notes |
| Secrets/raw logs | Never | Avoid; keep summaries only |
.safe-code/context/current-issues.md is special: safe-code creates the template and gitignores it. Both the user and the agent write it — the user pastes raw context, and the agent appends/updates issue entries on error triggers (see the Issue Tracking Rule). It stays gitignored and may contain raw errors, URLs, or secrets, so never copy its raw content into committed docs; a sanitized one-line summary of a fixed bug goes to LOG.md instead.
.safe-code/context/user-preferences.md captures explicit, durable user preferences from conversation. Add only when the user clearly says they want/avoid something, or repeats a preference. Draft changes in SESSION.md and apply on /safe-code --save.
Source-of-Truth Ownership
Avoid duplicate truth. Each fact has exactly one canonical home:
| Fact type | Canonical home | Non-canonical notes |
|---|---|---|
| Root read order and agent rules | AGENTS.md |
Do not duplicate full rules in context files |
| Product goals, users, scope | .safe-code/context/project-overview.md |
progress-tracker.md may reference current goal only |
| Stack, boundaries, invariants | .safe-code/context/architecture.md |
MEMORY.md stores temporary audit notes only |
| User preferences and hard dislikes | .safe-code/context/user-preferences.md |
AGENTS.md may point to it, not duplicate all preferences |
| Coding conventions | .safe-code/context/code-standards.md |
safe-refactor-code.md may store refactor-specific guardrails only |
| Agent workflow | .safe-code/context/ai-workflow-rules.md |
SESSION.md may hold temporary execution notes |
| UI design system | .safe-code/context/ui-context.md |
Read only for UI/design work |
| Current phase and safe decisions | .safe-code/context/progress-tracker.md |
ACTIVE.md stores resume state, not project history |
| Feature scope + idea history | .safe-code/context/feature-specs/<nn-name>.md |
Each spec carries a status: field (suggested/approved/in-progress/done/rejected); do not spread feature requirements across progress notes |
| Release/user-visible history | .safe-code/CHANGELOG.md |
Use for Added/Changed/Removed/Fixed/Security entries only |
| Issue tracking | .safe-code/context/current-issues.md |
Local-only, gitignored; user + agent-written. Sanitized fixed-bug summary may also go to LOG.md |
| Resume point | .safe-code/ACTIVE.md |
Operational state only |
| Live task list and drafts | .safe-code/SESSION.md |
Wiped on save |
| Cleanup/refactor candidates | .safe-code/safe-refactor-code.md |
Not general architecture truth |
When two files disagree, prefer executable repo evidence first, then canonical home, then session notes. Record mismatch in SESSION.md and fix canonical home on /safe-code --save.
Command Recognition (Read Before Parsing Any Command)
Different hosts wrap skill invocation differently. Treat all of the following as the same safe-code invocation, then parse the trailing argument (if any) to pick the mode:
/safe-code /skill:safe-code /skills safe-code
/skill safe-code /skill safe-code $safe-code
@safe-code safe-code run safe-code
Normalization rule:
- Strip any host prefix or wrapper (
/,$,@,skill:,skill,skills,run) and thesafe-codename. - Whatever remains is the argument. Map it to a mode:
- empty ->
/safe-code(setup / auto-resume / fresh pass) --continue,continue,-c,resume-> continue mode--save,save,-s,finish,end-> save mode--explain,explain,explain my project,what does my app do,apa projek-> explain mode (read-only briefing)fresh pass,fresh setup,ignore saved state-> force a fresh pass
- empty ->
- The canonical forms are
/safe-code,/safe-code --continue,/safe-code --save,/safe-code --explain. Use them in your own output, but accept any wrapper the host produced.
If the argument is unrecognized, default to plain /safe-code behavior and note which form you received. Never refuse a run just because the host used a different prefix.
Command: /safe-code
Run setup, auto-resume, or a fresh hygiene pass.
Behavior:
- Locate project root and the single
.safe-code/folder. - If saved unfinished safe-code state exists, automatically behave like
/safe-code --continueand print:Saved safe-code session found; resuming automatically. Say "fresh pass" to ignore saved state. - If no saved state exists, initialize/reconcile doc structure.
- If any legacy layout exists (
.codex/agents/,.claude/agents/,.cursor/agents/,.windsurf/agents/, v3.agents/, or safe-code-managed rootcontext/), run Legacy Layout Migration: move content into.safe-code/, patch old config to the new paths, remove the emptied legacy folders. - Explore repo facts and select the safest profile: Orientation, Audit, or Cleanup.
Start a truly fresh pass only when no saved state exists or user explicitly says fresh pass, fresh setup, or ignore saved state.
Command: /safe-code --continue
Resume an existing safe-code session with full context loading. Use this in a new chat, new day, or after /safe-code --save. /safe-code auto-enters this mode when saved state exists.
First, detect old setup config (legacy folders, old .gitignore entry, old AGENTS.md paths). If found, run Legacy Layout Migration before loading anything — saved state may still live in the old location.
Before doing work, read:
1. AGENTS.md
2. .safe-code/context/progress-tracker.md
3. ACTIVE.md
4. SESSION.md
5. LOG.md
6. active .safe-code/context/feature-specs/<file>.md if resuming a feature
7. MEMORY.md / safe-refactor-code.md only if audit/refactor/debug resumes
Do not guess previous context. If saved state contradicts repo evidence, trust executable repo evidence and record the mismatch in SESSION.md.
Command: /safe-code --save
End the session safely.
Save does these things:
0. Detect old setup config (legacy folders, old .gitignore entry, old AGENTS.md
paths) — if found, run Legacy Layout Migration first so the save lands in
.safe-code/ on the new version
1. Review SESSION.md draft updates
2. Apply approved context/doc updates
3. Update .safe-code/context/progress-tracker.md with safe summary only; set
last_synced_commit to current HEAD and context_synced_at to today (Context Freshness Check)
4. Update ALL SIX session files (Six-File Save Rule below):
- ACTIVE.md -> Last Session block + next_action
- SESSION.md -> wipe to clean carry-forward template
- LOG.md -> append safe typed summary + a `plain:` one-line recap
a non-coder can read (then apply trim rule)
- BACKLOG.md -> sync queue from SESSION.md drafts
- MEMORY.md -> apply drafted audit/refactor notes
- safe-refactor-code.md -> apply flagged candidates and guardrail changes
5. Update .safe-code/CHANGELOG.md only for releasable changes
6. Ensure local git repo exists when allowed by current repo state
7. Split the session into atomic commits (Atomic Commit Split Rule below)
8. Report commit hashes + types + local-only status + next action
Do not push.
Atomic Commit Split Rule
/safe-code --save turns the session's one save into several atomic commits grouped by logical change. The commit gate is unchanged: this still happens only at --save, stays local-only, and never pushes.
Split procedure (best-effort):
- Read
SESSION.mdcompleted tasks and each task's recorded touched paths + commit type (Task Annotation, Measure Twice section). - Order commits: code/behavior tasks first in task order, then ONE final bookkeeping commit for the
.safe-code/session files +context/updates. - For each group, stage only that group's paths (
git add <paths>) and commit with a conventionaltype: subjectmessage derived from the task. Never use--no-verify. - The six session files +
context/updates are ALWAYS the last commit, never mixed with code:docs: sync .safe-code session files. - Do not re-run verification between commits — each task was already verified per-slice during the run (Step 6). The split is a staging/commit operation over already-good changes. If a task's changes cannot stand alone, merge it with its dependency into one commit rather than emit a broken commit.
Commit type mapping:
| Work | type |
|---|---|
| dead-code removal, rename, restructure (Step 6/7) | refactor |
bug fix ($debug-issue / issue tracker) |
fix |
| new feature from a feature spec | feat |
| test additions/changes | test |
.safe-code/ session files, context/, CHANGELOG.md, AGENTS.md |
docs |
config/tooling/.gitignore |
chore |
Fallback (degrade to single commit):
if hunks overlap across tasks, the task list is thin/unannotated,
or changes cannot be cleanly separated:
-> stage everything, make ONE local commit (today's behavior)
-> append LOG.md note: "atomic split skipped: <reason>"
The save never fails or blocks because of splitting. Atomic splitting can only ever improve a save, never break one.
Six-File Save Rule
Every /safe-code --save MUST update all six session files in .safe-code/ — no exceptions, no "nothing changed" skips:
| File | Always written on save |
|---|---|
ACTIVE.md |
Last Session block, pending list, next_action |
SESSION.md |
Wiped to clean carry-forward template with fresh date stamp |
LOG.md |
One new typed entry appended (even a short verify/decision entry), each carrying a plain: one-line recap a non-coder can read |
BACKLOG.md |
Drafted items applied; otherwise refresh the _<DATE>_ stamp |
MEMORY.md |
Drafted notes applied; otherwise refresh the _<DATE>_ stamp |
safe-refactor-code.md |
Flagged candidates applied; otherwise refresh the _<DATE>_ stamp |
If a file has no new content this session, still refresh its date stamp so all six files provably reflect the last save. A save that leaves any of the six files untouched is an incomplete save — verify all six are in the commit diff before reporting done.
Draft-Until-Save Rule
During normal work, draft updates to .safe-code/context/*.md, AGENTS.md, .safe-code/CHANGELOG.md, and continuity docs in SESSION.md. Apply final persistent doc/context updates on /safe-code --save.
Exceptions:
- Create missing scaffold files/folders needed for safe operation.
- Add
/.safe-code/context/current-issues.mdto.gitignoreduring setup. - First-Run Population (see Step 1): on the first
/safe-coderun, populate empty scaffoldAGENTS.md+ evidence-derivable context files immediately, so agents have real context without waiting for--save. - Append/update issue entries in
.safe-code/context/current-issues.mdon error triggers (see the Issue Tracking Rule). This file is local-only/gitignored, so it is never part of a commit. - Write a feature spec (including a
status: suggestedidea) before implementation, or whenever a new feature is proposed (see the Feature Suggestion Rule). - Update code files as required by the user task.
The agent may append issue entries to .safe-code/context/current-issues.md, but must never copy its raw content (secrets, stack traces, private URLs) into any committed file.
Command: /safe-code --explain
Read the project brain back to the user in plain language. Read-only: make no edits, no commits, no save, and run no hygiene pass. This is for a non-technical user who wants to remember what their own project does.
Behavior:
- If
.safe-code/context/is missing or empty -> say there is no project brain yet and suggest running/safe-codefirst, then stop. - Otherwise load
project-overview.md,architecture.md, andprogress-tracker.md, and brief the user in plain language — no jargon dumps, no raw file contents:
What it does: <one or two sentences, and who it's for>
Built with: <stack in plain terms>
Where it's at: <current phase / what works now>
In progress: <current goal / next up>
Open questions: <unknowns from progress-tracker, if any>
- If the brain conflicts with executable repo evidence, trust the repo and say so briefly.
Do not load Layer 3, run helpers, audit, or touch git. --explain answers a question; it never changes the repo.
Deprecated Command Forms
/safe-code save-> print: "Use/safe-code --save."/safe-code continue-> print: "Use/safe-code --continue."
How to Make Decisions
Before every action, reason explicitly. Do not guess. Do not skip this.
Measure Twice, Cut Once Policy
Every run must maintain a visible task checklist in SESSION.md. The checklist is the working plan and progress tracker.
HARD RULE: Keep the codebase clean, no tmp files, no dead code, no dead files. Stay organized all the time. No unnecessary folders, subfolders, or files.
Rules:
- Create or refresh
SESSION.md ## Task Listbefore Step 3. - Every meaningful task starts as
[ ]. - Mark a task
[~]while actively working on it. - Mark a task
[x]only after the action and its verification are complete. - Add newly discovered work as a new task instead of doing it invisibly.
- Draft unrelated or deferred tasks for
BACKLOG.mdinSESSION.md; do not hide them in prose. - On
/safe-code --save, migrate unfinished checklist items intoACTIVE.md Last Session.pendingandnext_action. - Do not claim completion unless the checklist, verification output, and final summary agree.
- If verification fails, keep the task
[~]or[ ], add the failure note, and route to$debug-issuewhen appropriate. - When marking a task
[x], annotate it with the paths it touched and its commit type, so/safe-code --savecan map each task to one atomic commit (Atomic Commit Split Rule). Record paths while the info is fresh; never reconstruct at save time. A missing annotation is a thin task list — the split falls back to a single commit.
Task annotation format:
- [x] remove unused dateUtil · type: refactor · files: src/utils/dateUtil.ts
Default checklist:
## Task List
- [ ] Locate project root and `.safe-code/` folder
- [ ] Initialize or reconcile AGENTS.md, context, and session docs
- [ ] Detect saved state or legacy layout migration need
- [ ] Load required context for this command
- [ ] Check context freshness (drift vs last_synced_commit)
- [ ] Draft or update active feature spec if needed
- [ ] Check git state and rollback safety
- [ ] Check or bootstrap graph support when useful
- [ ] Explore repo facts before context backfill
- [ ] Run context self-test after backfill (verify brain is sufficient)
- [ ] Audit dead code and stale files only when in scope
- [ ] Audit agent config trust artifacts when in scope
- [ ] Decide run profile and execution mode
- [ ] Execute scoped code changes if requested
- [ ] Review changes and test coverage
- [ ] Debug verification failures, if any
- [ ] Draft docs/context updates in SESSION.md
- [ ] Save final docs/context updates on /safe-code --save
Decision Framework
- What are the 2-3 options?
- What does each risk or preserve?
- Which is safest given what I know?
- Can this be undone?
- What am I assuming? → verify from codebase first; ask only if cannot verify
If assumption is about user intent (not a technical fact) → verify from codebase first. If assumption cannot be verified from codebase → stop and ask.
If (4) = no → stop, show options to user before acting. If (4) = yes → proceed with safest option, log reasoning.
Act Autonomously When
- Action is reversible (git tracked)
- Confidence is High (zero references, no dynamic risk)
- Decision is technical, not about user intent
- Answer is discoverable from the codebase
Stop and Ask When
- Action is irreversible (no git, no backup)
- Confidence is Low
- Unexpected scope change (blast radius > 10 files)
Never ask about Medium confidence candidates — apply auto-promotion rule instead.
Reasoning Format
Reasoning:
Options: <list>
Risk: <list>
Decision: <chosen>
Why: <one sentence>
Reversible: yes/no
Assumptions: <list — or "none">
Step 0: Locate Project Root
Session state lives in a single agent-agnostic folder at the project root:
safe-code folder = <project-root>/.safe-code/
No agent detection is needed. Codex, Claude, Cursor, and Windsurf all share the same .safe-code/ folder so continuity belongs to the project, not the tool. Create <project-root>/.safe-code/ if it does not exist.
HARD RULE: never create .codex/, .claude/, .cursor/, .windsurf/, or .agents/ folders for session state. If any of them exist with safe-code docs inside, run Legacy Layout Migration (Step 1) — migrate their content into .safe-code/ and remove them. Exception: the Provider Bridge (Step 1) may write a thin read-pointer in a host's native config location (e.g. .cursor/rules/safe-code.mdc, .github/copilot-instructions.md); these hold no state, only a redirect to AGENTS.md/.safe-code/, and are never treated as legacy.
Step 1: Initialize Doc Structure
Create only the scaffold needed for safe operation before reading the codebase. Do not populate long-term context with guesses.
Create missing folders/files:
AGENTS.md
CLAUDE.md (provider bridge — pointer only)
GEMINI.md (provider bridge — pointer only)
.github/copilot-instructions.md (provider bridge — pointer only)
.cursor/rules/safe-code.mdc (provider bridge — pointer only)
.safe-code/CHANGELOG.md
.safe-code/context/
.safe-code/context/project-overview.md
.safe-code/context/architecture.md
.safe-code/context/user-preferences.md
.safe-code/context/code-standards.md
.safe-code/context/ai-workflow-rules.md
.safe-code/context/ui-context.md
.safe-code/context/progress-tracker.md
.safe-code/context/current-issues.md
.safe-code/context/feature-specs/
.safe-code/context/feature-specs/00-template.md
.safe-code/ACTIVE.md
.safe-code/SESSION.md
.safe-code/LOG.md
.safe-code/BACKLOG.md
.safe-code/MEMORY.md
.safe-code/safe-refactor-code.md
Rules:
- If a file exists, do not overwrite it.
- Create missing context files with templates only.
- Add
/.safe-code/context/current-issues.mdto.gitignoreif absent. - The user owns
.safe-code/context/current-issues.md; the agent only appends issue entries on error triggers (Issue Tracking Rule) and never copies its raw content into committed files. - For project facts, inspect repo evidence first.
- On the first run (empty scaffold), populate evidence-derivable context files immediately (First-Run Population below). On later runs, draft updates in
SESSION.mdand apply on/safe-code --saveunless a scaffold file or active feature spec is required now.
Existing Project Backfill
If the repo already has code, docs, manifests, routes, schemas, tests, or configs:
- Treat the repo as source of truth.
- Backfill
.safe-code/context/*.mdfrom evidence only. - Put unverifiable product or architecture facts into
.safe-code/context/progress-tracker.mdOpen Questions. - Generate feature specs for upcoming work, active bugs, refactors, or missing documentation units; record new feature ideas as
status: suggestedspecs (Feature Suggestion Rule). - Do not create fake historical specs for completed features unless the user asks.
First-Run Population
The whole point of the first run is that any agent can read real context afterward and not hallucinate. So on the first /safe-code run — when the target file is still an empty scaffold — write context immediately instead of waiting for --save:
| File | First-run write |
|---|---|
AGENTS.md |
Yes — Read First order + verified project facts/commands |
.safe-code/context/project-overview.md |
Yes — from README, manifests, package metadata |
.safe-code/context/architecture.md |
Yes — stack, boundaries, invariants, and a Navigation map (where things live / entry points) from manifests/folders/configs |
.safe-code/context/code-standards.md |
Yes — conventions from linter/formatter/tsconfig/editorconfig |
.safe-code/context/ai-workflow-rules.md |
Only if repo/team docs reveal real workflow; else leave template |
.safe-code/context/progress-tracker.md |
Yes — Current Phase + Open Questions (unverifiable facts) |
.safe-code/context/user-preferences.md |
No — conversation-derived only, no repo evidence |
.safe-code/context/ui-context.md |
No — only when UI/design work occurs |
.safe-code/context/current-issues.md |
No — manual + issue-trigger only |
Rules:
- This immediate-write exception applies only while a file is an empty scaffold. Once it holds real content, later edits revert to Draft-Until-Save.
- Never invent facts. Anything not provable from repo evidence is an Open Question, not a populated claim.
- Still draft this session's ongoing changes in
SESSION.md; First-Run Population is about seeding empty context, not about live edits. - After populating, run the Context Self-Test to verify the brain is sufficient; fill or flag any gaps it finds.
Provider Bridge
AGENTS.md + .safe-code/ are the source of truth, but not every host auto-reads AGENTS.md. So safe-code writes thin pointer files in each major host's native config location, so a fresh chat in any provider loads the same brain without the user invoking safe-code:
| Host | Bridge file | Mechanism |
|---|---|---|
| Claude Code | CLAUDE.md |
@AGENTS.md import + read-context instruction |
| Gemini CLI | GEMINI.md |
read-AGENTS.md-and-context instruction |
| GitHub Copilot | .github/copilot-instructions.md |
read-AGENTS.md-and-context instruction |
| Cursor | .cursor/rules/safe-code.mdc |
alwaysApply rule pointing at AGENTS.md |
Rules:
- Bridges are pointers, not state — each is a few lines that redirect to
AGENTS.md+.safe-code/context/. Never duplicate project facts into them. - Never overwrite an existing host file. If it exists and does not already point at
AGENTS.md/.safe-code/, append one clearly-marked<!-- safe-code:bridge -->block; if it already points there, leave it. - Bridges are scaffold/pointer files — write them immediately (like
AGENTS.md), not draft-until-save. - Preserve bridges during Legacy Layout Migration; they are not legacy session state.
- Read fallback shapes from
references/doc-templates.md(Provider Bridge Files).
Legacy Layout Migration
Older safe-code versions left other folders and config in the repo. Detect them on every safe-code command — /safe-code, /safe-code --continue, and /safe-code --save — and migrate immediately (this is a scaffold operation — it does not wait for --save):
Pre-v3 layout: .codex/agents/ .claude/agents/ .cursor/agents/ .windsurf/agents/
.codex/memory/ .claude/memory/ .cursor/memory/ .windsurf/memory/
v3 layout: .agents/ (six session files) + root context/ + root CHANGELOG.md
created by safe-code (gitignore entry /context/current-issues.md is the marker)
Migration steps (per legacy location found):
- Move every safe-code
*.mdinto its new home —git mvwhen tracked, plain move otherwise:- session docs (
ACTIVE.md,SESSION.md,LOG.md,BACKLOG.md,MEMORY.md,safe-refactor-code.md) ->.safe-code/ - root
context/->.safe-code/context/ - root
CHANGELOG.md->.safe-code/CHANGELOG.md(skip if the repo never had safe-code manage it and the user objects)
- session docs (
- Never overwrite: if the destination file already exists, keep the legacy file in place, report the conflict, and let the user merge.
- Patch old config to the new version wherever the repo uses it:
.gitignore: replace/context/current-issues.mdwith/.safe-code/context/current-issues.mdAGENTS.md: rewrite Read First paths and anycontext/,.agents/,.codex/agents/references to.safe-code/paths- any other repo doc safe-code wrote that points at old paths
- Remove each legacy folder once it is empty — including a now-empty
.codex/,.claude/,.cursor/, or.windsurf/parent. Never remove a folder that still holds unmigrated or non-safe-code files; report what was left behind instead. - Log the whole migration as one typed
decisionentry inLOG.md.
Content mapping when old continuity docs are thin or pre-date context/:
MEMORY.md-> draft candidate facts for.safe-code/context/architecture.mdBACKLOG.md-> draft Next Up / Open Questions for.safe-code/context/progress-tracker.mdACTIVE.md-> draft Current Goal / In Progress for.safe-code/context/progress-tracker.mdLOG.md-> safe decision summaries only- existing
AGENTS.md-> preserve verified rules and add Read First section
Migration rules:
- File moves and config patches happen now; content rewrites (mapping above) are drafted in
SESSION.mdand applied on/safe-code --save. - Do not copy raw logs, secrets, stack traces, private URLs, or
current-issues.mdcontent into context files. - Mark uncertain migrated facts as Open Questions.
- After migration,
.safe-code/context/is canonical project context; the six session files in.safe-code/remain session state.
Doc + Session Templates (loaded on demand)
Do not inline template bodies here. When creating or reconciling scaffold files in Step 1, read the fallback shapes from the skill's references/ folder and apply them only to missing files:
references/agents-md-authoring.md—AGENTS.mdtemplate and the canonical AGENTS.md authoring rules. This is the single source of truth for how to writeAGENTS.md; helper skills defer to it when run under safe-code.references/doc-templates.md— fallback shapes for.safe-code/CHANGELOG.md, every.safe-code/context/*.mdfile, and every.safe-code/*.mdsession file (ACTIVE, SESSION, BACKLOG, LOG, MEMORY, safe-refactor-code), including the Flagged Dead Code entry format.references/examples.md— worked end-to-end examples of correct runs (Orientation / Audit / Cleanup profiles and--save), plus anti-patterns. Read it when unsure what the shape of a good run looks like.references/agent-config-audit.md— scope, scan patterns, and High/Medium/Info classification for the Step 4b Agent Config Trust Audit. Read it only when that step runs.
Rules when applying templates:
- Never overwrite a file that already exists; create missing files with the template shape only.
- When creating, populating, or reconciling
AGENTS.md, follow the authoring rules inreferences/agents-md-authoring.mdinstead of filling the template blindly. - Draft real content in
SESSION.mdand finalize on/safe-code --save, except scaffold files and active feature specs.
1c. Confirm Initialization
Project root: <path>
Safe-code folder: <project-root>/.safe-code/
Root: AGENTS.md - <created|exists|populated>
Bridges: CLAUDE.md / GEMINI.md / copilot-instructions.md / cursor rule - <created|exists|appended|skipped>
Folder: .safe-code/ - <created|exists|migrated> | CHANGELOG.md - <created|exists>
Context: context/ - <created|exists|migrated> | feature-specs/ - <created|exists>
current-issues.md - <created|exists|gitignored>
Session: ACTIVE.md - <created|exists> | SESSION.md - <created|exists>
BACKLOG.md - <created|exists> | LOG.md - <created|exists>
MEMORY.md - <created|exists> | safe-refactor-code.md - <created|exists>
Legacy: <none found | migrated + removed: <list> | conflicts left for user: <list>>
All paths inside project root. Proceeding.
Step 2: Load Context + Detect Session Mode
2a. Load Layer 1 (always, every session)
Load the Layer 1 — Entry file set defined in Loading Layers above, reading only the indicated slice of each file. Do not keep a second copy of the list here (single source of truth).
Do not read .safe-code/context/current-issues.md during normal work. Read and append to it on issue triggers ("fix this", "failed", "got error", pasted stack trace) or when the user references that file (Issue Tracking Rule).
2b. Detect saved session from ACTIVE.md
This step is mandatory for both /safe-code and /safe-code --continue.
if Last Session.status = "saved" and pending/next_action exists:
-> Auto-continue, even for plain /safe-code
-> Load Layer 2: .safe-code/context/progress-tracker.md full + ACTIVE.md full + SESSION.md full + LOG.md full
-> Print: "Saved safe-code session found; resuming automatically. Say 'fresh pass' to ignore saved state."
-> Print: "Pending: <pending> | Next: <next_action>"
-> Skip completed slices
-> Resume from next_action directly
if Last Session.status = "completed":
-> Load Layer 1 only
-> Start new pass unless user asks to inspect previous work
if Last Session.status = "none" or block missing:
-> Load Layer 1 only
-> Start setup/orientation
If the user explicitly says fresh pass, fresh setup, or ignore saved state, do not auto-continue. Record this in SESSION.md.
2c. Create or Update Task List
Before Step 3, write SESSION.md ## Task List.
if /safe-code with no saved state:
-> create fresh default checklist
-> mark completed setup items [x] as they finish
if /safe-code auto-continues or /safe-code --continue:
-> load unfinished items from ACTIVE.md Last Session.pending
-> merge them with default checklist
-> keep completed items visible only if needed to avoid repeated work
if /safe-code --save:
-> read current checklist
-> migrate unchecked or active items into ACTIVE.md Last Session.pending
-> set next_action to first unfinished task
Use the canonical Default checklist from the Measure Twice, Cut Once Policy section above as the base — do not maintain a second, divergent copy here (single source of truth). Then adapt it per the mode block above (fresh / resume / save).
Update checklist after every major step. Never wait until final summary to mark progress.
Last Session block (written by /safe-code --save)
## Last Session
status: saved
saved_at: <ISO timestamp>
completed:
- <slice>
pending:
- <slice>
next_action: <what to do on resume>
After all pending done, reset to:
## Last Session
status: completed
saved_at: <ISO timestamp>
completed: all
pending: []
next_action: none
LOG.md Trim Rule
Check LOG.md line count on every /safe-code --save.
if LOG.md > 200 lines:
-> Collect all entries older than 7 days
-> Summarize them into one block at the bottom:
## Archived Summary [<oldest date> - <7 days ago>]
- <bullet summary of what happened in that period>
-> Keep last 7 days of entries as-is above the archive block
-> Never delete any information — only compress old entries
-> Append new entries above everything as usual
This keeps LOG.md scannable without losing history.
Context Checkpoint Rule
Long runs lose context to compaction. Unsaved state must never be the casualty.
A checkpoint = update SESSION.md now (task list states, draft updates, current slice) so auto-resume from ACTIVE.md/SESSION.md works even if the session dies right after.
Checkpoint triggers:
- A run phase completes: orientation done, audit done, config audit done,
each execute slice verified
- Scope grows unexpectedly mid-run
- The host warns about context pressure/compaction, or own output starts
referring to stale facts
If context pressure is high mid-run: checkpoint first, then suggest the user run /safe-code --save and resume with /safe-code --continue in a fresh session. Do not push through with degraded context.
Context Freshness Check
A fresh chat must read current context, not a stale brain. safe-code stamps the commit it last synced context to, and checks drift on every run.
Stamp: .safe-code/context/progress-tracker.md carries last_synced_commit: <hash> and context_synced_at: <date>, written on /safe-code --save.
On /safe-code and /safe-code --continue, after loading context:
last_synced_commitmissing -> context was never synced; treat empty files as First-Run Population and flag populated-but-unstamped files for a refresh check.last_synced_commit== currentHEAD-> brain is fresh; no refresh needed.- They differ -> run a quick drift scan on signal files in
last_synced_commit..HEAD:- dependency manifests/locks (
package.json,*-lock*,requirements*.txt,pyproject.toml,go.mod,Cargo.toml,Gemfile, …) - top-level folder add / remove / rename
- build/test/run scripts and config (
tsconfig, linter/formatter, CI, framework config) AGENTS.md/.safe-code/context/*themselves
- dependency manifests/locks (
- Signal files changed -> mark the affected context sections possibly stale, refresh them from current repo evidence (draft in
SESSION.md, apply on--save), and note it in the summary. Only unrelated files changed -> context stays vali
…(truncated)