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