| 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