cclaw-cli 7.7.1 → 8.1.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 (282) hide show
  1. package/README.md +210 -134
  2. package/dist/artifact-frontmatter.d.ts +51 -0
  3. package/dist/artifact-frontmatter.js +131 -0
  4. package/dist/artifact-paths.d.ts +7 -27
  5. package/dist/artifact-paths.js +20 -249
  6. package/dist/cancel.d.ts +16 -0
  7. package/dist/cancel.js +66 -0
  8. package/dist/cli.d.ts +2 -27
  9. package/dist/cli.js +90 -508
  10. package/dist/compound.d.ts +26 -0
  11. package/dist/compound.js +96 -0
  12. package/dist/config.d.ts +14 -51
  13. package/dist/config.js +23 -359
  14. package/dist/constants.d.ts +11 -18
  15. package/dist/constants.js +19 -106
  16. package/dist/content/antipatterns.d.ts +1 -0
  17. package/dist/content/antipatterns.js +109 -0
  18. package/dist/content/artifact-templates.d.ts +10 -0
  19. package/dist/content/artifact-templates.js +550 -0
  20. package/dist/content/cancel-command.d.ts +2 -2
  21. package/dist/content/cancel-command.js +25 -17
  22. package/dist/content/core-agents.d.ts +9 -233
  23. package/dist/content/core-agents.js +39 -768
  24. package/dist/content/decision-protocol.d.ts +1 -12
  25. package/dist/content/decision-protocol.js +27 -20
  26. package/dist/content/examples.d.ts +8 -42
  27. package/dist/content/examples.js +293 -425
  28. package/dist/content/idea-command.d.ts +2 -0
  29. package/dist/content/idea-command.js +38 -0
  30. package/dist/content/iron-laws.d.ts +4 -138
  31. package/dist/content/iron-laws.js +18 -197
  32. package/dist/content/meta-skill.d.ts +1 -3
  33. package/dist/content/meta-skill.js +57 -134
  34. package/dist/content/node-hooks.d.ts +12 -8
  35. package/dist/content/node-hooks.js +188 -838
  36. package/dist/content/recovery.d.ts +8 -0
  37. package/dist/content/recovery.js +179 -0
  38. package/dist/content/reference-patterns.d.ts +4 -13
  39. package/dist/content/reference-patterns.js +260 -389
  40. package/dist/content/research-playbooks.d.ts +8 -8
  41. package/dist/content/research-playbooks.js +108 -121
  42. package/dist/content/review-loop.d.ts +6 -192
  43. package/dist/content/review-loop.js +29 -731
  44. package/dist/content/skills.d.ts +8 -38
  45. package/dist/content/skills.js +681 -732
  46. package/dist/content/specialist-prompts/architect.d.ts +1 -0
  47. package/dist/content/specialist-prompts/architect.js +225 -0
  48. package/dist/content/specialist-prompts/brainstormer.d.ts +1 -0
  49. package/dist/content/specialist-prompts/brainstormer.js +168 -0
  50. package/dist/content/specialist-prompts/index.d.ts +2 -0
  51. package/dist/content/specialist-prompts/index.js +14 -0
  52. package/dist/content/specialist-prompts/planner.d.ts +1 -0
  53. package/dist/content/specialist-prompts/planner.js +182 -0
  54. package/dist/content/specialist-prompts/reviewer.d.ts +1 -0
  55. package/dist/content/specialist-prompts/reviewer.js +193 -0
  56. package/dist/content/specialist-prompts/security-reviewer.d.ts +1 -0
  57. package/dist/content/specialist-prompts/security-reviewer.js +133 -0
  58. package/dist/content/specialist-prompts/slice-builder.d.ts +1 -0
  59. package/dist/content/specialist-prompts/slice-builder.js +232 -0
  60. package/dist/content/stage-playbooks.d.ts +8 -0
  61. package/dist/content/stage-playbooks.js +404 -0
  62. package/dist/content/start-command.d.ts +2 -12
  63. package/dist/content/start-command.js +221 -207
  64. package/dist/flow-state.d.ts +21 -178
  65. package/dist/flow-state.js +67 -170
  66. package/dist/fs-utils.d.ts +6 -26
  67. package/dist/fs-utils.js +29 -162
  68. package/dist/gitignore.d.ts +2 -1
  69. package/dist/gitignore.js +51 -34
  70. package/dist/harness-detect.d.ts +10 -0
  71. package/dist/harness-detect.js +29 -0
  72. package/dist/install.d.ts +27 -15
  73. package/dist/install.js +230 -1342
  74. package/dist/knowledge-store.d.ts +19 -163
  75. package/dist/knowledge-store.js +56 -590
  76. package/dist/logger.d.ts +8 -3
  77. package/dist/logger.js +13 -4
  78. package/dist/orchestrator-routing.d.ts +29 -0
  79. package/dist/orchestrator-routing.js +156 -0
  80. package/dist/run-persistence.d.ts +7 -118
  81. package/dist/run-persistence.js +29 -845
  82. package/dist/runtime/run-hook.entry.d.ts +1 -3
  83. package/dist/runtime/run-hook.entry.js +19 -4
  84. package/dist/runtime/run-hook.mjs +13 -1024
  85. package/dist/types.d.ts +25 -261
  86. package/dist/types.js +8 -36
  87. package/package.json +6 -3
  88. package/dist/artifact-linter/brainstorm.d.ts +0 -2
  89. package/dist/artifact-linter/brainstorm.js +0 -353
  90. package/dist/artifact-linter/design.d.ts +0 -18
  91. package/dist/artifact-linter/design.js +0 -444
  92. package/dist/artifact-linter/findings-dedup.d.ts +0 -56
  93. package/dist/artifact-linter/findings-dedup.js +0 -232
  94. package/dist/artifact-linter/plan.d.ts +0 -2
  95. package/dist/artifact-linter/plan.js +0 -826
  96. package/dist/artifact-linter/review-army.d.ts +0 -49
  97. package/dist/artifact-linter/review-army.js +0 -520
  98. package/dist/artifact-linter/review.d.ts +0 -2
  99. package/dist/artifact-linter/review.js +0 -113
  100. package/dist/artifact-linter/scope.d.ts +0 -2
  101. package/dist/artifact-linter/scope.js +0 -158
  102. package/dist/artifact-linter/shared.d.ts +0 -637
  103. package/dist/artifact-linter/shared.js +0 -2163
  104. package/dist/artifact-linter/ship.d.ts +0 -2
  105. package/dist/artifact-linter/ship.js +0 -250
  106. package/dist/artifact-linter/spec.d.ts +0 -2
  107. package/dist/artifact-linter/spec.js +0 -176
  108. package/dist/artifact-linter/tdd.d.ts +0 -118
  109. package/dist/artifact-linter/tdd.js +0 -1404
  110. package/dist/artifact-linter.d.ts +0 -15
  111. package/dist/artifact-linter.js +0 -517
  112. package/dist/codex-feature-flag.d.ts +0 -58
  113. package/dist/codex-feature-flag.js +0 -193
  114. package/dist/content/closeout-guidance.d.ts +0 -14
  115. package/dist/content/closeout-guidance.js +0 -44
  116. package/dist/content/diff-command.d.ts +0 -1
  117. package/dist/content/diff-command.js +0 -43
  118. package/dist/content/harness-doc.d.ts +0 -1
  119. package/dist/content/harness-doc.js +0 -65
  120. package/dist/content/hook-events.d.ts +0 -9
  121. package/dist/content/hook-events.js +0 -23
  122. package/dist/content/hook-manifest.d.ts +0 -81
  123. package/dist/content/hook-manifest.js +0 -156
  124. package/dist/content/hooks.d.ts +0 -11
  125. package/dist/content/hooks.js +0 -1972
  126. package/dist/content/idea.d.ts +0 -60
  127. package/dist/content/idea.js +0 -416
  128. package/dist/content/language-policy.d.ts +0 -2
  129. package/dist/content/language-policy.js +0 -13
  130. package/dist/content/learnings.d.ts +0 -6
  131. package/dist/content/learnings.js +0 -141
  132. package/dist/content/observe.d.ts +0 -19
  133. package/dist/content/observe.js +0 -86
  134. package/dist/content/opencode-plugin.d.ts +0 -1
  135. package/dist/content/opencode-plugin.js +0 -635
  136. package/dist/content/review-prompts.d.ts +0 -1
  137. package/dist/content/review-prompts.js +0 -104
  138. package/dist/content/runtime-shared-snippets.d.ts +0 -8
  139. package/dist/content/runtime-shared-snippets.js +0 -80
  140. package/dist/content/session-hooks.d.ts +0 -7
  141. package/dist/content/session-hooks.js +0 -107
  142. package/dist/content/skills-elicitation.d.ts +0 -1
  143. package/dist/content/skills-elicitation.js +0 -167
  144. package/dist/content/stage-command.d.ts +0 -2
  145. package/dist/content/stage-command.js +0 -17
  146. package/dist/content/stage-schema.d.ts +0 -117
  147. package/dist/content/stage-schema.js +0 -955
  148. package/dist/content/stages/_lint-metadata/index.d.ts +0 -2
  149. package/dist/content/stages/_lint-metadata/index.js +0 -97
  150. package/dist/content/stages/brainstorm.d.ts +0 -2
  151. package/dist/content/stages/brainstorm.js +0 -184
  152. package/dist/content/stages/design.d.ts +0 -2
  153. package/dist/content/stages/design.js +0 -288
  154. package/dist/content/stages/index.d.ts +0 -8
  155. package/dist/content/stages/index.js +0 -11
  156. package/dist/content/stages/plan.d.ts +0 -2
  157. package/dist/content/stages/plan.js +0 -191
  158. package/dist/content/stages/review.d.ts +0 -2
  159. package/dist/content/stages/review.js +0 -240
  160. package/dist/content/stages/schema-types.d.ts +0 -203
  161. package/dist/content/stages/schema-types.js +0 -1
  162. package/dist/content/stages/scope.d.ts +0 -2
  163. package/dist/content/stages/scope.js +0 -254
  164. package/dist/content/stages/ship.d.ts +0 -2
  165. package/dist/content/stages/ship.js +0 -159
  166. package/dist/content/stages/spec.d.ts +0 -2
  167. package/dist/content/stages/spec.js +0 -170
  168. package/dist/content/stages/tdd.d.ts +0 -4
  169. package/dist/content/stages/tdd.js +0 -273
  170. package/dist/content/state-contracts.d.ts +0 -1
  171. package/dist/content/state-contracts.js +0 -63
  172. package/dist/content/status-command.d.ts +0 -4
  173. package/dist/content/status-command.js +0 -109
  174. package/dist/content/subagent-context-skills.d.ts +0 -4
  175. package/dist/content/subagent-context-skills.js +0 -279
  176. package/dist/content/subagents.d.ts +0 -3
  177. package/dist/content/subagents.js +0 -997
  178. package/dist/content/templates.d.ts +0 -26
  179. package/dist/content/templates.js +0 -1692
  180. package/dist/content/track-render-context.d.ts +0 -18
  181. package/dist/content/track-render-context.js +0 -53
  182. package/dist/content/tree-command.d.ts +0 -1
  183. package/dist/content/tree-command.js +0 -64
  184. package/dist/content/utility-skills.d.ts +0 -30
  185. package/dist/content/utility-skills.js +0 -160
  186. package/dist/content/view-command.d.ts +0 -2
  187. package/dist/content/view-command.js +0 -92
  188. package/dist/delegation.d.ts +0 -649
  189. package/dist/delegation.js +0 -1539
  190. package/dist/early-loop.d.ts +0 -70
  191. package/dist/early-loop.js +0 -302
  192. package/dist/execution-topology.d.ts +0 -44
  193. package/dist/execution-topology.js +0 -95
  194. package/dist/gate-evidence.d.ts +0 -85
  195. package/dist/gate-evidence.js +0 -631
  196. package/dist/harness-adapters.d.ts +0 -151
  197. package/dist/harness-adapters.js +0 -756
  198. package/dist/harness-selection.d.ts +0 -31
  199. package/dist/harness-selection.js +0 -214
  200. package/dist/hook-schema.d.ts +0 -6
  201. package/dist/hook-schema.js +0 -114
  202. package/dist/hook-schemas/claude-hooks.v1.json +0 -10
  203. package/dist/hook-schemas/codex-hooks.v1.json +0 -10
  204. package/dist/hook-schemas/cursor-hooks.v1.json +0 -13
  205. package/dist/init-detect.d.ts +0 -2
  206. package/dist/init-detect.js +0 -50
  207. package/dist/internal/advance-stage/advance.d.ts +0 -89
  208. package/dist/internal/advance-stage/advance.js +0 -655
  209. package/dist/internal/advance-stage/cancel-run.d.ts +0 -8
  210. package/dist/internal/advance-stage/cancel-run.js +0 -19
  211. package/dist/internal/advance-stage/flow-state-coercion.d.ts +0 -3
  212. package/dist/internal/advance-stage/flow-state-coercion.js +0 -81
  213. package/dist/internal/advance-stage/helpers.d.ts +0 -14
  214. package/dist/internal/advance-stage/helpers.js +0 -145
  215. package/dist/internal/advance-stage/hook.d.ts +0 -8
  216. package/dist/internal/advance-stage/hook.js +0 -40
  217. package/dist/internal/advance-stage/parsers.d.ts +0 -72
  218. package/dist/internal/advance-stage/parsers.js +0 -357
  219. package/dist/internal/advance-stage/proactive-delegation-trace.d.ts +0 -24
  220. package/dist/internal/advance-stage/proactive-delegation-trace.js +0 -56
  221. package/dist/internal/advance-stage/review-loop.d.ts +0 -16
  222. package/dist/internal/advance-stage/review-loop.js +0 -199
  223. package/dist/internal/advance-stage/rewind.d.ts +0 -14
  224. package/dist/internal/advance-stage/rewind.js +0 -108
  225. package/dist/internal/advance-stage/start-flow.d.ts +0 -13
  226. package/dist/internal/advance-stage/start-flow.js +0 -241
  227. package/dist/internal/advance-stage/verify.d.ts +0 -21
  228. package/dist/internal/advance-stage/verify.js +0 -185
  229. package/dist/internal/advance-stage.d.ts +0 -7
  230. package/dist/internal/advance-stage.js +0 -138
  231. package/dist/internal/cohesion-contract-stub.d.ts +0 -24
  232. package/dist/internal/cohesion-contract-stub.js +0 -148
  233. package/dist/internal/compound-readiness.d.ts +0 -23
  234. package/dist/internal/compound-readiness.js +0 -102
  235. package/dist/internal/detect-public-api-changes.d.ts +0 -5
  236. package/dist/internal/detect-public-api-changes.js +0 -45
  237. package/dist/internal/detect-supply-chain-changes.d.ts +0 -6
  238. package/dist/internal/detect-supply-chain-changes.js +0 -138
  239. package/dist/internal/early-loop-status.d.ts +0 -7
  240. package/dist/internal/early-loop-status.js +0 -93
  241. package/dist/internal/envelope-validate.d.ts +0 -7
  242. package/dist/internal/envelope-validate.js +0 -66
  243. package/dist/internal/flow-state-repair.d.ts +0 -20
  244. package/dist/internal/flow-state-repair.js +0 -104
  245. package/dist/internal/plan-split-waves.d.ts +0 -190
  246. package/dist/internal/plan-split-waves.js +0 -764
  247. package/dist/internal/runtime-integrity.d.ts +0 -7
  248. package/dist/internal/runtime-integrity.js +0 -268
  249. package/dist/internal/slice-commit.d.ts +0 -7
  250. package/dist/internal/slice-commit.js +0 -619
  251. package/dist/internal/tdd-loop-status.d.ts +0 -14
  252. package/dist/internal/tdd-loop-status.js +0 -68
  253. package/dist/internal/tdd-red-evidence.d.ts +0 -7
  254. package/dist/internal/tdd-red-evidence.js +0 -153
  255. package/dist/internal/waiver-grant.d.ts +0 -62
  256. package/dist/internal/waiver-grant.js +0 -294
  257. package/dist/internal/wave-status.d.ts +0 -74
  258. package/dist/internal/wave-status.js +0 -506
  259. package/dist/managed-resources.d.ts +0 -53
  260. package/dist/managed-resources.js +0 -313
  261. package/dist/policy.d.ts +0 -10
  262. package/dist/policy.js +0 -167
  263. package/dist/retro-gate.d.ts +0 -9
  264. package/dist/retro-gate.js +0 -47
  265. package/dist/run-archive.d.ts +0 -61
  266. package/dist/run-archive.js +0 -391
  267. package/dist/runs.d.ts +0 -2
  268. package/dist/runs.js +0 -2
  269. package/dist/stack-detection.d.ts +0 -116
  270. package/dist/stack-detection.js +0 -489
  271. package/dist/streaming/event-stream.d.ts +0 -31
  272. package/dist/streaming/event-stream.js +0 -114
  273. package/dist/tdd-cycle.d.ts +0 -107
  274. package/dist/tdd-cycle.js +0 -289
  275. package/dist/tdd-verification-evidence.d.ts +0 -17
  276. package/dist/tdd-verification-evidence.js +0 -122
  277. package/dist/track-heuristics.d.ts +0 -27
  278. package/dist/track-heuristics.js +0 -154
  279. package/dist/util/slice-id.d.ts +0 -58
  280. package/dist/util/slice-id.js +0 -89
  281. package/dist/worktree-manager.d.ts +0 -20
  282. package/dist/worktree-manager.js +0 -108
@@ -1,655 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import path from "node:path";
3
- import { resolveArtifactPath } from "../../artifact-paths.js";
4
- import { appendDelegation, checkMandatoryDelegations, readDelegationEvents, readDelegationLedger } from "../../delegation.js";
5
- import { verifyCompletedStagesGateClosure, verifyCurrentStageGateEvidence } from "../../gate-evidence.js";
6
- import { extractMarkdownSectionBody, learningsParseFailureHumanSummary, parseLearningsSection } from "../../artifact-linter.js";
7
- import { getAvailableTransitions, getTransitionGuards } from "../../flow-state.js";
8
- import { appendKnowledge } from "../../knowledge-store.js";
9
- import { readFlowState, writeFlowState } from "../../runs.js";
10
- import { stageSchema } from "../../content/stage-schema.js";
11
- import { extractReviewLoopEnvelopeFromArtifact } from "../../content/review-loop.js";
12
- import { unique } from "./helpers.js";
13
- import { AUTO_REVIEW_LOOP_GATE_BY_STAGE, reviewLoopArtifactFixHint, reviewLoopEnvelopeExample, validateGateEvidenceShape } from "./review-loop.js";
14
- import { ensureProactiveDelegationTrace } from "./proactive-delegation-trace.js";
15
- import { consumeWaiverToken } from "../waiver-grant.js";
16
- function resolveSuccessorTransition(stage, track, transitionTargets, satisfiedGuards, selectedTransitionGuards) {
17
- const natural = transitionTargets[0] ?? null;
18
- const specialTargets = transitionTargets.filter((target) => target !== natural);
19
- for (const target of specialTargets) {
20
- const guards = getTransitionGuards(stage, target, track);
21
- if (guards.length === 0)
22
- continue;
23
- const selectedSpecial = guards.some((guard) => selectedTransitionGuards.has(guard));
24
- if (!selectedSpecial)
25
- continue;
26
- if (guards.every((guard) => satisfiedGuards.has(guard))) {
27
- return target;
28
- }
29
- }
30
- if (natural) {
31
- const guards = getTransitionGuards(stage, natural, track);
32
- if (guards.every((guard) => satisfiedGuards.has(guard))) {
33
- return natural;
34
- }
35
- }
36
- for (const target of specialTargets) {
37
- const guards = getTransitionGuards(stage, target, track);
38
- if (guards.every((guard) => satisfiedGuards.has(guard))) {
39
- return target;
40
- }
41
- }
42
- return natural;
43
- }
44
- function nextInteractionHints(flowState, args, successor) {
45
- const hints = { ...(flowState.interactionHints ?? {}) };
46
- delete hints[args.stage];
47
- if (successor) {
48
- if (args.skipQuestions) {
49
- hints[successor] = {
50
- skipQuestions: true,
51
- sourceStage: args.stage,
52
- recordedAt: new Date().toISOString()
53
- };
54
- }
55
- else {
56
- delete hints[successor];
57
- }
58
- }
59
- return hints;
60
- }
61
- /**
62
- * entry point — auto-hydrate evidence for an auto-hydratable
63
- * gate that the agent already included in --passed but for which they
64
- * forgot to provide --evidence-json. Returns silently when no
65
- * hydration is possible (no auto-hydratable gate, no artifact, no
66
- * envelope, etc.).
67
- *
68
- * layered `tryAutoHydrateAndSelectReviewLoopGate` on
69
- * top of this so the gate is also auto-included in selectedGateIds
70
- * when the artifact yields a valid envelope. Together the two helpers
71
- * remove the contradiction:
72
- * - "omit this gate from --evidence-json so stage-complete can
73
- * auto-hydrate it" → "missing --evidence-json entries for passed
74
- * gates: design_diagram_freshness".
75
- */
76
- export async function hydrateReviewLoopEvidenceFromArtifact(projectRoot, stage, track, selectedGateIds, evidenceByGate) {
77
- const gateId = AUTO_REVIEW_LOOP_GATE_BY_STAGE[stage];
78
- if (!gateId)
79
- return;
80
- if (!selectedGateIds.includes(gateId))
81
- return;
82
- const reviewStage = stage === "scope" || stage === "design" ? stage : null;
83
- if (!reviewStage)
84
- return;
85
- const existing = evidenceByGate[gateId];
86
- if (typeof existing === "string" && existing.trim().length > 0) {
87
- return;
88
- }
89
- const resolved = await resolveArtifactPath(stage, {
90
- projectRoot,
91
- track,
92
- intent: "read"
93
- });
94
- let raw = "";
95
- try {
96
- raw = await fs.readFile(resolved.absPath, "utf8");
97
- }
98
- catch {
99
- return;
100
- }
101
- const envelope = extractReviewLoopEnvelopeFromArtifact(raw, reviewStage, resolved.relPath);
102
- if (!envelope)
103
- return;
104
- evidenceByGate[gateId] = JSON.stringify(envelope);
105
- }
106
- /**
107
- * auto-include an auto-hydratable review-loop gate
108
- * in `selectedGateIds` when:
109
- * - The stage has an auto-hydratable gate registered via
110
- * `AUTO_REVIEW_LOOP_GATE_BY_STAGE` (currently `design`).
111
- * - The artifact yields a valid review-loop envelope via
112
- * `extractReviewLoopEnvelopeFromArtifact`.
113
- * - The gate is required for the active track.
114
- * - The agent has NOT passed the gate yet (so we don't double-add).
115
- *
116
- * Returns the (possibly extended) array of selected gate IDs and
117
- * mutates `evidenceByGate` to include the hydrated envelope.
118
- *
119
- * Together with `hydrateReviewLoopEvidenceFromArtifact` this makes the
120
- * flow consistent: if the artifact contains the envelope, the agent
121
- * neither has to include the gate in --passed nor pass --evidence-json
122
- * for it. If the artifact does NOT contain the envelope, the agent
123
- * gets a clear error pointing at the artifact section to add (via
124
- * `reviewLoopArtifactFixHint`).
125
- */
126
- export async function tryAutoHydrateAndSelectReviewLoopGate(projectRoot, stage, track, requiredGateIds, selectedGateIds, evidenceByGate) {
127
- const gateId = AUTO_REVIEW_LOOP_GATE_BY_STAGE[stage];
128
- if (!gateId)
129
- return selectedGateIds;
130
- const reviewStage = stage === "scope" || stage === "design" ? stage : null;
131
- if (!reviewStage)
132
- return selectedGateIds;
133
- if (!requiredGateIds.includes(gateId))
134
- return selectedGateIds;
135
- if (selectedGateIds.includes(gateId)) {
136
- // Already selected — fall through to the existing hydration helper
137
- // for the manual --evidence-json path.
138
- await hydrateReviewLoopEvidenceFromArtifact(projectRoot, stage, track, selectedGateIds, evidenceByGate);
139
- return selectedGateIds;
140
- }
141
- const existing = evidenceByGate[gateId];
142
- if (typeof existing === "string" && existing.trim().length > 0) {
143
- return [...selectedGateIds, gateId];
144
- }
145
- const resolved = await resolveArtifactPath(stage, {
146
- projectRoot,
147
- track,
148
- intent: "read"
149
- });
150
- let raw = "";
151
- try {
152
- raw = await fs.readFile(resolved.absPath, "utf8");
153
- }
154
- catch {
155
- return selectedGateIds;
156
- }
157
- const envelope = extractReviewLoopEnvelopeFromArtifact(raw, reviewStage, resolved.relPath);
158
- if (!envelope)
159
- return selectedGateIds;
160
- evidenceByGate[gateId] = JSON.stringify(envelope);
161
- return [...selectedGateIds, gateId];
162
- }
163
- export async function buildValidationReport(projectRoot, flowState, options = {}) {
164
- // forward `flowState.taskClass` so the
165
- // bugfix-skip lights up via the `cclaw advance-stage` path. The
166
- // delegation helper now has its own fallback (it reads `flowState`
167
- // internally), but threading the value here keeps the call site
168
- // self-documenting and survives any future refactor that drops the
169
- // implicit fallback.
170
- const delegation = await checkMandatoryDelegations(projectRoot, flowState.currentStage, {
171
- taskClass: flowState.taskClass ?? undefined
172
- });
173
- const gates = await verifyCurrentStageGateEvidence(projectRoot, flowState, {
174
- extraStageFlags: options.extraStageFlags
175
- });
176
- const completedStages = verifyCompletedStagesGateClosure(flowState);
177
- const blockedReviewRouteComplete = options.allowBlockedReviewRoute === true
178
- && flowState.currentStage === "review"
179
- && typeof flowState.guardEvidence.review_verdict_blocked === "string"
180
- && flowState.guardEvidence.review_verdict_blocked.trim().length > 0
181
- && !flowState.stageGateCatalog.review.passed.includes("review_criticals_resolved");
182
- const ok = delegation.satisfied && gates.ok && (gates.complete || blockedReviewRouteComplete) && completedStages.ok;
183
- return {
184
- ok,
185
- stage: flowState.currentStage,
186
- delegation: {
187
- satisfied: delegation.satisfied,
188
- missing: delegation.missing,
189
- waived: delegation.waived,
190
- missingEvidence: delegation.missingEvidence,
191
- missingDispatchProof: delegation.missingDispatchProof,
192
- legacyInferredCompletions: delegation.legacyInferredCompletions,
193
- corruptEventLines: delegation.corruptEventLines,
194
- staleWorkers: delegation.staleWorkers,
195
- expectedMode: delegation.expectedMode,
196
- skippedByTrack: delegation.skippedByTrack
197
- },
198
- gates: {
199
- ok: gates.ok,
200
- complete: gates.complete,
201
- issues: gates.issues,
202
- missingRequired: gates.missingRequired,
203
- missingTriggeredConditional: gates.missingTriggeredConditional
204
- },
205
- completedStages: {
206
- ok: completedStages.ok,
207
- issues: completedStages.issues
208
- }
209
- };
210
- }
211
- const LEARNINGS_HARVEST_MARKER_PREFIX = "<!-- cclaw:learnings-harvested:";
212
- export function withLearningsHarvestMarker(artifactMarkdown, appendedEntries, skippedDuplicates) {
213
- const suffix = artifactMarkdown.endsWith("\n") ? "" : "\n";
214
- return `${artifactMarkdown}${suffix}${LEARNINGS_HARVEST_MARKER_PREFIX}${new Date().toISOString()} appended=${appendedEntries} skipped=${skippedDuplicates} -->\n`;
215
- }
216
- export async function harvestStageLearnings(projectRoot, stage, track) {
217
- const resolvedArtifact = await resolveArtifactPath(stage, {
218
- projectRoot,
219
- track,
220
- intent: "read"
221
- });
222
- const artifactPath = resolvedArtifact.absPath;
223
- let raw = "";
224
- try {
225
- raw = await fs.readFile(artifactPath, "utf8");
226
- }
227
- catch (err) {
228
- return {
229
- ok: false,
230
- markerWritten: false,
231
- parsedEntries: 0,
232
- appendedEntries: 0,
233
- skippedDuplicates: 0,
234
- details: `Unable to read artifact for learnings harvest (${artifactPath}): ${err instanceof Error ? err.message : String(err)}`
235
- };
236
- }
237
- if (raw.includes(LEARNINGS_HARVEST_MARKER_PREFIX)) {
238
- return {
239
- ok: true,
240
- markerWritten: false,
241
- parsedEntries: 0,
242
- appendedEntries: 0,
243
- skippedDuplicates: 0,
244
- details: "Learnings already harvested for this artifact."
245
- };
246
- }
247
- const learningsBody = extractMarkdownSectionBody(raw, "Learnings");
248
- if (learningsBody === null) {
249
- return {
250
- ok: false,
251
- markerWritten: false,
252
- parsedEntries: 0,
253
- appendedEntries: 0,
254
- skippedDuplicates: 0,
255
- details: 'Artifact is missing required "## Learnings" section.'
256
- };
257
- }
258
- const parsed = parseLearningsSection(learningsBody);
259
- if (!parsed.ok) {
260
- return {
261
- ok: false,
262
- markerWritten: false,
263
- parsedEntries: 0,
264
- appendedEntries: 0,
265
- skippedDuplicates: 0,
266
- details: learningsParseFailureHumanSummary(resolvedArtifact.relPath, parsed.errors)
267
- };
268
- }
269
- const appendResult = await appendKnowledge(projectRoot, parsed.entries, {
270
- stage,
271
- originStage: stage,
272
- project: path.basename(projectRoot)
273
- });
274
- if (appendResult.invalid > 0) {
275
- return {
276
- ok: false,
277
- markerWritten: false,
278
- parsedEntries: parsed.entries.length,
279
- appendedEntries: appendResult.appended,
280
- skippedDuplicates: appendResult.skippedDuplicates,
281
- details: `Learnings append failed schema checks: ${appendResult.errors.join(" | ")}`
282
- };
283
- }
284
- const withMarker = withLearningsHarvestMarker(raw, appendResult.appended, appendResult.skippedDuplicates);
285
- await fs.writeFile(artifactPath, withMarker, "utf8");
286
- return {
287
- ok: true,
288
- markerWritten: true,
289
- parsedEntries: parsed.entries.length,
290
- appendedEntries: appendResult.appended,
291
- skippedDuplicates: appendResult.skippedDuplicates,
292
- details: parsed.none
293
- ? "Learnings section marked none; harvest marker recorded."
294
- : `Harvested ${appendResult.appended} learning entr${appendResult.appended === 1 ? "y" : "ies"} (${appendResult.skippedDuplicates} duplicate skipped).`
295
- };
296
- }
297
- export async function runAdvanceStage(projectRoot, args, io) {
298
- const flowState = await readFlowState(projectRoot);
299
- if (flowState.currentStage !== args.stage) {
300
- io.stderr.write(`cclaw internal advance-stage: current stage is "${flowState.currentStage}", not "${args.stage}".\n`);
301
- return 1;
302
- }
303
- const schema = stageSchema(args.stage, flowState.track, flowState.discoveryMode, flowState.taskClass ?? null);
304
- const requiredGateIds = schema.requiredGates
305
- .filter((gate) => gate.tier === "required")
306
- .map((gate) => gate.id);
307
- const transitionTargets = getAvailableTransitions(args.stage, flowState.track).map((rule) => rule.to);
308
- const allowedGateIds = new Set(schema.requiredGates.map((gate) => gate.id));
309
- const transitionGuardIds = new Set(transitionTargets
310
- .flatMap((target) => getTransitionGuards(args.stage, target, flowState.track))
311
- .filter((guardId) => !allowedGateIds.has(guardId)));
312
- const selectableGateIds = new Set([...allowedGateIds, ...transitionGuardIds]);
313
- let selectedGateIds = args.passedGateIds.length > 0
314
- ? args.passedGateIds.filter((gateId) => selectableGateIds.has(gateId))
315
- : requiredGateIds;
316
- // if the active stage has an auto-hydratable
317
- // review-loop gate (currently `design.design_architecture_locked`)
318
- // and the artifact already contains a valid review-loop envelope,
319
- // include the gate in selectedGateIds and hydrate evidence in one
320
- // step. This removes the contradiction between "omit from
321
- // --evidence-json so we can auto-hydrate" and "missing
322
- // --evidence-json entries for passed gates".
323
- selectedGateIds = await tryAutoHydrateAndSelectReviewLoopGate(projectRoot, args.stage, flowState.track, requiredGateIds, selectedGateIds, args.evidenceByGate);
324
- const selectedGateIdSet = new Set(selectedGateIds);
325
- const selectedTransitionGuards = selectedGateIds.filter((gateId) => transitionGuardIds.has(gateId));
326
- const blockedReviewRoute = args.stage === "review" && selectedGateIdSet.has("review_verdict_blocked");
327
- const requiredForSelectedRoute = blockedReviewRoute
328
- ? requiredGateIds.filter((gateId) => gateId !== "review_criticals_resolved")
329
- : requiredGateIds;
330
- const missingRequired = requiredForSelectedRoute.filter((gateId) => !selectedGateIdSet.has(gateId));
331
- if (missingRequired.length > 0) {
332
- const autoHydrateGate = AUTO_REVIEW_LOOP_GATE_BY_STAGE[args.stage];
333
- const autoHydrateHint = autoHydrateGate && missingRequired.includes(autoHydrateGate) && (args.stage === "scope" || args.stage === "design")
334
- ? ` Auto-hydratable gate "${autoHydrateGate}" was NOT auto-included because the design artifact is missing the review-loop envelope. Add a \`## ${args.stage === "scope" ? "Scope Outside Voice Loop" : "Design Outside Voice Loop"}\` table (example envelope: ${reviewLoopEnvelopeExample(args.stage)}), or pass --evidence-json='{"${autoHydrateGate}": "<envelope-json>"}' alongside --passed=...,${autoHydrateGate}.`
335
- : "";
336
- io.stderr.write(`cclaw internal advance-stage: required gates not selected as passed: ${missingRequired.join(", ")}.${autoHydrateHint}\n`);
337
- return 1;
338
- }
339
- const mandatory = new Set(schema.mandatoryDelegations);
340
- for (const agent of args.waiveDelegations) {
341
- if (!mandatory.has(agent)) {
342
- io.stderr.write(`cclaw internal advance-stage: cannot waive "${agent}" for stage "${args.stage}" (not mandatory).\n`);
343
- return 1;
344
- }
345
- }
346
- if (args.waiveDelegations.length > 0) {
347
- const waiverReason = args.waiverReason?.trim();
348
- if (!waiverReason) {
349
- io.stderr.write("cclaw internal advance-stage: --waive-delegation requires an explicit non-empty --waiver-reason.\n");
350
- return 1;
351
- }
352
- for (const agent of args.waiveDelegations) {
353
- await appendDelegation(projectRoot, {
354
- stage: args.stage,
355
- agent,
356
- mode: "mandatory",
357
- status: "waived",
358
- waiverReason,
359
- runId: flowState.activeRunId,
360
- fulfillmentMode: "role-switch",
361
- ts: new Date().toISOString()
362
- });
363
- }
364
- }
365
- // hydration + auto-select happens earlier via
366
- // `tryAutoHydrateAndSelectReviewLoopGate`. The previous explicit
367
- // call here was redundant (helper already covered both the
368
- // already-selected and not-yet-selected paths).
369
- const catalog = flowState.stageGateCatalog[args.stage];
370
- const nextPassed = unique([...catalog.passed, ...selectedGateIds]).filter((gateId) => allowedGateIds.has(gateId));
371
- const nextPassedSet = new Set(nextPassed);
372
- const nextBlocked = unique(catalog.blocked.filter((gateId) => !nextPassedSet.has(gateId))).filter((gateId) => allowedGateIds.has(gateId));
373
- const conditional = new Set(catalog.conditional);
374
- const nextTriggered = unique([
375
- ...catalog.triggered.filter((gateId) => conditional.has(gateId)),
376
- ...nextPassed.filter((gateId) => conditional.has(gateId)),
377
- ...nextBlocked.filter((gateId) => conditional.has(gateId))
378
- ]);
379
- const guardEvidenceGateIds = unique([...nextPassed, ...selectedTransitionGuards]);
380
- const missingGuardEvidence = guardEvidenceGateIds.filter((gateId) => {
381
- const existing = flowState.guardEvidence[gateId];
382
- if (typeof existing === "string" && existing.trim().length > 0) {
383
- return false;
384
- }
385
- const provided = args.evidenceByGate[gateId];
386
- return !(typeof provided === "string" && provided.trim().length > 0);
387
- });
388
- if (missingGuardEvidence.length > 0) {
389
- io.stderr.write(`cclaw internal advance-stage: missing --evidence-json entries for passed gates: ${missingGuardEvidence.join(", ")}.\n`);
390
- return 1;
391
- }
392
- const malformedGateEvidence = [];
393
- for (const gateId of nextPassed) {
394
- const provided = args.evidenceByGate[gateId];
395
- const existing = flowState.guardEvidence[gateId];
396
- const effectiveEvidence = typeof provided === "string" && provided.trim().length > 0
397
- ? provided
398
- : typeof existing === "string" && existing.trim().length > 0
399
- ? existing
400
- : "";
401
- const issue = await validateGateEvidenceShape(projectRoot, args.stage, gateId, effectiveEvidence);
402
- if (issue) {
403
- malformedGateEvidence.push(`${gateId}: ${issue}${reviewLoopArtifactFixHint(args.stage, gateId)}`);
404
- }
405
- }
406
- if (malformedGateEvidence.length > 0) {
407
- io.stderr.write(`cclaw internal advance-stage: gate evidence format check failed: ${malformedGateEvidence.join(" | ")}.\n`);
408
- return 1;
409
- }
410
- const nextGuardEvidence = { ...flowState.guardEvidence };
411
- for (const gateId of guardEvidenceGateIds) {
412
- const provided = args.evidenceByGate[gateId];
413
- if (typeof provided === "string" && provided.trim().length > 0) {
414
- nextGuardEvidence[gateId] = provided.trim();
415
- }
416
- }
417
- const nextStageCatalog = {
418
- required: [...catalog.required],
419
- recommended: [...catalog.recommended],
420
- conditional: [...catalog.conditional],
421
- triggered: nextTriggered,
422
- passed: nextPassed,
423
- blocked: nextBlocked
424
- };
425
- const candidateState = {
426
- ...flowState,
427
- guardEvidence: nextGuardEvidence,
428
- stageGateCatalog: {
429
- ...flowState.stageGateCatalog,
430
- [args.stage]: nextStageCatalog
431
- }
432
- };
433
- const validation = await buildValidationReport(projectRoot, candidateState, {
434
- allowBlockedReviewRoute: blockedReviewRoute,
435
- extraStageFlags: args.skipQuestions ? ["--skip-questions"] : undefined
436
- });
437
- if (!validation.ok) {
438
- const delegationFailureCount = validation.delegation.missing.length +
439
- validation.delegation.missingEvidence.length +
440
- validation.delegation.missingDispatchProof.length +
441
- validation.delegation.legacyInferredCompletions.length +
442
- validation.delegation.corruptEventLines.length +
443
- validation.delegation.staleWorkers.length;
444
- const gatesFailureCount = validation.gates.issues.length;
445
- const closureFailureCount = validation.completedStages.issues.length;
446
- const failureCounts = {
447
- delegation: delegationFailureCount,
448
- gates: gatesFailureCount,
449
- closure: closureFailureCount
450
- };
451
- const ledgerForDiag = await readDelegationLedger(projectRoot).catch(() => ({ entries: [] }));
452
- const eventsForDiag = await readDelegationEvents(projectRoot).catch(() => ({ events: [], corruptLines: [] }));
453
- const ledgerEntriesText = await fs.readFile(path.join(projectRoot, ".cclaw/state/delegation-events.jsonl"), "utf8").catch(() => "");
454
- const corruptSnippets = (() => {
455
- if (validation.delegation.corruptEventLines.length === 0)
456
- return [];
457
- const lines = ledgerEntriesText.split(/\r?\n/u);
458
- return validation.delegation.corruptEventLines.slice(0, 3).map((lineNo) => {
459
- const line = lines[lineNo - 1] ?? "";
460
- const sample = line.length > 120 ? `${line.slice(0, 117)}...` : line;
461
- return `line ${lineNo}: ${sample}`;
462
- });
463
- })();
464
- const dispatchProofDetails = validation.delegation.missingDispatchProof.flatMap((agent) => {
465
- const rows = ledgerForDiag.entries.filter((entry) => entry.agent === agent && entry.status === "completed");
466
- return rows.map((row) => `${agent}(spanId=${row.spanId ?? "unknown"})`);
467
- });
468
- const nextActions = [];
469
- if (validation.delegation.missing.length > 0) {
470
- nextActions.push(`Run mandatory delegation(s) for stage "${args.stage}": ${validation.delegation.missing.join(", ")}. These roles are required by the stage schema before advance. If dispatch is impossible, use the waiver fallback only with a user-visible reason: \`node .cclaw/hooks/stage-complete.mjs ${args.stage} --waive-delegation=${validation.delegation.missing.join(",")} --waiver-reason="<why safe>"\`.`);
471
- }
472
- if (validation.delegation.missingEvidence.length > 0) {
473
- nextActions.push(`Role-switch fallback completion needs artifact evidenceRefs naming what the role proved; rerun completion with --evidence-ref=<artifact#anchor> or escalate to a real isolated dispatch surface.`);
474
- }
475
- if (validation.delegation.missingDispatchProof.length > 0) {
476
- nextActions.push(`Isolated completion(s) ${dispatchProofDetails.join(", ") || validation.delegation.missingDispatchProof.join(", ")} lack event-log dispatch proof. The ledger says completed, but .cclaw/state/delegation-events.jsonl must show scheduled -> launched -> acknowledged -> completed with --span-id, --dispatch-id, --dispatch-surface, --agent-definition-path, ackTs, and completedTs before advancing.`);
477
- }
478
- if (validation.delegation.legacyInferredCompletions.length > 0) {
479
- nextActions.push(`Pre-v3 ledger entries found: ${validation.delegation.legacyInferredCompletions.join(", ")}. Run \`node .cclaw/hooks/delegation-record.mjs --rerecord --span-id=<id> --dispatch-id=<id> --dispatch-surface=<surface> --agent-definition-path=<path>\` to upgrade the row to dispatch-proof shape.`);
480
- }
481
- if (validation.delegation.corruptEventLines.length > 0) {
482
- nextActions.push(`delegation-events.jsonl has ${validation.delegation.corruptEventLines.length} corrupt line(s) at ${validation.delegation.corruptEventLines.slice(0, 3).join(", ")}${validation.delegation.corruptEventLines.length > 3 ? ", ..." : ""}; remove or fix them before advancing.`);
483
- }
484
- if (validation.delegation.staleWorkers.length > 0) {
485
- nextActions.push(`Stale scheduled delegations ${validation.delegation.staleWorkers.join(", ")} have no terminal row sharing the same spanId; emit launched/acknowledged/completed (or failed/stale) before advancing.`);
486
- }
487
- if (validation.gates.issues.length > 0) {
488
- nextActions.push("Fix the artifact/gate issue shown in gates.issues, then rerun stage-complete.");
489
- }
490
- if (validation.completedStages.issues.length > 0) {
491
- nextActions.push("Repair previously completed stage gate closure before advancing.");
492
- }
493
- if (args.json) {
494
- io.stdout.write(`${JSON.stringify({
495
- ok: false,
496
- command: "advance-stage",
497
- stage: args.stage,
498
- kind: "validation-failed",
499
- failureCounts,
500
- delegation: validation.delegation,
501
- gates: validation.gates,
502
- completedStages: validation.completedStages,
503
- diagnostics: {
504
- dispatchProofRows: dispatchProofDetails,
505
- corruptEventSamples: corruptSnippets,
506
- unawareEvents: eventsForDiag.corruptLines.length
507
- },
508
- nextActions
509
- })}\n`);
510
- }
511
- io.stderr.write(`cclaw internal advance-stage: validation failed for stage "${args.stage}" (delegation=${failureCounts.delegation}, gates=${failureCounts.gates}, closure=${failureCounts.closure}).\n`);
512
- if (validation.delegation.missing.length > 0) {
513
- io.stderr.write(`- missing delegations: ${validation.delegation.missing.join(", ")}\n`);
514
- io.stderr.write(` next action: run the named agent(s) for this stage, or rerun with --waive-delegation=${validation.delegation.missing.join(",")} --waiver-reason="<why safe>" only when the user accepts the safety trade-off.\n`);
515
- }
516
- if (validation.delegation.missingEvidence.length > 0) {
517
- io.stderr.write(`- role-switch evidence missing: ${validation.delegation.missingEvidence.join(", ")}\n`);
518
- io.stderr.write(` next action: include --evidence-ref=<artifact#anchor> when emitting the completed event so the artifact shows what was reviewed/proved, or escalate to a true isolated dispatch surface.\n`);
519
- }
520
- if (validation.delegation.missingDispatchProof.length > 0) {
521
- io.stderr.write(`- isolated completion lacks dispatch proof: ${dispatchProofDetails.join(", ") || validation.delegation.missingDispatchProof.join(", ")}\n`);
522
- io.stderr.write(` next action: repair the event log proof by emitting scheduled -> launched -> acknowledged -> completed with --span-id, --dispatch-id, --dispatch-surface, --agent-definition-path, ackTs, and completedTs before advancing.\n`);
523
- }
524
- if (validation.delegation.legacyInferredCompletions.length > 0) {
525
- io.stderr.write(`- legacy-inferred completions need rerecord: ${validation.delegation.legacyInferredCompletions.join(", ")}\n`);
526
- io.stderr.write(` next action: \`node .cclaw/hooks/delegation-record.mjs --rerecord --span-id=<id> --dispatch-id=<id> --dispatch-surface=<surface> --agent-definition-path=<path>\`.\n`);
527
- }
528
- if (validation.delegation.corruptEventLines.length > 0) {
529
- io.stderr.write(`- corrupt delegation-events.jsonl line(s): ${validation.delegation.corruptEventLines.slice(0, 3).join(", ")}${validation.delegation.corruptEventLines.length > 3 ? `, ... (+${validation.delegation.corruptEventLines.length - 3})` : ""}\n`);
530
- for (const snippet of corruptSnippets) {
531
- io.stderr.write(` sample: ${snippet}\n`);
532
- }
533
- }
534
- if (validation.delegation.staleWorkers.length > 0) {
535
- io.stderr.write(`- stale scheduled delegations: ${validation.delegation.staleWorkers.join(", ")}\n`);
536
- io.stderr.write(` next action: emit a terminal row (completed/failed/stale) for the same span before advancing.\n`);
537
- }
538
- if (validation.gates.issues.length > 0) {
539
- io.stderr.write(`- gate issues: ${validation.gates.issues.join(" | ")}\n`);
540
- }
541
- if (validation.completedStages.issues.length > 0) {
542
- io.stderr.write(`- completed-stage closure issues: ${validation.completedStages.issues.join(" | ")}\n`);
543
- }
544
- return 1;
545
- }
546
- let approvalRecord = null;
547
- if (args.acceptProactiveWaiver) {
548
- const tokenRaw = args.acceptProactiveWaiverToken?.trim() ?? "";
549
- if (tokenRaw.length === 0) {
550
- io.stderr.write(`cclaw internal advance-stage: --accept-proactive-waiver now requires =<token>. Run \`cclaw-cli internal waiver-grant --stage ${args.stage} --reason "<why safe>"\` to issue one, then rerun with --accept-proactive-waiver=<token>.\n`);
551
- return 2;
552
- }
553
- const consumed = await consumeWaiverToken(projectRoot, {
554
- stage: args.stage,
555
- token: tokenRaw,
556
- consumedBy: "advance-stage"
557
- });
558
- if (!consumed.ok) {
559
- io.stderr.write(`cclaw internal advance-stage: waiver token rejected (${consumed.reason}): ${consumed.detail}. Issue a fresh token via \`cclaw-cli internal waiver-grant --stage ${args.stage} --reason "<why safe>"\`.\n`);
560
- return 2;
561
- }
562
- approvalRecord = consumed.record;
563
- }
564
- const proactiveTrace = await ensureProactiveDelegationTrace(projectRoot, args.stage, {
565
- acceptWaiver: args.acceptProactiveWaiver,
566
- waiverReason: args.acceptProactiveWaiverReason,
567
- approvalToken: approvalRecord?.token,
568
- approvalReason: approvalRecord?.reason,
569
- approvalIssuedAt: approvalRecord?.issuedAt,
570
- discoveryMode: flowState.discoveryMode,
571
- repoSignals: flowState.repoSignals
572
- });
573
- if (proactiveTrace.missingRules.length > 0) {
574
- const missingSummary = proactiveTrace.missingRules
575
- .map((rule) => `${rule.agent} (when: ${rule.when})`)
576
- .join(", ");
577
- const nextAction = "Run the proactive delegations listed above, or rerun stage-complete with " +
578
- "--accept-proactive-waiver [--accept-proactive-waiver-reason=\"<why safe>\"] " +
579
- "after explicit user approval.";
580
- if (args.json) {
581
- io.stdout.write(`${JSON.stringify({
582
- ok: false,
583
- command: "advance-stage",
584
- stage: args.stage,
585
- kind: "proactive-delegations-missing",
586
- proactiveDelegations: proactiveTrace.missingRules.map((rule) => ({
587
- agent: rule.agent,
588
- when: rule.when,
589
- skill: rule.skill ?? null
590
- })),
591
- nextActions: [nextAction]
592
- })}\n`);
593
- }
594
- io.stderr.write(`cclaw internal advance-stage: proactive delegation evidence is missing for stage "${args.stage}": ${missingSummary}.\n`);
595
- io.stderr.write(` next action: ${nextAction}\n`);
596
- return 1;
597
- }
598
- const learningsHarvest = await harvestStageLearnings(projectRoot, args.stage, flowState.track);
599
- if (!learningsHarvest.ok) {
600
- io.stderr.write(`cclaw internal advance-stage: ${learningsHarvest.details}\n`);
601
- return 1;
602
- }
603
- const satisfiedGuards = new Set([...nextPassed, ...selectedTransitionGuards]);
604
- const successor = resolveSuccessorTransition(args.stage, flowState.track, transitionTargets, satisfiedGuards, new Set(selectedTransitionGuards));
605
- const completedStages = blockedReviewRoute
606
- ? flowState.completedStages.filter((finished) => finished !== args.stage)
607
- : flowState.completedStages.includes(args.stage)
608
- ? [...flowState.completedStages]
609
- : [...flowState.completedStages, args.stage];
610
- let completedStageMeta = flowState.completedStageMeta ?? {};
611
- if (!blockedReviewRoute && !flowState.completedStages.includes(args.stage)) {
612
- completedStageMeta = {
613
- ...completedStageMeta,
614
- [args.stage]: { completedAt: new Date().toISOString() }
615
- };
616
- }
617
- const interactionHints = nextInteractionHints(flowState, args, successor);
618
- const finalState = {
619
- ...candidateState,
620
- completedStages,
621
- completedStageMeta,
622
- currentStage: successor ?? args.stage,
623
- interactionHints
624
- };
625
- await writeFlowState(projectRoot, finalState, { writerSubsystem: "advance-stage" });
626
- if (args.quiet) {
627
- io.stdout.write(`${JSON.stringify({
628
- ok: true,
629
- command: "stage-complete",
630
- stage: args.stage,
631
- completedStages: finalState.completedStages,
632
- currentStage: finalState.currentStage,
633
- runId: finalState.activeRunId
634
- })}\n`);
635
- }
636
- else {
637
- io.stdout.write(`${JSON.stringify({
638
- ok: true,
639
- command: "advance-stage",
640
- stage: args.stage,
641
- nextStage: successor,
642
- currentStage: finalState.currentStage,
643
- completedStages: finalState.completedStages,
644
- skipQuestionsHint: args.skipQuestions,
645
- learnings: {
646
- parsed: learningsHarvest.parsedEntries,
647
- appended: learningsHarvest.appendedEntries,
648
- skippedDuplicates: learningsHarvest.skippedDuplicates,
649
- markerWritten: learningsHarvest.markerWritten,
650
- details: learningsHarvest.details
651
- }
652
- }, null, 2)}\n`);
653
- }
654
- return 0;
655
- }
@@ -1,8 +0,0 @@
1
- import type { CancelRunArgs } from "./parsers.js";
2
- import type { Writable } from "node:stream";
3
- interface InternalIo {
4
- stdout: Writable;
5
- stderr: Writable;
6
- }
7
- export declare function runCancelRun(projectRoot: string, args: CancelRunArgs, io: InternalIo): Promise<number>;
8
- export {};