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,291 @@
1
+ // cohorte — /cohorte-refactor as a deterministic workflow (opt-in; the conversational
2
+ // /cohorte-refactor command remains the default path and the fallback).
3
+ //
4
+ // BIG domains only: a domain with just a handful of open backlog items is
5
+ // cheaper through the conversational /cohorte-refactor — this script skips it and says
6
+ // so. Invoke with args = {domains: ["backend", …]} or {domains: "all"}.
7
+ //
8
+ // Shape (SCHEMA.md §Workflows): profile via profile-reader (phase 0), the open
9
+ // backlog read once, the `shared` domain (contract package — every slice
10
+ // imports it) refactored FIRST and alone, then the other domains' surface
11
+ // implementers in parallel (their trees are disjoint by construction), each
12
+ // verified per-domain with one bounded retry round, and the backlog ticked.
13
+
14
+ export const meta = {
15
+ name: 'cohorte-refactor',
16
+ description: 'Apply the /cohorte-audit refactor backlog for big domains: shared first, then parallel surface implementers, per-domain verify + one retry',
17
+ whenToUse: 'Only when the human explicitly asks for the refactor workflow on big domains. args = {domains: ["<surface key>", …] | "all"}.',
18
+ phases: [
19
+ { title: 'Profile', detail: 'PIPELINE.md → JSON via profile-reader', model: 'haiku' },
20
+ { title: 'Backlog', detail: 'read the open items per requested domain', model: 'haiku' },
21
+ { title: 'Shared', detail: 'refactor the contract package first, alone' },
22
+ { title: 'Refactor', detail: 'one surface implementer per domain, parallel' },
23
+ { 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' },
25
+ ],
26
+ }
27
+
28
+ // A domain below this many open items is not "big" — the conversational
29
+ // /cohorte-refactor handles it with less overhead than a workflow run.
30
+ const MIN_ITEMS = 5
31
+
32
+ // The Workflow runtime hands `args` to a script verbatim, so a caller that passes a
33
+ // JSON-ENCODED STRING instead of a real object gets that string back here. Parse it
34
+ // back into the object it was meant to be. A bare slug is shorthand for the DOMAIN in
35
+ // this script — mapping it to {feature, target} (review.js's keys, once copy-pasted
36
+ // here) left ARGS.domains undefined, which fell through to 'all': the shorthand
37
+ // "backend" dispatched code-editing implementers on EVERY big domain, not the one
38
+ // the caller named.
39
+ const ARGS = (() => {
40
+ if (typeof args === 'string') {
41
+ const t = args.trim()
42
+ if (t.startsWith('{')) {
43
+ try { const o = JSON.parse(t); if (o && typeof o === 'object' && !Array.isArray(o)) return o } catch {}
44
+ }
45
+ return { domains: [t] }
46
+ }
47
+ return args && typeof args === 'object' ? args : {}
48
+ })()
49
+
50
+ const wanted = (() => {
51
+ const d = ARGS.domains
52
+ if (!d || d === 'all') return 'all'
53
+ return Array.isArray(d) ? d : [String(d)]
54
+ })()
55
+
56
+ // The profile-reader returns through a StructuredOutput tool call, and a haiku agent
57
+ // intermittently nests the whole profile as a JSON *string* under a single wrapper field
58
+ // ({"output": "{\"surfaces\": …}"}) instead of putting the profile's keys at the top level.
59
+ // The schema here used to be {type:'object', additionalProperties:true} — no declared
60
+ // properties, no required keys — so that wrapper validated cleanly and every field then read
61
+ // as undefined: `surfaces` fell back to [], parallel([]) dispatched zero agents, the
62
+ // dead-agent guard had no surfaces to find missing, and the run reported a verdict having
63
+ // done nothing. On the surface it is indistinguishable from a clean run with an empty diff.
64
+ // Declaring the shape gives the tool layer something to validate and the agent something to
65
+ // aim at; unwrapProfile() salvages a wrapped return that still gets through; and the
66
+ // zero-surface abort below makes the silent-success path impossible either way.
67
+ // See also the structured-output section of core/agents/cohorte-profile-reader.md.
68
+ const PROFILE = {
69
+ type: 'object', additionalProperties: true,
70
+ properties: {
71
+ error: { type: 'string', description: 'set ONLY when PIPELINE.md is missing or unparseable' },
72
+ surfaces: {
73
+ type: 'array',
74
+ description: "one entry per surface, at the TOP LEVEL of this object — never a JSON string",
75
+ items: {
76
+ type: 'object', required: ['key'], additionalProperties: true,
77
+ properties: { key: { type: 'string' }, path: { type: 'string' }, agent: { type: 'string' } },
78
+ },
79
+ },
80
+ },
81
+ }
82
+
83
+ // Salvage a profile handed back as JSON text rather than as an object — either the whole
84
+ // return, or nested under a single wrapper field. Anything already shaped like a profile
85
+ // (has `surfaces`, or is the documented `{error}` failure shape) passes through untouched.
86
+ const unwrapProfile = p => {
87
+ if (typeof p === 'string') { try { return JSON.parse(p) } catch { return null } }
88
+ if (!p || typeof p !== 'object') return null
89
+ if (Array.isArray(p.surfaces) || p.error) return p
90
+ for (const v of Object.values(p)) {
91
+ if (typeof v !== 'string') continue
92
+ try {
93
+ const inner = JSON.parse(v)
94
+ if (inner && typeof inner === 'object' && !Array.isArray(inner)) return inner
95
+ } catch {}
96
+ }
97
+ return p
98
+ }
99
+
100
+ const OPEN = {
101
+ type: 'object', required: ['domains'], additionalProperties: false,
102
+ properties: {
103
+ domains: {
104
+ type: 'array',
105
+ items: {
106
+ type: 'object', required: ['key', 'items'], additionalProperties: false,
107
+ properties: {
108
+ key: { type: 'string' },
109
+ items: { type: 'array', items: { type: 'string', description: 'the open `- [ ] …` line verbatim' } },
110
+ },
111
+ },
112
+ },
113
+ },
114
+ }
115
+
116
+ const VERIFY = {
117
+ type: 'object', required: ['cleared', 'remaining', 'gatesGreen'], additionalProperties: false,
118
+ properties: {
119
+ cleared: { type: 'array', items: { type: 'string' } },
120
+ remaining: { type: 'array', items: { type: 'string' } },
121
+ gatesGreen: { type: 'boolean' },
122
+ failures: { type: 'string', description: 'one line per gate failure, no output dumps' },
123
+ },
124
+ }
125
+
126
+ // ── Phase 0 — profile ────────────────────────────────────────────────────────
127
+ phase('Profile')
128
+ const profile = unwrapProfile(await agent(
129
+ 'Return this project\'s PIPELINE.md `yaml pipeline-profile` block as JSON, per your instructions.',
130
+ { agentType: 'cohorte-profile-reader', label: 'profile', schema: PROFILE, effort: 'low' },
131
+ ))
132
+ if (!profile || profile.error) {
133
+ return { error: `profile unreadable: ${(profile && profile.error) || 'profile-reader returned nothing'}` }
134
+ }
135
+ const surfaces = Array.isArray(profile.surfaces) ? profile.surfaces : []
136
+ // A profile with no surfaces cannot do this workflow's work, and every later
137
+ // guard compares against `surfaces` — an empty list makes them all vacuously
138
+ // pass. Fail loudly here instead of finishing with nothing done.
139
+ if (!surfaces.length) {
140
+ return { error: 'profile has no surfaces — nothing would be refactored. the `yaml pipeline-profile` block in PIPELINE.md is empty or unparseable, or the profile-reader mis-returned; run /cohorte-doctor' }
141
+ }
142
+ const byKey = Object.fromEntries(surfaces.map(s => [s.key, s]))
143
+ const contractPath = (profile.contract && profile.contract.path) || ''
144
+ const base = (profile.vcs && profile.vcs.default_branch) || 'main'
145
+ const quiet = s => (s.test_quiet_cmd && !String(s.test_quiet_cmd).startsWith('<'))
146
+ ? s.test_quiet_cmd : s.test_cmd ? `${s.test_cmd} 2>&1 | tail -40` : ''
147
+ const real = c => c && !String(c).startsWith('<')
148
+ // The `shared` domain (contract package / everything outside the surface trees) has no
149
+ // surface entry, so no per-surface commands — it used to verify with NO gates and report
150
+ // gatesGreen=true by default. Every slice imports it, so it is verified with the REPO-WIDE
151
+ // commands (profile.commands), which is what a change there can actually break.
152
+ const cmds = profile.commands || {}
153
+ const repoGates = [
154
+ real(cmds.test_quiet) ? cmds.test_quiet : real(cmds.test) ? `${cmds.test} 2>&1 | tail -40` : '',
155
+ real(cmds.lint_quiet) ? cmds.lint_quiet : real(cmds.lint) ? `${cmds.lint} 2>&1 | tail -40` : '',
156
+ cmds.typecheck,
157
+ ].filter(real)
158
+
159
+ // ── Phase 1 — read the open backlog ──────────────────────────────────────────
160
+ phase('Backlog')
161
+ const backlog = await agent(
162
+ 'Read specs/refactor-backlog.md and return, per `## <domain>` heading, the OPEN `- [ ] …` item lines ' +
163
+ 'verbatim (skip checked `- [x]` ones). File missing ⇒ return an empty domains array. ' +
164
+ `Requested domains: ${wanted === 'all' ? 'all' : wanted.join(', ')} — return only those (all ⇒ every domain with open items).`,
165
+ { model: 'haiku', label: 'read-backlog', schema: OPEN, effort: 'low' },
166
+ )
167
+ // A dead reader is not "the backlog is empty" — reporting it as such sends the
168
+ // human to re-run /cohorte-audit on a backlog that is already there.
169
+ if (!backlog) return { error: 'the backlog-reading agent died — nothing was read; re-run the refactor workflow' }
170
+ const open = (backlog.domains || []).filter(d => d.items.length)
171
+ if (!open.length) return { error: 'no open backlog items for the requested domains — run /cohorte-audit (or the audit workflow) first' }
172
+
173
+ const big = open.filter(d => d.items.length >= MIN_ITEMS)
174
+ const small = open.filter(d => d.items.length < MIN_ITEMS)
175
+ for (const d of small) log(`Skipping ${d.key} (${d.items.length} open item(s) < ${MIN_ITEMS}) — use the conversational /cohorte-refactor ${d.key}, it's cheaper`)
176
+ if (!big.length) return { skipped: Object.fromEntries(small.map(d => [d.key, d.items.length])), reason: `every requested domain is below the ${MIN_ITEMS}-item workflow threshold — use /cohorte-refactor` }
177
+
178
+ const implementPrompt = d =>
179
+ 'Refactor pass on your surface (no feature spec). Read PIPELINE.md first. Add the missing tests ' +
180
+ 'FIRST (pin current behavior / cover the entry points), watch them pass, THEN refactor to clear each ' +
181
+ 'item. Preserve current public behavior unless an item marks it a bug. Migrations stay additive. ' +
182
+ `Need the current state of your tree? Compute it yourself: <core>/pipeline/scripts/feature-diff.sh --default ${base} --patch -- <your surface path> ` +
183
+ '(<core> = "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/cohorte"; never a bare git diff — it hides files you created). ' +
184
+ 'Lint + format before handoff; return the handoff in the format your agent instructions define. ' +
185
+ 'Backlog items for YOUR surface (self-contained — clear exactly these, reading only the files they name):\n' +
186
+ d.items.join('\n')
187
+
188
+ const verifyDomain = async (d, implHandoff) => {
189
+ if (implHandoff == null) return { key: d.key, cleared: [], remaining: d.items, gatesGreen: false, failures: 'implementer died' }
190
+ const s = byKey[d.key]
191
+ const gateCmds = s ? [quiet(s), s.lint_quiet_cmd || (s.lint_cmd ? `${s.lint_cmd} 2>&1 | tail -40` : ''), s.typecheck_cmd]
192
+ .filter(real) : d.key === 'shared' ? repoGates : []
193
+ // No gates at all is not green: it is unverified. Say so instead of defaulting to true.
194
+ const noGates = gateCmds.length === 0
195
+ let v = await agent(
196
+ `Verify a cohorte refactor round for domain ${d.key}. 1. Run these gates, each redirected to ` +
197
+ `specs/reports/refactor-verify.${d.key}.txt (append) — never print their output: ` +
198
+ `${noGates ? '(none declared — skip the gates; return gatesGreen=false and failures="no gate commands declared")' : gateCmds.map(c => JSON.stringify(c)).join(' · ')}. ` +
199
+ '2. For EACH backlog item below, open its file:line and check the prescribed fix actually landed. ' +
200
+ 'Return the item lines split into cleared / remaining (verbatim), gatesGreen, and one line per gate failure.\n' +
201
+ 'Items:\n' + d.items.join('\n'),
202
+ { model: 'haiku', label: `verify:${d.key}`, phase: 'Verify', schema: VERIFY, effort: 'low' },
203
+ )
204
+ if (v && noGates) v = { ...v, gatesGreen: false, failures: 'no gate commands declared for this domain — gates unverified' }
205
+ // One bounded retry: re-dispatch the implementer on what verification rejected.
206
+ // The re-verify covers ONLY the retried items, so round 1's cleared list is carried
207
+ // forward — overwriting it un-ticked every item the first pass verified, and the
208
+ // next /cohorte-refactor re-dispatched finished work.
209
+ if (v && (v.remaining.length || (!v.gatesGreen && !noGates)) && byKey[d.key]) {
210
+ const cleared1 = v.cleared || []
211
+ // Never retry items round 1 already verified cleared: on a gates-red round with
212
+ // nothing remaining, retrying ALL items put the same lines in both `cleared` and
213
+ // `remaining` when the re-verifier died — ticked off the backlog AND reported open.
214
+ const retryItems = v.remaining.length ? v.remaining : d.items.filter(i => !cleared1.includes(i))
215
+ log(`${d.key}: ${v.remaining.length} item(s) remaining${v.gatesGreen ? '' : ' + red gates'} — one retry round`)
216
+ await agent(
217
+ implementPrompt({ key: d.key, items: retryItems }) + (v.failures ? `\nGate failures to clear too:\n${v.failures}` : ''),
218
+ { agentType: byKey[d.key].agent, label: `retry:${d.key}`, phase: 'Refactor' },
219
+ )
220
+ const v2 = await agent(
221
+ `Re-verify domain ${d.key} after a retry round — same procedure as before (gates redirected to ` +
222
+ `specs/reports/refactor-verify.${d.key}.txt, per-item file:line check, verbatim cleared/remaining lines).\n` +
223
+ 'Items:\n' + retryItems.join('\n'),
224
+ { model: 'haiku', label: `reverify:${d.key}`, phase: 'Verify', schema: VERIFY, effort: 'low' },
225
+ )
226
+ // A dead re-verifier loses only the RETRY round's claim — round 1's verified
227
+ // clears stay cleared; the retried items stay open (unverified ≠ cleared).
228
+ v = v2
229
+ ? { ...v2, cleared: [...new Set(cleared1.concat(v2.cleared || []))] }
230
+ : { cleared: cleared1, remaining: retryItems, gatesGreen: false, failures: 'verifier died on the retry round' }
231
+ }
232
+ return { key: d.key, ...(v || { cleared: [], remaining: d.items, gatesGreen: false, failures: 'verifier died' }) }
233
+ }
234
+
235
+ // ── Phase 2 — `shared` first, alone (every slice imports the contract pkg) ───
236
+ const results = []
237
+ const shared = big.find(d => d.key === 'shared')
238
+ if (shared) {
239
+ phase('Shared')
240
+ const handoff = await agent(
241
+ `Refactor the shared contract package (${contractPath || 'the tree outside every surface'}) of this ` +
242
+ 'cohorte project — normally lead-owned, so: additive changes only, never break a shape a surface ' +
243
+ 'imports (grep consumers before changing any export), migrations stay additive, lint + format before ' +
244
+ 'handoff. Clear exactly these open backlog items (self-contained; read only the files they name):\n' +
245
+ shared.items.join('\n'),
246
+ { label: 'refactor:shared', phase: 'Shared' },
247
+ )
248
+ results.push(await verifyDomain(shared, handoff))
249
+ }
250
+
251
+ // ── Phases 3+4 — the other domains in parallel, each verified as it lands ────
252
+ const rest = big.filter(d => d.key !== 'shared' && byKey[d.key])
253
+ for (const d of big) {
254
+ if (d.key !== 'shared' && !byKey[d.key]) log(`Skipping ${d.key} — no matching surface in PIPELINE.md`)
255
+ }
256
+ const restResults = await pipeline(
257
+ rest,
258
+ d => agent(implementPrompt(d), { agentType: byKey[d.key].agent, label: `refactor:${d.key}`, phase: 'Refactor' }),
259
+ (handoff, d) => verifyDomain(d, handoff),
260
+ )
261
+ results.push(...restResults.filter(Boolean))
262
+
263
+ // ── Phase 5 — tick the cleared items ─────────────────────────────────────────
264
+ phase('Tick')
265
+ const clearedAll = results.flatMap(r => r.cleared)
266
+ let tickedOk = true
267
+ if (clearedAll.length) {
268
+ const ticked = await agent(
269
+ 'In specs/refactor-backlog.md flip EXACTLY these open `- [ ]` item lines to `- [x]` (match verbatim, ' +
270
+ 'leave every other line untouched), then return the single word done:\n' + clearedAll.join('\n'),
271
+ { model: 'haiku', label: 'tick-backlog', effort: 'low' },
272
+ )
273
+ // Reporting items as cleared while the backlog still shows them open means the
274
+ // next /cohorte-refactor re-dispatches work that is already done.
275
+ tickedOk = ticked != null && /done/i.test(String(ticked))
276
+ }
277
+
278
+ return {
279
+ domains: Object.fromEntries(results.map(r => [r.key, {
280
+ cleared: r.cleared.length, remaining: r.remaining.length, gatesGreen: r.gatesGreen,
281
+ }])),
282
+ skippedSmall: Object.fromEntries(small.map(d => [d.key, d.items.length])),
283
+ stillOpen: results.flatMap(r => r.remaining.map(line => `[${r.key}] ${line}`)).slice(0, 15),
284
+ backlogTicked: tickedOk,
285
+ next: !tickedOk
286
+ ? `${clearedAll.length} item(s) were cleared in code but NOT ticked off specs/refactor-backlog.md ` +
287
+ '(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',
291
+ }