cool-workflow 0.1.98 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (306) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/README.md +11 -2
  4. package/apps/architecture-review/app.json +1 -1
  5. package/apps/architecture-review-fast/app.json +1 -1
  6. package/apps/end-to-end-golden-path/app.json +1 -1
  7. package/apps/pr-review-fix-ci/app.json +1 -1
  8. package/apps/release-cut/app.json +1 -1
  9. package/apps/research-synthesis/app.json +1 -1
  10. package/dist/cli/dispatch.js +236 -0
  11. package/dist/cli/entry.js +120 -0
  12. package/dist/cli/io.js +21 -4
  13. package/dist/cli/parseargv.js +157 -0
  14. package/dist/cli.js +6 -33
  15. package/dist/core/capability-table.js +3534 -0
  16. package/dist/core/format/help.js +314 -0
  17. package/dist/{state-explosion/format.js → core/format/state-explosion-text.js} +10 -1
  18. package/dist/core/hash.js +137 -0
  19. package/dist/core/multi-agent/candidate-scoring.js +219 -0
  20. package/dist/core/multi-agent/collaboration.js +481 -0
  21. package/dist/core/multi-agent/coordinator.js +515 -0
  22. package/dist/core/multi-agent/eval-replay.js +306 -0
  23. package/dist/core/multi-agent/runtime.js +929 -0
  24. package/dist/core/multi-agent/topology.js +298 -0
  25. package/dist/core/multi-agent/trust-policy.js +197 -0
  26. package/dist/core/pipeline/commit-gate.js +320 -0
  27. package/dist/{pipeline-contract.js → core/pipeline/contract.js} +24 -37
  28. package/dist/core/pipeline/dispatch.js +103 -0
  29. package/dist/core/pipeline/drive-decide.js +227 -0
  30. package/dist/core/pipeline/error-feedback.js +161 -0
  31. package/dist/core/pipeline/loop-expansion.js +124 -0
  32. package/dist/{result-normalize.js → core/pipeline/result-normalize.js} +14 -37
  33. package/dist/core/pipeline/runner.js +230 -0
  34. package/dist/{contract-migration.js → core/state/contract-migration.js} +68 -92
  35. package/dist/{state-migrations.js → core/state/migrations.js} +103 -96
  36. package/dist/core/state/node-projection.js +95 -0
  37. package/dist/core/state/node-snapshot.js +230 -0
  38. package/dist/core/state/run-paths.js +93 -0
  39. package/dist/{schema-validate.js → core/state/schema-validate.js} +35 -28
  40. package/dist/core/state/schema.js +50 -0
  41. package/dist/core/state/state-explosion/digest.js +243 -0
  42. package/dist/core/state/state-explosion/graph.js +527 -0
  43. package/dist/{state-explosion → core/state/state-explosion}/helpers.js +34 -3
  44. package/dist/core/state/state-explosion/report.js +187 -0
  45. package/dist/{state-explosion → core/state/state-explosion}/size.js +25 -7
  46. package/dist/{state-node.js → core/state/state-node.js} +90 -113
  47. package/dist/core/state/types.js +19 -0
  48. package/dist/{validation.js → core/state/validation.js} +64 -131
  49. package/dist/core/trust/evidence-grounding.js +134 -0
  50. package/dist/core/trust/ledger.js +199 -0
  51. package/dist/{telemetry-attestation.js → core/trust/telemetry-attestation.js} +94 -68
  52. package/dist/core/trust/telemetry-ledger.js +127 -0
  53. package/dist/core/types.js +20 -0
  54. package/dist/core/version.js +16 -0
  55. package/dist/{workflow-app-framework.js → core/workflow-apps/app-schema.js} +337 -426
  56. package/dist/mcp/dispatch.js +104 -0
  57. package/dist/mcp/server.js +144 -0
  58. package/dist/mcp-server.js +6 -84
  59. package/dist/{agent-config.js → shell/agent-config.js} +118 -71
  60. package/dist/shell/app-run-cli.js +88 -0
  61. package/dist/shell/audit-cli.js +259 -0
  62. package/dist/shell/audit-provenance.js +83 -0
  63. package/dist/shell/candidate-scoring-io.js +459 -0
  64. package/dist/shell/collaboration-io.js +264 -0
  65. package/dist/shell/commit-summary.js +104 -0
  66. package/dist/shell/commit.js +290 -0
  67. package/dist/shell/coordinator-io.js +476 -0
  68. package/dist/shell/demo-cli.js +19 -0
  69. package/dist/shell/dispatch.js +162 -0
  70. package/dist/{doctor.js → shell/doctor.js} +123 -56
  71. package/dist/shell/drive.js +873 -0
  72. package/dist/shell/error-feedback-io.js +305 -0
  73. package/dist/shell/eval-io.js +473 -0
  74. package/dist/{multi-agent-eval/format.js → shell/eval-text.js} +78 -49
  75. package/dist/{evidence-reasoning.js → shell/evidence-reasoning.js} +124 -255
  76. package/dist/shell/exec-backend-cli.js +88 -0
  77. package/dist/shell/execution-backend/agent.js +475 -0
  78. package/dist/shell/execution-backend/ci.js +15 -0
  79. package/dist/shell/execution-backend/container.js +69 -0
  80. package/dist/shell/execution-backend/envelopes.js +55 -0
  81. package/dist/shell/execution-backend/local.js +113 -0
  82. package/dist/shell/execution-backend/probes.js +175 -0
  83. package/dist/shell/execution-backend/registry.js +402 -0
  84. package/dist/shell/execution-backend/remote.js +128 -0
  85. package/dist/shell/execution-backend/types.js +11 -0
  86. package/dist/shell/feedback-cli.js +81 -0
  87. package/dist/shell/feedback-operations.js +48 -0
  88. package/dist/shell/fs-atomic.js +276 -0
  89. package/dist/shell/harness.js +98 -0
  90. package/dist/shell/ledger-cli.js +212 -0
  91. package/dist/shell/ledger-io.js +169 -0
  92. package/dist/shell/man-cli.js +89 -0
  93. package/dist/shell/metrics-cli.js +98 -0
  94. package/dist/shell/multi-agent-cli.js +1002 -0
  95. package/dist/shell/multi-agent-host.js +563 -0
  96. package/dist/shell/multi-agent-io.js +387 -0
  97. package/dist/{multi-agent-operator-ux.js → shell/multi-agent-operator-ux.js} +234 -191
  98. package/dist/shell/node-store.js +124 -0
  99. package/dist/{observability/format.js → shell/observability-format.js} +7 -1
  100. package/dist/{observability/intake.js → shell/observability-intake.js} +79 -56
  101. package/dist/{observability.js → shell/observability.js} +159 -332
  102. package/dist/{onramp.js → shell/onramp.js} +11 -0
  103. package/dist/{operator-ux/format.js → shell/operator-ux-text.js} +250 -239
  104. package/dist/shell/operator-ux.js +431 -0
  105. package/dist/shell/orchestrator.js +231 -0
  106. package/dist/shell/pipeline-cli.js +667 -0
  107. package/dist/shell/pipeline.js +217 -0
  108. package/dist/shell/reclamation-io.js +1366 -0
  109. package/dist/shell/registry-cli.js +329 -0
  110. package/dist/{remote-source.js → shell/remote-source.js} +2 -2
  111. package/dist/shell/report-cli.js +101 -0
  112. package/dist/shell/report-view-cli.js +117 -0
  113. package/dist/{orchestrator → shell}/report.js +289 -282
  114. package/dist/shell/reporter.js +62 -0
  115. package/dist/shell/run-export-cli.js +106 -0
  116. package/dist/shell/run-export.js +680 -0
  117. package/dist/shell/run-registry-io.js +1014 -0
  118. package/dist/shell/run-store.js +164 -0
  119. package/dist/{sandbox-profile.js → shell/sandbox-profile.js} +134 -95
  120. package/dist/{scheduler.js → shell/scheduler-io.js} +248 -48
  121. package/dist/shell/scheduling-io.js +311 -0
  122. package/dist/shell/state-cli.js +181 -0
  123. package/dist/shell/state-explosion-cli.js +197 -0
  124. package/dist/shell/telemetry-cli.js +85 -0
  125. package/dist/{telemetry-demo.js → shell/telemetry-demo.js} +149 -119
  126. package/dist/shell/telemetry-ledger-io.js +132 -0
  127. package/dist/{term.js → shell/term.js} +36 -46
  128. package/dist/shell/topology-io.js +361 -0
  129. package/dist/shell/trust-audit.js +471 -0
  130. package/dist/{multi-agent-trust.js → shell/trust-policy-io.js} +67 -205
  131. package/dist/shell/verifier.js +48 -0
  132. package/dist/shell/workbench-host.js +250 -0
  133. package/dist/shell/workbench-text.js +18 -0
  134. package/dist/shell/workbench.js +175 -0
  135. package/dist/shell/worker-cli.js +124 -0
  136. package/dist/shell/worker-isolation.js +852 -0
  137. package/dist/shell/workflow-app-loader.js +650 -0
  138. package/docs/agent-delegation-drive.7.md +2 -0
  139. package/docs/cli-mcp-parity.7.md +280 -219
  140. package/docs/contract-migration-tooling.7.md +2 -0
  141. package/docs/control-plane-scheduling.7.md +2 -0
  142. package/docs/durable-state-and-locking.7.md +2 -0
  143. package/docs/evidence-adoption-reasoning-chain.7.md +2 -0
  144. package/docs/execution-backends.7.md +2 -0
  145. package/docs/multi-agent-cli-mcp-surface.7.md +2 -0
  146. package/docs/multi-agent-eval-replay-harness.7.md +2 -0
  147. package/docs/multi-agent-operator-ux.7.md +2 -0
  148. package/docs/node-snapshot-diff-replay.7.md +2 -0
  149. package/docs/observability-cost-accounting.7.md +2 -0
  150. package/docs/project-index.md +132 -71
  151. package/docs/real-execution-backends.7.md +2 -0
  152. package/docs/release-and-migration.7.md +2 -0
  153. package/docs/release-tooling.7.md +2 -0
  154. package/docs/run-registry-control-plane.7.md +2 -0
  155. package/docs/run-retention-reclamation.7.md +23 -0
  156. package/docs/state-explosion-management.7.md +2 -0
  157. package/docs/team-collaboration.7.md +2 -0
  158. package/docs/web-desktop-workbench.7.md +2 -0
  159. package/manifest/plugin.manifest.json +1 -1
  160. package/manifest/source-context-profiles.json +9 -13
  161. package/package.json +1 -1
  162. package/scripts/agents/cw-attest-wrap.js +2 -2
  163. package/scripts/bump-version.js +4 -3
  164. package/scripts/canonical-apps.js +4 -4
  165. package/scripts/dogfood-architecture-review.js +2 -3
  166. package/scripts/dogfood-release.js +3 -3
  167. package/scripts/gen-parity-doc.js +15 -2
  168. package/scripts/golden-path.js +4 -4
  169. package/scripts/onramp-check.js +1 -1
  170. package/scripts/parity-check.js +38 -21
  171. package/scripts/release-flow.js +2 -2
  172. package/scripts/sync-project-index.js +51 -27
  173. package/scripts/validate-run-state-schema.js +2 -2
  174. package/scripts/version-sync-check.js +30 -30
  175. package/dist/candidate-scoring.js +0 -729
  176. package/dist/capability-core.js +0 -1189
  177. package/dist/capability-registry.js +0 -885
  178. package/dist/cli/command-surface.js +0 -494
  179. package/dist/cli/format.js +0 -56
  180. package/dist/cli/handlers/audit.js +0 -82
  181. package/dist/cli/handlers/blackboard.js +0 -81
  182. package/dist/cli/handlers/candidate.js +0 -40
  183. package/dist/cli/handlers/clones.js +0 -34
  184. package/dist/cli/handlers/collaboration.js +0 -61
  185. package/dist/cli/handlers/eval.js +0 -40
  186. package/dist/cli/handlers/ledger.js +0 -169
  187. package/dist/cli/handlers/maintenance.js +0 -107
  188. package/dist/cli/handlers/multi-agent.js +0 -165
  189. package/dist/cli/handlers/node.js +0 -41
  190. package/dist/cli/handlers/operational.js +0 -155
  191. package/dist/cli/handlers/operator.js +0 -146
  192. package/dist/cli/handlers/registry.js +0 -68
  193. package/dist/cli/handlers/run.js +0 -153
  194. package/dist/cli/handlers/scheduling.js +0 -132
  195. package/dist/cli/handlers/workbench.js +0 -41
  196. package/dist/cli/handlers/worker.js +0 -45
  197. package/dist/cli/run-summary.js +0 -45
  198. package/dist/clones.js +0 -162
  199. package/dist/collaboration.js +0 -726
  200. package/dist/commit.js +0 -592
  201. package/dist/compare.js +0 -18
  202. package/dist/coordinator/classify.js +0 -45
  203. package/dist/coordinator/paths.js +0 -42
  204. package/dist/coordinator/util.js +0 -126
  205. package/dist/coordinator.js +0 -990
  206. package/dist/daemon.js +0 -44
  207. package/dist/dispatch.js +0 -250
  208. package/dist/drive.js +0 -864
  209. package/dist/error-feedback.js +0 -419
  210. package/dist/evidence-grounding.js +0 -184
  211. package/dist/execution-backend/agent.js +0 -354
  212. package/dist/execution-backend/probes.js +0 -112
  213. package/dist/execution-backend/util.js +0 -47
  214. package/dist/execution-backend.js +0 -961
  215. package/dist/gates.js +0 -48
  216. package/dist/harness.js +0 -61
  217. package/dist/ledger.js +0 -313
  218. package/dist/loop-expansion.js +0 -60
  219. package/dist/mcp/tool-call.js +0 -470
  220. package/dist/mcp/tool-definitions.js +0 -1066
  221. package/dist/mcp-surface.js +0 -30
  222. package/dist/multi-agent/graph.js +0 -84
  223. package/dist/multi-agent/helpers.js +0 -141
  224. package/dist/multi-agent/ids.js +0 -20
  225. package/dist/multi-agent/paths.js +0 -22
  226. package/dist/multi-agent-eval/normalize.js +0 -51
  227. package/dist/multi-agent-eval.js +0 -678
  228. package/dist/multi-agent-host.js +0 -777
  229. package/dist/multi-agent.js +0 -984
  230. package/dist/node-projection.js +0 -59
  231. package/dist/node-snapshot.js +0 -260
  232. package/dist/operator-ux.js +0 -631
  233. package/dist/orchestrator/app-operations.js +0 -211
  234. package/dist/orchestrator/audit-operations.js +0 -182
  235. package/dist/orchestrator/candidate-operations.js +0 -117
  236. package/dist/orchestrator/cli-options.js +0 -294
  237. package/dist/orchestrator/collaboration-operations.js +0 -86
  238. package/dist/orchestrator/feedback-operations.js +0 -81
  239. package/dist/orchestrator/host-operations.js +0 -78
  240. package/dist/orchestrator/lifecycle-operations.js +0 -650
  241. package/dist/orchestrator/migration-operations.js +0 -44
  242. package/dist/orchestrator/multi-agent-operations.js +0 -362
  243. package/dist/orchestrator/topology-operations.js +0 -84
  244. package/dist/orchestrator.js +0 -925
  245. package/dist/pipeline-runner.js +0 -285
  246. package/dist/reclamation/hash.js +0 -72
  247. package/dist/reclamation.js +0 -812
  248. package/dist/reporter.js +0 -67
  249. package/dist/run-export.js +0 -815
  250. package/dist/run-registry/derive.js +0 -175
  251. package/dist/run-registry/format.js +0 -124
  252. package/dist/run-registry/gc.js +0 -251
  253. package/dist/run-registry/policy.js +0 -16
  254. package/dist/run-registry/queue.js +0 -115
  255. package/dist/run-registry.js +0 -850
  256. package/dist/run-state-schema.js +0 -68
  257. package/dist/scheduling.js +0 -184
  258. package/dist/state-explosion.js +0 -1014
  259. package/dist/state.js +0 -367
  260. package/dist/telemetry-ledger.js +0 -196
  261. package/dist/topology.js +0 -565
  262. package/dist/triggers.js +0 -184
  263. package/dist/trust-audit.js +0 -644
  264. package/dist/types/blackboard.js +0 -2
  265. package/dist/types/candidate.js +0 -2
  266. package/dist/types/collaboration.js +0 -2
  267. package/dist/types/core.js +0 -2
  268. package/dist/types/drive.js +0 -10
  269. package/dist/types/error-feedback.js +0 -2
  270. package/dist/types/evidence-reasoning.js +0 -2
  271. package/dist/types/execution-backend.js +0 -2
  272. package/dist/types/multi-agent.js +0 -2
  273. package/dist/types/observability.js +0 -2
  274. package/dist/types/pipeline.js +0 -2
  275. package/dist/types/reclamation.js +0 -8
  276. package/dist/types/report-bundle.js +0 -6
  277. package/dist/types/result.js +0 -2
  278. package/dist/types/run-registry.js +0 -2
  279. package/dist/types/run.js +0 -2
  280. package/dist/types/sandbox.js +0 -2
  281. package/dist/types/schedule.js +0 -2
  282. package/dist/types/state-node.js +0 -2
  283. package/dist/types/topology.js +0 -2
  284. package/dist/types/trust.js +0 -2
  285. package/dist/types/workbench.js +0 -2
  286. package/dist/types/worker.js +0 -2
  287. package/dist/types/workflow-app.js +0 -2
  288. package/dist/types.js +0 -44
  289. package/dist/util/fingerprint.js +0 -19
  290. package/dist/util/fingerprint.test.js +0 -27
  291. package/dist/verifier.js +0 -78
  292. package/dist/version.js +0 -8
  293. package/dist/workbench-host.js +0 -192
  294. package/dist/workbench.js +0 -192
  295. package/dist/worker-accept/acceptance.js +0 -114
  296. package/dist/worker-accept/blackboard-fanout.js +0 -80
  297. package/dist/worker-accept/blackboard-linkage.js +0 -19
  298. package/dist/worker-accept/context.js +0 -2
  299. package/dist/worker-accept/telemetry-ledger.js +0 -126
  300. package/dist/worker-accept/validation.js +0 -77
  301. package/dist/worker-accept/verifier-completion.js +0 -73
  302. package/dist/worker-isolation/helpers.js +0 -51
  303. package/dist/worker-isolation/paths.js +0 -46
  304. package/dist/worker-isolation.js +0 -656
  305. package/dist/workflow-api.js +0 -131
  306. /package/dist/{types → core/types}/boundary.js +0 -0
@@ -0,0 +1,481 @@
1
+ "use strict";
2
+ // core/multi-agent/collaboration.ts — approvals/comments/handoffs,
3
+ // deriveReviewState (review-gate stacking rule).
4
+ //
5
+ // MILESTONE 9. Byte-exact port of the old build's src/collaboration.ts,
6
+ // minus recordTrustAuditEvent/saveCheckpoint calls (those are impure —
7
+ // see shell/collaboration-io.ts, which calls the pure builders here then
8
+ // wires the audit event + persist).
9
+ //
10
+ // BYTE-COMPAT / REBUILD RISK 8 [load-bearing]: `reviewGateErrors` STACKS
11
+ // on top of a verifier/selection gate — it can only ADD StateNodeErrors,
12
+ // never replace or suppress one. See reviewstack-verifier-error-
13
+ // precedence.case.js and SPEC/multi-agent.md invariant 7/8.
14
+ //
15
+ // Evidence: SPEC/multi-agent.md section F ("Team collaboration / review
16
+ // gate"), "Collaboration exact outputs"; plugins/cool-workflow/src/
17
+ // collaboration.ts (byte-exact source).
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.UNATTRIBUTED_ACTOR = exports.COLLABORATION_SCHEMA_VERSION = void 0;
20
+ exports.emptyCollaborationState = emptyCollaborationState;
21
+ exports.normalizeActor = normalizeActor;
22
+ exports.normalizeTarget = normalizeTarget;
23
+ exports.createCollabId = createCollabId;
24
+ exports.buildApproval = buildApproval;
25
+ exports.buildComment = buildComment;
26
+ exports.buildHandoff = buildHandoff;
27
+ exports.buildReviewPolicy = buildReviewPolicy;
28
+ exports.deriveReviewState = deriveReviewState;
29
+ exports.reviewGateErrors = reviewGateErrors;
30
+ exports.commitReviewProvenance = commitReviewProvenance;
31
+ exports.deriveOwner = deriveOwner;
32
+ exports.buildTimeline = buildTimeline;
33
+ exports.buildNextActions = buildNextActions;
34
+ exports.selfActorIdsForCandidate = selfActorIdsForCandidate;
35
+ exports.listComments = listComments;
36
+ exports.distinctTargets = distinctTargets;
37
+ exports.formatReviewStatus = formatReviewStatus;
38
+ exports.formatCommentList = formatCommentList;
39
+ exports.COLLABORATION_SCHEMA_VERSION = 1;
40
+ /** The single, honest stand-in for an absent identity. */
41
+ exports.UNATTRIBUTED_ACTOR = {
42
+ kind: "unattributed",
43
+ id: "unattributed",
44
+ attestation: "unattributed",
45
+ attested: false,
46
+ source: "runtime-derived",
47
+ };
48
+ function emptyCollaborationState() {
49
+ return { schemaVersion: exports.COLLABORATION_SCHEMA_VERSION, approvals: [], comments: [], handoffs: [] };
50
+ }
51
+ function trimmed(value) {
52
+ if (value === undefined || value === null)
53
+ return "";
54
+ return String(value).trim();
55
+ }
56
+ const ACTOR_KINDS = ["operator", "worker", "role", "membership", "group", "host", "service", "unattributed"];
57
+ function normalizeActorKind(raw, roleId) {
58
+ const value = trimmed(raw);
59
+ if (value && ACTOR_KINDS.includes(value))
60
+ return value;
61
+ if (roleId)
62
+ return "role";
63
+ return "operator";
64
+ }
65
+ function sourceForAttestation(attestation) {
66
+ if (attestation === "host-attested")
67
+ return "host-attested";
68
+ if (attestation === "operator-recorded")
69
+ return "operator-recorded";
70
+ return "runtime-derived";
71
+ }
72
+ /** Absent id -> the unattributed actor. Unknown kind falls back to
73
+ * "role" (if a role id is given) or "operator". */
74
+ function normalizeActor(input) {
75
+ const id = trimmed(input?.actor);
76
+ if (!id)
77
+ return { ...exports.UNATTRIBUTED_ACTOR };
78
+ const roleId = trimmed(input?.roleId) || trimmed(input?.role);
79
+ const kind = normalizeActorKind(input?.actorKind, roleId);
80
+ const attestation = input?.attestation ? input.attestation : input?.attested ? "host-attested" : "operator-recorded";
81
+ const attested = attestation === "host-attested";
82
+ return { kind, id, displayName: trimmed(input?.displayName) || undefined, attestation, attested, roleId: roleId || undefined, source: sourceForAttestation(attestation) };
83
+ }
84
+ function normalizeTarget(target) {
85
+ const kind = target?.kind;
86
+ const id = trimmed(target?.id);
87
+ if (!kind || !id)
88
+ throw new Error("Collaboration target requires a kind and id");
89
+ if (!["run", "task", "candidate", "selection", "commit", "node"].includes(kind)) {
90
+ throw new Error(`Unknown collaboration target kind: ${kind}`);
91
+ }
92
+ return { kind, id };
93
+ }
94
+ function safeFileName(value) {
95
+ return value.replace(/[^a-zA-Z0-9_.:-]+/g, "_");
96
+ }
97
+ /** Deterministic collab id: caller-supplied count (approvals/comments/
98
+ * handoffs length), no wall-clock stamp. */
99
+ function createCollabId(kind, count) {
100
+ return `collab-${safeFileName(kind)}-${String(count + 1).padStart(4, "0")}`;
101
+ }
102
+ function compact(value) {
103
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
104
+ }
105
+ /** Append-only: id shares the `approvals` array's length counter across
106
+ * approve/reject (a rejection right after an approval mints the NEXT
107
+ * sequence number, not its own). */
108
+ function buildApproval(input, approvalCount, runId, now, auditEventId) {
109
+ const actor = normalizeActor(input);
110
+ const target = normalizeTarget(input.target);
111
+ const decision = input.decision === "reject" ? "reject" : "approve";
112
+ return compact({
113
+ schemaVersion: exports.COLLABORATION_SCHEMA_VERSION,
114
+ id: createCollabId(decision === "approve" ? "approval" : "rejection", approvalCount),
115
+ runId,
116
+ createdAt: now,
117
+ actor,
118
+ decision,
119
+ target,
120
+ rationale: trimmed(input.rationale) || undefined,
121
+ roleId: actor.roleId,
122
+ supersedes: trimmed(input.supersedes) || undefined,
123
+ auditEventIds: [auditEventId],
124
+ metadata: undefined,
125
+ });
126
+ }
127
+ function buildComment(input, commentCount, runId, now, auditEventId) {
128
+ const actor = normalizeActor(input);
129
+ const target = normalizeTarget(input.target);
130
+ const body = trimmed(input.body) || trimmed(input.message) || trimmed(input.text);
131
+ if (!body)
132
+ throw new Error("Comment body is required");
133
+ const threadId = trimmed(input.threadId) || `${target.kind}:${target.id}`;
134
+ return compact({
135
+ schemaVersion: exports.COLLABORATION_SCHEMA_VERSION,
136
+ id: createCollabId("comment", commentCount),
137
+ runId,
138
+ createdAt: now,
139
+ actor,
140
+ target,
141
+ body,
142
+ threadId,
143
+ parentId: trimmed(input.parentId) || undefined,
144
+ auditEventIds: [auditEventId],
145
+ });
146
+ }
147
+ function buildHandoff(input, handoffCount, runId, now, auditEventId) {
148
+ const recorder = normalizeActor(input);
149
+ const fromActor = input.fromActor ? normalizeActor({ actor: input.fromActor, actorKind: input.fromActorKind, role: input.fromRole, attested: input.attested }) : recorder;
150
+ const toActor = normalizeActor({ actor: input.toActor, actorKind: input.toActorKind, role: input.toRole, displayName: input.toDisplayName, attested: input.toAttested });
151
+ if (toActor.kind === "unattributed")
152
+ throw new Error("Handoff requires a to-actor (--to)");
153
+ const target = normalizeTarget(input.target);
154
+ const reason = trimmed(input.reason) || "handoff";
155
+ return compact({
156
+ schemaVersion: exports.COLLABORATION_SCHEMA_VERSION,
157
+ id: createCollabId("handoff", handoffCount),
158
+ runId,
159
+ createdAt: now,
160
+ actor: recorder,
161
+ fromActor,
162
+ toActor,
163
+ target,
164
+ reason,
165
+ auditEventIds: [auditEventId],
166
+ });
167
+ }
168
+ /** Boolean-coerce a defined tri-state flag; leave `undefined` alone so the
169
+ * caller's `?? existing ?? default` chain still governs an unset flag. */
170
+ function coerceFlag(value) {
171
+ return value === undefined ? undefined : Boolean(value);
172
+ }
173
+ function toNumber(value, fallback) {
174
+ if (value === undefined || value === null || value === "" || value === true)
175
+ return fallback;
176
+ const parsed = Number(value);
177
+ return Number.isFinite(parsed) ? parsed : fallback;
178
+ }
179
+ function uniqueList(values) {
180
+ return Array.from(new Set(values));
181
+ }
182
+ function toStringList(value, fallback) {
183
+ if (value === undefined)
184
+ return fallback;
185
+ const list = Array.isArray(value) ? value : String(value).split(",");
186
+ const cleaned = list.map((entry) => String(entry).trim()).filter(Boolean);
187
+ return cleaned.length ? uniqueList(cleaned) : fallback;
188
+ }
189
+ function toTargetKindList(value, fallback) {
190
+ if (value === undefined)
191
+ return fallback;
192
+ const list = Array.isArray(value) ? value : String(value).split(",");
193
+ const valid = ["run", "task", "candidate", "selection", "commit", "node"];
194
+ const cleaned = list.map((entry) => String(entry).trim()).filter((entry) => valid.includes(entry));
195
+ return cleaned.length ? uniqueList(cleaned) : fallback;
196
+ }
197
+ function buildReviewPolicy(input, existing, now) {
198
+ return {
199
+ schemaVersion: exports.COLLABORATION_SCHEMA_VERSION,
200
+ id: existing?.id || createCollabId("policy", 0),
201
+ requiredApprovals: Math.max(0, Math.floor(toNumber(input.requiredApprovals, existing?.requiredApprovals ?? 0))),
202
+ authorizedRoles: toStringList(input.authorizedRoles, existing?.authorizedRoles ?? ["*"]),
203
+ allowSelfApproval: coerceFlag(input.allowSelfApproval) ?? existing?.allowSelfApproval ?? false,
204
+ requireAttestedActor: coerceFlag(input.requireAttestedActor) ?? existing?.requireAttestedActor ?? false,
205
+ appliesTo: toTargetKindList(input.appliesTo, existing?.appliesTo ?? ["commit"]),
206
+ updatedAt: now,
207
+ };
208
+ }
209
+ function sameTarget(left, right) {
210
+ return left.kind === right.kind && left.id === right.id;
211
+ }
212
+ function matchesAnyTarget(target, related) {
213
+ return related.some((entry) => sameTarget(target, entry));
214
+ }
215
+ function compareByCreated(left, right) {
216
+ return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
217
+ }
218
+ function disqualify(record, policy, selfIds) {
219
+ const actor = record.actor;
220
+ if (actor.kind === "unattributed")
221
+ return "unattributed";
222
+ if (policy?.requireAttestedActor && !actor.attested)
223
+ return "unattributed";
224
+ if (policy && !roleAuthorized(actor.roleId, policy.authorizedRoles))
225
+ return "unauthorized-role";
226
+ if (policy && !policy.allowSelfApproval && selfIds.has(actor.id))
227
+ return "self-approval";
228
+ return undefined;
229
+ }
230
+ function roleAuthorized(roleId, authorizedRoles) {
231
+ if (authorizedRoles.includes("*"))
232
+ return true;
233
+ if (!roleId)
234
+ return false;
235
+ return authorizedRoles.includes(roleId);
236
+ }
237
+ function deriveStatus(gated, required, recorded, rejectionCount, disqualified) {
238
+ if (!gated)
239
+ return "approved";
240
+ if (rejectionCount > 0)
241
+ return "rejected";
242
+ if (recorded >= required)
243
+ return "approved";
244
+ if (recorded === 0 && disqualified.length > 0) {
245
+ const blocking = disqualified.filter((entry) => entry.reason !== "superseded");
246
+ if (blocking.length > 0 && blocking.every((entry) => entry.reason === "unattributed"))
247
+ return "unattributed";
248
+ if (blocking.length > 0)
249
+ return "blocked";
250
+ }
251
+ return "pending";
252
+ }
253
+ function buildMissing(status, gated, required, recorded, policy, rejections, disqualified) {
254
+ if (!gated || status === "approved")
255
+ return [];
256
+ const missing = [];
257
+ if (status === "rejected") {
258
+ for (const record of rejections)
259
+ missing.push(`rejected by ${record.actor.id}${record.rationale ? ` (${record.rationale})` : ""}`);
260
+ return missing;
261
+ }
262
+ const roles = policy?.authorizedRoles?.length ? policy.authorizedRoles.join(", ") : "*";
263
+ missing.push(`${required - recorded} more approval(s) from authorized role(s) [${roles}] required (have ${recorded}/${required})`);
264
+ const selfCount = disqualified.filter((entry) => entry.reason === "self-approval").length;
265
+ const unattributedCount = disqualified.filter((entry) => entry.reason === "unattributed").length;
266
+ const unauthorizedCount = disqualified.filter((entry) => entry.reason === "unauthorized-role").length;
267
+ if (selfCount)
268
+ missing.push(`${selfCount} self-approval(s) ignored (policy forbids self-approval)`);
269
+ if (unattributedCount)
270
+ missing.push(`${unattributedCount} unattributed approval(s) ignored`);
271
+ if (unauthorizedCount)
272
+ missing.push(`${unauthorizedCount} approval(s) from unauthorized role(s) ignored`);
273
+ return missing;
274
+ }
275
+ /** Pure projection: derive a target's review state from append-only
276
+ * records + policy. Approvals are processed in createdAt-then-id order;
277
+ * only the FIRST approval per actor id counts. A reject with disqualify
278
+ * reason "self-approval" still counts as a veto; a reject from an
279
+ * unattributed/unauthorized actor is disqualified instead. */
280
+ function deriveReviewState(runId, approvalsAll, target, options = {}) {
281
+ const normalized = normalizeTarget(target);
282
+ const policy = options.policy;
283
+ const related = (options.relatedTargets && options.relatedTargets.length ? options.relatedTargets : [normalized]).map(normalizeTarget);
284
+ const selfIds = new Set((options.selfActorIds || []).filter(Boolean));
285
+ const approvals = approvalsAll.filter((record) => matchesAnyTarget(record.target, related));
286
+ const supersededIds = new Set(approvals.map((record) => record.supersedes).filter((id) => Boolean(id)));
287
+ const gated = Boolean(policy && policy.requiredApprovals > 0 && policy.appliesTo.includes(normalized.kind));
288
+ const required = gated ? policy.requiredApprovals : 0;
289
+ const counted = [];
290
+ const countedActorIds = new Set();
291
+ const rejections = [];
292
+ const disqualified = [];
293
+ for (const record of [...approvals].sort(compareByCreated)) {
294
+ if (supersededIds.has(record.id)) {
295
+ disqualified.push({ approvalId: record.id, actorId: record.actor.id, reason: "superseded" });
296
+ continue;
297
+ }
298
+ const reason = disqualify(record, policy, selfIds);
299
+ if (record.decision === "reject") {
300
+ if (!reason || reason === "self-approval")
301
+ rejections.push(record);
302
+ else
303
+ disqualified.push({ approvalId: record.id, actorId: record.actor.id, reason });
304
+ continue;
305
+ }
306
+ if (reason) {
307
+ disqualified.push({ approvalId: record.id, actorId: record.actor.id, reason });
308
+ continue;
309
+ }
310
+ if (!countedActorIds.has(record.actor.id)) {
311
+ countedActorIds.add(record.actor.id);
312
+ counted.push(record);
313
+ }
314
+ }
315
+ const recordedApprovals = countedActorIds.size;
316
+ const status = deriveStatus(gated, required, recordedApprovals, rejections.length, disqualified);
317
+ const approvers = [...countedActorIds].sort();
318
+ const missing = buildMissing(status, gated, required, recordedApprovals, policy, rejections, disqualified);
319
+ return { schemaVersion: exports.COLLABORATION_SCHEMA_VERSION, runId, target: normalized, status, gated, policyId: policy?.id, requiredApprovals: required, recordedApprovals, approvers, approvals: counted, rejections, disqualified, missing };
320
+ }
321
+ function gateTarget(input) {
322
+ if (input.targetKind === "commit")
323
+ return { kind: "commit", id: input.commitId || "(pending)" };
324
+ if (input.targetKind === "selection")
325
+ return { kind: "selection", id: input.selectionId || "(pending)" };
326
+ if (input.targetKind === "candidate")
327
+ return { kind: "candidate", id: input.candidateId || "(pending)" };
328
+ if (input.targetKind === "node")
329
+ return { kind: "node", id: input.nodeId || "(pending)" };
330
+ if (input.targetKind === "task")
331
+ return { kind: "task", id: input.taskId || "(pending)" };
332
+ return { kind: "run", id: input.commitId || input.candidateId || input.selectionId || "(pending)" };
333
+ }
334
+ function gateRelatedTargets(input) {
335
+ const related = [];
336
+ if (input.commitId)
337
+ related.push({ kind: "commit", id: input.commitId });
338
+ if (input.selectionId)
339
+ related.push({ kind: "selection", id: input.selectionId });
340
+ if (input.candidateId)
341
+ related.push({ kind: "candidate", id: input.candidateId });
342
+ if (input.nodeId)
343
+ related.push({ kind: "node", id: input.nodeId });
344
+ if (input.taskId)
345
+ related.push({ kind: "task", id: input.taskId });
346
+ if (!related.length)
347
+ related.push(gateTarget(input));
348
+ return related;
349
+ }
350
+ /** The StateNodeErrors a review gate contributes. Empty when the target
351
+ * is not gated or the gate is satisfied — so it can only ADD
352
+ * constraints on top of a verifier gate's own errors, never remove
353
+ * them. Caller (candidate-scoring/commit-gate) appends this list to its
354
+ * own failure list. */
355
+ function reviewGateErrors(runId, approvalsAll, input, now) {
356
+ const policy = input.policy;
357
+ if (!policy || policy.requiredApprovals <= 0 || !policy.appliesTo.includes(input.targetKind))
358
+ return [];
359
+ const target = gateTarget(input);
360
+ const related = gateRelatedTargets(input);
361
+ const state = deriveReviewState(runId, approvalsAll, target, { policy, relatedTargets: related, selfActorIds: input.selfActorIds });
362
+ if (state.status === "approved")
363
+ return [];
364
+ return [
365
+ {
366
+ code: "review-gate-missing-approvals",
367
+ message: `Review gate blocked (${state.status}): ${state.missing.join("; ")}`,
368
+ at: now,
369
+ retryable: false,
370
+ details: { reviewStatus: state.status, requiredApprovals: state.requiredApprovals, recordedApprovals: state.recordedApprovals, approvers: state.approvers, missing: state.missing, policyId: state.policyId, targetKind: input.targetKind },
371
+ },
372
+ ];
373
+ }
374
+ function commitReviewProvenance(runId, approvalsAll, input) {
375
+ const policy = input.policy;
376
+ if (!policy || policy.requiredApprovals <= 0 || !policy.appliesTo.includes(input.targetKind))
377
+ return undefined;
378
+ const target = gateTarget(input);
379
+ const state = deriveReviewState(runId, approvalsAll, target, { policy, relatedTargets: gateRelatedTargets(input), selfActorIds: input.selfActorIds });
380
+ if (state.status !== "approved")
381
+ return undefined;
382
+ return { policyId: policy.id, requiredApprovals: state.requiredApprovals, recordedApprovals: state.recordedApprovals, approvers: state.approvers, approvalIds: state.approvals.map((record) => record.id).sort(), target };
383
+ }
384
+ function deriveOwner(handoffs) {
385
+ const relevant = [...handoffs].filter((record) => record.target.kind === "run" || record.target.kind === "task").sort(compareByCreated);
386
+ return relevant.length ? relevant[relevant.length - 1].toActor : undefined;
387
+ }
388
+ function truncate(value, max) {
389
+ return value.length > max ? `${value.slice(0, max - 1)}…` : value;
390
+ }
391
+ function buildTimeline(state) {
392
+ const entries = [];
393
+ for (const record of state.approvals) {
394
+ entries.push({ kind: "approval", id: record.id, createdAt: record.createdAt, actor: record.actor, target: record.target, summary: `${record.decision === "approve" ? "approved" : "rejected"} ${record.target.kind} ${record.target.id}${record.rationale ? ` — ${record.rationale}` : ""}` });
395
+ }
396
+ for (const record of state.comments) {
397
+ entries.push({ kind: "comment", id: record.id, createdAt: record.createdAt, actor: record.actor, target: record.target, summary: `commented on ${record.target.kind} ${record.target.id}: ${truncate(record.body, 80)}` });
398
+ }
399
+ for (const record of state.handoffs) {
400
+ entries.push({ kind: "handoff", id: record.id, createdAt: record.createdAt, actor: record.actor, target: record.target, summary: `handed off ${record.target.kind} ${record.target.id}: ${record.fromActor.id} → ${record.toActor.id} (${record.reason})` });
401
+ }
402
+ if (state.policy) {
403
+ const policy = state.policy;
404
+ entries.push({
405
+ kind: "policy",
406
+ id: policy.id,
407
+ createdAt: policy.updatedAt,
408
+ actor: { ...exports.UNATTRIBUTED_ACTOR, kind: "operator", id: "operator", attestation: "operator-recorded", source: "operator-recorded" },
409
+ summary: `review policy: ${policy.requiredApprovals} approval(s) from [${policy.authorizedRoles.join(", ")}] for [${policy.appliesTo.join(", ")}]`,
410
+ });
411
+ }
412
+ return entries.sort(compareByCreated);
413
+ }
414
+ function buildNextActions(runId, states, policy) {
415
+ const actions = [];
416
+ if (!policy) {
417
+ actions.push(`node scripts/cw.js review policy ${runId} --requiredApprovals 1 --authorizedRoles reviewer --appliesTo commit`);
418
+ return actions;
419
+ }
420
+ for (const state of states) {
421
+ if (state.status === "pending" || state.status === "blocked" || state.status === "unattributed") {
422
+ actions.push(`node scripts/cw.js approve ${state.target.kind} ${runId} ${state.target.id} --role <authorized-role> --actor <id> --attested`);
423
+ }
424
+ }
425
+ if (!actions.length)
426
+ actions.push(`node scripts/cw.js review status ${runId} --json`);
427
+ return actions;
428
+ }
429
+ /** Self ids for a candidate/selection target: its producing worker +
430
+ * selector(s). Pure form of the old build's selfActorIdsForCandidate —
431
+ * the caller resolves the candidate's workerId and any matching
432
+ * selections' selectedBy values (shell/candidate-scoring-io.ts has the
433
+ * WorkflowRun-shaped lookups this needs). */
434
+ function selfActorIdsForCandidate(workerId, selectedByIds) {
435
+ const ids = new Set();
436
+ if (workerId)
437
+ ids.add(workerId);
438
+ for (const id of selectedByIds)
439
+ if (id)
440
+ ids.add(id);
441
+ return [...ids];
442
+ }
443
+ function listComments(state, target) {
444
+ const filtered = target ? state.comments.filter((record) => sameTarget(record.target, normalizeTarget(target))) : state.comments;
445
+ return [...filtered].sort(compareByCreated);
446
+ }
447
+ function distinctTargets(state) {
448
+ const seen = new Map();
449
+ const targetKey = (target) => `${target.kind}:${target.id}`;
450
+ for (const record of state.approvals)
451
+ seen.set(targetKey(record.target), record.target);
452
+ for (const record of state.comments)
453
+ seen.set(targetKey(record.target), record.target);
454
+ for (const record of state.handoffs)
455
+ seen.set(targetKey(record.target), record.target);
456
+ return [...seen.values()].sort((left, right) => targetKey(left).localeCompare(targetKey(right)));
457
+ }
458
+ function formatReviewStatus(report) {
459
+ const lines = [];
460
+ const policy = report.policy;
461
+ lines.push(`review ${report.runId} policy=${policy ? `${policy.requiredApprovals} from [${policy.authorizedRoles.join(",")}] on [${policy.appliesTo.join(",")}]` : "none"}`);
462
+ if (report.owner)
463
+ lines.push(` owner: ${report.owner.id} (${report.owner.attestation})`);
464
+ lines.push(` counts: approvals=${report.counts.approvals} rejections=${report.counts.rejections} comments=${report.counts.comments} handoffs=${report.counts.handoffs}`);
465
+ for (const state of report.targets) {
466
+ lines.push(` ${state.target.kind} ${state.target.id}: ${state.status}` + (state.gated ? ` (${state.recordedApprovals}/${state.requiredApprovals}${state.approvers.length ? ` by ${state.approvers.join(",")}` : ""})` : " (not gated)"));
467
+ for (const note of state.missing)
468
+ lines.push(` - ${note}`);
469
+ }
470
+ if (report.timeline.length) {
471
+ lines.push(" timeline:");
472
+ for (const entry of report.timeline)
473
+ lines.push(` ${entry.createdAt} ${entry.actor.id} ${entry.summary}`);
474
+ }
475
+ return lines.join("\n");
476
+ }
477
+ function formatCommentList(comments) {
478
+ if (!comments.length)
479
+ return "no comments";
480
+ return comments.map((record) => `${record.createdAt} ${record.actor.id} (${record.actor.attestation}) [${record.target.kind} ${record.target.id}] ${record.body}`).join("\n");
481
+ }