cool-workflow 0.1.81 → 0.1.83

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 (102) hide show
  1. package/.claude-plugin/plugin.json +2 -2
  2. package/.codex-plugin/plugin.json +4 -4
  3. package/README.md +125 -121
  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/candidate-scoring.js +20 -26
  11. package/dist/capability-core.js +80 -93
  12. package/dist/capability-registry.js +30 -3
  13. package/dist/cli.js +12 -1
  14. package/dist/commit.js +217 -204
  15. package/dist/coordinator/util.js +6 -9
  16. package/dist/dispatch.js +11 -3
  17. package/dist/doctor.js +153 -0
  18. package/dist/evidence-reasoning.js +4 -1
  19. package/dist/execution-backend/agent.js +11 -48
  20. package/dist/execution-backend.js +11 -31
  21. package/dist/gates.js +48 -0
  22. package/dist/mcp-server.js +11 -0
  23. package/dist/multi-agent/helpers.js +6 -10
  24. package/dist/multi-agent/ids.js +20 -0
  25. package/dist/multi-agent-eval.js +27 -1
  26. package/dist/multi-agent-host.js +53 -21
  27. package/dist/multi-agent-operator-ux.js +2 -1
  28. package/dist/multi-agent-trust.js +5 -5
  29. package/dist/node-projection.js +59 -0
  30. package/dist/node-snapshot.js +8 -18
  31. package/dist/orchestrator/lifecycle-operations.js +22 -1
  32. package/dist/orchestrator.js +29 -2
  33. package/dist/reclamation/hash.js +72 -0
  34. package/dist/reclamation.js +31 -112
  35. package/dist/run-registry/queue.js +6 -7
  36. package/dist/run-registry.js +35 -24
  37. package/dist/scheduler.js +112 -57
  38. package/dist/topology.js +25 -4
  39. package/dist/trust-audit.js +70 -38
  40. package/dist/validation.js +328 -0
  41. package/dist/version.js +1 -1
  42. package/dist/worker-isolation.js +163 -58
  43. package/docs/agent-delegation-drive.7.md +90 -85
  44. package/docs/agent-framework.md +33 -32
  45. package/docs/candidate-scoring.7.md +26 -24
  46. package/docs/canonical-workflow-apps.7.md +40 -40
  47. package/docs/capability-topology-registry.7.md +24 -24
  48. package/docs/cli-mcp-parity.7.md +227 -154
  49. package/docs/contract-migration-tooling.7.md +49 -41
  50. package/docs/control-plane-scheduling.7.md +45 -40
  51. package/docs/coordinator-blackboard.7.md +30 -30
  52. package/docs/dogfood-one-real-repo.7.md +44 -44
  53. package/docs/durable-state-and-locking.7.md +35 -30
  54. package/docs/end-to-end-golden-path.7.md +29 -29
  55. package/docs/error-feedback.7.md +27 -27
  56. package/docs/evidence-adoption-reasoning-chain.7.md +63 -58
  57. package/docs/execution-backends.7.md +84 -79
  58. package/docs/getting-started.md +35 -18
  59. package/docs/index.md +3 -3
  60. package/docs/mcp-app-surface.7.md +64 -64
  61. package/docs/multi-agent-cli-mcp-surface.7.md +83 -77
  62. package/docs/multi-agent-eval-replay-harness.7.md +59 -54
  63. package/docs/multi-agent-operator-ux.7.md +70 -65
  64. package/docs/multi-agent-runtime-core.7.md +39 -39
  65. package/docs/multi-agent-topologies.7.md +24 -24
  66. package/docs/multi-agent-trust-policy-audit.7.md +38 -38
  67. package/docs/node-snapshot-diff-replay.7.md +26 -21
  68. package/docs/observability-cost-accounting.7.md +50 -45
  69. package/docs/operator-ux.7.md +30 -30
  70. package/docs/pipeline-runner.7.md +31 -31
  71. package/docs/project-index.md +15 -6
  72. package/docs/real-execution-backends.7.md +47 -42
  73. package/docs/release-and-migration.7.md +43 -38
  74. package/docs/release-tooling.7.md +74 -39
  75. package/docs/routines.md +16 -16
  76. package/docs/run-registry-control-plane.7.md +120 -115
  77. package/docs/run-retention-reclamation.7.md +46 -41
  78. package/docs/sandbox-profiles.7.md +32 -32
  79. package/docs/scheduled-tasks.md +14 -14
  80. package/docs/security-trust-hardening.7.md +29 -29
  81. package/docs/source-context-profiles.7.md +28 -28
  82. package/docs/state-explosion-management.7.md +64 -59
  83. package/docs/state-node.7.md +8 -8
  84. package/docs/team-collaboration.7.md +63 -58
  85. package/docs/trust-model.md +126 -126
  86. package/docs/unix-principles.md +80 -80
  87. package/docs/vendor-manifest-loadability.7.md +20 -20
  88. package/docs/verifier-gated-commit.7.md +16 -16
  89. package/docs/web-desktop-workbench.7.md +70 -65
  90. package/docs/worker-isolation.7.md +34 -37
  91. package/docs/workflow-app-framework.7.md +38 -38
  92. package/manifest/plugin.manifest.json +4 -4
  93. package/manifest/source-context-profiles.json +1 -1
  94. package/package.json +3 -2
  95. package/scripts/canonical-apps.js +4 -4
  96. package/scripts/children/batch-delegate-child.js +58 -0
  97. package/scripts/children/http-delegate-child.js +39 -0
  98. package/scripts/dogfood-release.js +1 -1
  99. package/scripts/gen-parity-doc.js +106 -0
  100. package/scripts/golden-path.js +4 -4
  101. package/scripts/release-flow.js +181 -5
  102. package/dist/verifier-registry.js +0 -46
@@ -0,0 +1,328 @@
1
+ "use strict";
2
+ // Fail-closed shape guards for persisted per-record types (F5, integrity boundary).
3
+ //
4
+ // `JSON.parse(...) as T` is a LIE: the cast asserts a shape TypeScript never
5
+ // checked at runtime, so a corrupt/forged/old-schema record flows in as if it
6
+ // were a valid T and is used/upserted unvalidated. These guards re-establish the
7
+ // integrity boundary at the read edge: after parse, the raw value is structurally
8
+ // validated against the type def in src/types/* BEFORE it is trusted.
9
+ //
10
+ // Two callers, two error semantics — both fail closed, neither fabricates:
11
+ // - validate*() throw a descriptive Error on mismatch (for readers that
12
+ // already let parse errors propagate / require the record).
13
+ // - tryValidate*() return null on mismatch (for best-effort readers that
14
+ // swallow parse errors and SKIP the record — the downstream
15
+ // gate then fails closed on the absence). Never throws.
16
+ //
17
+ // Dependency-light by construction: imports ONLY from ./types. No fs, no clock,
18
+ // no randomness — pure structural checks, safe in replay/core paths.
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.RecordValidationError = void 0;
21
+ exports.validateWorkerScope = validateWorkerScope;
22
+ exports.tryValidateWorkerScope = tryValidateWorkerScope;
23
+ exports.validateNodeSnapshot = validateNodeSnapshot;
24
+ exports.tryValidateNodeSnapshot = tryValidateNodeSnapshot;
25
+ exports.validateNodeReplayRun = validateNodeReplayRun;
26
+ exports.tryValidateNodeReplayRun = tryValidateNodeReplayRun;
27
+ exports.validateCandidateScore = validateCandidateScore;
28
+ exports.tryValidateCandidateScore = tryValidateCandidateScore;
29
+ exports.validateCandidateRecord = validateCandidateRecord;
30
+ exports.tryValidateCandidateRecord = tryValidateCandidateRecord;
31
+ // ---------------------------------------------------------------------------
32
+ // Primitive predicates — small, total, never throw.
33
+ // ---------------------------------------------------------------------------
34
+ function isRecord(value) {
35
+ return value !== null && typeof value === "object" && !Array.isArray(value);
36
+ }
37
+ function isString(value) {
38
+ return typeof value === "string";
39
+ }
40
+ function isFiniteNumber(value) {
41
+ return typeof value === "number" && Number.isFinite(value);
42
+ }
43
+ function isStringArray(value) {
44
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
45
+ }
46
+ function isObjectArray(value) {
47
+ return Array.isArray(value) && value.every((entry) => isRecord(entry));
48
+ }
49
+ const WORKER_STATUSES = new Set([
50
+ "allocated",
51
+ "running",
52
+ "completed",
53
+ "failed",
54
+ "rejected",
55
+ "verified",
56
+ "orphaned"
57
+ ]);
58
+ const SCORE_VERDICTS = new Set(["pass", "warn", "fail"]);
59
+ const CANDIDATE_STATUSES = new Set([
60
+ "registered",
61
+ "scored",
62
+ "selected",
63
+ "rejected",
64
+ "verified",
65
+ "failed"
66
+ ]);
67
+ const CANDIDATE_KINDS = new Set(["worker-output", "result", "artifact", "manual", "release"]);
68
+ const SNAPSHOT_FRESHNESS = new Set(["valid", "stale", "absent"]);
69
+ /** Descriptive integrity error — the message names the type and the field that
70
+ * broke, so a corrupt record is diagnosable from logs alone. */
71
+ class RecordValidationError extends Error {
72
+ code = "record-shape-invalid";
73
+ typeName;
74
+ field;
75
+ constructor(typeName, reason, field) {
76
+ super(`Invalid persisted ${typeName}: ${reason}`);
77
+ this.name = "RecordValidationError";
78
+ this.typeName = typeName;
79
+ this.field = field;
80
+ }
81
+ }
82
+ exports.RecordValidationError = RecordValidationError;
83
+ // ---------------------------------------------------------------------------
84
+ // WorkerScope — worker-isolation.ts:309 / :905
85
+ // Required (per src/types/worker.ts WorkerScope): schemaVersion===1, id, runId,
86
+ // taskId, createdAt, updatedAt, status (enum), workerDir, inputPath, resultPath,
87
+ // artifactsDir, logsDir are strings; allowedPaths string[]; feedbackIds string[];
88
+ // errors object[]. Optional fields are not enforced (additive, may be absent).
89
+ // ---------------------------------------------------------------------------
90
+ function workerScopeReason(value) {
91
+ if (!isRecord(value))
92
+ return { reason: "not an object" };
93
+ if (value.schemaVersion !== 1)
94
+ return { field: "schemaVersion", reason: "must equal 1" };
95
+ const requiredStrings = [
96
+ "id",
97
+ "runId",
98
+ "taskId",
99
+ "createdAt",
100
+ "updatedAt",
101
+ "workerDir",
102
+ "inputPath",
103
+ "resultPath",
104
+ "artifactsDir",
105
+ "logsDir"
106
+ ];
107
+ for (const field of requiredStrings) {
108
+ if (!isString(value[field]))
109
+ return { field: field, reason: "must be a string" };
110
+ }
111
+ if (!isString(value.status) || !WORKER_STATUSES.has(value.status)) {
112
+ return { field: "status", reason: "must be a valid WorkerIsolationStatus" };
113
+ }
114
+ if (!isStringArray(value.allowedPaths))
115
+ return { field: "allowedPaths", reason: "must be a string[]" };
116
+ if (!isStringArray(value.feedbackIds))
117
+ return { field: "feedbackIds", reason: "must be a string[]" };
118
+ if (!isObjectArray(value.errors))
119
+ return { field: "errors", reason: "must be a StateNodeError[]" };
120
+ return undefined;
121
+ }
122
+ /** Throw-on-mismatch guard for WorkerScope (callers that require the record). */
123
+ function validateWorkerScope(value) {
124
+ const problem = workerScopeReason(value);
125
+ if (problem)
126
+ throw new RecordValidationError("WorkerScope", problem.reason, problem.field);
127
+ return value;
128
+ }
129
+ /** Best-effort variant: returns null on mismatch (caller skips the record). */
130
+ function tryValidateWorkerScope(value) {
131
+ return workerScopeReason(value) ? null : value;
132
+ }
133
+ // ---------------------------------------------------------------------------
134
+ // NodeSnapshotBody — shared by NodeSnapshot.body and NodeReplayRun.body.
135
+ // Required (per src/types/state-node.ts): id, kind, status, loopStage strings;
136
+ // inputs/outputs records; artifacts/evidence/errors object arrays;
137
+ // parents/children string arrays.
138
+ // ---------------------------------------------------------------------------
139
+ function nodeSnapshotBodyReason(value, prefix) {
140
+ if (!isRecord(value))
141
+ return { field: prefix, reason: "must be a NodeSnapshotBody object" };
142
+ const requiredStrings = ["id", "kind", "status", "loopStage"];
143
+ for (const field of requiredStrings) {
144
+ if (!isString(value[field]))
145
+ return { field: `${prefix}.${String(field)}`, reason: "must be a string" };
146
+ }
147
+ if (!isRecord(value.inputs))
148
+ return { field: `${prefix}.inputs`, reason: "must be an object" };
149
+ if (!isRecord(value.outputs))
150
+ return { field: `${prefix}.outputs`, reason: "must be an object" };
151
+ if (!isObjectArray(value.artifacts))
152
+ return { field: `${prefix}.artifacts`, reason: "must be a StateArtifact[]" };
153
+ if (!isObjectArray(value.evidence))
154
+ return { field: `${prefix}.evidence`, reason: "must be a StateEvidence[]" };
155
+ if (!isObjectArray(value.errors))
156
+ return { field: `${prefix}.errors`, reason: "must be a StateNodeError[]" };
157
+ if (!isStringArray(value.parents))
158
+ return { field: `${prefix}.parents`, reason: "must be a string[]" };
159
+ if (!isStringArray(value.children))
160
+ return { field: `${prefix}.children`, reason: "must be a string[]" };
161
+ return undefined;
162
+ }
163
+ // ---------------------------------------------------------------------------
164
+ // NodeSnapshot — node-snapshot.ts:121
165
+ // Required: schemaVersion===1, snapshotId, runId, nodeId, capturedAt,
166
+ // sourceFingerprint strings; body a valid NodeSnapshotBody.
167
+ // ---------------------------------------------------------------------------
168
+ function nodeSnapshotReason(value) {
169
+ if (!isRecord(value))
170
+ return { reason: "not an object" };
171
+ if (value.schemaVersion !== 1)
172
+ return { field: "schemaVersion", reason: "must equal 1" };
173
+ const requiredStrings = ["snapshotId", "runId", "nodeId", "capturedAt", "sourceFingerprint"];
174
+ for (const field of requiredStrings) {
175
+ if (!isString(value[field]))
176
+ return { field: field, reason: "must be a string" };
177
+ }
178
+ return nodeSnapshotBodyReason(value.body, "body");
179
+ }
180
+ /** Throw-on-mismatch guard for NodeSnapshot (read edge requires the record). */
181
+ function validateNodeSnapshot(value) {
182
+ const problem = nodeSnapshotReason(value);
183
+ if (problem)
184
+ throw new RecordValidationError("NodeSnapshot", problem.reason, problem.field);
185
+ return value;
186
+ }
187
+ /** Best-effort variant: returns null on mismatch. */
188
+ function tryValidateNodeSnapshot(value) {
189
+ return nodeSnapshotReason(value) ? null : value;
190
+ }
191
+ // ---------------------------------------------------------------------------
192
+ // NodeReplayRun — node-snapshot.ts:133
193
+ // Required: schemaVersion===1, replayId, runId, nodeId, snapshotId, replayedAt,
194
+ // outputFingerprint strings; freshness enum; contractValidated boolean; body a
195
+ // valid NodeSnapshotBody.
196
+ // ---------------------------------------------------------------------------
197
+ function nodeReplayRunReason(value) {
198
+ if (!isRecord(value))
199
+ return { reason: "not an object" };
200
+ if (value.schemaVersion !== 1)
201
+ return { field: "schemaVersion", reason: "must equal 1" };
202
+ const requiredStrings = [
203
+ "replayId",
204
+ "runId",
205
+ "nodeId",
206
+ "snapshotId",
207
+ "replayedAt",
208
+ "outputFingerprint"
209
+ ];
210
+ for (const field of requiredStrings) {
211
+ if (!isString(value[field]))
212
+ return { field: field, reason: "must be a string" };
213
+ }
214
+ if (!isString(value.freshness) || !SNAPSHOT_FRESHNESS.has(value.freshness)) {
215
+ return { field: "freshness", reason: "must be a valid NodeSnapshotFreshness" };
216
+ }
217
+ if (typeof value.contractValidated !== "boolean") {
218
+ return { field: "contractValidated", reason: "must be a boolean" };
219
+ }
220
+ return nodeSnapshotBodyReason(value.body, "body");
221
+ }
222
+ /** Throw-on-mismatch guard for NodeReplayRun (read edge requires the record). */
223
+ function validateNodeReplayRun(value) {
224
+ const problem = nodeReplayRunReason(value);
225
+ if (problem)
226
+ throw new RecordValidationError("NodeReplayRun", problem.reason, problem.field);
227
+ return value;
228
+ }
229
+ /** Best-effort variant: returns null on mismatch. */
230
+ function tryValidateNodeReplayRun(value) {
231
+ return nodeReplayRunReason(value) ? null : value;
232
+ }
233
+ // ---------------------------------------------------------------------------
234
+ // CandidateScore — multi-agent-operator-ux.ts:502 / evidence-reasoning.ts:750
235
+ // Required (per src/types/candidate.ts): schemaVersion===1, id, candidateId,
236
+ // runId, createdAt, scorer strings; criteria record of numbers; total/maxTotal/
237
+ // normalized finite numbers; verdict enum; evidence/artifacts object arrays.
238
+ // ---------------------------------------------------------------------------
239
+ function isNumberRecord(value) {
240
+ return isRecord(value) && Object.values(value).every((entry) => isFiniteNumber(entry));
241
+ }
242
+ function candidateScoreReason(value) {
243
+ if (!isRecord(value))
244
+ return { reason: "not an object" };
245
+ if (value.schemaVersion !== 1)
246
+ return { field: "schemaVersion", reason: "must equal 1" };
247
+ const requiredStrings = ["id", "candidateId", "runId", "createdAt", "scorer"];
248
+ for (const field of requiredStrings) {
249
+ if (!isString(value[field]))
250
+ return { field: field, reason: "must be a string" };
251
+ }
252
+ if (!isNumberRecord(value.criteria))
253
+ return { field: "criteria", reason: "must be a Record<string, number>" };
254
+ if (!isFiniteNumber(value.total))
255
+ return { field: "total", reason: "must be a finite number" };
256
+ if (!isFiniteNumber(value.maxTotal))
257
+ return { field: "maxTotal", reason: "must be a finite number" };
258
+ if (!isFiniteNumber(value.normalized))
259
+ return { field: "normalized", reason: "must be a finite number" };
260
+ if (!isString(value.verdict) || !SCORE_VERDICTS.has(value.verdict)) {
261
+ return { field: "verdict", reason: "must be a valid CandidateScoreVerdict" };
262
+ }
263
+ if (!isObjectArray(value.evidence))
264
+ return { field: "evidence", reason: "must be a StateEvidence[]" };
265
+ if (!isObjectArray(value.artifacts))
266
+ return { field: "artifacts", reason: "must be a StateArtifact[]" };
267
+ return undefined;
268
+ }
269
+ /** Throw-on-mismatch guard for CandidateScore (callers that require the record). */
270
+ function validateCandidateScore(value) {
271
+ const problem = candidateScoreReason(value);
272
+ if (problem)
273
+ throw new RecordValidationError("CandidateScore", problem.reason, problem.field);
274
+ return value;
275
+ }
276
+ /** Best-effort variant: returns null on mismatch (caller skips the record so the
277
+ * downstream score gate fails closed on its absence). */
278
+ function tryValidateCandidateScore(value) {
279
+ return candidateScoreReason(value) ? null : value;
280
+ }
281
+ // ---------------------------------------------------------------------------
282
+ // CandidateRecord — candidate-scoring.ts getCandidate / loadCandidatesFromDisk.
283
+ // Required (per src/types/candidate.ts): schemaVersion===1, id, runId, createdAt,
284
+ // updatedAt strings; kind/status enums; artifacts/evidence object arrays;
285
+ // scores/feedbackIds string arrays. Optional ids (workerId/taskId/…) not enforced.
286
+ // A corrupt/forged candidate record must NOT flow into the run as a trusted T —
287
+ // the gate that backs commit selection reads these fields, so we fail closed at
288
+ // the read edge instead of upserting an unvalidated cast.
289
+ // ---------------------------------------------------------------------------
290
+ function candidateRecordReason(value) {
291
+ if (!isRecord(value))
292
+ return { reason: "not an object" };
293
+ if (value.schemaVersion !== 1)
294
+ return { field: "schemaVersion", reason: "must equal 1" };
295
+ const requiredStrings = ["id", "runId", "createdAt", "updatedAt"];
296
+ for (const field of requiredStrings) {
297
+ if (!isString(value[field]))
298
+ return { field: field, reason: "must be a string" };
299
+ }
300
+ if (!isString(value.kind) || !CANDIDATE_KINDS.has(value.kind)) {
301
+ return { field: "kind", reason: "must be a valid CandidateKind" };
302
+ }
303
+ if (!isString(value.status) || !CANDIDATE_STATUSES.has(value.status)) {
304
+ return { field: "status", reason: "must be a valid CandidateStatus" };
305
+ }
306
+ if (!isObjectArray(value.artifacts))
307
+ return { field: "artifacts", reason: "must be a StateArtifact[]" };
308
+ if (!isObjectArray(value.evidence))
309
+ return { field: "evidence", reason: "must be a StateEvidence[]" };
310
+ if (!isStringArray(value.scores))
311
+ return { field: "scores", reason: "must be a string[]" };
312
+ if (!isStringArray(value.feedbackIds))
313
+ return { field: "feedbackIds", reason: "must be a string[]" };
314
+ return undefined;
315
+ }
316
+ /** Throw-on-mismatch guard for CandidateRecord (callers that require the record
317
+ * at the disk read edge — getCandidate / loadCandidatesFromDisk). */
318
+ function validateCandidateRecord(value) {
319
+ const problem = candidateRecordReason(value);
320
+ if (problem)
321
+ throw new RecordValidationError("CandidateRecord", problem.reason, problem.field);
322
+ return value;
323
+ }
324
+ /** Best-effort variant: returns null on mismatch (caller skips the record so the
325
+ * downstream selection gate fails closed on its absence). */
326
+ function tryValidateCandidateRecord(value) {
327
+ return candidateRecordReason(value) ? null : value;
328
+ }
package/dist/version.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MIN_SUPPORTED_RUN_STATE_SCHEMA_VERSION = exports.LEGACY_RUN_STATE_SCHEMA_VERSION = exports.CURRENT_RUN_STATE_SCHEMA_VERSION = exports.WORKFLOW_APP_SCHEMA_VERSION = exports.CURRENT_COOL_WORKFLOW_VERSION = void 0;
4
- exports.CURRENT_COOL_WORKFLOW_VERSION = "0.1.81";
4
+ exports.CURRENT_COOL_WORKFLOW_VERSION = "0.1.83";
5
5
  exports.WORKFLOW_APP_SCHEMA_VERSION = 1;
6
6
  exports.CURRENT_RUN_STATE_SCHEMA_VERSION = 1;
7
7
  exports.LEGACY_RUN_STATE_SCHEMA_VERSION = 0;
@@ -34,6 +34,7 @@ const telemetry_ledger_1 = require("./telemetry-ledger");
34
34
  const coordinator_1 = require("./coordinator");
35
35
  const helpers_1 = require("./worker-isolation/helpers");
36
36
  const paths_1 = require("./worker-isolation/paths");
37
+ const validation_1 = require("./validation");
37
38
  exports.WORKER_ISOLATION_SCHEMA_VERSION = 1;
38
39
  function allocateWorkerScope(run, task, options = {}) {
39
40
  ensureWorkerState(run);
@@ -269,11 +270,39 @@ function getWorkerScope(run, workerId) {
269
270
  const file = node_path_1.default.join(workerRoot(run), (0, state_1.safeFileName)(workerId), paths_1.WORKER_SCOPE_FILE);
270
271
  if (!node_fs_1.default.existsSync(file))
271
272
  return undefined;
272
- const scope = JSON.parse(node_fs_1.default.readFileSync(file, "utf8"));
273
+ let scope;
274
+ try {
275
+ scope = (0, validation_1.validateWorkerScope)(JSON.parse(node_fs_1.default.readFileSync(file, "utf8")));
276
+ }
277
+ catch (error) {
278
+ // A present-but-corrupt scope fails closed with context, not a raw
279
+ // SyntaxError/validation throw bubbling up from deep in the call stack.
280
+ throw new Error(`Corrupt worker scope ${file}: ${error instanceof Error ? error.message : String(error)}`);
281
+ }
273
282
  upsertWorkerScope(run, scope);
274
283
  return scope;
275
284
  }
276
285
  function recordWorkerOutput(run, workerId, resultPath, options = {}) {
286
+ // Accept-path orchestrator. The recorded order + side effects of these ordered
287
+ // steps are load-bearing (replay determinism + the hash-chained audit/telemetry
288
+ // ledgers cross-link by parent event ids), so each helper runs exactly where it
289
+ // did before and mutates the shared `accept` context in place. Do NOT reorder.
290
+ const accept = validateWorkerResult(run, workerId, resultPath, options);
291
+ const delegation = attestWorkerDelegation(accept);
292
+ acceptWorkerResult(accept, delegation);
293
+ recordWorkerDelegationLedger(accept, delegation);
294
+ runWorkerVerify(accept);
295
+ recordWorkerCompletion(accept, delegation);
296
+ fanOutWorkerOutput(accept);
297
+ if (options.persist !== false)
298
+ (0, state_1.saveCheckpoint)(run);
299
+ return accept.output;
300
+ }
301
+ /** Step 1 — validateResult: resolve scope/task, enforce the sandbox boundary, the
302
+ * result-file existence, the envelope contract, and (opt-in) resolvable evidence.
303
+ * Fail-closed: any guard records a worker failure and throws BEFORE accept-side
304
+ * state mutation. Returns the partially-filled accept context on success. */
305
+ function validateWorkerResult(run, workerId, resultPath, options) {
277
306
  const scope = requireWorkerScope(run, workerId);
278
307
  const task = requireWorkerTask(run, scope);
279
308
  const absoluteResultPath = node_path_1.default.resolve(resultPath);
@@ -316,6 +345,30 @@ function recordWorkerOutput(run, workerId, resultPath, options = {}) {
316
345
  throw new Error(error.message);
317
346
  }
318
347
  }
348
+ return {
349
+ run,
350
+ workerId,
351
+ options,
352
+ scope,
353
+ task,
354
+ absoluteResultPath,
355
+ rawResult,
356
+ parsedResult,
357
+ destination: "",
358
+ pathAuditId: "",
359
+ acceptedAuditId: "",
360
+ resultNode: undefined,
361
+ verifierNodeId: "",
362
+ verifierStatus: "",
363
+ output: undefined
364
+ };
365
+ }
366
+ /** Step 2 — attestSandbox/attestDelegation: verify the agent's signed telemetry
367
+ * BEFORE recording it, enforce the opt-in require-attested-telemetry gate (still
368
+ * fail-closed, pre-mutation), and build the agent-hop provenance. Non-agent hops
369
+ * return an empty delegation. */
370
+ function attestWorkerDelegation(accept) {
371
+ const { run, workerId, options, task, absoluteResultPath, rawResult } = accept;
319
372
  // Agent Delegation Drive (v0.1.38): if this worker's result.md was produced by an
320
373
  // EXTERNAL agent, record the agent-hop attestation AS PROVENANCE — the agent
321
374
  // (kind:process) handle, the agent-REPORTED model (never CW_AGENT_MODEL), the
@@ -355,6 +408,16 @@ function recordWorkerOutput(run, workerId, resultPath, options = {}) {
355
408
  ...(telemetry ? { usageAttestation: telemetry.status, usageAttestationReason: telemetry.reason } : {})
356
409
  }
357
410
  : undefined;
411
+ return { agentDelegation, telemetry };
412
+ }
413
+ /** Step 3 — recordStateNode/audit: the irreversible accept. Records the allowed
414
+ * path decision, copies the result into the run results dir, completes the task,
415
+ * builds + appends the result node, emits the accepted audit event, re-normalizes
416
+ * node evidence against both audit ids, and surfaces the empty-capture warning.
417
+ * Writes destination/pathAuditId/acceptedAuditId/resultNode back into `accept`. */
418
+ function acceptWorkerResult(accept, delegation) {
419
+ const { run, workerId, scope, task, absoluteResultPath, parsedResult } = accept;
420
+ const { agentDelegation } = delegation;
358
421
  const pathAudit = (0, trust_audit_1.recordSandboxPathDecision)(run, {
359
422
  workerId,
360
423
  taskId: task.id,
@@ -443,58 +506,75 @@ function recordWorkerOutput(run, workerId, resultPath, options = {}) {
443
506
  metadata: { reason: "no findings or evidence captured from result.md", resultPath: destination }
444
507
  });
445
508
  }
509
+ accept.destination = destination;
510
+ accept.pathAuditId = pathAudit.id;
511
+ accept.acceptedAuditId = acceptedAudit.id;
512
+ accept.resultNode = resultNode;
513
+ }
514
+ /** Step 4 — recordTelemetryLedger: the agent-hop attestation. Binds the telemetry
515
+ * verdict into the append-only hash-chained ledger BEFORE the audit event (so the
516
+ * event can cross-link the record hash), then emits the worker.agent-delegation
517
+ * audit event. No-op for non-agent hops. */
518
+ function recordWorkerDelegationLedger(accept, delegation) {
519
+ const { agentDelegation } = delegation;
446
520
  // The agent-hop attestation event — hung off worker.output, alongside
447
521
  // worker.backend. Recorded in trust-audit/provenance, NEVER in node evidence.
448
- if (agentDelegation) {
449
- // Track 1 (tamper-evidence): bind this verdict into the append-only,
450
- // hash-chained telemetry ledger BEFORE the audit event, so the event can
451
- // cross-link the record hash. Editing the recorded verdict/usage later breaks
452
- // the chain (verifyTelemetryLedger). Only when a verdict was computed.
453
- const ledgerRecord = agentDelegation.usageAttestation
454
- ? (0, telemetry_ledger_1.appendTelemetryAttestation)(run, {
455
- workerId,
456
- taskId: task.id,
457
- promptDigest: agentDelegation.promptDigest,
458
- reportedUsage: agentDelegation.reportedUsage,
459
- usageSignature: agentDelegation.usageSignature,
460
- attestation: agentDelegation.usageAttestation,
461
- attestationReason: agentDelegation.usageAttestationReason
462
- })
463
- : undefined;
464
- (0, trust_audit_1.recordTrustAuditEvent)(run, {
465
- kind: "worker.agent-delegation",
466
- decision: "recorded",
467
- source: "host-attested",
522
+ if (!agentDelegation)
523
+ return;
524
+ const { run, workerId, scope, task, resultNode, acceptedAuditId } = accept;
525
+ // Track 1 (tamper-evidence): bind this verdict into the append-only,
526
+ // hash-chained telemetry ledger BEFORE the audit event, so the event can
527
+ // cross-link the record hash. Editing the recorded verdict/usage later breaks
528
+ // the chain (verifyTelemetryLedger). Only when a verdict was computed.
529
+ const ledgerRecord = agentDelegation.usageAttestation
530
+ ? (0, telemetry_ledger_1.appendTelemetryAttestation)(run, {
468
531
  workerId,
469
532
  taskId: task.id,
470
- nodeId: resultNode.id,
471
- sandboxProfileId: scope.sandboxProfileId,
472
- policySnapshot: scope.sandboxPolicy,
473
- parentEventIds: [acceptedAudit.id],
474
- metadata: {
475
- backendId: agentDelegation.backendId,
476
- handleKind: agentDelegation.handle.kind,
477
- handleRef: agentDelegation.handle.ref,
478
- model: agentDelegation.model,
479
- promptDigest: agentDelegation.promptDigest,
480
- resultDigest: agentDelegation.resultDigest,
481
- command: agentDelegation.command,
482
- args: agentDelegation.args,
483
- exitCode: agentDelegation.exitCode,
484
- // Track 1: the telemetry verdict travels with the agent-hop event so the
485
- // audit report can surface `unattested` usage loudly. Absent ⇒ no usage.
486
- ...(agentDelegation.usageAttestation
487
- ? {
488
- telemetryAttestation: agentDelegation.usageAttestation,
489
- ...(agentDelegation.usageAttestationReason ? { telemetryAttestationReason: agentDelegation.usageAttestationReason } : {}),
490
- ...(agentDelegation.reportedUsage ? { reportedUsage: agentDelegation.reportedUsage } : {}),
491
- // Cross-link to the hash-chained ledger entry (tamper-evidence).
492
- ...(ledgerRecord ? { telemetryRecordId: ledgerRecord.recordId, telemetryRecordHash: ledgerRecord.recordHash, telemetryPrevHash: ledgerRecord.prevHash } : {})
493
- }
494
- : {})
495
- }
496
- });
497
- }
533
+ promptDigest: agentDelegation.promptDigest,
534
+ reportedUsage: agentDelegation.reportedUsage,
535
+ usageSignature: agentDelegation.usageSignature,
536
+ attestation: agentDelegation.usageAttestation,
537
+ attestationReason: agentDelegation.usageAttestationReason
538
+ })
539
+ : undefined;
540
+ (0, trust_audit_1.recordTrustAuditEvent)(run, {
541
+ kind: "worker.agent-delegation",
542
+ decision: "recorded",
543
+ source: "host-attested",
544
+ workerId,
545
+ taskId: task.id,
546
+ nodeId: resultNode.id,
547
+ sandboxProfileId: scope.sandboxProfileId,
548
+ policySnapshot: scope.sandboxPolicy,
549
+ parentEventIds: [acceptedAuditId],
550
+ metadata: {
551
+ backendId: agentDelegation.backendId,
552
+ handleKind: agentDelegation.handle.kind,
553
+ handleRef: agentDelegation.handle.ref,
554
+ model: agentDelegation.model,
555
+ promptDigest: agentDelegation.promptDigest,
556
+ resultDigest: agentDelegation.resultDigest,
557
+ command: agentDelegation.command,
558
+ args: agentDelegation.args,
559
+ exitCode: agentDelegation.exitCode,
560
+ // Track 1: the telemetry verdict travels with the agent-hop event so the
561
+ // audit report can surface `unattested` usage loudly. Absent ⇒ no usage.
562
+ ...(agentDelegation.usageAttestation
563
+ ? {
564
+ telemetryAttestation: agentDelegation.usageAttestation,
565
+ ...(agentDelegation.usageAttestationReason ? { telemetryAttestationReason: agentDelegation.usageAttestationReason } : {}),
566
+ ...(agentDelegation.reportedUsage ? { reportedUsage: agentDelegation.reportedUsage } : {}),
567
+ // Cross-link to the hash-chained ledger entry (tamper-evidence).
568
+ ...(ledgerRecord ? { telemetryRecordId: ledgerRecord.recordId, telemetryRecordHash: ledgerRecord.recordHash, telemetryPrevHash: ledgerRecord.prevHash } : {})
569
+ }
570
+ : {})
571
+ }
572
+ });
573
+ }
574
+ /** Step 5 — runVerify: drive the verify pipeline stage off the accepted result node
575
+ * and record the verifier node id on the task + accept context. */
576
+ function runWorkerVerify(accept) {
577
+ const { run, workerId, scope, task, parsedResult, destination, resultNode } = accept;
498
578
  const verifierResult = (0, pipeline_runner_1.createPipelineRunner)({ persist: false }).runPipelineStage(run, "verify", resultNode.id, {
499
579
  outputNodeId: `${run.id}:verifier:${task.id}`,
500
580
  outputStatus: "verified",
@@ -507,14 +587,24 @@ function recordWorkerOutput(run, workerId, resultPath, options = {}) {
507
587
  metadata: { taskId: task.id, workerId, resultNodeId: resultNode.id, sandboxProfileId: scope.sandboxProfileId }
508
588
  });
509
589
  task.verifierNodeId = verifierResult.outputNodeId;
590
+ accept.verifierNodeId = verifierResult.outputNodeId;
591
+ // Carry the verify verdict for the scope-status transition in recordWorkerCompletion.
592
+ accept.verifierStatus = verifierResult.status;
593
+ }
594
+ /** Step 6 — recordStateNode (worker record): assemble the worker output record +
595
+ * host-attested usage record, then persist the worker scope with the verify-derived
596
+ * status, output digest/size, and (when present) usage. */
597
+ function recordWorkerCompletion(accept, delegation) {
598
+ const { run, workerId, scope, task, absoluteResultPath, rawResult, resultNode, verifierNodeId, verifierStatus, pathAuditId, acceptedAuditId } = accept;
599
+ const { agentDelegation, telemetry } = delegation;
510
600
  const output = {
511
601
  workerId,
512
602
  taskId: task.id,
513
603
  resultPath: absoluteResultPath,
514
604
  recordedAt: new Date().toISOString(),
515
605
  stateNodeId: resultNode.id,
516
- verifierNodeId: verifierResult.outputNodeId,
517
- auditEventIds: [pathAudit.id, acceptedAudit.id]
606
+ verifierNodeId,
607
+ auditEventIds: [pathAuditId, acceptedAuditId]
518
608
  };
519
609
  // Host-attested usage rides on the worker record. Recorded when the agent
520
610
  // REPORTED a model OR token usage — `unreported`/absent stays ABSENT (never
@@ -537,7 +627,7 @@ function recordWorkerOutput(run, workerId, resultPath, options = {}) {
537
627
  updateWorkerScope(run, {
538
628
  ...scope,
539
629
  updatedAt: new Date().toISOString(),
540
- status: verifierResult.status === "advanced" ? "verified" : "completed",
630
+ status: verifierStatus === "advanced" ? "verified" : "completed",
541
631
  resultNodeId: resultNode.id,
542
632
  output,
543
633
  // Output integrity (v0.1.63): SHA256 digest + file size
@@ -545,20 +635,23 @@ function recordWorkerOutput(run, workerId, resultPath, options = {}) {
545
635
  outputSizeBytes: Buffer.byteLength(rawResult, "utf8"),
546
636
  ...(usageRecord ? { usage: usageRecord } : {})
547
637
  });
548
- const blackboardLinks = publishWorkerOutputToBlackboard(run, scope, task, parsedResult.summary, destination, absoluteResultPath, resultNode.evidence, acceptedAudit.id);
638
+ accept.output = output;
639
+ }
640
+ /** Step 7 — fanOut: publish the accepted output to the blackboard and record the
641
+ * multi-agent worker output (linking the blackboard message/artifact refs). */
642
+ function fanOutWorkerOutput(accept) {
643
+ const { run, workerId, scope, task, absoluteResultPath, parsedResult, destination, resultNode, verifierNodeId, acceptedAuditId } = accept;
644
+ const blackboardLinks = publishWorkerOutputToBlackboard(run, scope, task, parsedResult.summary, destination, absoluteResultPath, resultNode.evidence, acceptedAuditId);
549
645
  (0, multi_agent_1.recordMultiAgentWorkerOutput)(run, {
550
646
  workerId,
551
647
  taskId: task.id,
552
648
  resultNodeId: resultNode.id,
553
- verifierNodeId: verifierResult.outputNodeId,
649
+ verifierNodeId,
554
650
  evidence: resultNode.evidence,
555
651
  artifactPaths: [destination, absoluteResultPath],
556
652
  blackboardMessageIds: blackboardLinks.messageIds,
557
653
  blackboardArtifactRefIds: blackboardLinks.artifactRefIds
558
654
  });
559
- if (options.persist !== false)
560
- (0, state_1.saveCheckpoint)(run);
561
- return output;
562
655
  }
563
656
  function recordWorkerFailure(run, workerId, error, options = {}) {
564
657
  const scope = requireWorkerScope(run, workerId);
@@ -786,7 +879,19 @@ function loadWorkerScopesFromDisk(run) {
786
879
  .filter((entry) => entry.isDirectory())
787
880
  .map((entry) => node_path_1.default.join(workerRoot(run), entry.name, paths_1.WORKER_SCOPE_FILE))
788
881
  .filter((file) => node_fs_1.default.existsSync(file))
789
- .map((file) => JSON.parse(node_fs_1.default.readFileSync(file, "utf8")));
882
+ .map((file) => {
883
+ // One corrupt/partially-written worker.json must not blank the whole
884
+ // listing (summarizeWorkers/listWorkerScopes) — skip it with a diagnostic
885
+ // and surface every worker that IS readable.
886
+ try {
887
+ return (0, validation_1.validateWorkerScope)(JSON.parse(node_fs_1.default.readFileSync(file, "utf8")));
888
+ }
889
+ catch (error) {
890
+ process.stderr.write(`cw: skipping unreadable worker scope ${file}: ${error instanceof Error ? error.message : String(error)}\n`);
891
+ return undefined;
892
+ }
893
+ })
894
+ .filter((scope) => scope !== undefined);
790
895
  }
791
896
  function requireWorkerScope(run, workerId) {
792
897
  const scope = getWorkerScope(run, workerId);