cool-workflow 0.1.82 → 0.1.84

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 (92) hide show
  1. package/.claude-plugin/plugin.json +2 -2
  2. package/.codex-plugin/plugin.json +4 -4
  3. package/README.md +128 -120
  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/capability-core.js +16 -8
  11. package/dist/capability-registry.js +270 -0
  12. package/dist/cli/command-surface.js +1320 -0
  13. package/dist/cli.js +2 -1307
  14. package/dist/commit.js +5 -1
  15. package/dist/doctor.js +153 -0
  16. package/dist/mcp-server.js +15 -1451
  17. package/dist/mcp-surface.js +1441 -0
  18. package/dist/orchestrator.js +13 -0
  19. package/dist/reclamation/hash.js +72 -0
  20. package/dist/reclamation.js +25 -78
  21. package/dist/run-registry/queue.js +6 -7
  22. package/dist/run-registry.js +35 -24
  23. package/dist/scheduler.js +78 -53
  24. package/dist/version.js +1 -1
  25. package/dist/worker-accept/acceptance.js +114 -0
  26. package/dist/worker-accept/blackboard-fanout.js +80 -0
  27. package/dist/worker-accept/blackboard-linkage.js +19 -0
  28. package/dist/worker-accept/context.js +2 -0
  29. package/dist/worker-accept/telemetry-ledger.js +116 -0
  30. package/dist/worker-accept/validation.js +77 -0
  31. package/dist/worker-accept/verifier-completion.js +73 -0
  32. package/dist/worker-isolation.js +41 -446
  33. package/docs/agent-delegation-drive.7.md +94 -86
  34. package/docs/agent-framework.md +33 -32
  35. package/docs/candidate-scoring.7.md +26 -24
  36. package/docs/canonical-workflow-apps.7.md +40 -40
  37. package/docs/capability-topology-registry.7.md +24 -24
  38. package/docs/cli-mcp-parity.7.md +230 -154
  39. package/docs/contract-migration-tooling.7.md +52 -41
  40. package/docs/control-plane-scheduling.7.md +49 -41
  41. package/docs/coordinator-blackboard.7.md +30 -30
  42. package/docs/dogfood-one-real-repo.7.md +44 -44
  43. package/docs/durable-state-and-locking.7.md +38 -30
  44. package/docs/end-to-end-golden-path.7.md +29 -29
  45. package/docs/error-feedback.7.md +27 -27
  46. package/docs/evidence-adoption-reasoning-chain.7.md +66 -58
  47. package/docs/execution-backends.7.md +88 -80
  48. package/docs/getting-started.md +35 -18
  49. package/docs/index.md +3 -3
  50. package/docs/mcp-app-surface.7.md +64 -64
  51. package/docs/multi-agent-cli-mcp-surface.7.md +86 -77
  52. package/docs/multi-agent-eval-replay-harness.7.md +63 -55
  53. package/docs/multi-agent-operator-ux.7.md +73 -65
  54. package/docs/multi-agent-runtime-core.7.md +39 -39
  55. package/docs/multi-agent-topologies.7.md +24 -24
  56. package/docs/multi-agent-trust-policy-audit.7.md +38 -38
  57. package/docs/node-snapshot-diff-replay.7.md +30 -22
  58. package/docs/observability-cost-accounting.7.md +53 -45
  59. package/docs/operator-ux.7.md +30 -30
  60. package/docs/pipeline-runner.7.md +31 -31
  61. package/docs/project-index.md +16 -5
  62. package/docs/real-execution-backends.7.md +51 -43
  63. package/docs/release-and-migration.7.md +46 -38
  64. package/docs/release-tooling.7.md +67 -50
  65. package/docs/routines.md +16 -16
  66. package/docs/run-registry-control-plane.7.md +124 -116
  67. package/docs/run-retention-reclamation.7.md +49 -41
  68. package/docs/sandbox-profiles.7.md +32 -32
  69. package/docs/scheduled-tasks.md +14 -14
  70. package/docs/security-trust-hardening.7.md +29 -29
  71. package/docs/source-context-profiles.7.md +28 -28
  72. package/docs/state-explosion-management.7.md +67 -59
  73. package/docs/state-node.7.md +8 -8
  74. package/docs/team-collaboration.7.md +66 -58
  75. package/docs/trust-model.md +126 -126
  76. package/docs/unix-principles.md +80 -80
  77. package/docs/vendor-manifest-loadability.7.md +20 -20
  78. package/docs/verifier-gated-commit.7.md +16 -16
  79. package/docs/web-desktop-workbench.7.md +73 -65
  80. package/docs/worker-isolation.7.md +34 -37
  81. package/docs/workflow-app-framework.7.md +38 -38
  82. package/manifest/plugin.manifest.json +4 -4
  83. package/package.json +3 -2
  84. package/scripts/bump-version.js +9 -1
  85. package/scripts/canonical-apps.js +4 -4
  86. package/scripts/dogfood-release.js +1 -1
  87. package/scripts/gen-parity-doc.js +106 -0
  88. package/scripts/golden-path.js +4 -4
  89. package/scripts/parity-check.js +27 -57
  90. package/scripts/release-flow.js +7 -6
  91. package/scripts/sync-project-index.js +1 -1
  92. package/dist/verifier-registry.js +0 -46
@@ -21,20 +21,18 @@ const state_1 = require("./state");
21
21
  const pipeline_contract_1 = require("./pipeline-contract");
22
22
  const error_feedback_1 = require("./error-feedback");
23
23
  const state_node_1 = require("./state-node");
24
- const pipeline_runner_1 = require("./pipeline-runner");
25
- const verifier_1 = require("./verifier");
26
- const evidence_grounding_1 = require("./evidence-grounding");
27
- const result_normalize_1 = require("./result-normalize");
28
24
  const sandbox_profile_1 = require("./sandbox-profile");
29
25
  const execution_backend_1 = require("./execution-backend");
30
26
  const trust_audit_1 = require("./trust-audit");
31
- const multi_agent_1 = require("./multi-agent");
32
- const telemetry_attestation_1 = require("./telemetry-attestation");
33
- const telemetry_ledger_1 = require("./telemetry-ledger");
34
- const coordinator_1 = require("./coordinator");
35
27
  const helpers_1 = require("./worker-isolation/helpers");
36
28
  const paths_1 = require("./worker-isolation/paths");
37
29
  const validation_1 = require("./validation");
30
+ const acceptance_1 = require("./worker-accept/acceptance");
31
+ const blackboard_linkage_1 = require("./worker-accept/blackboard-linkage");
32
+ const blackboard_fanout_1 = require("./worker-accept/blackboard-fanout");
33
+ const telemetry_ledger_1 = require("./worker-accept/telemetry-ledger");
34
+ const validation_2 = require("./worker-accept/validation");
35
+ const verifier_completion_1 = require("./worker-accept/verifier-completion");
38
36
  exports.WORKER_ISOLATION_SCHEMA_VERSION = 1;
39
37
  function allocateWorkerScope(run, task, options = {}) {
40
38
  ensureWorkerState(run);
@@ -270,7 +268,15 @@ function getWorkerScope(run, workerId) {
270
268
  const file = node_path_1.default.join(workerRoot(run), (0, state_1.safeFileName)(workerId), paths_1.WORKER_SCOPE_FILE);
271
269
  if (!node_fs_1.default.existsSync(file))
272
270
  return undefined;
273
- const scope = (0, validation_1.validateWorkerScope)(JSON.parse(node_fs_1.default.readFileSync(file, "utf8")));
271
+ let scope;
272
+ try {
273
+ scope = (0, validation_1.validateWorkerScope)(JSON.parse(node_fs_1.default.readFileSync(file, "utf8")));
274
+ }
275
+ catch (error) {
276
+ // A present-but-corrupt scope fails closed with context, not a raw
277
+ // SyntaxError/validation throw bubbling up from deep in the call stack.
278
+ throw new Error(`Corrupt worker scope ${file}: ${error instanceof Error ? error.message : String(error)}`);
279
+ }
274
280
  upsertWorkerScope(run, scope);
275
281
  return scope;
276
282
  }
@@ -279,372 +285,22 @@ function recordWorkerOutput(run, workerId, resultPath, options = {}) {
279
285
  // steps are load-bearing (replay determinism + the hash-chained audit/telemetry
280
286
  // ledgers cross-link by parent event ids), so each helper runs exactly where it
281
287
  // did before and mutates the shared `accept` context in place. Do NOT reorder.
282
- const accept = validateWorkerResult(run, workerId, resultPath, options);
283
- const delegation = attestWorkerDelegation(accept);
284
- acceptWorkerResult(accept, delegation);
285
- recordWorkerDelegationLedger(accept, delegation);
286
- runWorkerVerify(accept);
287
- recordWorkerCompletion(accept, delegation);
288
- fanOutWorkerOutput(accept);
288
+ const accept = (0, validation_2.validateWorkerResult)(run, workerId, resultPath, options, {
289
+ requireWorkerScope,
290
+ requireWorkerTask,
291
+ validateWorkerBoundary,
292
+ recordWorkerFailure
293
+ });
294
+ const delegation = (0, telemetry_ledger_1.attestWorkerDelegation)(accept, { recordWorkerFailure });
295
+ (0, acceptance_1.acceptWorkerResult)(accept, delegation);
296
+ (0, telemetry_ledger_1.recordWorkerDelegationLedger)(accept, delegation);
297
+ (0, verifier_completion_1.runWorkerVerify)(accept);
298
+ (0, verifier_completion_1.recordWorkerCompletion)(accept, delegation, { updateWorkerScope });
299
+ (0, blackboard_fanout_1.fanOutWorkerOutput)(accept);
289
300
  if (options.persist !== false)
290
301
  (0, state_1.saveCheckpoint)(run);
291
302
  return accept.output;
292
303
  }
293
- /** Step 1 — validateResult: resolve scope/task, enforce the sandbox boundary, the
294
- * result-file existence, the envelope contract, and (opt-in) resolvable evidence.
295
- * Fail-closed: any guard records a worker failure and throws BEFORE accept-side
296
- * state mutation. Returns the partially-filled accept context on success. */
297
- function validateWorkerResult(run, workerId, resultPath, options) {
298
- const scope = requireWorkerScope(run, workerId);
299
- const task = requireWorkerTask(run, scope);
300
- const absoluteResultPath = node_path_1.default.resolve(resultPath);
301
- const violation = validateWorkerBoundary(run, workerId, { ...options, policy: options.policy, path: absoluteResultPath });
302
- if (violation) {
303
- (0, trust_audit_1.recordSandboxPathDecision)(run, {
304
- workerId,
305
- taskId: task.id,
306
- sandboxProfileId: scope.sandboxProfileId,
307
- policySnapshot: scope.sandboxPolicy,
308
- target: absoluteResultPath,
309
- decision: "denied",
310
- metadata: { code: violation.code, allowedPaths: violation.allowedPaths }
311
- });
312
- recordWorkerFailure(run, workerId, violation, { ...options, path: absoluteResultPath, code: violation.code, retryable: false });
313
- throw new Error(violation.message);
314
- }
315
- if (!node_fs_1.default.existsSync(absoluteResultPath)) {
316
- const error = (0, helpers_1.structuredError)("worker-result-missing", `Worker result file does not exist: ${absoluteResultPath}`, {
317
- path: absoluteResultPath,
318
- retryable: true
319
- });
320
- recordWorkerFailure(run, workerId, error, { ...options, persist: options.persist });
321
- throw new Error(error.message);
322
- }
323
- const rawResult = node_fs_1.default.readFileSync(absoluteResultPath, "utf8");
324
- const parsedResult = (0, verifier_1.parseResultEnvelope)(rawResult);
325
- (0, verifier_1.validateResultEnvelope)(task, parsedResult);
326
- // Strict evidence resolution (v0.1.40 self-audit P1, opt-in via
327
- // CW_REQUIRE_RESOLVABLE_EVIDENCE): fail closed if the result cites file-style
328
- // evidence that does not resolve on disk, so a worker cannot land a result
329
- // whose evidence locators point nowhere. Off by default — the default gate is
330
- // the deterministic grounding check in validateResultEnvelope.
331
- if ((0, evidence_grounding_1.requireResolvableEvidence)()) {
332
- const baseDirs = Array.from(new Set([run.cwd, process.cwd(), scope.workerDir, run.paths.runDir].filter(Boolean)));
333
- const unresolved = (0, evidence_grounding_1.unresolvedFileEvidence)(parsedResult.evidence, baseDirs);
334
- if (unresolved.length) {
335
- const error = (0, helpers_1.structuredError)("worker-evidence-unresolvable", `Worker ${workerId} result cites file evidence that does not resolve on disk: ${unresolved.join(", ")}`, { path: absoluteResultPath, retryable: false });
336
- recordWorkerFailure(run, workerId, error, { ...options, persist: options.persist });
337
- throw new Error(error.message);
338
- }
339
- }
340
- return {
341
- run,
342
- workerId,
343
- options,
344
- scope,
345
- task,
346
- absoluteResultPath,
347
- rawResult,
348
- parsedResult,
349
- destination: "",
350
- pathAuditId: "",
351
- acceptedAuditId: "",
352
- resultNode: undefined,
353
- verifierNodeId: "",
354
- verifierStatus: "",
355
- output: undefined
356
- };
357
- }
358
- /** Step 2 — attestSandbox/attestDelegation: verify the agent's signed telemetry
359
- * BEFORE recording it, enforce the opt-in require-attested-telemetry gate (still
360
- * fail-closed, pre-mutation), and build the agent-hop provenance. Non-agent hops
361
- * return an empty delegation. */
362
- function attestWorkerDelegation(accept) {
363
- const { run, workerId, options, task, absoluteResultPath, rawResult } = accept;
364
- // Agent Delegation Drive (v0.1.38): if this worker's result.md was produced by an
365
- // EXTERNAL agent, record the agent-hop attestation AS PROVENANCE — the agent
366
- // (kind:process) handle, the agent-REPORTED model (never CW_AGENT_MODEL), the
367
- // prompt digest, the secret-stripped args, and the result digest computed HERE
368
- // from the accepted result.md. These live in the result node's metadata (covered
369
- // by the v0.1.35 snapshot body) + a trust-audit event, NEVER in `evidence`.
370
- // Track 1: verify the agent's signed telemetry BEFORE recording it. CW holds
371
- // only the operator's PUBLIC key — it verifies attribution, never measures
372
- // usage. Absent/invalid signature ⇒ `unattested`/`absent`, surfaced loudly,
373
- // NEVER silently recorded as trusted.
374
- const telemetry = options.agentDelegation
375
- ? (0, telemetry_attestation_1.verifyTelemetryAttestation)(options.agentDelegation.reportedUsage, options.agentDelegation.usageSignature, (0, telemetry_attestation_1.resolveTrustPublicKey)(options.agentDelegation.usageTrustPublicKey), { runId: run.id, taskId: task.id, promptDigest: options.agentDelegation.promptDigest })
376
- : undefined;
377
- // Track 1 fail-closed (Decision 2 — OPT-IN, off by default). When the operator
378
- // requires attested telemetry, a delegated hop whose verdict is not `attested`
379
- // is REJECTED here — BEFORE any accept-side state mutation — so the drive parks
380
- // it instead of recording unverifiable usage. Default behavior is unchanged
381
- // (flag-and-surface). Non-agent hops carry no verdict and are never blocked.
382
- if (options.requireAttestedTelemetry && telemetry && telemetry.status !== "attested") {
383
- const error = (0, helpers_1.structuredError)("telemetry-unattested-blocked", `Worker ${workerId} telemetry is ${telemetry.status} (${telemetry.reason || "unverified"}) and require-attested-telemetry is enabled — refusing to accept a hop whose usage cannot be cryptographically verified`, { path: absoluteResultPath, retryable: false });
384
- recordWorkerFailure(run, workerId, error, { ...options, persist: options.persist });
385
- throw new Error(error.message);
386
- }
387
- const agentDelegation = options.agentDelegation
388
- ? {
389
- schemaVersion: 1,
390
- backendId: "agent",
391
- handle: options.agentDelegation.handle,
392
- model: options.agentDelegation.model,
393
- promptDigest: options.agentDelegation.promptDigest,
394
- resultDigest: (0, execution_backend_1.sha256)(rawResult),
395
- command: options.agentDelegation.command,
396
- args: options.agentDelegation.args,
397
- exitCode: options.agentDelegation.exitCode,
398
- ...(options.agentDelegation.reportedUsage ? { reportedUsage: options.agentDelegation.reportedUsage } : {}),
399
- ...(options.agentDelegation.usageSignature ? { usageSignature: options.agentDelegation.usageSignature } : {}),
400
- ...(telemetry ? { usageAttestation: telemetry.status, usageAttestationReason: telemetry.reason } : {})
401
- }
402
- : undefined;
403
- return { agentDelegation, telemetry };
404
- }
405
- /** Step 3 — recordStateNode/audit: the irreversible accept. Records the allowed
406
- * path decision, copies the result into the run results dir, completes the task,
407
- * builds + appends the result node, emits the accepted audit event, re-normalizes
408
- * node evidence against both audit ids, and surfaces the empty-capture warning.
409
- * Writes destination/pathAuditId/acceptedAuditId/resultNode back into `accept`. */
410
- function acceptWorkerResult(accept, delegation) {
411
- const { run, workerId, scope, task, absoluteResultPath, parsedResult } = accept;
412
- const { agentDelegation } = delegation;
413
- const pathAudit = (0, trust_audit_1.recordSandboxPathDecision)(run, {
414
- workerId,
415
- taskId: task.id,
416
- sandboxProfileId: scope.sandboxProfileId,
417
- policySnapshot: scope.sandboxPolicy,
418
- target: absoluteResultPath,
419
- decision: "allowed",
420
- metadata: { operation: "worker-output-acceptance" }
421
- });
422
- const destination = node_path_1.default.join(run.paths.resultsDir, `${(0, state_1.safeFileName)(task.id)}.md`);
423
- node_fs_1.default.mkdirSync(run.paths.resultsDir, { recursive: true });
424
- node_fs_1.default.copyFileSync(absoluteResultPath, destination);
425
- task.status = "completed";
426
- task.completedAt = new Date().toISOString();
427
- task.resultPath = destination;
428
- task.loopStage = "observe";
429
- task.result = parsedResult;
430
- const evidence = (0, trust_audit_1.normalizeEvidence)(run, parsedResult.evidence.map((entry, index) => ({
431
- id: `result:${index + 1}`,
432
- source: "cw:result",
433
- locator: entry,
434
- summary: entry
435
- })), { source: "cw-validated", workerId, taskId: task.id, auditEventIds: [pathAudit.id] });
436
- const resultNode = (0, state_node_1.appendRunNode)(run, (0, state_node_1.createStateNode)({
437
- id: `${run.id}:result:${task.id}`,
438
- kind: "result",
439
- status: "completed",
440
- loopStage: "observe",
441
- inputs: { taskId: task.id, dispatchId: task.dispatchId, workerId },
442
- outputs: parsedResult,
443
- artifacts: [
444
- { id: "result", kind: "markdown", path: destination },
445
- { id: "worker-result", kind: "markdown", path: absoluteResultPath }
446
- ],
447
- evidence,
448
- parents: task.dispatchId ? [`${run.id}:dispatch:${task.dispatchId}`] : [task.stateNodeId || `${run.id}:task:${task.id}`],
449
- contractId: pipeline_contract_1.DEFAULT_PIPELINE_CONTRACT_ID,
450
- metadata: {
451
- taskId: task.id,
452
- workerId,
453
- workerDir: scope.workerDir,
454
- sandboxProfileId: scope.sandboxProfileId,
455
- auditEventIds: [pathAudit.id],
456
- // Empty-capture warning (v0.1.42): even after robust normalization the result
457
- // yielded NO findings and NO evidence — surfaced, never silently passed.
458
- ...((0, result_normalize_1.isEmptyCapture)(parsedResult) ? { captureWarning: "no findings or evidence captured from result.md" } : {}),
459
- // Folded into the snapshotted node body so v0.1.35 replay re-verifies the
460
- // prompt/result/model digests WITHOUT re-spawning the agent. NOT evidence.
461
- ...(agentDelegation ? { agentDelegation } : {})
462
- }
463
- }));
464
- const acceptedAudit = (0, trust_audit_1.recordTrustAuditEvent)(run, {
465
- kind: "worker.output",
466
- decision: "accepted",
467
- source: "cw-validated",
468
- workerId,
469
- taskId: task.id,
470
- nodeId: resultNode.id,
471
- sandboxProfileId: scope.sandboxProfileId,
472
- policySnapshot: scope.sandboxPolicy,
473
- normalizedPath: absoluteResultPath,
474
- evidence,
475
- parentEventIds: [pathAudit.id],
476
- metadata: { destination }
477
- });
478
- resultNode.evidence = (0, trust_audit_1.normalizeEvidence)(run, resultNode.evidence, {
479
- source: "cw-validated",
480
- workerId,
481
- taskId: task.id,
482
- resultNodeId: resultNode.id,
483
- auditEventIds: [pathAudit.id, acceptedAudit.id]
484
- });
485
- (0, state_node_1.appendRunNode)(run, resultNode);
486
- task.resultNodeId = resultNode.id;
487
- // Warn (don't silently pass) when a worker's result captured no structured signal
488
- // at all — the v0.1.41 self-audit's "accepted with evidenceCount:0" failure mode.
489
- if ((0, result_normalize_1.isEmptyCapture)(parsedResult)) {
490
- (0, trust_audit_1.recordTrustAuditEvent)(run, {
491
- kind: "worker.capture-warning",
492
- decision: "recorded",
493
- source: "cw-validated",
494
- workerId,
495
- taskId: task.id,
496
- nodeId: resultNode.id,
497
- parentEventIds: [acceptedAudit.id],
498
- metadata: { reason: "no findings or evidence captured from result.md", resultPath: destination }
499
- });
500
- }
501
- accept.destination = destination;
502
- accept.pathAuditId = pathAudit.id;
503
- accept.acceptedAuditId = acceptedAudit.id;
504
- accept.resultNode = resultNode;
505
- }
506
- /** Step 4 — recordTelemetryLedger: the agent-hop attestation. Binds the telemetry
507
- * verdict into the append-only hash-chained ledger BEFORE the audit event (so the
508
- * event can cross-link the record hash), then emits the worker.agent-delegation
509
- * audit event. No-op for non-agent hops. */
510
- function recordWorkerDelegationLedger(accept, delegation) {
511
- const { agentDelegation } = delegation;
512
- // The agent-hop attestation event — hung off worker.output, alongside
513
- // worker.backend. Recorded in trust-audit/provenance, NEVER in node evidence.
514
- if (!agentDelegation)
515
- return;
516
- const { run, workerId, scope, task, resultNode, acceptedAuditId } = accept;
517
- // Track 1 (tamper-evidence): bind this verdict into the append-only,
518
- // hash-chained telemetry ledger BEFORE the audit event, so the event can
519
- // cross-link the record hash. Editing the recorded verdict/usage later breaks
520
- // the chain (verifyTelemetryLedger). Only when a verdict was computed.
521
- const ledgerRecord = agentDelegation.usageAttestation
522
- ? (0, telemetry_ledger_1.appendTelemetryAttestation)(run, {
523
- workerId,
524
- taskId: task.id,
525
- promptDigest: agentDelegation.promptDigest,
526
- reportedUsage: agentDelegation.reportedUsage,
527
- usageSignature: agentDelegation.usageSignature,
528
- attestation: agentDelegation.usageAttestation,
529
- attestationReason: agentDelegation.usageAttestationReason
530
- })
531
- : undefined;
532
- (0, trust_audit_1.recordTrustAuditEvent)(run, {
533
- kind: "worker.agent-delegation",
534
- decision: "recorded",
535
- source: "host-attested",
536
- workerId,
537
- taskId: task.id,
538
- nodeId: resultNode.id,
539
- sandboxProfileId: scope.sandboxProfileId,
540
- policySnapshot: scope.sandboxPolicy,
541
- parentEventIds: [acceptedAuditId],
542
- metadata: {
543
- backendId: agentDelegation.backendId,
544
- handleKind: agentDelegation.handle.kind,
545
- handleRef: agentDelegation.handle.ref,
546
- model: agentDelegation.model,
547
- promptDigest: agentDelegation.promptDigest,
548
- resultDigest: agentDelegation.resultDigest,
549
- command: agentDelegation.command,
550
- args: agentDelegation.args,
551
- exitCode: agentDelegation.exitCode,
552
- // Track 1: the telemetry verdict travels with the agent-hop event so the
553
- // audit report can surface `unattested` usage loudly. Absent ⇒ no usage.
554
- ...(agentDelegation.usageAttestation
555
- ? {
556
- telemetryAttestation: agentDelegation.usageAttestation,
557
- ...(agentDelegation.usageAttestationReason ? { telemetryAttestationReason: agentDelegation.usageAttestationReason } : {}),
558
- ...(agentDelegation.reportedUsage ? { reportedUsage: agentDelegation.reportedUsage } : {}),
559
- // Cross-link to the hash-chained ledger entry (tamper-evidence).
560
- ...(ledgerRecord ? { telemetryRecordId: ledgerRecord.recordId, telemetryRecordHash: ledgerRecord.recordHash, telemetryPrevHash: ledgerRecord.prevHash } : {})
561
- }
562
- : {})
563
- }
564
- });
565
- }
566
- /** Step 5 — runVerify: drive the verify pipeline stage off the accepted result node
567
- * and record the verifier node id on the task + accept context. */
568
- function runWorkerVerify(accept) {
569
- const { run, workerId, scope, task, parsedResult, destination, resultNode } = accept;
570
- const verifierResult = (0, pipeline_runner_1.createPipelineRunner)({ persist: false }).runPipelineStage(run, "verify", resultNode.id, {
571
- outputNodeId: `${run.id}:verifier:${task.id}`,
572
- outputStatus: "verified",
573
- loopStage: "adjust",
574
- outputs: { accepted: true, workerId },
575
- artifacts: [{ id: "result", kind: "markdown", path: destination }],
576
- evidence: resultNode.evidence.length
577
- ? resultNode.evidence
578
- : [{ id: "result:summary", source: "summary", summary: parsedResult.summary }],
579
- metadata: { taskId: task.id, workerId, resultNodeId: resultNode.id, sandboxProfileId: scope.sandboxProfileId }
580
- });
581
- task.verifierNodeId = verifierResult.outputNodeId;
582
- accept.verifierNodeId = verifierResult.outputNodeId;
583
- // Carry the verify verdict for the scope-status transition in recordWorkerCompletion.
584
- accept.verifierStatus = verifierResult.status;
585
- }
586
- /** Step 6 — recordStateNode (worker record): assemble the worker output record +
587
- * host-attested usage record, then persist the worker scope with the verify-derived
588
- * status, output digest/size, and (when present) usage. */
589
- function recordWorkerCompletion(accept, delegation) {
590
- const { run, workerId, scope, task, absoluteResultPath, rawResult, resultNode, verifierNodeId, verifierStatus, pathAuditId, acceptedAuditId } = accept;
591
- const { agentDelegation, telemetry } = delegation;
592
- const output = {
593
- workerId,
594
- taskId: task.id,
595
- resultPath: absoluteResultPath,
596
- recordedAt: new Date().toISOString(),
597
- stateNodeId: resultNode.id,
598
- verifierNodeId,
599
- auditEventIds: [pathAuditId, acceptedAuditId]
600
- };
601
- // Host-attested usage rides on the worker record. Recorded when the agent
602
- // REPORTED a model OR token usage — `unreported`/absent stays ABSENT (never
603
- // backfilled from the operator-chosen CW_AGENT_MODEL, never synthesized).
604
- // Track 1: the attestation verdict (`attested`/`unattested`/`absent`) and its
605
- // reason ride along, and the token buckets come from the (verified-or-not)
606
- // reported usage — CW still never measures them, it records + labels them.
607
- const reportedModel = agentDelegation && agentDelegation.model && agentDelegation.model !== "unreported" ? agentDelegation.model : undefined;
608
- const usageRecord = agentDelegation && (reportedModel || agentDelegation.reportedUsage)
609
- ? {
610
- schemaVersion: 1,
611
- source: "host-attested",
612
- ...(reportedModel ? { model: reportedModel } : {}),
613
- ...(0, telemetry_attestation_1.normalizeReportedUsage)(agentDelegation.reportedUsage),
614
- attestedAt: new Date().toISOString(),
615
- ...(telemetry ? { attestation: telemetry.status, ...(telemetry.reason ? { attestationReason: telemetry.reason } : {}) } : {}),
616
- note: "agent-delegation host-attested usage"
617
- }
618
- : undefined;
619
- updateWorkerScope(run, {
620
- ...scope,
621
- updatedAt: new Date().toISOString(),
622
- status: verifierStatus === "advanced" ? "verified" : "completed",
623
- resultNodeId: resultNode.id,
624
- output,
625
- // Output integrity (v0.1.63): SHA256 digest + file size
626
- outputDigest: (0, execution_backend_1.sha256)(rawResult),
627
- outputSizeBytes: Buffer.byteLength(rawResult, "utf8"),
628
- ...(usageRecord ? { usage: usageRecord } : {})
629
- });
630
- accept.output = output;
631
- }
632
- /** Step 7 — fanOut: publish the accepted output to the blackboard and record the
633
- * multi-agent worker output (linking the blackboard message/artifact refs). */
634
- function fanOutWorkerOutput(accept) {
635
- const { run, workerId, scope, task, absoluteResultPath, parsedResult, destination, resultNode, verifierNodeId, acceptedAuditId } = accept;
636
- const blackboardLinks = publishWorkerOutputToBlackboard(run, scope, task, parsedResult.summary, destination, absoluteResultPath, resultNode.evidence, acceptedAuditId);
637
- (0, multi_agent_1.recordMultiAgentWorkerOutput)(run, {
638
- workerId,
639
- taskId: task.id,
640
- resultNodeId: resultNode.id,
641
- verifierNodeId,
642
- evidence: resultNode.evidence,
643
- artifactPaths: [destination, absoluteResultPath],
644
- blackboardMessageIds: blackboardLinks.messageIds,
645
- blackboardArtifactRefIds: blackboardLinks.artifactRefIds
646
- });
647
- }
648
304
  function recordWorkerFailure(run, workerId, error, options = {}) {
649
305
  const scope = requireWorkerScope(run, workerId);
650
306
  const task = requireWorkerTask(run, scope);
@@ -871,7 +527,19 @@ function loadWorkerScopesFromDisk(run) {
871
527
  .filter((entry) => entry.isDirectory())
872
528
  .map((entry) => node_path_1.default.join(workerRoot(run), entry.name, paths_1.WORKER_SCOPE_FILE))
873
529
  .filter((file) => node_fs_1.default.existsSync(file))
874
- .map((file) => (0, validation_1.validateWorkerScope)(JSON.parse(node_fs_1.default.readFileSync(file, "utf8"))));
530
+ .map((file) => {
531
+ // One corrupt/partially-written worker.json must not blank the whole
532
+ // listing (summarizeWorkers/listWorkerScopes) — skip it with a diagnostic
533
+ // and surface every worker that IS readable.
534
+ try {
535
+ return (0, validation_1.validateWorkerScope)(JSON.parse(node_fs_1.default.readFileSync(file, "utf8")));
536
+ }
537
+ catch (error) {
538
+ process.stderr.write(`cw: skipping unreadable worker scope ${file}: ${error instanceof Error ? error.message : String(error)}\n`);
539
+ return undefined;
540
+ }
541
+ })
542
+ .filter((scope) => scope !== undefined);
875
543
  }
876
544
  function requireWorkerScope(run, workerId) {
877
545
  const scope = getWorkerScope(run, workerId);
@@ -918,7 +586,7 @@ function sandboxPolicyForBoundary(run, scope, options = {}) {
918
586
  });
919
587
  }
920
588
  function blackboardManifest(run, scope) {
921
- const linkage = blackboardLinkage(run, scope);
589
+ const linkage = (0, blackboard_linkage_1.blackboardLinkage)(run, scope);
922
590
  if (!linkage.blackboardId)
923
591
  return undefined;
924
592
  const root = run.paths.blackboardDir || node_path_1.default.join(run.paths.runDir, "blackboard");
@@ -938,79 +606,6 @@ function blackboardManifest(run, scope) {
938
606
  ]
939
607
  };
940
608
  }
941
- function publishWorkerOutputToBlackboard(run, scope, task, summary, destination, workerResultPath, evidence, acceptedAuditId) {
942
- const linkage = blackboardLinkage(run, scope);
943
- if (!linkage.blackboardId || !linkage.topicIds.length)
944
- return { messageIds: [], artifactRefIds: [] };
945
- const topicId = linkage.topicIds[0];
946
- const artifactRefs = [
947
- (0, coordinator_1.addBlackboardArtifact)(run, {
948
- topicId,
949
- blackboardId: linkage.blackboardId,
950
- kind: "worker-result",
951
- path: destination,
952
- owner: { kind: "worker", id: scope.id },
953
- author: { kind: "runtime", id: "cw" },
954
- source: "cw-validated-worker-output",
955
- provenance: {
956
- workerId: scope.id,
957
- taskId: task.id,
958
- multiAgentRunId: scope.multiAgent?.runId,
959
- agentGroupId: scope.multiAgent?.groupId,
960
- agentRoleId: scope.multiAgent?.roleId,
961
- agentMembershipId: scope.multiAgent?.membershipId,
962
- auditEventIds: [acceptedAuditId]
963
- },
964
- evidenceRefs: evidence.map((entry) => entry.locator || entry.path || entry.summary || entry.id).filter(Boolean),
965
- auditEventIds: [acceptedAuditId],
966
- metadata: { workerResultPath }
967
- })
968
- ];
969
- const message = (0, coordinator_1.postBlackboardMessage)(run, {
970
- topicId,
971
- blackboardId: linkage.blackboardId,
972
- body: summary,
973
- author: { kind: "worker", id: scope.id },
974
- scope: { kind: "worker", id: scope.id },
975
- artifactRefIds: artifactRefs.map((artifact) => artifact.id),
976
- evidenceRefs: evidence.map((entry) => entry.locator || entry.path || entry.summary || entry.id).filter(Boolean),
977
- auditEventIds: [acceptedAuditId],
978
- links: {
979
- multiAgentRunId: scope.multiAgent?.runId,
980
- agentGroupId: scope.multiAgent?.groupId,
981
- agentRoleId: scope.multiAgent?.roleId,
982
- agentMembershipId: scope.multiAgent?.membershipId,
983
- agentFanoutId: scope.multiAgent?.fanoutId,
984
- taskId: task.id,
985
- workerId: scope.id,
986
- auditEventIds: [acceptedAuditId]
987
- },
988
- metadata: {
989
- taskId: task.id,
990
- resultPath: destination,
991
- multiAgent: scope.multiAgent
992
- }
993
- });
994
- return {
995
- messageIds: [message.id],
996
- artifactRefIds: artifactRefs.map((artifact) => artifact.id)
997
- };
998
- }
999
- function blackboardLinkage(run, scope) {
1000
- const membershipId = scope.multiAgent?.membershipId;
1001
- const membership = membershipId ? run.multiAgent?.memberships.find((entry) => entry.id === membershipId) : undefined;
1002
- const group = scope.multiAgent?.groupId ? run.multiAgent?.groups.find((entry) => entry.id === scope.multiAgent?.groupId) : undefined;
1003
- const role = scope.multiAgent?.roleId ? run.multiAgent?.roles.find((entry) => entry.id === scope.multiAgent?.roleId) : undefined;
1004
- const multiAgentRun = scope.multiAgent?.runId ? run.multiAgent?.runs.find((entry) => entry.id === scope.multiAgent?.runId) : undefined;
1005
- const blackboardId = membership?.blackboardId || group?.blackboardId || role?.blackboardId || multiAgentRun?.blackboardId;
1006
- const topicIds = (0, helpers_1.unique)([
1007
- ...(membership?.topicIds || []),
1008
- ...(group?.topicIds || []),
1009
- ...(role?.topicIds || []),
1010
- ...(multiAgentRun?.topicIds || [])
1011
- ]);
1012
- return { blackboardId, topicIds };
1013
- }
1014
609
  function normalizeWorkerError(error, scope, options) {
1015
610
  if ((0, helpers_1.isBoundaryViolation)(error)) {
1016
611
  return (0, helpers_1.structuredError)(error.code, error.message, {