| name | file-guardian |
| description | ALWAYS ACTIVE for any codebase. Use when starting code work, resuming a task, continuing after a session break, or modifying any file. CRITICAL: .ai/ is agent memory — READ mirror docs before coding (especially on resume); write docs so the NEXT agent can continue. Missing .ai/ or file doc → create first. Bug fixes: document plan in .ai/ before code.
|
File Guardian — Agent Memory + Documentation-First
Why .ai/ Exists (Not Just Logging)
.ai/ is not a write-only changelog. It is shared memory across agents and sessions.
| Mode | Who | What |
|---|
| READ | Current agent | Reconstruct past intent, constraints, failed approaches, open threads |
| WRITE | Current agent | Leave a handoff the next agent (or you tomorrow) can act on |
If you only write and never read, the folder is pure waste. Every session that touches a file must consume its mirror first, then leave a better handoff.
The Absolute Rule
📋 NO DOC → NO WORK
📖 NO READ → NO CODE (when a mirror already exists)
Before touching ANY code:
- Check
.ai/ exists (create if not)
- Check file-specific doc exists (create if not)
- READ the doc and apply its context (decisions, NEVER-change, bugs, open threads)
- Update doc with planned changes / open threads
- Get user confirmation (unless user already authorized execution this turn)
- NOW touch code
- Sync doc to final state (write for the next reader)
Directory Structure: .ai/ Mirror
Code: AI Docs:
src/ .ai/src/
├── components/ ├── components/
│ ├── Button.tsx → │ ├── Button.md
│ └── Card.tsx → │ └── Card.md
├── utils/ ├── utils/
│ ├── format.ts → │ ├── format.md
│ └── validate.ts → │ └── validate.md
└── features/ └── features/
└── pricing/ └── pricing/
├── Calculator.tsx → ├── Calculator.md
└── utils.ts → └── utils.md
.ai/PROJECT_CONTEXT.md (global orientation + current work)
Rule: Replace extension with .md, preserve full path.
HARD-GATE — Non-Negotiable
For ANY code operation (create, modify, delete, fix bug, refactor, resume):
STEP 0: Session / task orientation (resume & multi-file work)
On new session, "continue", "resume", or work spanning multiple prior changes:
1. Read .ai/PROJECT_CONTEXT.md first (Architecture, Current Work, NEVER Change)
2. Identify which files the task will touch
3. Read EACH of those .ai/{path}/{file}.md BEFORE reading or editing code
Skip STEP 0 only for a brand-new single-file create when no prior docs exist.
STEP 1: Ensure .ai/ infrastructure
if .ai/ directory does NOT exist:
→ Create .ai/
→ Create .ai/PROJECT_CONTEXT.md (from template)
→ Log: "Created .ai/ infrastructure"
STEP 2: Ensure file-specific doc exists
Code file: src/components/Button.tsx
Doc file: .ai/src/components/Button.md
if doc file does NOT exist:
→ Create it FIRST (before ANY code work)
→ Fill with template
→ Document current state (if existing file) or planned design (if new)
STEP 3: READ and extract actionable context (MANDATORY)
Do not "glance and ignore." Extract and use:
| Section | Extract | Use for |
|---|
| Purpose / What It Does | Role of the file | Avoid wrong-layer changes |
| NEVER Change / Important Notes | Hard constraints | Do not violate |
| Agent Decisions / Thoughts | Why it was built this way; rejected alternatives | Don't re-litigate settled choices; avoid known dead ends |
| Bug Fixes | Past failures | Don't reintroduce fixed bugs |
| Change History | Recent trajectory | Know what just landed |
| Open Threads / Resume Context | Unfinished plan, next steps, blockers | Primary input when resuming |
After reading, you should be able to answer:
- What must not change?
- What did previous agents already try or decide?
- Is there an unfinished plan I should continue rather than redesign?
Reading code without the mirror is incomplete context. Prefer: mirror → then code.
STEP 4: Update doc with plan (write for the next agent)
- Document WHAT you're about to do and WHY (one clear intent, not a diary).
- Put durable reasoning under Agent Decisions / Thoughts (trade-offs, "why not X").
- Put unfinished work under Open Threads / Resume Context (so resume works even if chat is gone).
- For bug fixes: cause, fix strategy, regression risks.
- One short row in Change History after you're done (not a novel).
STEP 5: Present to user and get confirmation
"I'm about to [action] [file]. Context from .ai/: [1–3 bullets of constraints/prior decisions].
Plan: [summary]. Confirm to proceed?"
If the user already ordered full execution this turn, still update the doc before code; confirmation may be treated as satisfied.
STEP 6: Execute code work
STEP 7: Sync docs (handoff quality)
- Match final code
- Clear or rewrite Open Threads (done → remove; partial → leave next steps)
- Update PROJECT_CONTEXT.md → Current Work when the change is project-visible
- Prefer durable "why" over "I edited line 40"
NO EXCEPTIONS. EVER.
Write for Readers (Anti-Waste)
Bad .ai/ docs are append-only noise. Good ones are dense handoffs.
Do write
- Constraints the next agent will violate if they only read code
- Non-obvious decisions and rejected approaches ("Tried X; failed because Y")
- Open threads: exact next steps if interrupted mid-task
- Bug root causes that are not obvious from the fix alone
Do not write
- Duplicate plan+implement pairs that restate the same change twice
- Play-by-play of every tool call or "I read the file"
- Restating the Public API table in Agent Decisions
- Long Change History when a one-line summary + one Decision bullet is enough
Agent Decisions vs Change History vs Open Threads
| Section | Purpose | Keep |
|---|
| Agent Decisions | Durable why / trade-offs | Forever (prune only if obsolete) |
| Change History | Chronology of what shipped | One line per meaningful change |
| Open Threads | What to do next if work continues | Always current; clear when done |
Rule of thumb: If a future agent wouldn't change their code after reading a bullet, delete the bullet.
Initialization Modes
Mode 1: Progressive (Default) — For Large Codebases
Use when: Large codebase, or don't want to process all files at once
User: 帮我改 Button.tsx
↓
AI: 检查 .ai/ 存在?
↓ NO → 创建 .ai/ + PROJECT_CONTEXT.md
↓
AI: 检查 .ai/src/components/Button.md 存在?
↓ NO → 只创建 Button.md(不碰其他文件)
↓ YES → 完整阅读 Button.md,提取约束与 Open Threads
↓
AI: 继续正常流程
Result: 用哪个文件,就给哪个文件创建/读取文档。
Mode 2: Full Initialization — User Triggered
Trigger phrases:
- "给我初始化所有 AI 文档"
- "给整个项目创建 .ai/ 文档"
- "全量初始化 File Guardian"
- "给所有文件创建文档镜像"
- "初始化所有文档"
- "批量创建 AI 文档"
Process in batches (e.g. 20 files). On timeout, resume from last completed batch.
Critical Scenarios
Scenario 0: Resume / Continue / New Session — THE MEMORY USE CASE
User: continue the receipt resume work
OR: new session, "pick up where we left off on dashboard performance"
OR: agent resumes a multi-step task after a break
AI MUST:
1. Read .ai/PROJECT_CONTEXT.md → Current Work, Architecture, NEVER Change
2. List candidate files from Current Work + user message
3. Read each .ai/.../{file}.md fully
4. Prefer Open Threads / last Agent Decisions over inventing a new design
5. State aloud: "From .ai/: [prior decision] / [open thread] / [constraint]. Continuing with..."
6. Only then read code and implement
Anti-pattern (FORBIDDEN):
- Jumping into code because "the chat already explained it"
- Redesigning from scratch when Open Threads already has a plan
- Treating Change History as optional flavor text
If Open Threads is empty but Change History is rich: synthesize the last intent from recent history + Decisions, then continue.
Scenario 1: New Feature (No Doc Exists)
User: 帮我做个价格计算器
AI:
- Create .ai/.../PriceCalculator.md (design first)
- Present Purpose + API + constraints
- Confirm → implement → sync
Scenario 2: Bug Fix
User: Button 点击没反应,修一下
AI:
1. Read .ai/src/components/Button.md (past bugs + NEVER Change)
2. Read code with those constraints in mind
3. Write bug cause + fix plan into the doc
4. Confirm → fix → sync Bug Fixes table + clear Open Threads
Scenario 3: Batch Operations (>3 files)
Batch design summary first; for each existing file, read its mirror before batch implement. One Open Thread can live in PROJECT_CONTEXT.Current Work for the multi-file effort.
Scenario 4: Delete/Rename
Always move/delete the .ai/ twin with the code file. Update references in other docs if known.
Flow Diagram
digraph file_guardian {
rankdir=TB;
node [shape=box, fontname=sans-serif];
start [label="AI starts or resumes work" shape=oval];
orient [label="Read PROJECT_CONTEXT\n(if resume / multi-file)"];
detect [label="Check .ai/ exists?"];
no_ai [label="Create .ai/ +\nPROJECT_CONTEXT.md"];
has_doc [label="Check .ai/{file}.md\nexists?"];
create_doc [label="Create doc FIRST"];
read_doc [label="READ doc → extract\nconstraints, decisions,\nopen threads"];
apply [label="Apply context\n(do not redesign settled choices)"];
update_doc [label="Update plan +\nOpen Threads"];
present [label="Present to user\nGet confirmation"];
execute [label="Execute code work"];
sync [label="Sync docs + handoff\n(clear/update Open Threads)"];
start -> orient;
orient -> detect;
detect -> no_ai [label="No"];
detect -> has_doc [label="Yes"];
no_ai -> has_doc;
has_doc -> create_doc [label="No"];
has_doc -> read_doc [label="Yes"];
create_doc -> update_doc;
read_doc -> apply;
apply -> update_doc;
update_doc -> present;
present -> execute [label="Confirmed"];
present -> update_doc [label="Changes\nrequested"];
execute -> sync;
}
Documentation Format
.ai/{path}/{file}.md Template
# {FileName}
> Last updated: {DATE} | Protection: {STANDARD|PROTECTED|CRITICAL}
## Purpose(一句话人话)
{用人类语言描述}
## What It Does
{详细功能描述}
## Public API
| Name | Type | Description |
|------|------|-------------|
| {export} | {type} | {description} |
## Props / Parameters
| Name | Type | Required | Description |
|------|------|----------|-------------|
| {prop} | {type} | {Yes/No} | {description} |
## Dependencies
- **Internal:** `{./path/to/file}` — {why}
- **External:** `{package}` — {why}
## Open Threads / Resume Context
{Empty when idle. When work is in progress or interrupted, write enough that a NEW agent can continue with no chat history:}
- **Status:** in_progress | blocked | ready_for_next
- **Intent:** {what we are trying to finish}
- **Next steps:** 1) ... 2) ...
- **Blockers / notes:** {optional}
## Agent Decisions / Thoughts
- **{DATE} {AUTHOR}:** {Durable why / trade-off / rejected alternative — not a play-by-play}
## Important Notes / NEVER Change
- {约束}
## Bug Fixes
| Date | Bug | Cause | Fix |
|------|-----|-------|-----|
| {DATE} | {description} | {root cause} | {solution} |
## Change History
| Date | Change | Author |
|------|--------|--------|
| {DATE} | {one-line what shipped} | {who} |
PROJECT_CONTEXT.md — always keep Current Work fresh
## Current Work
- {DATE}: {active initiative or last meaningful project-level change}
- Open: {optional multi-file resume pointer}
New/resumed agents read this first to know where the project is pointed.
Edge Cases (Blue Team Fixes)
See rules/edge-cases.md for:
- Missing
.ai/ → Auto-create
- Batch operations → Batch declaration
- Delete/Rename → Sync both files
- Bug fixes → Document first
- Circular deps → Depth limit 5
- User rejection → Iterate
- External edits → Warn on desync
- Large projects → Lazy / progressive docs
- File boundaries → Include/exclude list
- Resume / empty Open Threads → Reconstruct from Decisions + History
- Bloated docs → Prefer pruning noise over blind append
Red Flags — You Are Wasting .ai/
Stop and fix process if you catch yourself:
- Writing Change History but never opening the doc at task start
- "I'll just read the source; docs are probably stale" (then refresh the doc after reading code)
- "Chat has context so I can skip the mirror" (chat dies; mirror survives)
- Appending another plan/implement essay to Agent Decisions
- Leaving Open Threads empty after partial work
- Claiming "docs are up to date" without having read them this turn
All of these mean: READ the mirror, extract constraints, then code.
Common Rationalizations
| Excuse | Reality |
|---|
| "Docs are just bureaucracy" | Mirror is the only reliable cross-session memory for this file |
| "Resume already has the plan in chat" | Next session/agent won't. Open Threads is the plan that persists |
| "I'll update docs after the fix" | Then you skip constraints and reintroduce fixed bugs |
| "The file is small, skip the doc" | Small files still have NEVER-change and past decisions |
| "I'll write a long log so nothing is lost" | Long logs get ignored. Dense Open Threads + Decisions get used |
Why This Works
| Problem | Solution |
|---|
| AI hallucinates | Doc forces intent before code |
| Code drift | Doc-code sync enforced |
| Bug fixes undocumented | Cause + plan required |
| New agent / resume loses context | Mandatory READ of PROJECT_CONTEXT + file mirrors |
.ai/ becomes write-only waste | Read-to-act + write-for-next-reader rules |
| User sees wrong result | Design/plan before code |
| Maintainability | Human-readable constraints |
Templates & Rules