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,1014 @@
1
+ "use strict";
2
+ // shell/run-registry-io.ts — the on-disk run registry: index/queue/history
3
+ // persistence, lifecycle derivation, search/resume/archive/rerun.
4
+ //
5
+ // MILESTONE 10 (v2/PLAN.md build order, step 10). Byte-exact port of the
6
+ // old build's src/run-registry.ts + src/run-registry/{derive,policy,
7
+ // queue}.ts. The registry is a DERIVED, rebuildable index over each repo's
8
+ // `.cw/runs/<id>/state.json` (the single source of truth, never mutated
9
+ // here except via `archive`/`rerun`'s overlay files). Every read
10
+ // re-derives from source; the persisted index.json is only ever compared,
11
+ // never trusted (fail-OPEN on a corrupt index.json — see the file header
12
+ // note in SPEC/scheduling-registry.md's "Rebuild risks" #1).
13
+ //
14
+ // Evidence: SPEC/scheduling-registry.md sections C, D (partial: policy
15
+ // constant), H; plugins/cool-workflow/src/run-registry.ts,
16
+ // src/run-registry/{derive,policy,queue}.ts (byte-exact source).
17
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ var desc = Object.getOwnPropertyDescriptor(m, k);
20
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
+ desc = { enumerable: true, get: function() { return m[k]; } };
22
+ }
23
+ Object.defineProperty(o, k2, desc);
24
+ }) : (function(o, m, k, k2) {
25
+ if (k2 === undefined) k2 = k;
26
+ o[k2] = m[k];
27
+ }));
28
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
30
+ }) : function(o, v) {
31
+ o["default"] = v;
32
+ });
33
+ var __importStar = (this && this.__importStar) || (function () {
34
+ var ownKeys = function(o) {
35
+ ownKeys = Object.getOwnPropertyNames || function (o) {
36
+ var ar = [];
37
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
38
+ return ar;
39
+ };
40
+ return ownKeys(o);
41
+ };
42
+ return function (mod) {
43
+ if (mod && mod.__esModule) return mod;
44
+ var result = {};
45
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
46
+ __setModuleDefault(result, mod);
47
+ return result;
48
+ };
49
+ })();
50
+ Object.defineProperty(exports, "__esModule", { value: true });
51
+ exports.RunRegistry = exports.DEFAULT_RUN_REGISTRY_POLICY = exports.RUN_REGISTRY_SCHEMA_VERSION = void 0;
52
+ exports.compareBytes = compareBytes;
53
+ exports.compareRecords = compareRecords;
54
+ exports.compareHistory = compareHistory;
55
+ exports.compareQueue = compareQueue;
56
+ exports.matchesQuery = matchesQuery;
57
+ exports.distinctBackends = distinctBackends;
58
+ exports.digestInputs = digestInputs;
59
+ exports.countRecords = countRecords;
60
+ exports.optionalLower = optionalLower;
61
+ exports.clampInt = clampInt;
62
+ exports.queueId = queueId;
63
+ exports.isRunLifecycleState = isRunLifecycleState;
64
+ exports.loadReclaimedFromDir = loadReclaimedFromDir;
65
+ exports.deriveLifecycle = deriveLifecycle;
66
+ exports.resolveCwHome = resolveCwHome;
67
+ exports.humanBytes = humanBytes;
68
+ exports.formatRegistryReport = formatRegistryReport;
69
+ exports.formatRunSearch = formatRunSearch;
70
+ exports.formatRunShow = formatRunShow;
71
+ exports.formatResume = formatResume;
72
+ exports.formatHistory = formatHistory;
73
+ exports.formatQueueList = formatQueueList;
74
+ const fs = __importStar(require("node:fs"));
75
+ const os = __importStar(require("node:os"));
76
+ const path = __importStar(require("node:path"));
77
+ const fs_atomic_1 = require("./fs-atomic");
78
+ const run_store_1 = require("./run-store");
79
+ const hash_1 = require("../core/hash");
80
+ exports.RUN_REGISTRY_SCHEMA_VERSION = 1;
81
+ exports.DEFAULT_RUN_REGISTRY_POLICY = {
82
+ schemaVersion: 1,
83
+ archiveOlderThanDays: 0,
84
+ archiveStates: ["completed", "failed"],
85
+ defaultQueuePriority: 100,
86
+ reclaimAfterArchiveDays: 0,
87
+ reclaimStates: ["completed", "failed"],
88
+ keepSnapshots: false,
89
+ keepScratch: false,
90
+ maxReclaimRuns: 0,
91
+ maxReclaimBytes: 0,
92
+ };
93
+ // ---------------------------------------------------------------------------
94
+ // Pure helpers (byte-exact port of src/run-registry/derive.ts)
95
+ // ---------------------------------------------------------------------------
96
+ /** Simple byte (UTF-16 code-unit) comparator — matches src/compare.ts's
97
+ * `compareBytes` used throughout the old build's registry/reclamation
98
+ * code. Kept as a small local copy (same pattern as core/multi-agent's
99
+ * own local copies) rather than a new shared module. */
100
+ function compareBytes(a, b) {
101
+ return a < b ? -1 : a > b ? 1 : 0;
102
+ }
103
+ function compareRecords(a, b) {
104
+ if (a.createdAt !== b.createdAt)
105
+ return a.createdAt < b.createdAt ? -1 : 1;
106
+ return compareBytes(a.runId, b.runId);
107
+ }
108
+ function compareHistory(a, b) {
109
+ if (a.createdAt !== b.createdAt)
110
+ return a.createdAt < b.createdAt ? 1 : -1;
111
+ return compareBytes(a.runId, b.runId);
112
+ }
113
+ function compareQueue(a, b) {
114
+ if (a.priority !== b.priority)
115
+ return a.priority - b.priority;
116
+ if (a.enqueuedAt !== b.enqueuedAt)
117
+ return a.enqueuedAt < b.enqueuedAt ? -1 : 1;
118
+ return compareBytes(a.id, b.id);
119
+ }
120
+ function matchesQuery(record, query) {
121
+ if (query.app && !(record.appId || record.workflowId || "").toLowerCase().includes(query.app))
122
+ return false;
123
+ if (query.status && record.lifecycle !== query.status && record.derivedLifecycle !== query.status)
124
+ return false;
125
+ if (query.repo && path.resolve(record.repo) !== query.repo)
126
+ return false;
127
+ if (query.since && record.createdAt < query.since)
128
+ return false;
129
+ if (query.until && record.createdAt > query.until)
130
+ return false;
131
+ if (query.text) {
132
+ const haystack = [
133
+ record.runId,
134
+ record.appId,
135
+ record.workflowId,
136
+ record.title,
137
+ record.repo,
138
+ record.lifecycle,
139
+ record.loopStage,
140
+ record.inputsDigest,
141
+ ]
142
+ .filter(Boolean)
143
+ .join(" ")
144
+ .toLowerCase();
145
+ if (!haystack.includes(query.text))
146
+ return false;
147
+ }
148
+ return true;
149
+ }
150
+ const DIGEST_PRIORITY_KEYS = ["question", "prompt", "task", "summary", "title", "objective", "focus", "topic"];
151
+ function distinctBackends(run) {
152
+ const backends = new Set();
153
+ for (const dispatch of run.dispatches || []) {
154
+ if (dispatch.backendId)
155
+ backends.add(dispatch.backendId);
156
+ }
157
+ for (const task of run.tasks || []) {
158
+ if (task.backendId)
159
+ backends.add(task.backendId);
160
+ }
161
+ return [...backends].sort();
162
+ }
163
+ function digestInputs(inputs) {
164
+ if (!inputs || typeof inputs !== "object")
165
+ return undefined;
166
+ const keys = Object.keys(inputs);
167
+ const ordered = [
168
+ ...DIGEST_PRIORITY_KEYS.filter((k) => keys.includes(k)),
169
+ ...keys.filter((k) => !DIGEST_PRIORITY_KEYS.includes(k)).sort(),
170
+ ];
171
+ const parts = [];
172
+ for (const key of ordered) {
173
+ const value = inputs[key];
174
+ if (value === undefined || value === null)
175
+ continue;
176
+ const rendered = Array.isArray(value) ? value.join(",") : typeof value === "object" ? JSON.stringify(value) : String(value);
177
+ parts.push(`${key}=${rendered}`);
178
+ }
179
+ const joined = parts.join(" ").replace(/\s+/g, " ").trim();
180
+ return joined.length > 360 ? `${joined.slice(0, 357)}...` : joined;
181
+ }
182
+ function countRecords(records) {
183
+ const counts = {
184
+ total: records.length,
185
+ queued: 0,
186
+ running: 0,
187
+ blocked: 0,
188
+ completed: 0,
189
+ failed: 0,
190
+ archived: 0,
191
+ reclaimed: 0,
192
+ };
193
+ for (const record of records) {
194
+ counts[record.lifecycle] = (counts[record.lifecycle] || 0) + 1;
195
+ }
196
+ return counts;
197
+ }
198
+ function optionalLower(value) {
199
+ if (value === undefined || value === null || value === "")
200
+ return undefined;
201
+ return String(value).toLowerCase();
202
+ }
203
+ function clampInt(value, fallback, min) {
204
+ const n = Number(value);
205
+ if (!Number.isFinite(n))
206
+ return fallback;
207
+ return Math.max(min, Math.floor(n));
208
+ }
209
+ let queueCounter = 0;
210
+ function queueId() {
211
+ queueCounter += 1;
212
+ const stamp = new Date().toISOString().replace(/[-:.TZ]/g, "").slice(0, 14);
213
+ return `q-${stamp}-${String(queueCounter).padStart(3, "0")}`;
214
+ }
215
+ function isRunLifecycleState(value) {
216
+ return (typeof value === "string" &&
217
+ ["queued", "running", "blocked", "completed", "failed", "archived", "reclaimed"].includes(value));
218
+ }
219
+ /** Read a run dir's `reclaimed.json` overlay. Fail-OPEN to an empty chain
220
+ * on absence/corruption — a malformed overlay must never brick the run
221
+ * (SPEC/scheduling-registry.md "Rebuild risks" #1). */
222
+ function loadReclaimedFromDir(runDir) {
223
+ const file = path.join(runDir, "reclaimed.json");
224
+ if (!fs.existsSync(file))
225
+ return { schemaVersion: 1, runId: "", tombstones: [] };
226
+ try {
227
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
228
+ if (!parsed || typeof parsed !== "object" || parsed.schemaVersion !== 1 || !Array.isArray(parsed.tombstones)) {
229
+ return { schemaVersion: 1, runId: "", tombstones: [] };
230
+ }
231
+ return { schemaVersion: 1, runId: String(parsed.runId || ""), tombstones: parsed.tombstones };
232
+ }
233
+ catch {
234
+ return { schemaVersion: 1, runId: "", tombstones: [] };
235
+ }
236
+ }
237
+ function fingerprintRun(run) {
238
+ const parts = [
239
+ `id:${run.id}`,
240
+ `updatedAt:${run.updatedAt}`,
241
+ `loopStage:${run.loopStage}`,
242
+ `schema:${run.schemaVersion}`,
243
+ ];
244
+ for (const task of [...run.tasks].sort((a, b) => compareBytes(a.id, b.id))) {
245
+ parts.push(`task:${task.id}:${task.status}`);
246
+ }
247
+ for (const commit of [...run.commits].sort((a, b) => compareBytes(a.id, b.id))) {
248
+ parts.push(`commit:${commit.id}:${commit.verifierGated ? "gated" : "checkpoint"}`);
249
+ }
250
+ for (const phase of [...run.phases].sort((a, b) => compareBytes(a.id, b.id))) {
251
+ parts.push(`phase:${phase.id}:${phase.status}`);
252
+ }
253
+ for (const fb of [...(run.feedback || [])].sort((a, b) => compareBytes(a.id, b.id))) {
254
+ parts.push(`feedback:${fb.id}:${fb.status}`);
255
+ }
256
+ return (0, hash_1.fingerprintStrings)(parts);
257
+ }
258
+ /** Classify a run's lifecycle purely from its source state. First match
259
+ * wins, per SPEC/scheduling-registry.md section C. */
260
+ function deriveLifecycle(input) {
261
+ if (input.running > 0)
262
+ return "running";
263
+ if (input.openFeedback > 0)
264
+ return "blocked";
265
+ if (input.failed > 0)
266
+ return "failed";
267
+ if (input.total > 0 && input.completed === input.total)
268
+ return "completed";
269
+ if (input.verifierGatedCommits > 0 && input.pending === 0)
270
+ return "completed";
271
+ if (input.completed > 0)
272
+ return "running";
273
+ return "queued";
274
+ }
275
+ function lifecycleInputs(run) {
276
+ const tasks = run.tasks || [];
277
+ return {
278
+ total: tasks.length,
279
+ pending: tasks.filter((t) => t.status === "pending").length,
280
+ running: tasks.filter((t) => t.status === "running").length,
281
+ failed: tasks.filter((t) => t.status === "failed").length,
282
+ completed: tasks.filter((t) => t.status === "completed").length,
283
+ verifierGatedCommits: (run.commits || []).filter((c) => c.verifierGated).length,
284
+ openFeedback: (run.feedback || []).filter((f) => f.status === "open" || f.status === "tasked").length,
285
+ loopStage: run.loopStage,
286
+ };
287
+ }
288
+ // ---------------------------------------------------------------------------
289
+ // Home registry location
290
+ // ---------------------------------------------------------------------------
291
+ /** Resolve the home registry root: CW_HOME, then XDG_STATE_HOME/
292
+ * cool-workflow, then ~/.local/state/cool-workflow. */
293
+ function resolveCwHome(env = process.env) {
294
+ if (env.CW_HOME && String(env.CW_HOME).trim())
295
+ return path.resolve(String(env.CW_HOME));
296
+ if (env.XDG_STATE_HOME && String(env.XDG_STATE_HOME).trim()) {
297
+ return path.join(path.resolve(String(env.XDG_STATE_HOME)), "cool-workflow");
298
+ }
299
+ return path.join(os.homedir(), ".local", "state", "cool-workflow");
300
+ }
301
+ function requireOverlayObject(parsed, file) {
302
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
303
+ throw new Error(`Corrupt overlay ${file}: expected a JSON object, got ${Array.isArray(parsed) ? "array" : parsed === null ? "null" : typeof parsed}`);
304
+ }
305
+ return parsed;
306
+ }
307
+ // ---------------------------------------------------------------------------
308
+ // The registry
309
+ // ---------------------------------------------------------------------------
310
+ class RunRegistry {
311
+ repoRoot;
312
+ homeRoot;
313
+ planner;
314
+ constructor(cwd = process.cwd(), planner, env = process.env) {
315
+ this.repoRoot = path.resolve(cwd);
316
+ this.homeRoot = resolveCwHome(env);
317
+ this.planner = planner;
318
+ }
319
+ repoRunsDir(repo) {
320
+ return path.join(repo, ".cw", "runs");
321
+ }
322
+ repoRegistryDir(repo) {
323
+ return path.join(repo, ".cw", "registry");
324
+ }
325
+ homeRegistryDir() {
326
+ return path.join(this.homeRoot, "registry");
327
+ }
328
+ loadArchiveOverlay(repo) {
329
+ const file = path.join(this.repoRegistryDir(repo), "archive.json");
330
+ if (!fs.existsSync(file))
331
+ return { schemaVersion: 1, archived: {} };
332
+ const parsed = requireOverlayObject((0, fs_atomic_1.readJson)(file), file);
333
+ return { schemaVersion: 1, archived: parsed.archived || {} };
334
+ }
335
+ loadProvenanceOverlay(repo) {
336
+ const file = path.join(this.repoRegistryDir(repo), "provenance.json");
337
+ if (!fs.existsSync(file))
338
+ return { schemaVersion: 1, links: {} };
339
+ const parsed = requireOverlayObject((0, fs_atomic_1.readJson)(file), file);
340
+ return { schemaVersion: 1, links: parsed.links || {} };
341
+ }
342
+ loadRepoOverlays(repo) {
343
+ return { archive: this.loadArchiveOverlay(repo), provenance: this.loadProvenanceOverlay(repo) };
344
+ }
345
+ get defaultQueuePriority() {
346
+ return exports.DEFAULT_RUN_REGISTRY_POLICY.defaultQueuePriority;
347
+ }
348
+ reposFilePath() {
349
+ return path.join(this.homeRegistryDir(), "repos.json");
350
+ }
351
+ loadRepos() {
352
+ const file = this.reposFilePath();
353
+ if (!fs.existsSync(file))
354
+ return { schemaVersion: 1, repos: [] };
355
+ const parsed = requireOverlayObject((0, fs_atomic_1.readJson)(file), file);
356
+ return { schemaVersion: 1, repos: Array.isArray(parsed.repos) ? parsed.repos : [] };
357
+ }
358
+ knownRepos() {
359
+ const roots = new Set([this.repoRoot]);
360
+ for (const entry of this.loadRepos().repos)
361
+ roots.add(path.resolve(entry.root));
362
+ return [...roots].sort();
363
+ }
364
+ registerRepo(repo = this.repoRoot) {
365
+ const resolved = path.resolve(repo);
366
+ const file = this.reposFilePath();
367
+ return (0, fs_atomic_1.withFileLock)(file, () => {
368
+ const current = this.loadRepos();
369
+ const already = current.repos.some((entry) => path.resolve(entry.root) === resolved);
370
+ if (!already)
371
+ current.repos.push({ root: resolved, addedAt: new Date().toISOString() });
372
+ current.repos.sort((a, b) => compareBytes(a.root, b.root));
373
+ (0, fs_atomic_1.writeJson)(file, current, { durable: true });
374
+ return { registered: !already, repos: current.repos.map((entry) => entry.root) };
375
+ });
376
+ }
377
+ // ---- queue file (durable, ordered; drained by the host) ----------------
378
+ queueFilePath() {
379
+ return path.join(this.homeRegistryDir(), "queue.json");
380
+ }
381
+ loadQueueEntries() {
382
+ const file = this.queueFilePath();
383
+ if (!fs.existsSync(file))
384
+ return [];
385
+ const parsed = (0, fs_atomic_1.readJson)(file);
386
+ return Array.isArray(parsed.entries) ? parsed.entries : [];
387
+ }
388
+ saveQueueEntries(entries) {
389
+ (0, fs_atomic_1.writeJson)(this.queueFilePath(), { schemaVersion: 1, entries }, { durable: true });
390
+ }
391
+ schedulingPolicyPath() {
392
+ return path.join(this.homeRegistryDir(), "scheduling-policy.json");
393
+ }
394
+ queueAdd(options = {}) {
395
+ const repo = options.repo ? path.resolve(options.repo) : this.repoRoot;
396
+ return (0, fs_atomic_1.withFileLock)(this.queueFilePath(), () => {
397
+ const entries = this.loadQueueEntries();
398
+ const entry = {
399
+ schemaVersion: 1,
400
+ id: options.id || queueId(),
401
+ runId: options.runId,
402
+ appId: options.appId,
403
+ workflowId: options.workflowId,
404
+ repo,
405
+ priority: Number.isFinite(options.priority) ? Number(options.priority) : this.defaultQueuePriority,
406
+ enqueuedAt: new Date().toISOString(),
407
+ status: "pending",
408
+ inputs: options.inputs,
409
+ note: options.note,
410
+ };
411
+ entries.push(entry);
412
+ this.registerRepo(repo);
413
+ this.saveQueueEntries(entries);
414
+ return entry;
415
+ });
416
+ }
417
+ queueList(options = {}) {
418
+ let entries = this.loadQueueEntries();
419
+ if (options.status)
420
+ entries = entries.filter((e) => e.status === options.status);
421
+ if (options.repo) {
422
+ const repo = path.resolve(options.repo);
423
+ entries = entries.filter((e) => path.resolve(e.repo) === repo);
424
+ }
425
+ entries = [...entries].sort(compareQueue);
426
+ return { schemaVersion: 1, total: entries.length, entries };
427
+ }
428
+ queueShow(id) {
429
+ const entry = this.loadQueueEntries().find((e) => e.id === id);
430
+ if (!entry)
431
+ throw new Error(`Queue entry not found: ${id}`);
432
+ return entry;
433
+ }
434
+ queueDrain(options = {}) {
435
+ const limit = clampInt(options.limit, 1, 1);
436
+ const repoFilter = options.repo ? path.resolve(options.repo) : undefined;
437
+ return (0, fs_atomic_1.withFileLock)(this.queueFilePath(), () => {
438
+ const entries = this.loadQueueEntries();
439
+ const drainable = entries
440
+ .filter((e) => e.status === "pending" || e.status === "ready")
441
+ .filter((e) => !repoFilter || path.resolve(e.repo) === repoFilter)
442
+ .sort(compareQueue);
443
+ const drained = [];
444
+ const drainedAt = new Date().toISOString();
445
+ for (const entry of drainable.slice(0, limit)) {
446
+ entry.status = "drained";
447
+ entry.drainedAt = drainedAt;
448
+ drained.push(entry);
449
+ }
450
+ this.saveQueueEntries(entries);
451
+ const remaining = entries.filter((e) => e.status === "pending" || e.status === "ready").length;
452
+ return { schemaVersion: 1, drained, remaining };
453
+ });
454
+ }
455
+ // ---- record derivation (always from source) -----------------------------
456
+ deriveRecord(repo, runDir, overlays = this.loadRepoOverlays(repo)) {
457
+ const statePath = path.join(runDir, "state.json");
458
+ if (!fs.existsSync(statePath))
459
+ return null;
460
+ let run;
461
+ try {
462
+ const result = (0, run_store_1.loadRunStateFile)(statePath, { dryRun: true });
463
+ if (result.report.status === "unsupported")
464
+ return null;
465
+ run = result.run;
466
+ }
467
+ catch {
468
+ return null;
469
+ }
470
+ const li = lifecycleInputs(run);
471
+ const derived = deriveLifecycle(li);
472
+ const archive = overlays.archive.archived[run.id];
473
+ const provenance = overlays.provenance.links[run.id];
474
+ const reclaim = loadReclaimedFromDir(runDir);
475
+ const lastTombstone = reclaim.tombstones[reclaim.tombstones.length - 1];
476
+ const tier = lastTombstone ? "reclaimed" : archive ? "archived" : "live";
477
+ const capability = lastTombstone ? lastTombstone.capability : "re-runnable";
478
+ const capabilityReason = lastTombstone
479
+ ? lastTombstone.capabilityReason
480
+ : archive
481
+ ? "archived-full"
482
+ : "live-full";
483
+ const appMeta = run.workflow.app;
484
+ return {
485
+ schemaVersion: 1,
486
+ runId: run.id,
487
+ appId: appMeta?.id,
488
+ appVersion: appMeta?.version,
489
+ workflowId: run.workflow.id,
490
+ title: run.workflow.title,
491
+ repo,
492
+ runDir,
493
+ statePath,
494
+ createdAt: run.createdAt,
495
+ updatedAt: run.updatedAt,
496
+ loopStage: run.loopStage,
497
+ lifecycle: lastTombstone ? "reclaimed" : archive ? "archived" : derived,
498
+ derivedLifecycle: derived,
499
+ archived: Boolean(archive),
500
+ archivedAt: archive?.archivedAt,
501
+ archiveReason: archive?.reason,
502
+ tier,
503
+ capability,
504
+ capabilityReason,
505
+ reclaimedAt: lastTombstone?.reclaimedAt,
506
+ reclaimedBytes: reclaim.tombstones.reduce((sum, t) => sum + (t.bytesFreed || 0), 0) || undefined,
507
+ tombstoneHash: lastTombstone?.tombstoneHash,
508
+ tasks: { total: li.total, pending: li.pending, running: li.running, failed: li.failed, completed: li.completed },
509
+ commitCount: (run.commits || []).length,
510
+ verifierGatedCommitCount: li.verifierGatedCommits,
511
+ openFeedbackCount: li.openFeedback,
512
+ backends: distinctBackends(run),
513
+ inputsDigest: digestInputs(run.inputs),
514
+ sourceFingerprint: fingerprintRun(run),
515
+ freshness: "valid",
516
+ provenance,
517
+ };
518
+ }
519
+ scanRepo(repo) {
520
+ const runsDir = this.repoRunsDir(repo);
521
+ if (!fs.existsSync(runsDir))
522
+ return [];
523
+ const overlays = this.loadRepoOverlays(repo);
524
+ const records = [];
525
+ for (const entry of fs.readdirSync(runsDir, { withFileTypes: true })) {
526
+ if (!entry.isDirectory())
527
+ continue;
528
+ const record = this.deriveRecord(repo, path.join(runsDir, entry.name), overlays);
529
+ if (record)
530
+ records.push(record);
531
+ }
532
+ return records.sort(compareRecords);
533
+ }
534
+ buildIndex(scope) {
535
+ const repos = scope === "home" ? this.knownRepos() : [this.repoRoot];
536
+ const records = [];
537
+ for (const repo of repos)
538
+ records.push(...this.scanRepo(repo));
539
+ records.sort(compareRecords);
540
+ const queue = scope === "home" ? this.loadQueueEntries() : this.loadQueueEntries().filter((q) => path.resolve(q.repo) === this.repoRoot);
541
+ const sourceFingerprint = (0, hash_1.fingerprintStrings)([
542
+ ...repos.map((r) => `repo:${r}`),
543
+ ...records.map((r) => `${r.runId}:${r.sourceFingerprint}:${r.lifecycle}`),
544
+ ]);
545
+ return {
546
+ schemaVersion: 1,
547
+ scope,
548
+ root: scope === "home" ? this.homeRoot : this.repoRoot,
549
+ generatedAt: new Date().toISOString(),
550
+ sourceFingerprint,
551
+ repos,
552
+ records,
553
+ queue,
554
+ counts: countRecords(records),
555
+ };
556
+ }
557
+ persistedIndexPath(scope) {
558
+ return scope === "home" ? path.join(this.homeRegistryDir(), "index.json") : path.join(this.repoRegistryDir(this.repoRoot), "index.json");
559
+ }
560
+ /** Fail-OPEN on a corrupt persisted index.json (rebuildable cache):
561
+ * returns undefined rather than throwing, per SPEC's asymmetric rule. */
562
+ loadPersistedIndex(scope) {
563
+ const file = this.persistedIndexPath(scope);
564
+ if (!fs.existsSync(file))
565
+ return undefined;
566
+ try {
567
+ const parsed = (0, fs_atomic_1.readJson)(file);
568
+ if (!parsed || parsed.schemaVersion !== 1)
569
+ return undefined;
570
+ return parsed;
571
+ }
572
+ catch {
573
+ return undefined;
574
+ }
575
+ }
576
+ refresh(options = {}) {
577
+ const scope = options.scope || "repo";
578
+ this.registerRepo(this.repoRoot);
579
+ const index = this.buildIndex(scope);
580
+ (0, fs_atomic_1.writeJson)(this.persistedIndexPath(scope), index);
581
+ if (scope === "repo") {
582
+ const homeIndex = this.buildIndex("home");
583
+ (0, fs_atomic_1.writeJson)(this.persistedIndexPath("home"), homeIndex);
584
+ }
585
+ return this.report(scope, index);
586
+ }
587
+ show(options = {}) {
588
+ const scope = options.scope || "repo";
589
+ return this.report(scope, this.buildIndex(scope));
590
+ }
591
+ report(scope, current) {
592
+ const persisted = this.loadPersistedIndex(scope);
593
+ const currentById = new Map(current.records.map((r) => [r.runId, r]));
594
+ let status = persisted ? "valid" : "absent";
595
+ const staleRuns = [];
596
+ const missingRuns = [];
597
+ if (persisted) {
598
+ if (persisted.sourceFingerprint !== current.sourceFingerprint)
599
+ status = "stale";
600
+ for (const prior of persisted.records) {
601
+ const now = currentById.get(prior.runId);
602
+ if (!now) {
603
+ missingRuns.push(prior.runId);
604
+ }
605
+ else if (now.sourceFingerprint !== prior.sourceFingerprint) {
606
+ staleRuns.push(prior.runId);
607
+ }
608
+ }
609
+ if (staleRuns.length || missingRuns.length)
610
+ status = "stale";
611
+ }
612
+ const refreshCmd = scope === "home" ? "node scripts/cw.js registry refresh --scope home" : "node scripts/cw.js registry refresh";
613
+ return {
614
+ schemaVersion: 1,
615
+ scope,
616
+ root: current.root,
617
+ generatedAt: current.generatedAt,
618
+ freshness: {
619
+ status,
620
+ persistedFingerprint: persisted?.sourceFingerprint,
621
+ currentFingerprint: current.sourceFingerprint,
622
+ staleRuns: staleRuns.sort(),
623
+ missingRuns: missingRuns.sort(),
624
+ },
625
+ index: current,
626
+ counts: current.counts,
627
+ nextAction: status === "valid" ? "node scripts/cw.js run search" : refreshCmd,
628
+ };
629
+ }
630
+ search(raw = {}) {
631
+ const scope = raw.scope || "home";
632
+ const index = this.buildIndex(scope);
633
+ const report = this.report(scope, index);
634
+ const query = {
635
+ text: optionalLower(raw.text),
636
+ app: optionalLower(raw.app),
637
+ status: raw.status,
638
+ repo: raw.repo ? path.resolve(raw.repo) : undefined,
639
+ since: raw.since,
640
+ until: raw.until,
641
+ includeArchived: raw.includeArchived ?? true,
642
+ offset: clampInt(raw.offset, 0, 0),
643
+ limit: clampInt(raw.limit, 50, 1),
644
+ };
645
+ let records = index.records.filter((record) => matchesQuery(record, query));
646
+ if (!query.includeArchived)
647
+ records = records.filter((record) => !record.archived);
648
+ records.sort(compareRecords);
649
+ const total = records.length;
650
+ const page = records.slice(query.offset, query.offset + query.limit);
651
+ return {
652
+ schemaVersion: 1,
653
+ scope,
654
+ query,
655
+ freshness: report.freshness.status,
656
+ total,
657
+ offset: query.offset,
658
+ limit: query.limit,
659
+ records: page,
660
+ nextAction: report.freshness.status === "valid" ? "node scripts/cw.js run show <run-id>" : "node scripts/cw.js registry refresh",
661
+ };
662
+ }
663
+ list(options = {}) {
664
+ return this.search({
665
+ scope: options.scope || "home",
666
+ includeArchived: options.includeArchived ?? true,
667
+ limit: options.limit,
668
+ offset: options.offset,
669
+ });
670
+ }
671
+ showRun(runId, options = {}) {
672
+ const scope = options.scope || "home";
673
+ const located = this.locate(runId, scope);
674
+ if (located) {
675
+ return {
676
+ schemaVersion: 1,
677
+ runId,
678
+ found: true,
679
+ freshness: "valid",
680
+ resolvedFrom: located.from,
681
+ repo: located.record.repo,
682
+ record: located.record,
683
+ nextAction: located.record.archived ? "node scripts/cw.js run resume " + runId : "node scripts/cw.js run show " + runId,
684
+ };
685
+ }
686
+ const persisted = this.findPersisted(runId, scope);
687
+ return {
688
+ schemaVersion: 1,
689
+ runId,
690
+ found: false,
691
+ freshness: "missing",
692
+ repo: persisted?.repo,
693
+ persisted,
694
+ nextAction: "node scripts/cw.js registry refresh" + (scope === "home" ? " --scope home" : ""),
695
+ };
696
+ }
697
+ locate(runId, scope) {
698
+ const here = this.deriveRecordForRun(this.repoRoot, runId);
699
+ if (here)
700
+ return { record: here, from: "repo" };
701
+ if (scope === "repo")
702
+ return undefined;
703
+ for (const repo of this.knownRepos()) {
704
+ if (path.resolve(repo) === this.repoRoot)
705
+ continue;
706
+ const record = this.deriveRecordForRun(repo, runId);
707
+ if (record)
708
+ return { record, from: "home" };
709
+ }
710
+ return undefined;
711
+ }
712
+ deriveRecordForRun(repo, runId) {
713
+ const runDir = path.join(this.repoRunsDir(repo), runId);
714
+ if (!fs.existsSync(path.join(runDir, "state.json")))
715
+ return null;
716
+ return this.deriveRecord(repo, runDir);
717
+ }
718
+ findPersisted(runId, scope) {
719
+ for (const s of scope === "home" ? ["home", "repo"] : ["repo"]) {
720
+ const persisted = this.loadPersistedIndex(s);
721
+ const hit = persisted?.records.find((r) => r.runId === runId);
722
+ if (hit)
723
+ return hit;
724
+ }
725
+ return undefined;
726
+ }
727
+ loadRun(repo, runId) {
728
+ const statePath = path.join(this.repoRunsDir(repo), runId, "state.json");
729
+ if (!fs.existsSync(statePath))
730
+ throw new Error(`Run not found: ${runId}`);
731
+ const result = (0, run_store_1.loadRunStateFile)(statePath, { dryRun: true });
732
+ if (result.report.status === "unsupported") {
733
+ throw new Error(`Unsupported run state for ${runId}: ${result.report.errors.join("; ")}`);
734
+ }
735
+ return result.run;
736
+ }
737
+ resume(runId, options = {}) {
738
+ const scope = options.scope || "home";
739
+ const located = this.locate(runId, scope);
740
+ if (!located) {
741
+ throw new Error(`Cannot resume: run ${runId} not found in source state (fail closed; try registry refresh).`);
742
+ }
743
+ const record = located.record;
744
+ const run = this.loadRun(record.repo, runId);
745
+ const limit = clampInt(options.limit, 5, 1);
746
+ const nextTasks = (run.tasks || [])
747
+ .filter((t) => t.status === "pending" || t.status === "running")
748
+ .slice(0, limit)
749
+ .map((t) => ({ id: t.id, phase: t.phase, status: t.status, taskPath: t.taskPath }));
750
+ const terminal = record.derivedLifecycle === "completed" || record.derivedLifecycle === "failed";
751
+ const resumable = nextTasks.length > 0 || (!terminal && record.derivedLifecycle !== "completed");
752
+ const nextActions = [];
753
+ if (nextTasks.length) {
754
+ nextActions.push({
755
+ command: `node scripts/cw.js dispatch ${runId} --cwd ${record.repo}`,
756
+ reason: `Continue ${nextTasks.length} pending/running task(s) from durable state.`,
757
+ });
758
+ nextActions.push({
759
+ command: `node scripts/cw.js multi-agent step ${runId} --cwd ${record.repo}`,
760
+ reason: "Take one deterministic host step without spawning agents.",
761
+ });
762
+ }
763
+ else if (record.derivedLifecycle === "failed") {
764
+ nextActions.push({
765
+ command: `node scripts/cw.js run rerun ${runId}`,
766
+ reason: "Run terminated as failed with no runnable tasks; rerun as a new linked run.",
767
+ });
768
+ }
769
+ else {
770
+ nextActions.push({
771
+ command: `node scripts/cw.js status ${runId} --cwd ${record.repo} --json`,
772
+ reason: "No runnable tasks remain; inspect status.",
773
+ });
774
+ }
775
+ return {
776
+ schemaVersion: 1,
777
+ runId,
778
+ repo: record.repo,
779
+ runDir: record.runDir,
780
+ statePath: record.statePath,
781
+ resolvedFrom: located.from,
782
+ lifecycle: record.lifecycle,
783
+ derivedLifecycle: record.derivedLifecycle,
784
+ loopStage: record.loopStage,
785
+ freshness: "valid",
786
+ resumable,
787
+ reason: record.archived ? "Run is archived; resuming reads durable state without un-archiving." : undefined,
788
+ record,
789
+ nextTasks,
790
+ nextActions,
791
+ };
792
+ }
793
+ archive(runId, options = {}) {
794
+ const scope = options.scope || "home";
795
+ const located = this.locate(runId, scope);
796
+ if (!located)
797
+ throw new Error(`Cannot archive: run ${runId} not found in source state (fail closed).`);
798
+ const repo = located.record.repo;
799
+ const file = path.join(this.repoRegistryDir(repo), "archive.json");
800
+ (0, fs_atomic_1.withFileLock)(file, () => {
801
+ const overlay = this.loadArchiveOverlay(repo);
802
+ if (options.unarchive) {
803
+ delete overlay.archived[runId];
804
+ }
805
+ else {
806
+ overlay.archived[runId] = { archivedAt: new Date().toISOString(), reason: options.reason };
807
+ }
808
+ (0, fs_atomic_1.writeJson)(file, overlay, { durable: true });
809
+ });
810
+ const record = this.deriveRecord(repo, located.record.runDir);
811
+ return {
812
+ runId,
813
+ repo,
814
+ archived: record.archived,
815
+ archivedAt: record.archivedAt,
816
+ reason: record.archiveReason,
817
+ record,
818
+ overlayPath: file,
819
+ };
820
+ }
821
+ archiveByPolicy(policy = exports.DEFAULT_RUN_REGISTRY_POLICY, options = {}) {
822
+ const scope = options.scope || "home";
823
+ if (!policy.archiveOlderThanDays || policy.archiveOlderThanDays <= 0) {
824
+ return { policy, archived: [], eligible: 0 };
825
+ }
826
+ const nowMs = options.now ? Date.parse(options.now) : Date.now();
827
+ const cutoff = nowMs - policy.archiveOlderThanDays * 24 * 60 * 60 * 1000;
828
+ const index = this.buildIndex(scope);
829
+ const eligible = index.records.filter((r) => !r.archived && policy.archiveStates.includes(r.derivedLifecycle) && Date.parse(r.updatedAt) < cutoff);
830
+ const archived = [];
831
+ for (const record of eligible) {
832
+ this.archive(record.runId, { reason: `retention:${policy.archiveOlderThanDays}d`, scope });
833
+ archived.push(record.runId);
834
+ }
835
+ return { policy, archived: archived.sort(), eligible: eligible.length };
836
+ }
837
+ rerun(runId, options = {}) {
838
+ if (!this.planner)
839
+ throw new Error("rerun requires a run planner (CoolWorkflowRunner)");
840
+ const scope = options.scope || "home";
841
+ const located = this.locate(runId, scope);
842
+ if (!located)
843
+ throw new Error(`Cannot rerun: run ${runId} not found in source state (fail closed).`);
844
+ const original = located.record;
845
+ const originalRun = this.loadRun(original.repo, runId);
846
+ const appMeta = originalRun.workflow.app;
847
+ const appId = appMeta?.id || originalRun.workflow.id;
848
+ const inputs = { ...(originalRun.inputs || {}), cwd: original.repo, repo: original.repo };
849
+ const newRun = this.planner.plan(appId, inputs);
850
+ const priorProv = original.provenance;
851
+ const provenance = {
852
+ rerunOf: runId,
853
+ rerunOfRepo: original.repo,
854
+ originRunId: priorProv?.originRunId || runId,
855
+ generation: (priorProv?.generation || 0) + 1,
856
+ reason: options.reason || "rerun of failed run",
857
+ createdAt: new Date().toISOString(),
858
+ };
859
+ const provFile = path.join(this.repoRegistryDir(original.repo), "provenance.json");
860
+ (0, fs_atomic_1.withFileLock)(provFile, () => {
861
+ const provOverlay = this.loadProvenanceOverlay(original.repo);
862
+ provOverlay.links[newRun.id] = provenance;
863
+ (0, fs_atomic_1.writeJson)(provFile, provOverlay, { durable: true });
864
+ });
865
+ const newAppMeta = newRun.workflow.app;
866
+ return {
867
+ schemaVersion: 1,
868
+ originalRunId: runId,
869
+ originalRepo: original.repo,
870
+ originalLifecycle: original.lifecycle,
871
+ newRunId: newRun.id,
872
+ repo: original.repo,
873
+ appId: newAppMeta?.id || appId,
874
+ workflowId: newRun.workflow.id,
875
+ statePath: newRun.paths.state,
876
+ reportPath: newRun.paths.report,
877
+ pendingTasks: newRun.tasks.filter((t) => t.status === "pending").length,
878
+ provenance,
879
+ nextActions: [
880
+ { command: `node scripts/cw.js run resume ${newRun.id}`, reason: "Continue the new linked run." },
881
+ { command: `node scripts/cw.js run show ${runId}`, reason: "The original failed run is preserved for audit." },
882
+ ],
883
+ };
884
+ }
885
+ history(options = {}) {
886
+ const scope = options.scope || "home";
887
+ const index = this.buildIndex(scope);
888
+ const report = this.report(scope, index);
889
+ const app = optionalLower(options.app);
890
+ const limit = clampInt(options.limit, 50, 1);
891
+ const offset = clampInt(options.offset, 0, 0);
892
+ let records = index.records;
893
+ if (app)
894
+ records = records.filter((r) => (r.appId || r.workflowId || "").toLowerCase().includes(app));
895
+ if (options.status)
896
+ records = records.filter((r) => r.lifecycle === options.status || r.derivedLifecycle === options.status);
897
+ const ordered = [...records].sort(compareHistory);
898
+ const total = ordered.length;
899
+ const page = ordered.slice(offset, offset + limit);
900
+ const entries = page.map((r) => ({
901
+ runId: r.runId,
902
+ repo: r.repo,
903
+ appId: r.appId,
904
+ workflowId: r.workflowId,
905
+ lifecycle: r.lifecycle,
906
+ loopStage: r.loopStage,
907
+ createdAt: r.createdAt,
908
+ updatedAt: r.updatedAt,
909
+ freshness: r.freshness,
910
+ provenance: r.provenance,
911
+ }));
912
+ return {
913
+ schemaVersion: 1,
914
+ scope,
915
+ freshness: report.freshness.status,
916
+ total,
917
+ offset,
918
+ limit,
919
+ repos: index.repos,
920
+ entries,
921
+ nextAction: report.freshness.status === "valid" ? "node scripts/cw.js run show <run-id>" : "node scripts/cw.js registry refresh --scope home",
922
+ };
923
+ }
924
+ }
925
+ exports.RunRegistry = RunRegistry;
926
+ // ---------------------------------------------------------------------------
927
+ // Human formatting (CLI-only; never affects --json/MCP payloads)
928
+ // ---------------------------------------------------------------------------
929
+ function humanBytes(n) {
930
+ if (n < 1024)
931
+ return `${n}B`;
932
+ const units = ["KiB", "MiB", "GiB"];
933
+ let v = n / 1024;
934
+ let i = 0;
935
+ while (v >= 1024 && i < units.length - 1) {
936
+ v /= 1024;
937
+ i += 1;
938
+ }
939
+ return `${v.toFixed(1)}${units[i]}`;
940
+ }
941
+ function countsLine(counts) {
942
+ return `total=${counts.total} queued=${counts.queued} running=${counts.running} blocked=${counts.blocked} completed=${counts.completed} failed=${counts.failed} archived=${counts.archived} reclaimed=${counts.reclaimed}`;
943
+ }
944
+ function recordLine(record) {
945
+ const flags = [record.archived ? "archived" : "", record.provenance?.rerunOf ? `rerunOf=${record.provenance.rerunOf}` : ""]
946
+ .filter(Boolean)
947
+ .join(" ");
948
+ return ` [${record.lifecycle}] ${record.runId} (${record.appId || record.workflowId}) ${record.loopStage}${flags ? ` {${flags}}` : ""}`;
949
+ }
950
+ function formatRegistryReport(report) {
951
+ const lines = [];
952
+ lines.push(`Run Registry (${report.scope}): ${report.root}`);
953
+ lines.push(`Freshness: ${report.freshness.status}${report.freshness.staleRuns.length ? ` (stale: ${report.freshness.staleRuns.join(", ")})` : ""}${report.freshness.missingRuns.length ? ` (missing: ${report.freshness.missingRuns.join(", ")})` : ""}`);
954
+ lines.push(`Repos: ${report.index.repos.length}`);
955
+ lines.push(countsLine(report.counts));
956
+ if (report.freshness.status !== "valid")
957
+ lines.push(`Next Action: ${report.nextAction}`);
958
+ return lines.join("\n");
959
+ }
960
+ function formatRunSearch(result) {
961
+ const lines = [];
962
+ lines.push(`Run Search (${result.scope}): ${result.total} match(es), showing ${result.records.length} [offset ${result.offset}] freshness=${result.freshness}`);
963
+ for (const record of result.records)
964
+ lines.push(recordLine(record));
965
+ if (!result.records.length)
966
+ lines.push(" (no matching runs)");
967
+ return lines.join("\n");
968
+ }
969
+ function formatRunShow(result) {
970
+ if (!result.found) {
971
+ return `Run ${result.runId}: MISSING (source state.json absent — fail closed). Next: ${result.nextAction}`;
972
+ }
973
+ const r = result.record;
974
+ const lines = [
975
+ `Run ${r.runId} [${r.lifecycle}] (derived: ${r.derivedLifecycle})`,
976
+ ` app=${r.appId || r.workflowId} loopStage=${r.loopStage} repo=${r.repo}`,
977
+ ` tasks: total=${r.tasks.total} pending=${r.tasks.pending} running=${r.tasks.running} failed=${r.tasks.failed} completed=${r.tasks.completed}`,
978
+ ` commits=${r.commitCount} (verifier-gated=${r.verifierGatedCommitCount}) openFeedback=${r.openFeedbackCount}`,
979
+ ];
980
+ if (r.provenance?.rerunOf)
981
+ lines.push(` provenance: rerunOf=${r.provenance.rerunOf} gen=${r.provenance.generation} origin=${r.provenance.originRunId}`);
982
+ if (r.tier && r.tier !== "live") {
983
+ lines.push(` tier=${r.tier} capability=${r.capability} reason=${r.capabilityReason}${r.reclaimedBytes ? ` bytesFreed=${r.reclaimedBytes}` : ""}${r.tombstoneHash ? ` tombstone=${r.tombstoneHash.slice(0, 19)}` : ""}`);
984
+ }
985
+ return lines.join("\n");
986
+ }
987
+ function formatResume(result) {
988
+ const lines = [
989
+ `Resume ${result.runId} [${result.lifecycle}] loopStage=${result.loopStage} (resolved from ${result.resolvedFrom}, ${result.freshness})`,
990
+ ` resumable=${result.resumable} nextTasks=${result.nextTasks.length}`,
991
+ ];
992
+ for (const action of result.nextActions)
993
+ lines.push(` -> ${action.command}\n ${action.reason}`);
994
+ return lines.join("\n");
995
+ }
996
+ function formatHistory(result) {
997
+ const lines = [];
998
+ lines.push(`Run History (${result.scope}): ${result.total} run(s) across ${result.repos.length} repo(s), freshness=${result.freshness}`);
999
+ for (const entry of result.entries) {
1000
+ lines.push(` ${entry.createdAt} [${entry.lifecycle}] ${entry.runId} (${entry.appId || entry.workflowId})${entry.provenance?.rerunOf ? ` rerunOf=${entry.provenance.rerunOf}` : ""}`);
1001
+ }
1002
+ if (!result.entries.length)
1003
+ lines.push(" (no runs)");
1004
+ return lines.join("\n");
1005
+ }
1006
+ function formatQueueList(result) {
1007
+ const lines = [`Run Queue: ${result.total} entry(ies) [priority asc]`];
1008
+ for (const entry of result.entries) {
1009
+ lines.push(` #${entry.priority} ${entry.id} [${entry.status}] ${entry.appId || entry.workflowId || entry.runId || "?"} repo=${entry.repo}${entry.note ? ` note=${entry.note}` : ""}`);
1010
+ }
1011
+ if (!result.entries.length)
1012
+ lines.push(" (queue empty)");
1013
+ return lines.join("\n");
1014
+ }