cohorte 3.0.0 → 3.1.1

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 (69) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +16 -10
  3. package/bin/cli.js +2 -1
  4. package/core/agents/cohorte-profile-reader.md +21 -31
  5. package/core/agents/cohorte-release.md +6 -3
  6. package/core/agents/cohorte-review.md +31 -5
  7. package/core/agents/implementer.template.md +13 -5
  8. package/core/commands/cohorte-align-ds.md +1 -1
  9. package/core/commands/cohorte-audit.md +11 -4
  10. package/core/commands/cohorte-brainstorm.md +2 -2
  11. package/core/commands/cohorte-build.md +19 -12
  12. package/core/commands/cohorte-doctor.md +11 -9
  13. package/core/commands/cohorte-fix.md +3 -3
  14. package/core/commands/cohorte-fleet.md +2 -2
  15. package/core/commands/cohorte-init-pipeline.md +2 -2
  16. package/core/commands/cohorte-intake.md +4 -4
  17. package/core/commands/cohorte-patch.md +2 -2
  18. package/core/commands/cohorte-refactor.md +73 -8
  19. package/core/commands/cohorte-retro.md +3 -3
  20. package/core/commands/cohorte-revert.md +104 -0
  21. package/core/commands/cohorte-review.md +32 -17
  22. package/core/commands/cohorte-ship.md +26 -9
  23. package/core/commands/cohorte-spec.md +13 -4
  24. package/core/commands/cohorte-update-pipeline.md +12 -8
  25. package/core/commands/cohorte-verify.md +106 -0
  26. package/core/hooks/gate.py +326 -21
  27. package/core/templates/patch.template.md +11 -2
  28. package/core/templates/spec.template.md +23 -2
  29. package/core/templates/steps/init-pipeline/01-detect-stack.md +14 -5
  30. package/core/templates/steps/init-pipeline/02-interview-gaps.md +26 -3
  31. package/core/templates/steps/init-pipeline/03-draft-profile.md +2 -1
  32. package/core/templates/steps/init-pipeline/04-write-render.md +16 -12
  33. package/core/templates/steps/init-pipeline/05-report.md +1 -1
  34. package/core/workflows/audit.js +9 -4
  35. package/core/workflows/loop.js +15 -10
  36. package/core/workflows/refactor.js +116 -9
  37. package/core/workflows/review.js +24 -10
  38. package/lib/doctor.js +37 -3
  39. package/lib/install.js +68 -33
  40. package/lib/project.js +45 -8
  41. package/lib/render.js +3 -3
  42. package/lib/yaml.js +10 -1
  43. package/package.json +2 -2
  44. package/profile/PIPELINE.template.md +39 -1
  45. package/profile/SCHEMA.md +27 -746
  46. package/profile/cohorte.config.template.yaml +1 -1
  47. package/profile/schema/dead-agents.md +29 -0
  48. package/profile/schema/decisions.md +23 -0
  49. package/profile/schema/deferred.md +22 -0
  50. package/profile/schema/feature-diff.md +20 -0
  51. package/profile/schema/kanban.md +95 -0
  52. package/profile/schema/metrics.md +23 -0
  53. package/profile/schema/output-discipline.md +21 -0
  54. package/profile/schema/preflight.md +81 -0
  55. package/profile/schema/profile-block.md +103 -0
  56. package/profile/schema/project-kinds.md +89 -0
  57. package/profile/schema/readiness.md +17 -0
  58. package/profile/schema/reconcile.md +64 -0
  59. package/profile/schema/release-notes.md +29 -0
  60. package/profile/schema/rendering.md +48 -0
  61. package/profile/schema/retrieval.md +58 -0
  62. package/profile/schema/spec-status.md +79 -0
  63. package/profile/schema/specialization.md +41 -0
  64. package/profile/schema/verify.md +115 -0
  65. package/profile/schema/workflows.md +78 -0
  66. package/scripts/kanban-move.sh +45 -3
  67. package/scripts/new-feature.sh.template +7 -1
  68. package/scripts/remove-feature.sh.template +14 -5
  69. package/scripts/verify-run.sh +509 -0
@@ -3,7 +3,8 @@
3
3
  ### Phase 3 — Draft the profile (show, don't write yet)
4
4
 
5
5
  Assemble the full `PIPELINE.md` from `<core>/pipeline/PIPELINE.template.md`, filling the `yaml pipeline-profile`
6
- block and every prose section from Phases 1–2. **Keep it lean**: every stateless agent re-reads this
6
+ block and every prose section from Phases 1–2 — including `project.kind` as confirmed in Phase 2
7
+ (and the `design`/`rbac` defaults it implied). **Keep it lean**: every stateless agent re-reads this
7
8
  file on every dispatch, so its length is a per-dispatch token+latency tax — terse rule-shaped
8
9
  conventions, no narration, no facts derivable from the code. **Show the human the drafted
9
10
  `PIPELINE.md` in a fenced block and get a go-ahead** before writing.
@@ -6,8 +6,7 @@
6
6
  2. **Wire it into `<memory>`:** if `<memory>` exists, ensure it references the profile (add a line
7
7
  near the top: `> Project profile & pipeline facts: **@PIPELINE.md**`). If not, create a minimal
8
8
  `<memory>` with that reference + a one-paragraph project intro.
9
- 3. **Render one agent per surface** — for each surface, follow SCHEMA.md §"Rendering / reconciling a
10
- surface agent" (steps 2–3): render `<agents>/<agent>.md` from the installer's
9
+ 3. **Render one agent per surface** — for each surface, follow `<core>/pipeline/schema/rendering.md` (steps 2–3): render `<agents>/<agent>.md` from the installer's
11
10
  `pipeline/implementer.template.md`, substituting `<SURFACE_AGENT>`, `<SURFACE_LABEL>`, `<SURFACE_PATH>`,
12
11
  `<SURFACE_TOOLS>`, `<SURFACE_MODEL>`, `<PROJECT_NAME>`, `<SURFACE_CONVENTIONS>` (the surface's
13
12
  baked convention slice — §Shared + its `### Surface:` stanza + its §Testing lines from the
@@ -26,14 +25,15 @@
26
25
  permission prompts — including mid-workflow, where nobody is watching a prompt: the detected
27
26
  per-surface `test_cmd`/`lint_cmd`/`typecheck_cmd`/`build_cmd` **and their `*_quiet_cmd`
28
27
  variants** and repo-wide `commands.*` equivalents as `Bash(<cmd>:*)` rules, plus read-only git —
29
- `Bash(git status:*)`, `Bash(git diff:*)`, `Bash(git log:*)`, `Bash(git rev-parse:*)` — plus the
28
+ `Bash(git status:*)`, `Bash(git diff:*)`, `Bash(git log:*)`, `Bash(git rev-parse:*)`, plus
29
+ `Bash(git switch:*)` and `Bash(date:*)` (the refactor workflow cuts its branch and dates its spec) — plus the
30
30
  shipped pipeline scripts (`Bash(<core>/pipeline/scripts/:*)` — preflight, kanban-move;
31
31
  a prefix rule matches a command *starting* with that path, so a `bash <path>`
32
32
  invocation would need its own entry), and the
33
33
  retrieval provider's MCP tools when wired (e.g. `mcp__serena`). Never allowlist anything matching
34
34
  a `gate.ask`/`gate.deny` pattern. Mention the human can widen it later with
35
35
  `/fewer-permission-prompts`) + the PostToolUse formatter hook (detected formatter). Do **not**
36
- write the gate hook here — step 9 (`<sync>`) registers it.
36
+ write the gate hook here — step 8 (`<sync>`) registers it.
37
37
  Preserve any existing custom keys.
38
38
  6. **Wire the retrieval provider** (skip if `retrieval.provider: none`):
39
39
  - **serena:** if the `serena` CLI is missing, have the human install it (`uv tool install -p 3.13
@@ -42,35 +42,39 @@
42
42
  recommend the PATH fix (`uv tool update-shell`, or add `~/.local/bin` to the shell profile) for
43
43
  CLI use. Then register at **project scope** (committed `.mcp.json`, portable —
44
44
  `--project-from-cwd` resolves the project at server start) using the **PATH-proof launcher**
45
- from SCHEMA.md §Code retrieval (`sh -c 'exec "$(command -v serena || echo
45
+ from `<core>/pipeline/schema/retrieval.md` (`sh -c 'exec "$(command -v serena || echo
46
46
  "$HOME/.local/bin/serena")" start-mcp-server …'` — a bare `serena` entry dies with ENOENT when
47
47
  Claude Code was launched from an environment without `~/.local/bin` on PATH; Windows-native
48
48
  teams use the bare form + PATH instead). If `.mcp.json` already has a bare `serena` entry,
49
49
  upgrade it to the launcher form rather than skipping. Add `.serena/` to the repo's `.gitignore`
50
50
  (per-machine cache/config Serena creates on first launch). On a large repo, offer the one-off
51
- `serena project index`. Finish with the **health check** from SCHEMA.md §Code retrieval and
51
+ `serena project index`. Finish with the **health check** from `<core>/pipeline/schema/retrieval.md` and
52
52
  report each result — if the static checks pass but the server isn't connected in this session,
53
53
  say a session restart is needed; never report Serena wired on registration alone.
54
54
  - **graphify:** have the human install it (`uv tool install graphify` then `graphify install`),
55
55
  build the initial graph (`/graphify .`), and note it needs incremental rescans (`--update`) after
56
56
  big changes.
57
57
  - Either way the rendered agents already carry the provider's MCP tools in their `tools:` list
58
- (step 3 / SCHEMA §Rendering); remind the human the new MCP server appears after a session restart.
58
+ (step 3 / `<core>/pipeline/schema/rendering.md`); remind the human the new MCP server appears after a session restart.
59
59
  7. **Render the isolation scripts** (if `isolation.enabled`) from the installer's
60
60
  `pipeline/scripts/*.template` to this repo's `scripts/new-feature.sh` and `scripts/remove-feature.sh`,
61
61
  substituting the `__TOKENS__` (project
62
62
  slug, DB pattern, port bases, compose file, branch prefix, install/dev/migrate commands, per-surface
63
63
  env stanzas). `chmod +x` them. If isolation is disabled, skip and note features build in the main checkout.
64
- 8. **Wire the project: run `<sync>`** from the repo root (one Bash call) and show its output. It is
64
+ 8. **Wire the project: run `<sync>`** from the repo root (one Bash call) and show its output — always
65
+ AFTER step 1 wrote `PIPELINE.md`, never before: it parses the machine block into
66
+ `<state>/profile.json`, the file the agents read instead of `PIPELINE.md`. It is
65
67
  deterministic and idempotent: it copies the gate to `.claude/hooks/cohorte-gate.py`, registers it
66
- in `.claude/settings.json` (matchers `Bash|Task|Agent` and `Write|Edit|MultiEdit`, exactly once,
68
+ in `.claude/settings.json` (matchers `Bash|Task|Agent` and `Write|Edit|MultiEdit|NotebookEdit`, exactly once,
67
69
  every other hook kept), writes the `<state>/pipeline.json` pointer, adds
68
70
  `<state>/preflight.ok`, `<state>/pipeline-metrics.jsonl` and `specs/reports/` to `.gitignore`, and
69
- seeds `specs/_template.md`. If it exits non-zero (e.g. `.claude/settings.json` is not valid JSON),
71
+ seeds `specs/_template.md`, and writes `<state>/profile.json` (it says so if the block does not
72
+ parse — fix `PIPELINE.md` and re-run). If it exits non-zero (e.g. `.claude/settings.json` is not valid JSON),
70
73
  stop and show the error — never hand-write those files instead. If `<state>/preflight.ok` is
71
74
  already tracked: `git rm --cached <state>/preflight.ok`.
72
75
  9. **Tell the human what to commit:** `PIPELINE.md`, `<agents>/`, `<state>/gate-config.json`,
73
- `<state>/settings.json`, `.claude/hooks/cohorte-gate.py`, `<state>/pipeline.json`, `.gitignore`,
76
+ `<state>/settings.json`, `.claude/hooks/cohorte-gate.py`, `<state>/pipeline.json`,
77
+ `<state>/profile.json` (regenerated by every `<sync>` — commit it with each `PIPELINE.md` change), `.gitignore`,
74
78
  `<memory>`. A teammate who clones gets the gate immediately; they need `npm i -g cohorte &&
75
79
  cohorte install` only for the commands.
76
80
  10. **CI workflow** (if `vcs.host: github` and no existing workflow already runs the profile's
@@ -81,7 +85,7 @@
81
85
  sibling workflow does if one exists. `/cohorte-ship` watches these checks before the merge.
82
86
  11. **Design system:** if `design.enabled` with a snapshot dir, note that `/cohorte-align-ds` is active; else the
83
87
  `/cohorte-align-ds` command will no-op with a clear message.
84
- 12. **Kanban** (only if the human opted in at Phase 2): wire it per SCHEMA.md §Kanban, writing into the
88
+ 12. **Kanban** (only if the human opted in at Phase 2): wire it per `<core>/pipeline/schema/kanban.md`, writing into the
85
89
  **global** `<config>` (never into this repo — the board points at a
86
90
  personal vault). Create the file from `pipeline/cohorte.config.template.yaml` if absent; set
87
91
  `kanban.enabled: true` and `obsidian.vault_path` if it was empty. Add a `kanban.boards[<PIPELINE
@@ -7,5 +7,5 @@ tailored workflow line, e.g.
7
7
  `/cohorte-brainstorm → /cohorte-spec → (design) → /cohorte-build <id> → test → /cohorte-review → /cohorte-ship`. Tell the human to sanity-check
8
8
  `PIPELINE.md`, commit it, and run `/cohorte-brainstorm` to start a feature. Note that this was the one-time
9
9
  setup: from now on `/cohorte-update-pipeline` both refreshes the core AND reconciles the generated files
10
- (SCHEMA.md §Reconcile), and `/cohorte-build` auto-grows surfaces — re-running `/cohorte-init-pipeline` is only for deep
10
+ (`<core>/pipeline/schema/reconcile.md`), and `/cohorte-build` auto-grows surfaces — re-running `/cohorte-init-pipeline` is only for deep
11
11
  stack changes (package manager, contract mechanism, surface overhaul).
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // Invoke with args = {target: "<path or domain>"} (optional — default whole repo).
5
5
  //
6
- // Shape (SCHEMA.md §Workflows): profile via profile-reader (phase 0), the
6
+ // Shape (profile/schema/workflows.md): profile via profile-reader (phase 0), the
7
7
  // mechanical gates staged to disk by one haiku agent, then ONE auditor per
8
8
  // domain (each surface + `shared`) running concurrently — the runtime caps
9
9
  // concurrency at 20 (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS since 2026-08), extra
@@ -144,7 +144,7 @@ const BACKLOG = {
144
144
  // ── Phase 0 — profile ────────────────────────────────────────────────────────
145
145
  phase('Profile')
146
146
  const profile = unwrapProfile(await agent(
147
- 'Return this project\'s PIPELINE.md `yaml pipeline-profile` block as JSON, per your instructions.',
147
+ 'Return this project\'s profile (the `yaml pipeline-profile` block — `.claude/profile.json`, else PIPELINE.md) as JSON, per your instructions.',
148
148
  { agentType: 'cohorte-profile-reader', label: 'profile', schema: PROFILE, effort: 'low' },
149
149
  ))
150
150
  if (!profile || profile.error) {
@@ -180,7 +180,7 @@ const gates = await agent(
180
180
  { model: 'haiku', label: 'gates', schema: GATES, effort: 'low' },
181
181
  )
182
182
  // A dead gates agent is NOT "zero mechanical failures" — silence would read as the
183
- // cleanest possible inventory from a phase that never ran (SCHEMA.md §Dead agents).
183
+ // cleanest possible inventory from a phase that never ran (profile/schema/dead-agents.md).
184
184
  // The domain auditors still run (they read the staged gates file, which then simply
185
185
  // isn't there), but the run must say the mechanical sweep is uncovered.
186
186
  const gatesCovered = gates != null
@@ -238,6 +238,11 @@ const oldDomains = (existing && Array.isArray(existing.domains) ? existing.domai
238
238
  .filter(d => d && d.key).map(d => ({ key: String(d.key).trim(), lines: Array.isArray(d.lines) ? d.lines : [] }))
239
239
  const oldByKey = Object.fromEntries(oldDomains.map(d => [d.key, d.lines]))
240
240
  const isOpenDeferred = l => /^- \[ \]/.test(l) && /deferred:\S/.test(l)
241
+ // A ticked item cleared by a refactor round that has not shipped yet: its `refactor:<id>` spec is
242
+ // the review → PR route, and dropping the line would orphan it. Workflow scripts cannot read the
243
+ // spec's status, so the workflow keeps every such line; /cohorte-audit (conversational) prunes the
244
+ // ones whose spec is merged or gone.
245
+ const isRefactorTick = l => /^- \[x\]/.test(l) && /refactor:\S/.test(l)
241
246
  let total = 0
242
247
  let carried = 0
243
248
  const sections = []
@@ -250,7 +255,7 @@ for (const key of order) {
250
255
  total += items.length
251
256
  const lines = items.map(it => `- [ ] ${it.severity} · ${it.file}:${it.line} · ${it.kind} · ${it.fix}`)
252
257
  if (d.overflow) lines.push(`- [ ] (+${d.overflow} more beyond the cap — re-audit ${d.key} after this pass)`)
253
- const keep = (oldByKey[key] || []).filter(isOpenDeferred).filter(l => !lines.includes(l))
258
+ const keep = (oldByKey[key] || []).filter(l => isOpenDeferred(l) || isRefactorTick(l)).filter(l => !lines.includes(l))
254
259
  carried += keep.length
255
260
  sections.push({ key, lines: lines.concat(keep) })
256
261
  } else if (oldByKey[key] && oldByKey[key].length) {
@@ -33,8 +33,8 @@
33
33
  // review. scripts/test-workflows.mjs stubs workflow() to pin both paths.
34
34
  //
35
35
  // NOTE for unattended runs: workflow subagents run in acceptEdits whatever the session
36
- // mode, so hooks/gate.py is the only brake on file edits for the whole run (SCHEMA.md
37
- // §Preflight) — and in bypassPermissions its asks escalate to hard denies.
36
+ // mode, so hooks/gate.py is the only brake on file edits for the whole run
37
+ // (profile/schema/preflight.md) — and in bypassPermissions its asks escalate to hard denies.
38
38
 
39
39
  export const meta = {
40
40
  name: 'cohorte-loop',
@@ -88,7 +88,7 @@ const TERMINAL = new Set(['treading-water', 'max-rounds', 'contract-change'])
88
88
  // ── The reducer — the whole design, as one pure function ─────────────────────
89
89
  // Evaluated in this order; the first match wins, and the order is load-bearing:
90
90
  // 1. A child abort (preflight red, dead stager) carries no coverage claim — relay it.
91
- // 2. `unreviewed` BEFORE `blocking`: SCHEMA.md §Dead agents — a dead reviewer makes
91
+ // 2. `unreviewed` BEFORE `blocking`: profile/schema/dead-agents.md — a dead reviewer makes
92
92
  // blocking == 0 a statement about code nobody read. Checked the other way round,
93
93
  // the loop ships a feature whose reviewer crashed, silently and "successfully".
94
94
  // 3. blocking == 0 ⇒ ship. HIGH/MEDIUM/LOW never block (they route to the backlog)
@@ -247,7 +247,7 @@ const spent = () => {
247
247
  }
248
248
 
249
249
  // kanban-move.sh is optional infrastructure — every prompt that runs it defines <core>
250
- // and tolerates its absence, per SCHEMA.md §Kanban.
250
+ // and tolerates its absence, per profile/schema/kanban.md.
251
251
  const CORE_DEF = '(<core> = "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/cohorte" — ' +
252
252
  'script absent ⇒ skip the kanban step, the board is optional.)'
253
253
  const METRICS_PATH = '$(dirname "$(git rev-parse --git-common-dir)")/.claude/pipeline-metrics.jsonl'
@@ -255,7 +255,7 @@ const METRICS_PATH = '$(dirname "$(git rev-parse --git-common-dir)")/.claude/pip
255
255
  // ── Phase 0 — profile ────────────────────────────────────────────────────────
256
256
  phase('Profile')
257
257
  const profile = unwrapProfile(await agent(
258
- 'Return this project\'s PIPELINE.md `yaml pipeline-profile` block as JSON, per your instructions.',
258
+ 'Return this project\'s profile (the `yaml pipeline-profile` block — `.claude/profile.json`, else PIPELINE.md) as JSON, per your instructions.',
259
259
  { agentType: 'cohorte-profile-reader', label: 'profile', schema: PROFILE, effort: 'low' },
260
260
  ))
261
261
  if (!profile || profile.error) {
@@ -340,7 +340,12 @@ if (!['frozen', 'in-review', 'in-progress'].includes(status) && !blockedOk) {
340
340
  ? `spec is blocked by a finished loop run (reason: ${prevStop || 'unknown'}) — that stop needs a human: ` +
341
341
  `/cohorte-fix ${feature} for open Remediation items, or /cohorte-build ${feature} [--readiness-only] to re-enter; then re-run the loop`
342
342
  : `spec status is '${status || '(none)'}' — the loop needs frozen | in-review | in-progress ` +
343
- `(SCHEMA.md §Spec status). draft ⇒ /cohorte-spec; shipped/merged ⇒ done already`)
343
+ `(profile/schema/spec-status.md). draft ⇒ /cohorte-spec; shipped/merged ⇒ done already`)
344
+ }
345
+ // 1b. A `kind: refactor` spec (frozen by /cohorte-refactor §4) has no contract and enters at
346
+ // review — building it would dispatch implementers against a contract that does not exist.
347
+ if (facts.spec.kind === 'refactor') {
348
+ return abortPre(`specs/${feature}.md is a kind: refactor spec — it was built by /cohorte-refactor; run /cohorte-review ${feature} then /cohorte-ship ${feature}, never the loop`)
344
349
  }
345
350
  // 2. A fresh readiness verdict — the gate /cohorte-build §1.6 wrote. NOT-READY is the one
346
351
  // outcome more passes cannot fix; stale-or-absent means nobody has judged THIS spec.
@@ -410,7 +415,7 @@ const dispatchPrompt = j =>
410
415
  'Readiness gaps for YOUR surface (§1.6 RESERVATIONS — the spec is silent here: implement the stated ' +
411
416
  `assumption and flag what you assumed in your handoff): ${j.gaps}.`
412
417
 
413
- // Dispatch + roll call, SCHEMA.md §Dead agents: parallel fan-out, then each silent
418
+ // Dispatch + roll call, profile/schema/dead-agents.md: parallel fan-out, then each silent
414
419
  // surface retried ONCE, alone, byte-identical. Never a surface that answered.
415
420
  const dispatchSurfaces = async (jobs, phaseTitle) => {
416
421
  const tag = phaseTitle === 'Build' ? 'build' : 'fix'
@@ -470,7 +475,7 @@ const writeState = async ({ label, phaseName, outcome, reason, status: st, kanba
470
475
  }
471
476
 
472
477
  // Close the run: final loop.json + status + kanban, then the return object. Status
473
- // doctrine (SCHEMA.md §Spec status): `blocked` = a round gave up, reason named in
478
+ // doctrine (profile/schema/spec-status.md): `blocked` = a round gave up, reason named in
474
479
  // loop.json; `in-review` = zero blocking, awaiting /cohorte-ship; precondition aborts
475
480
  // never stamped anything, so they change nothing here either. A RESUMABLE abort leaves
476
481
  // loop.json without `outcome` (phase kept, reason set), so the next invocation resumes at
@@ -519,7 +524,7 @@ if (fresh(facts.build) && !(facts.build.dead || []).length) {
519
524
  const built = await dispatchSurfaces(jobs, 'Build')
520
525
  const dead = built.filter(b => b.handoff == null).map(b => b.key)
521
526
  // Write build.json + the metrics line EVEN WHEN a surface died — an incomplete batch
522
- // is exactly the batch worth recording (SCHEMA.md §Dead agents).
527
+ // is exactly the batch worth recording (profile/schema/dead-agents.md).
523
528
  await writeState({
524
529
  label: 'state:built', phaseName: dead.length ? 'build' : 'review',
525
530
  metrics: {
@@ -653,7 +658,7 @@ while (true) {
653
658
  const fixed = await dispatchSurfaces(fixJobs, 'Fix')
654
659
  const fixDead = fixed.filter(f => f.handoff == null).map(f => f.key)
655
660
  // The metrics line is written EVEN WHEN a surface died — an incomplete batch is
656
- // exactly the batch worth recording (SCHEMA.md §Dead agents), so it lands before
661
+ // exactly the batch worth recording (profile/schema/dead-agents.md), so it lands before
657
662
  // the dead-implementers abort, with the dead surfaces named.
658
663
  await writeState({ label: `state:fixed-${round}`, phaseName: 'review', metrics: {
659
664
  phase: 'fix', tokens: Math.max(0, spent() - mark),
@@ -5,11 +5,13 @@
5
5
  // cheaper through the conversational /cohorte-refactor — this script skips it and says
6
6
  // so. Invoke with args = {domains: ["backend", …]} or {domains: "all"}.
7
7
  //
8
- // Shape (SCHEMA.md §Workflows): profile via profile-reader (phase 0), the open
8
+ // Shape (profile/schema/workflows.md): profile via profile-reader (phase 0), the open
9
9
  // backlog read once, the `shared` domain (contract package — every slice
10
10
  // imports it) refactored FIRST and alone, then the other domains' surface
11
11
  // implementers in parallel (their trees are disjoint by construction), each
12
- // verified per-domain with one bounded retry round, and the backlog ticked.
12
+ // verified per-domain with one bounded retry round, then — gates green and ≥ 1 item
13
+ // cleared — the round frozen as ONE `kind: refactor` spec (the route to /cohorte-review →
14
+ // /cohorte-ship, which ships specs, not backlogs) and the backlog ticked with its id.
13
15
 
14
16
  export const meta = {
15
17
  name: 'cohorte-refactor',
@@ -21,7 +23,8 @@ export const meta = {
21
23
  { title: 'Shared', detail: 'refactor the contract package first, alone' },
22
24
  { title: 'Refactor', detail: 'one surface implementer per domain, parallel' },
23
25
  { title: 'Verify', detail: 'per-domain gates + item check, one retry round', model: 'haiku' },
24
- { title: 'Tick', detail: 'check cleared items off specs/refactor-backlog.md', model: 'haiku' },
26
+ { title: 'Spec', detail: 'freeze the round as a kind: refactor spec for review → ship', model: 'haiku' },
27
+ { title: 'Tick', detail: 'check cleared items off specs/refactor-backlog.md (· refactor:<id>)', model: 'haiku' },
25
28
  ],
26
29
  }
27
30
 
@@ -113,6 +116,18 @@ const OPEN = {
113
116
  },
114
117
  }
115
118
 
119
+ // The spec writer settles the id (the script has no clock — Date is unavailable in a
120
+ // workflow) and returns it; anything not shaped like a refactor id counts as a dead writer.
121
+ const SPEC = {
122
+ type: 'object', required: ['id', 'branch'], additionalProperties: false,
123
+ properties: {
124
+ id: { type: 'string', description: 'refactor-<domains>-<YYYY-MM-DD>[-n], the spec file name without .md' },
125
+ branch: { type: 'string', description: 'the branch checked out after step 3' },
126
+ kanban: { type: 'string', description: 'the line kanban-move.sh printed' },
127
+ },
128
+ }
129
+ const SPEC_ID = /^refactor-[a-z0-9][a-z0-9-]*$/
130
+
116
131
  const VERIFY = {
117
132
  type: 'object', required: ['cleared', 'remaining', 'gatesGreen'], additionalProperties: false,
118
133
  properties: {
@@ -126,7 +141,7 @@ const VERIFY = {
126
141
  // ── Phase 0 — profile ────────────────────────────────────────────────────────
127
142
  phase('Profile')
128
143
  const profile = unwrapProfile(await agent(
129
- 'Return this project\'s PIPELINE.md `yaml pipeline-profile` block as JSON, per your instructions.',
144
+ 'Return this project\'s profile (the `yaml pipeline-profile` block — `.claude/profile.json`, else PIPELINE.md) as JSON, per your instructions.',
130
145
  { agentType: 'cohorte-profile-reader', label: 'profile', schema: PROFILE, effort: 'low' },
131
146
  ))
132
147
  if (!profile || profile.error) {
@@ -228,6 +243,9 @@ const verifyDomain = async (d, implHandoff) => {
228
243
  v = v2
229
244
  ? { ...v2, cleared: [...new Set(cleared1.concat(v2.cleared || []))] }
230
245
  : { cleared: cleared1, remaining: retryItems, gatesGreen: false, failures: 'verifier died on the retry round' }
246
+ // The retry's verifier is asked the same question with no gates either — its
247
+ // gatesGreen is no more evidence than round 1's was.
248
+ if (noGates) v = { ...v, gatesGreen: false, failures: 'no gate commands declared for this domain — gates unverified' }
231
249
  }
232
250
  return { key: d.key, ...(v || { cleared: [], remaining: d.items, gatesGreen: false, failures: 'verifier died' }) }
233
251
  }
@@ -260,13 +278,94 @@ const restResults = await pipeline(
260
278
  )
261
279
  results.push(...restResults.filter(Boolean))
262
280
 
263
- // ── Phase 5 — tick the cleared items ─────────────────────────────────────────
264
- phase('Tick')
281
+ // ── Phase 5 — freeze the round as a `kind: refactor` spec ────────────────────
282
+ // Without it the round is code in the working tree with no route to a PR. ONE spec for the
283
+ // whole round: review's diff, the freshness digest and the release commit all cover the
284
+ // whole tree, so a spec per domain would each claim the others' code. Red gates ⇒ no spec
285
+ // (review's preflight would abort it anyway) — finish the round first.
265
286
  const clearedAll = results.flatMap(r => r.cleared)
287
+ const remainingAll = results.flatMap(r => r.remaining)
288
+ const gatesAllGreen = results.length > 0 && results.every(r => r.gatesGreen)
289
+ const clearedDomains = results.filter(r => r.cleared.length)
290
+ // Surface keys are free text (`web_checkout`, `API`); an id is a file name and a branch,
291
+ // and SPEC_ID below rejects anything else — so normalize here, not in the writer.
292
+ const idPart = k => String(k).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'domain'
293
+ const slug = clearedDomains.length > 3 ? 'all' : clearedDomains.map(r => idPart(r.key)).join('-')
294
+ const prefix = (profile.vcs && profile.vcs.feature_branch_prefix) || 'feature/'
295
+ const bare = l => String(l).replace(/^- \[[ x]\] /, '- ')
296
+ const specTitle = `Refactor ${slug} — ${clearedAll.length} backlog item(s)`
297
+ const specText = [
298
+ '---',
299
+ 'feature_id: <ID>',
300
+ 'kind: refactor # behaviour-preserving backlog pass — no contract; commit as refactor(<scope>)',
301
+ `title: ${specTitle}`,
302
+ 'status: frozen',
303
+ `branch: ${prefix}<ID>`,
304
+ 'created: <DATE>',
305
+ 'reviewed_base:',
306
+ 'reviewed_digest:',
307
+ '---',
308
+ '',
309
+ `# ${specTitle}`,
310
+ '',
311
+ '## 1. Goal',
312
+ '',
313
+ `Clear ${clearedAll.length} \`specs/refactor-backlog.md\` item(s) on ${clearedDomains.map(r => r.key).join(', ')} with no change of public behaviour.`,
314
+ '',
315
+ '## 2. Scope',
316
+ '',
317
+ '**In:** the §6 items, verbatim. **Out:** any behaviour change; the items §7 lists.',
318
+ '',
319
+ '## 6. Surface tasks',
320
+ ...clearedDomains.flatMap(r => ['', `### ${r.key}`, '', ...r.cleared.map(bare)]),
321
+ '',
322
+ '## 7. Out of scope',
323
+ '',
324
+ ...(remainingAll.length ? remainingAll.map(l => `${bare(l)} (still open in the backlog)`) : ['none']),
325
+ '',
326
+ '## 9. Acceptance criteria / DoD',
327
+ '',
328
+ '- [ ] Public behaviour preserved — no exported signature, route, response shape, CLI flag or persisted format changed (unless an item marks it a bug)',
329
+ '- [ ] Each §6 item cleared at its file:line',
330
+ '- [ ] All tests green — behaviour pinned by tests added first; no existing test loosened',
331
+ '- [ ] `PIPELINE.md` commands.lint · typecheck · test green',
332
+ "- [ ] Nothing outside §6's surfaces changed",
333
+ '',
334
+ '## Remediation',
335
+ '',
336
+ ].join('\n')
337
+
338
+ let spec = null
339
+ const wantSpec = clearedAll.length > 0 && gatesAllGreen
340
+ if (wantSpec) {
341
+ phase('Spec')
342
+ const w = await agent(
343
+ 'Freeze this cohorte refactor round as a spec (mechanical — no judgment). ' +
344
+ `0. ONE open refactor spec per branch: if \`git rev-parse --abbrev-ref HEAD\` is ${prefix}refactor-<x> and ` +
345
+ 'specs/refactor-<x>.md exists with `status:` frozen or in-review, then ID = refactor-<x>: append the §6 item ' +
346
+ "lines below under their `### <domain>` headings there (add a heading if missing), skip to step 4. " +
347
+ `1. Run \`date +%F\` ⇒ DATE; ID = refactor-${slug}-DATE. If specs/ID.md exists and its \`status:\` is ` +
348
+ 'shipped/merged/abandoned, suffix -2, -3… until the name is free. If it exists UNSHIPPED (frozen/in-review), ' +
349
+ "do not overwrite it: append this round's §6 item lines under their `### <domain>` headings there and skip step 2. " +
350
+ '2. Write specs/ID.md with EXACTLY the content below, every <ID> and <DATE> substituted. ' +
351
+ `3. \`git rev-parse --abbrev-ref HEAD\`: on ${base} ⇒ \`git switch -c ${prefix}ID\` (uncommitted work carries over); ` +
352
+ `already on ${prefix}ID ⇒ keep it; any other branch ⇒ leave it and report it. ` +
353
+ `4. \`<core>/pipeline/scripts/kanban-move.sh auto ID ready --title "[refactor] ${slug}"\` ` +
354
+ '(<core> = "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/cohorte"). ' +
355
+ 'Return id (ID), branch (checked out now) and kanban (the line the script printed).\n' +
356
+ `<<<SPEC\n${specText}SPEC`,
357
+ { model: 'haiku', label: 'write-spec', schema: SPEC, effort: 'low' },
358
+ )
359
+ spec = w && typeof w === 'object' && SPEC_ID.test(String(w.id || '')) ? w : null
360
+ }
361
+
362
+ // ── Phase 6 — tick the cleared items ─────────────────────────────────────────
363
+ phase('Tick')
266
364
  let tickedOk = true
267
365
  if (clearedAll.length) {
268
366
  const ticked = await agent(
269
367
  'In specs/refactor-backlog.md flip EXACTLY these open `- [ ]` item lines to `- [x]` (match verbatim, ' +
368
+ (spec ? `append \` · refactor:${spec.id}\` to each flipped line, ` : '') +
270
369
  'leave every other line untouched), then return the single word done:\n' + clearedAll.join('\n'),
271
370
  { model: 'haiku', label: 'tick-backlog', effort: 'low' },
272
371
  )
@@ -275,6 +374,7 @@ if (clearedAll.length) {
275
374
  tickedOk = ticked != null && /done/i.test(String(ticked))
276
375
  }
277
376
 
377
+ const branchOk = spec && spec.branch === `${prefix}${spec.id}`
278
378
  return {
279
379
  domains: Object.fromEntries(results.map(r => [r.key, {
280
380
  cleared: r.cleared.length, remaining: r.remaining.length, gatesGreen: r.gatesGreen,
@@ -282,10 +382,17 @@ return {
282
382
  skippedSmall: Object.fromEntries(small.map(d => [d.key, d.items.length])),
283
383
  stillOpen: results.flatMap(r => r.remaining.map(line => `[${r.key}] ${line}`)).slice(0, 15),
284
384
  backlogTicked: tickedOk,
385
+ // Only a writer that came back with a well-formed id has its spec claimed.
386
+ refactorSpec: spec ? `specs/${spec.id}.md` : null,
285
387
  next: !tickedOk
286
388
  ? `${clearedAll.length} item(s) were cleared in code but NOT ticked off specs/refactor-backlog.md ` +
287
389
  '(the ticking agent died) — tick them by hand, or the next /cohorte-refactor re-dispatches finished work'
288
- : results.some(r => r.remaining.length || !r.gatesGreen)
289
- ? 'items remain — finish them with the conversational /cohorte-refactor <domain>'
290
- : 'all dispatched domains clean — optionally close with one final /cohorte-audit',
390
+ : wantSpec && !spec
391
+ ? `the refactor spec was NOT written (the spec writer died) — the ${clearedAll.length} cleared item(s) have no ` +
392
+ 'route to a PR: write it per /cohorte-refactor §4, then /cohorte-review <id> → /cohorte-ship <id>'
393
+ : spec
394
+ ? `/cohorte-review ${spec.id} → /cohorte-ship ${spec.id}` +
395
+ (branchOk ? '' : ` — but the checked-out branch is ${spec.branch || 'unknown'}, not ${prefix}${spec.id}: /cohorte-ship refuses it, switch first`) +
396
+ (remainingAll.length ? ` (${remainingAll.length} item(s) still open, listed in its §7 — /cohorte-refactor <domain> appends them to this spec first, or ship without them)` : '')
397
+ : 'items remain — finish them with the conversational /cohorte-refactor <domain> (gates must be green before the round gets a spec)',
291
398
  }
@@ -4,7 +4,7 @@
4
4
  // Invoke with args = {feature: "<feature_id>"} (or the bare feature id string).
5
5
  // Requires Claude Code >= 2.1.154 with workflows enabled — /cohorte-doctor reports this.
6
6
  //
7
- // Shape (SCHEMA.md §Workflows): phase 0 reads the profile through the
7
+ // Shape (profile/schema/workflows.md): phase 0 reads the profile through the
8
8
  // profile-reader agent (scripts have no filesystem or shell), the deterministic
9
9
  // preflight aborts while red (zero reviewers spawned), the diff is staged ONCE
10
10
  // per touched surface, one reviewer runs per surface in parallel, an adversarial
@@ -44,7 +44,7 @@ const ARGS = (() => {
44
44
  })()
45
45
  // Approximate cost of this run from the runtime's own output-token counter — the one
46
46
  // figure the conversational path cannot record (a lead cannot read a subagent's token
47
- // count; SCHEMA.md §Measuring cost). Sampled at start, delta stamped into the metrics line.
47
+ // count; profile/schema/metrics.md). Sampled at start, delta stamped into the metrics line.
48
48
  const spentNow = () => {
49
49
  try {
50
50
  const v = (budget && typeof budget.spent === 'function') ? budget.spent() : 0
@@ -183,7 +183,7 @@ const VERDICT = {
183
183
  // ── Phase 0 — profile ────────────────────────────────────────────────────────
184
184
  phase('Profile')
185
185
  const profile = unwrapProfile(await agent(
186
- 'Return this project\'s PIPELINE.md `yaml pipeline-profile` block as JSON, per your instructions.',
186
+ 'Return this project\'s profile (the `yaml pipeline-profile` block — `.claude/profile.json`, else PIPELINE.md) as JSON, per your instructions.',
187
187
  { agentType: 'cohorte-profile-reader', label: 'profile', schema: PROFILE, effort: 'low' },
188
188
  ))
189
189
  if (!profile || profile.error) {
@@ -199,16 +199,28 @@ if (!surfaces.length) {
199
199
  return { verdict: 'ABORTED', aborted: 'profile', reason: 'profile has no surfaces — nothing would be reviewed. the `yaml pipeline-profile` block in PIPELINE.md is empty or unparseable, or the profile-reader mis-returned; run /cohorte-doctor' }
200
200
  }
201
201
  const quiet = (q, full) => (q && !String(q).startsWith('<') ? q : full ? `${full} 2>&1 | tail -40` : '')
202
+ // commands.security (profile/schema/preflight.md): dependency audits and a secret scan of the
203
+ // feature's own diff, run AFTER typecheck/lint/tests by the same script, into the same report.
204
+ // A no-op marker opens their section so a reviewer (no Bash) can Grep for it and Read from there.
205
+ const SECURITY_MARKER = ': cohorte-security-scans'
206
+ const security = (Array.isArray(cmds.security) ? cmds.security : [cmds.security])
207
+ .filter(c => typeof c === 'string' && c.trim() && !c.trim().startsWith('<'))
202
208
  const checks = [cmds.typecheck, quiet(cmds.lint_quiet, cmds.lint), quiet(cmds.test_quiet, cmds.test)]
203
209
  .filter(c => c && !String(c).startsWith('<'))
210
+ .concat(security.length ? [SECURITY_MARKER, ...security] : [])
211
+ // Each check is one argument of the preflight call. Double quotes would let the CALLING shell
212
+ // expand a `$VAR` meant for the check's own `sh -c` (the secret-scan recipe sets and reads one),
213
+ // so a command with shell syntax in it is single-quoted instead.
214
+ const shq = c => /[$`\\]/.test(c) ? `'${String(c).replace(/'/g, "'\\''")}'` : JSON.stringify(c)
215
+ const preflightReport = `specs/reports/${feature}.preflight.txt`
204
216
 
205
217
  // ── Phase 1 — deterministic preflight (abort while red, zero reviewers) ─────
206
218
  phase('Preflight')
207
219
  const pre = await agent(
208
220
  `Run the cohorte deterministic pre-flight for feature ${feature} in ONE Bash call, starting it with ` +
209
221
  '`date +%s` (return that number as `epoch` — the run\'s wall-clock origin for the metrics line):\n' +
210
- `<core>/pipeline/scripts/preflight.sh specs/reports/${feature}.preflight.txt ` +
211
- checks.map(c => JSON.stringify(c)).join(' ') + '\n' +
222
+ `<core>/pipeline/scripts/preflight.sh ${preflightReport} ` +
223
+ checks.map(shq).join(' ') + '\n' +
212
224
  '(<core> = "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/cohorte". ' +
213
225
  'Script absent: run the quoted commands yourself, each appended to the same report file, stopping at the first failure.) ' +
214
226
  'Return pass=true only on a fully green run. On failure set pass=false, put the raw last 40 lines of the report ' +
@@ -221,7 +233,8 @@ const pre = await agent(
221
233
  if (!pre || !pre.pass) {
222
234
  return {
223
235
  verdict: 'ABORTED', aborted: 'preflight',
224
- reason: 'preflight red — fix the mechanical failures (or run /cohorte-fix) before any review; no reviewer was spawned',
236
+ reason: 'preflight red — fix the mechanical failures (or run /cohorte-fix) before any review; no reviewer was spawned' +
237
+ (security.length ? ' (commands.security counts: a dependency advisory at its threshold, or a secret in the feature diff, is red too)' : ''),
225
238
  failures: (pre && pre.tail) || 'preflight agent returned nothing',
226
239
  }
227
240
  }
@@ -229,7 +242,7 @@ if (!pre || !pre.pass) {
229
242
  // ── Phase 2 — stage the diff once ────────────────────────────────────────────
230
243
  phase('Stage')
231
244
  const surfaceList = surfaces.map(s => `${s.key} → ${s.path}`).join(' · ') || '(none declared)'
232
- // Every diff goes through feature-diff.sh (SCHEMA.md §Feature diff): a throwaway index so
245
+ // Every diff goes through feature-diff.sh (profile/schema/feature-diff.md): a throwaway index so
233
246
  // UNTRACKED files are reviewed (feature work is uncommitted until ship — a bare `git diff`
234
247
  // dropped every new module, and an adds-only feature staged an empty diff that scored SHIP),
235
248
  // against the MERGE-BASE with the default branch (its tip blamed the feature for every file
@@ -293,8 +306,9 @@ const reviewPrompt = s =>
293
306
  'one line each, no code excerpts). Put anything real but OUT of this feature\'s scope in `deferred` ' +
294
307
  '(max 10, each with its out-of-scope reason) per your §Deferred rules — never in `findings`. — Variable slots: ' +
295
308
  `feature ${feature} · scope: the ${s.key} surface only · spec: specs/${feature}.md · ` +
296
- `staged diff: ${s.diff} · changed files: ${s.files.join(', ')}`
297
- // SCHEMA.md §Dead agents, the same rule as the build: a silent reviewer is retried ONCE,
309
+ `staged diff: ${s.diff} · changed files: ${s.files.join(', ')}` +
310
+ (security.length ? ` · preflight report: ${preflightReport} (security section from the line \`$ ${SECURITY_MARKER}\`)` : '')
311
+ // profile/schema/dead-agents.md, the same rule as the build: a silent reviewer is retried ONCE,
298
312
  // byte-identical (the staged diff is already on disk — the retry costs one agent); only a
299
313
  // surface silent twice is `unreviewed`.
300
314
  const reviewOnce = (s, label) =>
@@ -426,7 +440,7 @@ const staging = await agent(
426
440
  `${verdictJson}\n` +
427
441
  // Per-surface verdicts (not the merged one stamped on every row — one BLOCK used to
428
442
  // mark ALL surfaces failed), and dead reviewers logged as "dead"
429
- // per SCHEMA.md §Dead agents — an incomplete batch is the batch worth recording.
443
+ // per profile/schema/dead-agents.md — an incomplete batch is the batch worth recording.
430
444
  `3. Append one line to $(dirname "$(git rev-parse --git-common-dir)")/.claude/pipeline-metrics.jsonl: ` +
431
445
  // seconds: the clock lives in Bash (scripts have none) — elapsed since the preflight's
432
446
  // `date +%s`. No epoch came back ⇒ the field is OMITTED, never a made-up 0.
package/lib/doctor.js CHANGED
@@ -8,7 +8,7 @@
8
8
  const fs = require('fs');
9
9
  const path = require('path');
10
10
  const { spawnSync } = require('child_process');
11
- const { parseProfileBlock } = require('./yaml');
11
+ const { parseProfileBlock, profileJsonText } = require('./yaml');
12
12
  const { versions } = require('./versions');
13
13
 
14
14
  // Shipped (non-surface) agent names. 3.x installs them machine-wide; a 2.x bundled repo has
@@ -19,8 +19,9 @@ const FIXED_AGENTS = new Set([
19
19
  ]);
20
20
  const WORKFLOWS = ['cohorte-review.js', 'cohorte-audit.js', 'cohorte-refactor.js', 'cohorte-loop.js'];
21
21
  const GATE_FILE = path.join('.claude', 'hooks', 'cohorte-gate.py');
22
+ const PROFILE_JSON = path.join('.claude', 'profile.json');
22
23
 
23
- // The spec lifecycle (SCHEMA.md §Spec status). `in-progress` and `blocked` stay valid after
24
+ // The spec lifecycle (profile/schema/spec-status.md). `in-progress` and `blocked` stay valid after
24
25
  // /cohorte-loop was retired in 2.2.0: specs in existing repos carry them, and an external driver
25
26
  // still needs somewhere to record "a round is under way" / "a round gave up".
26
27
  const VALID_STATUS = ['draft', 'frozen', 'in-progress', 'in-review', 'shipped', 'merged', 'blocked', 'abandoned'];
@@ -105,6 +106,38 @@ function checkProfile(profile, hasPipelineMd) {
105
106
  n ? undefined : 'add at least one surface to §surfaces');
106
107
  }
107
108
 
109
+ // `.claude/profile.json` is the parsed machine block agents read instead of the whole PIPELINE.md.
110
+ // The CONTENT decides freshness — compared byte for byte with what `cohorte sync` would write now,
111
+ // through the same serializer. Modification times alone cannot: git does not preserve them (a fresh
112
+ // clone can show the JSON "older" than PIPELINE.md while identical), and sync rightly leaves an
113
+ // identical file alone after a prose-only edit. mtime only names the likely cause of a mismatch.
114
+ function checkProfileJson(pipelineMd, projectRoot) {
115
+ const want = pipelineMd != null ? profileJsonText(pipelineMd) : null;
116
+ if (!want) return mk('profile-json', 'Profile cache (.claude/profile.json)', 'skip', 'no parseable profile block to cache');
117
+ const file = path.join(projectRoot, PROFILE_JSON);
118
+ const have = readText(file);
119
+ if (have == null) {
120
+ return mk('profile-json', 'Profile cache (.claude/profile.json)', 'warn',
121
+ 'missing — agents fall back to parsing PIPELINE.md themselves (slower, costlier)',
122
+ 'cohorte sync (writes .claude/profile.json — commit it)');
123
+ }
124
+ // A Windows checkout with core.autocrlf rewrites line endings: that is not staleness.
125
+ if (have.replace(/\r\n/g, '\n') !== want) {
126
+ let older = false;
127
+ try { older = fs.statSync(file).mtimeMs < fs.statSync(path.join(projectRoot, 'PIPELINE.md')).mtimeMs; } catch { /* unknown */ }
128
+ return mk('profile-json', 'Profile cache (.claude/profile.json)', 'warn',
129
+ older ? 'stale — PIPELINE.md was edited after the last sync; agents read the old machine block'
130
+ : 'differs from a fresh parse of PIPELINE.md (hand-edited?) — agents read the wrong machine block',
131
+ 'cohorte sync (regenerates .claude/profile.json — commit it)');
132
+ }
133
+ if (isTracked(projectRoot, PROFILE_JSON) === false) {
134
+ return mk('profile-json', 'Profile cache (.claude/profile.json)', 'warn',
135
+ 'fresh, but not committed — teammates\' agents fall back to parsing PIPELINE.md',
136
+ 'git add .claude/profile.json && git commit');
137
+ }
138
+ return mk('profile-json', 'Profile cache (.claude/profile.json)', 'ok', 'matches PIPELINE.md');
139
+ }
140
+
108
141
  function checkAgents(profile, projectRoot, globalDir) {
109
142
  if (!profile || !(profile.surfaces || []).length) {
110
143
  return mk('agents', 'Surfaces ↔ agents', 'skip', 'no surfaces to reconcile');
@@ -309,7 +342,7 @@ function checkHooks(projectRoot, globalDir) {
309
342
  : 'cohorte sync (copies and registers the project gate — then commit .claude/)';
310
343
  return mk('hooks', 'Gate hook', status, problems.join(' · '), fix);
311
344
  }
312
- return mk('hooks', 'Gate hook', 'ok', `registered once (${shell[0].matcher} + Write|Edit|MultiEdit), committed`);
345
+ return mk('hooks', 'Gate hook', 'ok', `registered once (${shell[0].matcher} + Write|Edit|MultiEdit|NotebookEdit), committed`);
313
346
  }
314
347
 
315
348
  function checkRetrieval(profile, projectRoot) {
@@ -435,6 +468,7 @@ async function state({ projectRoot, globalDir, cliVersion, offline }) {
435
468
  const checks = [
436
469
  checkCore(v, isProject),
437
470
  checkProfile(profile, pipelineMd != null),
471
+ checkProfileJson(pipelineMd, projectRoot),
438
472
  checkAgents(profile, projectRoot, globalDir),
439
473
  checkGate(profile, projectRoot),
440
474
  checkLocalArtifacts(projectRoot, ['.claude']),