cool-workflow 0.1.98 → 0.2.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 (306) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/README.md +11 -2
  4. package/apps/architecture-review/app.json +1 -1
  5. package/apps/architecture-review-fast/app.json +1 -1
  6. package/apps/end-to-end-golden-path/app.json +1 -1
  7. package/apps/pr-review-fix-ci/app.json +1 -1
  8. package/apps/release-cut/app.json +1 -1
  9. package/apps/research-synthesis/app.json +1 -1
  10. package/dist/cli/dispatch.js +236 -0
  11. package/dist/cli/entry.js +120 -0
  12. package/dist/cli/io.js +21 -4
  13. package/dist/cli/parseargv.js +157 -0
  14. package/dist/cli.js +6 -33
  15. package/dist/core/capability-table.js +3534 -0
  16. package/dist/core/format/help.js +314 -0
  17. package/dist/{state-explosion/format.js → core/format/state-explosion-text.js} +10 -1
  18. package/dist/core/hash.js +137 -0
  19. package/dist/core/multi-agent/candidate-scoring.js +219 -0
  20. package/dist/core/multi-agent/collaboration.js +481 -0
  21. package/dist/core/multi-agent/coordinator.js +515 -0
  22. package/dist/core/multi-agent/eval-replay.js +306 -0
  23. package/dist/core/multi-agent/runtime.js +929 -0
  24. package/dist/core/multi-agent/topology.js +298 -0
  25. package/dist/core/multi-agent/trust-policy.js +197 -0
  26. package/dist/core/pipeline/commit-gate.js +320 -0
  27. package/dist/{pipeline-contract.js → core/pipeline/contract.js} +24 -37
  28. package/dist/core/pipeline/dispatch.js +103 -0
  29. package/dist/core/pipeline/drive-decide.js +227 -0
  30. package/dist/core/pipeline/error-feedback.js +161 -0
  31. package/dist/core/pipeline/loop-expansion.js +124 -0
  32. package/dist/{result-normalize.js → core/pipeline/result-normalize.js} +14 -37
  33. package/dist/core/pipeline/runner.js +230 -0
  34. package/dist/{contract-migration.js → core/state/contract-migration.js} +68 -92
  35. package/dist/{state-migrations.js → core/state/migrations.js} +103 -96
  36. package/dist/core/state/node-projection.js +95 -0
  37. package/dist/core/state/node-snapshot.js +230 -0
  38. package/dist/core/state/run-paths.js +93 -0
  39. package/dist/{schema-validate.js → core/state/schema-validate.js} +35 -28
  40. package/dist/core/state/schema.js +50 -0
  41. package/dist/core/state/state-explosion/digest.js +243 -0
  42. package/dist/core/state/state-explosion/graph.js +527 -0
  43. package/dist/{state-explosion → core/state/state-explosion}/helpers.js +34 -3
  44. package/dist/core/state/state-explosion/report.js +187 -0
  45. package/dist/{state-explosion → core/state/state-explosion}/size.js +25 -7
  46. package/dist/{state-node.js → core/state/state-node.js} +90 -113
  47. package/dist/core/state/types.js +19 -0
  48. package/dist/{validation.js → core/state/validation.js} +64 -131
  49. package/dist/core/trust/evidence-grounding.js +134 -0
  50. package/dist/core/trust/ledger.js +199 -0
  51. package/dist/{telemetry-attestation.js → core/trust/telemetry-attestation.js} +94 -68
  52. package/dist/core/trust/telemetry-ledger.js +127 -0
  53. package/dist/core/types.js +20 -0
  54. package/dist/core/version.js +16 -0
  55. package/dist/{workflow-app-framework.js → core/workflow-apps/app-schema.js} +337 -426
  56. package/dist/mcp/dispatch.js +104 -0
  57. package/dist/mcp/server.js +144 -0
  58. package/dist/mcp-server.js +6 -84
  59. package/dist/{agent-config.js → shell/agent-config.js} +118 -71
  60. package/dist/shell/app-run-cli.js +88 -0
  61. package/dist/shell/audit-cli.js +259 -0
  62. package/dist/shell/audit-provenance.js +83 -0
  63. package/dist/shell/candidate-scoring-io.js +459 -0
  64. package/dist/shell/collaboration-io.js +264 -0
  65. package/dist/shell/commit-summary.js +104 -0
  66. package/dist/shell/commit.js +290 -0
  67. package/dist/shell/coordinator-io.js +476 -0
  68. package/dist/shell/demo-cli.js +19 -0
  69. package/dist/shell/dispatch.js +162 -0
  70. package/dist/{doctor.js → shell/doctor.js} +123 -56
  71. package/dist/shell/drive.js +873 -0
  72. package/dist/shell/error-feedback-io.js +305 -0
  73. package/dist/shell/eval-io.js +473 -0
  74. package/dist/{multi-agent-eval/format.js → shell/eval-text.js} +78 -49
  75. package/dist/{evidence-reasoning.js → shell/evidence-reasoning.js} +124 -255
  76. package/dist/shell/exec-backend-cli.js +88 -0
  77. package/dist/shell/execution-backend/agent.js +475 -0
  78. package/dist/shell/execution-backend/ci.js +15 -0
  79. package/dist/shell/execution-backend/container.js +69 -0
  80. package/dist/shell/execution-backend/envelopes.js +55 -0
  81. package/dist/shell/execution-backend/local.js +113 -0
  82. package/dist/shell/execution-backend/probes.js +175 -0
  83. package/dist/shell/execution-backend/registry.js +402 -0
  84. package/dist/shell/execution-backend/remote.js +128 -0
  85. package/dist/shell/execution-backend/types.js +11 -0
  86. package/dist/shell/feedback-cli.js +81 -0
  87. package/dist/shell/feedback-operations.js +48 -0
  88. package/dist/shell/fs-atomic.js +276 -0
  89. package/dist/shell/harness.js +98 -0
  90. package/dist/shell/ledger-cli.js +212 -0
  91. package/dist/shell/ledger-io.js +169 -0
  92. package/dist/shell/man-cli.js +89 -0
  93. package/dist/shell/metrics-cli.js +98 -0
  94. package/dist/shell/multi-agent-cli.js +1002 -0
  95. package/dist/shell/multi-agent-host.js +563 -0
  96. package/dist/shell/multi-agent-io.js +387 -0
  97. package/dist/{multi-agent-operator-ux.js → shell/multi-agent-operator-ux.js} +234 -191
  98. package/dist/shell/node-store.js +124 -0
  99. package/dist/{observability/format.js → shell/observability-format.js} +7 -1
  100. package/dist/{observability/intake.js → shell/observability-intake.js} +79 -56
  101. package/dist/{observability.js → shell/observability.js} +159 -332
  102. package/dist/{onramp.js → shell/onramp.js} +11 -0
  103. package/dist/{operator-ux/format.js → shell/operator-ux-text.js} +250 -239
  104. package/dist/shell/operator-ux.js +431 -0
  105. package/dist/shell/orchestrator.js +231 -0
  106. package/dist/shell/pipeline-cli.js +667 -0
  107. package/dist/shell/pipeline.js +217 -0
  108. package/dist/shell/reclamation-io.js +1366 -0
  109. package/dist/shell/registry-cli.js +329 -0
  110. package/dist/{remote-source.js → shell/remote-source.js} +2 -2
  111. package/dist/shell/report-cli.js +101 -0
  112. package/dist/shell/report-view-cli.js +117 -0
  113. package/dist/{orchestrator → shell}/report.js +289 -282
  114. package/dist/shell/reporter.js +62 -0
  115. package/dist/shell/run-export-cli.js +106 -0
  116. package/dist/shell/run-export.js +680 -0
  117. package/dist/shell/run-registry-io.js +1014 -0
  118. package/dist/shell/run-store.js +164 -0
  119. package/dist/{sandbox-profile.js → shell/sandbox-profile.js} +134 -95
  120. package/dist/{scheduler.js → shell/scheduler-io.js} +248 -48
  121. package/dist/shell/scheduling-io.js +311 -0
  122. package/dist/shell/state-cli.js +181 -0
  123. package/dist/shell/state-explosion-cli.js +197 -0
  124. package/dist/shell/telemetry-cli.js +85 -0
  125. package/dist/{telemetry-demo.js → shell/telemetry-demo.js} +149 -119
  126. package/dist/shell/telemetry-ledger-io.js +132 -0
  127. package/dist/{term.js → shell/term.js} +36 -46
  128. package/dist/shell/topology-io.js +361 -0
  129. package/dist/shell/trust-audit.js +471 -0
  130. package/dist/{multi-agent-trust.js → shell/trust-policy-io.js} +67 -205
  131. package/dist/shell/verifier.js +48 -0
  132. package/dist/shell/workbench-host.js +250 -0
  133. package/dist/shell/workbench-text.js +18 -0
  134. package/dist/shell/workbench.js +175 -0
  135. package/dist/shell/worker-cli.js +124 -0
  136. package/dist/shell/worker-isolation.js +852 -0
  137. package/dist/shell/workflow-app-loader.js +650 -0
  138. package/docs/agent-delegation-drive.7.md +2 -0
  139. package/docs/cli-mcp-parity.7.md +280 -219
  140. package/docs/contract-migration-tooling.7.md +2 -0
  141. package/docs/control-plane-scheduling.7.md +2 -0
  142. package/docs/durable-state-and-locking.7.md +2 -0
  143. package/docs/evidence-adoption-reasoning-chain.7.md +2 -0
  144. package/docs/execution-backends.7.md +2 -0
  145. package/docs/multi-agent-cli-mcp-surface.7.md +2 -0
  146. package/docs/multi-agent-eval-replay-harness.7.md +2 -0
  147. package/docs/multi-agent-operator-ux.7.md +2 -0
  148. package/docs/node-snapshot-diff-replay.7.md +2 -0
  149. package/docs/observability-cost-accounting.7.md +2 -0
  150. package/docs/project-index.md +132 -71
  151. package/docs/real-execution-backends.7.md +2 -0
  152. package/docs/release-and-migration.7.md +2 -0
  153. package/docs/release-tooling.7.md +2 -0
  154. package/docs/run-registry-control-plane.7.md +2 -0
  155. package/docs/run-retention-reclamation.7.md +23 -0
  156. package/docs/state-explosion-management.7.md +2 -0
  157. package/docs/team-collaboration.7.md +2 -0
  158. package/docs/web-desktop-workbench.7.md +2 -0
  159. package/manifest/plugin.manifest.json +1 -1
  160. package/manifest/source-context-profiles.json +9 -13
  161. package/package.json +1 -1
  162. package/scripts/agents/cw-attest-wrap.js +2 -2
  163. package/scripts/bump-version.js +4 -3
  164. package/scripts/canonical-apps.js +4 -4
  165. package/scripts/dogfood-architecture-review.js +2 -3
  166. package/scripts/dogfood-release.js +3 -3
  167. package/scripts/gen-parity-doc.js +15 -2
  168. package/scripts/golden-path.js +4 -4
  169. package/scripts/onramp-check.js +1 -1
  170. package/scripts/parity-check.js +38 -21
  171. package/scripts/release-flow.js +2 -2
  172. package/scripts/sync-project-index.js +51 -27
  173. package/scripts/validate-run-state-schema.js +2 -2
  174. package/scripts/version-sync-check.js +30 -30
  175. package/dist/candidate-scoring.js +0 -729
  176. package/dist/capability-core.js +0 -1189
  177. package/dist/capability-registry.js +0 -885
  178. package/dist/cli/command-surface.js +0 -494
  179. package/dist/cli/format.js +0 -56
  180. package/dist/cli/handlers/audit.js +0 -82
  181. package/dist/cli/handlers/blackboard.js +0 -81
  182. package/dist/cli/handlers/candidate.js +0 -40
  183. package/dist/cli/handlers/clones.js +0 -34
  184. package/dist/cli/handlers/collaboration.js +0 -61
  185. package/dist/cli/handlers/eval.js +0 -40
  186. package/dist/cli/handlers/ledger.js +0 -169
  187. package/dist/cli/handlers/maintenance.js +0 -107
  188. package/dist/cli/handlers/multi-agent.js +0 -165
  189. package/dist/cli/handlers/node.js +0 -41
  190. package/dist/cli/handlers/operational.js +0 -155
  191. package/dist/cli/handlers/operator.js +0 -146
  192. package/dist/cli/handlers/registry.js +0 -68
  193. package/dist/cli/handlers/run.js +0 -153
  194. package/dist/cli/handlers/scheduling.js +0 -132
  195. package/dist/cli/handlers/workbench.js +0 -41
  196. package/dist/cli/handlers/worker.js +0 -45
  197. package/dist/cli/run-summary.js +0 -45
  198. package/dist/clones.js +0 -162
  199. package/dist/collaboration.js +0 -726
  200. package/dist/commit.js +0 -592
  201. package/dist/compare.js +0 -18
  202. package/dist/coordinator/classify.js +0 -45
  203. package/dist/coordinator/paths.js +0 -42
  204. package/dist/coordinator/util.js +0 -126
  205. package/dist/coordinator.js +0 -990
  206. package/dist/daemon.js +0 -44
  207. package/dist/dispatch.js +0 -250
  208. package/dist/drive.js +0 -864
  209. package/dist/error-feedback.js +0 -419
  210. package/dist/evidence-grounding.js +0 -184
  211. package/dist/execution-backend/agent.js +0 -354
  212. package/dist/execution-backend/probes.js +0 -112
  213. package/dist/execution-backend/util.js +0 -47
  214. package/dist/execution-backend.js +0 -961
  215. package/dist/gates.js +0 -48
  216. package/dist/harness.js +0 -61
  217. package/dist/ledger.js +0 -313
  218. package/dist/loop-expansion.js +0 -60
  219. package/dist/mcp/tool-call.js +0 -470
  220. package/dist/mcp/tool-definitions.js +0 -1066
  221. package/dist/mcp-surface.js +0 -30
  222. package/dist/multi-agent/graph.js +0 -84
  223. package/dist/multi-agent/helpers.js +0 -141
  224. package/dist/multi-agent/ids.js +0 -20
  225. package/dist/multi-agent/paths.js +0 -22
  226. package/dist/multi-agent-eval/normalize.js +0 -51
  227. package/dist/multi-agent-eval.js +0 -678
  228. package/dist/multi-agent-host.js +0 -777
  229. package/dist/multi-agent.js +0 -984
  230. package/dist/node-projection.js +0 -59
  231. package/dist/node-snapshot.js +0 -260
  232. package/dist/operator-ux.js +0 -631
  233. package/dist/orchestrator/app-operations.js +0 -211
  234. package/dist/orchestrator/audit-operations.js +0 -182
  235. package/dist/orchestrator/candidate-operations.js +0 -117
  236. package/dist/orchestrator/cli-options.js +0 -294
  237. package/dist/orchestrator/collaboration-operations.js +0 -86
  238. package/dist/orchestrator/feedback-operations.js +0 -81
  239. package/dist/orchestrator/host-operations.js +0 -78
  240. package/dist/orchestrator/lifecycle-operations.js +0 -650
  241. package/dist/orchestrator/migration-operations.js +0 -44
  242. package/dist/orchestrator/multi-agent-operations.js +0 -362
  243. package/dist/orchestrator/topology-operations.js +0 -84
  244. package/dist/orchestrator.js +0 -925
  245. package/dist/pipeline-runner.js +0 -285
  246. package/dist/reclamation/hash.js +0 -72
  247. package/dist/reclamation.js +0 -812
  248. package/dist/reporter.js +0 -67
  249. package/dist/run-export.js +0 -815
  250. package/dist/run-registry/derive.js +0 -175
  251. package/dist/run-registry/format.js +0 -124
  252. package/dist/run-registry/gc.js +0 -251
  253. package/dist/run-registry/policy.js +0 -16
  254. package/dist/run-registry/queue.js +0 -115
  255. package/dist/run-registry.js +0 -850
  256. package/dist/run-state-schema.js +0 -68
  257. package/dist/scheduling.js +0 -184
  258. package/dist/state-explosion.js +0 -1014
  259. package/dist/state.js +0 -367
  260. package/dist/telemetry-ledger.js +0 -196
  261. package/dist/topology.js +0 -565
  262. package/dist/triggers.js +0 -184
  263. package/dist/trust-audit.js +0 -644
  264. package/dist/types/blackboard.js +0 -2
  265. package/dist/types/candidate.js +0 -2
  266. package/dist/types/collaboration.js +0 -2
  267. package/dist/types/core.js +0 -2
  268. package/dist/types/drive.js +0 -10
  269. package/dist/types/error-feedback.js +0 -2
  270. package/dist/types/evidence-reasoning.js +0 -2
  271. package/dist/types/execution-backend.js +0 -2
  272. package/dist/types/multi-agent.js +0 -2
  273. package/dist/types/observability.js +0 -2
  274. package/dist/types/pipeline.js +0 -2
  275. package/dist/types/reclamation.js +0 -8
  276. package/dist/types/report-bundle.js +0 -6
  277. package/dist/types/result.js +0 -2
  278. package/dist/types/run-registry.js +0 -2
  279. package/dist/types/run.js +0 -2
  280. package/dist/types/sandbox.js +0 -2
  281. package/dist/types/schedule.js +0 -2
  282. package/dist/types/state-node.js +0 -2
  283. package/dist/types/topology.js +0 -2
  284. package/dist/types/trust.js +0 -2
  285. package/dist/types/workbench.js +0 -2
  286. package/dist/types/worker.js +0 -2
  287. package/dist/types/workflow-app.js +0 -2
  288. package/dist/types.js +0 -44
  289. package/dist/util/fingerprint.js +0 -19
  290. package/dist/util/fingerprint.test.js +0 -27
  291. package/dist/verifier.js +0 -78
  292. package/dist/version.js +0 -8
  293. package/dist/workbench-host.js +0 -192
  294. package/dist/workbench.js +0 -192
  295. package/dist/worker-accept/acceptance.js +0 -114
  296. package/dist/worker-accept/blackboard-fanout.js +0 -80
  297. package/dist/worker-accept/blackboard-linkage.js +0 -19
  298. package/dist/worker-accept/context.js +0 -2
  299. package/dist/worker-accept/telemetry-ledger.js +0 -126
  300. package/dist/worker-accept/validation.js +0 -77
  301. package/dist/worker-accept/verifier-completion.js +0 -73
  302. package/dist/worker-isolation/helpers.js +0 -51
  303. package/dist/worker-isolation/paths.js +0 -46
  304. package/dist/worker-isolation.js +0 -656
  305. package/dist/workflow-api.js +0 -131
  306. /package/dist/{types → core/types}/boundary.js +0 -0
@@ -1,650 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.plan = plan;
7
- exports.dispatch = dispatch;
8
- exports.recordResult = recordResult;
9
- exports.recordWorkerOutput = recordWorkerOutput;
10
- exports.recordWorkerFailure = recordWorkerFailure;
11
- exports.checkState = checkState;
12
- exports.commit = commit;
13
- // Core run-lifecycle operations (v0.1.40 self-audit P3 router pattern).
14
- //
15
- // The engine core — plan / dispatch / recordResult / worker-output / commit /
16
- // checkState — carved out of CoolWorkflowRunner so the runner is a pure router.
17
- // plan() receives an already-resolved workflow app record (the runner still owns
18
- // app loading, which is instance-stateful). Behavior is identical to the inline
19
- // implementations; only the location changed.
20
- const node_crypto_1 = __importDefault(require("node:crypto"));
21
- const node_fs_1 = __importDefault(require("node:fs"));
22
- const node_path_1 = __importDefault(require("node:path"));
23
- const state_1 = require("../state");
24
- const report_1 = require("./report");
25
- const cli_options_1 = require("./cli-options");
26
- const harness_1 = require("../harness");
27
- const workflow_app_framework_1 = require("../workflow-app-framework");
28
- const workflow_api_1 = require("../workflow-api");
29
- const observability_1 = require("../observability");
30
- const compare_1 = require("../compare");
31
- const loop_expansion_1 = require("../loop-expansion");
32
- const evidence_grounding_1 = require("../evidence-grounding");
33
- const dispatch_1 = require("../dispatch");
34
- const verifier_1 = require("../verifier");
35
- const trust_audit_1 = require("../trust-audit");
36
- const multi_agent_1 = require("../multi-agent");
37
- const topology_1 = require("../topology");
38
- const state_node_1 = require("../state-node");
39
- const pipeline_contract_1 = require("../pipeline-contract");
40
- const pipeline_runner_1 = require("../pipeline-runner");
41
- const commit_1 = require("../commit");
42
- const error_feedback_1 = require("../error-feedback");
43
- const trust_audit_2 = require("../trust-audit");
44
- const result_normalize_1 = require("../result-normalize");
45
- const state_explosion_1 = require("../state-explosion");
46
- const worker_isolation_1 = require("../worker-isolation");
47
- function plan(appRecord, options) {
48
- const workflow = appRecord.app.workflow;
49
- const inputs = normalizeInputs(options);
50
- validateInputs(workflow, inputs);
51
- // Fold declared defaults: a missing OPTIONAL input renders as its declared
52
- // default (or empty), so a task prompt referencing it never leaks a literal
53
- // "{{name}}" placeholder into the agent's worker input.
54
- for (const declared of workflow.inputs || []) {
55
- if ((0, cli_options_1.isMissing)(inputs[declared.name]))
56
- inputs[declared.name] = declared.default ?? "";
57
- }
58
- const cwd = node_path_1.default.resolve(String(inputs.cwd || inputs.repo || process.cwd()));
59
- // A caller (e.g. an inline sub-workflow task) may inject a DETERMINISTIC run id so
60
- // the child run id is reproducible across re-runs; otherwise mint one. `runId` is
61
- // never a declared workflow input, so strip it from inputs to keep run.inputs (and
62
- // the digests derived from it) clean — POLA for every normal plan.
63
- const injectedRunId = typeof options.runId === "string" && options.runId.trim() ? options.runId.trim() : undefined;
64
- delete inputs.runId;
65
- const runId = injectedRunId || createRunId(workflow.id);
66
- const runDir = node_path_1.default.join(cwd, ".cw", "runs", runId);
67
- const paths = (0, state_1.createRunPaths)(runDir);
68
- (0, state_1.ensureRunDirs)(paths);
69
- const tasks = flattenTasks(workflow, inputs);
70
- const run = {
71
- schemaVersion: 1,
72
- id: runId,
73
- createdAt: new Date().toISOString(),
74
- updatedAt: new Date().toISOString(),
75
- cwd,
76
- workflow: {
77
- id: workflow.id,
78
- title: workflow.title,
79
- summary: workflow.summary || "",
80
- limits: workflow.limits,
81
- app: (0, workflow_app_framework_1.workflowAppRunMetadata)(appRecord)
82
- },
83
- inputs,
84
- loopStage: "interpret",
85
- phases: workflow.phases.map((phase) => ({
86
- id: phase.id || (0, workflow_api_1.slugify)(phase.name),
87
- name: phase.name,
88
- status: "pending",
89
- taskIds: phase.tasks.map((task) => task.id),
90
- // parallel() DSL: the drive loop reads this to size its concurrent round.
91
- ...(phase.mode ? { mode: phase.mode } : {}),
92
- // loop() DSL: the ORIGIN phase carries the loop spec + round 1; the expander
93
- // appends round-2+ phases after each round (loop-expansion / maybeExpandLoop).
94
- ...(phase.loop ? { loop: phase.loop, loopRound: 1 } : {})
95
- })),
96
- tasks,
97
- dispatches: [],
98
- commits: [],
99
- paths,
100
- nodes: [],
101
- contracts: [],
102
- feedback: [],
103
- audit: {
104
- schemaVersion: 1,
105
- eventLogPath: paths.auditDir ? node_path_1.default.join(paths.auditDir, "events.jsonl") : undefined,
106
- summaryPath: paths.auditDir ? node_path_1.default.join(paths.auditDir, "summary.json") : undefined,
107
- indexPath: paths.auditDir ? node_path_1.default.join(paths.auditDir, "index.json") : undefined
108
- },
109
- workers: [],
110
- sandboxProfiles: [],
111
- candidates: [],
112
- candidateSelections: [],
113
- multiAgent: {
114
- schemaVersion: 1,
115
- runs: [],
116
- roles: [],
117
- groups: [],
118
- memberships: [],
119
- fanouts: [],
120
- fanins: []
121
- },
122
- blackboard: {
123
- schemaVersion: 1,
124
- boards: [],
125
- topics: [],
126
- messages: [],
127
- contexts: [],
128
- artifacts: [],
129
- snapshots: [],
130
- decisions: []
131
- },
132
- topologies: {
133
- schemaVersion: 1,
134
- runs: []
135
- }
136
- };
137
- (0, trust_audit_1.ensureTrustAudit)(run);
138
- (0, multi_agent_1.ensureMultiAgentState)(run);
139
- (0, topology_1.ensureTopologyState)(run);
140
- (0, harness_1.writeTaskFiles)(run);
141
- // Use app's custom pipeline if defined; fall back to default (v0.1.56).
142
- const defaultContract = (0, pipeline_contract_1.createDefaultPipelineContract)();
143
- const appPipeline = appRecord.app.pipeline;
144
- const contract = appPipeline
145
- ? (0, state_node_1.upsertRunContract)(run, { ...defaultContract, ...appPipeline, id: defaultContract.id })
146
- : (0, state_node_1.upsertRunContract)(run, defaultContract);
147
- const inputNode = (0, state_node_1.appendRunNode)(run, (0, state_node_1.createStateNode)({
148
- id: `${run.id}:input`,
149
- kind: "input",
150
- status: "completed",
151
- loopStage: "interpret",
152
- outputs: run.inputs,
153
- artifacts: [{ id: "state", kind: "json", path: run.paths.state }],
154
- contractId: contract.id,
155
- metadata: { workflowId: workflow.id, app: (0, workflow_app_framework_1.workflowAppRunMetadata)(appRecord) }
156
- }));
157
- (0, state_1.saveCheckpoint)(run);
158
- const pipeline = (0, pipeline_runner_1.createPipelineRunner)({ contractId: contract.id, persist: false });
159
- for (const task of run.tasks) {
160
- const taskResult = pipeline.runPipelineStage(run, "plan", inputNode.id, {
161
- outputNodeId: `${run.id}:task:${task.id}`,
162
- outputStatus: "pending",
163
- loopStage: "interpret",
164
- artifacts: [{ id: "task", kind: "markdown", path: task.taskPath }],
165
- metadata: {
166
- workflowId: workflow.id,
167
- appId: appRecord.app.id,
168
- appVersion: appRecord.app.version,
169
- taskId: task.id,
170
- phase: task.phase,
171
- taskKind: task.kind,
172
- requiresEvidence: task.requiresEvidence,
173
- sandboxProfileId: task.sandboxProfileId
174
- }
175
- });
176
- task.stateNodeId = taskResult.outputNodeId;
177
- }
178
- (0, report_1.writeReport)(run);
179
- (0, commit_1.commitState)(run, "initial-plan");
180
- (0, state_1.saveCheckpoint)(run);
181
- return run;
182
- }
183
- /** `options.persistState === false` (concurrent-round callers ONLY — never from
184
- * a CLI/MCP arg bag) skips commitState/saveCheckpoint/writeReport on every
185
- * branch, success or error, so a caller driving many tasks through one
186
- * in-memory `run` can defer the disk flush to a single call at round end
187
- * instead of once per task. Default (absent) preserves today's exact
188
- * per-call persistence. */
189
- function dispatch(run, options) {
190
- const persistState = options.persistState !== false;
191
- try {
192
- const manifest = (0, dispatch_1.createDispatchManifest)(run, (0, cli_options_1.numberOption)(options.limit), {
193
- sandboxProfileId: (0, cli_options_1.stringOption)(options.sandbox) || (0, cli_options_1.stringOption)(options.sandboxProfile) || (0, cli_options_1.stringOption)(options.sandboxProfileId),
194
- backendId: (0, cli_options_1.stringOption)(options.backend) || (0, cli_options_1.stringOption)(options.backendId) || (0, cli_options_1.stringOption)(options.executionBackend),
195
- multiAgentRunId: (0, cli_options_1.stringOption)(options.multiAgentRun || options.multiAgentRunId || options["multi-agent-run"]),
196
- multiAgentGroupId: (0, cli_options_1.stringOption)(options.multiAgentGroup || options.multiAgentGroupId || options.group || options["multi-agent-group"]),
197
- multiAgentRoleId: (0, cli_options_1.stringOption)(options.multiAgentRole || options.multiAgentRoleId || options.role || options["multi-agent-role"]),
198
- multiAgentFanoutId: (0, cli_options_1.stringOption)(options.multiAgentFanout || options.multiAgentFanoutId || options.fanout || options["multi-agent-fanout"])
199
- });
200
- run.loopStage = "act";
201
- if (persistState) {
202
- if (manifest.dispatchId)
203
- (0, commit_1.commitState)(run, `dispatch:${manifest.dispatchId}`);
204
- (0, state_1.saveCheckpoint)(run);
205
- (0, report_1.writeReport)(run);
206
- }
207
- return manifest;
208
- }
209
- catch (error) {
210
- if ((0, cli_options_1.isSandboxProfileError)(error)) {
211
- run.loopStage = "adjust";
212
- (0, error_feedback_1.recordFeedback)(run, {
213
- source: "cli",
214
- error: {
215
- code: error.code,
216
- message: error.message,
217
- at: new Date().toISOString(),
218
- path: error.path,
219
- retryable: false,
220
- details: error.details
221
- },
222
- retryable: false,
223
- metadata: { sandboxProfileId: (0, cli_options_1.stringOption)(options.sandbox) || (0, cli_options_1.stringOption)(options.sandboxProfile) || (0, cli_options_1.stringOption)(options.sandboxProfileId) }
224
- }, { persist: false });
225
- if (persistState) {
226
- (0, report_1.writeReport)(run);
227
- (0, state_1.saveCheckpoint)(run);
228
- }
229
- }
230
- throw error;
231
- }
232
- }
233
- function recordResult(run, taskId, resultPath, options = {}) {
234
- const task = run.tasks.find((candidate) => candidate.id === taskId);
235
- if (!task)
236
- throw new Error(`Unknown task id for run ${run.id}: ${taskId}`);
237
- // Host-attested token usage (v0.1.31), if the caller supplied it. CW records
238
- // it verbatim as provenance and NEVER synthesizes it; absent ⇒ `unreported`.
239
- const usage = (0, observability_1.parseUsageFromArgs)(options, new Date().toISOString());
240
- try {
241
- (0, verifier_1.assertTaskCanComplete)(run, task);
242
- const absoluteResultPath = node_path_1.default.resolve(resultPath);
243
- if (/^\/(etc|bin|sbin|usr|Library|System|Applications|boot|dev|proc|sys|root|var\/log|var\/run)\//.test(absoluteResultPath)) {
244
- throw new Error(`Result path must not be a system directory: ${resultPath}`);
245
- }
246
- if (!node_fs_1.default.existsSync(absoluteResultPath)) {
247
- throw new Error(`Result file does not exist: ${absoluteResultPath}`);
248
- }
249
- const rawResult = node_fs_1.default.readFileSync(absoluteResultPath, "utf8");
250
- run.loopStage = "observe";
251
- const parsedResult = (0, verifier_1.parseResultEnvelope)(rawResult);
252
- run.loopStage = "adjust";
253
- (0, verifier_1.validateResultEnvelope)(task, parsedResult);
254
- const unresolved = (0, evidence_grounding_1.unresolvedFileEvidence)(parsedResult.evidence, [run.cwd, process.cwd(), run.paths.runDir, node_path_1.default.dirname(absoluteResultPath)]);
255
- if (unresolved.length) {
256
- throw new Error(`Result cites file evidence that does not resolve on disk: ${unresolved.join(", ")}`);
257
- }
258
- const destination = node_path_1.default.join(run.paths.resultsDir, `${(0, state_1.safeFileName)(taskId)}.md`);
259
- node_fs_1.default.copyFileSync(absoluteResultPath, destination);
260
- task.status = "completed";
261
- task.completedAt = new Date().toISOString();
262
- task.resultPath = destination;
263
- task.loopStage = "observe";
264
- task.result = parsedResult;
265
- if (usage)
266
- task.usage = usage;
267
- const resultNode = (0, state_node_1.appendRunNode)(run, (0, state_node_1.createStateNode)({
268
- id: `${run.id}:result:${task.id}`,
269
- kind: "result",
270
- status: "completed",
271
- loopStage: "observe",
272
- inputs: { taskId: task.id, dispatchId: task.dispatchId },
273
- outputs: parsedResult,
274
- artifacts: [{ id: "result", kind: "markdown", path: destination }],
275
- evidence: parsedResult.evidence.map((entry, index) => ({
276
- id: `result:${index + 1}`,
277
- source: "cw:result",
278
- locator: entry,
279
- summary: entry
280
- })),
281
- parents: task.dispatchId ? [`${run.id}:dispatch:${task.dispatchId}`] : [task.stateNodeId || `${run.id}:task:${task.id}`],
282
- contractId: pipeline_contract_1.DEFAULT_PIPELINE_CONTRACT_ID,
283
- metadata: {
284
- taskId: task.id,
285
- // Empty-capture warning (v0.1.42): surfaced, never silently passed.
286
- ...((0, result_normalize_1.isEmptyCapture)(parsedResult) ? { captureWarning: "no findings or evidence captured from result.md" } : {})
287
- }
288
- }));
289
- task.resultNodeId = resultNode.id;
290
- if ((0, result_normalize_1.isEmptyCapture)(parsedResult)) {
291
- (0, trust_audit_2.recordTrustAuditEvent)(run, {
292
- kind: "worker.capture-warning",
293
- decision: "recorded",
294
- source: "cw-validated",
295
- taskId: task.id,
296
- nodeId: resultNode.id,
297
- metadata: { reason: "no findings or evidence captured from result.md", resultPath: destination }
298
- });
299
- }
300
- (0, dispatch_1.updatePhaseStatuses)(run);
301
- (0, verifier_1.validateRunGates)(run);
302
- const verifierResult = (0, pipeline_runner_1.createPipelineRunner)({ persist: false }).runPipelineStage(run, "verify", resultNode.id, {
303
- outputNodeId: `${run.id}:verifier:${task.id}`,
304
- outputStatus: "verified",
305
- loopStage: "adjust",
306
- outputs: { accepted: true },
307
- artifacts: [{ id: "result", kind: "markdown", path: destination }],
308
- evidence: resultNode.evidence.length
309
- ? resultNode.evidence
310
- : [{ id: "result:summary", source: "summary", summary: parsedResult.summary }],
311
- metadata: { taskId: task.id, resultNodeId: resultNode.id }
312
- });
313
- task.verifierNodeId = verifierResult.outputNodeId;
314
- (0, commit_1.commitState)(run, `result:${taskId}`);
315
- (0, report_1.writeReport)(run);
316
- (0, state_1.saveCheckpoint)(run);
317
- return (0, report_1.summarizeRun)(run);
318
- }
319
- catch (error) {
320
- (0, error_feedback_1.recordFeedback)(run, {
321
- source: "verifier",
322
- error: error instanceof Error ? error : String(error),
323
- taskId: task.id,
324
- path: resultPath ? node_path_1.default.resolve(resultPath) : undefined,
325
- retryable: false,
326
- metadata: {
327
- taskStatus: task.status,
328
- dispatchId: task.dispatchId,
329
- stateNodeId: task.stateNodeId,
330
- resultNodeId: task.resultNodeId
331
- }
332
- });
333
- (0, report_1.writeReport)(run);
334
- throw error;
335
- }
336
- }
337
- function recordWorkerOutput(run, workerId, resultPath, options = {}) {
338
- const usage = (0, observability_1.parseUsageFromArgs)(options, new Date().toISOString());
339
- // Agent Delegation Drive (v0.1.38): the drive loop passes the agent-hop
340
- // attestation through verbatim so recordWorkerOutput can fold the digests +
341
- // model into provenance/trust-audit. Absent for a hand-fulfilled worker.
342
- const agentDelegation = options.agentDelegation || undefined;
343
- // Track 1 fail-closed (opt-in): forward the policy so recordWorkerOutput can
344
- // park a hop whose telemetry isn't attested. Default (absent) ⇒ flag-and-surface.
345
- const requireAttestedTelemetry = options.requireAttestedTelemetry === true;
346
- const persistState = options.persistState !== false;
347
- try {
348
- (0, worker_isolation_1.recordWorkerOutput)(run, workerId, resultPath, { persist: false, agentDelegation, requireAttestedTelemetry });
349
- if (usage) {
350
- const worker = (0, worker_isolation_1.getWorkerScope)(run, workerId);
351
- // Host-attested token usage rides on the worker record as provenance.
352
- if (worker)
353
- worker.usage = usage;
354
- }
355
- run.loopStage = "observe";
356
- (0, dispatch_1.updatePhaseStatuses)(run);
357
- // Bounded dynamic loops: after a round's tasks complete, evaluate the predicate
358
- // and either append the next round or mark the loop done (no-op for non-loop runs).
359
- maybeExpandLoop(run);
360
- (0, verifier_1.validateRunGates)(run);
361
- if (persistState) {
362
- (0, commit_1.commitState)(run, `worker:${workerId}:result`);
363
- (0, report_1.writeReport)(run);
364
- (0, state_1.saveCheckpoint)(run);
365
- }
366
- return (0, report_1.summarizeRun)(run);
367
- }
368
- catch (error) {
369
- run.loopStage = "adjust";
370
- (0, dispatch_1.updatePhaseStatuses)(run);
371
- if (persistState) {
372
- (0, report_1.writeReport)(run);
373
- (0, state_1.saveCheckpoint)(run);
374
- }
375
- throw error;
376
- }
377
- }
378
- function recordWorkerFailure(run, workerId, message, options = {}) {
379
- const persistState = options.persistState !== false;
380
- const failure = (0, worker_isolation_1.recordWorkerFailure)(run, workerId, {
381
- code: String(options.code || "worker-runtime-error"),
382
- message,
383
- at: new Date().toISOString(),
384
- path: options.path ? node_path_1.default.resolve(String(options.path)) : undefined,
385
- retryable: Boolean(options.retryable)
386
- }, { persist: false, retryCount: typeof options.retryCount === "number" ? Number(options.retryCount) : undefined });
387
- run.loopStage = "adjust";
388
- (0, dispatch_1.updatePhaseStatuses)(run);
389
- if (persistState) {
390
- (0, report_1.writeReport)(run);
391
- (0, state_1.saveCheckpoint)(run);
392
- }
393
- return failure;
394
- }
395
- function checkState(runId, options = {}) {
396
- const cwd = node_path_1.default.resolve(String(options.cwd || process.cwd()));
397
- const statePath = options.state
398
- ? node_path_1.default.resolve(String(options.state))
399
- : node_path_1.default.join(cwd, ".cw", "runs", runId, "state.json");
400
- const result = (0, state_1.migrateRunStateFile)(statePath, { write: Boolean(options.write) });
401
- return result.report;
402
- }
403
- function commit(run, input = {}) {
404
- run.loopStage = "checkpoint";
405
- const options = typeof input === "string" ? { reason: input } : input;
406
- const allowCheckpoint = Boolean(options.allowUnverifiedCheckpoint || options["allow-unverified-checkpoint"]);
407
- const hasGateOption = Boolean(options.verifier || options.verifierNode || options["verifier-node"] || options.candidate || options.selection);
408
- try {
409
- const commitRecord = (0, commit_1.commitState)(run, {
410
- reason: (0, cli_options_1.stringOption)(options.reason) || "manual",
411
- verifierNodeId: (0, cli_options_1.stringOption)(options.verifier) || (0, cli_options_1.stringOption)(options.verifierNode) || (0, cli_options_1.stringOption)(options["verifier-node"]),
412
- candidateId: (0, cli_options_1.stringOption)(options.candidate),
413
- selectionId: (0, cli_options_1.stringOption)(options.selection),
414
- verifierGated: hasGateOption || !allowCheckpoint,
415
- allowUnverifiedCheckpoint: allowCheckpoint,
416
- source: "cli"
417
- });
418
- (0, report_1.writeReport)(run);
419
- (0, state_1.saveCheckpoint)(run);
420
- (0, state_explosion_1.maybeCompactRun)(run);
421
- return { runId: run.id, commit: commitRecord };
422
- }
423
- catch (error) {
424
- (0, report_1.writeReport)(run);
425
- (0, state_1.saveCheckpoint)(run);
426
- throw error;
427
- }
428
- }
429
- // ---- plan() private helpers (moved verbatim from the runner) ----------------
430
- function normalizeInputs(options) {
431
- const inputs = {};
432
- for (const [key, value] of Object.entries(options)) {
433
- if (key === "arg") {
434
- const pairs = Array.isArray(value) ? value : [value];
435
- for (const pair of pairs) {
436
- const [argKey, ...rest] = String(pair).split("=");
437
- inputs[argKey] = rest.join("=");
438
- }
439
- continue;
440
- }
441
- inputs[key] = value;
442
- }
443
- if (inputs.repo && !inputs.cwd)
444
- inputs.cwd = inputs.repo;
445
- return inputs;
446
- }
447
- function validateInputs(workflow, inputs) {
448
- for (const input of workflow.inputs || []) {
449
- if (input.required && (0, cli_options_1.isMissing)(inputs[input.name])) {
450
- throw new Error(`Missing required input --${input.name}`);
451
- }
452
- }
453
- }
454
- /** Bounded dynamic loop expansion. After a worker result is recorded: if the just-
455
- * completed phase is the LATEST round of a loop whose origin is not yet done, evaluate
456
- * the registered predicate over the round's recorded results and either append the
457
- * next round (clone the round-1 template tasks into a fresh phase, materialized like
458
- * plan() does) or mark the loop done. One deterministic `loop-control` node is recorded
459
- * per round boundary — the replay source of truth. No-op when the run has no loop
460
- * phases (POLA). Expands at most ONE loop boundary per call; the next accept handles
461
- * the next. Bounded: a loop never exceeds `maxRounds` (fail-closed); an unregistered
462
- * predicate stops the loop rather than spinning. */
463
- function maybeExpandLoop(run) {
464
- for (const phase of [...run.phases]) {
465
- const originId = phase.loop ? phase.id : phase.loopOrigin;
466
- if (!originId)
467
- continue;
468
- const origin = run.phases.find((p) => p.id === originId);
469
- if (!origin || !origin.loop || origin.loopDone)
470
- continue;
471
- // Act only from the LATEST round phase of this loop.
472
- const loopPhases = run.phases.filter((p) => p.id === originId || p.loopOrigin === originId);
473
- const latest = loopPhases.reduce((a, b) => ((b.loopRound || 1) >= (a.loopRound || 1) ? b : a));
474
- if (phase.id !== latest.id)
475
- continue;
476
- const roundTasks = run.tasks.filter((t) => latest.taskIds.includes(t.id));
477
- if (roundTasks.length === 0 || !roundTasks.every((t) => t.status === "completed"))
478
- continue;
479
- const round = latest.loopRound || 1;
480
- const ordered = (tasks) => tasks.slice().sort((a, b) => (0, compare_1.compareBytes)(a.id, b.id)).map((t) => t.result);
481
- const roundResults = ordered(roundTasks);
482
- const allLoopTasks = run.tasks.filter((t) => t.status === "completed" && loopPhases.some((p) => p.taskIds.includes(t.id)));
483
- const allResults = ordered(allLoopTasks);
484
- const ctx = { round, roundResults, allResults, usageTotals: (0, observability_1.deriveUsageTotals)(run).totals, inputs: run.inputs };
485
- const until = origin.loop.until;
486
- let decision;
487
- if (until.kind === "budget-target") {
488
- // Budget-aware scaling: keep spawning rounds while RECORDED (attested-only) usage
489
- // stays under the target. Composes with the fail-closed cap (limits.tokenBudget),
490
- // which the drive enforces before each spawn and which remains the absolute
491
- // backstop — whichever fires first wins, and the cap can never be overshot.
492
- const spent = ctx.usageTotals.totalTokens;
493
- decision = { done: spent >= until.target, reason: `budget-target: ${spent}/${until.target} recorded tokens` };
494
- }
495
- else {
496
- const predicate = (0, loop_expansion_1.getLoopPredicate)(until.ref);
497
- decision = predicate
498
- ? predicate(ctx)
499
- : { done: true, reason: `loop predicate "${until.ref}" not registered — stopping fail-closed` };
500
- }
501
- const atCap = round >= origin.loop.maxRounds;
502
- const done = decision.done || atCap;
503
- // Record the decision under a deterministic id (the replay source of truth).
504
- (0, state_node_1.appendRunNode)(run, (0, state_node_1.createStateNode)({
505
- id: `${run.id}:loop-control:${originId}:r${round}`,
506
- kind: "loop-control",
507
- status: "completed",
508
- loopStage: "adjust",
509
- outputs: { round, done, atCap, reason: decision.reason },
510
- metadata: { originPhaseId: originId, until: until.kind === "predicate" ? until.ref : `budget-target:${until.target}`, round, done, atCap, reason: decision.reason }
511
- }));
512
- if (done) {
513
- origin.loopDone = true;
514
- return;
515
- }
516
- // Expand: clone the ROUND-1 template tasks into a fresh phase appended right after.
517
- const nextRound = round + 1;
518
- const nextPhaseName = `${origin.name} (round ${nextRound})`;
519
- const templateTasks = run.tasks.filter((t) => origin.taskIds.includes(t.id));
520
- const newTasks = templateTasks.map((t) => ({
521
- id: `${t.id.replace(/@r\d+$/, "")}@r${nextRound}`,
522
- kind: t.kind,
523
- phase: nextPhaseName,
524
- status: "pending",
525
- requiresEvidence: t.requiresEvidence,
526
- prompt: t.prompt,
527
- taskPath: "",
528
- resultPath: "",
529
- loopStage: "interpret",
530
- loopRound: nextRound,
531
- ...(t.sandboxProfileId ? { sandboxProfileId: t.sandboxProfileId } : {}),
532
- ...(t.label ? { label: t.label } : {}),
533
- ...(t.model ? { model: t.model } : {}),
534
- ...(t.agentType ? { agentType: t.agentType } : {}),
535
- ...(t.schema ? { schema: t.schema } : {})
536
- }));
537
- const nextPhase = {
538
- id: `${originId}@r${nextRound}`,
539
- name: nextPhaseName,
540
- status: "pending",
541
- taskIds: newTasks.map((t) => t.id),
542
- loopOrigin: originId,
543
- loopRound: nextRound,
544
- ...(origin.mode ? { mode: origin.mode } : {})
545
- };
546
- const insertAt = run.phases.findIndex((p) => p.id === latest.id);
547
- run.phases.splice(insertAt + 1, 0, nextPhase);
548
- run.tasks.push(...newTasks);
549
- // Materialize: task files + a plan-stage contract node per new task (mirrors plan()).
550
- (0, harness_1.writeTaskFiles)(run);
551
- const contractId = run.contracts && run.contracts[0] ? run.contracts[0].id : undefined;
552
- const inputNodeId = `${run.id}:input`;
553
- const pipeline = (0, pipeline_runner_1.createPipelineRunner)({ contractId, persist: false });
554
- for (const t of newTasks) {
555
- const result = pipeline.runPipelineStage(run, "plan", inputNodeId, {
556
- outputNodeId: `${run.id}:task:${t.id}`,
557
- outputStatus: "pending",
558
- loopStage: "interpret",
559
- artifacts: [{ id: "task", kind: "markdown", path: t.taskPath }],
560
- metadata: { workflowId: run.workflow.id, taskId: t.id, phase: t.phase, taskKind: t.kind, requiresEvidence: t.requiresEvidence, sandboxProfileId: t.sandboxProfileId }
561
- });
562
- t.stateNodeId = result.outputNodeId;
563
- }
564
- (0, dispatch_1.updatePhaseStatuses)(run);
565
- return;
566
- }
567
- }
568
- function flattenTasks(workflow, inputs) {
569
- const seen = new Set();
570
- const tasks = [];
571
- for (const phase of workflow.phases) {
572
- for (const task of phase.tasks) {
573
- if (seen.has(task.id))
574
- throw new Error(`Duplicate task id: ${task.id}`);
575
- seen.add(task.id);
576
- tasks.push({
577
- id: task.id,
578
- kind: task.kind,
579
- phase: phase.name,
580
- status: "pending",
581
- loopStage: "interpret",
582
- requiresEvidence: Boolean(task.requiresEvidence),
583
- sandboxProfileId: task.sandboxProfileId,
584
- prompt: renderPrompt(task.prompt, inputs),
585
- taskPath: "",
586
- resultPath: "",
587
- // Track 3: carry the declared output schema onto the run task so
588
- // validateResultEnvelope can enforce it at intake. Absent ⇒ no schema check.
589
- ...(task.schema ? { schema: task.schema } : {}),
590
- // Authoring metadata the drive READS: label (progress/operator views),
591
- // model (per-task delegation override), agentType (dispatch backend).
592
- ...(task.label ? { label: task.label } : {}),
593
- ...(task.model ? { model: task.model } : {}),
594
- ...(task.agentType ? { agentType: task.agentType } : {}),
595
- ...(task.resultCache ? { resultCache: task.resultCache } : {}),
596
- ...(task.subWorkflow ? { subWorkflow: task.subWorkflow } : {}),
597
- // A loop phase's tasks are round 1 of the loop; the expander clones them.
598
- ...(phase.loop ? { loopRound: 1 } : {})
599
- });
600
- }
601
- }
602
- return tasks;
603
- }
604
- function renderPrompt(prompt, inputs) {
605
- const invariant = Array.isArray(inputs.invariant)
606
- ? inputs.invariant.join("; ")
607
- : String(inputs.invariant || "");
608
- let rendered = String(prompt)
609
- .replaceAll("{{repo}}", String(inputs.repo || ""))
610
- .replaceAll("{{question}}", String(inputs.question || ""))
611
- .replaceAll("{{invariant}}", invariant);
612
- for (const [key, value] of Object.entries(inputs)) {
613
- const replacement = Array.isArray(value) ? value.join("; ") : String(value ?? "");
614
- rendered = rendered.replaceAll(`{{${key}}}`, replacement);
615
- }
616
- return rendered;
617
- }
618
- // Deterministic run id (replay-determinism self-audit): the wall-clock stamp is an
619
- // edge timestamp (recorded once and stripped on replay), but the former
620
- // Math.random() suffix made the run id itself non-reproducible — re-deriving the id
621
- // for the SAME recorded run would never match. The suffix is now a content hash of
622
- // the run's deterministic identity (workflowId + the recorded stamp), so the id is a
623
- // pure function of inputs that already live in state. Distinct plan() invocations
624
- // still get distinct ids because the per-millisecond stamp differs; replaying a
625
- // recorded run reproduces the byte-identical id. Mirrors the de-clock done for
626
- // worker ids in src/worker-isolation/paths.ts.
627
- let runIdSequence = 0;
628
- function createRunId(workflowId) {
629
- // Use process.pid + monotonic counter for uniqueness (no wall-clock),
630
- // but keep a second-resolution stamp for human readability in the id.
631
- const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "Z");
632
- // Set CW_DETERMINISTIC_RUN_IDS=1 to use a content hash instead of wall-clock,
633
- // so two plan() calls with the same inputs produce the same id (replay-safe).
634
- if (/^(1|true|yes|on)$/i.test(process.env.CW_DETERMINISTIC_RUN_IDS || "")) {
635
- runIdSequence += 1;
636
- const suffix = node_crypto_1.default
637
- .createHash("sha256")
638
- .update(`${workflowId}:${process.pid}:${runIdSequence}`)
639
- .digest("hex")
640
- .slice(0, 6);
641
- return `${workflowId}-${suffix}`;
642
- }
643
- runIdSequence += 1;
644
- const suffix = node_crypto_1.default
645
- .createHash("sha256")
646
- .update(`${workflowId}:${stamp}:${process.pid}:${runIdSequence}`)
647
- .digest("hex")
648
- .slice(0, 6);
649
- return `${workflowId}-${stamp}-${suffix}`;
650
- }