cairn-ai 0.5.0 → 0.7.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 (65) hide show
  1. package/.agents/workflows/cairn-doctor.md +4 -1
  2. package/.agents/workflows/cairn-install.md +3 -1
  3. package/.agents/workflows/cairn-memory.md +2 -2
  4. package/.agents/workflows/cairn-plan.md +2 -2
  5. package/.agents/workflows/cairn-review.md +1 -1
  6. package/.agents/workflows/cairn-uninstall.md +3 -1
  7. package/.agents/workflows/cairn-upgrade.md +3 -1
  8. package/.agents/workflows/cairn-work.md +2 -2
  9. package/.claude/agents/explorer.md +1 -1
  10. package/.claude/agents/worker.md +1 -1
  11. package/.codex-plugin/plugin.json +2 -2
  12. package/README.de.md +46 -8
  13. package/README.es.md +46 -8
  14. package/README.fr.md +46 -8
  15. package/README.ja.md +46 -8
  16. package/README.ko.md +51 -15
  17. package/README.md +51 -15
  18. package/README.pt.md +46 -8
  19. package/README.zh.md +46 -8
  20. package/agents/explorer.md +1 -1
  21. package/agents/worker.md +1 -1
  22. package/commands/cairn-doctor.md +4 -1
  23. package/commands/cairn-install.md +11 -5
  24. package/commands/cairn-memory.md +2 -2
  25. package/commands/cairn-plan.md +2 -2
  26. package/commands/cairn-review.md +1 -1
  27. package/commands/cairn-uninstall.md +9 -4
  28. package/commands/cairn-upgrade.md +8 -1
  29. package/commands/cairn-work.md +2 -2
  30. package/package.json +2 -2
  31. package/scripts/cairn-auto-upgrade.mjs +334 -0
  32. package/scripts/cairn-cleanup.mjs +142 -15
  33. package/scripts/cairn-goal-cli.mjs +50 -4
  34. package/scripts/cairn-goal-history.mjs +316 -0
  35. package/scripts/cairn-goal-operations-evidence.mjs +2 -2
  36. package/scripts/cairn-goal-operations.mjs +11 -3
  37. package/scripts/cairn-goal.mjs +3 -0
  38. package/scripts/cairn-index.mjs +1052 -0
  39. package/scripts/cairn-lifecycle-claude.mjs +64 -18
  40. package/scripts/cairn-lifecycle-commands.mjs +355 -79
  41. package/scripts/cairn-lifecycle-hosts.mjs +98 -0
  42. package/scripts/cairn-lifecycle-integrity.mjs +106 -33
  43. package/scripts/cairn-lifecycle-layout.mjs +69 -0
  44. package/scripts/cairn-lifecycle-staging.mjs +45 -30
  45. package/scripts/cairn-lifecycle-transaction-journal.mjs +50 -7
  46. package/scripts/cairn-lifecycle.mjs +148 -45
  47. package/scripts/cairn-paths.mjs +12 -0
  48. package/scripts/cairn-safe-fs.mjs +7 -2
  49. package/scripts/cairn-state-context.mjs +126 -10
  50. package/scripts/cairn-state-init.mjs +11 -68
  51. package/scripts/cairn-state.mjs +63 -19
  52. package/scripts/cairn-update-state.mjs +219 -0
  53. package/scripts/cairn.mjs +68 -26
  54. package/skills/cairn-memory/SKILL.md +4 -4
  55. package/skills/cairn-plan/SKILL.md +2 -2
  56. package/skills/cairn-plan/delegation.md +2 -1
  57. package/skills/cairn-plan/planning-rules.md +10 -0
  58. package/skills/cairn-review/SKILL.md +3 -1
  59. package/skills/cairn-work/SKILL.md +1 -1
  60. package/skills/cairn-work/delegation.md +2 -1
  61. package/skills/cairn-work/verification.md +15 -1
  62. package/templates/MEMORY.md +4 -6
  63. package/templates/PLAN.md +2 -15
  64. package/templates/domain-memory.md +2 -0
  65. package/templates/work-plan.md +3 -1
package/README.ko.md CHANGED
@@ -78,13 +78,21 @@ 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`가 읽습니다.
86
88
 
87
- 런타임 script, template, command, agent, model guidance는 설치된 플러그인 루트에 유지합니다. 각 표면의 locator가 같은 설치본을 가리키므로 대상 저장소에 Cairn 내부 파일을 복사하지 않습니다. 공유 런타임 또는 locator가 없거나 읽을 수 없거나 불일치하면 이를 가리키는 모든 mirror 사용을 중단하고 게시 패키지에서 `bunx cairn-ai@latest doctor` 후 `bunx cairn-ai@latest upgrade`를 실행해 복구합니다. 다른 host mirror나 대상 저장소를 복구 원본으로 사용하지 않습니다.
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은 바뀌지 않습니다.
94
+
95
+ 런타임 script, template, command, agent, model guidance는 설치된 canonical runtime `~/.cairn/install/runtime/<version>/`에 유지합니다. 각 표면의 locator가 같은 설치본을 가리키므로 대상 저장소에 Cairn 내부 파일을 복사하지 않습니다. 공유 런타임 또는 locator가 없거나 읽을 수 없거나 불일치하면 이를 가리키는 모든 mirror 사용을 중단하고 게시 패키지에서 `bunx cairn-ai@latest doctor` 후 `bunx cairn-ai@latest upgrade`를 실행해 복구합니다. 다른 host mirror나 대상 저장소를 복구 원본으로 사용하지 않습니다.
88
96
 
89
97
  ## Commands
90
98
 
@@ -107,17 +115,21 @@ cairn upgrade
107
115
  cairn doctor
108
116
  cairn uninstall
109
117
  cairn toolcheck
118
+ cairn auto-upgrade status
110
119
  ```
111
120
 
112
- - `cairn install`: custom marketplace source, versioned Codex runtime cache, Cairn-owned config section, Claude Code mirror와 플러그인, 현재 Antigravity IDE/CLI skill 표면을 transaction으로 설치합니다.
113
- - `cairn upgrade`: ownership manifest의 installed digest와 현재 값이 같은 항목만 교체하며, staged validation과 역순 rollback을 적용합니다.
114
- - `cairn doctor`: ownership manifest, managed digest, 유효 Codex feature, 실제 plugin installed/enabled/version, mirror/runtime locator를 수정 없이 진단합니다.
115
- - `cairn uninstall`: 먼저 config 외 모든 ownership manifest 항목을 설치 digest와 대조하고, 수정되거나 삭제된 managed artifact가 하나라도 있으면 아무것도 바꾸지 않고 uninstall 전체를 거부합니다. 그렇지 않으면 managed 항목을 제거·복원하고 빈 managed cache scaffold를 정리하며, unmanaged target과 그 상위 디렉터리는 보존하고 commit 전 실패는 rollback합니다.
121
+ - `cairn install [--hosts all|codex,claude,antigravity]`: canonical runtime을 `~/.cairn/install/` 아래에 설치하고, 선택한 호스트에 대해 Codex marketplace source, versioned Codex runtime cache, Cairn-owned config section, Claude Code mirror와 플러그인, 현재 Antigravity IDE/CLI skill 표면을 transaction으로 설치합니다. `--hosts`가 없으면 터미널에서 처음 설치할 때 호스트를 묻고, 비대화형 실행과 CI는 모든 호스트를 설치합니다.
122
+ - `cairn upgrade [--hosts all|codex,claude,antigravity]`: ownership manifest의 installed digest와 현재 값이 같은 항목만 교체하며, staged validation과 역순 rollback을 적용합니다. `--hosts`로 바꾸지 않으면 기록된 호스트를 유지하고, Cairn 0.6.0 이하에서 만든 설치를 이전하며, 다른 버전을 담은 Claude Code 플러그인 캐시를 갱신합니다. 설치본 버전이 이 CLI보다 높으면 `install`과 `upgrade`는 아무것도 바꾸지 않고 거부하며, 그래도 이 CLI 버전으로 내리려면 `--allow-downgrade`를 붙입니다.
123
+ - `cairn doctor`: 첫 줄에 `Hosts: <ids>`를 출력한 뒤 선택된 호스트의 ownership manifest, managed digest, 유효 Codex feature, 실제 plugin installed/enabled/version(`Claude plugin cache version` 포함), mirror/runtime locator를 수정 없이 진단합니다. legacy 설치가 있으면 `cairn upgrade`로 이전하라는 안내를 출력합니다.
124
+ - `cairn uninstall`: 먼저 config 외 모든 ownership manifest 항목을 설치 digest와 대조하고, 수정되거나 삭제된 managed artifact가 하나라도 있으면 아무것도 바꾸지 않고 uninstall 전체를 거부합니다. 그렇지 않으면 managed 항목과 유예 중인 runtime을 제거·복원하고 빈 managed scaffold를 정리하며, unmanaged target과 그 상위 디렉터리는 보존하고 commit 전 실패는 rollback합니다. `~/.cairn/update/`도 지우며 `~/.cairn/config.json`과 `~/.cairn/projects/`는 남깁니다. legacy 레이아웃 설치는 이전하지 않고 그 자리에서 제거합니다.
125
+ - `cairn auto-upgrade status|on|off|run`: `status`는 설정, 설치 버전, 마지막 확인, 대기 중인 알림을 JSON으로 출력합니다. `on`과 `off`는 `~/.cairn/config.json`에 `autoUpgrade`를 쓰고 같은 보고를 출력합니다. `run`은 하루 주기와 backoff를 무시하고 지금 npm을 확인해 결과를 출력합니다. exit 0은 성공, 1은 실행 오류 또는 실패한 실행, 2는 사용법 오류입니다.
116
126
  - `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을 만듭니다.
127
+ - `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입니다.
128
+ - `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가 될 수 있습니다.
129
+ - `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`는 기존 안내문을 출력합니다.
130
+ - `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` 절이 남아 있으면 경고합니다.
131
+ - `cairn-memory`: 도메인 지식을 탐색하고 `Summary:` 줄이 있는 노트를 쓰며 `MEMORY.md` 색인을 유지합니다.
132
+ - `cairn-plan`: 관련 메모리 노트와 관련 완료 계획(최대 3개)을 재활용한 뒤 `docs/plan/` 아래에 decision-complete plan을 만듭니다.
121
133
  - `cairn-work`: 현재 `PLAN.md`의 다음 모듈 작업을 실행하고 두 검증 게이트를 확보합니다.
122
134
  - `cairn-review`: 계획, memory, 증거를 기준으로 완료된 작업을 검토합니다.
123
135
 
@@ -125,13 +137,37 @@ cairn toolcheck
125
137
 
126
138
  토큰 효율 실행에서는 구현보다 먼저 요구사항·불변식·경계·실패 모드로 집중 실행 test contract를 설계하는 데 추론을 배분합니다. 구현에는 실패 계약과 제한된 파일 범위만 전달하고 통과에 필요한 최소 변경을 요구합니다. 성공 여부는 도구 exit code와 기계적 요약으로 판정하며 성공 출력은 축약하고 실패할 때만 컨텍스트를 확장합니다. 명시적 `--watch`가 없으면 Git fingerprint는 ignored file을 제외하므로 주장에 필요한 ignored artifact는 각각 `--watch <path>` 또는 명시적인 상위 디렉터리로 지정해야 합니다. package 검증 전 lifecycle script를 검사하고 기본적으로 정상 `npm pack --dry-run`을 실행합니다. content-producing 또는 미분류 script에는 `--ignore-scripts`를 사용하면 안 되며, script가 없거나 content-neutral임을 입증했고 전체 검사 증거가 여전히 유효할 때만 사용할 수 있습니다. 성공한 상태 변경은 `--quiet`를 지원하므로 커지는 goal JSON이 대화 토큰을 소모하지 않습니다.
127
139
 
128
- `install`과 `upgrade`는 custom marketplace lifecycle을 유지하며 `codex plugin add`를 호출하지 않습니다. candidate를 staging에서 검증한 뒤 commit하고, 현재 managed destination과 digest를 ownership manifest에 기록하며 실패 시 완료된 phase를 역순 rollback합니다. 별도의 고정된 SHA-256 release 0.2.2 file-hash allowlist는 정확한 legacy file set 검증 전용이며 현재 package file list나 암호학적 서명이 아닙니다. 수정되지 않은 지원 legacy 설치만 release-integrity 검증 뒤 인수하고, 수정되거나 알 수 없는 artifact는 보존한 채 거부합니다. Cairn-owned TOML section만 편집하고 public feature/agent 설정은 강제하지 않습니다. lifecycle command는 교체 대상 cache copy가 아니라 게시/전역 package에서 실행해야 합니다.
140
+ `install`과 `upgrade`는 custom marketplace lifecycle을 유지하며 `codex plugin add`를 호출하지 않습니다. candidate를 staging에서 검증한 뒤 commit하고, 현재 managed destination과 digest를 ownership manifest에 기록하며 실패 시 완료된 phase를 역순 rollback합니다. 별도의 고정된 SHA-256 release 0.2.2 file-hash allowlist는 정확한 legacy file set 검증 전용이며 현재 package file list나 암호학적 서명이 아닙니다. 수정되지 않은 지원 legacy 설치만 release-integrity 검증 뒤 인수하고, 수정되거나 알 수 없는 artifact는 보존한 채 거부합니다. Cairn-owned TOML section만 편집하고 public feature/agent 설정은 강제하지 않습니다. lifecycle command는 교체 대상인 `~/.cairn/install/` 아래 설치본이나 Codex plugin cache가 아니라 게시/전역 package에서 실행해야 합니다.
129
141
 
130
- Clean uninstall은 모든 managed scaffold가 비었을 때만 recursive 삭제 없이 빈 디렉터리 제거로 Cairn marketplace cache root를 정리합니다. 소스 저장소와 저장소의 `MEMORY.md`/`PLAN.md`, 사용자 홈 Cairn goal 상태, 전역 `cairn-ai` package, package-manager download cache, legacy backup, 현재 ownership manifest 밖의 legacy shared setting은 지우지 않으며 별도의 명시적 정리 판단이 필요합니다.
142
+ Clean uninstall은 모든 managed scaffold가 비었을 때만 recursive 삭제 없이 빈 디렉터리 제거로 `~/.cairn/install/`과 Codex cache root `$CODEX_HOME/plugins/cache/cairn`을 정리합니다. 소스 저장소와 저장소의 `MEMORY.md`/`PLAN.md`, 사용자 홈 Cairn goal 상태, 전역 `cairn-ai` package, package-manager download cache, legacy backup, 현재 ownership manifest 밖의 legacy shared setting은 지우지 않으며 별도의 명시적 정리 판단이 필요합니다.
131
143
 
132
144
  Codex는 `skills/`와 `commands/`를 사용합니다. Claude Code는 `~/.claude/` 아래의 mirror command·agent definition과 Claude Code 플러그인 `cairn@cairn`을 사용합니다. Antigravity는 `.agents/workflows`와 global skills mirror를 사용합니다.
133
145
 
134
- Claude Code 플러그인은 Cairn이 소유한 로컬 marketplace `~/.codex/plugins/cache/cairn/claude`에 생성되며, Cairn skill 4개와 SessionStart·UserPromptSubmit·PostToolUse·Stop·SubagentStop hook을 담습니다. hook은 설치된 버전 런타임을 절대경로로 호출합니다. 파일 commit 뒤 `cairn install`/`upgrade`가 `claude plugin marketplace add`와 `claude plugin install cairn@cairn --scope user`로 등록하므로 다음 세션부터 Claude Code 터미널·데스크톱 앱·IDE 플러그인 목록에 표시됩니다. `claude` CLI가 없으면 등록을 건너뛰고 수동 명령을 안내하며, 이미 `cairn`이라는 다른 marketplace가 있으면 건드리지 않습니다. `cairn uninstall`은 파일 제거 전에 Cairn 소유 marketplace만 등록 해제하고, uninstall이 rollback되면 다시 등록합니다. `cairn doctor`는 `Claude plugin files`, `Claude plugin registered`, `Claude plugin enabled`를 보고합니다.
146
+ Claude Code 플러그인은 Cairn이 소유한 로컬 marketplace `~/.cairn/install/claude`에 생성되며, Cairn skill 4개와 SessionStart·UserPromptSubmit·PostToolUse·Stop·SubagentStop hook을 담습니다. hook은 canonical runtime을 절대경로로 호출합니다. 파일 commit 뒤 `cairn install`/`upgrade`가 `claude plugin marketplace add`와 `claude plugin install cairn@cairn --scope user`로 등록하므로 다음 세션부터 Claude Code 터미널·데스크톱 앱·IDE 플러그인 목록에 표시됩니다. `claude` CLI가 없으면 등록을 건너뛰고 수동 명령을 안내하며, 이미 `cairn`이라는 다른 marketplace가 있으면 건드리지 않습니다. `cairn uninstall`은 파일 제거 전에 Cairn 소유 marketplace만 등록 해제하고, uninstall이 rollback되면 다시 등록합니다. Claude Code 플러그인 캐시에 다른 버전이 있으면 `cairn upgrade`가 `claude plugin marketplace update cairn`과 `claude plugin update cairn@cairn --scope user`로 갱신합니다. 갱신에 실패하면 업그레이드된 설치는 그대로 두고 수동으로 마칠 명령을 출력하며 exit 1입니다. `cairn doctor`는 `Claude plugin files`, `Claude plugin registered`, `Claude plugin enabled`, `Claude plugin cache version`을 보고합니다.
147
+
148
+ ## Install Layout And Auto-Upgrade
149
+
150
+ Cairn은 설치본을 `CAIRN_HOME`(기본 `~/.cairn`) 아래에 둡니다. `CODEX_HOME`, `CLAUDE_HOME`, `ANTIGRAVITY_HOME`, `ANTIGRAVITY_CLI_HOME`, `CODEX_CONFIG_PATH`는 여전히 각 호스트 경로를 따로 정합니다.
151
+
152
+ ```text
153
+ ~/.cairn/
154
+ install/ lifecycle 관리 파일
155
+ lifecycle.json ownership manifest (schema 2: hosts, origin, 유예 runtime)
156
+ lifecycle.lock, transaction.json, transactions/
157
+ runtime/<version>/ 모든 runtime locator와 Claude Code hook이 쓰는 canonical runtime
158
+ codex/ Codex 로컬 marketplace source
159
+ claude/ Claude Code 로컬 marketplace
160
+ projects/ goal 상태
161
+ config.json 사용자 설정 ("autoUpgrade")
162
+ update/ 자동 업그레이드 상태
163
+ $CODEX_HOME/plugins/cache/cairn/cairn/<version>/ Codex 플러그인 캐시 사본 (Codex를 선택했을 때만)
164
+ ```
165
+
166
+ - 호스트: `--hosts`는 `install`과 `upgrade`에서만 받으며 값은 `all` 또는 `codex`, `claude`, `antigravity`의 쉼표 목록입니다. 선택은 ownership manifest에 기록되고 `upgrade`, `doctor`, `uninstall`이 따릅니다. `cairn upgrade --hosts <list>`는 호스트를 추가하고 빠진 호스트를 제거합니다(빠지는 호스트의 관리 파일이 수정됐으면 거부). 대화형 prompt는 전체(기본), Claude Code만, Codex만, Antigravity만, 쉼표 목록을 제시하며 아직 아무것도 설치되지 않았을 때만 나옵니다.
167
+ - 이전: Cairn 0.6.0 이하에서 만든 설치(`$CODEX_HOME/plugins/cache/cairn` 아래 전체)는 `cairn upgrade` 한 번으로 `~/.cairn/install/`로 옮겨지고, Claude Code 플러그인도 새 marketplace 경로로 다시 등록됩니다. 이전이 실패하거나 중단되면 원래 상태로 복구하고, 수정된 관리 파일이 있으면 아무것도 바꾸지 않고 거부합니다. legacy 설치는 모든 호스트를 가진 채 이전되므로 전체가 아닌 `--hosts`는 거부되며, 다음 실행에서 고릅니다. 이전한 뒤에는 이 레이아웃을 아는 Cairn CLI로만 설치본을 다루고, 이전 중 열려 있던 세션은 다시 시작합니다.
168
+ - 유예: 버전이 바뀌는 업그레이드는 직전 canonical runtime과 Codex 캐시 사본을 3일 동안(종류별 최대 3개) 남겨, 업그레이드 전에 시작한 세션이 계속 동작하게 합니다. 기간이 지난 것은 다음 install이나 upgrade가 제거하고, uninstall은 모두 제거합니다. 새 버전과 같거나 높은 Codex 캐시 사본은 남기지 않습니다. Codex는 캐시에서 가장 높은 버전을 로드하기 때문입니다.
169
+ - 자동 업그레이드: 기본으로 켜져 있습니다. 24시간에 한 번 이하로(설치·업그레이드 직후 24시간은 제외) `SessionStart`가 분리 프로세스를 시작합니다. 이 프로세스는 npm에서 `cairn-ai` 최신 버전을 읽고, 그 정확한 버전을 `--ignore-scripts`로 `~/.cairn/update/stage/`에 설치해 검증한 뒤, 그 패키지의 `cairn-lifecycle.mjs upgrade --auto`를 실행합니다. major를 포함한 모든 새 버전을 적용하며 다운그레이드하지 않습니다. 다음 `SessionStart`는 결과를 한 줄로 한 번만 알립니다: `updated`, `failed`, `manual`(설치됐지만 Claude Code 플러그인 캐시에 `claude plugin update cairn@cairn`이 필요함). npm 조회·설치 실패는 알림 없이 backoff하고, 업그레이드 실패는 backoff하며 버전마다 한 번 알립니다. git 체크아웃에서 설치한 설치본(`origin: "checkout"`)과 소스 체크아웃 실행에서는 동작하지 않습니다.
170
+ - 끄기: `cairn auto-upgrade off`, `CAIRN_AUTO_UPGRADE=0`(`false`, `off`, `no`도 가능), 또는 `~/.cairn/config.json`의 `"autoUpgrade": false`. 읽을 수 없는 `config.json`도 자동 업그레이드를 끕니다. 상태와 마지막 실행 출력은 `~/.cairn/update/`(`state.json`, `notice.json`, `last-run.log`, `update.lock`, `stage/`)에 있습니다.
135
171
 
136
172
  ## Antigravity Compatibility
137
173
 
package/README.md CHANGED
@@ -86,13 +86,21 @@ 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`.
94
96
 
95
- 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.
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.
102
+
103
+ Runtime scripts, templates, commands, agents, and model guidance stay in the installed canonical runtime, `~/.cairn/install/runtime/<version>/`. 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
 
97
105
  ## Commands
98
106
 
@@ -115,17 +123,21 @@ cairn upgrade
115
123
  cairn doctor
116
124
  cairn uninstall
117
125
  cairn toolcheck
126
+ cairn auto-upgrade status
118
127
  ```
119
128
 
120
- - `cairn install`: transactionally installs the custom marketplace source, versioned Codex runtime cache, Cairn-owned config sections, Claude Code mirrors and plugin, and current Antigravity IDE/CLI skill surfaces.
121
- - `cairn upgrade`: replaces only ownership-manifest entries whose installed digests still match, with staged validation and reverse-order rollback on failure.
122
- - `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
- - `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.
129
+ - `cairn install [--hosts all|codex,claude,antigravity]`: transactionally installs the canonical runtime under `~/.cairn/install/` and, for the selected hosts, the Codex marketplace source, versioned Codex runtime cache, and Cairn-owned config sections, the Claude Code mirrors and plugin, and the current Antigravity IDE/CLI skill surfaces. Without `--hosts`, a first install at a terminal asks which hosts to use; non-interactive runs and CI install every host.
130
+ - `cairn upgrade [--hosts all|codex,claude,antigravity]`: replaces only ownership-manifest entries whose installed digests still match, with staged validation and reverse-order rollback on failure. It keeps the recorded hosts unless `--hosts` changes them, migrates an installation made by Cairn 0.6.0 or earlier, and refreshes a Claude Code plugin cache that still holds another version. When the installed version is newer than this CLI, `install` and `upgrade` refuse without changing anything; `--allow-downgrade` installs this CLI's version anyway.
131
+ - `cairn doctor`: prints `Hosts: <ids>` first, then validates the ownership manifest, managed digests, effective Codex features, actual installed/enabled/version plugin state (including `Claude plugin cache version`), and mirror/runtime locators of the selected hosts without repairing them. A legacy installation is reported with a hint to run `cairn upgrade`.
132
+ - `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 and retained runtimes, prunes empty managed scaffolds, preserves unmanaged targets and their parent directories, and rolls back pre-commit failures. It also removes `~/.cairn/update/` and keeps `~/.cairn/config.json` and `~/.cairn/projects/`. A legacy-layout installation is removed in place without migrating.
133
+ - `cairn auto-upgrade status|on|off|run`: `status` prints the setting, installed version, last check, and pending notice as JSON; `on` and `off` write `autoUpgrade` to `~/.cairn/config.json` and print the same report; `run` checks npm now, ignoring the daily interval and backoff, and prints the result. Exit 0 is success, 1 an execution error or a failed run, 2 a usage error.
124
134
  - `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/`.
135
+ - `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.
136
+ - `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.
137
+ - `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.
138
+ - `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.
139
+ - `cairn-memory`: explores domain knowledge, writes notes with a `Summary:` line, and keeps `MEMORY.md` indexed.
140
+ - `cairn-plan`: reuses related memory notes and at most 3 related completed plans, then creates a decision-complete plan under `docs/plan/`.
129
141
  - `cairn-work`: executes the next module task in the current `PLAN.md` with two verification gates.
130
142
  - `cairn-review`: reviews completed tasks against plan, memory, and evidence.
131
143
 
@@ -133,13 +145,37 @@ On every `UserPromptSubmit`, Cairn injects model-visible guidance that non-trivi
133
145
 
134
146
  For token-efficient execution, Cairn puts reasoning into a focused executable test contract—requirements, invariants, boundaries, and failure modes—before implementation. Implementation receives the failing contract and bounded file scope, then makes the minimum passing change. Tool exit codes and machine summaries decide success; successful output stays concise and only failures expand context. Verification climbs from focused tests to one final full check. With no explicit `--watch`, a Git workspace fingerprint covers tracked and non-ignored untracked files; ignored artifacts are excluded. Any ignored artifact needed by the claim must be named with an explicit `--watch <path>` (or an explicit containing directory). Before package verification, inspect lifecycle scripts and run normal `npm pack --dry-run` by default: content-producing or unknown scripts must never use `--ignore-scripts`; only absent or proven content-neutral scripts may use it while the full-check evidence remains fresh. Successful state mutations support `--quiet` so growing goal JSON does not consume the conversation budget.
135
147
 
136
- Install and upgrade keep the custom marketplace lifecycle; they do not invoke `codex plugin add`. Candidates are staged and validated before commit, every current managed destination and digest is recorded in an ownership manifest, and committed phases roll back in reverse order on failure. The separate pinned SHA-256 release 0.2.2 file-hash allowlist verifies the exact legacy file set only; it is not the current package file list and is not a cryptographic signature. An exact unmodified supported legacy installation can be adopted after release-integrity validation; modified or unknown artifacts are preserved and rejected. Cairn edits only its own TOML sections and never forces public feature or agent settings. The source plugin manifest stays validator-friendly; only the installed cache copy gets a `hooks` field. Lifecycle commands must run from the published/global package, not from the cached copy that they replace.
148
+ Install and upgrade keep the custom marketplace lifecycle; they do not invoke `codex plugin add`. Candidates are staged and validated before commit, every current managed destination and digest is recorded in an ownership manifest, and committed phases roll back in reverse order on failure. The separate pinned SHA-256 release 0.2.2 file-hash allowlist verifies the exact legacy file set only; it is not the current package file list and is not a cryptographic signature. An exact unmodified supported legacy installation can be adopted after release-integrity validation; modified or unknown artifacts are preserved and rejected. Cairn edits only its own TOML sections and never forces public feature or agent settings. The source plugin manifest stays validator-friendly; only the installed copies get a `hooks` field. Lifecycle commands must run from the published/global package, not from an installed copy under `~/.cairn/install/` or the Codex plugin cache that they replace.
137
149
 
138
- Clean uninstall removes the Cairn marketplace cache root only when every managed scaffold is empty, using empty-directory removal rather than recursive deletion. It does not delete the source repository, repository `MEMORY.md`/`PLAN.md`, user-home Cairn goal state, the global `cairn-ai` package, package-manager download caches, legacy backups, or legacy shared settings outside the current ownership manifest; those require a separate explicit cleanup decision.
150
+ Clean uninstall removes `~/.cairn/install/` and the Codex cache root `$CODEX_HOME/plugins/cache/cairn` only when every managed scaffold is empty, using empty-directory removal rather than recursive deletion. It does not delete the source repository, repository `MEMORY.md`/`PLAN.md`, user-home Cairn goal state, the global `cairn-ai` package, package-manager download caches, legacy backups, or legacy shared settings outside the current ownership manifest; those require a separate explicit cleanup decision.
139
151
 
140
152
  Codex uses `skills/` and `commands/`. Claude Code uses mirrored commands and agent definitions under `~/.claude/` plus a Claude Code plugin, `cairn@cairn`. Antigravity uses `.agents/workflows` and global skills mirrors.
141
153
 
142
- The Claude Code plugin is generated in a Cairn-owned local marketplace at `~/.codex/plugins/cache/cairn/claude` and carries the four Cairn skills and the SessionStart, UserPromptSubmit, PostToolUse, Stop, and SubagentStop hooks, which call the installed versioned runtime by absolute path. After the files commit, `cairn install`/`upgrade` registers it through `claude plugin marketplace add` and `claude plugin install cairn@cairn --scope user`, so it appears in the Claude Code terminal, desktop app, and IDE plugin lists from the next session. Registration is skipped with a manual command when the `claude` CLI is missing, and a different marketplace already named `cairn` is never touched. `cairn uninstall` unregisters only Cairn's own marketplace before removing files, and re-registers it if the uninstall rolls back. `cairn doctor` reports `Claude plugin files`, `Claude plugin registered`, and `Claude plugin enabled`.
154
+ The Claude Code plugin is generated in a Cairn-owned local marketplace at `~/.cairn/install/claude` and carries the four Cairn skills and the SessionStart, UserPromptSubmit, PostToolUse, Stop, and SubagentStop hooks, which call the canonical runtime by absolute path. After the files commit, `cairn install`/`upgrade` registers it through `claude plugin marketplace add` and `claude plugin install cairn@cairn --scope user`, so it appears in the Claude Code terminal, desktop app, and IDE plugin lists from the next session. Registration is skipped with a manual command when the `claude` CLI is missing, and a different marketplace already named `cairn` is never touched. `cairn uninstall` unregisters only Cairn's own marketplace before removing files, and re-registers it if the uninstall rolls back. When the Claude Code plugin cache holds a different version, `cairn upgrade` refreshes it with `claude plugin marketplace update cairn` and `claude plugin update cairn@cairn --scope user`; if the refresh fails, the upgrade stays installed, prints those commands to finish by hand, and exits 1. `cairn doctor` reports `Claude plugin files`, `Claude plugin registered`, `Claude plugin enabled`, and `Claude plugin cache version`.
155
+
156
+ ## Install Layout And Auto-Upgrade
157
+
158
+ Cairn keeps its installation under `CAIRN_HOME` (default `~/.cairn`). `CODEX_HOME`, `CLAUDE_HOME`, `ANTIGRAVITY_HOME`, `ANTIGRAVITY_CLI_HOME`, and `CODEX_CONFIG_PATH` still set the host paths independently.
159
+
160
+ ```text
161
+ ~/.cairn/
162
+ install/ lifecycle-managed files
163
+ lifecycle.json ownership manifest (schema 2: hosts, origin, retained runtimes)
164
+ lifecycle.lock, transaction.json, transactions/
165
+ runtime/<version>/ canonical runtime used by every runtime locator and the Claude Code hooks
166
+ codex/ Codex local marketplace source
167
+ claude/ Claude Code local marketplace
168
+ projects/ goal state
169
+ config.json user settings ("autoUpgrade")
170
+ update/ auto-upgrade state
171
+ $CODEX_HOME/plugins/cache/cairn/cairn/<version>/ Codex plugin cache copy (only when Codex is selected)
172
+ ```
173
+
174
+ - Hosts: `--hosts` takes `all` or a comma list of `codex`, `claude`, and `antigravity`, on `install` and `upgrade` only. The selection is recorded in the ownership manifest, and `upgrade`, `doctor`, and `uninstall` follow it; `cairn upgrade --hosts <list>` adds hosts and removes deselected ones (a modified artifact of a deselected host is refused). The interactive prompt offers all hosts (default), Claude Code only, Codex only, Antigravity only, or a comma list, and appears only when nothing is installed yet.
175
+ - Migration: an installation made by Cairn 0.6.0 or earlier (everything under `$CODEX_HOME/plugins/cache/cairn`) moves to `~/.cairn/install/` with one `cairn upgrade`, which also re-registers the Claude Code plugin from its new marketplace path. A failed or interrupted migration is restored, and modified managed files refuse the migration without changes. A legacy installation migrates with every host, so a narrower `--hosts` is refused until the next run. After migration, manage the installation only with a Cairn CLI that knows this layout, and restart sessions that were open during it.
176
+ - Retention: an upgrade that changes the version keeps the previous canonical runtime and Codex cache copy for 3 days (at most 3 of each) so sessions started before it keep working. The next install or upgrade removes expired ones, and uninstall removes all of them. A Codex cache copy at or above the new version is never kept, because Codex loads the highest cached version.
177
+ - Auto-upgrade: on by default. At most once every 24 hours (and not within 24 hours of an install or upgrade), `SessionStart` starts a detached process that reads the latest `cairn-ai` version from npm, installs that exact version into `~/.cairn/update/stage/` with `--ignore-scripts`, verifies the staged package, and runs its `cairn-lifecycle.mjs upgrade --auto`. Every newer release is applied, major versions included, and it never downgrades. The next `SessionStart` shows one line, once: `updated`, `failed`, or `manual` (installed, but the Claude Code plugin cache still needs `claude plugin update cairn@cairn`). npm lookup and install failures back off silently; a failed upgrade backs off and is announced once per version. It never runs for an installation from a git checkout (`origin: "checkout"`) or from a source checkout.
178
+ - Turning it off: `cairn auto-upgrade off`, `CAIRN_AUTO_UPGRADE=0` (also `false`, `off`, or `no`), or `"autoUpgrade": false` in `~/.cairn/config.json`. A `config.json` that cannot be read also turns it off. State and the last run's output live in `~/.cairn/update/` (`state.json`, `notice.json`, `last-run.log`, `update.lock`, `stage/`).
143
179
 
144
180
  ## Antigravity Compatibility
145
181
 
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
 
@@ -94,14 +102,19 @@ cairn upgrade
94
102
  cairn doctor
95
103
  cairn uninstall
96
104
  cairn toolcheck
105
+ cairn auto-upgrade status
97
106
  ```
98
107
 
99
- - `cairn install`: instala de forma transacional custom marketplace source, versioned runtime, secoes config do Cairn e mirrors atuais.
100
- - `cairn upgrade`: substitui apenas entradas intactas do ownership manifest apos staged validation e usa rollback em falhas.
101
- - `cairn doctor`: valida ownership digests, features efetivos do Codex, status real do plugin e runtime locators sem reparar.
102
- - `cairn uninstall`: remove apenas entradas gerenciadas intactas; alvos modified ou unmanaged sao preservados como conflict.
108
+ - `cairn install [--hosts all|codex,claude,antigravity]`: instala de forma transacional custom marketplace source, versioned runtime, secoes config do Cairn e mirrors atuais. O canonical runtime fica em `~/.cairn/install/` e o resto e instalado apenas para os hosts escolhidos. Sem `--hosts`, a primeira instalacao em um terminal pergunta os hosts; execucoes nao interativas e CI instalam todos.
109
+ - `cairn upgrade [--hosts all|codex,claude,antigravity]`: substitui apenas entradas intactas do ownership manifest apos staged validation e usa rollback em falhas. Mantem os hosts registrados, a menos que `--hosts` os altere, migra uma instalacao do Cairn 0.6.0 ou anterior e atualiza um Claude Code plugin cache que ainda tenha outra versao. Se a versao instalada for mais nova que esta CLI, `install` e `upgrade` recusam sem mudar nada; `--allow-downgrade` instala mesmo assim a versao desta CLI.
110
+ - `cairn doctor`: valida ownership digests, features efetivos do Codex, status real do plugin e runtime locators sem reparar. Imprime primeiro `Hosts: <ids>` e verifica apenas os hosts escolhidos (incluindo `Claude plugin cache version`). Uma instalacao legacy e relatada com a indicacao de migrar com `cairn upgrade`.
111
+ - `cairn uninstall`: primeiro compara cada entrada nao config do ownership manifest com seu installed digest e recusa todo o uninstall, sem mudar nada, se algum managed artifact foi modificado ou removido. Caso contrario, remove ou restaura as entradas gerenciadas e os retained runtimes, limpa os managed scaffolds vazios, preserva alvos unmanaged e seus diretorios pai e aplica rollback a falhas antes do commit. Tambem remove `~/.cairn/update/`, e mantem `~/.cairn/config.json` e `~/.cairn/projects/`. Uma instalacao com layout legacy e removida no lugar, sem migracao.
112
+ - `cairn auto-upgrade status|on|off|run`: `status` imprime em JSON a configuracao, a versao instalada, a ultima verificacao e o aviso pendente; `on`/`off` gravam `autoUpgrade` em `~/.cairn/config.json` e imprimem o mesmo relatorio; `run` consulta o npm agora, sem esperar o intervalo de 24 horas nem o backoff. Exit 0 e sucesso, 1 erro de execucao ou execucao com falha, 2 erro de uso.
103
113
  - `cairn toolcheck`: detecta repository stacks e verifica required tools; apenas um installer suportado e aprovado e executado, caso contrario `installer-unavailable`.
104
114
  - `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.
115
+ - `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.
116
+ - `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`.
117
+ - `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
118
  - `cairn-memory`: explora domain knowledge e atualiza `MEMORY.md`.
106
119
  - `cairn-plan`: cria um decision-complete plan em `docs/plan/`.
107
120
  - `cairn-work`: executa o proximo module task no `PLAN.md` atual com dois verification gates.
@@ -109,10 +122,35 @@ cairn toolcheck
109
122
 
110
123
  O custom marketplace lifecycle separa source e versioned runtime. Staged validation precede cada commit, o ownership manifest vincula todos os managed digests e uma falha aciona reverse-order rollback. Artifacts modified ou unmanaged sao preserved e relatados como conflict. O Cairn altera apenas suas TOML sections e nao forca feature/agent settings publicos.
111
124
 
112
- Clean uninstall remove o Cairn marketplace cache root somente quando todos os managed scaffold directories estao vazios; qualquer conteudo unmanaged e preservado. O source repository, repository `MEMORY.md`/`PLAN.md` e user-home Cairn goal state, o package global `cairn-ai`, package-manager caches e legacy backups/settings fora do ownership manifest atual nao sao removidos automaticamente.
125
+ Clean uninstall remove `~/.cairn/install/` e o Codex cache root `$CODEX_HOME/plugins/cache/cairn` somente quando todos os managed scaffold directories estao vazios; qualquer conteudo unmanaged e preservado. O source repository, repository `MEMORY.md`/`PLAN.md` e user-home Cairn goal state, o package global `cairn-ai`, package-manager caches e legacy backups/settings fora do ownership manifest atual nao sao removidos automaticamente.
113
126
 
114
127
  Codex usa `skills/` e `commands/`. Claude Code usa comandos espelhados e agent definitions em `.claude/`. Antigravity usa `.agents/workflows` e global skills mirrors.
115
128
 
129
+ ## Install Layout And Auto-Upgrade
130
+
131
+ O Cairn guarda a instalacao em `CAIRN_HOME` (padrao `~/.cairn`). Os caminhos de cada host continuam definidos separadamente por `CODEX_HOME`, `CLAUDE_HOME`, `ANTIGRAVITY_HOME`, `ANTIGRAVITY_CLI_HOME` e `CODEX_CONFIG_PATH`.
132
+
133
+ ```text
134
+ ~/.cairn/
135
+ install/ arquivos gerenciados pelo lifecycle
136
+ lifecycle.json ownership manifest (schema 2: hosts, origin, retained runtimes)
137
+ lifecycle.lock, transaction.json, transactions/
138
+ runtime/<version>/ canonical runtime usado por todos os runtime locators e pelos hooks do Claude Code
139
+ codex/ Codex local marketplace source
140
+ claude/ Claude Code local marketplace
141
+ projects/ goal state
142
+ config.json configuracoes do usuario ("autoUpgrade")
143
+ update/ estado do auto-upgrade
144
+ $CODEX_HOME/plugins/cache/cairn/cairn/<version>/ copia no Codex plugin cache (somente se Codex for escolhido)
145
+ ```
146
+
147
+ - Hosts: apenas `install` e `upgrade` aceitam `--hosts`, com `all` ou uma lista separada por virgulas de `codex`, `claude` e `antigravity`. A selecao fica no ownership manifest e `upgrade`, `doctor` e `uninstall` a seguem. Ela muda com `cairn upgrade --hosts <list>`; um arquivo gerenciado modificado de um host removido causa recusa. O prompt interativo (todos por padrao, apenas Claude Code, apenas Codex, apenas Antigravity ou uma lista) aparece somente quando nada esta instalado.
148
+ - Migracao: uma instalacao do Cairn 0.6.0 ou anterior (tudo em `$CODEX_HOME/plugins/cache/cairn`) passa para `~/.cairn/install/` com um unico `cairn upgrade`, que tambem registra de novo o plugin do Claude Code a partir do novo caminho do marketplace. Uma migracao com falha ou interrompida e restaurada, e arquivos gerenciados modificados a recusam sem mudancas. A instalacao legacy migra com todos os hosts; um `--hosts` parcial fica para a execucao seguinte. Depois, gerencie a instalacao apenas com um Cairn CLI que conheca este layout e reinicie as sessoes abertas durante a migracao.
149
+ - Retencao: um upgrade que muda a versao mantem o canonical runtime anterior e a copia do Codex cache por 3 dias (no maximo 3 de cada tipo) para que sessoes iniciadas antes continuem funcionando. O install ou upgrade seguinte remove os vencidos, e uninstall remove todos. Uma copia do Codex cache igual ou superior a nova versao nunca e mantida, porque o Codex carrega a versao mais alta do cache.
150
+ - Claude Code plugin cache: se ainda tiver outra versao, `cairn upgrade` o atualiza com `claude plugin marketplace update cairn` e `claude plugin update cairn@cairn --scope user`. Se falhar, a instalacao atualizada e mantida, os comandos para concluir manualmente sao impressos e a saida e exit 1.
151
+ - Auto-upgrade: ativado por padrao. No maximo uma vez a cada 24 horas (e nao nas 24 horas apos um install ou upgrade), `SessionStart` inicia um processo separado que le a versao mais recente de `cairn-ai` no npm, instala essa versao exata com `--ignore-scripts` em `~/.cairn/update/stage/`, verifica e executa o `cairn-lifecycle.mjs upgrade --auto` dela. Todas as versoes novas sao aplicadas, inclusive major, e nunca ha downgrade. O `SessionStart` seguinte mostra o resultado (`updated`, `failed` ou `manual`) em uma linha, uma unica vez. Nao funciona para instalacoes a partir de um git checkout (`origin: "checkout"`) nem ao executar de um source checkout.
152
+ - Desativar: `cairn auto-upgrade off`, `CAIRN_AUTO_UPGRADE=0` (ou `false`, `off`, `no`) ou `"autoUpgrade": false` em `~/.cairn/config.json`. Um `config.json` ilegivel tambem desativa. O estado e o log da ultima execucao ficam em `~/.cairn/update/`.
153
+
116
154
  ## Antigravity Compatibility
117
155
 
118
156
  Antigravity suporta Agent Skills e Workflows baseados em `SKILL.md` chamados como `/workflow-name`. Cairn instala estes paths para essa superficie.
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
 
@@ -94,14 +102,19 @@ cairn upgrade
94
102
  cairn doctor
95
103
  cairn uninstall
96
104
  cairn toolcheck
105
+ cairn auto-upgrade status
97
106
  ```
98
107
 
99
- - `cairn install`: 以事务方式安装 custom marketplace source、versioned runtime、Cairn-owned config sections 和当前 host mirrors。
100
- - `cairn upgrade`: staged validation 后只替换 ownership manifest 中未修改的 entry,失败时 rollback。
101
- - `cairn doctor`: 只读验证 ownership digests、effective Codex features、真实 plugin status 和 runtime locators。
102
- - `cairn uninstall`: 只删除未修改的 managed entry;modified 或 unmanaged target 会 preserve 并报告 conflict。
108
+ - `cairn install [--hosts all|codex,claude,antigravity]`: 以事务方式安装 custom marketplace source、versioned runtime、Cairn-owned config sections 和当前 host mirrors。 canonical runtime 位于 `~/.cairn/install/`,其余内容只为所选 host 安装。未提供 `--hosts` 时,在 terminal 中首次安装会询问 host,非交互运行和 CI 会安装所有 host。
109
+ - `cairn upgrade [--hosts all|codex,claude,antigravity]`: staged validation 后只替换 ownership manifest 中未修改的 entry,失败时 rollback。 除非用 `--hosts` 修改,否则沿用已记录的 hosts;会迁移 Cairn 0.6.0 及更早版本的安装,并更新仍为其他版本的 Claude Code plugin cache。 已安装版本比当前 CLI 更新时,`install` 和 `upgrade` 不做任何更改并拒绝;如仍要安装当前 CLI 的版本,加 `--allow-downgrade`。
110
+ - `cairn doctor`: 只读验证 ownership digests、effective Codex features、真实 plugin status 和 runtime locators。 第一行输出 `Hosts: <ids>`,只检查所选 host(包括 `Claude plugin cache version`)。发现 legacy 安装时提示运行 `cairn upgrade` 迁移。
111
+ - `cairn uninstall`: 先将 config 以外的所有 ownership manifest entry 与 installed digest 对照,只要有任何 managed artifact 被修改或删除,就不做任何更改并拒绝整个 uninstall。否则删除或恢复 managed entry 和 retained runtimes,清理空的 managed scaffold,preserve unmanaged target 及其父目录,并 rollback commit 前的失败。 同时删除 `~/.cairn/update/`,保留 `~/.cairn/config.json` 和 `~/.cairn/projects/`。legacy layout 的安装不经迁移直接原地删除。
112
+ - `cairn auto-upgrade status|on|off|run`: `status` 以 JSON 输出设置、已安装版本、上次检查时间和待显示的 notice;`on`/`off` 将 `autoUpgrade` 写入 `~/.cairn/config.json` 并输出同样的报告;`run` 忽略 24 小时周期和 backoff,立即检查 npm。exit 0 表示成功,1 表示执行错误或运行失败,2 表示用法错误。
103
113
  - `cairn toolcheck`: 检测 repository stacks 和 required tools;只执行已批准的 supported installer,否则返回 `installer-unavailable`。
104
114
  - `cairn cleanup --root <repo>`: 默认只读报告 legacy project-local `.cairn` residue。`--yes` 将 valid active state 迁移/协调到 user-home store,只删除 known state/lock/tool residue,保留 unknown files,并且仅在目录为空时清理目录。
115
+ - `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` 仍输出原有指引。
116
+ - `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。
117
+ - `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
118
  - `cairn-memory`: 探索 domain knowledge 并更新 `MEMORY.md`。
106
119
  - `cairn-plan`: 在 `docs/plan/` 下创建 decision-complete plan。
107
120
  - `cairn-work`: 执行当前 `PLAN.md` 中的下一个 module task,并收集两个 verification gates。
@@ -109,10 +122,35 @@ cairn toolcheck
109
122
 
110
123
  custom marketplace lifecycle 将 source 与 versioned runtime 分离。每次 commit 前执行 staged validation,ownership manifest 绑定全部 managed digests,失败时执行 reverse-order rollback。modified 或 unmanaged artifacts 会 preserve 并报告 conflict。Cairn 只修改自身 TOML sections,不强制 public feature/agent settings。
111
124
 
112
- Clean uninstall 仅在所有 managed scaffold directory 均为空时删除 Cairn marketplace cache root,并保留任何 unmanaged content。它不会自动删除 source repository、repository `MEMORY.md`/`PLAN.md`、user-home Cairn goal state、全局 `cairn-ai` package、package-manager cache,或当前 ownership manifest 之外的 legacy backup/settings。
125
+ Clean uninstall 仅在所有 managed scaffold directory 均为空时删除 `~/.cairn/install/` 和 Codex cache root `$CODEX_HOME/plugins/cache/cairn`,并保留任何 unmanaged content。它不会自动删除 source repository、repository `MEMORY.md`/`PLAN.md`、user-home Cairn goal state、全局 `cairn-ai` package、package-manager cache,或当前 ownership manifest 之外的 legacy backup/settings。
113
126
 
114
127
  Codex 使用 `skills/` 和 `commands/`。Claude Code 使用 `.claude/` 下的 mirrored commands 和 agent definitions。Antigravity 使用 `.agents/workflows` 和 global skills mirrors。
115
128
 
129
+ ## Install Layout And Auto-Upgrade
130
+
131
+ Cairn 将安装内容放在 `CAIRN_HOME`(默认 `~/.cairn`)下。各 host 的路径仍分别由 `CODEX_HOME`、`CLAUDE_HOME`、`ANTIGRAVITY_HOME`、`ANTIGRAVITY_CLI_HOME`、`CODEX_CONFIG_PATH` 决定。
132
+
133
+ ```text
134
+ ~/.cairn/
135
+ install/ lifecycle 管理的文件
136
+ lifecycle.json ownership manifest (schema 2: hosts, origin, retained runtimes)
137
+ lifecycle.lock, transaction.json, transactions/
138
+ runtime/<version>/ 所有 runtime locator 和 Claude Code hooks 使用的 canonical runtime
139
+ codex/ Codex local marketplace source
140
+ claude/ Claude Code local marketplace
141
+ projects/ goal state
142
+ config.json 用户设置 ("autoUpgrade")
143
+ update/ auto-upgrade 状态
144
+ $CODEX_HOME/plugins/cache/cairn/cairn/<version>/ Codex plugin cache copy (仅在选择 Codex 时)
145
+ ```
146
+
147
+ - Hosts: 只有 `install` 和 `upgrade` 接受 `--hosts`,值为 `all` 或 `codex`、`claude`、`antigravity` 的逗号列表。选择会记录在 ownership manifest 中,`upgrade`、`doctor`、`uninstall` 都遵循它。用 `cairn upgrade --hosts <list>` 修改;被移除 host 的 managed file 若已被修改则拒绝。交互式 prompt(全部(默认)、仅 Claude Code、仅 Codex、仅 Antigravity、逗号列表)只在尚未安装任何内容时出现。
148
+ - 迁移: Cairn 0.6.0 及更早版本的安装(`$CODEX_HOME/plugins/cache/cairn` 下的全部内容)只需一次 `cairn upgrade` 即迁移到 `~/.cairn/install/`,Claude Code plugin 也会用新的 marketplace 路径重新注册。迁移失败或中断时会恢复原状,存在被修改的 managed file 时不做任何改动并拒绝。legacy 安装以全部 host 迁移,因此非全部的 `--hosts` 需在下一次运行时指定。迁移后只用认识该 layout 的 Cairn CLI 管理,并重启迁移期间打开的 session。
149
+ - 保留期: 改变版本的 upgrade 会把上一个 canonical runtime 和 Codex cache copy 保留 3 天(每类最多 3 个),让 upgrade 前启动的 session 继续工作。过期的由下一次 install/upgrade 删除,uninstall 会全部删除。不低于新版本的 Codex cache copy 不会保留,因为 Codex 会加载 cache 中最高的版本。
150
+ - Claude Code plugin cache: 若仍为其他版本,`cairn upgrade` 会用 `claude plugin marketplace update cairn` 和 `claude plugin update cairn@cairn --scope user` 更新。更新失败时保留已升级的安装,输出手动完成的命令并以 exit 1 结束。
151
+ - Auto-upgrade: 默认开启。`SessionStart` 每 24 小时最多一次(install 或 upgrade 后 24 小时内不检查)启动一个 detached process:从 npm 读取最新的 `cairn-ai` 版本,以该确切版本加 `--ignore-scripts` 安装到 `~/.cairn/update/stage/` 并验证,然后运行该 package 的 `cairn-lifecycle.mjs upgrade --auto`。包括 major 在内的所有新版本都会应用,从不降级。下一个 `SessionStart` 用一行只提示一次结果(`updated`、`failed`、`manual`)。从 git checkout 安装(`origin: "checkout"`)或从 source checkout 运行时不会执行。
152
+ - 关闭: `cairn auto-upgrade off`、`CAIRN_AUTO_UPGRADE=0`(也可用 `false`、`off`、`no`),或在 `~/.cairn/config.json` 中设置 `"autoUpgrade": false`。无法读取的 `config.json` 也视为关闭。状态和上次运行日志位于 `~/.cairn/update/`。
153
+
116
154
  ## Antigravity Compatibility
117
155
 
118
156
  Antigravity 支持通过 `/workflow-name` 调用的 `SKILL.md` based Agent Skills and Workflows。Cairn 会为该 surface 安装这些 paths。
@@ -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
 
@@ -10,9 +10,12 @@ bunx cairn-ai@latest doctor
10
10
 
11
11
  The doctor validates the custom marketplace installation and ownership manifest without repairing it. Diagnostics are read-only; rollback is performed only by lifecycle transaction recovery.
12
12
 
13
+ The first line is `Hosts: <ids>`; only the selected hosts are checked and only their host CLIs are run. A legacy installation is reported with a hint to run `cairn upgrade`.
14
+
13
15
  Checks:
14
16
 
15
17
  - Source plugin manifest.
18
+ - Canonical runtime under `~/.cairn/install/runtime/<version>/`.
16
19
  - Codex cached installation.
17
20
  - Marketplace file.
18
21
  - Hook manifest link in the installed copy.
@@ -20,6 +23,6 @@ Checks:
20
23
  - `cairn@cairn` installed/enabled/version from the actual Codex CLI.
21
24
  - effective Codex plugin/hook/multi-agent feature state (reported, never forced).
22
25
  - hook trust state.
23
- - Claude Code commands and agents mirror files.
26
+ - Claude Code commands and agents mirror files, plugin files, and `cairn@cairn` registered/enabled state and `Claude plugin cache version`.
24
27
  - Antigravity IDE/CLI skills and workflows mirror files.
25
28
  - Installed runtime locators and their referenced scripts, templates, and model guidance.
@@ -6,19 +6,25 @@ Run from the published or global package, not from the installed cache copy:
6
6
 
7
7
  ```sh
8
8
  bunx cairn-ai@latest install
9
+ bunx cairn-ai@latest install --hosts claude
9
10
  ```
10
11
 
11
- The current custom marketplace lifecycle remains in use; this is not a migration to `codex plugin add`. Do not invoke lifecycle install/upgrade from the cached plugin root because that copy is the replacement target.
12
+ The current custom marketplace lifecycle remains in use; this is not a migration to `codex plugin add`. Do not invoke lifecycle install/upgrade from an installed copy (`~/.cairn/install/` or the Codex plugin cache) because that copy is the replacement target.
13
+
14
+ Hosts: `--hosts all` or a comma list of `codex`, `claude`, `antigravity` (also `--hosts=<list>`). Without it, a first install at a terminal asks once (all hosts is the default); non-interactive runs and CI install every host. The selection is recorded in the ownership manifest and followed by upgrade, doctor, and uninstall.
12
15
 
13
16
  Actions:
14
17
 
15
- - Stage and validate the Cairn installation, then transactionally commit the custom marketplace source and versioned runtime cache.
16
- - Add the `hooks/hooks.json` link to the installed manifest.
18
+ - Stage and validate the Cairn installation, then transactionally commit the canonical runtime `~/.cairn/install/runtime/<version>/` (`CAIRN_HOME` overrides `~/.cairn`) and, for Codex, the marketplace source `~/.cairn/install/codex/` and the versioned runtime cache `$CODEX_HOME/plugins/cache/cairn/cairn/<version>/`.
19
+ - Add the `hooks/hooks.json` link to the installed manifests.
17
20
  - Register only Cairn-owned marketplace, plugin, and hook trust sections in `~/.codex/config.toml`; do not rewrite public feature or agent settings.
18
21
  - Install `cairn-*` commands and agents mirror files for Claude Code.
19
- - Generate the Claude Code plugin `cairn@cairn` (four skills plus hooks that call the installed runtime) in the Cairn-owned local marketplace, then register it with `claude plugin marketplace add` and `claude plugin install cairn@cairn --scope user` after the files commit. Skip with a manual command when the `claude` CLI is missing, and never touch a different marketplace named `cairn`.
22
+ - Generate the Claude Code plugin `cairn@cairn` (four skills plus hooks that call the canonical runtime) in the Cairn-owned local marketplace `~/.cairn/install/claude/`, then register it with `claude plugin marketplace add` and `claude plugin install cairn@cairn --scope user` after the files commit. Skip with a manual command when the `claude` CLI is missing, and never touch a different marketplace named `cairn`.
20
23
  - Install `cairn-*` skills and workflows mirror files for Antigravity IDE/CLI.
21
24
  - Write runtime locators so all mirrors resolve scripts, templates, and model guidance from the installed plugin root.
22
- - Record every current managed destination and digest in the ownership manifest under the custom marketplace, and rollback committed phases in reverse order on failure.
25
+ - Install only the surfaces of the selected hosts; the canonical runtime is always installed.
26
+ - Record every current managed destination and digest, the host selection, and the install origin in the ownership manifest `~/.cairn/install/lifecycle.json`, and rollback committed phases in reverse order on failure.
27
+ - Automatic upgrades are on by default for a package install; see `cairn auto-upgrade status|on|off|run`.
23
28
  - Use the separate pinned SHA-256 release 0.2.2 file-hash allowlist only to validate that exact legacy file set; it is not the current package file list or a cryptographic signature.
24
29
  - Adopt an exact, unmodified supported legacy install only after release-integrity validation; preserve and reject modified or unknown artifacts.
30
+ - Refuse, changing nothing, when the installed version is newer than this CLI; `--allow-downgrade` installs this CLI's version anyway.
@@ -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.