cairn-ai 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/.agents/workflows/cairn-memory.md +2 -2
  2. package/.agents/workflows/cairn-plan.md +2 -2
  3. package/.agents/workflows/cairn-review.md +1 -1
  4. package/.agents/workflows/cairn-work.md +2 -2
  5. package/.claude/agents/explorer.md +1 -1
  6. package/.claude/agents/worker.md +1 -1
  7. package/.codex-plugin/plugin.json +2 -2
  8. package/README.de.md +14 -3
  9. package/README.es.md +14 -3
  10. package/README.fr.md +14 -3
  11. package/README.ja.md +14 -3
  12. package/README.ko.md +17 -7
  13. package/README.md +17 -7
  14. package/README.pt.md +14 -3
  15. package/README.zh.md +14 -3
  16. package/agents/explorer.md +1 -1
  17. package/agents/worker.md +1 -1
  18. package/commands/cairn-memory.md +2 -2
  19. package/commands/cairn-plan.md +2 -2
  20. package/commands/cairn-review.md +1 -1
  21. package/commands/cairn-work.md +2 -2
  22. package/package.json +1 -1
  23. package/scripts/cairn-cleanup.mjs +142 -15
  24. package/scripts/cairn-goal-cli.mjs +50 -4
  25. package/scripts/cairn-goal-history.mjs +316 -0
  26. package/scripts/cairn-goal-operations-evidence.mjs +2 -2
  27. package/scripts/cairn-goal-operations.mjs +11 -3
  28. package/scripts/cairn-goal.mjs +3 -0
  29. package/scripts/cairn-index.mjs +1052 -0
  30. package/scripts/cairn-safe-fs.mjs +7 -2
  31. package/scripts/cairn-state-context.mjs +101 -10
  32. package/scripts/cairn-state-init.mjs +11 -68
  33. package/scripts/cairn-state.mjs +14 -3
  34. package/scripts/cairn.mjs +55 -18
  35. package/skills/cairn-memory/SKILL.md +4 -4
  36. package/skills/cairn-plan/SKILL.md +2 -2
  37. package/skills/cairn-plan/delegation.md +2 -1
  38. package/skills/cairn-plan/planning-rules.md +10 -0
  39. package/skills/cairn-review/SKILL.md +3 -1
  40. package/skills/cairn-work/SKILL.md +1 -1
  41. package/skills/cairn-work/delegation.md +2 -1
  42. package/skills/cairn-work/verification.md +15 -1
  43. package/templates/MEMORY.md +4 -6
  44. package/templates/PLAN.md +2 -15
  45. package/templates/domain-memory.md +2 -0
  46. package/templates/work-plan.md +3 -1
@@ -12,6 +12,6 @@ Procedure:
12
12
  2. Every agent reads project-root `MEMORY.md` when present and continues without repository memory when absent before assigned discovery or update work.
13
13
  3. Explore repository facts with focused tools.
14
14
  4. Use `explorer` for read-only domain discovery and contradiction checks when available; use `worker` for exact references, command checks, and bounded evidence capture. When subagent tools are available, each agent may recursively delegate bounded sub-tasks to subagents. Tell every delegated agent and child subagent to read the project-root `MEMORY.md` before work, keep scope, and preserve others' edits.
15
- 5. Write details to `docs/memory/<domain>.md`. When a lesson or correction recurs and is machine-checkable, encode it as a test, lint rule, script, or hook instead of more prose; memory keeps judgment rules and a pointer to the enforcing check.
16
- 6. Keep `MEMORY.md` as a short index.
15
+ 5. Write details to `docs/memory/<domain>.md` with a `Summary:` line under the H1 (one line, at most 120 characters: what the note answers and when to read it). When a lesson or correction recurs and is machine-checkable, encode it as a test, lint rule, script, or hook instead of more prose; memory keeps judgment rules and a pointer to the enforcing check.
16
+ 6. Keep `MEMORY.md` as a short index: one line per note under `## Domain Knowledge`; a note link in another section is a mention that `index` never rewrites. Run the installed Cairn CLI with `memory index --root <repoRoot>` to add unlisted notes and refresh changed summaries (`--dry-run` previews; it never deletes entries and writes nothing when the insertion point is inside an unclosed code fence), then `memory check --root <repoRoot>` and fix the unindexed notes, dead links, duplicates, stale summaries, or control characters it reports.
17
17
  7. Use the OS locale for user-visible responses and generated or updated documentation, plans, and memory artifacts unless the user asks for another language.
@@ -13,9 +13,9 @@ Complexity is staged: request checkpoint, planning checkpoint after exploration,
13
13
  Procedure:
14
14
 
15
15
  1. Every agent reads project-root `MEMORY.md` when present and continues without repository memory when absent before repository exploration, tool selection, work, or delegation.
16
- 2. For non-trivial implementation or continuation of planned work, write an initial `docs/plan/<topic>.md` and `PLAN.md` entry with `triage-plan` as the first active task. This initial plan is decision-complete for triage and explicitly not implementation-ready.
16
+ 2. For non-trivial implementation or continuation of planned work, write an initial `docs/plan/<topic>.md` and `PLAN.md` entry with `triage-plan` as the first active task. The `PLAN.md` entry is one line of 200 characters or fewer under `## Active Plans`; the installed Cairn CLI's `plan index --root <repoRoot>` adds missing entries and `plan check --root <repoRoot>` verifies them. This initial plan is decision-complete for triage and explicitly not implementation-ready.
17
17
  3. Before exploration, toolcheck, triage, or delegation, call Codex `update_plan` and then `create_goal` when available (main agent only; subagents skip), and start the repository Cairn goal with the same roadmap. Copy the session-start hook's `Cairn CLI:` prefix literally into each command; never store it in a shell variable. `--root` may be omitted when the cwd is inside the repository. Fold new work into an unfinished goal with `goal replan` instead of cancelling it; when a hook reports another session owns the goal you continue, run `goal claim --session <id>`.
18
- 4. Read relevant `docs/memory/*.md` and, under the locator's `resources.modelGuidance`, `claude.md` for Claude-family or `codex.md` for Codex-family models; invoke Node with the locator's absolute `entrypoints.cli`, `toolcheck`, and `--root` for the target repository (installation only with explicit approval), and explore before asking the user.
18
+ 4. Reuse before exploring: pick related `docs/memory` notes from the `MEMORY.md` entries and at most 3 completed plans from `PLAN.md` (older ones in `docs/plan/ARCHIVE.md`) that changed the same modules or solved the same kind of problem; read only those plans' goal, design decisions, and evidence, and record the picks in the plan's `## Memory Inputs` with `Related completed plans:` (or `none related`). Read the picked notes and, under the locator's `resources.modelGuidance`, `claude.md` for Claude-family or `codex.md` for Codex-family models; invoke Node with the locator's absolute `entrypoints.cli`, `toolcheck`, and `--root` for the target repository (installation only with explicit approval), and explore before asking the user.
19
19
  5. Classify the whole work into executable tasks with `dependsOn`, `writeScope`, and handoff files, finalize triage, and update the same plan and `update_plan` roadmap to a decision-complete implementation plan: selected path, checked Heavy Path signals, tool readiness, file scope, dry-run/check, module acceptance, surface integration, stable IDs, and fail-closed evidence. Heavy Path adds an explicit automated test command and `Tests:` evidence line.
20
20
  6. Resolve the skill's reference files through the locator's `pluginRoot` and read them only when needed: `cairn://skills/cairn-plan/planning-rules.md` when finalizing, `cairn://skills/cairn-plan/delegation.md` before dispatching, `cairn://skills/cairn-plan/heavy-path.md` only on a Heavy signal or route change.
21
21
  7. The user-called/main agent orchestrates; implementation edits go to `worker` when subagent tools are available, otherwise the main agent takes over and records it. Advance a UI step only after the matching repository task transition succeeds with its required bound evidence.
@@ -9,7 +9,7 @@ Goal: review completed work against plan, memory, policy, and evidence.
9
9
  Procedure:
10
10
 
11
11
  1. Every agent reads project-root `MEMORY.md` when present and continues without repository memory when absent before review work, then reads the plan task and available memory inputs.
12
- 2. Check changed files, tool readiness evidence, and verification evidence. Inspect test, fixture, and verification-command diffs and reject any weakening without a recorded plan reason. For defect fixes, confirm the same-rule sweep was performed and its result recorded.
12
+ 2. Check changed files, tool readiness evidence, and verification evidence. Inspect test, fixture, and verification-command diffs and reject any weakening without a recorded plan reason. For defect fixes, confirm the same-rule sweep was performed and its result recorded. Confirm the plan's Evidence has a filled `Memory promotion:` line (`docs/memory/<domain>.md` or `none: <reason>`) and that the installed Cairn CLI's `memory check --root <repoRoot>` and `plan check --root <repoRoot>` exit 0. A `none: <reason>` decision is acceptable: do not create a note or demand one; flag a missing or placeholder line, or a named note that does not exist.
13
13
  3. Delegate independent read-only review to `explorer` when it materially improves speed or quality; use `worker` only for scoped verification reruns or QA artifacts. When subagent tools are available, each agent may recursively delegate bounded sub-tasks to subagents. Tell every delegated agent and child subagent to read the project-root `MEMORY.md` before work, keep scope, and preserve others' edits.
14
14
  4. Report findings first, ordered by severity, with file and line references. If no issues are found, say so clearly and mention remaining test gaps or residual risk.
15
15
  5. Record review evidence in `docs/plan/<topic>.md`.
@@ -18,7 +18,7 @@ Procedure:
18
18
  6. Run module acceptance and surface integration through `goal verify -- ...`; `--kind "moduleAcceptance|surfaceIntegration"` records both from one run. Treat tool exit codes as authoritative and expand context only around failing tests. Heavy Path records explicit `Tests:` evidence.
19
19
  7. Never edit, weaken, skip, or delete existing tests, fixtures, or verification commands to make a gate pass unless the plan records the contract change. Reproduce reported defects before fixing, and after a fix search for other implementations of the same rule or pattern.
20
20
  8. Inspect package lifecycle scripts and run normal `npm pack --dry-run` by default. Content-producing or unknown lifecycle scripts must never use `--ignore-scripts`; only absent or proven content-neutral scripts may use it while the full check remains fresh.
21
- 9. Relevant mutation makes the current task's evidence stale; rerun it before completing the task. Do not rerun earlier tasks' checks; finish with one goal-level check through `goal finish -- ...`. Missing, failed, skipped, stale, or placeholder evidence never completes work. `goal stats` measures receipt reruns.
21
+ 9. Relevant mutation makes the current task's evidence stale; rerun it before completing the task. Do not rerun earlier tasks' checks; finish with one goal-level check through `goal finish -- ...`. Missing, failed, skipped, stale, or placeholder evidence never completes work. `goal stats` measures receipt reruns; `goal stats --history` compares finished goals of the repository.
22
22
  10. Resolve the skill's reference files through the locator's `pluginRoot` and read them only when needed: `cairn://skills/cairn-work/verification.md`, `cairn://skills/cairn-work/delegation.md`, `cairn://skills/cairn-work/recovery.md`, and `cairn://skills/cairn-work/heavy-path.md` (Heavy route only).
23
- 11. Update the plan, goal state, and `PLAN.md` only after evidence exists. If the user asks a side question, status question, or narrow clarification while this task is still active, answer it briefly and then resume the previous active work unless the user explicitly asks to pause, stop, or switch tasks.
23
+ 11. Before `goal finish`, record the memory promotion decision in the plan's Evidence: `Memory promotion: docs/memory/<domain>.md` when the goal produced reusable repository knowledge (write the note with a `Summary:` line, then run `memory index --root <repoRoot>`), otherwise `Memory promotion: none: <reason>`. The line is required and the note is optional: do not create a note when nothing qualifies. Update the plan, goal state, and `PLAN.md` only after evidence exists. If the user asks a side question, status question, or narrow clarification while this task is still active, answer it briefly and then resume the previous active work unless the user explicitly asks to pause, stop, or switch tasks.
24
24
  12. Use the OS locale for user-visible responses and generated or updated documentation, plans, and memory artifacts unless the user asks for another language.
@@ -2,6 +2,6 @@
2
2
 
3
3
  Read-only discovery agent for codebase questions, impact analysis, pattern search, and verification.
4
4
 
5
- Before any task, read project-root `MEMORY.md` when present; continue without repository memory when absent.
5
+ Before any task, read project-root `MEMORY.md` when present and open only the `docs/memory/*.md` notes whose entries match the task or that the assignment names; continue without repository memory when absent.
6
6
 
7
7
  Read the installed Cairn runtime locator at `{{CAIRN_RUNTIME_LOCATOR_JSON}}`. Resolve `resources.agents` from that JSON object and follow `explorer.md` in that directory. Do not resolve Cairn agent files from the target project. If the shared runtime or locator is missing, unreadable, or inconsistent, stop all dependent mirrors and recover with published/global `cairn doctor` followed by `cairn upgrade`; do not repair through another mirror.
@@ -2,6 +2,6 @@
2
2
 
3
3
  Focused execution agent for search, small edits, command checks, and QA artifacts.
4
4
 
5
- Before any task, read project-root `MEMORY.md` when present; continue without repository memory when absent.
5
+ Before any task, read project-root `MEMORY.md` when present and open only the `docs/memory/*.md` notes whose entries match the task or that the assignment names; continue without repository memory when absent.
6
6
 
7
7
  Read the installed Cairn runtime locator at `{{CAIRN_RUNTIME_LOCATOR_JSON}}`. Resolve `resources.agents` from that JSON object and follow `worker.md` in that directory. Do not resolve Cairn agent files from the target project. If the shared runtime or locator is missing, unreadable, or inconsistent, stop all dependent mirrors and recover with published/global `cairn doctor` followed by `cairn upgrade`; do not repair through another mirror.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cairn",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Token-efficient agent harness with tool readiness for Codex, Claude Code, and Antigravity.",
5
5
  "author": {
6
6
  "name": "WkNam"
@@ -21,7 +21,7 @@
21
21
  "Tool Readiness"
22
22
  ],
23
23
  "defaultPrompt": [
24
- "Use Cairn's repository-local PLAN.md and persisted goal state as the recovery spine; read root MEMORY.md first when it exists, and continue without repository memory when it does not.",
24
+ "Use Cairn's repository-local PLAN.md and persisted goal state as the recovery spine; read root MEMORY.md first when it exists (it indexes docs/memory notes; PLAN.md indexes docs/plan plans — open only the entries the task needs), and continue without repository memory when it does not.",
25
25
  "For non-trivial work, load the phase skill (cairn-plan, cairn-work, or cairn-review), then restore the active plan and current-task references before acting.",
26
26
  "After compaction, restart, handoff, or delegation, restore optional MEMORY.md → phase skill → active plan → current task references; do not rely on conversation recall.",
27
27
  "A missing MEMORY.md never blocks work; fail closed only when active state, its skill, plan, or a required task reference is missing, unreadable, or inconsistent.",
package/README.de.md CHANGED
@@ -63,11 +63,19 @@ Details stehen im installierten Plugin unter `cairn://docs/model-guidance/README
63
63
 
64
64
  Das harness erstellt und pflegt diese files im Ziel-repository root.
65
65
 
66
- - `MEMORY.md`: kurzer Index persistent domain knowledge.
67
- - `docs/memory/*.md`: detailliertes Wissen je domain.
66
+ - `MEMORY.md`: kurzer Index persistent domain knowledge: eine Zeile pro Notiz unter `## Domain Knowledge` (`- [<name>](docs/memory/<name>.md): <summary>`) plus die `## Policy` des Repositorys.
67
+ - `docs/memory/*.md`: detailliertes Wissen je domain. Jede Notiz beginnt mit einer einzeiligen `Summary:` (höchstens 120 Zeichen), die Index und Hook anzeigen.
68
68
  - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/state.json`: user-home Active-Goal/Task/Evidence-State, getrennt nach Projekt und Worktree, für Wiederaufnahme und scoped stop gates. Der Working Tree besitzt keinen Runtime-State.
69
- - `PLAN.md`: kurzer Index aktiver und abgeschlossener work topics.
69
+ - `PLAN.md`: kurzer Index der Arbeitspläne: eine Zeile mit höchstens 200 Zeichen pro Plan unter `## Active Plans` und `## Completed Plans`. Planungsregeln stehen im Skill `cairn-plan`, nicht in `PLAN.md`.
70
70
  - `docs/plan/*.md`: detailed execution plans.
71
+ - `docs/plan/ARCHIVE.md`: ältere abgeschlossene Einträge, die `cairn plan index --archive` aus `PLAN.md` verschoben hat, neueste zuerst, dazu der Inhalt eines legacy Abschnitts `## Planning Rules` unter `## Legacy Planning Rules`. Listenzeilen vor der ersten `## `-Überschrift gelten weiterhin als indexiert.
72
+ - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/history.jsonl`: ein Zusammenfassungsdatensatz pro abgeschlossenem oder abgebrochenem goal (die neuesten 200 je Worktree) für `goal stats --history`.
73
+
74
+ Halten Sie `## Completed Plans` neueste zuerst. `cairn plan index --archive` behält die ersten 20 Einträge und verschiebt den Rest, ohne etwas zu löschen, nach `docs/plan/ARCHIVE.md`; eine älteste-zuerst geführte Liste würde daher die neuesten Pläne archivieren. Prüfen Sie vorher mit `--dry-run`. Bestehende `MEMORY.md`/`PLAN.md` funktionieren ohne Migration: `init` schreibt sie nie um, und `check` meldet das alte Format nur als warning.
75
+
76
+ Bei `SessionStart` teilt der Hook dem Agenten mit, welche Memory-Notizen existieren (Name und `Summary:`, bei langen Listen eine Zeile nur mit Namen), und ergänzt ohne aktives goal eine Zeile zum Plan-Index: Anzahl der Pläne, aktive Pläne, die zuletzt abgeschlossenen Pläne und `docs/plan/ARCHIVE.md`, falls vorhanden. Bei einem active, paused, blocked oder einer anderen Session gehörenden goal kommt nur die Memory-Liste hinzu, und die Kapsel einer fremden Session zeigt nie Plan-Namen. Ein `UserPromptSubmit` ohne goal ergänzt einen Satz mit der Anzahl der Notizen. Der Hook liest nur Indexdateien und Verzeichnislisten, nie Notizinhalte, und schreibt nichts; ein Repository ohne Notizen und Pläne erhält dieselbe Ausgabe wie bisher.
77
+
78
+ Vor `goal finish` hält `cairn-work` pro goal einmal eine memory promotion Entscheidung in der Evidence des Plans fest: `Memory promotion: docs/memory/<domain>.md`, wenn das goal wiederverwendbares Repository-Wissen ergeben hat, sonst `Memory promotion: none: <reason>`. Die Entscheidung ist Pflicht, eine Notiz zu schreiben ist optional. Wenn ein goal abgeschlossen wird und seine Plan-Datei keine ausgefüllte Zeile `Memory promotion:` hat, geben `goal finish` und `goal complete` eine einzeilige Erinnerung auf stderr aus, ohne exit code oder stdout zu ändern.
71
79
 
72
80
  Root files bleiben kurz, Details wandern unter `docs/`, damit agents nur den benötigten context lesen.
73
81
 
@@ -102,6 +110,9 @@ cairn toolcheck
102
110
  - `cairn uninstall`: entfernt nur unveränderte verwaltete Einträge; modified oder unmanaged Ziele bleiben als conflict erhalten.
103
111
  - `cairn toolcheck`: erkennt repository stacks und prüft required tools; Installation läuft nur für einen genehmigten unterstützten installer, sonst gilt `installer-unavailable`.
104
112
  - `cairn cleanup --root <repo>`: meldet standardmäßig read-only legacy projektlokale `.cairn`-Reste. `--yes` migriert/gleicht gültigen active state mit dem user-home store ab, entfernt nur bekannte state/lock/tool-Reste, bewahrt unbekannte Dateien und entfernt das Verzeichnis nur, wenn es leer ist.
113
+ - `cairn memory check|index [--root <repo>]`: `check` gleicht `MEMORY.md` mit `docs/memory/*.md` ab und gibt einen JSON-Bericht aus; bei nicht indexierten Notizen, dead links, Duplikaten, veralteten Zusammenfassungen, Steuerzeichen in Zusammenfassungen oder unsicheren Pfaden endet es mit exit 1, warnings schlagen nur mit `--strict` fehl. Einträge sind Listenzeilen unter `## Domain Knowledge` (in einer älteren Datei ohne diesen Abschnitt alle Listenzeilen); ein Notizlink in einem anderen Abschnitt ist eine Erwähnung, die `index` nie umschreibt. `index` ergänzt fehlende Notizen und ersetzt bei geändertem `Summary:` nur die Zusammenfassung nach dem Link (eine Zeile mit mehreren Links bleibt unverändert); es entfernt nur exakt passende Cairn-Platzhalterzeilen in diesem Abschnitt, löscht nie Einträge oder dead links und erhält den Rest Byte für Byte. `--dry-run` zeigt eine Vorschau. Liegt die Einfügestelle in einem nicht geschlossenen Codeblock, schreibt `index` nichts und endet mit exit 1 und `unclosed-fence`. Usage-Fehler enden mit exit 2; `cairn memory` ohne Unterbefehl gibt weiterhin den Hinweis aus.
114
+ - `cairn plan check|index [--archive] [--root <repo>]`: dasselbe für `PLAN.md` und `docs/plan/*.md`, deren Einträge Listenzeilen unter `## `-Überschriften sind, die auf `Plans` enden (etwa `## Superseded Plans`). `index` setzt einen Plan, dessen Checkboxen alle abgehakt sind, an den Anfang von `## Completed Plans` und jeden anderen unter `## Active Plans`; nur `--archive` verschiebt Zeilen nach `docs/plan/ARCHIVE.md`: abgeschlossene Einträge jenseits der neuesten 20 samt eingerückten Absätzen und den Inhalt eines legacy Abschnitts `## Planning Rules`. `check` warnt, wenn `## Completed Plans` mehr als 20 Einträge hat oder ein legacy Abschnitt `## Planning Rules` übrig ist.
115
+ - `cairn goal ...`: verwaltet das Repository-goal (`cairn goal --help`). `goal stats --history [--limit N]` fasst die beendeten goals des Repositorys über alle Worktrees zusammen: Anzahl completed/cancelled, Median und p90 der Dauer, Mediane von tasks und receipts, Rerun-Rate, memory promotion Entscheidungen, einen older/newer `trend` ab 4 abgeschlossenen goals und die letzten goals; ohne Historie gibt es `{"schemaVersion":1,"scope":"repository","goals":0}` aus. `completionCriteria` (`goal start --criteria`) ist `advisory`: Cairn zeichnet es auf, erzwingt es aber nicht, und der Abschluss hängt nur von der erforderlichen Evidence ab.
105
116
  - `cairn-memory`: erkundet domain knowledge und aktualisiert `MEMORY.md`.
106
117
  - `cairn-plan`: erstellt einen decision-complete plan unter `docs/plan/`.
107
118
  - `cairn-work`: führt den nächsten module task im aktuellen `PLAN.md` mit zwei verification gates aus.
package/README.es.md CHANGED
@@ -63,11 +63,19 @@ La guía detallada vive en el plugin instalado y se referencia como `cairn://doc
63
63
 
64
64
  El harness crea y mantiene estos archivos en la raíz del repositorio objetivo.
65
65
 
66
- - `MEMORY.md`: índice corto de conocimiento persistente del dominio.
67
- - `docs/memory/*.md`: conocimiento detallado por dominio.
66
+ - `MEMORY.md`: índice corto de conocimiento persistente del dominio: una línea por nota bajo `## Domain Knowledge` (`- [<name>](docs/memory/<name>.md): <summary>`) más la `## Policy` del repositorio.
67
+ - `docs/memory/*.md`: conocimiento detallado por dominio. Cada nota empieza con una línea `Summary:` (120 caracteres como máximo) que muestran el índice y el hook.
68
68
  - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/state.json`: estado active goal/task/evidence en user-home, aislado por proyecto y worktree, para recuperación y scoped stop gates. El working tree no posee runtime state.
69
- - `PLAN.md`: índice corto de temas activos y completados.
69
+ - `PLAN.md`: índice corto de planes de trabajo: una línea de 200 caracteres o menos por plan bajo `## Active Plans` y `## Completed Plans`. Las reglas de planificación viven en el skill `cairn-plan`, no en `PLAN.md`.
70
70
  - `docs/plan/*.md`: planes de ejecución detallados.
71
+ - `docs/plan/ARCHIVE.md`: entradas completadas antiguas que `cairn plan index --archive` movió desde `PLAN.md`, de la más nueva a la más antigua, más el cuerpo de una sección legacy `## Planning Rules` bajo `## Legacy Planning Rules`. Las líneas de lista antes de su primer encabezado `## ` siguen contando como indexadas.
72
+ - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/history.jsonl`: un registro resumen por goal completado o cancelado (los 200 más recientes por worktree) para `goal stats --history`.
73
+
74
+ Mantén `## Completed Plans` de la más nueva a la más antigua. `cairn plan index --archive` conserva las primeras 20 entradas y mueve el resto a `docs/plan/ARCHIVE.md` sin borrar nada, así que una lista ordenada de la más antigua a la más nueva archivaría los planes más recientes; revisa antes con `--dry-run`. Los `MEMORY.md`/`PLAN.md` existentes funcionan sin migración: `init` nunca los reescribe y `check` solo avisa del formato antiguo con warnings.
75
+
76
+ En `SessionStart`, el hook indica al agente qué notas de memoria existen (nombre y `Summary:`, o una sola línea con nombres cuando la lista es larga) y, sin goal activo, añade una línea sobre el índice de planes: número de planes, planes activos, los últimos planes completados y `docs/plan/ARCHIVE.md` si existe. Con un goal active, paused, blocked o de otra sesión solo se añade la lista de memoria, y la cápsula de otra sesión nunca muestra nombres de planes. Un `UserPromptSubmit` sin goal añade una frase con el número de notas. El hook solo lee los archivos índice y los listados de directorio, nunca el cuerpo de las notas, y no escribe nada; un repositorio sin notas ni planes recibe la misma salida que antes.
77
+
78
+ Antes de `goal finish`, `cairn-work` registra una decisión de memory promotion por goal en la Evidence del plan: `Memory promotion: docs/memory/<domain>.md` cuando el goal produjo conocimiento reutilizable del repositorio, o `Memory promotion: none: <reason>` en caso contrario. La decisión es obligatoria; escribir una nota es opcional. Si un goal se completa y su archivo de plan no tiene una línea `Memory promotion:` rellenada, `goal finish` y `goal complete` imprimen un recordatorio de una línea en stderr sin cambiar el exit code ni stdout.
71
79
 
72
80
  Los archivos raíz se mantienen cortos y los detalles pasan a `docs/`, para que los agentes lean solo el contexto que necesitan.
73
81
 
@@ -102,6 +110,9 @@ cairn toolcheck
102
110
  - `cairn uninstall`: elimina solo entradas gestionadas sin modificar; los objetivos modified o unmanaged se preservan como conflict.
103
111
  - `cairn toolcheck`: detecta repository stacks y revisa required tools; solo ejecuta un installer compatible aprobado, o devuelve `installer-unavailable`.
104
112
  - `cairn cleanup --root <repo>`: por defecto informa en modo read-only el residuo legacy `.cairn` local al proyecto. `--yes` migra/reconcilia active state válido al almacén user-home, elimina solo residuos conocidos de state/lock/tool, conserva archivos desconocidos y poda el directorio solo si queda vacío.
113
+ - `cairn memory check|index [--root <repo>]`: `check` compara `MEMORY.md` con `docs/memory/*.md` e imprime un informe JSON; sale con 1 ante notas sin indexar, dead links, duplicados, resúmenes desactualizados, caracteres de control en resúmenes o rutas inseguras, y los warnings solo fallan con `--strict`. Las entradas son líneas de lista bajo `## Domain Knowledge` (o todas las líneas de lista en un archivo antiguo sin esa sección); un enlace a una nota en otra sección es una mención que `index` nunca reescribe. `index` añade las notas que faltan y, si el `Summary:` cambió, reemplaza solo el resumen tras el enlace (una línea con varios enlaces queda como está); solo elimina líneas placeholder de Cairn que coinciden exactamente dentro de esa sección, nunca borra entradas ni dead links y conserva el resto byte a byte. `--dry-run` muestra una vista previa. Si el punto de inserción está dentro de un bloque de código sin cerrar, `index` no escribe nada y sale con 1 con `unclosed-fence`. Los errores de uso salen con 2; `cairn memory` sin subcomando sigue mostrando la guía.
114
+ - `cairn plan check|index [--archive] [--root <repo>]`: lo mismo para `PLAN.md` y `docs/plan/*.md`, cuyas entradas son líneas de lista bajo encabezados `## ` que terminan en `Plans` (como `## Superseded Plans`). `index` coloca un plan con todas sus casillas marcadas al principio de `## Completed Plans` y cualquier otro en `## Active Plans`; solo `--archive` mueve líneas a `docs/plan/ARCHIVE.md`: las entradas completadas más allá de las 20 más nuevas, con sus párrafos sangrados, y el cuerpo de una sección legacy `## Planning Rules`. `check` avisa cuando `## Completed Plans` supera 20 entradas o queda una sección legacy `## Planning Rules`.
115
+ - `cairn goal ...`: gestiona el goal del repositorio (`cairn goal --help`). `goal stats --history [--limit N]` agrega los goals terminados del repositorio en todos sus worktrees: recuentos completed/cancelled, mediana y p90 de duración, medianas de tasks y receipts, tasa de reruns, decisiones de memory promotion, un `trend` older/newer desde 4 goals completados y los goals recientes; sin historial imprime `{"schemaVersion":1,"scope":"repository","goals":0}`. `completionCriteria` (`goal start --criteria`) es `advisory`: Cairn lo registra pero no lo hace cumplir, y la finalización depende solo de la evidencia requerida.
105
116
  - `cairn-memory`: explora domain knowledge y actualiza `MEMORY.md`.
106
117
  - `cairn-plan`: crea un decision-complete plan bajo `docs/plan/`.
107
118
  - `cairn-work`: ejecuta el siguiente module task del `PLAN.md` actual con dos verification gates.
package/README.fr.md CHANGED
@@ -63,11 +63,19 @@ Les détails se trouvent dans le plugin installé sous `cairn://docs/model-guida
63
63
 
64
64
  Le harness crée et maintient ces fichiers à la racine du repository cible.
65
65
 
66
- - `MEMORY.md` : index court de persistent domain knowledge.
67
- - `docs/memory/*.md` : connaissances détaillées par domaine.
66
+ - `MEMORY.md` : index court de persistent domain knowledge : une ligne par note sous `## Domain Knowledge` (`- [<name>](docs/memory/<name>.md): <summary>`), plus la `## Policy` du dépôt.
67
+ - `docs/memory/*.md` : connaissances détaillées par domaine. Chaque note commence par une ligne `Summary:` (120 caractères au maximum) que l'index et le hook affichent.
68
68
  - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/state.json` : état active goal/task/evidence dans user-home, isolé par projet et worktree, pour la reprise et les scoped stop gates. Le working tree ne possède pas le runtime state.
69
- - `PLAN.md` : index court des sujets actifs et terminés.
69
+ - `PLAN.md` : index court des plans de travail : une ligne de 200 caractères au plus par plan sous `## Active Plans` et `## Completed Plans`. Les règles de planification vivent dans le skill `cairn-plan`, pas dans `PLAN.md`.
70
70
  - `docs/plan/*.md` : detailed execution plans.
71
+ - `docs/plan/ARCHIVE.md` : anciennes entrées terminées déplacées hors de `PLAN.md` par `cairn plan index --archive`, de la plus récente à la plus ancienne, plus le corps d'une section legacy `## Planning Rules` sous `## Legacy Planning Rules`. Les lignes de liste avant son premier titre `## ` comptent toujours comme indexées.
72
+ - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/history.jsonl` : un enregistrement de synthèse par goal terminé ou annulé (les 200 plus récents par worktree) pour `goal stats --history`.
73
+
74
+ Gardez `## Completed Plans` de la plus récente à la plus ancienne. `cairn plan index --archive` conserve les 20 premières entrées et déplace le reste vers `docs/plan/ARCHIVE.md` sans rien supprimer ; une liste tenue de la plus ancienne à la plus récente archiverait donc les plans les plus récents. Vérifiez d'abord avec `--dry-run`. Les `MEMORY.md`/`PLAN.md` existants fonctionnent sans migration : `init` ne les réécrit jamais et `check` signale l'ancien format uniquement par des warnings.
75
+
76
+ Au `SessionStart`, le hook indique à l'agent quelles notes de mémoire existent (nom et `Summary:`, ou une seule ligne de noms quand la liste est longue) et, sans goal actif, ajoute une ligne sur l'index des plans : nombre de plans, plans actifs, derniers plans terminés et `docs/plan/ARCHIVE.md` s'il existe. Avec un goal active, paused, blocked ou détenu par une autre session, seule la liste de mémoire est ajoutée, et la capsule d'une autre session n'affiche jamais de noms de plans. Un `UserPromptSubmit` sans goal ajoute une phrase avec le nombre de notes. Le hook lit uniquement les fichiers d'index et les listes de répertoires, jamais le corps des notes, et n'écrit rien ; un dépôt sans notes ni plans reçoit la même sortie qu'avant.
77
+
78
+ Avant `goal finish`, `cairn-work` consigne une décision de memory promotion par goal dans l'Evidence du plan : `Memory promotion: docs/memory/<domain>.md` quand le goal a produit une connaissance réutilisable du dépôt, sinon `Memory promotion: none: <reason>`. La décision est obligatoire ; écrire une note est facultatif. Quand un goal se termine et que son fichier de plan n'a pas de ligne `Memory promotion:` renseignée, `goal finish` et `goal complete` affichent un rappel d'une ligne sur stderr sans changer l'exit code ni stdout.
71
79
 
72
80
  Les fichiers racine restent courts et les détails vont sous `docs/`, afin que les agents ne lisent que le contexte nécessaire.
73
81
 
@@ -102,6 +110,9 @@ cairn toolcheck
102
110
  - `cairn uninstall` : supprime uniquement les entrées gérées intactes ; les cibles modified ou unmanaged sont préservées comme conflict.
103
111
  - `cairn toolcheck` : détecte repository stacks et vérifie required tools ; seul un installer approuvé et pris en charge s'exécute, sinon `installer-unavailable`.
104
112
  - `cairn cleanup --root <repo>` : signale par défaut, en lecture seule, les résidus legacy `.cairn` locaux au projet. `--yes` migre/réconcilie le valid active state vers le stockage user-home, supprime uniquement les résidus connus state/lock/tool, préserve les fichiers inconnus et ne supprime le répertoire que s'il est vide.
113
+ - `cairn memory check|index [--root <repo>]` : `check` compare `MEMORY.md` à `docs/memory/*.md` et affiche un rapport JSON ; il sort avec 1 en cas de notes non indexées, dead links, doublons, résumés périmés, caractères de contrôle dans les résumés ou chemins non sûrs, et les warnings n'échouent qu'avec `--strict`. Les entrées sont les lignes de liste sous `## Domain Knowledge` (ou toutes les lignes de liste d'un ancien fichier sans cette section) ; un lien vers une note dans une autre section est une mention que `index` ne réécrit jamais. `index` ajoute les notes manquantes et, si le `Summary:` a changé, remplace seulement le résumé après le lien (une ligne à plusieurs liens reste telle quelle) ; il ne supprime que les lignes placeholder de Cairn exactement identiques dans cette section, jamais d'entrées ni de dead links, et conserve le reste octet pour octet. `--dry-run` donne un aperçu. Si le point d'insertion est dans un bloc de code non fermé, `index` n'écrit rien et sort avec 1 avec `unclosed-fence`. Les erreurs d'usage sortent avec 2 ; `cairn memory` sans sous-commande affiche toujours le guide.
114
+ - `cairn plan check|index [--archive] [--root <repo>]` : la même chose pour `PLAN.md` et `docs/plan/*.md`, dont les entrées sont les lignes de liste sous les titres `## ` finissant par `Plans` (comme `## Superseded Plans`). `index` place un plan dont toutes les cases sont cochées en tête de `## Completed Plans` et tout autre plan dans `## Active Plans` ; seul `--archive` déplace des lignes vers `docs/plan/ARCHIVE.md` : les entrées terminées au-delà des 20 plus récentes, avec leurs paragraphes indentés, et le corps d'une section legacy `## Planning Rules`. `check` avertit quand `## Completed Plans` dépasse 20 entrées ou qu'une section legacy `## Planning Rules` subsiste.
115
+ - `cairn goal ...` : gère le goal du dépôt (`cairn goal --help`). `goal stats --history [--limit N]` agrège les goals terminés du dépôt sur tous ses worktrees : nombres completed/cancelled, médiane et p90 de durée, médianes de tasks et de receipts, taux de reruns, décisions de memory promotion, un `trend` older/newer dès 4 goals terminés et les goals récents ; sans historique il affiche `{"schemaVersion":1,"scope":"repository","goals":0}`. `completionCriteria` (`goal start --criteria`) est `advisory` : Cairn l'enregistre sans l'imposer, et la complétion dépend uniquement des preuves requises.
105
116
  - `cairn-memory` : explore domain knowledge et met à jour `MEMORY.md`.
106
117
  - `cairn-plan` : crée un decision-complete plan sous `docs/plan/`.
107
118
  - `cairn-work` : exécute le prochain module task du `PLAN.md` courant avec deux verification gates.
package/README.ja.md CHANGED
@@ -63,11 +63,19 @@ Cairn は Claude-family と Codex-family models にのみ model-specific adjustm
63
63
 
64
64
  harness は対象 repository root に次の files を作成して維持します。
65
65
 
66
- - `MEMORY.md`: persistent domain knowledge の短い index。
67
- - `docs/memory/*.md`: domain ごとの詳細 knowledge。
66
+ - `MEMORY.md`: persistent domain knowledge の短い index。`## Domain Knowledge` の下に note ごとに 1 行(`- [<name>](docs/memory/<name>.md): <summary>`)を置き、repository の `## Policy` も含みます。
67
+ - `docs/memory/*.md`: domain ごとの詳細 knowledge。各 note は H1 の下に 1 行の `Summary:`(120 文字以内)を置き、index と hook がそれを表示します。
68
68
  - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/state.json`: 中断復旧と scoped stop gate に使う user-home の project/worktree 別 active goal/task/evidence 状態。project working tree は runtime state を所有しません。
69
- - `PLAN.md`: active/completed work topics の短い index。
69
+ - `PLAN.md`: work plans の短い index。`## Active Plans` と `## Completed Plans` の下に plan ごとに 200 文字以内の 1 行を置きます。planning rules は `PLAN.md` ではなく `cairn-plan` skill にあります。
70
70
  - `docs/plan/*.md`: detailed execution plans。
71
+ - `docs/plan/ARCHIVE.md`: `cairn plan index --archive` が `PLAN.md` から移した古い completed entries を新しい順に保持し、legacy `## Planning Rules` section の本文を `## Legacy Planning Rules` の下に置きます。最初の `## ` 見出しより前の list 行は index 済みとして扱われます。
72
+ - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/history.jsonl`: completed/cancelled goal ごとの要約 record(worktree ごとに最新 200 件)。`goal stats --history` が読みます。
73
+
74
+ `## Completed Plans` は新しい順に保ちます。`cairn plan index --archive` は先頭 20 件を残し、残りを何も削除せずに `docs/plan/ARCHIVE.md` へ移すため、古い順に並べた list では最新の plans が archive されます。先に `--dry-run` で確認してください。既存の `MEMORY.md`/`PLAN.md` は migration なしで動作します。`init` は既存 file を書き換えず、`check` は古い形式を warning としてのみ報告します。
75
+
76
+ `SessionStart` で hook は、どの memory notes があるか(name と `Summary:`、list が長い場合は name だけの 1 行)を agent に知らせ、active goal がなければ plan index の 1 行(plan 数、active plans、最新の completed plans、存在すれば `docs/plan/ARCHIVE.md`)を追加します。active・paused・blocked goal や別 session が所有する goal がある場合は memory list だけを載せ、別 session の capsule に plan 名は出しません。goal がないときの `UserPromptSubmit` は note 数を伝える 1 文だけを追加します。hook は index files と directory listing だけを読み、note 本文は読まず、何も書き込みません。notes と plans がない repository の hook 出力は以前と同じです。
77
+
78
+ `cairn-work` は `goal finish` の前に goal ごとに 1 回、memory promotion の決定を plan の Evidence に記録します。再利用できる repository knowledge ができた場合は `Memory promotion: docs/memory/<domain>.md`、そうでなければ `Memory promotion: none: <reason>` です。決定の記録は必須で、note の作成は任意です。goal が完了したのに plan file に記入済みの `Memory promotion:` 行がない場合、`goal finish` と `goal complete` は stderr に 1 行の reminder を出しますが、exit code と stdout は変わりません。
71
79
 
72
80
  root files は短く保ち、詳細は `docs/` に移すことで、agents が必要な context だけを読めるようにします。
73
81
 
@@ -102,6 +110,9 @@ cairn toolcheck
102
110
  - `cairn uninstall`: 未変更の managed entry だけを削除し、modified または unmanaged target は conflict として preserve します。
103
111
  - `cairn toolcheck`: repository stacks と required tools を確認し、承認済み supported installer だけを実行します。それ以外は `installer-unavailable` です。
104
112
  - `cairn cleanup --root <repo>`: 既定では legacy project-local `.cairn` residue を read-only で報告します。`--yes` は valid active state を user-home store に移行・調整し、known state/lock/tool residue のみ削除し、unknown files を保持して空の場合だけ directory を削除します。
113
+ - `cairn memory check|index [--root <repo>]`: `check` は `MEMORY.md` と `docs/memory/*.md` を照合して JSON report を 1 つ出力します。unindexed notes、dead links、duplicates、stale summaries、summary 内の制御文字、unsafe paths があれば exit 1 で、warnings は `--strict` のときだけ失敗します。entries は `## Domain Knowledge` の下の list 行です(その section がない古い file ではすべての list 行)。他の section の note link は言及であり、`index` は書き換えません。`index` は抜けている notes を追加し、`Summary:` が変わると link の後ろの summary 部分だけを置き換えます(link が複数ある行はそのまま)。その section 内で完全に一致する Cairn placeholder 行だけを削除し、entries や dead links は削除せず、それ以外は byte 単位で保持します。`--dry-run` で事前確認できます。挿入位置が閉じていない code fence の中なら、`index` は何も書かず `unclosed-fence` で exit 1 になります。usage error は exit 2 で、subcommand なしの `cairn memory` は従来の案内を出力します。
114
+ - `cairn plan check|index [--archive] [--root <repo>]`: `PLAN.md` と `docs/plan/*.md` に同じ check と index を適用し、entries は見出しが `Plans` で終わる `## ` section(`## Superseded Plans` など)の list 行です。`index` は checkbox がすべて checked の plan を `## Completed Plans` の先頭に、それ以外を `## Active Plans` に追加します。行を移動するのは `--archive` だけで、最新 20 件を超える completed entries(インデントされた段落を含む)と legacy `## Planning Rules` section の本文を `docs/plan/ARCHIVE.md` へ移します。`check` は `## Completed Plans` が 20 件を超えるか legacy `## Planning Rules` section が残っていると warning を出します。
115
+ - `cairn goal ...`: repository goal を管理します(`cairn goal --help`)。`goal stats --history [--limit N]` は repository のすべての worktree で終了した goals を集計します。completed/cancelled 数、所要時間の median と p90、task と receipt の median、rerun rate、memory promotion の決定数、completed goal が 4 件以上のときの older/newer `trend`、最近の goals です。history がなければ `{"schemaVersion":1,"scope":"repository","goals":0}` を出力します。`completionCriteria`(`goal start --criteria`)は `advisory` です。Cairn は記録するだけで強制せず、完了は required evidence だけで判定されます。
105
116
  - `cairn-memory`: domain knowledge を探索し `MEMORY.md` を更新します。
106
117
  - `cairn-plan`: `docs/plan/` に decision-complete plan を作成します。
107
118
  - `cairn-work`: 現在の `PLAN.md` の次の module task を実行し、2 つの verification gates を取得します。
package/README.ko.md CHANGED
@@ -78,11 +78,19 @@ Cairn은 Claude-family와 Codex-family 모델에만 모델별 조정을 적용
78
78
 
79
79
  하네스는 대상 저장소 루트에 다음 파일을 생성하고 유지합니다.
80
80
 
81
- - `MEMORY.md`: 지속 도메인 지식의 짧은 색인.
82
- - `docs/memory/*.md`: 도메인별 상세 지식.
83
- - `PLAN.md`: 활성/완료 작업 주제의 짧은 색인.
81
+ - `MEMORY.md`: 지속 도메인 지식의 짧은 색인. `## Domain Knowledge` 아래에 노트당 한 줄(`- [<name>](docs/memory/<name>.md): <summary>`)을 두고, 저장소 `## Policy`를 함께 둡니다.
82
+ - `docs/memory/*.md`: 도메인별 상세 지식. 각 노트는 H1 아래에 한 줄 `Summary:`(120자 이하)를 두며, 색인과 hook이 이 줄을 보여 줍니다.
83
+ - `PLAN.md`: 작업 계획의 짧은 색인. `## Active Plans`와 `## Completed Plans` 아래에 계획당 200자 이하 한 줄을 둡니다. 계획 규칙은 `PLAN.md`가 아니라 `cairn-plan` 스킬에 있습니다.
84
84
  - `docs/plan/*.md`: 상세 실행 계획.
85
+ - `docs/plan/ARCHIVE.md`: `cairn plan index --archive`가 `PLAN.md`에서 옮긴 오래된 완료 항목을 최신순으로 보관하고, 예전 `## Planning Rules` 절의 본문은 `## Legacy Planning Rules` 아래에 둡니다. 첫 `## ` 제목 앞의 목록 줄은 색인된 것으로 셉니다.
85
86
  - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/state.json`: 중단 재개와 범위가 제한된 종료 게이트에 쓰는 사용자 홈의 프로젝트/워크트리별 활성 goal/task/증거 상태입니다. 프로젝트 작업 트리는 런타임 상태를 소유하지 않습니다.
87
+ - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/history.jsonl`: 완료·취소된 goal마다 요약 레코드 하나를 남기며(worktree당 최신 200개), `goal stats --history`가 읽습니다.
88
+
89
+ `## Completed Plans`는 최신 항목이 위에 오도록 유지합니다. `cairn plan index --archive`는 앞의 20개 항목을 남기고 나머지를 아무것도 지우지 않고 `docs/plan/ARCHIVE.md`로 옮기므로, 오래된 순으로 쌓은 목록에서는 최신 계획이 보관됩니다. 먼저 `--dry-run`으로 확인하세요. 기존 `MEMORY.md`/`PLAN.md`는 마이그레이션 없이 동작합니다. `init`은 기존 파일을 다시 쓰지 않고, `check`는 예전 형식을 경고로만 알립니다.
90
+
91
+ `SessionStart`에서 hook은 어떤 메모리 노트가 있는지(이름과 `Summary:`, 목록이 길면 이름만 나열한 한 줄)를 에이전트에게 알리고, 활성 goal이 없으면 계획 색인 한 줄(계획 수, 진행 중 계획, 최근 완료 계획, 있으면 `docs/plan/ARCHIVE.md`)을 덧붙입니다. 활성·일시정지·차단 goal이나 다른 session이 소유한 goal이 있으면 메모리 목록만 싣고, 다른 session의 캡슐에는 계획 이름을 넣지 않습니다. goal이 없을 때의 `UserPromptSubmit`은 노트 개수를 알리는 한 문장만 더합니다. hook은 색인 파일과 디렉터리 목록만 읽고 노트 본문은 읽지 않으며 아무것도 쓰지 않습니다. 노트와 계획이 없는 저장소의 hook 출력은 이전과 같습니다.
92
+
93
+ `cairn-work`는 `goal finish` 전에 goal마다 한 번 메모리 승격 결정을 계획의 Evidence에 기록합니다. 다시 쓸 저장소 지식이 생겼으면 `Memory promotion: docs/memory/<domain>.md`, 아니면 `Memory promotion: none: <reason>`입니다. 결정 기록은 필수이고 노트 작성은 선택입니다. goal이 완료됐는데 계획 파일에 채워진 `Memory promotion:` 줄이 없으면 `goal finish`와 `goal complete`가 stderr에 한 줄 알림을 내며, exit code와 stdout은 바뀌지 않습니다.
86
94
 
87
95
  런타임 script, template, command, agent, model guidance는 설치된 플러그인 루트에 유지합니다. 각 표면의 locator가 같은 설치본을 가리키므로 대상 저장소에 Cairn 내부 파일을 복사하지 않습니다. 공유 런타임 또는 locator가 없거나 읽을 수 없거나 불일치하면 이를 가리키는 모든 mirror 사용을 중단하고 게시 패키지에서 `bunx cairn-ai@latest doctor` 후 `bunx cairn-ai@latest upgrade`를 실행해 복구합니다. 다른 host mirror나 대상 저장소를 복구 원본으로 사용하지 않습니다.
88
96
 
@@ -114,10 +122,12 @@ cairn toolcheck
114
122
  - `cairn doctor`: ownership manifest, managed digest, 유효 Codex feature, 실제 plugin installed/enabled/version, mirror/runtime locator를 수정 없이 진단합니다.
115
123
  - `cairn uninstall`: 먼저 config 외 모든 ownership manifest 항목을 설치 digest와 대조하고, 수정되거나 삭제된 managed artifact가 하나라도 있으면 아무것도 바꾸지 않고 uninstall 전체를 거부합니다. 그렇지 않으면 managed 항목을 제거·복원하고 빈 managed cache scaffold를 정리하며, unmanaged target과 그 상위 디렉터리는 보존하고 commit 전 실패는 rollback합니다.
116
124
  - `cairn toolcheck`: 저장소 스택과 필요한 LSP·검증 도구를 확인하며, 승인된 지원 installer만 실행합니다.
117
- - `cairn cleanup --root <repo>`: 기본값은 legacy 프로젝트 로컬 `.cairn` 잔여물을 읽기 전용으로 보고합니다. `--yes`는 유효한 활성 상태를 사용자 홈 저장소로 조정·이관하고 알려진 상태/lock/tool 잔여물만 제거하며, 알 수 없는 파일은 보존하고 비었을 때만 디렉터리를 정리합니다.
118
- - `cairn goal ...`: 저장소의 영속 goal을 시작·조회·일시정지·재개·차단·취소·완료합니다. `goal claim --session <id>`는 같은 작업을 이어받는 session(재개·압축·handoff·fork)에 미완료 goal의 소유권을 넘기며, 미완료 goal 중에 들어온 새 작업은 goal을 취소하지 않고 `goal replan`으로 합칩니다. 기본 tool-bound 정책은 `goal verify -- <argv>`가 명령을 직접 실행해 성공 증거를 기록합니다. `goal receipt`는 기존 선언 증거를 가져오는 호환 명령입니다. 모든 `goal` 하위 명령에서 `--root`는 선택이며, 생략하면 `HARNESS_REPO_ROOT`, 없으면 cwd에서 가장 가까운 `.git` 상위 디렉터리로 결정됩니다. `goal verify --kind "moduleAcceptance|surfaceIntegration" -- <argv>`는 한 번 실행으로 kind마다 receipt를 기록하며, evidence scope는 `task`와 `goal`뿐입니다. `goal finish [--watch "<path|path>"] [--timeout-ms N] -- <argv>`는 active task를 완료하고(필수 증거가 fresh여야 함) argv를 한 번 실행해 goal requiredEvidence의 모든 kind(기본 `finalReview`)를 goal scope로 기록한 뒤 goal을 완료합니다. 이 goal scope 증거가 모든 task receipt 이후에 기록되면 이전 task 검사를 다시 실행하지 않습니다. `goal stats`는 receipt 수, 재실행, stale receipt를 JSON으로 출력합니다. task는 `dependsOn`(생략 시 이전 task)과 `writeScope`를 선언하고, `goal ready`는 active/ready/blocked task id를 출력하며, write scope가 겹치지 않는 ready task는 같은 worktree에서 최대 4개까지 병렬로 active가 될 수 있습니다.
119
- - `cairn-memory`: 도메인 지식을 탐색하고 `MEMORY.md`를 갱신합니다.
120
- - `cairn-plan`: `docs/plan/` 아래에 decision-complete plan을 만듭니다.
125
+ - `cairn cleanup --root <repo>`: 기본값은 legacy 프로젝트 로컬 `.cairn` 잔여물을 읽기 전용으로 보고합니다. `--yes`는 유효한 활성 상태를 사용자 홈 저장소로 조정·이관하고 알려진 상태/lock/tool 잔여물만 제거하며, 알 수 없는 파일은 보존하고 비었을 때만 디렉터리를 정리합니다. `state.lock`은 이 host에서 owner 프로세스가 종료된 유효한 lock 레코드일 때만 삭제하고, 격리된 `state.lock.stale.*` 파일은 유효한 레코드의 nonce가 파일 이름과 일치할 때만 삭제합니다. owner가 살아 있거나 다른 host의 lock, 파싱할 수 없는 lock은 보존하고 `preservedReasons`에 사유를 남깁니다. `--help`와 `--version`은 exit 0, 사용법 오류는 exit 2, 실행 오류는 `Cairn cleanup error:` 한 줄과 exit 1입니다.
126
+ - `cairn goal ...`: 저장소의 영속 goal을 시작·조회·일시정지·재개·차단·취소·완료합니다. `goal claim --session <id>`는 같은 작업을 이어받는 session(재개·압축·handoff·fork)에 미완료 goal의 소유권을 넘기며, 미완료 goal 중에 들어온 새 작업은 goal을 취소하지 않고 `goal replan`으로 합칩니다. 기본 tool-bound 정책은 `goal verify -- <argv>`가 명령을 직접 실행해 성공 증거를 기록합니다. `goal receipt`는 기존 선언 증거를 가져오는 호환 명령입니다. 모든 `goal` 하위 명령에서 `--root`는 선택이며, 생략하면 `HARNESS_REPO_ROOT`, 없으면 cwd에서 가장 가까운 `.git` 상위 디렉터리로 결정됩니다. `goal verify --kind "moduleAcceptance|surfaceIntegration" -- <argv>`는 한 번 실행으로 kind마다 receipt를 기록하며, evidence scope는 `task`와 `goal`뿐입니다. `goal finish [--watch "<path|path>"] [--timeout-ms N] -- <argv>`는 active task를 완료하고(필수 증거가 fresh여야 함) argv를 한 번 실행해 goal requiredEvidence의 모든 kind(기본 `finalReview`)를 goal scope로 기록한 뒤 goal을 완료합니다. 이 goal scope 증거가 모든 task receipt 이후에 기록되면 이전 task 검사를 다시 실행하지 않습니다. `goal stats`는 현재 goal의 receipt 수, 재실행, stale receipt를 JSON으로 출력합니다. `goal stats --history [--limit N]`은 저장소의 모든 worktree에서 끝난 goal을 집계합니다: 완료·취소 수, 소요 시간 중앙값과 p90, task·receipt 중앙값, 재실행 비율, 메모리 승격 결정 수, 완료 goal이 4개 이상일 때의 이전/최근 `trend`, 최근 goal 목록입니다. 이력이 없으면 `{"schemaVersion":1,"scope":"repository","goals":0}`을 출력합니다. `completionCriteria`(`goal start --criteria`)는 `advisory`입니다. Cairn은 이를 기록만 하고 강제하지 않으며, 완료는 필수 증거로만 판정합니다. task는 `dependsOn`(생략 시 이전 task)과 `writeScope`를 선언하고, `goal ready`는 active/ready/blocked task id를 출력하며, write scope가 겹치지 않는 ready task는 같은 worktree에서 최대 4개까지 병렬로 active가 될 수 있습니다.
127
+ - `cairn memory check|index [--root <repo>]`: `check`는 `MEMORY.md`와 `docs/memory/*.md`를 대조해 JSON 보고서 하나를 출력합니다. 미색인 노트, 죽은 링크, 중복, 오래된 요약, 요약의 제어문자, 안전하지 않은 경로가 있으면 exit 1이고, 경고는 `--strict`에서만 실패합니다. 항목은 `## Domain Knowledge` 아래의 목록 줄입니다(그 절이 없는 예전 파일은 모든 목록 줄). 다른 절의 노트 링크는 언급이며 `index`가 다시 쓰지 않습니다. `index`는 빠진 노트를 추가하고 `Summary:`가 바뀌면 링크 뒤의 요약 부분만 바꾸며(링크가 여럿인 줄은 그대로 둠), 그 절 안에서 Cairn placeholder 줄만 정확히 일치할 때 제거하고 항목이나 죽은 링크는 지우지 않으며 나머지 내용은 바이트 단위로 보존합니다. `--dry-run`으로 미리 볼 수 있습니다. 삽입 지점이 닫히지 않은 코드 펜스 안이면 `index`는 아무것도 쓰지 않고 `unclosed-fence`로 exit 1입니다. 사용법 오류는 exit 2이고, 하위 명령 없는 `cairn memory`는 기존 안내문을 출력합니다.
128
+ - `cairn plan check|index [--archive] [--root <repo>]`: `PLAN.md`와 `docs/plan/*.md`에 같은 검사와 색인을 적용하며, 항목은 제목이 `Plans`로 끝나는 `## ` 절(`## Superseded Plans` 등)의 목록 줄입니다. `index`는 체크박스가 모두 체크된 계획을 `## Completed Plans` 맨 위에, 그 밖의 계획을 `## Active Plans`에 넣습니다. 줄을 옮기는 것은 `--archive`뿐이며, 최신 20개를 넘는 완료 항목(들여쓴 문단 포함)과 예전 `## Planning Rules` 절의 본문을 `docs/plan/ARCHIVE.md`로 옮깁니다. `check`는 `## Completed Plans`가 20개를 넘거나 예전 `## Planning Rules` 절이 남아 있으면 경고합니다.
129
+ - `cairn-memory`: 도메인 지식을 탐색하고 `Summary:` 줄이 있는 노트를 쓰며 `MEMORY.md` 색인을 유지합니다.
130
+ - `cairn-plan`: 관련 메모리 노트와 관련 완료 계획(최대 3개)을 재활용한 뒤 `docs/plan/` 아래에 decision-complete plan을 만듭니다.
121
131
  - `cairn-work`: 현재 `PLAN.md`의 다음 모듈 작업을 실행하고 두 검증 게이트를 확보합니다.
122
132
  - `cairn-review`: 계획, memory, 증거를 기준으로 완료된 작업을 검토합니다.
123
133
 
package/README.md CHANGED
@@ -86,11 +86,19 @@ Detailed guidance lives in the installed plugin and is referenced as `cairn://do
86
86
 
87
87
  The harness creates and maintains these files at the target repository root.
88
88
 
89
- - `MEMORY.md`: short index of persistent domain knowledge.
90
- - `docs/memory/*.md`: detailed knowledge by domain.
91
- - `PLAN.md`: short index of active and completed work topics.
89
+ - `MEMORY.md`: short index of persistent domain knowledge: one line per note under `## Domain Knowledge` (`- [<name>](docs/memory/<name>.md): <summary>`) plus the repository `## Policy`.
90
+ - `docs/memory/*.md`: detailed knowledge by domain. Each note starts with a one-line `Summary:` (at most 120 characters) that the index and the hook show.
91
+ - `PLAN.md`: short index of work plans: one line of 200 characters or fewer per plan under `## Active Plans` and `## Completed Plans`. Planning rules live in the `cairn-plan` skill, not in `PLAN.md`.
92
92
  - `docs/plan/*.md`: detailed execution plans.
93
+ - `docs/plan/ARCHIVE.md`: older completed plan entries moved out of `PLAN.md` by `cairn plan index --archive`, newest first, plus the body of a legacy `## Planning Rules` section under `## Legacy Planning Rules`. List lines before its first `## ` heading still count as indexed.
93
94
  - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/state.json`: user-home, project/worktree-scoped active goal/task/evidence state used for interruption recovery and scoped stop gates. The project working tree does not own runtime state.
95
+ - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/history.jsonl`: one summary record per completed or cancelled goal (newest 200 per worktree) for `goal stats --history`.
96
+
97
+ Keep `## Completed Plans` newest first. `cairn plan index --archive` keeps the first 20 entries and moves the rest to `docs/plan/ARCHIVE.md` without deleting anything, so a list kept oldest first would archive the newest plans; preview with `--dry-run`. Existing `MEMORY.md`/`PLAN.md` files work without migration: `init` never rewrites them, and `check` only warns about the old layout.
98
+
99
+ At `SessionStart`, the hook tells the agent which memory notes exist (name and `Summary:`, or a names-only line when the list is long) and, when no goal is active, adds one line on the plan index: plan count, active plans, the latest completed plans, and `docs/plan/ARCHIVE.md` when present. Sessions with an active, paused, blocked, or foreign-owned goal get only the memory list, and a foreign capsule never shows plan names. An idle `UserPromptSubmit` adds one sentence with the note count. The hook reads only the index files and directory listings, never note bodies, and writes nothing; a repository without notes or plans gets the same hook output as before.
100
+
101
+ Before `goal finish`, `cairn-work` records one memory promotion decision per goal in the plan's Evidence: `Memory promotion: docs/memory/<domain>.md` when the goal produced reusable repository knowledge, otherwise `Memory promotion: none: <reason>`. The decision is required; writing a note is optional. When a goal completes and its plan file has no filled `Memory promotion:` line, `goal finish` and `goal complete` print a one-line reminder on stderr without changing the exit code or stdout.
94
102
 
95
103
  Runtime scripts, templates, commands, agents, and model guidance stay in the installed plugin root. Runtime locator files let Codex, Claude Code, and Antigravity share that installed copy without copying Cairn internals into the target repository. If the shared runtime or a locator is missing, unreadable, or inconsistent, stop using every mirror that points to it. Run `bunx cairn-ai@latest doctor` from the published package, then `bunx cairn-ai@latest upgrade` to recover it; do not repair one host from another mirror or search the target repository for runtime files.
96
104
 
@@ -122,10 +130,12 @@ cairn toolcheck
122
130
  - `cairn doctor`: validates the ownership manifest, managed digests, effective Codex features, actual installed/enabled/version plugin state, and mirror/runtime locators without repairing them.
123
131
  - `cairn uninstall`: verifies every non-config ownership-manifest entry against its installed digest first and refuses the whole uninstall, changing nothing, if any managed artifact was modified or removed. Otherwise it removes or restores the managed entries, prunes empty managed cache scaffolds, preserves unmanaged targets and their parent directories, and rolls back pre-commit failures.
124
132
  - `cairn toolcheck`: detects repository stacks and checks required LSP and verification tools; installation runs only for an approved supported installer.
125
- - `cairn cleanup --root <repo>`: reports legacy project-local `.cairn` residue without changing it; `--yes` migrates/reconciles valid active state into the user-home store, removes only known Cairn state/lock/tool residue, preserves unknown files, and prunes the directory only when empty.
126
- - `cairn goal ...`: starts, inspects, pauses, resumes, blocks, cancels, and completes a persisted repository goal. `goal claim --session <id>` hands an unfinished goal to the session that continues the same work (resume, compaction, handoff, fork); new work that arrives during an unfinished goal is folded in with `goal replan` instead of cancelling it. State lives under user-home `.cairn`, separated by repository and Git worktree; state without `worktreeId` and state copied from another worktree are stale and removed on the next hook/goal start. Successful completion or cancellation removes active state because completed evidence already lives in the plan document, while paused/blocked state remains resumable. The default tool-bound policy records successful evidence by executing `goal verify -- <argv>`. The legacy `goal receipt` command imports declared evidence only. `--root` is optional for every `goal` subcommand (it resolves via `HARNESS_REPO_ROOT`, else the nearest ancestor containing `.git`). `goal verify --kind "moduleAcceptance|surfaceIntegration" -- <argv>` records one receipt per kind from one run; evidence scopes are `task` and `goal`. `goal finish [--watch "<path|path>"] [--timeout-ms N] -- <argv>` completes the active task (its evidence must be fresh), runs the argv once, records every goal requiredEvidence kind (default `finalReview`) at goal scope, and completes the goal; once that goal-scope evidence is recorded after every task receipt, earlier task checks are not rerun. `goal stats` prints JSON receipt counts, reruns, and stale receipts. Tasks declare `dependsOn` (omitted = previous task) and `writeScope`; `goal ready` prints active/ready/blocked task ids, and up to 4 ready tasks with disjoint write scopes can be active in parallel in the same worktree.
127
- - `cairn-memory`: explores domain knowledge and updates `MEMORY.md`.
128
- - `cairn-plan`: creates a decision-complete plan under `docs/plan/`.
133
+ - `cairn cleanup --root <repo>`: reports legacy project-local `.cairn` residue without changing it; `--yes` migrates/reconciles valid active state into the user-home store, removes only known Cairn state/lock/tool residue, preserves unknown files, and prunes the directory only when empty. A `state.lock` is removed only when it holds a valid lock record whose owner process on this host is dead, and a quarantined `state.lock.stale.*` file only when its valid record's nonce matches its name; live-owner, foreign-host, and unparsable locks are preserved and listed with a reason in `preservedReasons`. `--help` and `--version` exit 0; usage errors exit 2 and runtime errors exit 1 with one `Cairn cleanup error:` line.
134
+ - `cairn goal ...`: starts, inspects, pauses, resumes, blocks, cancels, and completes a persisted repository goal. `goal claim --session <id>` hands an unfinished goal to the session that continues the same work (resume, compaction, handoff, fork); new work that arrives during an unfinished goal is folded in with `goal replan` instead of cancelling it. State lives under user-home `.cairn`, separated by repository and Git worktree; state without `worktreeId` and state copied from another worktree are stale and removed on the next hook/goal start. Successful completion or cancellation removes active state because completed evidence already lives in the plan document, while paused/blocked state remains resumable. The default tool-bound policy records successful evidence by executing `goal verify -- <argv>`. The legacy `goal receipt` command imports declared evidence only. `--root` is optional for every `goal` subcommand (it resolves via `HARNESS_REPO_ROOT`, else the nearest ancestor containing `.git`). `goal verify --kind "moduleAcceptance|surfaceIntegration" -- <argv>` records one receipt per kind from one run; evidence scopes are `task` and `goal`. `goal finish [--watch "<path|path>"] [--timeout-ms N] -- <argv>` completes the active task (its evidence must be fresh), runs the argv once, records every goal requiredEvidence kind (default `finalReview`) at goal scope, and completes the goal; once that goal-scope evidence is recorded after every task receipt, earlier task checks are not rerun. `goal stats` prints JSON receipt counts, reruns, and stale receipts for the current goal. `goal stats --history [--limit N]` aggregates the repository's finished goals across worktrees: completed/cancelled counts, median and p90 duration, task and receipt medians, rerun rate, memory promotion decisions, an older/newer `trend` once 4 goals have completed, and the most recent goals; with no history it prints `{"schemaVersion":1,"scope":"repository","goals":0}`. `completionCriteria` (`goal start --criteria`) is `advisory`: Cairn records it but does not enforce it, and completion is gated only by required evidence. Tasks declare `dependsOn` (omitted = previous task) and `writeScope`; `goal ready` prints active/ready/blocked task ids, and up to 4 ready tasks with disjoint write scopes can be active in parallel in the same worktree.
135
+ - `cairn memory check|index [--root <repo>]`: `check` compares `MEMORY.md` with `docs/memory/*.md` and prints one JSON report; it exits 1 for unindexed notes, dead links, duplicates, stale summaries, control characters in summaries, or unsafe paths, and warnings fail only with `--strict`. Entries are list lines under `## Domain Knowledge` (or every list line in an older file without that section); a note link in another section is a mention that `index` never rewrites. `index` adds unlisted notes, replaces only the summary after the link when `Summary:` changed (a line with several links stays as written), removes only exact Cairn placeholder lines in that section, never deletes entries or dead links, keeps the rest of the file byte-for-byte, and previews with `--dry-run`. If the insertion point is inside an unclosed code fence, `index` writes nothing and exits 1 with `unclosed-fence`. Usage errors exit 2; `cairn memory` alone still prints guidance.
136
+ - `cairn plan check|index [--archive] [--root <repo>]`: the same for `PLAN.md` and `docs/plan/*.md`, whose entries are list lines under `## ` headings ending in `Plans` (such as `## Superseded Plans`). `index` adds a plan whose checkboxes are all checked to the top of `## Completed Plans` and any other plan to `## Active Plans`; only `--archive` moves lines, to `docs/plan/ARCHIVE.md`: completed entries beyond the newest 20 with their indented paragraphs, and the body of a legacy `## Planning Rules` section. `check` warns when `## Completed Plans` has more than 20 entries or a legacy `## Planning Rules` section remains.
137
+ - `cairn-memory`: explores domain knowledge, writes notes with a `Summary:` line, and keeps `MEMORY.md` indexed.
138
+ - `cairn-plan`: reuses related memory notes and at most 3 related completed plans, then creates a decision-complete plan under `docs/plan/`.
129
139
  - `cairn-work`: executes the next module task in the current `PLAN.md` with two verification gates.
130
140
  - `cairn-review`: reviews completed tasks against plan, memory, and evidence.
131
141
 
package/README.pt.md CHANGED
@@ -63,11 +63,19 @@ A orientação detalhada fica no plugin instalado em `cairn://docs/model-guidanc
63
63
 
64
64
  O harness cria e mantem estes arquivos na raiz do repositorio alvo.
65
65
 
66
- - `MEMORY.md`: indice curto de persistent domain knowledge.
67
- - `docs/memory/*.md`: conhecimento detalhado por dominio.
66
+ - `MEMORY.md`: indice curto de persistent domain knowledge: uma linha por nota em `## Domain Knowledge` (`- [<name>](docs/memory/<name>.md): <summary>`) mais a `## Policy` do repositorio.
67
+ - `docs/memory/*.md`: conhecimento detalhado por dominio. Cada nota comeca com uma linha `Summary:` (no maximo 120 caracteres) que o indice e o hook exibem.
68
68
  - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/state.json`: active goal/task/evidence state no user-home, isolado por projeto e worktree, para retomada e scoped stop gates. O working tree nao possui runtime state.
69
- - `PLAN.md`: indice curto de active and completed work topics.
69
+ - `PLAN.md`: indice curto de planos de trabalho: uma linha de ate 200 caracteres por plano em `## Active Plans` e `## Completed Plans`. As regras de planejamento ficam no skill `cairn-plan`, nao em `PLAN.md`.
70
70
  - `docs/plan/*.md`: detailed execution plans.
71
+ - `docs/plan/ARCHIVE.md`: entradas concluidas antigas movidas de `PLAN.md` por `cairn plan index --archive`, da mais nova para a mais antiga, mais o corpo de uma secao legacy `## Planning Rules` sob `## Legacy Planning Rules`. Linhas de lista antes do seu primeiro titulo `## ` continuam contando como indexadas.
72
+ - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/history.jsonl`: um registro resumido por goal concluido ou cancelado (os 200 mais recentes por worktree) para `goal stats --history`.
73
+
74
+ Mantenha `## Completed Plans` da mais nova para a mais antiga. `cairn plan index --archive` mantem as primeiras 20 entradas e move o restante para `docs/plan/ARCHIVE.md` sem apagar nada; uma lista mantida da mais antiga para a mais nova arquivaria os planos mais recentes. Confira antes com `--dry-run`. `MEMORY.md`/`PLAN.md` existentes funcionam sem migracao: `init` nunca os reescreve e `check` apenas avisa sobre o formato antigo com warnings.
75
+
76
+ No `SessionStart`, o hook informa ao agente quais notas de memoria existem (nome e `Summary:`, ou uma linha so com nomes quando a lista e longa) e, sem goal ativo, adiciona uma linha sobre o indice de planos: quantidade de planos, planos ativos, os ultimos planos concluidos e `docs/plan/ARCHIVE.md` quando existe. Com um goal active, paused, blocked ou de outra sessao, so a lista de memoria e adicionada, e a capsula de outra sessao nunca mostra nomes de planos. Um `UserPromptSubmit` sem goal adiciona uma frase com a quantidade de notas. O hook le apenas os arquivos de indice e listagens de diretorio, nunca o corpo das notas, e nao escreve nada; um repositorio sem notas nem planos recebe a mesma saida de antes.
77
+
78
+ Antes de `goal finish`, `cairn-work` registra uma decisao de memory promotion por goal na Evidence do plano: `Memory promotion: docs/memory/<domain>.md` quando o goal gerou conhecimento reutilizavel do repositorio, ou `Memory promotion: none: <reason>` caso contrario. A decisao e obrigatoria; escrever uma nota e opcional. Quando um goal e concluido e o arquivo do plano nao tem uma linha `Memory promotion:` preenchida, `goal finish` e `goal complete` imprimem um lembrete de uma linha no stderr sem alterar o exit code nem o stdout.
71
79
 
72
80
  Arquivos raiz ficam curtos e os detalhes vao para `docs/`, para que agentes leiam apenas o contexto necessario.
73
81
 
@@ -102,6 +110,9 @@ cairn toolcheck
102
110
  - `cairn uninstall`: remove apenas entradas gerenciadas intactas; alvos modified ou unmanaged sao preservados como conflict.
103
111
  - `cairn toolcheck`: detecta repository stacks e verifica required tools; apenas um installer suportado e aprovado e executado, caso contrario `installer-unavailable`.
104
112
  - `cairn cleanup --root <repo>`: por padrao relata em modo read-only residuos legacy `.cairn` locais do projeto. `--yes` migra/reconcilia valid active state para o user-home store, remove apenas residuos conhecidos de state/lock/tool, preserva arquivos desconhecidos e remove o diretorio somente quando vazio.
113
+ - `cairn memory check|index [--root <repo>]`: `check` compara `MEMORY.md` com `docs/memory/*.md` e imprime um relatorio JSON; sai com 1 para notas nao indexadas, dead links, duplicatas, resumos desatualizados, caracteres de controle em resumos ou caminhos inseguros, e warnings so falham com `--strict`. Entradas sao linhas de lista sob `## Domain Knowledge` (ou todas as linhas de lista num arquivo antigo sem essa secao); um link de nota em outra secao e uma mencao que `index` nunca reescreve. `index` adiciona notas ausentes e, quando o `Summary:` muda, troca so o resumo apos o link (uma linha com varios links fica como esta); remove apenas linhas placeholder do Cairn que coincidem exatamente nessa secao, nunca apaga entradas nem dead links e preserva o restante byte a byte. `--dry-run` mostra uma previa. Se o ponto de insercao estiver dentro de um bloco de codigo nao fechado, `index` nao escreve nada e sai com 1 com `unclosed-fence`. Erros de uso saem com 2; `cairn memory` sem subcomando continua imprimindo a orientacao.
114
+ - `cairn plan check|index [--archive] [--root <repo>]`: o mesmo para `PLAN.md` e `docs/plan/*.md`, cujas entradas sao linhas de lista sob titulos `## ` que terminam em `Plans` (como `## Superseded Plans`). `index` coloca um plano com todas as caixas marcadas no topo de `## Completed Plans` e qualquer outro em `## Active Plans`; so `--archive` move linhas para `docs/plan/ARCHIVE.md`: entradas concluidas alem das 20 mais novas, com seus paragrafos recuados, e o corpo de uma secao legacy `## Planning Rules`. `check` avisa quando `## Completed Plans` passa de 20 entradas ou resta uma secao legacy `## Planning Rules`.
115
+ - `cairn goal ...`: gerencia o goal do repositorio (`cairn goal --help`). `goal stats --history [--limit N]` agrega os goals encerrados do repositorio em todos os worktrees: contagens completed/cancelled, mediana e p90 de duracao, medianas de tasks e receipts, taxa de reruns, decisoes de memory promotion, um `trend` older/newer a partir de 4 goals concluidos e os goals recentes; sem historico imprime `{"schemaVersion":1,"scope":"repository","goals":0}`. `completionCriteria` (`goal start --criteria`) e `advisory`: o Cairn registra mas nao o impoe, e a conclusao depende apenas da evidencia exigida.
105
116
  - `cairn-memory`: explora domain knowledge e atualiza `MEMORY.md`.
106
117
  - `cairn-plan`: cria um decision-complete plan em `docs/plan/`.
107
118
  - `cairn-work`: executa o proximo module task no `PLAN.md` atual com dois verification gates.
package/README.zh.md CHANGED
@@ -63,11 +63,19 @@ Cairn 只对 Claude-family 和 Codex-family models 应用 model-specific adjustm
63
63
 
64
64
  harness 会在目标 repository root 创建并维护这些文件。
65
65
 
66
- - `MEMORY.md`: persistent domain knowledge 的短索引。
67
- - `docs/memory/*.md`: 按 domain 记录的详细 knowledge。
66
+ - `MEMORY.md`: persistent domain knowledge 的短索引。在 `## Domain Knowledge` 下每个 note 一行(`- [<name>](docs/memory/<name>.md): <summary>`),并包含 repository 的 `## Policy`。
67
+ - `docs/memory/*.md`: 按 domain 记录的详细 knowledge。每个 note 在 H1 下有一行 `Summary:`(不超过 120 个字符),索引和 hook 会显示它。
68
68
  - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/state.json`: user-home 中按 project/worktree 隔离的 active goal/task/evidence 状态,用于中断恢复和 scoped stop gate。project working tree 不拥有 runtime state。
69
- - `PLAN.md`: active 和 completed work topics 的短索引。
69
+ - `PLAN.md`: work plans 的短索引。在 `## Active Plans` 和 `## Completed Plans` 下每个 plan 一行,不超过 200 个字符。planning rules 位于 `cairn-plan` skill,而不在 `PLAN.md` 中。
70
70
  - `docs/plan/*.md`: detailed execution plans。
71
+ - `docs/plan/ARCHIVE.md`: 按从新到旧保存 `cairn plan index --archive` 从 `PLAN.md` 移出的较旧 completed 条目,并把 legacy `## Planning Rules` section 的正文放在 `## Legacy Planning Rules` 下。第一个 `## ` 标题之前的列表行仍视为已索引。
72
+ - `~/.cairn/projects/<project-id>/worktrees/<worktree-id>/history.jsonl`: 每个 completed 或 cancelled goal 一条摘要记录(每个 worktree 保留最新 200 条),供 `goal stats --history` 读取。
73
+
74
+ `## Completed Plans` 保持从新到旧排列。`cairn plan index --archive` 保留前 20 条,把其余条目移到 `docs/plan/ARCHIVE.md` 且不删除任何内容;如果列表按从旧到新排列,被归档的会是最新的 plans。请先用 `--dry-run` 预览。现有 `MEMORY.md`/`PLAN.md` 无需迁移即可使用:`init` 不会重写已有文件,`check` 只以 warning 报告旧格式。
75
+
76
+ 在 `SessionStart`,hook 会告诉 agent 有哪些 memory notes(name 和 `Summary:`,列表过长时改为只列 name 的一行);没有 active goal 时,还会添加一行 plan 索引摘要(plan 数量、active plans、最近 completed plans,以及存在时的 `docs/plan/ARCHIVE.md`)。存在 active、paused、blocked 或其他 session 拥有的 goal 时,只附加 memory 列表,其他 session 的 capsule 绝不显示 plan 名称。没有 goal 时的 `UserPromptSubmit` 只增加一句 note 数量提示。hook 只读取索引文件和目录列表,不读取 note 正文,也不写入任何内容;没有 notes 和 plans 的 repository,hook 输出与以前相同。
77
+
78
+ `cairn-work` 在 `goal finish` 之前,每个 goal 在 plan 的 Evidence 中记录一次 memory promotion 决定:产生了可复用的 repository knowledge 时写 `Memory promotion: docs/memory/<domain>.md`,否则写 `Memory promotion: none: <reason>`。记录决定是必需的,编写 note 是可选的。goal 完成但 plan 文件中没有已填写的 `Memory promotion:` 行时,`goal finish` 和 `goal complete` 会在 stderr 输出一行提醒,exit code 和 stdout 不变。
71
79
 
72
80
  root files 保持简短,细节移到 `docs/` 下,让 agents 只读取当前任务需要的 context。
73
81
 
@@ -102,6 +110,9 @@ cairn toolcheck
102
110
  - `cairn uninstall`: 只删除未修改的 managed entry;modified 或 unmanaged target 会 preserve 并报告 conflict。
103
111
  - `cairn toolcheck`: 检测 repository stacks 和 required tools;只执行已批准的 supported installer,否则返回 `installer-unavailable`。
104
112
  - `cairn cleanup --root <repo>`: 默认只读报告 legacy project-local `.cairn` residue。`--yes` 将 valid active state 迁移/协调到 user-home store,只删除 known state/lock/tool residue,保留 unknown files,并且仅在目录为空时清理目录。
113
+ - `cairn memory check|index [--root <repo>]`: `check` 对照 `MEMORY.md` 与 `docs/memory/*.md` 并输出一个 JSON 报告;存在 unindexed notes、dead links、duplicates、stale summaries、summary 中的控制字符或 unsafe paths 时 exit 1,warnings 仅在 `--strict` 下失败。条目是 `## Domain Knowledge` 下的列表行(没有该 section 的旧文件则为所有列表行);其他 section 中的 note 链接只是提及,`index` 不会改写。`index` 添加缺失的 notes,`Summary:` 变化时只替换链接后的 summary 部分(含多个链接的行保持原样);只删除该 section 内完全匹配的 Cairn placeholder 行,不删除条目或 dead links,其余内容逐字节保留。可用 `--dry-run` 预览。插入位置位于未闭合的 code fence 内时,`index` 不写入任何内容,并以 `unclosed-fence` exit 1。用法错误 exit 2;不带子命令的 `cairn memory` 仍输出原有指引。
114
+ - `cairn plan check|index [--archive] [--root <repo>]`: 对 `PLAN.md` 和 `docs/plan/*.md` 执行相同的检查和索引,条目是标题以 `Plans` 结尾的 `## ` section(如 `## Superseded Plans`)中的列表行。`index` 把 checkbox 全部勾选的 plan 放到 `## Completed Plans` 顶部,其他 plan 放到 `## Active Plans`;只有 `--archive` 会移动行:把超出最新 20 条的 completed 条目(连同缩进段落)和 legacy `## Planning Rules` section 的正文移到 `docs/plan/ARCHIVE.md`。`## Completed Plans` 超过 20 条或仍有 legacy `## Planning Rules` section 时,`check` 会给出 warning。
115
+ - `cairn goal ...`: 管理 repository goal(`cairn goal --help`)。`goal stats --history [--limit N]` 汇总 repository 所有 worktree 中已结束的 goals:completed/cancelled 数量、耗时的中位数和 p90、task 与 receipt 的中位数、rerun rate、memory promotion 决定数、completed goal 达到 4 个后的 older/newer `trend`,以及最近的 goals;没有历史时输出 `{"schemaVersion":1,"scope":"repository","goals":0}`。`completionCriteria`(`goal start --criteria`)是 `advisory`:Cairn 只记录不强制,完成只由 required evidence 判定。
105
116
  - `cairn-memory`: 探索 domain knowledge 并更新 `MEMORY.md`。
106
117
  - `cairn-plan`: 在 `docs/plan/` 下创建 decision-complete plan。
107
118
  - `cairn-work`: 执行当前 `PLAN.md` 中的下一个 module task,并收集两个 verification gates。
@@ -8,7 +8,7 @@ tools: Read, Grep, Glob, Bash
8
8
 
9
9
  Handle read-only discovery and verification tasks.
10
10
 
11
- Before an assigned task, read project-root `MEMORY.md` when present. If absent, continue without repository memory and do not invoke another memory service; then read only relevant `docs/memory/*.md` notes that exist.
11
+ Before an assigned task, read project-root `MEMORY.md` when present. If absent, continue without repository memory and do not invoke another memory service. Then open only the `docs/memory/*.md` notes whose `MEMORY.md` entries (one line and summary per note) match the task, plus any note paths the assignment names; do not read every note.
12
12
 
13
13
  At the start and after compaction, restart, or handoff, restore context in this order: root `MEMORY.md` → the phase skill named by the assignment → the active plan → current-task references → model guidance recorded by that plan. The assignment must identify the plan and current task whenever persisted work is active. If a required reference is missing, unreadable, or inconsistent with the assignment or goal state, report a blocker and do not perform the assigned discovery or delegate it.
14
14
 
package/agents/worker.md CHANGED
@@ -8,7 +8,7 @@ tools: Read, Grep, Glob, Bash, Write, Edit, MultiEdit
8
8
 
9
9
  Handle narrow, focused tasks.
10
10
 
11
- Before an assigned task, read project-root `MEMORY.md` when present. If absent, continue without repository memory and do not invoke another memory service; then read only relevant `docs/memory/*.md` notes that exist.
11
+ Before an assigned task, read project-root `MEMORY.md` when present. If absent, continue without repository memory and do not invoke another memory service. Then open only the `docs/memory/*.md` notes whose `MEMORY.md` entries (one line and summary per note) match the task, plus any note paths the assignment names; do not read every note.
12
12
 
13
13
  At the start and after compaction, restart, or handoff, restore context in this order: root `MEMORY.md` → the phase skill named by the assignment → the active plan → current-task references → model guidance recorded by that plan. The assignment must identify the plan and current task whenever persisted work is active. If a required reference is missing, unreadable, or inconsistent with the assignment or goal state, report a blocker and do not edit, delegate, or claim completion.
14
14
 
@@ -12,6 +12,6 @@ Procedure:
12
12
  2. Every agent reads project-root `MEMORY.md` when present and continues without repository memory when absent before assigned discovery or update work.
13
13
  3. Explore repository facts with focused tools.
14
14
  4. Use `explorer` for read-only domain discovery and contradiction checks when available; use `worker` for exact references, command checks, and bounded evidence capture. When subagent tools are available, each agent may recursively delegate bounded sub-tasks to subagents. Tell every delegated agent and child subagent to read the project-root `MEMORY.md` before work, keep scope, and preserve others' edits.
15
- 5. Write details to `docs/memory/<domain>.md`. When a lesson or correction recurs and is machine-checkable, encode it as a test, lint rule, script, or hook instead of more prose; memory keeps judgment rules and a pointer to the enforcing check.
16
- 6. Keep `MEMORY.md` as a short index.
15
+ 5. Write details to `docs/memory/<domain>.md` with a `Summary:` line under the H1 (one line, at most 120 characters: what the note answers and when to read it). When a lesson or correction recurs and is machine-checkable, encode it as a test, lint rule, script, or hook instead of more prose; memory keeps judgment rules and a pointer to the enforcing check.
16
+ 6. Keep `MEMORY.md` as a short index: one line per note under `## Domain Knowledge`; a note link in another section is a mention that `index` never rewrites. Run the installed Cairn CLI with `memory index --root <repoRoot>` to add unlisted notes and refresh changed summaries (`--dry-run` previews; it never deletes entries and writes nothing when the insertion point is inside an unclosed code fence), then `memory check --root <repoRoot>` and fix the unindexed notes, dead links, duplicates, stale summaries, or control characters it reports.
17
17
  7. Use the OS locale for user-visible responses and generated or updated documentation, plans, and memory artifacts unless the user asks for another language.
@@ -13,9 +13,9 @@ Complexity is staged: request checkpoint, planning checkpoint after exploration,
13
13
  Procedure:
14
14
 
15
15
  1. Every agent reads project-root `MEMORY.md` when present and continues without repository memory when absent before repository exploration, tool selection, work, or delegation.
16
- 2. For non-trivial implementation or continuation of planned work, write an initial `docs/plan/<topic>.md` and `PLAN.md` entry with `triage-plan` as the first active task. This initial plan is decision-complete for triage and explicitly not implementation-ready.
16
+ 2. For non-trivial implementation or continuation of planned work, write an initial `docs/plan/<topic>.md` and `PLAN.md` entry with `triage-plan` as the first active task. The `PLAN.md` entry is one line of 200 characters or fewer under `## Active Plans`; the installed Cairn CLI's `plan index --root <repoRoot>` adds missing entries and `plan check --root <repoRoot>` verifies them. This initial plan is decision-complete for triage and explicitly not implementation-ready.
17
17
  3. Before exploration, toolcheck, triage, or delegation, call Codex `update_plan` and then `create_goal` when available (main agent only; subagents skip), and start the repository Cairn goal with the same roadmap. Copy the session-start hook's `Cairn CLI:` prefix literally into each command; never store it in a shell variable. `--root` may be omitted when the cwd is inside the repository. Fold new work into an unfinished goal with `goal replan` instead of cancelling it; when a hook reports another session owns the goal you continue, run `goal claim --session <id>`.
18
- 4. Read relevant `docs/memory/*.md` and the installed model guidance, run `toolcheck --root <repoRoot>` (installation only with explicit approval), and explore before asking the user.
18
+ 4. Reuse before exploring: pick related `docs/memory` notes from the `MEMORY.md` entries and at most 3 completed plans from `PLAN.md` (older ones in `docs/plan/ARCHIVE.md`) that changed the same modules or solved the same kind of problem; read only those plans' goal, design decisions, and evidence, and record the picks in the plan's `## Memory Inputs` with `Related completed plans:` (or `none related`). Read the picked notes and the installed model guidance, run `toolcheck --root <repoRoot>` (installation only with explicit approval), and explore before asking the user.
19
19
  5. Classify the whole work into executable tasks with `dependsOn`, `writeScope`, and handoff files, finalize triage, and update the same plan and `update_plan` roadmap to a decision-complete implementation plan: selected path, checked Heavy Path signals, tool readiness, file scope, dry-run/check, module acceptance, surface integration, stable IDs, and fail-closed evidence. Heavy Path adds an explicit automated test command and `Tests:` evidence line.
20
20
  6. Read the skill's reference files only when needed: `cairn://skills/cairn-plan/planning-rules.md` when finalizing, `cairn://skills/cairn-plan/delegation.md` before dispatching, `cairn://skills/cairn-plan/heavy-path.md` only on a Heavy signal or route change.
21
21
  7. The user-called/main agent orchestrates; implementation edits go to `worker` when subagent tools are available, otherwise the main agent takes over and records it. Advance a UI step only after the matching repository task transition succeeds with its required bound evidence.
@@ -9,7 +9,7 @@ Goal: review completed work against plan, memory, policy, and evidence.
9
9
  Procedure:
10
10
 
11
11
  1. Every agent reads project-root `MEMORY.md` when present and continues without repository memory when absent before review work, then reads the plan task and available memory inputs.
12
- 2. Check changed files, tool readiness evidence, and verification evidence. Inspect test, fixture, and verification-command diffs and reject any weakening without a recorded plan reason. For defect fixes, confirm the same-rule sweep was performed and its result recorded.
12
+ 2. Check changed files, tool readiness evidence, and verification evidence. Inspect test, fixture, and verification-command diffs and reject any weakening without a recorded plan reason. For defect fixes, confirm the same-rule sweep was performed and its result recorded. Confirm the plan's Evidence has a filled `Memory promotion:` line (`docs/memory/<domain>.md` or `none: <reason>`) and that the installed Cairn CLI's `memory check --root <repoRoot>` and `plan check --root <repoRoot>` exit 0. A `none: <reason>` decision is acceptable: do not create a note or demand one; flag a missing or placeholder line, or a named note that does not exist.
13
13
  3. Delegate independent read-only review to `explorer` when it materially improves speed or quality; use `worker` only for scoped verification reruns or QA artifacts. When subagent tools are available, each agent may recursively delegate bounded sub-tasks to subagents. Tell every delegated agent and child subagent to read the project-root `MEMORY.md` before work, keep scope, and preserve others' edits.
14
14
  4. Report findings first, ordered by severity, with file and line references. If no issues are found, say so clearly and mention remaining test gaps or residual risk.
15
15
  5. Record review evidence in `docs/plan/<topic>.md` and as the goal-level final review evidence record before completing the goal.
@@ -18,7 +18,7 @@ Procedure:
18
18
  6. Run module acceptance and surface integration through `goal verify -- ...`; `--kind "moduleAcceptance|surfaceIntegration"` records both from one run. Treat tool exit codes as authoritative and expand context only around failing tests. Heavy Path records explicit `Tests:` evidence.
19
19
  7. Never edit, weaken, skip, or delete existing tests, fixtures, or verification commands to make a gate pass unless the plan records the contract change. Reproduce reported defects before fixing, and after a fix search for other implementations of the same rule or pattern.
20
20
  8. Inspect package lifecycle scripts and run normal `npm pack --dry-run` by default. Content-producing or unknown lifecycle scripts must never use `--ignore-scripts`; only absent or proven content-neutral scripts may use it while the full check remains fresh.
21
- 9. Relevant mutation makes the current task's evidence stale; rerun it before completing the task. Do not rerun earlier tasks' checks; finish with one goal-level check through `goal finish -- ...`. Missing, failed, skipped, stale, or placeholder evidence never completes work. `goal stats` measures receipt reruns.
21
+ 9. Relevant mutation makes the current task's evidence stale; rerun it before completing the task. Do not rerun earlier tasks' checks; finish with one goal-level check through `goal finish -- ...`. Missing, failed, skipped, stale, or placeholder evidence never completes work. `goal stats` measures receipt reruns; `goal stats --history` compares finished goals of the repository.
22
22
  10. Read the skill's reference files only when needed: `cairn://skills/cairn-work/verification.md`, `cairn://skills/cairn-work/delegation.md`, `cairn://skills/cairn-work/recovery.md`, and `cairn://skills/cairn-work/heavy-path.md` (Heavy route only).
23
- 11. Update the plan, goal state, and `PLAN.md` only after evidence exists. Answer side questions briefly and resume unless explicitly asked to pause, stop, or switch.
23
+ 11. Before `goal finish`, record the memory promotion decision in the plan's Evidence: `Memory promotion: docs/memory/<domain>.md` when the goal produced reusable repository knowledge (write the note with a `Summary:` line, then run `memory index --root <repoRoot>`), otherwise `Memory promotion: none: <reason>`. The line is required and the note is optional: do not create a note when nothing qualifies. Update the plan, goal state, and `PLAN.md` only after evidence exists. Answer side questions briefly and resume unless explicitly asked to pause, stop, or switch.
24
24
  12. Use the OS locale for user-visible responses and generated or updated documentation, plans, and memory artifacts unless the user asks for another language.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cairn-ai",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Token-efficient agent harness with tool readiness for Codex, Claude Code, and Antigravity",
5
5
  "license": "MIT",
6
6
  "author": {