@melite/estate-queue 0.0.0-stage → 0.1.4-alpha

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 (129) hide show
  1. package/LICENSE +557 -0
  2. package/lib/bakeParams.d.ts +17 -0
  3. package/lib/bakeParams.js +182 -0
  4. package/lib/bench.d.ts +24 -0
  5. package/lib/bench.js +121 -0
  6. package/lib/cardsArmError.d.ts +18 -0
  7. package/lib/cardsArmError.js +33 -0
  8. package/lib/cardsCompose.d.ts +41 -0
  9. package/lib/cardsCompose.js +247 -0
  10. package/lib/cardsDangling.d.ts +16 -0
  11. package/lib/cardsDangling.js +168 -0
  12. package/lib/cardsFacts.d.ts +74 -0
  13. package/lib/cardsFacts.js +64 -0
  14. package/lib/cardsLanes.d.ts +33 -0
  15. package/lib/cardsLanes.js +115 -0
  16. package/lib/cardsRegistry.d.ts +316 -0
  17. package/lib/cardsRegistry.js +1274 -0
  18. package/lib/cardsVariant.d.ts +28 -0
  19. package/lib/cardsVariant.js +190 -0
  20. package/lib/discloseRegistry.d.ts +94 -0
  21. package/lib/discloseRegistry.js +154 -0
  22. package/lib/filmLead.d.ts +4 -0
  23. package/lib/filmLead.js +17 -0
  24. package/lib/filmMemoryWarn.d.ts +27 -0
  25. package/lib/filmMemoryWarn.js +99 -0
  26. package/lib/flowsData.d.ts +179 -0
  27. package/lib/flowsData.js +547 -0
  28. package/lib/flowsFamilyCompose.d.ts +48 -0
  29. package/lib/flowsFamilyCompose.js +191 -0
  30. package/lib/flowsRegistryRows.d.ts +10 -0
  31. package/lib/flowsRegistryRows.js +378 -0
  32. package/lib/index.d.ts +50 -0
  33. package/lib/index.js +66 -0
  34. package/lib/ledgerTail.d.ts +20 -0
  35. package/lib/ledgerTail.js +123 -0
  36. package/lib/loadPlane.d.ts +93 -0
  37. package/lib/loadPlane.js +553 -0
  38. package/lib/loadRegistry.d.ts +22 -0
  39. package/lib/loadRegistry.js +55 -0
  40. package/lib/manageOps.d.ts +21 -0
  41. package/lib/manageOps.js +142 -0
  42. package/lib/managePlane.d.ts +120 -0
  43. package/lib/managePlane.js +1515 -0
  44. package/lib/manageProbe.d.ts +57 -0
  45. package/lib/manageProbe.js +154 -0
  46. package/lib/manageRegistry.d.ts +28 -0
  47. package/lib/manageRegistry.js +75 -0
  48. package/lib/managerRail.d.ts +33 -0
  49. package/lib/managerRail.js +91 -0
  50. package/lib/mediaKinds.d.ts +3 -0
  51. package/lib/mediaKinds.js +2 -0
  52. package/lib/queue.d.ts +9 -0
  53. package/lib/queue.js +76 -0
  54. package/lib/queueCore.d.ts +69 -0
  55. package/lib/queueCore.js +124 -0
  56. package/lib/queueLifecycle.d.ts +26 -0
  57. package/lib/queueLifecycle.js +65 -0
  58. package/lib/queueLock.d.ts +54 -0
  59. package/lib/queueLock.js +195 -0
  60. package/lib/queueResurrect.d.ts +59 -0
  61. package/lib/queueResurrect.js +249 -0
  62. package/lib/queueRetry.d.ts +36 -0
  63. package/lib/queueRetry.js +24 -0
  64. package/lib/queueSidecar.d.ts +145 -0
  65. package/lib/queueSidecar.js +182 -0
  66. package/lib/queueSubmit.d.ts +31 -0
  67. package/lib/queueSubmit.js +117 -0
  68. package/lib/queueSweep.d.ts +30 -0
  69. package/lib/queueSweep.js +121 -0
  70. package/lib/resurrect.d.ts +6 -0
  71. package/lib/resurrect.js +18 -0
  72. package/lib/rootsManifest.d.ts +11 -0
  73. package/lib/rootsManifest.js +11 -0
  74. package/lib/runStatus.d.ts +7 -0
  75. package/lib/runStatus.js +21 -0
  76. package/lib/runsChange.d.ts +53 -0
  77. package/lib/runsChange.js +63 -0
  78. package/lib/runsErrorCodes.d.ts +2 -0
  79. package/lib/runsErrorCodes.js +15 -0
  80. package/lib/runsExecute.d.ts +26 -0
  81. package/lib/runsExecute.js +356 -0
  82. package/lib/runsGates.d.ts +161 -0
  83. package/lib/runsGates.js +306 -0
  84. package/lib/runsList.d.ts +78 -0
  85. package/lib/runsList.js +580 -0
  86. package/lib/runsRefusalVoices.d.ts +9 -0
  87. package/lib/runsRefusalVoices.js +44 -0
  88. package/lib/runsRegistry.d.ts +253 -0
  89. package/lib/runsRegistry.js +1750 -0
  90. package/lib/runsSourceEcho.d.ts +54 -0
  91. package/lib/runsSourceEcho.js +275 -0
  92. package/lib/runsStart.d.ts +121 -0
  93. package/lib/runsStart.js +528 -0
  94. package/lib/runsTypes.d.ts +183 -0
  95. package/lib/runsTypes.js +282 -0
  96. package/lib/runsValidate.d.ts +5 -0
  97. package/lib/runsValidate.js +31 -0
  98. package/lib/runsValidateArms.d.ts +7 -0
  99. package/lib/runsValidateArms.js +285 -0
  100. package/lib/runsValidateInline.d.ts +6 -0
  101. package/lib/runsValidateInline.js +82 -0
  102. package/lib/runsValidateRefusals.d.ts +7 -0
  103. package/lib/runsValidateRefusals.js +18 -0
  104. package/lib/runsValidateServe.d.ts +15 -0
  105. package/lib/runsValidateServe.js +254 -0
  106. package/lib/runsValidateShared.d.ts +84 -0
  107. package/lib/runsValidateShared.js +88 -0
  108. package/lib/runsValidateStages.d.ts +25 -0
  109. package/lib/runsValidateStages.js +491 -0
  110. package/lib/runsValidateSweeps.d.ts +6 -0
  111. package/lib/runsValidateSweeps.js +143 -0
  112. package/lib/service.d.ts +45 -0
  113. package/lib/service.js +81 -0
  114. package/lib/skillFrontmatter.d.ts +11 -0
  115. package/lib/skillFrontmatter.js +46 -0
  116. package/lib/skillFs.d.ts +19 -0
  117. package/lib/skillFs.js +80 -0
  118. package/lib/skillPlane.d.ts +98 -0
  119. package/lib/skillPlane.js +263 -0
  120. package/lib/skillRegistry.d.ts +23 -0
  121. package/lib/skillRegistry.js +55 -0
  122. package/lib/skillRows.d.ts +126 -0
  123. package/lib/skillRows.js +466 -0
  124. package/lib/toolProjection.d.ts +30 -0
  125. package/lib/toolProjection.js +142 -0
  126. package/lib/vocab.d.ts +6 -0
  127. package/lib/vocab.js +18 -0
  128. package/package.json +47 -4
  129. package/README.md +0 -3
@@ -0,0 +1,1750 @@
1
+ import { mediaKindOf } from "./mediaKinds.js";
2
+ // runsRegistry.ts — the live-run registry as a HOST Cordis service
3
+ // (REBUILD-6, gateway kill). Owns the rich run map + the serial
4
+ // pump over the queue seat's QueueCore (one machine — the door's
5
+ // RunsService map and the queue's core are one object now) and the
6
+ // start/status/stop business arms. DECORATOR-FREE on purpose: this
7
+ // package runs from source (node --experimental-strip-types), and
8
+ // decorators are not erasable syntax — the thin Typert adapters
9
+ // live in @melite/estate-runs (a built package, the drafts recipe),
10
+ // delegating to this seat. Failures throw the protocol's ONE
11
+ // RemoteError with the runs/* codes declared HERE (the producing
12
+ // package, next to the throws).
13
+ import { CARD_PLANE_ENGINE } from "@melite/contracts/benchStage";
14
+ import { join, relative } from "node:path";
15
+ import { Service } from "@deepseek-ai/cordis";
16
+ import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
17
+ import { stageEngineOf } from "@melite/contracts/benchStage";
18
+ import { benchResultDefects } from "@melite/contracts/benchResult";
19
+ import { remoteErrorOf } from "@deepseek-ai/dsh-typert-protocol";
20
+ import { needComfyUI } from "@melite/comfyui-cordis";
21
+ import { expandRegistryFlow, extractRequestInitials, getRegistryFlow, registryFlowToInline, inlineStagesNameCards, registryInitialsError, } from "./flowsData.js";
22
+ import { composeFamilyStages, liveFamilySeat } from "./flowsFamilyCompose.js";
23
+ import { resolveRepoRoot } from "@melite/comfyui-cordis";
24
+ import { loadEndpointConfig } from "@melite/comfyui-cordis";
25
+ import { fetchEngineMem, filmLoadOf, filmMemoryWarn } from "./filmMemoryWarn.js";
26
+ import { rootsManifest, searchedVoice } from "./rootsManifest.js";
27
+ import { newRunId, outRootFor, pipelineOf, strictBodyCheck, draftIdOk, planResurrect, bootSweep, appendLedger, refusal } from "./queue.js";
28
+ import { cardRefusal, toRemoteError, refusePreview } from "./runsRefusalVoices.js";
29
+ import { installRunsChangeSeam, notifyRunChanged, onRunChange } from "./runsChange.js";
30
+ import { coerceSnapshotBody } from "./runsValidateStages.js";
31
+ export { toRemoteError } from "./runsRefusalVoices.js";
32
+ import { readFileSync } from "node:fs";
33
+ import { CardArmError, } from "./cardsRegistry.js";
34
+ import { FLOW_ID_RE } from "./runsGates.js";
35
+ import { compileFlowInline, envelopeRefusal, registerCompiledRun, selectSubmitDoor, unknownDraftRefusal, } from "./runsStart.js";
36
+ import { listRunsAcross, parseIntOrNull } from "./runsList.js";
37
+ import { claimPersist, errText, runLogTail, settlePersist, RUN_STATUSES, } from "./runsTypes.js";
38
+ import { runOne, runEngine as runEngineOf } from "./runsExecute.js";
39
+ import { engineFilmName } from "./filmLead.js";
40
+ import { validate as validateArm, modelValidateArm } from "./runsValidateArms.js";
41
+ import { BENCH_DRAFT_PREFIX_RE, benchDraftIdOf } from '@melite/contracts/benchStage';
42
+
43
+ // typecheck). The adapter package that CONSUMES the seat declares it
44
+ // on Context — structurally, by its own header's rule: a compiled
45
+ // package may not import these source-run sources into its emit
46
+ // graph, so the contract travels with the caller, and the class that
47
+ // mounts the seat satisfies it structurally. Declaring it here as
48
+ // well (the rename left this twin behind, its comment still naming
49
+ // the pre-rename class) is TS2717 the moment one program composes
50
+ // both sides — which no program did until the walls did.
51
+ /** The refusal codes this remote serves, folded to the
52
+ * protocol's vocabulary — a literal table, no dynamic key. */
53
+ export function enrichDiskRow(row) {
54
+ const stages = Array.isArray(row['stages']) ? row['stages'] : [];
55
+ const artifacts = Array.isArray(row['artifacts'])
56
+ ? row['artifacts'].filter((value) => typeof value === 'string' && value !== '')
57
+ : [];
58
+ if (stages.length !== 1 || artifacts.length === 0)
59
+ return row;
60
+ const stage = stages[0];
61
+ if (stage === null || typeof stage !== 'object' || Array.isArray(stage))
62
+ return row;
63
+ const runId = typeof row['run_id'] === 'string' ? row['run_id'] : '';
64
+ const relative = (value) => {
65
+ const marker = `/${runId}/`;
66
+ const at = value.lastIndexOf(marker);
67
+ return at >= 0 ? value.slice(at + marker.length) : value.replace(/^\/+/, '');
68
+ };
69
+
70
+ // hero's ONLY media law — it carried avif|m4v|avi the contract's
71
+ // vocab did not, and DROPPED svg|bmp the vocab did carry, so a
72
+ // disk row whose lone artifact was an .svg got no hero and no
73
+ // gallery while an .avif was hero'd but unclassifiable. The
74
+ // classifier is the contract's mediaKindOf now, shared with the
75
+ // run list and the gallery client — the seats cannot disagree.
76
+ const names = [...new Set(artifacts.map(relative))]
77
+ .filter((name) => mediaKindOf(name) !== undefined);
78
+ if (names.length === 0)
79
+ return row;
80
+ const hero = engineFilmName(names) ?? names[0];
81
+ const current = stage;
82
+ return {
83
+ ...row,
84
+ stages: [{
85
+ ...current,
86
+ ...(typeof current['url'] === 'string' && current['url'] !== '' ? {} : { url: hero }),
87
+ ...(Array.isArray(current['gallery']) ? {} : { gallery: names.map((name) => ({ name })) }),
88
+ }],
89
+ };
90
+ }
91
+
92
+
93
+
94
+
95
+
96
+
97
+ export function sidecarReaderFor(dir) {
98
+ return (name) => {
99
+ try {
100
+ return readFileSync(join(dir, name), 'utf8');
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ };
106
+ }
107
+ /** The sidecar candidates for one stage row: every gallery name's
108
+ * own `<stem>.report.json` sibling, keyed by stem. */
109
+ function sidecarCandidatesOf(stage, runId) {
110
+ const candidates = new Map();
111
+ const add = (name) => {
112
+ const at = name.lastIndexOf('/');
113
+ const dir = at >= 0 ? name.slice(0, at + 1) : '';
114
+ const base = at >= 0 ? name.slice(at + 1) : name;
115
+ const dot = base.lastIndexOf('.');
116
+ const stem = dot > 0 ? base.slice(0, dot) : base;
117
+ if (stem === '')
118
+ return;
119
+ if (!candidates.has(stem))
120
+ candidates.set(stem, `${dir}${stem}.report.json`);
121
+ };
122
+ const gallery = Array.isArray(stage['gallery']) ? stage['gallery'] : [];
123
+ for (const g of gallery) {
124
+ if (typeof g === 'object' && g !== null && !Array.isArray(g)) {
125
+ const name = g['name'];
126
+ if (typeof name === 'string' && name !== '')
127
+ add(name);
128
+ }
129
+ }
130
+ const url = typeof stage['url'] === 'string' ? stage['url'] : '';
131
+ if (url !== '') {
132
+ const marker = `/${runId}/`;
133
+ const at = url.lastIndexOf(marker);
134
+ add(at >= 0 ? url.slice(at + marker.length) : url.replace(/^\/+/, ''));
135
+ }
136
+ return candidates;
137
+ }
138
+
139
+
140
+
141
+
142
+
143
+
144
+
145
+
146
+
147
+
148
+
149
+
150
+
151
+
152
+
153
+
154
+ export function withStageReports(row, read) {
155
+ const runId = typeof row['run_id'] === 'string' ? row['run_id'] : '';
156
+ const stages = Array.isArray(row['stages']) ? row['stages'] : [];
157
+ if (stages.length === 0)
158
+ return row;
159
+ const priorWarnings = Array.isArray(row['warnings']) ? row['warnings'].length : 0;
160
+ const warnings = Array.isArray(row['warnings'])
161
+ ? (row['warnings'].filter((w) => typeof w === 'string'))
162
+ : [];
163
+ let mounted = false;
164
+ const nextStages = stages.map((raw) => {
165
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
166
+ return raw;
167
+ const stage = raw;
168
+ const existing = typeof stage['reports'] === 'object' && stage['reports'] !== null
169
+ && !Array.isArray(stage['reports'])
170
+ ? stage['reports'] : {};
171
+ const reports = { ...existing };
172
+ for (const [stem, rel] of sidecarCandidatesOf(stage, runId)) {
173
+ if (stem in reports)
174
+ continue;
175
+ const text = read(rel);
176
+ if (text === null)
177
+ continue;
178
+ let parsed;
179
+ try {
180
+ parsed = JSON.parse(text);
181
+ }
182
+ catch {
183
+ warnings.push(`report sidecar ${rel} is not JSON — skipped`);
184
+ continue;
185
+ }
186
+ // THE CONTRACT JUDGES (the writer asserts, the reader
187
+ // normalizes — this seat does neither by hand): a probe row
188
+ // carrying only this entry surfaces the entry's own defects.
189
+ const defects = benchResultDefects({ run_id: 'probe', reports: { [stem]: parsed } })
190
+ .filter((d) => d.startsWith(`reports.${stem}`));
191
+ if (defects.length > 0) {
192
+ warnings.push(`report sidecar ${rel} refused by the bench result contract (${defects[0]}) — skipped`);
193
+ continue;
194
+ }
195
+ reports[stem] = parsed;
196
+ mounted = true;
197
+ }
198
+ return Object.keys(reports).length > 0 ? { ...stage, reports } : stage;
199
+ });
200
+ if (!mounted && warnings.length === priorWarnings)
201
+ return row;
202
+ return {
203
+ ...row,
204
+ stages: nextStages,
205
+ ...(warnings.length > 0 ? { warnings } : {}),
206
+ };
207
+ }
208
+ /** The runs registry seat: `ctx.runs`. The estate-runs adapters
209
+ * (Typert) delegate here; the door's registry/pump semantics ride
210
+ * this service verbatim. */
211
+ // ROLE (cookbook adding-a-package role table): Runtime: its contract is dispatch/execution/cancellation (the cookbook role table; a Registry owns membership, which this is not). Key "runs" unchanged (wire-stable).
212
+ /**
213
+ * THE BENCH'S WIRING, SPLIT BY KIND (the wired-bench law's read):
214
+ * cross — a stage takes an input from ANOTHER stage's output. This
215
+ * is the normal, intended shape ("select the input from
216
+ * the previous outputs") and the run MUST be a flow.
217
+ * self — a stage wires its OWN output into its own input. That is
218
+ * a cycle: no composition of it exists, in any arm, so it
219
+ * is named for what it is rather than run.
220
+ * Both are read from the bench doc as it stands — never from a
221
+ * caller's claim about it.
222
+ */
223
+
224
+
225
+
226
+
227
+
228
+
229
+
230
+
231
+
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+ /** The bench run's own line (never silent): how many stages the
241
+ * merged run carries, and that the wires are inside them. */
242
+ function curatedBenchLog(stageCount) {
243
+ console.log("[runs] bench run admitted — " + String(stageCount) +
244
+ " composed stage(s) with their FromStage links riding as stage inputs");
245
+ }
246
+ /** The card plane's engine is the CONTRACT's (benchStage.ts) — the
247
+ * bench is the card bench, and that is where it is stated. This arm
248
+ * applies it to a flow document's card= rows only: an mcp/flow
249
+ * stage that names no engine still refuses below, and that demand
250
+ * is intentional (a flow is hand-authored and must say where it
251
+ * runs; a bench row never has to). */
252
+ function deriveFlowCardEngines(stages) {
253
+ for (const st of stages) {
254
+ if (st === null || typeof st !== "object")
255
+ continue;
256
+ const row = st;
257
+ if (typeof row["card"] !== "string" || row["card"] === "")
258
+ continue;
259
+ row["engine"] = stageEngineOf(row);
260
+ }
261
+ }
262
+ export function benchWiring(benchDoc) {
263
+ const cross = [];
264
+ const self = [];
265
+ const stages = Array.isArray(benchDoc["stages"]) ? benchDoc["stages"] : [];
266
+ for (const st of stages) {
267
+ if (typeof st !== "object" || st === null)
268
+ continue;
269
+ const row = st;
270
+ const id = typeof row["id"] === "string" ? row["id"] : "";
271
+ const ins = row["inputs"];
272
+ if (typeof ins !== "object" || ins === null || Array.isArray(ins))
273
+ continue;
274
+ for (const [name, ref] of Object.entries(ins)) {
275
+ const rr = ref;
276
+ if (rr === null || typeof rr !== "object" || typeof rr["stage"] !== "string")
277
+ continue;
278
+ const label = name + " <- " + String(rr["stage"]) +
279
+ (typeof rr["output"] === "string" ? "." + String(rr["output"]) : "");
280
+ if (rr["stage"] === id)
281
+ self.push(label);
282
+ else
283
+ cross.push(label);
284
+ }
285
+ }
286
+ return { cross, self };
287
+ }
288
+ export class RunsRuntimeService extends Service {
289
+ static inject = ["queue", "draftsRemote", "cardRegistry"];
290
+ /** The pump reentrancy guard (door-verbatim — a public field:
291
+ * cordis proxies services, and private #fields do not cross the
292
+ * proxy). */
293
+ pumping = false;
294
+ /** The boot-reconcile guard (once per boot; the constructor's
295
+ * fire-and-forget burns it — walls re-arm this PUBLIC field and
296
+ * await bootReconcile directly, the pumping-field precedent:
297
+ * private #fields do not cross cordis proxies). */
298
+ reconciled = false;
299
+
300
+
301
+
302
+
303
+
304
+
305
+
306
+
307
+
308
+
309
+
310
+ tearingDown = false;
311
+ /** The cached engine seat for the teardown interrupt: a ctx.get
312
+ * from a DYING fiber refuses (the lookup that feeds the stop
313
+ * door works only while this fiber lives), so the pump caches
314
+ * the seat at claim time and the dispose effect rides the
315
+ * cache. Structural type — no engine import cycle. */
316
+ engineSeat;
317
+ constructor(ctx) {
318
+ super(ctx, "runs");
319
+ // THE RUNS CHANGE SEAM (1.8, the run-view push source): the
320
+ // write spine lives in pure modules (queueCore, runsExecute)
321
+ // that own no Context, so this service — the seat's owner —
322
+ // installs the seam on the bus; every writer keeps calling
323
+ // notifyRunChanged. Fiber-scoped: the effect detaches it when
324
+ // this fiber dies (the bench seat's installer law, verbatim).
325
+ installRunsChangeSeam(this.ctx);
326
+
327
+ // tested-but-unwired): queued sidecars of a DEAD process are
328
+ // REPLAYED through the start door with their own run ids, then
329
+ // stale running claims sweep. Fire-and-forget with a dispose
330
+ // guard; the walls await bootReconcile() directly.
331
+ let disposed = false;
332
+ this.ctx.effect(() => {
333
+ disposed = false;
334
+ // THE TEARDOWN ARM: the same flip arms the pump's claim gate
335
+ // and presses stop on anything in flight (the stop door's
336
+ // own verbs — flag first, engine interrupt best-effort; the
337
+ // worker's stop check converges the state when no seat
338
+ // answers). Never throws: teardown must not fail.
339
+ this.tearingDown = false;
340
+ return () => {
341
+ disposed = true;
342
+ this.tearingDown = true;
343
+ try {
344
+ for (const run of this.core.runs.values()) {
345
+ if (run.status === "queued" || run.status === "running" || run.status === "stopping") {
346
+ run.stopFlag = true;
347
+ }
348
+ }
349
+ const inFlight = [...this.core.runs.values()]
350
+ .filter((r) => r.status === "running" || r.status === "stopping");
351
+ if (inFlight.length > 0) {
352
+ // The cached seat first (a ctx.get from this dying
353
+ // fiber refuses); the fresh lookup is the fallback for
354
+ // a teardown before any claim (best-effort, never
355
+ // throws — teardown must not fail).
356
+ const comfy = this.engineSeat ?? (() => {
357
+ try {
358
+ return needComfyUI(this.ctx, "runsRemote teardown");
359
+ }
360
+ catch {
361
+ return undefined;
362
+ }
363
+ })();
364
+ if (comfy !== undefined) {
365
+ for (const run of inFlight) {
366
+ void comfy.stopForRunDir(run.dir).catch(() => { });
367
+ }
368
+ }
369
+ }
370
+ }
371
+ catch {
372
+ /* no engine seat at teardown: the stopFlags converge the
373
+ * worker loop at its next boundary — teardown never throws */
374
+ }
375
+ };
376
+ }, "estate-runs.reconcile-guard");
377
+ /* v8 ignore next 3 -- defensive-only (the fire-and-forget
378
+ * law's unhandled-rejection guard): planResurrect swallows
379
+ * its own I/O (the readdir try road + per-record reads), so
380
+ * the swallow arms the constructor against FUTURE plan-level
381
+ * faults, never a today-reachable one. The per-run arms own
382
+ * their failure writes; a plan-level fault must never take
383
+ * the fiber down. */
384
+ const swallowPlanFault = () => { };
385
+ void this.bootReconcile(() => disposed).catch(swallowPlanFault);
386
+ }
387
+ /** Subscribe to run-row movement (the seat face runs/subscribe
388
+ * parks on); returns the unsubscribe. Delegates to the module
389
+ * seam — a listener's fault never breaks the write (the wrapper
390
+ * guards; the law lives at runsChange.ts onRunChange). */
391
+ onRunChange(fn) {
392
+ return onRunChange(fn);
393
+ }
394
+ /** THE BOOT RECONCILE (stroke 83; boot_resurrect reborn as a
395
+ * REPLAY, not a hollow requeue): every usable QUEUED record's
396
+ * _request.json goes back through the START door under its own
397
+ * run id — the recompiled row carries REAL params (the old
398
+ * resurrectRuns requeued hollow stage faces and the pump's
399
+ * splice refused them all: every revived run settled failed
400
+ * "no inline workflow"). Replay = resubmit-with-same-id: the
401
+ * draft probe, the strict body, the compile all re-run against
402
+ * CURRENT truth; a refusal settles that run failed LOUD with
403
+ * the door's own voice. FIFO holds (plan order = created_at).
404
+ * After the replay, bootSweep retires stale RUNNING claims of
405
+ * the dead process (the ledgered dispositions, row-28 law). */
406
+ /** The validate door (delegates to the extracted arms). */
407
+ async validate(doc, signal) {
408
+ return validateArm(doc, signal, this.ctx);
409
+ }
410
+ /** The model-validate arm (delegates to the extracted arm). */
411
+ async modelValidateArm(body) {
412
+ return modelValidateArm(body, this.ctx);
413
+ }
414
+ async bootReconcile(disposed = () => false) {
415
+ if (this.reconciled)
416
+ return [];
417
+ this.reconciled = true;
418
+ const stateRoot = this.ctx.queue.stateRoot;
419
+ // Permissive by intent: the start door owns the draft probe —
420
+ // a deleted draft settles failed LOUD here instead of riding
421
+ // the orphan list silently.
422
+ const plan = planResurrect(stateRoot, undefined, undefined, () => true);
423
+ const revived = [];
424
+ for (const runId of plan.order) {
425
+ if (disposed())
426
+ return revived;
427
+ let body = null;
428
+ try {
429
+ body = JSON.parse(readFileSync(join(stateRoot, "output", runId, "_request.json"), "utf8"));
430
+ }
431
+ catch {
432
+ /* v8 ignore next 2 -- TOCTOU-only (the settleReplayRefusal
433
+ * law): the request PARSED at plan time or planResurrect
434
+ * orphaned the record (durableRecordUsable's requestText
435
+ * parse); this re-read catches a torn filesystem between
436
+ * the plan read and the replay read. bootSweep owns the
437
+ * genuinely-corrupt case (walled). */
438
+ continue;
439
+ }
440
+ try {
441
+ await this.start(body, new AbortController().signal, { runId });
442
+ revived.push(runId);
443
+ appendLedger(stateRoot, "run.resurrected", {
444
+ run_id: runId,
445
+ note: "replayed _request.json through the start door (stroke 83)",
446
+ });
447
+ }
448
+ catch (exc) {
449
+ // LOUD, in place: the sidecar moves to failed with the
450
+ // door's refusal text — a poison request can never haunt
451
+ // the next boot as "queued" forever.
452
+ await this.settleReplayRefusal(stateRoot, runId, errText(exc));
453
+ }
454
+ }
455
+ await bootSweep(stateRoot, revived);
456
+ if (revived.length > 0)
457
+ this.kick();
458
+ return revived;
459
+ }
460
+ /** Settle a replay-refused resurrect id: rebuild the row's
461
+ * identity from its own sidecar (the stage faces ride verbatim)
462
+ * and persist failed through the canonical terminal writer. */
463
+ async settleReplayRefusal(stateRoot, runId, error) {
464
+ const dir = join(outRootFor(stateRoot, false), runId);
465
+ let pre = {};
466
+ try {
467
+ // VERBATIM, DELIBERATELY (the work audit's P2, second pass): an
468
+ // earlier cut ran this through parseSidecar and gated the row on
469
+ // it — which zeroed the identity of a sidecar whose STAGES are
470
+ // junk. Carrying that identity forward is this settle's whole
471
+ // job: a refused replay settles LOUD in place showing the
472
+ // operator the run's own faces (created_at, pipeline, stage
473
+ // rows), and a gate here made those read "undefined". The readers
474
+ // that KEY a row by id (the boot sweep, the resurrect plan) are
475
+ // where the parse belongs.
476
+ const raw = JSON.parse(readFileSync(join(dir, "_flow.json"), "utf8"));
477
+ // post-parse shape guard (strictness fix 7): JSON.parse accepts
478
+ // `null`/`42`/`"x"` — the bare cast below would have served
479
+ // them as the settle's identity carrier. TOCTOU-only live: the
480
+ // plan's own parseSidecar refuses non-object docs before any id
481
+ // reaches this re-read (pinned in runs-registry-reconcile).
482
+ /* v8 ignore next -- TOCTOU-only: plan-time parseSidecar owns the static path */
483
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
484
+ throw new Error("sidecar is not an object");
485
+ pre = raw;
486
+ }
487
+ catch {
488
+ /* v8 ignore next 3 -- TOCTOU-only (the agent-engine law):
489
+ * the record was readable+queued at plan time or it never
490
+ * entered the plan; this re-read catches a torn filesystem
491
+ * between the two reads. The zeroed identity below is the
492
+ * honest floor for a vanished sidecar. */
493
+ pre = {};
494
+ }
495
+ const faces = Array.isArray(pre["stages"]) ? pre["stages"] : [];
496
+ const row = {
497
+ runId,
498
+ status: "failed",
499
+ stages: faces,
500
+ skippedStages: Array.isArray(pre["skipped_stages"])
501
+ ? pre["skipped_stages"].map((x) => typeof x === "string" ? x : "")
502
+ : [],
503
+ artifacts: [],
504
+ error,
505
+ /* v8 ignore next -- planResurrect admits only string sidecar
506
+ * draft_ids (durableRecordUsable's gate); the non-string arm
507
+ * is torn-state defense, unreachable in sequence. */
508
+ draftId: typeof pre["draft_id"] === "string" ? pre["draft_id"] : "",
509
+ dir,
510
+ testFlag: false,
511
+ stopFlag: false,
512
+ params: [],
513
+ createdAt: typeof pre["created_at"] === "number" ? pre["created_at"] : 0,
514
+ pipeline: typeof pre["pipeline"] === "string" ? pre["pipeline"] : "flow_inline",
515
+ graphRows: [],
516
+ outputNodes: [],
517
+ // A vanished/torn sidecar's floor: a failed resurrect carries
518
+ // no request initials (the queued original's _flow.json is the
519
+ // durable mirror; a re-plan re-registers through the door).
520
+ initials: {},
521
+ };
522
+ await settlePersist(row, stateRoot);
523
+ }
524
+ /** The queue seat's registry (the FIFO SSOT). */
525
+ get core() {
526
+ return this.ctx.queue.core;
527
+ }
528
+
529
+
530
+
531
+
532
+
533
+
534
+
535
+
536
+
537
+
538
+
539
+
540
+
541
+
542
+
543
+
544
+
545
+ /** ONE card stage, composed (the shared compose core — the bench
546
+ * run and the registry-flow arm both ride it, so a card composes
547
+ * through exactly ONE implementation and one refusal voice).
548
+ * `label` names the seat in a refusal ("bench stage " / "flow
549
+ * stage "). */
550
+ async composeCardStageRow(row, id, runId, label) {
551
+ const cards = this.ctx.cardRegistry;
552
+ const params = (typeof row["params"] === "object" && row["params"] !== null && !Array.isArray(row["params"]))
553
+ ? { ...row["params"] }
554
+ : {};
555
+ const card = String(row["card"] ?? "");
556
+ const mid = String(params["model"] ?? row["service"] ?? "");
557
+ let p1;
558
+ let composed;
559
+ try {
560
+ p1 = await cards.phase1Card({ ...params, card }, mid);
561
+ composed = await cards.phase2Card(p1, runId);
562
+ }
563
+ catch (e) {
564
+ if (e instanceof CardArmError) {
565
+ // QueueRefusal carries {status, payload} — the message
566
+ // lives at payload.error (`.message` was undefined at
567
+ // runtime; tsc had never run over this file).
568
+ const refusal = cardRefusal(e);
569
+ const p = refusal.payload;
570
+ // THE CARD ARM'S CLASSIFICATION AND EVIDENCE, KEPT (one
571
+ // voice per refusal): a card refusal composes here exactly
572
+ // as it does on the card arm — the card plane's own code
573
+ // (lane_input_missing carries the provision fetch URL) and
574
+ // its loc/expected/got, which are what make it actionable.
575
+ // Only the stage name is added, because only this arm knows
576
+ // which bench stage failed.
577
+ const mapped = toRemoteError(refusal);
578
+ // THE WHOLE REFUSAL RIDES, not just its code: the card
579
+ // plane's own loc/expected/got are what make a
580
+ // lane_input_missing actionable (which model, which folder,
581
+ // what was expected). This arm keeps them and adds the
582
+ // bench stage, so the two arms differ by the stage name
583
+ // and by nothing else.
584
+ // toRemoteError always builds a details object (it fills the
585
+ // three keys it has and omits the rest), so no fallback is
586
+ // owed here — a refusal with no evidence carries no keys.
587
+ const carried = { ...mapped.details };
588
+ const cardLoc = carried["loc"];
589
+ carried["loc"] =
590
+ "stages/" + JSON.stringify(id) +
591
+ (typeof cardLoc === "string" && cardLoc !== "" ? " (" + cardLoc + ")" : "");
592
+ throw new RemoteError(mapped.code, label + JSON.stringify(id) + ": " + p.error, carried);
593
+ }
594
+ throw e;
595
+ }
596
+ const stage = {
597
+ id,
598
+ engine: stageEngineOf(row),
599
+ params: {
600
+ workflow: composed.graph,
601
+ output_nodes: composed.outputNodes,
602
+ },
603
+
604
+ // `expected` for its kindsOk walk and defaults an absent bag to
605
+ // {} — so a composed stage that dropped it would compile with NO
606
+ // kind assertion on its own inputs. The registry rows declare
607
+ // them (audio-native-tts: { text: "text" }), and the check is
608
+ // theirs, not the composer's to discard.
609
+ ...(typeof row["expected"] === "object" && row["expected"] !== null && !Array.isArray(row["expected"])
610
+ ? { expected: { ...row["expected"] } }
611
+ : {}),
612
+ // THE WIRES RIDE (the whole point): the bench's own edges,
613
+ // verbatim, for the merged worker to link.
614
+ ...(typeof row["inputs"] === "object" && row["inputs"] !== null && !Array.isArray(row["inputs"])
615
+ ? { inputs: { ...row["inputs"] } }
616
+ : {}),
617
+ // THE BENCH'S OUTPUTS WIN ONLY WHEN THEY CARRY CHANNELS
618
+ // (the work audit's R1 — a regression the card-ports law
619
+ // introduced here): a card stage's stored outputs are `{}` by
620
+ // design (the channels derive from the card's own ports at
621
+ // compose), and this line kept that `{}` verbatim — so the
622
+ // merged worker published ZERO channels and every $spell
623
+ // consumer downstream got nothing where the old fabricated
624
+ // `{default: 'image'}` at least published one. An EMPTY
625
+ // channel map means "unfilled": the compose's own ports
626
+ // answer, exactly as the single-card path already does.
627
+ outputs: (typeof row["outputs"] === "object" && row["outputs"] !== null && !Array.isArray(row["outputs"])
628
+ && Object.keys(row["outputs"]).length > 0)
629
+ ? { ...row["outputs"] }
630
+ : composed.outputs,
631
+ };
632
+ return stage;
633
+ }
634
+
635
+
636
+
637
+
638
+
639
+
640
+
641
+
642
+
643
+
644
+
645
+
646
+
647
+
648
+
649
+
650
+
651
+ async composeRegistryFlowStages(inlineDoc, runId) {
652
+ const rows = inlineDoc["stages"];
653
+ // registryFlowToInline always projects an array of object rows, so
654
+ // the non-array answer needs no second shape (the compile-time
655
+ // gate below judges the same value).
656
+ if (!Array.isArray(rows))
657
+ return inlineDoc;
658
+ const out = [];
659
+ for (const [i, st] of rows.entries()) {
660
+ if (typeof st !== "object" || st === null)
661
+ continue;
662
+ const row = st;
663
+ const card = typeof row["card"] === "string" ? row["card"] : "";
664
+ const id = typeof row["id"] === "string" && row["id"] !== "" ? row["id"] : "s_" + String(i);
665
+ out.push(card === ""
666
+ ? { ...row }
667
+ : await this.composeCardStageRow(row, id, runId, "flow stage "));
668
+ }
669
+ return { ...inlineDoc, stages: out };
670
+ }
671
+ async composeBenchStages(benchDoc, runId) {
672
+ // the sole caller arrives gated on benchWiring(...).cross being
673
+ // non-empty, and benchWiring answers [] unless stages is an
674
+ // array — the non-array fallback here was a dead leg, pruned
675
+ const rows = benchDoc["stages"];
676
+ const out = [];
677
+ for (const [i, st] of rows.entries()) {
678
+ if (typeof st !== "object" || st === null)
679
+ continue;
680
+ const row = st;
681
+ const id = typeof row["id"] === "string" && row["id"] !== "" ? row["id"] : "s_" + String(i);
682
+ // A STAGE WITH NO CARD (an mcp/flow row) composes nowhere here
683
+ // — the bench run is the CARD bench; a foreign stage is named
684
+ // rather than silently dropped (no silent behavior).
685
+ if (typeof row["card"] !== "string" || row["card"] === "") {
686
+ throw new RemoteError("runs/invalid-request", "bench stage " + JSON.stringify(id) +
687
+ " names no card — the bench run composes card stages; an mcp/flow stage belongs in a flow, not the bench", { loc: "stages" });
688
+ }
689
+ out.push(await this.composeCardStageRow(row, id, runId, "bench stage "));
690
+ }
691
+ /* v8 ignore next 4 -- this bench is only composed when
692
+ * benchWiring found a CROSS wire, and benchWiring reaches wires
693
+ * only on object rows that carry an inputs bag — every such row
694
+ * either names a card (it composes, so out is non-empty) or
695
+ * refuses above at the cardless gate. An all-junk bench declares
696
+ * no wire, so it never becomes the bench run. */
697
+ if (out.length === 0) {
698
+ throw new RemoteError("runs/invalid-request", "the bench carries no composable card stage — a wired bench runs its cards, and there are none", { loc: "stages" });
699
+ }
700
+ return out;
701
+ }
702
+ async start(doc, signal,
703
+ /** INTERNAL (stroke 83 boot resurrect): reuse a dead process's
704
+ * run id when replaying its _request.json — the remote surface
705
+ * never passes this (two-arg wire calls only). */
706
+ reuse) {
707
+ signal.throwIfAborted();
708
+ // The pre-registration chain, order (queue.ts's envelope
709
+ // walk with the draft probe handed in): non-object, test-bool,
710
+ // draft required/malformed, then the AWAITED domain probe
711
+ // (unknown doc), then the strict body.
712
+ const draftExists = async (draftId) => {
713
+ try {
714
+ await this.ctx.draftsRemote.get(draftId, signal);
715
+ return true;
716
+ }
717
+ catch (error) {
718
+ const remote = remoteErrorOf(error);
719
+ if (remote !== undefined && remote.code === "draft/not-found") {
720
+ return false;
721
+ }
722
+ throw error;
723
+ }
724
+ };
725
+ // The envelope walk sits HERE (not queue.ts's sync
726
+ // validateSubmitEnvelope) because the draft probe is an
727
+ // AWAITED seat hop — the ORDER is preserved exactly.
728
+ const checked = await this.walkEnvelope(doc, draftExists);
729
+ // THE REFUSAL FIRST (stroke 48: the bench read below needs
730
+ // checked.draftId, which only the ok arm carries — refusing here
731
+ // is the same throw, minus the wasted draft probe).
732
+ if (checked.kind === "refusal")
733
+ throw toRemoteError(checked.refusal);
734
+ // THE BENCH SNAPSHOT (stroke 45d, the operator's question: "the
735
+ // FULL workflow, or just the card that ran?"): the run is born
736
+ // from the bench doc (CARD BIRTH LAW — draft_id = the bench);
737
+ // the doc read at THIS moment is the whole workflow as it stood
738
+ // when the user pressed Run. A read failure stamps nothing (the
739
+ // card snapshot below still carries the exact card + params).
740
+ let benchDoc;
741
+ try {
742
+ benchDoc = (await this.ctx.draftsRemote.get(checked.draftId, signal));
743
+ }
744
+ catch {
745
+ benchDoc = undefined;
746
+ }
747
+ // THE ONE RUN ID, MINTED ONCE (the operator's live refusal,
748
+
749
+ // run-65dc3ee505ef-…/gen)").
750
+ //
751
+ // Every composed graph carries its OWN `${runId}/gen` output
752
+ // prefix, so the run id is not a label — it is an INPUT to every
753
+ // stage's composition, and a forward reference to it must name
754
+ // the run that will exist. The bench-run path minted it TWICE:
755
+ // once to compose the stages (runIdSeed) and again below to
756
+ // register the run (runId). The two are different values, so
757
+ // every composed graph pointed at a run that was never created;
758
+ // the source resolver — correctly, and for the right reason —
759
+ // treated each `${runId}/gen` as a dead source and the run
760
+ // refused before it registered.
761
+ //
762
+ // One mint, one id, both consumers: the compose and the
763
+ // registration cannot disagree about which run exists, because
764
+ // there is only one value to disagree about. A wall drives the
765
+ // pair (the composed run's own forward references resolve, which
766
+ // is impossible when the two ids differ).
767
+ const runId = reuse?.runId ?? newRunId();
768
+ let body = checked.body;
769
+ const strict = strictBodyCheck(body);
770
+ if (strict !== null)
771
+ throw toRemoteError(strict);
772
+ let selected = selectSubmitDoor(body);
773
+ if ("payload" in selected)
774
+ throw toRemoteError(selected);
775
+ // Later strokes own these lanes; both refuse LOUD here (the
776
+ // preview-scope posture — never a silent accept).
777
+ const stateRoot = this.ctx.queue.stateRoot;
778
+
779
+ // own words: "By design, there is no 'non bench flow'. There is
780
+ // ALWAYS FromStage links. THERE IS NO FILTER, NO BREAKAGE FROM
781
+ // THIS. EVER.") ────────────────────────────────────────────────
782
+ // A stage that takes its input from a PRIOR stage's output cannot
783
+ // be run alone: the card arm composes ONE stage with
784
+ // inputNames: {}, so every FromStage link would be discarded. The
785
+ // old answer was a refusal telling the caller to run the flow
786
+ // instead — which is the operator-facing bug this replaces: the
787
+ // GUI's per-stage Run, the agent's card start, and any API caller
788
+ // all hit that wall, and the bench's wires were the very thing
789
+ // the run was FOR.
790
+ //
791
+ // So the door does not refuse a wired bench. IT BECOMES THE
792
+ // BENCH RUN: the body is restaged onto the flow_inline wire with
793
+ // the bench's own stages, and the run proceeds with the wires
794
+ // riding as stage inputs. There is no third shape: a bench with
795
+ // wires is a flow, whatever the caller named.
796
+ let benchComposed = false;
797
+ if (selected.door === "model" && benchDoc !== undefined) {
798
+ const wired = benchWiring(benchDoc);
799
+ if (wired.cross.length > 0) {
800
+
801
+ // behind it: there was no path that ran a WIRED bench. The
802
+ // GUI ran cards one at a time, each its own run, so a FromStage
803
+ // link had nowhere to ride — the wires were not refused, they
804
+ // were DISCARDED by the shape of the run. So this door
805
+ // composes EVERY card stage of the bench — through the SAME
806
+ // registry walk a single card start uses, laws and all — and
807
+ // submits ONE merged run whose stages carry their `inputs`
808
+ // edges for the worker to link. A $spell survives into the
809
+ // composed graph on purpose: the merge resolves it into the
810
+ // upstream stage's output (that is what a FromStage link IS).
811
+
812
+ // "run sources resolve nowhere (1 dead: run-65dc3ee505ef-…/
813
+ // gen)"). The bench run minted the id TWICE: once here, to
814
+ // compose the stages — and again below, to register the run.
815
+ // Every composed graph carries its own `${runId}/gen` output
816
+ // prefix, so the second mint left every forward reference
817
+ // naming a run that was never created; the source resolver
818
+ // (rightly) treated them as dead sources and the run refused
819
+ // before it registered. The id is minted ONCE, here, and both
820
+ // the compose and the registration take it — one derivation,
821
+ // and a wall drives the pair.
822
+ const composed = await this.composeBenchStages(benchDoc, runId);
823
+ const rest = { ...body };
824
+ delete rest["model"];
825
+ delete rest["card"];
826
+ delete rest["params"];
827
+ body = {
828
+ ...rest,
829
+ flow_inline: {
830
+
831
+ // and add it straight back — one address, two spellings.
832
+ id: benchDraftIdOf(String(checked.draftId).replace(BENCH_DRAFT_PREFIX_RE, "")),
833
+ stages: composed,
834
+ },
835
+ };
836
+ selected = { door: "flow_inline" };
837
+ benchComposed = true;
838
+ // the run's own log line says what happened — a re-route is
839
+ // never silent (NO SILENT BEHAVIOR, the same order as the
840
+ // spell gate below)
841
+ console.log("[runs] the bench wires " + JSON.stringify(wired.cross) +
842
+ " — the single-card start became the bench run (" +
843
+ String(composed.length) + " stages composed, wires riding as stage inputs)");
844
+ }
845
+ }
846
+ if (selected.door === "model") {
847
+ // The card start arm (handleCardStart 1016-1136, second
848
+ // move): phase-1 compose (run_id "") BEFORE registration — a
849
+ // params refusal names its field, never a zombie slot — then
850
+ // phase-2 with the minted id, register + sidecars + ledger,
851
+ // pump. Every compose failure refuses with the phase-N voice
852
+ // and registers nothing.
853
+ const mid = String(body["model"] ?? "");
854
+ const cards = this.ctx.cardRegistry;
855
+ let p1;
856
+ try {
857
+ p1 = await cards.phase1Card(body, mid);
858
+ }
859
+ catch (e) {
860
+ if (e instanceof CardArmError)
861
+ throw toRemoteError(cardRefusal(e));
862
+ throw e;
863
+ }
864
+ let composed;
865
+ try {
866
+ composed = await cards.phase2Card(p1, runId);
867
+ }
868
+ catch (e) {
869
+ if (e instanceof CardArmError)
870
+ throw toRemoteError(cardRefusal(e));
871
+ throw e;
872
+ }
873
+ const graph = composed.graph;
874
+ const skeleton = p1.skeleton;
875
+
876
+ // extermination order: NO SILENT BEHAVIOR — ever). The card
877
+ // arm composes ONE stage and resolves NOTHING: inputNames is
878
+ // {} by construction and the merged worker's initials ride
879
+ // empty — so a $spell anywhere in the composed graph is a
880
+ // PROMISE THIS DOOR CANNOT KEEP. Until now such a spell
881
+ // passed the door and died at the merge with a stranger's
882
+ // voice ('workflow carries $name' from rewriteSpells) — the
883
+ // exact silent seam that ate a wired bench run (run
884
+ // 880aaa85d928: bench wired input_images from s_0, the
885
+ // client's Run built a single-card body, the wire vanished,
886
+ // the spell reached the merge unresolved). THE DOOR COVERS
887
+ // WHAT THE RUN WILL DO (the flow_inline gate's own law,
888
+ // runsStart.ts THE SPELL GATE): refuse here, in the door's
889
+ // voice, naming every spell.
890
+ const spellSweep = (v, found) => {
891
+ if (typeof v === "string") {
892
+ if (v.startsWith("$") && v.length > 1)
893
+ found.add(v.slice(1));
894
+ }
895
+ else if (Array.isArray(v)) {
896
+ for (const x of v)
897
+ spellSweep(x, found);
898
+ }
899
+ else if (typeof v === "object" && v !== null) {
900
+ for (const x of Object.values(v)) {
901
+ spellSweep(x, found);
902
+ }
903
+ }
904
+ };
905
+ const spells = new Set();
906
+ spellSweep(graph, spells);
907
+ spellSweep(body, spells);
908
+ if (spells.size > 0) {
909
+ throw toRemoteError(refusal(400, "params carry " +
910
+ JSON.stringify([...spells].sort().map((n) => "$" + n)) +
911
+ " but a single-card run resolves no wires and no initials — the merge would refuse them at run time. Wire the input (run the bench flow so FromStage links ride) or replace the $spell with a concrete value.", "invalid_request"));
912
+ }
913
+ // THE BENCH-WIRE DISCARD GATE (same order): the bench doc this
914
+ // run was born from may wire stage inputs (FromStage links).
915
+ // The card arm composes ONE stage with inputNames: {} — every
916
+ // such wire would be DISCARDED SILENTLY (the run's graph row
917
+ // stamped input_names: {} while the bench wired input_images
918
+ // from s_0). A wire that cannot ride refuses HERE, named —
919
+ // never dropped.
920
+ const wiredRows = [];
921
+ if (benchDoc !== undefined && Array.isArray(benchDoc["stages"])) {
922
+ for (const st of benchDoc["stages"]) {
923
+ if (typeof st !== "object" || st === null)
924
+ continue;
925
+ const ins = st["inputs"];
926
+ if (typeof ins !== "object" || ins === null || Array.isArray(ins)) {
927
+ continue;
928
+ }
929
+ for (const [name, ref] of Object.entries(ins)) {
930
+ const rr = ref;
931
+ if (typeof rr === "object" && rr !== null &&
932
+ typeof rr["stage"] === "string") {
933
+ wiredRows.push(name + " <- " + String(rr["stage"]) +
934
+ (typeof rr["output"] === "string" ? "." + String(rr["output"]) : ""));
935
+ }
936
+ }
937
+ }
938
+ }
939
+ if (wiredRows.length > 0) {
940
+
941
+ // report: a bench carried input_images <- s_0.default — a
942
+ // stage wired to ITSELF, a persisted crime from before the
943
+ // bench door's bench/self-wire law landed). The generic
944
+ // "no FromStage links" message hid the specific crime and
945
+ // read as tool nonsense. Name it: a wire whose stage IS the
946
+ // run's own stage is a CYCLE (bench/self-wire, the same law
947
+ // the write doors hold).
948
+ //
949
+ // A wire naming ANOTHER stage never reaches this gate: the
950
+ // promotion above turns every cross-wired bench into the
951
+ // bench run before the card arm composes (a bench with wires
952
+ // is a flow, whatever the caller named). The cross arms this
953
+ // block once carried were provably dead code — deleted in
954
+
955
+ const selfWired = [];
956
+ /* v8 ignore next -- the same benchDoc and the same stages
957
+ * array the wired-rows walk above tested, with nothing
958
+ * between the two that mutates either. */
959
+ if (benchDoc !== undefined && Array.isArray(benchDoc["stages"])) {
960
+ for (const st of benchDoc["stages"]) {
961
+ if (typeof st !== "object" || st === null)
962
+ continue;
963
+ const stId = st["id"];
964
+ const ins = st["inputs"];
965
+ if (typeof ins !== "object" || ins === null || Array.isArray(ins))
966
+ continue;
967
+ for (const ref of Object.values(ins)) {
968
+ const rr = ref;
969
+ if (typeof rr === "object" && rr !== null && rr["stage"] === stId) {
970
+ selfWired.push(String(stId));
971
+ }
972
+ }
973
+ }
974
+ }
975
+ /* v8 ignore next -- this arm runs only because a wire
976
+ * reached the census, and benchWiring (the promotion above)
977
+ * consumes every CROSS wire into the bench run before the
978
+ * card arm composes — so every wire the census collected is
979
+ * the row's own, and selfWired is never empty here. */
980
+ if (selfWired.length > 0) {
981
+ throw toRemoteError(refusal(400, "the bench carries a SELF-WIRE (bench/self-wire): stage " +
982
+ JSON.stringify([...new Set(selfWired)]) +
983
+ " wires its own output into its own input — a cycle composes nothing. " +
984
+ "This wire predates the bench door's self-wire law and persisted; clear it (rewire the input with no source, or wire a real prior stage) and run again.", "invalid_request"));
985
+ }
986
+ }
987
+ const cardStage = {
988
+ id: skeleton,
989
+ // The {model:} card door's engine (the compose plane is
990
+ // ComfyUI's — the card arm rides it by construction).
991
+ engine: CARD_PLANE_ENGINE,
992
+ params: {
993
+ workflow: graph,
994
+ output_nodes: composed.outputNodes,
995
+ },
996
+ outputs: composed.outputs,
997
+ expected: {},
998
+ outputNodes: composed.outputNodes,
999
+ inputNames: {},
1000
+ };
1001
+ const reg = await registerCompiledRun({
1002
+ compiled: { stages: [cardStage] },
1003
+ testFlag: checked.testFlag,
1004
+ draftId: checked.draftId,
1005
+ stateRoot,
1006
+ enqueue: (row) => this.core.enqueue(row),
1007
+ // F-6(b): the admission warn computes pre-registration so
1008
+ // it rides the record AND the queued sidecar (disk rows
1009
+ // carry it after a reload).
1010
+ warnings: await this.filmAdmissionWarnings(p1.card, body),
1011
+ door: {
1012
+ runId,
1013
+ pipeline: pipelineOf(body),
1014
+ cardId: p1.card,
1015
+ // THE SNAPSHOT-COERCION LAW: the sidecar's request body
1016
+ // carries the numbers the card received (the same wire
1017
+ // family the compose seat runs), not dsh's stringly
1018
+ // encoding — the raw body above still feeds phase-1/2,
1019
+ // which own their own coercion.
1020
+ requestBody: coerceSnapshotBody(cards.defsSync().get(p1.card), body),
1021
+ // the bench snapshot rides the same law per stage: each
1022
+ // row's params coerce through its OWN card's carrier
1023
+ // (unknown cards verbatim), on a COPY — the remote's doc
1024
+ // object is never mutated.
1025
+ benchDoc: benchDoc === undefined ? undefined : {
1026
+ ...benchDoc,
1027
+ stages: Array.isArray(benchDoc["stages"])
1028
+ ? benchDoc["stages"].map((row) => row !== null && typeof row === "object" && !Array.isArray(row)
1029
+ ? {
1030
+ ...row,
1031
+ ...(typeof row["card"] === "string" &&
1032
+ typeof row["params"] === "object"
1033
+ ? {
1034
+ params: coerceSnapshotBody(cards.defsSync().get(row["card"]), row["params"]),
1035
+ }
1036
+ : {}),
1037
+ }
1038
+ : row)
1039
+ : benchDoc["stages"],
1040
+ },
1041
+ },
1042
+ });
1043
+ // THE SOURCE-ECHO REFUSAL: a dead media source refuses at the
1044
+ // door with its URL named — the run never registers.
1045
+ if ("payload" in reg)
1046
+ throw toRemoteError(reg);
1047
+ const { run } = reg;
1048
+ void run;
1049
+ this.kick();
1050
+ return {
1051
+ run_id: run.runId,
1052
+ status: "queued",
1053
+ queue_position: this.core.queuePosition(run.runId),
1054
+ };
1055
+ }
1056
+ // The request initials this start carries (declared at this
1057
+ // scope so the registration below can carry them on the door).
1058
+ // Both flow arms fill it — the named flow shim below, and the
1059
+ // flow_inline arm that recovers the declaration from the doc's
1060
+ // registry id (the boot replay's shape).
1061
+ const requestInitials = {};
1062
+ if (selected.door === "flow") {
1063
+ // THE NAMED-FLOW SHIM (REBUILD-13; the dead door's own law):
1064
+ // the registry flow expands (from_flow links
1065
+ // resolved live) and lands as the flow_inline doc; every gate
1066
+ // after this point — structural compile, single-stage policy,
1067
+ // registration, the merged worker — runs untouched. Multi-stage
1068
+ // and card= shapes refuse at those EXISTING gates with their
1069
+ // preview_scope voices (never silent).
1070
+ const raw = body["flow"];
1071
+ const name = typeof raw === "string" ? raw : "";
1072
+ // ADMISSION BEFORE PRESENCE (the {model} arm's own order): a
1073
+ // name that cannot be a flow id is refused as a shape failure,
1074
+ // never answered as an unknown flow. Without this, `flow: 42`
1075
+ // produced "no flow named in the registry" — the offending
1076
+ // value named nowhere — and an illegal spelling got the
1077
+ // presence voice from two different doors.
1078
+ if (!FLOW_ID_RE.test(name)) {
1079
+ throw new RemoteError("runs/invalid-request",
1080
+ // The RAW value, not the coerced name: `flow: 42` must
1081
+ // read "flow id 42 …" — the empty string the coercion
1082
+ // produced named nothing, which was half the old defect.
1083
+ "flow id " + JSON.stringify(raw) + " is not a legal identifier", { loc: "flow" });
1084
+ }
1085
+ const decl = getRegistryFlow(name);
1086
+ if (decl === undefined) {
1087
+ // The door's unknown-name voice (rendered invalid_request —
1088
+ // the start-door envelope norm for bad requests).
1089
+ throw new RemoteError("runs/invalid-request", "no flow named " + name + " in the registry", { loc: "flow" });
1090
+ }
1091
+ const expanded = expandRegistryFlow(decl);
1092
+ // THE COMPILE-TIME INITIAL GATE (REBUILD-21; the dead door's
1093
+ // law): present initials refuse BEFORE any run registers —
1094
+ // validate runs the same gate, so start can never queue what
1095
+ // validate refuses.
1096
+ const badInitial = registryInitialsError(expanded, body, {
1097
+ repoRoot: resolveRepoRoot(),
1098
+ stateRoot,
1099
+ });
1100
+ if (badInitial !== null) {
1101
+ throw new RemoteError("runs/invalid-request", badInitial, {
1102
+ loc: "body",
1103
+ });
1104
+ }
1105
+ // THE GATE-BLESSED INITIALS RIDE THE RUN: the worker submits
1106
+ // them to the engine merge, where every `$spell` over these
1107
+ // keys links against them — a flow whose stages spell a
1108
+ // declared initial cannot merge without this record. The
1109
+ // extractor's own shapes are the gate's ({path: …} unwraps,
1110
+ // bake_params objects stringify), so the engine sees the
1111
+ // same value the gate validated.
1112
+ const extracted = extractRequestInitials(decl, body);
1113
+ /* v8 ignore next 3 -- the compile-time gate above walks
1114
+ * expanded.initialValidators, which expandRegistryFlow carries
1115
+ * verbatim (it spreads the declaration and replaces only
1116
+ * stages), and it judges the same shapes per kind — so every
1117
+ * value this extractor would refuse was refused there already.
1118
+ * The arm is the extractor's belt for a caller that skips the
1119
+ * gate. */
1120
+ if ("refusal" in extracted) {
1121
+ throw new RemoteError("runs/invalid-request", extracted.refusal, {
1122
+ loc: "body",
1123
+ });
1124
+ }
1125
+ Object.assign(requestInitials, extracted.initials);
1126
+ // THE FAMILY-ACTION STAGES COMPOSE HERE (the atom vocabulary,
1127
+ // stroke 4): a stage naming family+action composes its graph
1128
+ // from the family DECL at expansion — the wire downstream sees
1129
+ // the SAME workflow envelope a raw stage authored, so every
1130
+ // gate after this point (structural compile, the curated-lane
1131
+ // lift, registration, the merged worker) runs untouched. A
1132
+ // refusal here (unknown family/action, unadmitted param,
1133
+ // contradicting hand-write) lands BEFORE any run registers —
1134
+ // the same before-queuing law the initial gate rides.
1135
+ let composedFlow;
1136
+ try {
1137
+ // The seat read rides ctx.get, the engines precedent below:
1138
+ // an undeclared-inject property access would throw cordis's
1139
+ // reflect voice ("cannot get property 'models' without
1140
+ // inject") instead of degrading to the booted singleton.
1141
+ const seat = liveFamilySeat(this.ctx.get("models"));
1142
+ composedFlow = composeFamilyStages(expanded, seat.decls, seat.state);
1143
+ }
1144
+ catch (e) {
1145
+ /* v8 ignore next -- every throw inside composeFamilyStages,
1146
+ * liveFamilySeat and the family DECL actions they call is a
1147
+ * constructed Error (flowsFamilyCompose.ts raises only
1148
+ * new Error), so the non-Error spelling is a belt for a
1149
+ * callee that throws a bare value. */
1150
+ throw new RemoteError("runs/invalid-request", e instanceof Error ? e.message : String(e), { loc: "stages" });
1151
+ }
1152
+ let inlineDoc = registryFlowToInline(composedFlow);
1153
+
1154
+ // `card` on every card-bearing stage, and the compiler refuses
1155
+ // those — which is why every card flow was validate-only. The
1156
+ // card walk composes them here, so a named flow RUNS the way the
1157
+ // bench runs, and the compiler only ever sees compiled stages.
1158
+ if (inlineStagesNameCards(inlineDoc)) {
1159
+ inlineDoc = await this.composeRegistryFlowStages(inlineDoc, runId);
1160
+ console.log("[runs] the flow " + name +
1161
+ " composes its card stages through the card plane (" +
1162
+ inlineDoc["stages"].length + " stages)");
1163
+ }
1164
+ const rest = { ...body };
1165
+ delete rest["flow"];
1166
+ body = { ...rest, flow_inline: inlineDoc };
1167
+ }
1168
+ // ONE stage schema for the whole bench (the law above): every
1169
+ // stage that reaches the compiler carries an engine, whether a
1170
+ // human, the GUI, the agent or a hand-written flow authored it.
1171
+ /* v8 ignore next 3 -- the card arm returned above, so only the
1172
+ * flow arms reach this line, and both of them just set
1173
+ * flow_inline on the body (the named flow shim and the
1174
+ * flow_inline arm that recovered it). */
1175
+ if (typeof body["flow_inline"] === "object" && body["flow_inline"] !== null) {
1176
+ const stages = body["flow_inline"]["stages"];
1177
+ if (Array.isArray(stages))
1178
+ deriveFlowCardEngines(stages);
1179
+ }
1180
+ const inline = body["flow_inline"];
1181
+ // The engines seat when mounted (stroke 53): the door consults
1182
+ // the live registry ids. Absent (fixture/wall boots) the pure
1183
+ // default ['comfyui'] governs — the pre-seam voice.
1184
+ const enginesSeat = this.ctx.get("engines");
1185
+ const knownEngines = enginesSeat !== undefined && typeof enginesSeat.ids === "function"
1186
+ ? enginesSeat.ids()
1187
+ : [CARD_PLANE_ENGINE];
1188
+ const compiled = compileFlowInline(inline, knownEngines);
1189
+ if ("payload" in compiled)
1190
+ throw toRemoteError(compiled);
1191
+ // THE REPLAY ARM RE-EXTRACTS THE INITIALS: a queued flow run's
1192
+ // durable request body is its flow_inline doc (the shim deleted
1193
+ // the flow name), so a run that rehydrates on the next boot
1194
+ // arrives here with no flow arm to extract, and its `$spell`s
1195
+ // would die unlinkable at the engine merge. A doc that names a
1196
+ // registry flow yields its declaration and the SAME gate the
1197
+ // flow arm ran — a hand-authored doc carrying a registry id must
1198
+ // not buy itself the initial-carrier privilege while skipping
1199
+ // the traversal, extension and on-disk checks that close it. A
1200
+ // bench-composed doc's id is always "bench"-prefixed (never a
1201
+ // registry name) and a hand-authored one usually names nothing
1202
+ // registered: nothing to recover, nothing refused.
1203
+ const replayId = inline["id"];
1204
+ if (typeof replayId === "string") {
1205
+ const replayDecl = getRegistryFlow(replayId);
1206
+ if (replayDecl !== undefined) {
1207
+ const badReplayInitial = registryInitialsError(replayDecl, body, {
1208
+ repoRoot: resolveRepoRoot(),
1209
+ stateRoot,
1210
+ });
1211
+ if (badReplayInitial !== null) {
1212
+ throw new RemoteError("runs/invalid-request", badReplayInitial, {
1213
+ loc: "body",
1214
+ });
1215
+ }
1216
+ const replayExtracted = extractRequestInitials(replayDecl, body);
1217
+ /* v8 ignore next 3 -- the replay initials gate above judged
1218
+ * the same declaration's initialValidators one statement
1219
+ * earlier (a replay body is the authored body, so the values
1220
+ * are the gate-blessed ones), leaving this the extractor's
1221
+ * belt for a caller that skips the gate. */
1222
+ if ("refusal" in replayExtracted) {
1223
+ throw new RemoteError("runs/invalid-request", replayExtracted.refusal, {
1224
+ loc: "body",
1225
+ });
1226
+ }
1227
+ Object.assign(requestInitials, replayExtracted.initials);
1228
+ }
1229
+ }
1230
+ if (compiled.stages.length !== 1) {
1231
+
1232
+ // resolved): the merged worker was ALWAYS multi-stage — the
1233
+ // engine's merge walk namespaces stages, links cross-stage
1234
+ // channels, rewrites $spells, and harvests per-stage (the
1235
+ // ROW-4 file-slot gate included); only this gateway gate held
1236
+ // the line. A HAND-AUTHORED multi-stage flow_inline stays
1237
+ // refused (unported, exactly the old voice); a doc whose id
1238
+ // names a REGISTRY flow is curated — its stages compile under
1239
+ // the registry walls and the validate one-admission walk — so
1240
+ // it drives (image-upscale: make → polish through ONE merged
1241
+ // submit).
1242
+ // THE CURATED PROOF: reaching here means compileFlowInline
1243
+ // SUCCEEDED on this inline — and its first gate is isRecord, so
1244
+ // the value is proven a non-array object. No re-checking dance
1245
+ // (a typeof/Array.isArray arm here would be dead code).
1246
+ const inlineId = inline["id"];
1247
+
1248
+ // The line this gate holds is "a hand-written multi-stage graph is
1249
+ // unported" — a doc WE composed from the bench, through the same
1250
+ // registry walk a single card start uses, is the opposite case:
1251
+ // its stages carry the registry's own graphs, its edges carry the
1252
+ // bench's own wires, and the merged worker is multi-stage by
1253
+ // construction. So the bench doc is admitted here on the same
1254
+ // footing as a curated registry flow — named, never silent.
1255
+ if (benchComposed) {
1256
+ curatedBenchLog(compiled.stages.length);
1257
+ // fall through to the registration the single-stage path uses
1258
+ }
1259
+ else {
1260
+ const curated = typeof inlineId === "string" && getRegistryFlow(inlineId) !== undefined;
1261
+ if (!curated) {
1262
+ throw toRemoteError(refusePreview("this gateway serves single-stage flow_inline runs only (" +
1263
+ compiled.stages.length +
1264
+ " stages) — multi-stage graphs are unported " +
1265
+ "(curated registry flows except: name a registry flow id, " +
1266
+ "or drive {flow: '<name>'})"));
1267
+ }
1268
+ }
1269
+ }
1270
+ const reg = await registerCompiledRun({
1271
+ compiled,
1272
+ testFlag: checked.testFlag,
1273
+ draftId: checked.draftId,
1274
+ stateRoot,
1275
+ enqueue: (row) => this.core.enqueue(row),
1276
+ // THE RUN ID IS AN INPUT, NOT A LABEL (the operator's live
1277
+
1278
+ // run-65dc3ee505ef-…/gen)").
1279
+ //
1280
+ // Every composed graph carries its own `${runId}/gen` output
1281
+ // prefix, so the id the stages were composed under MUST be the
1282
+
1283
+ // on the replay seam, so a normal flow_inline/bench run fell
1284
+ // through to runsStart's own mint — a DIFFERENT value — and
1285
+ // every forward reference in every composed graph then named a
1286
+ // run that was never created. The resolver (rightly) called
1287
+ // them dead sources and the run refused before it registered.
1288
+ //
1289
+ // The id rides ALWAYS. The replay arm (stroke 83) keeps its
1290
+ // meaning: the SAME id, rewritten in place, the pump picking
1291
+ // the rehydrated row up on the boot kick.
1292
+ // THE SNAPSHOT RIDES THE BENCH RUN TOO (the adversarial
1293
+
1294
+ // cardSnapshot + benchSnapshot, and this door passed neither —
1295
+ // so a Run ALL registered a run whose "restore the workflow
1296
+ // that made this" reconstructed from the LIVE bench draft,
1297
+ // which is the exact staleness the snapshot law was built to
1298
+ // kill (the bench has moved on by the time anyone restores).
1299
+ // A bench-composed run knows its own doc (read at submit) and
1300
+ // its own stage list; both ride the door verbatim.
1301
+ door: {
1302
+ runId,
1303
+ pipeline: pipelineOf(body),
1304
+ requestBody: body,
1305
+ ...(Object.keys(requestInitials).length === 0
1306
+ ? {}
1307
+ : { initials: requestInitials }),
1308
+ ...(benchDoc === undefined ? {} : { benchDoc }),
1309
+ },
1310
+ });
1311
+ // THE SOURCE-ECHO REFUSAL (same law on the inline door).
1312
+ if ("payload" in reg)
1313
+ throw toRemoteError(reg);
1314
+ const { run } = reg;
1315
+ void run;
1316
+ this.kick();
1317
+ return {
1318
+ run_id: run.runId,
1319
+ status: "queued",
1320
+ queue_position: this.core.queuePosition(run.runId),
1321
+ };
1322
+ }
1323
+ /** The list arm (REBUILD-7): the restore-port envelope over the
1324
+ * output roots. The raw limit STRING rides from the lane (strict
1325
+ * int() semantics: underscores parse, junk refuses). The drafts
1326
+ * probe rides the drafts remote. */
1327
+ async list(rawLimit, signal, test = false) {
1328
+ signal.throwIfAborted();
1329
+ // The door's 400 text (parseIntOrNull in runsList.ts) — the runs face's invalid-request refusal.
1330
+ // ONLY this parse folds; every other failure stays loud (no absorb).
1331
+ const parsed = parseIntOrNull(rawLimit);
1332
+ if (parsed === null) {
1333
+ throw new RemoteError("runs/invalid-request", "limit must be an integer (got '" + rawLimit + "')", { loc: "query.limit", expected: "integer", got: rawLimit });
1334
+ }
1335
+ const limit = Math.max(1, Math.min(500, parsed));
1336
+ // §23 CROSS-ROOTS: the union list across the manifest (own
1337
+ // root first — own rows win collisions, every row served_from).
1338
+ return await listRunsAcross(rootsManifest(this.ctx.queue.stateRoot), limit, async (draftId) => {
1339
+ try {
1340
+ await this.ctx.draftsRemote.get(draftId, signal);
1341
+ return true;
1342
+ }
1343
+ catch {
1344
+ return false;
1345
+ }
1346
+ });
1347
+ }
1348
+ /** The validate arm (REBUILD-8): the PURE compile pipeline
1349
+ * (flowFromBody → compile → pin sweep → the 200 row) over the
1350
+ * door's own bodies. The {model}/{flow} arms refuse the
1351
+ * preview refusal (their remotes are later strokes); a 4xx
1352
+ * answer folds to runs/flow-compile | runs/workflow-pin with
1353
+ * the door's payload voices; the 200 serves verbatim. */
1354
+ /** F-6(b) — THE ADMISSION MEMORY WARN (the film lane's tool
1355
+ * half of the pre-flight): a film admitted while the engine's
1356
+ * VRAM sits below the pressure line warns — the caller stamps
1357
+ * the returned warnings on the run (they ride run_status, never
1358
+ * a refusal). Any telemetry failure (config unreadable, engine
1359
+ * unreachable, stats unparseable) returns none — admission never
1360
+ * blocks on a stats read. */
1361
+ async filmAdmissionWarnings(cardId, body) {
1362
+ if (cardId !== "h3-timeline")
1363
+ return [];
1364
+ const load = filmLoadOf(body);
1365
+ if (load === null)
1366
+ return [];
1367
+ let url = "";
1368
+ try {
1369
+ const cfg = loadEndpointConfig();
1370
+ if (typeof cfg["url"] === "string")
1371
+ url = cfg["url"];
1372
+ }
1373
+ catch {
1374
+ url = "";
1375
+ }
1376
+ const warn = filmMemoryWarn(load, await fetchEngineMem(url));
1377
+ return warn === null ? [] : [warn];
1378
+ }
1379
+ async status(runId, signal, includeLog = false) {
1380
+ signal.throwIfAborted();
1381
+ const run = this.liveRun(runId);
1382
+ if (run === undefined) {
1383
+
1384
+ // lane answered "? — 0/0 stage(s)" / runs/unknown-run for runs
1385
+ // whose on-disk _flow.json held status completed + full stage
1386
+ // and artifact rows — the live map is the queue's cache, disk
1387
+ // is the durable record. A status read crossing a registry
1388
+ // reload (or a husk in-memory row) must still answer the truth
1389
+ // the run tree holds. Never fabricated: no disk row → the same
1390
+ // runs/unknown-run refusal as before.
1391
+ const disk = this.diskRunRow(runId);
1392
+ if (disk === undefined) {
1393
+
1394
+
1395
+ // names the trees it searched — the operator sees WHICH
1396
+ // roots answered, never a bare unknown. No branch: the
1397
+ // queue seat owns stateRoot on every boot (the service
1398
+ // refuses root-less — the constructor's law).
1399
+ throw new RemoteError("runs/unknown-run", "unknown run_id \"" + runId + "\" " +
1400
+ searchedVoice(rootsManifest(this.ctx.queue.stateRoot)), { runId });
1401
+ }
1402
+ return withStageReports({ ...enrichDiskRow(disk.row), from_disk: true, queue_position: 0, served_from: disk.root }, sidecarReaderFor(disk.dir));
1403
+ }
1404
+ const payload = {
1405
+ run_id: run.runId,
1406
+ status: run.status,
1407
+ // §23 CROSS-ROOTS: every row names the root that served it —
1408
+ // live rows ride the seat's own root, disk rows their find.
1409
+ served_from: this.ctx.queue.stateRoot,
1410
+
1411
+ // produced this run — the tab restores via drafts/get (the
1412
+ // draft holds the full card/engine/params stages) + per-stage
1413
+ // bench/add-stage. Additive: older consumers ignore it.
1414
+ draft_id: run.draftId,
1415
+ stages: run.stages,
1416
+ skipped_stages: [...run.skippedStages],
1417
+ // Route-relative (audit #11, proven live by the stroke-82 e2e):
1418
+ // the executor's artifacts are ABSOLUTE DISK PATHS — serving
1419
+ // them raw hands the browser strings the media route cannot
1420
+ // answer (a leading-/ path rides toRunMediaUrl verbatim). The
1421
+ // stage rows' `url` spelling is the truth: <run-id>/<rel>,
1422
+ // computed from the same outRoot the record lives under.
1423
+
1424
+ // the same doubling 023 quoted): relative() off the OUT ROOT
1425
+ // returns `<run-id>/<rel>` (the run dir rides inside), so
1426
+ // prefixing runId again served `<run-id>/<run-id>/<rel>` —
1427
+ // the receipt printed a path that exists nowhere. Relativize
1428
+ // off the RUN DIR: the join restores exactly <run-id>/<rel>.
1429
+ artifacts: [...run.artifacts].map((a) => a.startsWith("/")
1430
+ ? [run.runId, relative(join(outRootFor(this.ctx.queue.stateRoot, run.testFlag), run.runId), a)].join("/")
1431
+ : a),
1432
+ error: run.error,
1433
+ // F-6(b): admission warnings ride the row (additive — older
1434
+ // consumers ignore the key; absent means none were stamped).
1435
+ warnings: [...(run.warnings ?? [])],
1436
+ // THE COMPOSE ECHO, SERVED (the one-press/one-engine law,
1437
+
1438
+ // door served it — the face that pressed Run could not show
1439
+ // what the engine got without shell access). Additive, same
1440
+ // spelling as the sidecar; absent on non-film runs. The disk
1441
+ // fallback below spreads the sidecar row, which carries it.
1442
+ ...(run.composeEcho !== undefined ? { compose_echo: run.composeEcho } : {}),
1443
+ // THE SOURCE ECHO, SERVED (same law: the run's sources ride
1444
+ // the live row too — additive, same spelling as the sidecar).
1445
+ ...(run.sourceEcho !== undefined ? { source_echo: run.sourceEcho } : {}),
1446
+ // THE EXPORT NAME, SERVED (023's self-critique #4/#6: the
1447
+ // design lane's mint rides the live row too — additive,
1448
+ // same spelling as the sidecar; absent on non-export runs.
1449
+ // The disk fallback below spreads the sidecar row, which
1450
+ // carries it).
1451
+ ...(run.exportName !== undefined && run.exportName !== "" ? { export_name: run.exportName } : {}),
1452
+ // THE EXPORT PATH, SERVED (the export FULL PATH): the exact
1453
+ // minted file the engine reported — additive, same spelling
1454
+ // as the sidecar; the disk fallback spreads the sidecar row.
1455
+ ...(run.exportPath !== undefined && run.exportPath !== "" ? { export_path: run.exportPath } : {}),
1456
+ // THE VARIANT, SERVED (commission 033's self-critique #5):
1457
+ // the lane the run rode — additive, same spelling as the
1458
+ // sidecar; the disk fallback spreads the sidecar row, which
1459
+ // carries it. Absent on variant-less runs.
1460
+ ...(run.variant !== undefined && run.variant !== "" ? { variant: run.variant } : {}),
1461
+
1462
+ // compact receipt's data — additive, same spelling as the
1463
+ // sidecar; the disk fallback below spreads the sidecar row,
1464
+ // which carries them.
1465
+ ...(run.loudness !== undefined ? { loudness: run.loudness } : {}),
1466
+ ...(run.voiceFreshness !== undefined ? { voice_freshness: run.voiceFreshness } : {}),
1467
+ // THE TEST FLAG, SERVED (023's self-critique #3): the
1468
+ // agent-facing receipt canonicalizes route-relative artifact
1469
+ // paths against the out root — test runs live under
1470
+ // test-output/, and the row is what names it. Additive.
1471
+ test: run.testFlag,
1472
+ queue_position: this.core.queuePosition(run.runId),
1473
+ };
1474
+ // THE TERMINAL-HUSK RECOVERY (F-5's second face): a live row that
1475
+ // is terminal (completed/failed) yet carries NO stages and NO
1476
+ // artifacts is the husk signature — the queue settled the record
1477
+ // before the executor's rows landed (or a reload raced). Disk
1478
+ // holds the rich row; serve it (marked). A genuinely-empty run
1479
+ // (queued/running with nothing yet, or truly bare) stays live —
1480
+ // only the terminal+empty+disk-richer triple defers.
1481
+ if ((run.status === "completed" || run.status === "failed") &&
1482
+ run.stages.length === 0 && run.artifacts.length === 0) {
1483
+ const disk = this.diskRunRow(runId);
1484
+ const diskStages = disk !== undefined && Array.isArray(disk.row["stages"]) ? disk.row["stages"].length : 0;
1485
+ const diskArts = disk !== undefined && Array.isArray(disk.row["artifacts"]) ? disk.row["artifacts"].length : 0;
1486
+ if (disk !== undefined && (diskStages > 0 || diskArts > 0)) {
1487
+ return withStageReports({ ...enrichDiskRow(disk.row), from_disk: true, queue_position: payload["queue_position"], served_from: disk.root }, sidecarReaderFor(disk.dir));
1488
+ }
1489
+ }
1490
+
1491
+ // a live row that is queued/running yet carries NO stage rows
1492
+ // renders "? — 0/0" at the agent — zero signal for a 20-minute
1493
+ // render, which forced the whole bash-tail poll loop. The plan
1494
+ // is already stamped at registration (graphRows: stage id +
1495
+ // engine; cardId/pipeline; createdAt) — project it, never the
1496
+ // params (a film graph is 50 KB of prompt JSON). The agent sees
1497
+ // "running · plan: 1 stage (h3-timeline) · age 754s" and polls
1498
+ // the cheap door instead of tailing logs.
1499
+ if ((run.status === "queued" || run.status === "running" ||
1500
+ run.status === "stopping") &&
1501
+ run.stages.length === 0) {
1502
+ payload["planned_stages"] = run.graphRows.map((g) => ({
1503
+ id: g.id,
1504
+ engine: g.type,
1505
+ }));
1506
+ payload["card"] = run.cardId ?? run.pipeline;
1507
+ }
1508
+
1509
+ // attempts 14/16's receipts: a long single-stage h3 render shows
1510
+ // "running — 0/1 stage(s)" for ten-plus minutes and the maker
1511
+ // cannot tell progress from stuck): every LIVE row carries
1512
+ // run_age_s, planned or staged — age is the honest liveness
1513
+ // signal the executor owns without asking the engine.
1514
+ if ((run.status === "queued" || run.status === "running" ||
1515
+ run.status === "stopping") &&
1516
+ run.createdAt > 0) {
1517
+ payload["run_age_s"] = Math.max(0, Math.round(Date.now() / 1000 - run.createdAt));
1518
+ }
1519
+ if (includeLog)
1520
+ payload["log_tail"] = runLogTail(payload);
1521
+ // THE REPORT SIDECAR MOUNT, LIVE PATH: the same decorate the
1522
+ // disk fallback serves — a rig run's validate sidecar mounts
1523
+ // whether the row answered from the live map or disk.
1524
+ return withStageReports(payload, sidecarReaderFor(join(outRootFor(this.ctx.queue.stateRoot, run.testFlag), run.runId)));
1525
+ }
1526
+ async stop(runId, signal) {
1527
+ signal.throwIfAborted();
1528
+ const run = this.liveRun(runId);
1529
+ if (run === undefined) {
1530
+ // §23 CROSS-ROOTS: the stop miss names the searched roots
1531
+ // (same law as status — a stop for a maker-owned run says
1532
+ // which trees answered; cross-process stop stays refused by
1533
+ // the unknown code, never a blind guess).
1534
+ throw new RemoteError("runs/run-unknown", "unknown run_id " + JSON.stringify(runId) + " " +
1535
+ searchedVoice(rootsManifest(this.ctx.queue.stateRoot)), { runId });
1536
+ }
1537
+ if (run.status !== "queued" && run.status !== "running" && run.status !== "stopping") {
1538
+ return { error: "cannot stop run in state " + run.status };
1539
+ }
1540
+ // THE STOPPING STAMP (stroke 83 — the state existed in the
1541
+ // union but nothing ever set it): a stop press on a LIVE run
1542
+ // moves the row to "stopping" immediately, so the status door
1543
+ // reports the truth between the press and the settle (the
1544
+ // settle's stopFlag branch overwrites with "stopped"). A
1545
+ // re-press on an already-stopping row is idempotent.
1546
+ if (run.status === "running")
1547
+ run.status = "stopping";
1548
+ run.stopFlag = true;
1549
+ notifyRunChanged(runId);
1550
+ // The interrupt rides the injected engine service when the
1551
+ // seat exists (best-effort — the flag is the authority).
1552
+ try {
1553
+ const comfy = needComfyUI(this.ctx, "runsRemote stop");
1554
+ void comfy.stopForRunDir(run.dir).catch(() => { });
1555
+ }
1556
+ catch {
1557
+ /* no seat: the worker's stop check converges the state */
1558
+ }
1559
+ return { run_id: runId, status: "stopping" };
1560
+ }
1561
+ /** The live map (the queue seat's core registry — rich rows). */
1562
+ liveRun(runId) {
1563
+ return this.core.runs.get(runId);
1564
+ }
1565
+ /** The durable record under the run tree (F-5's fallback read):
1566
+ * the on-disk _flow.json for a run — the SAME file the maker
1567
+ * verified byte-by-byte while status answered husks. The
1568
+ * manifest roots are probed in order (own first), both
1569
+ * out-roots per root (production first, then test) since the
1570
+ * fallback may not know the row's testFlag. Unparseable/absent →
1571
+ * undefined — never a fabricated row. */
1572
+ diskRunRow(runId) {
1573
+
1574
+ // root first, then the maker's tree (MELITE_STATE_ROOTS). Own
1575
+ // writes win; the first root holding the run serves.
1576
+ for (const root of rootsManifest(this.ctx.queue.stateRoot)) {
1577
+ for (const dir of [join(root, "output", runId), join(root, "test-output", runId)]) {
1578
+ try {
1579
+ const doc = JSON.parse(readFileSync(join(dir, "_flow.json"), "utf8"));
1580
+ if (typeof doc === "object" && doc !== null && !Array.isArray(doc)) {
1581
+ const row = doc;
1582
+
1583
+ // run-level status rode out verbatim — a hand-edited or
1584
+ // foreign _flow.json served "banana" as a run status.
1585
+ // The durable boundary judges it: a status outside the
1586
+ // six-value vocabulary means the row is not ours to
1587
+ // serve, the same verdict as unparseable (undefined —
1588
+ // never a fabricated status, never a fold). The writer
1589
+ // only ever writes the six, so real sidecars pass.
1590
+ if (typeof row["status"] !== "string" || !RUN_STATUSES.has(row["status"])) {
1591
+ continue;
1592
+ }
1593
+ return { row, root, dir };
1594
+ }
1595
+ }
1596
+ catch {
1597
+ /* absent/unreadable in this root — try the next */
1598
+ }
1599
+ }
1600
+ }
1601
+ return undefined;
1602
+ }
1603
+ /** The envelope walk with the AWAITED draft probe (door order
1604
+ * preserved: the probe sits between malformed and unknown). */
1605
+ async walkEnvelope(doc, draftExists) {
1606
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc)) {
1607
+ return { kind: "refusal", refusal: envelopeRefusal("not-object", doc) };
1608
+ }
1609
+ const body = doc;
1610
+ // ONE ENVELOPE LAW with checkFlowsStartEnvelope (runsGates) and the
1611
+ // queue door: absent/null test means false — a chat tool's start
1612
+ // doc may carry test:null (LLM serializers emit nulls for omitted
1613
+ // booleans) and the retired gate (submit 1179-1270) never refused
1614
+ // it. This copy had drifted to a bare read, refusing legal calls
1615
+
1616
+ // "test flag must be a boolean (got unknown null)").
1617
+ const testFlag = body["test"] ?? false;
1618
+ if (typeof testFlag !== "boolean") {
1619
+ return {
1620
+ kind: "refusal",
1621
+ refusal: envelopeRefusal("bad-test", doc, { testFlag }),
1622
+ };
1623
+ }
1624
+ const draftId = body["draft_id"];
1625
+ if (typeof draftId !== "string" || draftId === "") {
1626
+ return {
1627
+ kind: "refusal",
1628
+ refusal: envelopeRefusal("missing-draft", doc),
1629
+ };
1630
+ }
1631
+ if (!draftIdOk(draftId)) {
1632
+ return {
1633
+ kind: "refusal",
1634
+ refusal: envelopeRefusal("malformed-draft", doc, { draftId }),
1635
+ };
1636
+ }
1637
+ if (!(await draftExists(draftId))) {
1638
+ return { kind: "refusal", refusal: unknownDraftRefusal(draftId) };
1639
+ }
1640
+ return { kind: "ok", body, testFlag: testFlag, draftId };
1641
+ }
1642
+ /** Kick the serial pump (door-verbatim guard). */
1643
+ kick() {
1644
+ void this.pump();
1645
+ }
1646
+ /** The serial worker: claim the FIFO head, execute, settle —
1647
+ * one GPU run machine-wide, strict submit order. */
1648
+ async pump() {
1649
+ if (this.pumping)
1650
+ return;
1651
+ this.pumping = true;
1652
+ try {
1653
+ for (;;) {
1654
+ // THE TEARDOWN CLAIM GATE: a disposed fiber claims nothing
1655
+ // more — the queued rows stay queued for the next boot's
1656
+ // reconcile (their replay law), and the in-flight run rides
1657
+ // the stopFlags the dispose effect pressed.
1658
+ if (this.tearingDown)
1659
+ return;
1660
+ // The remote only ever enqueues RICH rows (RunRecord
1661
+ // extends the core's row — one object, one voice), so the
1662
+ // claim is this map's own row.
1663
+ const run = this.core.tryDequeue();
1664
+ if (run === null)
1665
+ return;
1666
+
1667
+ // 'running' lands on disk at claim time, not only at settle —
1668
+ // claimPersist (runsTypes.ts) owns the crash window it closes.
1669
+ await claimPersist(run);
1670
+ // Cache the engine seat WHILE this fiber lives — the
1671
+ // teardown effect's interrupt rides this cache (a ctx.get
1672
+ // from a dying fiber refuses). Best-effort: a claim
1673
+ // without a seat leaves the cache untouched, never fails
1674
+ // the run (the worker converges on its own errors).
1675
+ if (this.engineSeat === undefined) {
1676
+ try {
1677
+ this.engineSeat = needComfyUI(this.ctx, "runsRemote pump");
1678
+ }
1679
+ catch {
1680
+ /* no seat yet — the card-plane rigs never have one */
1681
+ }
1682
+ }
1683
+ try {
1684
+ await runOne(run, this.ctx, (r) => this.settle(r));
1685
+ }
1686
+ catch (exc) {
1687
+ // THE CLAIM-RELEASE LAW (audit R1's arm, completed
1688
+
1689
+ // escape between claim and settle — a seat lookup on a
1690
+ // dying fiber, a persist fault — left activeId held with
1691
+ // the pump exited: every later run stranded behind a
1692
+ // claim nobody owned (the commission wedge's queue
1693
+ // half). The pump settles the row failed loud itself and
1694
+ // keeps claiming: the queue may delay a run, never
1695
+ // strand it.
1696
+ const text = "run seat escape (pump settle): " + errText(exc);
1697
+ for (const stage of run.stages) {
1698
+ if (stage["status"] === "running") {
1699
+ stage["status"] = "failed";
1700
+ stage["error"] = text;
1701
+ }
1702
+ }
1703
+ run.status = "failed";
1704
+ run.error = text;
1705
+ try {
1706
+ await this.settle(run);
1707
+ }
1708
+ catch {
1709
+ /* a dying fiber refuses its own seats — settle's very
1710
+ * capture throws. Nothing is left to free HERE: the
1711
+ * claim persist already wrote 'running' on disk, the
1712
+ * fiber's in-memory claim dies with the fiber, and the
1713
+ * next boot's sweep retires the row (queueSweep's law).
1714
+ * Touching this.core would re-read the dead ctx and
1715
+ * escape the pump — the exact shape this catch closes. */
1716
+ }
1717
+ }
1718
+ }
1719
+ }
1720
+ finally {
1721
+ this.pumping = false;
1722
+ }
1723
+ }
1724
+ /** The run's engine id (stroke 53): the first stage's engine,
1725
+ * defaulting to 'comfyui' for pre-seam rows (the only engine
1726
+ * that ever was). Single-stage gateway = one engine per run. */
1727
+ /** The engine read (static delegate to the extracted plane). */
1728
+ static runEngine(run) {
1729
+ return runEngineOf(run);
1730
+ }
1731
+ /** Terminal settle (queue core row + the settle persist). */
1732
+ async settle(run) {
1733
+ // Capture the queue seat before the first await: a settle that
1734
+ // resumes after fiber dispose must not re-read the dead ctx
1735
+ // injection (the persist still completes; the bookkeeping runs
1736
+ // on the captured instance).
1737
+ const queue = this.ctx.queue;
1738
+ await settlePersist(run, queue.stateRoot);
1739
+ queue.core.releaseActive();
1740
+ queue.core.evictSettled();
1741
+ // THE SETTLE WAKE: the change seam's contract lists the settle
1742
+ // among its emitters ("a claim, a settle, an artifacts harvest,
1743
+ // a stop press" — runsChange.ts), but this path never fired it;
1744
+ // a watcher parked on the running row never learned of the
1745
+ // terminal write. Firing after the evict so the re-read serves
1746
+ // the terminal row.
1747
+ notifyRunChanged(run.runId);
1748
+ }
1749
+ }
1750
+ //# sourceMappingURL=runsRegistry.js.map