cohorte 3.0.0-dev.8 → 3.0.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 (229) hide show
  1. package/CHANGELOG.md +1532 -0
  2. package/README.md +316 -62
  3. package/bin/cli.js +212 -0
  4. package/bin/report.js +141 -0
  5. package/core/agents/cohorte-profile-reader.md +50 -0
  6. package/core/agents/cohorte-release.md +58 -0
  7. package/core/agents/cohorte-review.md +174 -0
  8. package/core/agents/implementer.template.md +146 -0
  9. package/core/commands/cohorte-align-ds.md +33 -0
  10. package/core/commands/cohorte-audit.md +67 -0
  11. package/core/commands/cohorte-brainstorm.md +73 -0
  12. package/core/commands/cohorte-build.md +241 -0
  13. package/core/commands/cohorte-doctor.md +133 -0
  14. package/core/commands/cohorte-fix.md +80 -0
  15. package/core/commands/cohorte-fleet.md +111 -0
  16. package/core/commands/cohorte-init-pipeline.md +30 -0
  17. package/core/commands/cohorte-intake.md +92 -0
  18. package/core/commands/cohorte-patch.md +118 -0
  19. package/core/commands/cohorte-refactor.md +57 -0
  20. package/core/commands/cohorte-retro.md +85 -0
  21. package/core/commands/cohorte-review.md +224 -0
  22. package/core/commands/cohorte-ship.md +155 -0
  23. package/core/commands/cohorte-spec.md +105 -0
  24. package/core/commands/cohorte-update-pipeline.md +115 -0
  25. package/core/hooks/gate.py +2931 -0
  26. package/core/templates/agent-handoff.md +34 -0
  27. package/core/templates/brainstorm-return.md +42 -0
  28. package/core/templates/decisions.template.md +42 -0
  29. package/core/templates/design-brief.md +37 -0
  30. package/core/templates/patch.template.md +86 -0
  31. package/core/templates/pr-body.md +25 -0
  32. package/core/templates/review-feedback.md +46 -0
  33. package/core/templates/spec.template.md +88 -0
  34. package/core/templates/steps/init-pipeline/01-detect-stack.md +44 -0
  35. package/core/templates/steps/init-pipeline/02-interview-gaps.md +55 -0
  36. package/core/templates/steps/init-pipeline/03-draft-profile.md +9 -0
  37. package/core/templates/steps/init-pipeline/04-write-render.md +91 -0
  38. package/core/templates/steps/init-pipeline/05-report.md +11 -0
  39. package/core/templates/steps/review-pr/01-pr-mode.md +54 -0
  40. package/core/workflows/audit.js +306 -0
  41. package/core/workflows/loop.js +687 -0
  42. package/core/workflows/refactor.js +291 -0
  43. package/core/workflows/review.js +491 -0
  44. package/install.ps1 +72 -0
  45. package/install.sh +69 -0
  46. package/lib/doctor.js +472 -0
  47. package/lib/install.js +377 -0
  48. package/lib/project.js +322 -0
  49. package/lib/render.js +121 -0
  50. package/lib/versions.js +145 -0
  51. package/lib/yaml.js +174 -0
  52. package/package.json +36 -17
  53. package/profile/PIPELINE.template.md +250 -0
  54. package/profile/SCHEMA.md +749 -0
  55. package/profile/cohorte.config.template.yaml +43 -0
  56. package/scripts/feature-diff.sh +118 -0
  57. package/scripts/kanban-move.sh +307 -0
  58. package/scripts/metrics/collect.mjs +542 -0
  59. package/scripts/metrics/prices.json +42 -0
  60. package/scripts/new-feature.sh.template +122 -0
  61. package/scripts/preflight.sh +114 -0
  62. package/scripts/remove-feature.sh.template +56 -0
  63. package/assets/manifest.json +0 -203
  64. package/assets/migrations/config/README.md +0 -12
  65. package/assets/migrations/state/0001_init.sql +0 -154
  66. package/assets/prompts/README.md +0 -11
  67. package/assets/prompts/agents/brainstormer.md +0 -3
  68. package/assets/prompts/agents/fixer.md +0 -7
  69. package/assets/prompts/agents/implementer.md +0 -12
  70. package/assets/prompts/agents/reviewer.md +0 -8
  71. package/assets/prompts/agents/security-reviewer.md +0 -7
  72. package/assets/prompts/agents/spec-author.md +0 -3
  73. package/assets/prompts/phases/build.md +0 -5
  74. package/assets/prompts/phases/review.md +0 -5
  75. package/assets/prompts/phases/test.md +0 -5
  76. package/assets/prompts/system.md +0 -11
  77. package/assets/schemas/agent-output.schema.json +0 -225
  78. package/assets/schemas/auth-status.schema.json +0 -87
  79. package/assets/schemas/command-result.schema.json +0 -192
  80. package/assets/schemas/commands.schema.json +0 -959
  81. package/assets/schemas/config.schema.json +0 -2281
  82. package/assets/schemas/doctor-report.schema.json +0 -104
  83. package/assets/schemas/events.schema.json +0 -8514
  84. package/assets/schemas/fake-script.schema.json +0 -549
  85. package/assets/schemas/inspect.schema.json +0 -3133
  86. package/assets/schemas/manifest.schema.json +0 -79
  87. package/assets/schemas/ownership.schema.json +0 -52
  88. package/assets/schemas/policy-verdict.schema.json +0 -282
  89. package/assets/schemas/project-model.schema.json +0 -783
  90. package/assets/schemas/project-status.schema.json +0 -217
  91. package/assets/schemas/reconcile-plan.schema.json +0 -154
  92. package/assets/schemas/run-diff.schema.json +0 -177
  93. package/assets/schemas/run-snapshot-manifest.schema.json +0 -2104
  94. package/assets/schemas/run-state.schema.json +0 -1755
  95. package/assets/schemas/runtime-capabilities.schema.json +0 -1545
  96. package/assets/schemas/sandbox-capabilities.schema.json +0 -116
  97. package/assets/schemas/skill.schema.json +0 -87
  98. package/assets/schemas/spec.schema.json +0 -202
  99. package/assets/schemas/tool-catalogue.schema.json +0 -655
  100. package/assets/schemas/trust-record.schema.json +0 -38
  101. package/assets/skills/README.md +0 -9
  102. package/assets/skills/inspect-surface.md +0 -4
  103. package/dist/agent-host.mjs +0 -2187
  104. package/dist/agent-host.mjs.map +0 -1
  105. package/dist/bundle-manifest.json +0 -128
  106. package/dist/chunks/__host-DgGPyco9.mjs +0 -18
  107. package/dist/chunks/__host-DgGPyco9.mjs.map +0 -1
  108. package/dist/chunks/align-ds-r_X_1aQ_.mjs +0 -93
  109. package/dist/chunks/align-ds-r_X_1aQ_.mjs.map +0 -1
  110. package/dist/chunks/approve-Cv135UqI.mjs +0 -19
  111. package/dist/chunks/approve-Cv135UqI.mjs.map +0 -1
  112. package/dist/chunks/audit-B4ZWQ_DI.mjs +0 -179
  113. package/dist/chunks/audit-B4ZWQ_DI.mjs.map +0 -1
  114. package/dist/chunks/auth-BT5oVp76.mjs +0 -132
  115. package/dist/chunks/auth-BT5oVp76.mjs.map +0 -1
  116. package/dist/chunks/auth-Dnlksuo5.mjs +0 -141
  117. package/dist/chunks/auth-Dnlksuo5.mjs.map +0 -1
  118. package/dist/chunks/brainstorm-SJwOIEif.mjs +0 -123
  119. package/dist/chunks/brainstorm-SJwOIEif.mjs.map +0 -1
  120. package/dist/chunks/build-C_-mbZfD.mjs +0 -19
  121. package/dist/chunks/build-C_-mbZfD.mjs.map +0 -1
  122. package/dist/chunks/cancel-KV_cpsqS.mjs +0 -15
  123. package/dist/chunks/cancel-KV_cpsqS.mjs.map +0 -1
  124. package/dist/chunks/canonical-C8UxeEmB.mjs +0 -57
  125. package/dist/chunks/canonical-C8UxeEmB.mjs.map +0 -1
  126. package/dist/chunks/catalogue-IaCJdfB8.mjs +0 -1549
  127. package/dist/chunks/catalogue-IaCJdfB8.mjs.map +0 -1
  128. package/dist/chunks/compose-DRKjQcn0.mjs +0 -7333
  129. package/dist/chunks/compose-DRKjQcn0.mjs.map +0 -1
  130. package/dist/chunks/config-Cqu5XQoP.mjs +0 -96
  131. package/dist/chunks/config-Cqu5XQoP.mjs.map +0 -1
  132. package/dist/chunks/contract-DjssDPpS.mjs +0 -335
  133. package/dist/chunks/contract-DjssDPpS.mjs.map +0 -1
  134. package/dist/chunks/contract-bQ9FJl4N.mjs +0 -123
  135. package/dist/chunks/contract-bQ9FJl4N.mjs.map +0 -1
  136. package/dist/chunks/deny-ClTxSvHJ.mjs +0 -15
  137. package/dist/chunks/deny-ClTxSvHJ.mjs.map +0 -1
  138. package/dist/chunks/diff-Qw0II0sj.mjs +0 -101
  139. package/dist/chunks/diff-Qw0II0sj.mjs.map +0 -1
  140. package/dist/chunks/discover-BZPolSZG.mjs +0 -21
  141. package/dist/chunks/discover-BZPolSZG.mjs.map +0 -1
  142. package/dist/chunks/doctor-DcDFPvQM.mjs +0 -222
  143. package/dist/chunks/doctor-DcDFPvQM.mjs.map +0 -1
  144. package/dist/chunks/fix-C9roGiQz.mjs +0 -82
  145. package/dist/chunks/fix-C9roGiQz.mjs.map +0 -1
  146. package/dist/chunks/fleet-yWHQY2ya.mjs +0 -297
  147. package/dist/chunks/fleet-yWHQY2ya.mjs.map +0 -1
  148. package/dist/chunks/gc-BBXlBF5w.mjs +0 -161
  149. package/dist/chunks/gc-BBXlBF5w.mjs.map +0 -1
  150. package/dist/chunks/init--FxxkrcT.mjs +0 -63
  151. package/dist/chunks/init--FxxkrcT.mjs.map +0 -1
  152. package/dist/chunks/inspect-Buby4cQD.mjs +0 -22
  153. package/dist/chunks/inspect-Buby4cQD.mjs.map +0 -1
  154. package/dist/chunks/intake-C1pesxCJ.mjs +0 -12
  155. package/dist/chunks/intake-C1pesxCJ.mjs.map +0 -1
  156. package/dist/chunks/logs-Giq5sUau.mjs +0 -25
  157. package/dist/chunks/logs-Giq5sUau.mjs.map +0 -1
  158. package/dist/chunks/loop-BWsUpyus.mjs +0 -212
  159. package/dist/chunks/loop-BWsUpyus.mjs.map +0 -1
  160. package/dist/chunks/migrate-DuYCAbE3.mjs +0 -33
  161. package/dist/chunks/migrate-DuYCAbE3.mjs.map +0 -1
  162. package/dist/chunks/models-Btp6X2YZ.mjs +0 -24
  163. package/dist/chunks/models-Btp6X2YZ.mjs.map +0 -1
  164. package/dist/chunks/obsidian-BHLkXx_H.mjs +0 -235
  165. package/dist/chunks/obsidian-BHLkXx_H.mjs.map +0 -1
  166. package/dist/chunks/patch-sAgVqjpx.mjs +0 -50
  167. package/dist/chunks/patch-sAgVqjpx.mjs.map +0 -1
  168. package/dist/chunks/pause-BASBfKLO.mjs +0 -16
  169. package/dist/chunks/pause-BASBfKLO.mjs.map +0 -1
  170. package/dist/chunks/policy-Du7WVBFX.mjs +0 -139
  171. package/dist/chunks/policy-Du7WVBFX.mjs.map +0 -1
  172. package/dist/chunks/providers-Dx78imKj.mjs +0 -19
  173. package/dist/chunks/providers-Dx78imKj.mjs.map +0 -1
  174. package/dist/chunks/reconcile-BHn66X3C.mjs +0 -50
  175. package/dist/chunks/reconcile-BHn66X3C.mjs.map +0 -1
  176. package/dist/chunks/refactor-DV3RfGjk.mjs +0 -153
  177. package/dist/chunks/refactor-DV3RfGjk.mjs.map +0 -1
  178. package/dist/chunks/render-DyZr5Lgi.mjs +0 -53
  179. package/dist/chunks/render-DyZr5Lgi.mjs.map +0 -1
  180. package/dist/chunks/resume-GJQRb2Eb.mjs +0 -15
  181. package/dist/chunks/resume-GJQRb2Eb.mjs.map +0 -1
  182. package/dist/chunks/retro-Dr-2RTNN.mjs +0 -78
  183. package/dist/chunks/retro-Dr-2RTNN.mjs.map +0 -1
  184. package/dist/chunks/retry-CLrUem1H.mjs +0 -15
  185. package/dist/chunks/retry-CLrUem1H.mjs.map +0 -1
  186. package/dist/chunks/review-ZsBqp3vZ.mjs +0 -35
  187. package/dist/chunks/review-ZsBqp3vZ.mjs.map +0 -1
  188. package/dist/chunks/run-BGabwbDL.mjs +0 -109
  189. package/dist/chunks/run-BGabwbDL.mjs.map +0 -1
  190. package/dist/chunks/run-tool-C3rAv4XF.mjs +0 -26
  191. package/dist/chunks/run-tool-C3rAv4XF.mjs.map +0 -1
  192. package/dist/chunks/scan-C5uDr7Yq.mjs +0 -167
  193. package/dist/chunks/scan-C5uDr7Yq.mjs.map +0 -1
  194. package/dist/chunks/schema-Bq9qtgsd.mjs +0 -583
  195. package/dist/chunks/schema-Bq9qtgsd.mjs.map +0 -1
  196. package/dist/chunks/send-BdnJ85Nz.mjs +0 -19
  197. package/dist/chunks/send-BdnJ85Nz.mjs.map +0 -1
  198. package/dist/chunks/ship-BizfUe62.mjs +0 -140
  199. package/dist/chunks/ship-BizfUe62.mjs.map +0 -1
  200. package/dist/chunks/shutdown-BM92Iyv2.mjs +0 -15
  201. package/dist/chunks/shutdown-BM92Iyv2.mjs.map +0 -1
  202. package/dist/chunks/skip-DZG5kpcH.mjs +0 -18
  203. package/dist/chunks/skip-DZG5kpcH.mjs.map +0 -1
  204. package/dist/chunks/spec-C2h3U64g.mjs +0 -65
  205. package/dist/chunks/spec-C2h3U64g.mjs.map +0 -1
  206. package/dist/chunks/spec-path-tptqR7W8.mjs +0 -10
  207. package/dist/chunks/spec-path-tptqR7W8.mjs.map +0 -1
  208. package/dist/chunks/src-Bfr1yzsn.mjs +0 -1689
  209. package/dist/chunks/src-Bfr1yzsn.mjs.map +0 -1
  210. package/dist/chunks/src-CPW2_Ons.mjs +0 -5487
  211. package/dist/chunks/src-CPW2_Ons.mjs.map +0 -1
  212. package/dist/chunks/src-Cu3TxNob.mjs +0 -783
  213. package/dist/chunks/src-Cu3TxNob.mjs.map +0 -1
  214. package/dist/chunks/src-DNsLSxgm.mjs +0 -928
  215. package/dist/chunks/src-DNsLSxgm.mjs.map +0 -1
  216. package/dist/chunks/src-DbS9gkJy.mjs +0 -117
  217. package/dist/chunks/src-DbS9gkJy.mjs.map +0 -1
  218. package/dist/chunks/src-yi5whv3n.mjs +0 -2118
  219. package/dist/chunks/src-yi5whv3n.mjs.map +0 -1
  220. package/dist/chunks/status-SMjiOMYy.mjs +0 -29
  221. package/dist/chunks/status-SMjiOMYy.mjs.map +0 -1
  222. package/dist/chunks/tail-BuhT-2PH.mjs +0 -25
  223. package/dist/chunks/tail-BuhT-2PH.mjs.map +0 -1
  224. package/dist/chunks/update-BXIppsbi.mjs +0 -16
  225. package/dist/chunks/update-BXIppsbi.mjs.map +0 -1
  226. package/dist/chunks/update-pipeline-Du-Gu1Pl.mjs +0 -56
  227. package/dist/chunks/update-pipeline-Du-Gu1Pl.mjs.map +0 -1
  228. package/dist/cli.mjs +0 -186
  229. package/dist/cli.mjs.map +0 -1
@@ -0,0 +1,54 @@
1
+ # /cohorte-review · PR mode — review an INCOMING pull request (`--pr <num>` or a PR URL)
2
+
3
+ Loaded by `/cohorte-review` only when its arguments carry `--pr <num>` (or a GitHub PR URL — extract
4
+ the number). This is not a pipeline feature: it is **someone else's work arriving**, reviewed with
5
+ the same reviewers and the same report format, without pretending it went through the pipeline.
6
+ What that changes: **no spec** (reviewers run in audit mode — conventions + correctness + security +
7
+ TDD coverage only), **no kanban move, no verdict.json, no DoD tick, no freshness stamp, no metrics
8
+ line** — those certify pipeline features. Requires `vcs.host: github` + `gh`; otherwise say so and stop.
9
+
10
+ 1. **Who wrote it — before anything runs.** One Bash call:
11
+ `gh pr view <num> --json title,baseRefName,headRefName,author,isCrossRepository` (relay the one-line
12
+ summary) and `gh api 'repos/{owner}/{repo}/pulls/<num>' --jq .author_association`. **Trusted** =
13
+ `OWNER`, `MEMBER` or `COLLABORATOR`. Anything else — `CONTRIBUTOR`, `FIRST_TIME_CONTRIBUTOR`, `NONE`,
14
+ or the call failing — is **untrusted** (fail closed). Installing a PR's dependencies runs its
15
+ lifecycle scripts, and running its tests runs its code: on an untrusted PR that is arbitrary code
16
+ on the human's machine.
17
+ - **Untrusted ⇒ execute nothing from the PR until the human says so.** Default: **static review
18
+ only** — skip step 3's local checks and read the PR's CI instead (`gh pr checks <num>`; a red
19
+ check is a finding exactly as a red local check would be, a pending/absent one is "not verified
20
+ here"). Ask once, naming the risk: "run its install + checks locally (its code executes on this
21
+ machine)?" — only an explicit yes enables step 3, and even then with lifecycle scripts disabled.
22
+ - **Trusted ⇒ step 3 runs**, still with lifecycle scripts disabled by default.
23
+ 2. **Fetch into a throwaway worktree — never touch the current checkout.**
24
+ `git fetch -f origin pull/<num>/head:cohorte-pr-<num> <baseRefName> && git worktree add ../<repo>-pr-<num> cohorte-pr-<num>`
25
+ — `-f` so a branch left by a crashed earlier run updates instead of failing, and the **base ref is
26
+ fetched too** (the diff is against `origin/<baseRefName>`; a stale local base blames the PR for
27
+ every commit it hasn't rebased onto). Every later step runs `-C` that worktree.
28
+ 3. **Mechanical checks inside the worktree — the commands directly, NEVER `preflight.sh`** (it stamps
29
+ `<state>/preflight.ok` in the MAIN checkout on purpose; running it here would green pipeline
30
+ dispatches of a tree nobody preflighted). Install first (`commands.install` — a bare `worktree add`
31
+ has no dependencies) **with lifecycle scripts off** (`--ignore-scripts` for npm/pnpm/yarn/bun; no
32
+ equivalent for the stack ⇒ ask before installing at all), then the profile's
33
+ typecheck/lint-quiet/test-quiet, each appended to the worktree's
34
+ `specs/reports/pr-<num>.preflight.txt`, stopping at the first failure. **Red gets no reviewers**
35
+ (a reviewer on code that doesn't compile rediscovers what `tsc` printed) — but it is not an abort:
36
+ the mechanical failures ARE the review (CRITICAL, kind `quality`, the failing command + last lines)
37
+ — jump to step 5. An *environmental* failure (install failed, a missing service, a native build
38
+ that needed its scripts) is "not verifiable here", never a finding against the PR.
39
+ 4. **Stage + dispatch — `/cohorte-review` §1's staging and §2's dispatch, minus everything
40
+ spec-shaped** (no spec to confirm, no small-diff fast path — an unknown author's diff always gets
41
+ a full reviewer), with three substitutions: the diff is `git diff origin/<baseRefName>...HEAD`
42
+ (**three-dot** — only the PR's own commits; a PR is commits, so the untracked-file problem
43
+ `feature-diff.sh` solves does not arise), staged diffs and file paths are **absolute paths into
44
+ the worktree** (reviewers are stateless — they must not read the main checkout), and the
45
+ dispatch's spec/contract slots read
46
+ `spec: none (incoming PR — audit mode: PIPELINE.md conventions + quality/security/TDD only, skip spec conformance)` · `contract: none`.
47
+ Roll call + merge per §3 (retry once, `unreviewed` forbids a clean verdict), same capped REVIEW REPORT.
48
+ 5. **Stage the report to the MAIN checkout's `specs/reports/pr-<num>.md`** (it must outlive the
49
+ worktree), print the verdict + severity table + CRITICAL/security digests, and say which checks
50
+ were run locally, read from CI, or not verified. Then — **always ask first, posting is
51
+ outward-facing** — offer `gh pr comment <num> --body-file specs/reports/pr-<num>.md` (body prefixed
52
+ `Automated review — cohorte pipeline (advisory)`). "No" leaves the report on disk; that is complete.
53
+ 6. **Teardown, always** (also after a red check, a declined run or a dead reviewer):
54
+ `git worktree remove --force ../<repo>-pr-<num> && git branch -D cohorte-pr-<num>`.
@@ -0,0 +1,306 @@
1
+ // cohorte — /cohorte-audit as a deterministic workflow (opt-in; the conversational
2
+ // /cohorte-audit command remains the default path and the fallback).
3
+ //
4
+ // Invoke with args = {target: "<path or domain>"} (optional — default whole repo).
5
+ //
6
+ // Shape (SCHEMA.md §Workflows): profile via profile-reader (phase 0), the
7
+ // mechanical gates staged to disk by one haiku agent, then ONE auditor per
8
+ // domain (each surface + `shared`) running concurrently — the runtime caps
9
+ // concurrency at 20 (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS since 2026-08), extra
10
+ // domains queue — and a merge phase that writes the
11
+ // prioritized specs/refactor-backlog.md. Only the summary comes back.
12
+
13
+ export const meta = {
14
+ name: 'cohorte-audit',
15
+ description: 'Audit the codebase against PIPELINE.md: mechanical gates, one auditor per domain in parallel, prioritized refactor backlog',
16
+ whenToUse: 'Only when the human explicitly asks for the audit workflow. args = {target: "<path or domain>"} — omit for the whole repo.',
17
+ phases: [
18
+ { title: 'Profile', detail: 'PIPELINE.md → JSON via profile-reader', model: 'haiku' },
19
+ { title: 'Gates', detail: 'format/lint/typecheck/tests → specs/reports/audit-gates.txt', model: 'haiku' },
20
+ { title: 'Audit', detail: 'one review-in-audit-mode agent per domain (concurrent, runtime-capped 20)' },
21
+ { title: 'Backlog', detail: 'merge into specs/refactor-backlog.md (audited domains only)', model: 'haiku' },
22
+ ],
23
+ }
24
+
25
+ // The Workflow runtime hands `args` to a script verbatim, so a caller that passes a
26
+ // JSON-ENCODED STRING instead of a real object gets that string back here. The old
27
+ // `typeof args === 'string' ? args.trim()` then took the whole blob as the value — which
28
+ // is how a report landed on disk named `specs/reports/{"feature": "x"}.md`, and how
29
+ // maxRounds/smoke were silently dropped on the same run. Parse it back into the object
30
+ // it was meant to be; a bare slug stays valid shorthand.
31
+ const ARGS = (() => {
32
+ if (typeof args === 'string') {
33
+ const t = args.trim()
34
+ if (t.startsWith('{')) {
35
+ try { const o = JSON.parse(t); if (o && typeof o === 'object' && !Array.isArray(o)) return o } catch {}
36
+ }
37
+ return { feature: t, target: t }
38
+ }
39
+ return args && typeof args === 'object' ? args : {}
40
+ })()
41
+ const target = ARGS.target || ''
42
+
43
+ // The profile-reader returns through a StructuredOutput tool call, and a haiku agent
44
+ // intermittently nests the whole profile as a JSON *string* under a single wrapper field
45
+ // ({"output": "{\"surfaces\": …}"}) instead of putting the profile's keys at the top level.
46
+ // The schema here used to be {type:'object', additionalProperties:true} — no declared
47
+ // properties, no required keys — so that wrapper validated cleanly and every field then read
48
+ // as undefined: `surfaces` fell back to [], parallel([]) dispatched zero agents, the
49
+ // dead-agent guard had no surfaces to find missing, and the run reported a verdict having
50
+ // done nothing. On the surface it is indistinguishable from a clean run with an empty diff.
51
+ // Declaring the shape gives the tool layer something to validate and the agent something to
52
+ // aim at; unwrapProfile() salvages a wrapped return that still gets through; and the
53
+ // zero-surface abort below makes the silent-success path impossible either way.
54
+ // See also the structured-output section of core/agents/cohorte-profile-reader.md.
55
+ const PROFILE = {
56
+ type: 'object', additionalProperties: true,
57
+ properties: {
58
+ error: { type: 'string', description: 'set ONLY when PIPELINE.md is missing or unparseable' },
59
+ surfaces: {
60
+ type: 'array',
61
+ description: "one entry per surface, at the TOP LEVEL of this object — never a JSON string",
62
+ items: {
63
+ type: 'object', required: ['key'], additionalProperties: true,
64
+ properties: { key: { type: 'string' }, path: { type: 'string' }, agent: { type: 'string' } },
65
+ },
66
+ },
67
+ },
68
+ }
69
+
70
+ // Salvage a profile handed back as JSON text rather than as an object — either the whole
71
+ // return, or nested under a single wrapper field. Anything already shaped like a profile
72
+ // (has `surfaces`, or is the documented `{error}` failure shape) passes through untouched.
73
+ const unwrapProfile = p => {
74
+ if (typeof p === 'string') { try { return JSON.parse(p) } catch { return null } }
75
+ if (!p || typeof p !== 'object') return null
76
+ if (Array.isArray(p.surfaces) || p.error) return p
77
+ for (const v of Object.values(p)) {
78
+ if (typeof v !== 'string') continue
79
+ try {
80
+ const inner = JSON.parse(v)
81
+ if (inner && typeof inner === 'object' && !Array.isArray(inner)) return inner
82
+ } catch {}
83
+ }
84
+ return p
85
+ }
86
+
87
+ const GATES = {
88
+ type: 'object', required: ['failures'], additionalProperties: false,
89
+ properties: {
90
+ failures: {
91
+ type: 'array', maxItems: 40,
92
+ items: {
93
+ type: 'object', required: ['file', 'line', 'kind', 'summary'], additionalProperties: false,
94
+ properties: {
95
+ file: { type: 'string' }, line: { type: 'integer' },
96
+ kind: { enum: ['lint', 'format', 'type', 'test'] },
97
+ summary: { type: 'string', description: 'one line, no output excerpts' },
98
+ },
99
+ },
100
+ },
101
+ overflow: { type: 'integer', description: 'failures beyond the 40-item cap' },
102
+ },
103
+ }
104
+
105
+ // The backlog as it stands, read back STRUCTURALLY so the merge happens here, in script
106
+ // code a test can pin — not in a prompt. Lines are verbatim, in file order.
107
+ const EXISTING = {
108
+ type: 'object', required: ['exists', 'domains'], additionalProperties: false,
109
+ properties: {
110
+ exists: { type: 'boolean' },
111
+ lineCount: { type: 'integer', description: "the output of `grep -c '^- \\[' specs/refactor-backlog.md` (0 when absent)" },
112
+ domains: {
113
+ type: 'array',
114
+ items: {
115
+ type: 'object', required: ['key', 'lines'], additionalProperties: false,
116
+ properties: {
117
+ key: { type: 'string', description: 'the `## <domain>` heading text' },
118
+ lines: { type: 'array', items: { type: 'string', description: 'one `- [ ] …` / `- [x] …` line, verbatim' } },
119
+ },
120
+ },
121
+ },
122
+ },
123
+ }
124
+
125
+ const BACKLOG = {
126
+ type: 'object', required: ['items'], additionalProperties: false,
127
+ properties: {
128
+ items: {
129
+ type: 'array', maxItems: 30,
130
+ items: {
131
+ type: 'object', required: ['severity', 'file', 'line', 'kind', 'fix'], additionalProperties: false,
132
+ properties: {
133
+ severity: { enum: ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'] },
134
+ file: { type: 'string' }, line: { type: 'integer' },
135
+ kind: { enum: ['rule', 'tdd', 'lint', 'format', 'type', 'security'] },
136
+ fix: { type: 'string', description: 'one concrete change, one line, no code excerpts' },
137
+ },
138
+ },
139
+ },
140
+ overflow: { type: 'integer' },
141
+ },
142
+ }
143
+
144
+ // ── Phase 0 — profile ────────────────────────────────────────────────────────
145
+ phase('Profile')
146
+ const profile = unwrapProfile(await agent(
147
+ 'Return this project\'s PIPELINE.md `yaml pipeline-profile` block as JSON, per your instructions.',
148
+ { agentType: 'cohorte-profile-reader', label: 'profile', schema: PROFILE, effort: 'low' },
149
+ ))
150
+ if (!profile || profile.error) {
151
+ return { error: `profile unreadable: ${(profile && profile.error) || 'profile-reader returned nothing'}` }
152
+ }
153
+ const cmds = profile.commands || {}
154
+ const surfaces = Array.isArray(profile.surfaces) ? profile.surfaces : []
155
+ // A profile with no surfaces cannot do this workflow's work, and every later
156
+ // guard compares against `surfaces` — an empty list makes them all vacuously
157
+ // pass. Fail loudly here instead of finishing with nothing done.
158
+ if (!surfaces.length) {
159
+ return { error: 'profile has no surfaces — nothing would be audited. the `yaml pipeline-profile` block in PIPELINE.md is empty or unparseable, or the profile-reader mis-returned; run /cohorte-doctor' }
160
+ }
161
+ const quiet = (q, full) => (q && !String(q).startsWith('<') ? q : full ? `${full} 2>&1 | tail -40` : '')
162
+ const scope = target || 'the whole repo'
163
+
164
+ // ── Phase 1 — mechanical gates, staged to disk ───────────────────────────────
165
+ phase('Gates')
166
+ const gateCmds = [
167
+ cmds.format ? `${cmds.format} --check` : '',
168
+ quiet(cmds.lint_quiet, cmds.lint),
169
+ cmds.typecheck,
170
+ quiet(cmds.test_quiet, cmds.test),
171
+ ].filter(c => c && !String(c).startsWith('<'))
172
+ const gates = await agent(
173
+ `Run the cohorte audit's mechanical gates, scoped to ${scope}. Commands (adapt the format one to the ` +
174
+ `project's check mode if --check is wrong): ${gateCmds.map(c => JSON.stringify(c)).join(' · ')}.\n` +
175
+ 'FIRST truncate the report (`mkdir -p specs/reports && : > specs/reports/audit-gates.txt`) — a previous run\'s ' +
176
+ 'output must not be read as this one\'s — then for each command append a header and its output ' +
177
+ '(`printf \'\\n$ %s\\n\' "<cmd>" >> specs/reports/audit-gates.txt; <cmd> >> specs/reports/audit-gates.txt 2>&1`) — ' +
178
+ 'never print it — and keep going after failures (this is an inventory, not a gate to pass). Then grep ' +
179
+ 'the file and return each failure as file/line/kind/one-line summary, capped at 40 (set overflow for the rest).',
180
+ { model: 'haiku', label: 'gates', schema: GATES, effort: 'low' },
181
+ )
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).
184
+ // The domain auditors still run (they read the staged gates file, which then simply
185
+ // isn't there), but the run must say the mechanical sweep is uncovered.
186
+ const gatesCovered = gates != null
187
+ const mech = (gates && gates.failures) || []
188
+ log(gatesCovered
189
+ ? `Mechanical failures: ${mech.length}${gates.overflow ? ` (+${gates.overflow} overflow)` : ''}`
190
+ : 'the gates agent died — mechanical checks NOT covered this run')
191
+
192
+ // ── Phase 2 — one auditor per domain, concurrent ─────────────────────────────
193
+ // Domains = every surface + `shared` (contract package + anything outside the
194
+ // surface trees). The runtime caps concurrent agents at 20 by default; more domains
195
+ // queue. Raising CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS raises the ceiling, it does not
196
+ // change this script — the queue is the runtime's, and a queued domain is not a lost one.
197
+ phase('Audit')
198
+ const domainsAll = surfaces.map(s => ({ key: s.key, path: s.path }))
199
+ .concat([{ key: 'shared', path: (profile.contract && profile.contract.path) || '(everything outside the surface trees)' }])
200
+ const domains = domainsAll
201
+ .filter(d => !target || target === d.key || String(d.path).startsWith(target) || target.startsWith(String(d.path)))
202
+ if (!domains.length) return { error: `target "${target}" matches no surface/domain` }
203
+
204
+ const audited = await parallel(domains.map(d => () => agent(
205
+ 'Audit a target against PIPELINE.md (no spec — audit mode, per your agent instructions). Check ' +
206
+ 'conventions for the domain\'s surface, TDD coverage (untested entry points / modules), and — if the ' +
207
+ 'profile enables them — mobile-first + design-system usage. Mechanical findings are already staged: ' +
208
+ 'read specs/reports/audit-gates.txt and fold the ones in your domain in. Return the prioritized items, ' +
209
+ 'capped at 30, one line each, no code excerpts. — Variable slots: domain: ' +
210
+ `${d.key} · tree: ${d.path}${target ? ` · human-requested target: ${target}` : ''}`,
211
+ { agentType: 'cohorte-review', label: `audit:${d.key}`, schema: BACKLOG },
212
+ ).then(r => r && { key: d.key, items: r.items, overflow: r.overflow || 0 })))
213
+ const perDomain = audited.filter(Boolean)
214
+ // A dead auditor returns null, and a domain with no result is indistinguishable
215
+ // from a domain with nothing to report — the backlog would simply omit it and the
216
+ // human would read that as "clean". Name them instead.
217
+ const deadDomains = domains.filter(d => !perDomain.some(p => p.key === d.key)).map(d => d.key)
218
+ if (deadDomains.length) log(`Auditor died on: ${deadDomains.join(', ')} — those domains are NOT audited`)
219
+
220
+ // ── Phase 3 — merge into the backlog: ONLY the audited domains are rewritten ──
221
+ // The backlog is shared state, not this run's report. It holds other domains' items (a
222
+ // scoped audit looked at one domain), and open `deferred:<feature>` lines /cohorte-review
223
+ // parked there — a real finding a feature deliberately did not own. Overwriting the file
224
+ // with this run's items erased both. So: read it back, replace the sections of the domains
225
+ // this run actually audited (keeping their open deferred lines), keep every other section
226
+ // verbatim, write the result in one exact write.
227
+ phase('Backlog')
228
+ const existing = await agent(
229
+ 'Read specs/refactor-backlog.md (mechanical — no judgment). Return exists; lineCount = the output of ' +
230
+ "`grep -c '^- \\[' specs/refactor-backlog.md`; and per `## <domain>` heading (in file order) every list " +
231
+ 'line under it VERBATIM — both `- [ ]` and `- [x]` lines, nothing else. ' +
232
+ 'File missing ⇒ exists=false, lineCount=0 and an empty domains array.',
233
+ { model: 'haiku', label: 'read-backlog', schema: EXISTING, effort: 'low' },
234
+ )
235
+ const SEV = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3 }
236
+ const auditedKeys = new Set(perDomain.map(d => d.key))
237
+ const oldDomains = (existing && Array.isArray(existing.domains) ? existing.domains : [])
238
+ .filter(d => d && d.key).map(d => ({ key: String(d.key).trim(), lines: Array.isArray(d.lines) ? d.lines : [] }))
239
+ const oldByKey = Object.fromEntries(oldDomains.map(d => [d.key, d.lines]))
240
+ const isOpenDeferred = l => /^- \[ \]/.test(l) && /deferred:\S/.test(l)
241
+ let total = 0
242
+ let carried = 0
243
+ const sections = []
244
+ // Profile order first (surfaces, then shared), then any domain only the old file knows.
245
+ const order = [...domainsAll.map(d => d.key), ...oldDomains.map(d => d.key)].filter((k, i, a) => a.indexOf(k) === i)
246
+ for (const key of order) {
247
+ const d = perDomain.find(p => p.key === key)
248
+ if (d) {
249
+ const items = [...d.items].sort((a, b) => SEV[a.severity] - SEV[b.severity])
250
+ total += items.length
251
+ const lines = items.map(it => `- [ ] ${it.severity} · ${it.file}:${it.line} · ${it.kind} · ${it.fix}`)
252
+ 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))
254
+ carried += keep.length
255
+ sections.push({ key, lines: lines.concat(keep) })
256
+ } else if (oldByKey[key] && oldByKey[key].length) {
257
+ sections.push({ key, lines: oldByKey[key] }) // not audited this run — untouched
258
+ }
259
+ }
260
+ const body = ['# Refactor backlog', '',
261
+ `> Last merged by the cohorte-audit workflow (scope: ${scope}) — only the audited domains' sections were rewritten.`]
262
+ if (deadDomains.length) {
263
+ body.push('', `> ⚠ NOT audited (the auditor died): ${deadDomains.join(', ')} — their sections below are the`,
264
+ '> PREVIOUS run\'s, or absent; absence of items means "not looked at", not "clean". Re-run the audit for them.')
265
+ }
266
+ if (!gatesCovered) {
267
+ body.push('', '> ⚠ Mechanical gates NOT run (the gates agent died) — lint/typecheck/test failures',
268
+ '> are uncounted below. Re-run the audit for the mechanical sweep.')
269
+ }
270
+ for (const s of sections) body.push('', `## ${s.key}`, '', ...s.lines)
271
+ // A dead READER is not an empty backlog — writing on top of it would erase exactly what
272
+ // this phase exists to keep. Nor is a SHORT read: the reader echoes the file verbatim, and a
273
+ // truncated echo would silently drop other domains' lines. Its line count must match the
274
+ // lines it returned (grep -c, computed in its Bash), or the write is skipped like a dead read.
275
+ const readLines = oldDomains.reduce((n, d) => n + d.lines.filter(l => /^- \[/.test(l)).length, 0)
276
+ const readOk = existing != null && typeof existing === 'object'
277
+ && (typeof existing.lineCount !== 'number' || existing.lineCount === readLines)
278
+ if (existing != null && !readOk) log(`backlog read looks truncated (${readLines} lines returned, ${existing.lineCount} on disk) — not writing`)
279
+ const written = !readOk ? null : await agent(
280
+ `Write EXACTLY this content to specs/refactor-backlog.md (overwrite), then return the single word done:\n<<<BACKLOG\n${body.join('\n')}\nBACKLOG`,
281
+ { model: 'haiku', label: 'write-backlog', effort: 'low' },
282
+ )
283
+ // Returning `backlog: <path>` when the writer died points /cohorte-refactor at a file
284
+ // that does not exist (or, worse, at the PREVIOUS run's stale backlog).
285
+ const backlogOk = written != null && /done/i.test(String(written))
286
+
287
+ return {
288
+ backlog: backlogOk ? 'specs/refactor-backlog.md'
289
+ : existing == null ? '(NOT written — the backlog reader died; the file on disk is untouched)'
290
+ : !readOk ? '(NOT written — the backlog read came back short (reader died mid-echo); the file on disk is untouched)'
291
+ : '(NOT written — the backlog writer died)',
292
+ deferredCarried: carried, // open deferred:<feature> lines kept in the rewritten sections
293
+ notAudited: deadDomains, // absence of findings here means "not looked at"
294
+ mechanicalFailures: gatesCovered ? mech.length : null, // null = gates agent died, NOT zero
295
+ gatesCovered,
296
+ domains: Object.fromEntries(perDomain.map(d => [d.key, d.items.length + (d.overflow || 0)])),
297
+ total,
298
+ top: perDomain.flatMap(d => d.items.map(it => ({ ...it, domain: d.key })))
299
+ .sort((a, b) => SEV[a.severity] - SEV[b.severity]).slice(0, 10)
300
+ .map(it => `[${it.severity}] ${it.domain} · ${it.file}:${it.line} — ${it.fix}`),
301
+ next: !backlogOk
302
+ ? `the backlog was NEVER written (${!readOk ? 'reader' : 'writer'} died or came back short) — the counts above are real but nothing is on disk; re-run the audit`
303
+ : deadDomains.length
304
+ ? `re-audit ${deadDomains.join(', ')} (auditor died — not covered), then /cohorte-refactor <domain>`
305
+ : 'refactor a domain with /cohorte-refactor <domain> (or the refactor workflow for big domains)',
306
+ }