@melite/estate-queue 0.0.0-stage → 0.1.5-pre-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 (131) hide show
  1. package/LICENSE +557 -0
  2. package/README.md +54 -2
  3. package/lib/bakeParams.d.ts +17 -0
  4. package/lib/bakeParams.js +182 -0
  5. package/lib/bench.d.ts +32 -0
  6. package/lib/bench.js +111 -0
  7. package/lib/cardsArmError.d.ts +61 -0
  8. package/lib/cardsArmError.js +57 -0
  9. package/lib/cardsCompose.d.ts +53 -0
  10. package/lib/cardsCompose.js +295 -0
  11. package/lib/cardsDangling.d.ts +16 -0
  12. package/lib/cardsDangling.js +213 -0
  13. package/lib/cardsFacts.d.ts +87 -0
  14. package/lib/cardsFacts.js +78 -0
  15. package/lib/cardsLanes.d.ts +43 -0
  16. package/lib/cardsLanes.js +178 -0
  17. package/lib/cardsRegistry.d.ts +404 -0
  18. package/lib/cardsRegistry.js +1543 -0
  19. package/lib/cardsVariant.d.ts +37 -0
  20. package/lib/cardsVariant.js +243 -0
  21. package/lib/discloseRegistry.d.ts +95 -0
  22. package/lib/discloseRegistry.js +156 -0
  23. package/lib/filmLead.d.ts +4 -0
  24. package/lib/filmLead.js +17 -0
  25. package/lib/filmMemoryWarn.d.ts +27 -0
  26. package/lib/filmMemoryWarn.js +99 -0
  27. package/lib/flowsData.d.ts +234 -0
  28. package/lib/flowsData.js +673 -0
  29. package/lib/flowsFamilyCompose.d.ts +45 -0
  30. package/lib/flowsFamilyCompose.js +191 -0
  31. package/lib/flowsParamsOverlay.d.ts +55 -0
  32. package/lib/flowsParamsOverlay.js +197 -0
  33. package/lib/flowsRegistryRows.d.ts +12 -0
  34. package/lib/flowsRegistryRows.js +520 -0
  35. package/lib/index.d.ts +47 -0
  36. package/lib/index.js +75 -0
  37. package/lib/ledgerTail.d.ts +20 -0
  38. package/lib/ledgerTail.js +123 -0
  39. package/lib/lifecycleLatch.d.ts +16 -0
  40. package/lib/lifecycleLatch.js +42 -0
  41. package/lib/loadPlane.d.ts +94 -0
  42. package/lib/loadPlane.js +570 -0
  43. package/lib/loadRegistry.d.ts +22 -0
  44. package/lib/loadRegistry.js +55 -0
  45. package/lib/manageOps.d.ts +27 -0
  46. package/lib/manageOps.js +162 -0
  47. package/lib/managePlane.d.ts +151 -0
  48. package/lib/managePlane.js +1790 -0
  49. package/lib/manageProbe.d.ts +48 -0
  50. package/lib/manageProbe.js +165 -0
  51. package/lib/manageRegistry.d.ts +66 -0
  52. package/lib/manageRegistry.js +113 -0
  53. package/lib/managerRail.d.ts +33 -0
  54. package/lib/managerRail.js +91 -0
  55. package/lib/mediaKinds.d.ts +3 -0
  56. package/lib/mediaKinds.js +2 -0
  57. package/lib/queue.d.ts +9 -0
  58. package/lib/queue.js +80 -0
  59. package/lib/queueCore.d.ts +72 -0
  60. package/lib/queueCore.js +128 -0
  61. package/lib/queueLifecycle.d.ts +2 -0
  62. package/lib/queueLifecycle.js +11 -0
  63. package/lib/queueLock.d.ts +60 -0
  64. package/lib/queueLock.js +198 -0
  65. package/lib/queueResurrect.d.ts +59 -0
  66. package/lib/queueResurrect.js +249 -0
  67. package/lib/queueRetry.d.ts +36 -0
  68. package/lib/queueRetry.js +24 -0
  69. package/lib/queueSidecar.d.ts +149 -0
  70. package/lib/queueSidecar.js +183 -0
  71. package/lib/queueSubmit.d.ts +82 -0
  72. package/lib/queueSubmit.js +191 -0
  73. package/lib/queueSweep.d.ts +30 -0
  74. package/lib/queueSweep.js +132 -0
  75. package/lib/resurrect.d.ts +6 -0
  76. package/lib/resurrect.js +18 -0
  77. package/lib/rootsManifest.d.ts +11 -0
  78. package/lib/rootsManifest.js +11 -0
  79. package/lib/runsChange.d.ts +61 -0
  80. package/lib/runsChange.js +79 -0
  81. package/lib/runsErrorCodes.d.ts +2 -0
  82. package/lib/runsErrorCodes.js +48 -0
  83. package/lib/runsExecute.d.ts +52 -0
  84. package/lib/runsExecute.js +494 -0
  85. package/lib/runsGates.d.ts +161 -0
  86. package/lib/runsGates.js +307 -0
  87. package/lib/runsList.d.ts +78 -0
  88. package/lib/runsList.js +574 -0
  89. package/lib/runsRefusalVoices.d.ts +9 -0
  90. package/lib/runsRefusalVoices.js +96 -0
  91. package/lib/runsRegistry.d.ts +351 -0
  92. package/lib/runsRegistry.js +2394 -0
  93. package/lib/runsSourceEcho.d.ts +81 -0
  94. package/lib/runsSourceEcho.js +341 -0
  95. package/lib/runsStart.d.ts +163 -0
  96. package/lib/runsStart.js +667 -0
  97. package/lib/runsTypes.d.ts +218 -0
  98. package/lib/runsTypes.js +289 -0
  99. package/lib/runsValidate.d.ts +5 -0
  100. package/lib/runsValidate.js +31 -0
  101. package/lib/runsValidateArms.d.ts +7 -0
  102. package/lib/runsValidateArms.js +339 -0
  103. package/lib/runsValidateInline.d.ts +6 -0
  104. package/lib/runsValidateInline.js +82 -0
  105. package/lib/runsValidateRefusals.d.ts +7 -0
  106. package/lib/runsValidateRefusals.js +18 -0
  107. package/lib/runsValidateServe.d.ts +15 -0
  108. package/lib/runsValidateServe.js +276 -0
  109. package/lib/runsValidateShared.d.ts +84 -0
  110. package/lib/runsValidateShared.js +88 -0
  111. package/lib/runsValidateStages.d.ts +32 -0
  112. package/lib/runsValidateStages.js +511 -0
  113. package/lib/runsValidateSweeps.d.ts +6 -0
  114. package/lib/runsValidateSweeps.js +143 -0
  115. package/lib/service.d.ts +63 -0
  116. package/lib/service.js +89 -0
  117. package/lib/skillFrontmatter.d.ts +11 -0
  118. package/lib/skillFrontmatter.js +46 -0
  119. package/lib/skillFs.d.ts +24 -0
  120. package/lib/skillFs.js +78 -0
  121. package/lib/skillPlane.d.ts +99 -0
  122. package/lib/skillPlane.js +269 -0
  123. package/lib/skillRegistry.d.ts +23 -0
  124. package/lib/skillRegistry.js +55 -0
  125. package/lib/skillRows.d.ts +127 -0
  126. package/lib/skillRows.js +468 -0
  127. package/lib/toolProjection.d.ts +30 -0
  128. package/lib/toolProjection.js +142 -0
  129. package/lib/vocab.d.ts +6 -0
  130. package/lib/vocab.js +18 -0
  131. package/package.json +48 -4
@@ -0,0 +1,2394 @@
1
+ import { isEstateSidecarName, 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, RUN_MEDIA_PREFIX } 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, initialFileCandidates, registryFlowToInline, inlineStagesNameCards, registryInitialsError, } from "./flowsData.js";
22
+ import { isFile } from "./skillFs.js";
23
+ import { kindsOk } from "./runsValidateStages.js";
24
+ import { replayJudgeRows } from "./runsStart.js";
25
+ import { FlowError } from "./runsValidateShared.js";
26
+ import { composeFamilyStages, liveFamilySeat } from "./flowsFamilyCompose.js";
27
+ import { resolveRepoRoot } from "@melite/comfyui-cordis";
28
+ import { loadEndpointConfig } from "@melite/comfyui-cordis";
29
+ import { fetchEngineMem, filmLoadOf, filmMemoryWarn } from "./filmMemoryWarn.js";
30
+ import { searchedVoice } from "./rootsManifest.js";
31
+ import { newRunId, outRootFor, pipelineOf, strictBodyCheck, planResurrect, bootSweep, appendLedger, refusal, walkSubmitEnvelope } from "./queue.js";
32
+ import { cardRefusal, toRemoteError, refusePreview } from "./runsRefusalVoices.js";
33
+ import { lifecycleInFlight } from "./lifecycleLatch.js";
34
+ import { lanePresenceRefusal } from "./cardsLanes.js";
35
+ import { installRunsChangeSeam, notifyRunChanged, onRunChange } from "./runsChange.js";
36
+ import { coerceSnapshotBody } from "./runsValidateStages.js";
37
+ import { applyFlowParamsOverride, overlayDecls } from "./flowsParamsOverlay.js";
38
+ export { toRemoteError } from "./runsRefusalVoices.js";
39
+ import { readFileSync } from "node:fs";
40
+ import { CardArmError, } from "./cardsRegistry.js";
41
+ import { FLOW_ID_RE } from "./runsGates.js";
42
+ import { compileFlowInline, registerCompiledRun, selectSubmitDoor, } from "./runsStart.js";
43
+ import { listRunsAcross, parseIntOrNull } from "./runsList.js";
44
+ import { claimPersist, errText, runLogTail, settlePersist, RUN_STATUSES, } from "./runsTypes.js";
45
+ import { runOne, runEngine as runEngineOf } from "./runsExecute.js";
46
+ import { engineFilmName } from "./filmLead.js";
47
+ import { validate as validateArm, modelValidateArm } from "./runsValidateArms.js";
48
+ import { BENCH_DRAFT_PREFIX_RE, benchDraftIdOf } from '@melite/contracts/benchStage';
49
+
50
+ // typecheck). The adapter package that CONSUMES the seat declares it
51
+ // on Context — structurally, by its own header's rule: a compiled
52
+ // package may not import these source-run sources into its emit
53
+ // graph, so the contract travels with the caller, and the class that
54
+ // mounts the seat satisfies it structurally. Declaring it here as
55
+ // well (the rename left this twin behind, its comment still naming
56
+ // the pre-rename class) is TS2717 the moment one program composes
57
+ // both sides — which no program did until the walls did.
58
+ /** The refusal codes this remote serves, folded to the
59
+ * protocol's vocabulary — a literal table, no dynamic key. */
60
+ export function enrichDiskRow(row) {
61
+ const stages = Array.isArray(row['stages']) ? row['stages'] : [];
62
+ const artifacts = Array.isArray(row['artifacts'])
63
+ ? row['artifacts'].filter((value) => typeof value === 'string' && value !== '')
64
+ : [];
65
+ if (stages.length !== 1 || artifacts.length === 0)
66
+ return row;
67
+ const stage = stages[0];
68
+ if (stage === null || typeof stage !== 'object' || Array.isArray(stage))
69
+ return row;
70
+ const runId = typeof row['run_id'] === 'string' ? row['run_id'] : '';
71
+ const relative = (value) => {
72
+ const marker = `/${runId}/`;
73
+ const at = value.lastIndexOf(marker);
74
+ return at >= 0 ? value.slice(at + marker.length) : value.replace(/^\/+/, '');
75
+ };
76
+
77
+ // hero's ONLY media law — it carried avif|m4v|avi the contract's
78
+ // vocab did not, and DROPPED svg|bmp the vocab did carry, so a
79
+ // disk row whose lone artifact was an .svg got no hero and no
80
+ // gallery while an .avif was hero'd but unclassifiable. The
81
+ // classifier is the contract's mediaKindOf now, shared with the
82
+ // run list and the gallery client — the seats cannot disagree.
83
+
84
+ // text kind now (SaveText's own format set), so classification
85
+
86
+ // law does. `_request.json` is a sidecar by NAME, never media;
87
+ // a real `result.json` artifact stays eligible.
88
+ const names = [...new Set(artifacts.map(relative))]
89
+ .filter((name) => !isEstateSidecarName(name))
90
+ .filter((name) => mediaKindOf(name) !== undefined);
91
+ if (names.length === 0)
92
+ return row;
93
+ const hero = engineFilmName(names) ?? names[0];
94
+ const current = stage;
95
+ return {
96
+ ...row,
97
+ stages: [{
98
+ ...current,
99
+ ...(typeof current['url'] === 'string' && current['url'] !== '' ? {} : { url: hero }),
100
+ ...(Array.isArray(current['gallery']) ? {} : { gallery: names.map((name) => ({ name })) }),
101
+ }],
102
+ };
103
+ }
104
+
105
+
106
+
107
+
108
+
109
+
110
+ export function sidecarReaderFor(dir) {
111
+ return (name) => {
112
+ try {
113
+ return readFileSync(join(dir, name), 'utf8');
114
+ }
115
+ catch {
116
+ return null;
117
+ }
118
+ };
119
+ }
120
+ /** The sidecar candidates for one stage row: every gallery name's
121
+ * own `<stem>.report.json` sibling, keyed by stem. */
122
+ function sidecarCandidatesOf(stage, runId) {
123
+ const candidates = new Map();
124
+ const add = (name) => {
125
+ const at = name.lastIndexOf('/');
126
+ const dir = at >= 0 ? name.slice(0, at + 1) : '';
127
+ const base = at >= 0 ? name.slice(at + 1) : name;
128
+ const dot = base.lastIndexOf('.');
129
+ const stem = dot > 0 ? base.slice(0, dot) : base;
130
+ if (stem === '')
131
+ return;
132
+ if (!candidates.has(stem))
133
+ candidates.set(stem, `${dir}${stem}.report.json`);
134
+ };
135
+ const gallery = Array.isArray(stage['gallery']) ? stage['gallery'] : [];
136
+ for (const g of gallery) {
137
+ if (typeof g === 'object' && g !== null && !Array.isArray(g)) {
138
+ const name = g['name'];
139
+ if (typeof name === 'string' && name !== '')
140
+ add(name);
141
+ }
142
+ }
143
+ const url = typeof stage['url'] === 'string' ? stage['url'] : '';
144
+ if (url !== '') {
145
+ const marker = `/${runId}/`;
146
+ const at = url.lastIndexOf(marker);
147
+ add(at >= 0 ? url.slice(at + marker.length) : url.replace(/^\/+/, ''));
148
+ }
149
+ return candidates;
150
+ }
151
+
152
+
153
+
154
+
155
+
156
+
157
+
158
+
159
+
160
+
161
+
162
+
163
+
164
+
165
+
166
+
167
+ export function withStageReports(row, read) {
168
+ const runId = typeof row['run_id'] === 'string' ? row['run_id'] : '';
169
+ const stages = Array.isArray(row['stages']) ? row['stages'] : [];
170
+ if (stages.length === 0)
171
+ return row;
172
+ const priorWarnings = Array.isArray(row['warnings']) ? row['warnings'].length : 0;
173
+ const warnings = Array.isArray(row['warnings'])
174
+ ? (row['warnings'].filter((w) => typeof w === 'string'))
175
+ : [];
176
+ let mounted = false;
177
+ const nextStages = stages.map((raw) => {
178
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
179
+ return raw;
180
+ const stage = raw;
181
+ const existing = typeof stage['reports'] === 'object' && stage['reports'] !== null
182
+ && !Array.isArray(stage['reports'])
183
+ ? stage['reports'] : {};
184
+ const reports = { ...existing };
185
+ for (const [stem, rel] of sidecarCandidatesOf(stage, runId)) {
186
+ if (stem in reports)
187
+ continue;
188
+ const text = read(rel);
189
+ if (text === null)
190
+ continue;
191
+ let parsed;
192
+ try {
193
+ parsed = JSON.parse(text);
194
+ }
195
+ catch {
196
+ warnings.push(`report sidecar ${rel} is not JSON — skipped`);
197
+ continue;
198
+ }
199
+ // THE CONTRACT JUDGES (the writer asserts, the reader
200
+ // normalizes — this seat does neither by hand): a probe row
201
+ // carrying only this entry surfaces the entry's own defects.
202
+ const defects = benchResultDefects({ run_id: 'probe', reports: { [stem]: parsed } })
203
+ .filter((d) => d.startsWith(`reports.${stem}`));
204
+ if (defects.length > 0) {
205
+ warnings.push(`report sidecar ${rel} refused by the bench result contract (${defects[0]}) — skipped`);
206
+ continue;
207
+ }
208
+ reports[stem] = parsed;
209
+ mounted = true;
210
+ }
211
+ return Object.keys(reports).length > 0 ? { ...stage, reports } : stage;
212
+ });
213
+ if (!mounted && warnings.length === priorWarnings)
214
+ return row;
215
+ return {
216
+ ...row,
217
+ stages: nextStages,
218
+ ...(warnings.length > 0 ? { warnings } : {}),
219
+ };
220
+ }
221
+ /** The runs registry seat: `ctx.runs`. The estate-runs adapters
222
+ * (Typert) delegate here; the door's registry/pump semantics ride
223
+ * this service verbatim. */
224
+ // 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).
225
+ /**
226
+ * THE BENCH'S WIRING, SPLIT BY KIND (the wired-bench law's read):
227
+ * cross — a stage takes an input from ANOTHER stage's output. This
228
+ * is the normal, intended shape ("select the input from
229
+ * the previous outputs") and the run MUST be a flow.
230
+ * self — a stage wires its OWN output into its own input. That is
231
+ * a cycle: no composition of it exists, in any arm, so it
232
+ * is named for what it is rather than run.
233
+ * Both are read from the bench doc as it stands — never from a
234
+ * caller's claim about it.
235
+ */
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+
244
+
245
+
246
+
247
+
248
+
249
+
250
+
251
+
252
+
253
+ /** The bench run's own line (never silent): how many stages the
254
+ * merged run carries, and that the wires are inside them. */
255
+ function curatedBenchLog(stageCount) {
256
+ console.log("[runs] bench run admitted — " + String(stageCount) +
257
+ " composed stage(s) with their FromStage links riding as stage inputs");
258
+ }
259
+ /** The card plane's engine is the CONTRACT's (benchStage.ts) — the
260
+ * bench is the card bench, and that is where it is stated. This arm
261
+ * applies it to a flow document's card= rows only: an mcp/flow
262
+ * stage that names no engine still refuses below, and that demand
263
+ * is intentional (a flow is hand-authored and must say where it
264
+ * runs; a bench row never has to). */
265
+ function deriveFlowCardEngines(stages) {
266
+ for (const st of stages) {
267
+ if (st === null || typeof st !== "object")
268
+ continue;
269
+ const row = st;
270
+ if (typeof row["card"] !== "string" || row["card"] === "")
271
+ continue;
272
+ row["engine"] = stageEngineOf(row);
273
+ }
274
+ }
275
+ export function benchWiring(benchDoc) {
276
+ const cross = [];
277
+ const self = [];
278
+ const stages = Array.isArray(benchDoc["stages"]) ? benchDoc["stages"] : [];
279
+ for (const st of stages) {
280
+ if (typeof st !== "object" || st === null)
281
+ continue;
282
+ const row = st;
283
+ const id = typeof row["id"] === "string" ? row["id"] : "";
284
+ const ins = row["inputs"];
285
+ if (typeof ins !== "object" || ins === null || Array.isArray(ins))
286
+ continue;
287
+ for (const [name, ref] of Object.entries(ins)) {
288
+ const rr = ref;
289
+ if (rr === null || typeof rr !== "object" || typeof rr["stage"] !== "string")
290
+ continue;
291
+ const label = name + " <- " + String(rr["stage"]) +
292
+ (typeof rr["output"] === "string" ? "." + String(rr["output"]) : "");
293
+ if (rr["stage"] === id)
294
+ self.push(label);
295
+ else
296
+ cross.push(label);
297
+ }
298
+ }
299
+ return { cross, self };
300
+ }
301
+ export class RunsRuntimeService extends Service {
302
+
303
+
304
+
305
+ static PRESS_MEMORY_MAX = 64;
306
+ static inject = ["queue", "draftsRemote", "cardRegistry"];
307
+ /** The pump reentrancy guard (door-verbatim — a public field:
308
+ * cordis proxies services, and private #fields do not cross the
309
+ * proxy). */
310
+ pumping = false;
311
+ /** The boot-reconcile guard (once per boot; the constructor's
312
+ * fire-and-forget burns it — walls re-arm this PUBLIC field and
313
+ * await bootReconcile directly, the pumping-field precedent:
314
+ * private #fields do not cross cordis proxies). */
315
+ reconciled = false;
316
+
317
+
318
+
319
+
320
+
321
+
322
+
323
+
324
+
325
+
326
+
327
+ tearingDown = false;
328
+ /** The cached engine seat for the teardown interrupt: a ctx.get
329
+ * from a DYING fiber refuses (the lookup that feeds the stop
330
+ * door works only while this fiber lives), so the pump caches
331
+ * the seat at claim time and the dispose effect rides the
332
+ * cache. Structural type — no engine import cycle. */
333
+ engineSeat;
334
+ constructor(ctx) {
335
+ super(ctx, "runs");
336
+ // THE RUNS CHANGE SEAM (1.8, the run-view push source): the
337
+ // write spine lives in pure modules (queueCore, runsExecute)
338
+ // that own no Context, so this service — the seat's owner —
339
+ // installs the seam on the bus; every writer keeps calling
340
+ // notifyRunChanged. Fiber-scoped: the effect detaches it when
341
+ // this fiber dies (the bench seat's installer law, verbatim).
342
+ installRunsChangeSeam(this.ctx);
343
+
344
+ // tested-but-unwired): queued sidecars of a DEAD process are
345
+ // REPLAYED through the start door with their own run ids, then
346
+ // stale running claims sweep. Fire-and-forget with a dispose
347
+ // guard; the walls await bootReconcile() directly.
348
+ let disposed = false;
349
+ this.ctx.effect(() => {
350
+ disposed = false;
351
+ // THE TEARDOWN ARM: the same flip arms the pump's claim gate
352
+ // and presses stop on anything in flight (the stop door's
353
+ // own verbs — flag first, engine interrupt best-effort; the
354
+ // worker's stop check converges the state when no seat
355
+ // answers). Never throws: teardown must not fail.
356
+ this.tearingDown = false;
357
+ return () => {
358
+ disposed = true;
359
+ this.tearingDown = true;
360
+ try {
361
+ for (const run of this.core.runs.values()) {
362
+ if (run.status === "queued" || run.status === "running" || run.status === "stopping") {
363
+ run.stopFlag = true;
364
+ }
365
+ }
366
+ const inFlight = [...this.core.runs.values()]
367
+ .filter((r) => r.status === "running" || r.status === "stopping");
368
+ if (inFlight.length > 0) {
369
+ // The cached seat first (a ctx.get from this dying
370
+ // fiber refuses); the fresh lookup is the fallback for
371
+ // a teardown before any claim (best-effort, never
372
+ // throws — teardown must not fail).
373
+ const comfy = this.engineSeat ?? (() => {
374
+ try {
375
+ return needComfyUI(this.ctx, "runsRemote teardown");
376
+ }
377
+ catch {
378
+ return undefined;
379
+ }
380
+ })();
381
+ if (comfy !== undefined) {
382
+ for (const run of inFlight) {
383
+ void comfy.stopForRunDir(run.dir).catch((e) => {
384
+ // named (audit N-S5): an interrupt outage is
385
+ // observable; the stopFlags still converge
386
+ console.log("[estate-queue] teardown interrupt failed:", e instanceof Error ? e.message : String(e));
387
+ });
388
+ }
389
+ }
390
+ }
391
+ }
392
+ catch {
393
+ /* no engine seat at teardown: the stopFlags converge the
394
+ * worker loop at its next boundary — teardown never throws */
395
+ }
396
+ };
397
+ }, "estate-runs.reconcile-guard");
398
+ /* v8 ignore next 3 -- defensive-only (the fire-and-forget
399
+ * law's unhandled-rejection guard): planResurrect swallows
400
+ * its own I/O (the readdir try road + per-record reads), so
401
+ * the swallow arms the constructor against FUTURE plan-level
402
+ * faults, never a today-reachable one. The per-run arms own
403
+ * their failure writes; a plan-level fault must never take
404
+ * the fiber down. */
405
+ const swallowPlanFault = () => { };
406
+ void this.bootReconcile(() => disposed).catch(swallowPlanFault);
407
+ }
408
+ /** Subscribe to run-row movement (the seat face runs/subscribe
409
+ * parks on); returns the unsubscribe. Delegates to the module
410
+ * seam — a listener's fault never breaks the write (the wrapper
411
+ * guards; the law lives at runsChange.ts onRunChange). */
412
+ onRunChange(fn) {
413
+ return onRunChange(fn);
414
+ }
415
+ /** THE BOOT RECONCILE (stroke 83; boot_resurrect reborn as a
416
+ * REPLAY, not a hollow requeue): every usable QUEUED record's
417
+ * _request.json goes back through the START door under its own
418
+ * run id — the recompiled row carries REAL params (the old
419
+ * resurrectRuns requeued hollow stage faces and the pump's
420
+ * splice refused them all: every revived run settled failed
421
+ * "no inline workflow"). Replay = resubmit-with-same-id: the
422
+ * draft probe, the strict body, the compile all re-run against
423
+ * CURRENT truth; a refusal settles that run failed LOUD with
424
+ * the door's own voice. FIFO holds (plan order = created_at).
425
+ * After the replay, bootSweep retires stale RUNNING claims of
426
+ * the dead process (the ledgered dispositions, row-28 law). */
427
+ /** The validate door (delegates to the extracted arms). */
428
+ async validate(doc, signal) {
429
+ return validateArm(doc, signal, this.ctx);
430
+ }
431
+ /** The model-validate arm (delegates to the extracted arm). */
432
+ async modelValidateArm(body) {
433
+ return modelValidateArm(body, this.ctx);
434
+ }
435
+ async bootReconcile(disposed = () => false) {
436
+ if (this.reconciled)
437
+ return [];
438
+ this.reconciled = true;
439
+ const stateRoot = this.ctx.queue.stateRoot;
440
+ // Permissive by intent: the start door owns the draft probe —
441
+ // a deleted draft settles failed LOUD here instead of riding
442
+ // the orphan list silently.
443
+ const plan = planResurrect(stateRoot, undefined, undefined, () => true);
444
+ const revived = [];
445
+ const deferred = [];
446
+ for (const runId of plan.order) {
447
+ if (disposed())
448
+ return revived;
449
+ let body = null;
450
+ try {
451
+ body = JSON.parse(readFileSync(join(stateRoot, "output", runId, "_request.json"), "utf8"));
452
+ }
453
+ catch {
454
+ /* v8 ignore next 2 -- TOCTOU-only (the settleReplayRefusal
455
+ * law): the request PARSED at plan time or planResurrect
456
+ * orphaned the record (durableRecordUsable's requestText
457
+ * parse); this re-read catches a torn filesystem between
458
+ * the plan read and the replay read. bootSweep owns the
459
+ * genuinely-corrupt case (walled). */
460
+ continue;
461
+ }
462
+ try {
463
+ await this.start(body, new AbortController().signal, { runId });
464
+ revived.push(runId);
465
+ appendLedger(stateRoot, "run.resurrected", {
466
+ run_id: runId,
467
+ note: "replayed _request.json through the start door (stroke 83)",
468
+ });
469
+ }
470
+ catch (exc) {
471
+ // THE TRANSIENT REFUSAL (round-20 lifecycle audit Q2): a
472
+ // teardown holding the latch at replay time is not a poison
473
+ // request — settling the row failed would be permanent poison
474
+ // for a refusal a retry cures. The row stays queued, loudly,
475
+ // and rides the sweep's live set so the same pass cannot
476
+ // retire what it just deferred.
477
+ if (exc instanceof RemoteError && exc.code === "runs/lifecycle-inflight") {
478
+ console.warn(`[runs] replay of ${runId} deferred: a lifecycle teardown is in flight (the row stays queued)`);
479
+ deferred.push(runId);
480
+ continue;
481
+ }
482
+ // LOUD, in place: the sidecar moves to failed with the
483
+ // door's refusal text — a poison request can never haunt
484
+ // the next boot as "queued" forever.
485
+ await this.settleReplayRefusal(stateRoot, runId, errText(exc));
486
+ }
487
+ }
488
+ await bootSweep(stateRoot, [...revived, ...deferred]);
489
+ if (revived.length > 0)
490
+ this.kick();
491
+ return revived;
492
+ }
493
+ /** Settle a replay-refused resurrect id: rebuild the row's
494
+ * identity from its own sidecar (the stage faces ride verbatim)
495
+ * and persist failed through the canonical terminal writer. */
496
+ async settleReplayRefusal(stateRoot, runId, error) {
497
+ const dir = join(outRootFor(stateRoot, false), runId);
498
+ let pre = {};
499
+ try {
500
+ // VERBATIM, DELIBERATELY (the work audit's P2, second pass): an
501
+ // earlier cut ran this through parseSidecar and gated the row on
502
+ // it — which zeroed the identity of a sidecar whose STAGES are
503
+ // junk. Carrying that identity forward is this settle's whole
504
+ // job: a refused replay settles LOUD in place showing the
505
+ // operator the run's own faces (created_at, pipeline, stage
506
+ // rows), and a gate here made those read "undefined". The readers
507
+ // that KEY a row by id (the boot sweep, the resurrect plan) are
508
+ // where the parse belongs.
509
+ const raw = JSON.parse(readFileSync(join(dir, "_flow.json"), "utf8"));
510
+ // post-parse shape guard (strictness fix 7): JSON.parse accepts
511
+ // `null`/`42`/`"x"` — the bare cast below would have served
512
+ // them as the settle's identity carrier. TOCTOU-only live: the
513
+ // plan's own parseSidecar refuses non-object docs before any id
514
+ // reaches this re-read (pinned in runs-registry-reconcile).
515
+ /* v8 ignore next -- TOCTOU-only: plan-time parseSidecar owns the static path */
516
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
517
+ throw new Error("sidecar is not an object");
518
+ pre = raw;
519
+ }
520
+ catch {
521
+ /* v8 ignore next 3 -- TOCTOU-only (the agent-engine law):
522
+ * the record was readable+queued at plan time or it never
523
+ * entered the plan; this re-read catches a torn filesystem
524
+ * between the two reads. The zeroed identity below is the
525
+ * honest floor for a vanished sidecar. */
526
+ pre = {};
527
+ }
528
+ const faces = Array.isArray(pre["stages"]) ? pre["stages"] : [];
529
+ const row = {
530
+ runId,
531
+ status: "failed",
532
+ stages: faces,
533
+ skippedStages: Array.isArray(pre["skipped_stages"])
534
+ ? pre["skipped_stages"].map((x) => typeof x === "string" ? x : "")
535
+ : [],
536
+ artifacts: [],
537
+ error,
538
+ /* v8 ignore next -- planResurrect admits only string sidecar
539
+ * draft_ids (durableRecordUsable's gate); the non-string arm
540
+ * is torn-state defense, unreachable in sequence. */
541
+ draftId: typeof pre["draft_id"] === "string" ? pre["draft_id"] : "",
542
+ dir,
543
+ testFlag: false,
544
+ stopFlag: false,
545
+ params: [],
546
+ createdAt: typeof pre["created_at"] === "number" ? pre["created_at"] : 0,
547
+ pipeline: typeof pre["pipeline"] === "string" ? pre["pipeline"] : "flow_inline",
548
+ graphRows: [],
549
+ outputNodes: [],
550
+ // A vanished/torn sidecar's floor: a failed resurrect carries
551
+ // no request initials (the queued original's _flow.json is the
552
+ // durable mirror; a re-plan re-registers through the door).
553
+ initials: {},
554
+ };
555
+ await settlePersist(row, stateRoot);
556
+ }
557
+ /** The queue seat's registry (the FIFO SSOT). */
558
+ get core() {
559
+ return this.ctx.queue.core;
560
+ }
561
+
562
+
563
+
564
+
565
+
566
+
567
+
568
+
569
+
570
+
571
+
572
+
573
+
574
+
575
+
576
+
577
+
578
+ /** ONE card stage, composed (the shared compose core — the bench
579
+ * run and the registry-flow arm both ride it, so a card composes
580
+ * through exactly ONE implementation and one refusal voice).
581
+ * `label` names the seat in a refusal ("bench stage " / "flow
582
+ * stage "). */
583
+ async composeCardStageRow(row, id, runId, label,
584
+
585
+
586
+
587
+
588
+ famsOut) {
589
+ const cards = this.ctx.cardRegistry;
590
+ const params = (typeof row["params"] === "object" && row["params"] !== null && !Array.isArray(row["params"]))
591
+ ? { ...row["params"] }
592
+ : {};
593
+ const card = String(row["card"] ?? "");
594
+ // STROKE 3'S FALLBACK (the validate walk's own shape —
595
+ // runsValidateArms: a family-less card stage composes by its OWN
596
+ // card id — mid alone, never an injected body.model, which would
597
+ // hit the board check before prepareCardParams resolved the
598
+ // card-unit arm). The old `?? ""` handed prepareCardParams an
599
+ // empty mid — "model id \"\" is not a legal identifier" on the
600
+ // body-to-somax rig hop and every family-less flow stage after
601
+
602
+
603
+ // effective routing key rode an EXPLICIT spelling — params.model
604
+ // or the row's service key — the compose lanes that value while
605
+ // the admission judge reads body.model only, so a service-bearing
606
+ // row ran in the routing family's lane UNGATED by the board law
607
+ // (live receipt: the tts+krea-2 row composing image-gen's voice).
608
+ // The stamp hands the judge the value that lanes. The ?? card
609
+ // fallback is NEVER stamped: for a family-less card mid is the
610
+ // card-unit alias's own spelling (mid alone; the GUI's explicit
611
+ // card-id press rides the alias arm at admitStageModel), and a
612
+ // boarded card with no model picked keeps its honest phase-2
613
+ // refusal ("requires a model id").
614
+ const service = typeof row["service"] === "string" && row["service"] !== "" ? row["service"] : undefined;
615
+ const mid = String(params["model"] ?? service ?? card);
616
+ if (params["model"] === undefined && service !== undefined)
617
+ params["model"] = service;
618
+ let p1;
619
+ let composed;
620
+ try {
621
+ p1 = await cards.phase1Card({ ...params, card }, mid);
622
+ composed = await cards.phase2Card(p1, runId);
623
+ }
624
+ catch (e) {
625
+ if (e instanceof CardArmError) {
626
+ // QueueRefusal carries {status, payload} — the message
627
+ // lives at payload.error (`.message` was undefined at
628
+ // runtime; tsc had never run over this file).
629
+ const refusal = cardRefusal(e);
630
+ const p = refusal.payload;
631
+ // THE CARD ARM'S CLASSIFICATION AND EVIDENCE, KEPT (one
632
+ // voice per refusal): a card refusal composes here exactly
633
+ // as it does on the card arm — the card plane's own code
634
+ // (lane_input_missing carries the provision fetch URL) and
635
+ // its loc/expected/got, which are what make it actionable.
636
+ // Only the stage name is added, because only this arm knows
637
+ // which bench stage failed.
638
+ const mapped = toRemoteError(refusal);
639
+ // THE WHOLE REFUSAL RIDES, not just its code: the card
640
+ // plane's own loc/expected/got are what make a
641
+ // lane_input_missing actionable (which model, which folder,
642
+ // what was expected). This arm keeps them and adds the
643
+ // bench stage, so the two arms differ by the stage name
644
+ // and by nothing else.
645
+ // toRemoteError always builds a details object (it fills the
646
+ // three keys it has and omits the rest), so no fallback is
647
+ // owed here — a refusal with no evidence carries no keys.
648
+ const carried = { ...mapped.details };
649
+ const cardLoc = carried["loc"];
650
+ carried["loc"] =
651
+ "stages/" + JSON.stringify(id) +
652
+ (typeof cardLoc === "string" && cardLoc !== "" ? " (" + cardLoc + ")" : "");
653
+ throw new RemoteError(mapped.code, label + JSON.stringify(id) + ": " + p.error, carried);
654
+ }
655
+ throw e;
656
+ }
657
+ const stageOutputs = (typeof row["outputs"] === "object" && row["outputs"] !== null && !Array.isArray(row["outputs"])
658
+ && Object.keys(row["outputs"]).length > 0)
659
+ ? { ...row["outputs"] }
660
+ // THE BENCH'S OUTPUTS WIN ONLY WHEN THEY CARRY CHANNELS
661
+ // (the work audit's R1 — a regression the card-ports law
662
+ // introduced here): a card stage's stored outputs are `{}` by
663
+ // design (the channels derive from the card's own ports at
664
+ // compose), and this line kept that `{}` verbatim — so the
665
+ // merged worker published ZERO channels and every $spell
666
+ // consumer downstream got nothing where the old fabricated
667
+ // `{default: 'image'}` at least published one. An EMPTY
668
+ // channel map means "unfilled": the compose's own ports
669
+ // answer, exactly as the single-card path already does.
670
+ : composed.outputs;
671
+ // THE OUTPUT RENAME FOLLOWS THE BINDINGS (the run-9f8bd60f8cb8
672
+
673
+ // channels (outputs {body: "mesh"} over the card's own
674
+ // {default: "mesh"}), but params.output_nodes kept the card's
675
+ // naming — the merged worker then bound the artifact under
676
+ // "default" while the declared channel was "body": the unbound
677
+ // ext sweep published "body" fine, and the receipt gate refused
678
+ // binding channel "default" as produced-no-artifact although the
679
+ // GLB sat fetched on disk. When the row renames, the bindings
680
+ // rename with it — kind-matched, one-to-one; an ambiguous kind
681
+ // (two declared channels of one kind) leaves the card naming
682
+ // verbatim and the receipt gate names the ambiguity loud.
683
+ const cardOuts = (composed.outputs ?? {});
684
+ const cardNodes = (composed.outputNodes ?? {});
685
+ const rowChannelsByKind = {};
686
+ for (const [ch, kind] of Object.entries(stageOutputs)) {
687
+ (rowChannelsByKind[String(kind)] ??= []).push(ch);
688
+ }
689
+ const renamedNodes = {};
690
+ let renamedAny = false;
691
+ for (const [ch, node] of Object.entries(cardNodes)) {
692
+ const targets = rowChannelsByKind[String(cardOuts[ch] ?? "")] ?? [];
693
+ if (targets.length === 1 && stageOutputs[ch] === undefined) {
694
+ renamedNodes[targets[0]] = node;
695
+ renamedAny = true;
696
+ }
697
+ else {
698
+ renamedNodes[ch] = node;
699
+ }
700
+ }
701
+ // benchExpected: the derivation law's bench half (J-E1 comment
702
+ // at the spread below) — the card's declared input kinds fill the
703
+ // absent slots, the hand-written row wins per input.
704
+ const cardDef = cards.defsSync().get(card);
705
+ const cardInputs = cardDef?.flowKinds?.inputs;
706
+ const cardAliases = cardDef?.flowKinds?.legacyAliases;
707
+ const rowExpected = (typeof row["expected"] === "object" && row["expected"] !== null && !Array.isArray(row["expected"]))
708
+ ? row["expected"]
709
+ : {};
710
+ const benchExpected = cardInputs === undefined && cardAliases === undefined
711
+ ? { ...rowExpected }
712
+ : { ...(cardInputs ?? {}), ...(cardAliases ?? {}), ...rowExpected };
713
+ const stage = {
714
+ id,
715
+ engine: stageEngineOf(row),
716
+ params: {
717
+ workflow: composed.graph,
718
+ output_nodes: (renamedAny ? renamedNodes : cardNodes),
719
+ },
720
+
721
+ // `expected` for its kindsOk walk and defaults an absent bag to
722
+ // {} — so a composed stage that dropped it would compile with NO
723
+ // kind assertion on its own inputs. The registry rows declare
724
+ // them (audio-native-tts: { text: "text" }), and the check is
725
+ // theirs, not the composer's to discard.
726
+ //
727
+
728
+ // law runs at the compose too, not only in validate's kindsOk —
729
+ // a bench row carries inputs with no hand-written expected, and
730
+ // an empty bag queued the run with no kind assertion on its own
731
+ // wired inputs. The card's declared input kinds (legacy aliases
732
+ // included, the naming law's lattice half) fill the absent
733
+ // slots; a hand-written row still wins per input, because the
734
+ // override exists for initials the card cannot know.
735
+ ...(Object.keys(benchExpected).length > 0 ? { expected: benchExpected } : {}),
736
+ // THE WIRES RIDE (the whole point): the bench's own edges,
737
+ // verbatim, for the merged worker to link.
738
+ ...(typeof row["inputs"] === "object" && row["inputs"] !== null && !Array.isArray(row["inputs"])
739
+ ? { inputs: { ...row["inputs"] } }
740
+ : {}),
741
+ outputs: stageOutputs,
742
+ };
743
+ if (famsOut !== undefined)
744
+ famsOut[id] = p1.fam;
745
+ return stage;
746
+ }
747
+
748
+
749
+
750
+
751
+
752
+
753
+
754
+
755
+
756
+
757
+
758
+
759
+
760
+
761
+
762
+
763
+
764
+ async composeRegistryFlowStages(inlineDoc, runId,
765
+
766
+
767
+ stageFams) {
768
+ const rows = inlineDoc["stages"];
769
+ // registryFlowToInline always projects an array of object rows, so
770
+ // the non-array answer needs no second shape (the compile-time
771
+ // gate below judges the same value).
772
+ if (!Array.isArray(rows))
773
+ return inlineDoc;
774
+ const out = [];
775
+ for (const [i, st] of rows.entries()) {
776
+ if (typeof st !== "object" || st === null)
777
+ continue;
778
+ const row = st;
779
+ const card = typeof row["card"] === "string" ? row["card"] : "";
780
+ const id = typeof row["id"] === "string" && row["id"] !== "" ? row["id"] : "s_" + String(i);
781
+ out.push(card === ""
782
+ ? { ...row }
783
+ : await this.composeCardStageRow(row, id, runId, "flow stage ", stageFams));
784
+ }
785
+ return { ...inlineDoc, stages: out };
786
+ }
787
+ async composeBenchStages(benchDoc, runId,
788
+
789
+
790
+
791
+
792
+
793
+ famsOut) {
794
+ // the sole caller arrives gated on benchWiring(...).cross being
795
+ // non-empty, and benchWiring answers [] unless stages is an
796
+ // array — the non-array fallback here was a dead leg, pruned
797
+ const rows = benchDoc["stages"];
798
+ const out = [];
799
+ for (const [i, st] of rows.entries()) {
800
+ if (typeof st !== "object" || st === null)
801
+ continue;
802
+ const row = st;
803
+ const id = typeof row["id"] === "string" && row["id"] !== "" ? row["id"] : "s_" + String(i);
804
+ // A STAGE WITH NO CARD (an mcp/flow row) composes nowhere here
805
+ // — the bench run is the CARD bench; a foreign stage is named
806
+ // rather than silently dropped (no silent behavior).
807
+ if (typeof row["card"] !== "string" || row["card"] === "") {
808
+ throw new RemoteError("runs/invalid-request", "bench stage " + JSON.stringify(id) +
809
+ " names no card — the bench run composes card stages; an mcp/flow stage belongs in a flow, not the bench", { loc: "stages" });
810
+ }
811
+ out.push(await this.composeCardStageRow(row, id, runId, "bench stage ", famsOut));
812
+ }
813
+ /* v8 ignore next 4 -- this bench is only composed when
814
+ * benchWiring found a CROSS wire, and benchWiring reaches wires
815
+ * only on object rows that carry an inputs bag — every such row
816
+ * either names a card (it composes, so out is non-empty) or
817
+ * refuses above at the cardless gate. An all-junk bench declares
818
+ * no wire, so it never becomes the bench run. */
819
+ if (out.length === 0) {
820
+ 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" });
821
+ }
822
+ return out;
823
+ }
824
+ async start(doc, signal,
825
+ /** INTERNAL (stroke 83 boot resurrect): reuse a dead process's
826
+ * run id when replaying its _request.json — the remote surface
827
+ * never passes this (two-arg wire calls only). */
828
+ reuse) {
829
+ signal.throwIfAborted();
830
+ // The pre-registration chain, order (queue.ts's envelope
831
+ // walk with the draft probe handed in): non-object, test-bool,
832
+ // draft required/malformed, then the AWAITED domain probe
833
+ // (unknown doc), then the strict body.
834
+ const draftExists = async (draftId) => {
835
+ try {
836
+ await this.ctx.draftsRemote.get(draftId, signal);
837
+ return true;
838
+ }
839
+ catch (error) {
840
+ const remote = remoteErrorOf(error);
841
+ if (remote !== undefined && remote.code === "draft/not-found") {
842
+ return false;
843
+ }
844
+ throw error;
845
+ }
846
+ };
847
+ // The envelope walk sits HERE (the one shared walker,
848
+ // walkSubmitEnvelope — the S3 twin cure deleted the sync face)
849
+ // because the draft probe is an AWAITED seat hop — the ORDER is
850
+ // preserved exactly.
851
+ const checked = await walkSubmitEnvelope(doc, draftExists);
852
+ // THE REFUSAL FIRST (stroke 48: the bench read below needs
853
+ // checked.draftId, which only the ok arm carries — refusing here
854
+ // is the same throw, minus the wasted draft probe).
855
+ if (checked.kind === "refusal")
856
+ throw toRemoteError(checked.refusal);
857
+
858
+ // refuses the press BEFORE the replay, the reserve and the mint —
859
+ // a run born now would tear mid-render. Named code, and the
860
+ // replay cannot launder it (the check sits above the replay).
861
+ const lifecycleHeld = lifecycleInFlight();
862
+ if (lifecycleHeld !== null) {
863
+ throw toRemoteError(refusal(409, "refused: lifecycle " + lifecycleHeld + " in flight — retry the press when it settles (the teardown holds the run gate until it completes)", "lifecycle_inflight"));
864
+ }
865
+
866
+ // answered names a run that exists — return ITS summary, mint
867
+ // nothing, enqueue nothing. The row is gone (swept, or its seat
868
+ // restarted) → the key is stale, a retry may run again.
869
+ const pressKey = typeof checked.body["press_key"] === "string"
870
+ ? checked.body["press_key"]
871
+ : undefined;
872
+ if (pressKey !== undefined) {
873
+ const replay = this.pressReplay(pressKey);
874
+ if (replay !== null)
875
+ return replay;
876
+ // THE CONCURRENT-PRESS RESERVATION (the double-mint cure,
877
+
878
+ // first mint registers — two concurrent starts with one key
879
+ // both saw the empty map and minted twice (two runs, two
880
+ // enqueues, double GPU spend). The reservation goes in
881
+ // SYNCHRONOUSLY after a miss (no await sits between), so
882
+ // exactly one caller becomes the minter; the twin rides its
883
+ // promise — one run_id, one enqueue, the same answer face.
884
+ // The reservation's identity is the key STRING, not the body:
885
+ // a second body under one key is the same press (the client
886
+ // re-sent it), so the twin answers the minting body's outcome.
887
+ const twin = this.reservePress(pressKey);
888
+ if (twin !== null)
889
+ return await this.awaitTwin(twin, signal);
890
+ try {
891
+ return await this.startReserved(pressKey, checked, signal, reuse);
892
+ }
893
+ catch (error) {
894
+ this.failPress(pressKey, error);
895
+ throw error;
896
+ }
897
+ finally {
898
+ this.pendingPresses.delete(pressKey);
899
+ }
900
+ }
901
+ return this.startReserved(undefined, checked, signal, reuse);
902
+ }
903
+
904
+
905
+
906
+
907
+
908
+ pressReplay(pressKey) {
909
+ const seen = this.presses.get(pressKey);
910
+ if (seen !== undefined) {
911
+ const row = this.core.runs.get(seen);
912
+ if (row !== undefined) {
913
+ return {
914
+ run_id: row.runId,
915
+ status: row.status,
916
+ queue_position: this.core.queuePosition(row.runId),
917
+ };
918
+ }
919
+ this.presses.delete(pressKey);
920
+ }
921
+ else {
922
+
923
+ // the key while its run still lives (a queued press behind a
924
+ // long render outlives 64 newer presses routinely). The row's
925
+ // own stamp answers the replay — the double-spend window the
926
+ // press memory was built to close stays closed past the cap.
927
+ // the registry stores full RunRecords in the queue's map
928
+ // (liveRun's own cast — QueueRunRow is the queue's narrow view)
929
+ for (const row of this.core.runs.values()) {
930
+ if (row.pressKey !== pressKey)
931
+ continue;
932
+ this.rememberPress(pressKey, row.runId); // re-admit to the map
933
+ return {
934
+ run_id: row.runId,
935
+ status: row.status,
936
+ queue_position: this.core.queuePosition(row.runId),
937
+ };
938
+ }
939
+ }
940
+ return null;
941
+ }
942
+ /** THE START ARMS under a settled replay/reservation verdict: the
943
+ * bench-composed arm and the flow_inline arm, behavior-verbatim
944
+ * from before the concurrent-press cure split them behind the
945
+ * shell (the split's only edits are the two summary settles). */
946
+ async startReserved(pressKey, checked, signal, reuse) {
947
+
948
+ // arm scope owns it — the registerCompiledRun door reads it
949
+ // after the name/flow_inline blocks close (flow arms AND the
950
+ // bench-composed arm feed it; the single-card run alone rides
951
+ // its fam key).
952
+ let flowStageFams = {};
953
+ // THE BENCH SNAPSHOT (stroke 45d, the operator's question: "the
954
+ // FULL workflow, or just the card that ran?"): the run is born
955
+ // from the bench doc (CARD BIRTH LAW — draft_id = the bench);
956
+ // the doc read at THIS moment is the whole workflow as it stood
957
+ // when the user pressed Run. A read failure stamps a warning on
958
+ // the row (audit N-S3): draftExists probed true a moment ago, so
959
+ // a failure HERE is a transient drafts outage — the run proceeds
960
+ // on the card snapshot alone and the wand will restore from the
961
+ // LIVE bench, the exact staleness the snapshot law kills. The
962
+ // row says so.
963
+ let benchDoc;
964
+ const benchWarnings = [];
965
+ try {
966
+ // R7 CURE (round-14 race audit, LOW — the run-press live alias):
967
+ // the drafts read answers the CACHED doc by reference (the
968
+ // cached-object law), so composing + snapshotting from it naked
969
+ // let a mutation landing between press and snapshot straddle
970
+ // the two (a snapshot that was not quite a snapshot). The
971
+ // press now owns a DEEP copy: what the run composes and what
972
+ // the sidecar snapshots is the SAME frozen instant, no matter
973
+ // what the live bench does next.
974
+ benchDoc = structuredClone(await this.ctx.draftsRemote.get(checked.draftId, signal));
975
+ }
976
+ catch (e) {
977
+ benchDoc = undefined;
978
+ benchWarnings.push("bench snapshot read failed at press (" +
979
+ (e instanceof Error ? e.message : String(e)) +
980
+ ") — only the card snapshot rode; restore reconstructs from the live bench");
981
+ }
982
+ // THE ONE RUN ID, MINTED ONCE (the operator's live refusal,
983
+
984
+ // run-65dc3ee505ef-…/gen)").
985
+ //
986
+ // Every composed graph carries its OWN `${runId}/gen` output
987
+ // prefix, so the run id is not a label — it is an INPUT to every
988
+ // stage's composition, and a forward reference to it must name
989
+ // the run that will exist. The bench-run path minted it TWICE:
990
+ // once to compose the stages (runIdSeed) and again below to
991
+ // register the run (runId). The two are different values, so
992
+ // every composed graph pointed at a run that was never created;
993
+ // the source resolver — correctly, and for the right reason —
994
+ // treated each `${runId}/gen` as a dead source and the run
995
+ // refused before it registered.
996
+ //
997
+ // One mint, one id, both consumers: the compose and the
998
+ // registration cannot disagree about which run exists, because
999
+ // there is only one value to disagree about. A wall drives the
1000
+ // pair (the composed run's own forward references resolve, which
1001
+ // is impossible when the two ids differ).
1002
+ const runId = reuse?.runId ?? newRunId();
1003
+ let body = checked.body;
1004
+ const strict = strictBodyCheck(body);
1005
+ if (strict !== null)
1006
+ throw toRemoteError(strict);
1007
+ let selected = selectSubmitDoor(body, {
1008
+ // THE BENCH-SHAPE GATE: a draft-only press is the bench door
1009
+ // only over a draft that IS a bench — a doc carrying a
1010
+ // non-empty stages array. Anything else (the envelope spec's
1011
+ // bare d1 doc, an emptied bench) is a shapeless body: the
1012
+ // gate's own "no flow selected" stands.
1013
+ draftBench: benchDoc !== undefined &&
1014
+ "draft_id" in body &&
1015
+ Array.isArray(benchDoc["stages"]) &&
1016
+ benchDoc["stages"].length > 0,
1017
+ });
1018
+ if ("payload" in selected)
1019
+ throw toRemoteError(selected);
1020
+ // Later strokes own these lanes; both refuse LOUD here (the
1021
+ // preview-scope posture — never a silent accept).
1022
+ const stateRoot = this.ctx.queue.stateRoot;
1023
+
1024
+ // own words: "By design, there is no 'non bench flow'. There is
1025
+ // ALWAYS FromStage links. THERE IS NO FILTER, NO BREAKAGE FROM
1026
+ // THIS. EVER.") ────────────────────────────────────────────────
1027
+ // A stage that takes its input from a PRIOR stage's output cannot
1028
+ // be run alone: the card arm composes ONE stage with
1029
+ // inputNames: {}, so every FromStage link would be discarded. The
1030
+ // old answer was a refusal telling the caller to run the flow
1031
+ // instead — which is the operator-facing bug this replaces: the
1032
+ // GUI's per-stage Run, the agent's card start, and any API caller
1033
+ // all hit that wall, and the bench's wires were the very thing
1034
+ // the run was FOR.
1035
+ //
1036
+ // So the door does not refuse a wired bench. IT BECOMES THE
1037
+ // BENCH RUN: the body is restaged onto the flow_inline wire with
1038
+ // the bench's own stages, and the run proceeds with the wires
1039
+ // riding as stage inputs. There is no third shape: a bench with
1040
+ // wires is a flow, whatever the caller named.
1041
+ let benchComposed = false;
1042
+ if ((selected.door === "model" || selected.door === "draft") &&
1043
+ benchDoc !== undefined) {
1044
+ const wired = benchWiring(benchDoc);
1045
+ // The DRAFT door composes unconditionally: the body names the
1046
+ // bench — pressing the bench is the meaning of the press. The
1047
+ // model door keeps its wire gate (a card Run over an unwired
1048
+ // bench stays a card run).
1049
+ if (selected.door === "draft" || wired.cross.length > 0) {
1050
+
1051
+ // behind it: there was no path that ran a WIRED bench. The
1052
+ // GUI ran cards one at a time, each its own run, so a FromStage
1053
+ // link had nowhere to ride — the wires were not refused, they
1054
+ // were DISCARDED by the shape of the run. So this door
1055
+ // composes EVERY card stage of the bench — through the SAME
1056
+ // registry walk a single card start uses, laws and all — and
1057
+ // submits ONE merged run whose stages carry their `inputs`
1058
+ // edges for the worker to link. A $spell survives into the
1059
+ // composed graph on purpose: the merge resolves it into the
1060
+ // upstream stage's output (that is what a FromStage link IS).
1061
+
1062
+ // "run sources resolve nowhere (1 dead: run-65dc3ee505ef-…/
1063
+ // gen)"). The bench run minted the id TWICE: once here, to
1064
+ // compose the stages — and again below, to register the run.
1065
+ // Every composed graph carries its own `${runId}/gen` output
1066
+ // prefix, so the second mint left every forward reference
1067
+ // naming a run that was never created; the source resolver
1068
+ // (rightly) treated them as dead sources and the run refused
1069
+ // before it registered. The id is minted ONCE, here, and both
1070
+ // the compose and the registration take it — one derivation,
1071
+ // and a wall drives the pair.
1072
+ const benchFams = {};
1073
+ const composed = await this.composeBenchStages(benchDoc, runId, benchFams);
1074
+ // the bench-composed stages' families reach the same claim
1075
+ // re-probe ledger the flow arm feeds (S-S4): the empty-ledger
1076
+ // carve-out below is the card-single path alone, never this
1077
+ // one.
1078
+ flowStageFams = benchFams;
1079
+ const rest = { ...body };
1080
+ delete rest["model"];
1081
+ delete rest["card"];
1082
+ delete rest["params"];
1083
+ body = {
1084
+ ...rest,
1085
+ flow_inline: {
1086
+
1087
+ // and add it straight back — one address, two spellings.
1088
+ id: benchDraftIdOf(String(checked.draftId).replace(BENCH_DRAFT_PREFIX_RE, "")),
1089
+ stages: composed,
1090
+ },
1091
+ };
1092
+ selected = { door: "flow_inline" };
1093
+ benchComposed = true;
1094
+ // the run's own log line says what happened — a re-route is
1095
+ // never silent (NO SILENT BEHAVIOR, the same order as the
1096
+ // spell gate below)
1097
+ console.log("[runs] the bench wires " + JSON.stringify(wired.cross) +
1098
+ " — the single-card start became the bench run (" +
1099
+ String(composed.length) + " stages composed, wires riding as stage inputs)");
1100
+ }
1101
+ }
1102
+ if (selected.door === "model") {
1103
+ // The card start arm (handleCardStart 1016-1136, second
1104
+ // move): phase-1 compose (run_id "") BEFORE registration — a
1105
+ // params refusal names its field, never a zombie slot — then
1106
+ // phase-2 with the minted id, register + sidecars + ledger,
1107
+ // pump. Every compose failure refuses with the phase-N voice
1108
+ // and registers nothing.
1109
+ const mid = String(body["model"] ?? "");
1110
+ const cards = this.ctx.cardRegistry;
1111
+ let p1;
1112
+ try {
1113
+ p1 = await cards.phase1Card(body, mid);
1114
+ }
1115
+ catch (e) {
1116
+ if (e instanceof CardArmError)
1117
+ throw toRemoteError(cardRefusal(e));
1118
+ throw e;
1119
+ }
1120
+ let composed;
1121
+ try {
1122
+ composed = await cards.phase2Card(p1, runId);
1123
+ }
1124
+ catch (e) {
1125
+ if (e instanceof CardArmError)
1126
+ throw toRemoteError(cardRefusal(e));
1127
+ throw e;
1128
+ }
1129
+ const graph = composed.graph;
1130
+ const skeleton = p1.skeleton;
1131
+
1132
+ // extermination order: NO SILENT BEHAVIOR — ever). The card
1133
+ // arm composes ONE stage and resolves NOTHING: inputNames is
1134
+ // {} by construction and the merged worker's initials ride
1135
+ // empty — so a $spell anywhere in the composed graph is a
1136
+ // PROMISE THIS DOOR CANNOT KEEP. Until now such a spell
1137
+ // passed the door and died at the merge with a stranger's
1138
+ // voice ('workflow carries $name' from rewriteSpells) — the
1139
+ // exact silent seam that ate a wired bench run (run
1140
+ // 880aaa85d928: bench wired input_images from s_0, the
1141
+ // client's Run built a single-card body, the wire vanished,
1142
+ // the spell reached the merge unresolved). THE DOOR COVERS
1143
+ // WHAT THE RUN WILL DO (the flow_inline gate's own law,
1144
+ // runsStart.ts THE SPELL GATE): refuse here, in the door's
1145
+ // voice, naming every spell.
1146
+ const spellSweep = (v, found) => {
1147
+ if (typeof v === "string") {
1148
+ if (v.startsWith("$") && v.length > 1)
1149
+ found.add(v.slice(1));
1150
+ }
1151
+ else if (Array.isArray(v)) {
1152
+ for (const x of v)
1153
+ spellSweep(x, found);
1154
+ }
1155
+ else if (typeof v === "object" && v !== null) {
1156
+ for (const x of Object.values(v)) {
1157
+ spellSweep(x, found);
1158
+ }
1159
+ }
1160
+ };
1161
+ const spells = new Set();
1162
+ spellSweep(graph, spells);
1163
+ spellSweep(body, spells);
1164
+ if (spells.size > 0) {
1165
+ throw toRemoteError(refusal(400, "params carry " +
1166
+ JSON.stringify([...spells].sort().map((n) => "$" + n)) +
1167
+ " 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"));
1168
+ }
1169
+ // THE BENCH-WIRE DISCARD GATE (same order): the bench doc this
1170
+ // run was born from may wire stage inputs (FromStage links).
1171
+ // The card arm composes ONE stage with inputNames: {} — every
1172
+ // such wire would be DISCARDED SILENTLY (the run's graph row
1173
+ // stamped input_names: {} while the bench wired input_images
1174
+ // from s_0). A wire that cannot ride refuses HERE, named —
1175
+ // never dropped.
1176
+ const wiredRows = [];
1177
+ if (benchDoc !== undefined && Array.isArray(benchDoc["stages"])) {
1178
+ for (const st of benchDoc["stages"]) {
1179
+ if (typeof st !== "object" || st === null)
1180
+ continue;
1181
+ const ins = st["inputs"];
1182
+ if (typeof ins !== "object" || ins === null || Array.isArray(ins)) {
1183
+ continue;
1184
+ }
1185
+ for (const [name, ref] of Object.entries(ins)) {
1186
+ const rr = ref;
1187
+ if (typeof rr === "object" && rr !== null &&
1188
+ typeof rr["stage"] === "string") {
1189
+ wiredRows.push(name + " <- " + String(rr["stage"]) +
1190
+ (typeof rr["output"] === "string" ? "." + String(rr["output"]) : ""));
1191
+ }
1192
+ }
1193
+ }
1194
+ }
1195
+ if (wiredRows.length > 0) {
1196
+
1197
+ // report: a bench carried input_images <- s_0.default — a
1198
+ // stage wired to ITSELF, a persisted crime from before the
1199
+ // bench door's bench/self-wire law landed). The generic
1200
+ // "no FromStage links" message hid the specific crime and
1201
+ // read as tool nonsense. Name it: a wire whose stage IS the
1202
+ // run's own stage is a CYCLE (bench/self-wire, the same law
1203
+ // the write doors hold).
1204
+ //
1205
+ // A wire naming ANOTHER stage never reaches this gate: the
1206
+ // promotion above turns every cross-wired bench into the
1207
+ // bench run before the card arm composes (a bench with wires
1208
+ // is a flow, whatever the caller named). The cross arms this
1209
+ // block once carried were provably dead code — deleted in
1210
+
1211
+ const selfWired = [];
1212
+ /* v8 ignore next -- the same benchDoc and the same stages
1213
+ * array the wired-rows walk above tested, with nothing
1214
+ * between the two that mutates either. */
1215
+ if (benchDoc !== undefined && Array.isArray(benchDoc["stages"])) {
1216
+ for (const st of benchDoc["stages"]) {
1217
+ if (typeof st !== "object" || st === null)
1218
+ continue;
1219
+ const stId = st["id"];
1220
+ const ins = st["inputs"];
1221
+ if (typeof ins !== "object" || ins === null || Array.isArray(ins))
1222
+ continue;
1223
+ for (const ref of Object.values(ins)) {
1224
+ const rr = ref;
1225
+ if (typeof rr === "object" && rr !== null && rr["stage"] === stId) {
1226
+ selfWired.push(String(stId));
1227
+ }
1228
+ }
1229
+ }
1230
+ }
1231
+ /* v8 ignore next -- this arm runs only because a wire
1232
+ * reached the census, and benchWiring (the promotion above)
1233
+ * consumes every CROSS wire into the bench run before the
1234
+ * card arm composes — so every wire the census collected is
1235
+ * the row's own, and selfWired is never empty here. */
1236
+ if (selfWired.length > 0) {
1237
+ throw toRemoteError(refusal(400, "the bench carries a SELF-WIRE (bench/self-wire): stage " +
1238
+ JSON.stringify([...new Set(selfWired)]) +
1239
+ " wires its own output into its own input — a cycle composes nothing. " +
1240
+ "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"));
1241
+ }
1242
+ }
1243
+ const cardStage = {
1244
+ id: skeleton,
1245
+
1246
+ // card over the bench doc — the draft row that declared it is
1247
+ // the doc's single stage row, and the settle mirror addresses
1248
+ // the draft row by THAT id, never by the card skeleton the
1249
+ // run row carries as `id` (the two namespaces diverge on
1250
+ // every {model:} bench run; the motivating wound
1251
+ // run-4610e1c38d75 was "edit" here vs "s_2" in the draft
1252
+ // doc). Multi-row benches compose through the bench loop,
1253
+ // which stamps each row's own id.
1254
+ benchStageId: benchStageIdOf(benchDoc, skeleton),
1255
+ // The {model:} card door's engine (the compose plane is
1256
+ // ComfyUI's — the card arm rides it by construction).
1257
+ engine: CARD_PLANE_ENGINE,
1258
+ params: {
1259
+ workflow: graph,
1260
+ output_nodes: composed.outputNodes,
1261
+ },
1262
+ outputs: composed.outputs,
1263
+ // the card compose computes the card's channels itself —
1264
+ // nothing here is an engine-table fill
1265
+ outputsDeclared: true,
1266
+ expected: {},
1267
+ outputNodes: composed.outputNodes,
1268
+ inputNames: {},
1269
+ };
1270
+ const reg = await registerCompiledRun({
1271
+ compiled: { stages: [cardStage] },
1272
+ testFlag: checked.testFlag,
1273
+ draftId: checked.draftId,
1274
+ stateRoot,
1275
+ enqueue: (row) => this.core.enqueue(row),
1276
+ // F-6(b): the admission warn computes pre-registration so
1277
+ // it rides the record AND the queued sidecar (disk rows
1278
+ // carry it after a reload).
1279
+ warnings: [
1280
+ ...benchWarnings,
1281
+ ...(await this.filmAdmissionWarnings(p1.card, body)),
1282
+ ],
1283
+ door: {
1284
+ runId,
1285
+ pipeline: pipelineOf(body),
1286
+ cardId: p1.card,
1287
+
1288
+ // the row so the pump re-runs the presence gate at claim.
1289
+ fam: p1.fam,
1290
+ // THE SNAPSHOT-COERCION LAW: the sidecar's request body
1291
+ // carries the numbers the card received (the same wire
1292
+ // family the compose seat runs), not dsh's stringly
1293
+ // encoding — the raw body above still feeds phase-1/2,
1294
+ // which own their own coercion.
1295
+ requestBody: coerceSnapshotBody(cards.defsSync().get(p1.card), body),
1296
+ // the bench snapshot rides the same law per stage: each
1297
+ // row's params coerce through its OWN card's carrier
1298
+ // (unknown cards verbatim), on a COPY — the remote's doc
1299
+ // object is never mutated.
1300
+ benchDoc: benchDoc === undefined ? undefined : {
1301
+ ...benchDoc,
1302
+ stages: Array.isArray(benchDoc["stages"])
1303
+ ? benchDoc["stages"].map((row) => row !== null && typeof row === "object" && !Array.isArray(row)
1304
+ ? {
1305
+ ...row,
1306
+ ...(typeof row["card"] === "string" &&
1307
+ typeof row["params"] === "object"
1308
+ ? {
1309
+ params: coerceSnapshotBody(cards.defsSync().get(row["card"]), row["params"]),
1310
+ }
1311
+ : {}),
1312
+ }
1313
+ : row)
1314
+ : benchDoc["stages"],
1315
+ },
1316
+ },
1317
+ });
1318
+ // THE SOURCE-ECHO REFUSAL: a dead media source refuses at the
1319
+ // door with its URL named — the run never registers.
1320
+ if ("payload" in reg)
1321
+ throw toRemoteError(reg);
1322
+ const { run } = reg;
1323
+ void run;
1324
+ if (pressKey !== undefined) {
1325
+ run.pressKey = pressKey; // the row mirror (S-S7)
1326
+ this.rememberPress(pressKey, run.runId);
1327
+ }
1328
+ this.kick();
1329
+ const summary = {
1330
+ run_id: run.runId,
1331
+ status: "queued",
1332
+ queue_position: this.core.queuePosition(run.runId),
1333
+ };
1334
+ // THE TWIN'S ANSWER (the concurrent-press cure): the summary
1335
+ // settles the reservation AFTER rememberPress holds the key —
1336
+ // a third caller replays from the press memory, never re-mints.
1337
+ this.resolvePress(pressKey, summary);
1338
+ return summary;
1339
+ }
1340
+ // The request initials this start carries (declared at this
1341
+ // scope so the registration below can carry them on the door).
1342
+ // Both flow arms fill it — the named flow shim below, and the
1343
+ // flow_inline arm that recovers the declaration from the doc's
1344
+ // registry id (the boot replay's shape).
1345
+ const requestInitials = {};
1346
+ // The FILE-kind subset (photo | glb) — the keys whose values the
1347
+ // claim-time re-probe re-judges on disk (the F5 cure): the gate
1348
+ // ran at press, minutes can pass before the merge uses the file.
1349
+ const initialFileKeys = [];
1350
+ if (selected.door === "flow") {
1351
+ // THE NAMED-FLOW SHIM (REBUILD-13; the dead door's own law):
1352
+ // the registry flow expands (from_flow links
1353
+ // resolved live) and lands as the flow_inline doc; every gate
1354
+ // after this point — structural compile, single-stage policy,
1355
+ // registration, the merged worker — runs untouched. Multi-stage
1356
+ // and card= shapes refuse at those EXISTING gates with their
1357
+ // preview_scope voices (never silent).
1358
+ const raw = body["flow"];
1359
+ const name = typeof raw === "string" ? raw : "";
1360
+ // ADMISSION BEFORE PRESENCE (the {model} arm's own order): a
1361
+ // name that cannot be a flow id is refused as a shape failure,
1362
+ // never answered as an unknown flow. Without this, `flow: 42`
1363
+ // produced "no flow named in the registry" — the offending
1364
+ // value named nowhere — and an illegal spelling got the
1365
+ // presence voice from two different doors.
1366
+ if (!FLOW_ID_RE.test(name)) {
1367
+ throw new RemoteError("runs/invalid-request",
1368
+ // The RAW value, not the coerced name: `flow: 42` must
1369
+ // read "flow id 42 …" — the empty string the coercion
1370
+ // produced named nothing, which was half the old defect.
1371
+ "flow id " + JSON.stringify(raw) + " is not a legal identifier", { loc: "flow" });
1372
+ }
1373
+ const decl = this.ctx.get("meliteFlows").get(name);
1374
+ if (decl === undefined) {
1375
+ // The door's unknown-name voice (rendered invalid_request —
1376
+ // the start-door envelope norm for bad requests).
1377
+ throw new RemoteError("runs/invalid-request", "no flow named " + name + " in the registry", { loc: "flow" });
1378
+ }
1379
+ // THE EXPANSION FOLD (round-21 flows audit F4): expansion's
1380
+ // authoring throws (dangling from_flow links, raw-workflow
1381
+ // shapes) are bare Errors — without this fold they escaped
1382
+ // the door as 500-class. They ride the door's invalid-request
1383
+ // voice with the expansion's own text, mirroring the
1384
+ // family-compose fold below.
1385
+ let expanded;
1386
+ try {
1387
+ expanded = expandRegistryFlow(decl, this.ctx.get("meliteFlows"));
1388
+ }
1389
+ catch (e) {
1390
+ throw new RemoteError("runs/invalid-request", e instanceof Error ? e.message : String(e), { loc: "stages" });
1391
+ }
1392
+ // THE FLOW PARAMS OVERRIDE DOOR (the af-move commission's press,
1393
+
1394
+ // overlaid on the expanded stages' row params, refused BEFORE
1395
+ // any run registers (the initial-gate law). Without this door
1396
+ // the template's params were final: the maker's
1397
+ // `file_format: "fbx"` rode top-level and died silently
1398
+ // (run-6cb3a8e094fc), leaving the FBX export unreachable from
1399
+ // the flow door. The overlay law is SHARED (round-21 flows
1400
+ // audit F1): applyFlowParamsOverride below, the same helper the
1401
+ // validate door rides.
1402
+ const overrideRaw = body["params"];
1403
+ if (overrideRaw !== undefined) {
1404
+ applyFlowParamsOverride(name, expanded.stages, overrideRaw, overlayDecls(this.ctx.cardRegistry), String(body["model"] ?? ""));
1405
+ const rest = { ...body };
1406
+ delete rest["params"];
1407
+ body = rest;
1408
+ }
1409
+ // THE COMPILE-TIME INITIAL GATE (REBUILD-21; the dead door's
1410
+ // law): present initials refuse BEFORE any run registers —
1411
+ // validate runs the same gate, so start can never queue what
1412
+ // validate refuses.
1413
+ const badInitial = registryInitialsError(expanded, body, {
1414
+ repoRoot: resolveRepoRoot(),
1415
+ stateRoot,
1416
+ });
1417
+
1418
+ // start-arm scope owns it: the flow door at registerCompiledRun
1419
+ // reads it after the name and flow_inline blocks close
1420
+ // (bench-composed runs ride the same door with an empty ledger).
1421
+ let flowStageFams = {};
1422
+ if (badInitial !== null) {
1423
+ throw new RemoteError("runs/invalid-request", badInitial, {
1424
+ loc: "body",
1425
+ });
1426
+ }
1427
+ // THE GATE-BLESSED INITIALS RIDE THE RUN: the worker submits
1428
+ // them to the engine merge, where every `$spell` over these
1429
+ // keys links against them — a flow whose stages spell a
1430
+ // declared initial cannot merge without this record. The
1431
+ // extractor's own shapes are the gate's ({path: …} unwraps,
1432
+ // bake_params objects stringify), so the engine sees the
1433
+ // same value the gate validated.
1434
+ const extracted = extractRequestInitials(decl, body);
1435
+ /* v8 ignore next 3 -- the compile-time gate above walks
1436
+ * expanded.initialValidators, which expandRegistryFlow carries
1437
+ * verbatim (it spreads the declaration and replaces only
1438
+ * stages), and it judges the same shapes per kind — so every
1439
+ * value this extractor would refuse was refused there already.
1440
+ * The arm is the extractor's belt for a caller that skips the
1441
+ * gate. */
1442
+ if ("refusal" in extracted) {
1443
+ throw new RemoteError("runs/invalid-request", extracted.refusal, {
1444
+ loc: "body",
1445
+ });
1446
+ }
1447
+ Object.assign(requestInitials, extracted.initials);
1448
+ for (const [k, kind] of Object.entries(decl.initialValidators)) {
1449
+ if ((kind === "photo" || kind === "glb") && k in extracted.initials && !initialFileKeys.includes(k)) {
1450
+ initialFileKeys.push(k);
1451
+ }
1452
+ }
1453
+ // THE FAMILY-ACTION STAGES COMPOSE HERE (the atom vocabulary,
1454
+ // stroke 4): a stage naming family+action composes its graph
1455
+ // from the family DECL at expansion — the wire downstream sees
1456
+ // the SAME workflow envelope a raw stage authored, so every
1457
+ // gate after this point (structural compile, the curated-lane
1458
+ // lift, registration, the merged worker) runs untouched. A
1459
+ // refusal here (unknown family/action, unadmitted param,
1460
+ // contradicting hand-write) lands BEFORE any run registers —
1461
+ // the same before-queuing law the initial gate rides.
1462
+ let composedFlow;
1463
+ try {
1464
+ // The seat read rides ctx.get, the engines precedent below:
1465
+ // an undeclared-inject property access would throw cordis's
1466
+ // reflect voice ("cannot get property 'models' without
1467
+ // inject") instead of degrading to the booted singleton.
1468
+ const seat = liveFamilySeat(this.ctx.get("models"));
1469
+ composedFlow = composeFamilyStages(expanded, seat.decls, seat.state);
1470
+ }
1471
+ catch (e) {
1472
+ /* v8 ignore next -- composeFamilyStages, liveFamilySeat and
1473
+ * declaredAction raise constructed Errors; a family build's
1474
+ * throw class is the family module's own contract (nothing
1475
+ * here owns it), so the non-Error spelling is the belt that
1476
+ * folds any bare-value throw too (round-23 audit Q6). */
1477
+ throw new RemoteError("runs/invalid-request", e instanceof Error ? e.message : String(e), { loc: "stages" });
1478
+ }
1479
+ let inlineDoc = registryFlowToInline(composedFlow);
1480
+
1481
+ // `card` on every card-bearing stage, and the compiler refuses
1482
+ // those — which is why every card flow was validate-only. The
1483
+ // card walk composes them here, so a named flow RUNS the way the
1484
+ // bench runs, and the compiler only ever sees compiled stages.
1485
+ if (inlineStagesNameCards(inlineDoc)) {
1486
+ const stageFams = {};
1487
+ inlineDoc = await this.composeRegistryFlowStages(inlineDoc, runId, stageFams);
1488
+ flowStageFams = stageFams;
1489
+ console.log("[runs] the flow " + name +
1490
+ " composes its card stages through the card plane (" +
1491
+ inlineDoc["stages"].length + " stages)");
1492
+ }
1493
+ const rest = { ...body };
1494
+ delete rest["flow"];
1495
+ body = { ...rest, flow_inline: inlineDoc };
1496
+ }
1497
+ // ONE stage schema for the whole bench (the law above): every
1498
+ // stage that reaches the compiler carries an engine, whether a
1499
+ // human, the GUI, the agent or a hand-written flow authored it.
1500
+ /* v8 ignore next 3 -- the card arm returned above, so only the
1501
+ * flow arms reach this line, and both of them just set
1502
+ * flow_inline on the body (the named flow shim and the
1503
+ * flow_inline arm that recovered it). */
1504
+ if (typeof body["flow_inline"] === "object" && body["flow_inline"] !== null) {
1505
+ const stages = body["flow_inline"]["stages"];
1506
+ if (Array.isArray(stages))
1507
+ deriveFlowCardEngines(stages);
1508
+ }
1509
+ const inline = body["flow_inline"];
1510
+ // The engines seat when mounted (stroke 53): the door consults
1511
+ // the live registry ids. Absent (fixture/wall boots) the pure
1512
+ // default ['comfyui'] governs — the pre-seam voice.
1513
+ const enginesSeat = this.ctx.get("engines");
1514
+ const knownEngines = enginesSeat !== undefined && typeof enginesSeat.ids === "function"
1515
+ ? enginesSeat.ids()
1516
+ : [CARD_PLANE_ENGINE];
1517
+
1518
+ // kind lattice (kindsOk, inside flowFromBody) is validate-only —
1519
+ // a raw pre-flight here would REFUSE real benches (bench rows
1520
+ // carry inputs without expected; validate derives the kinds from
1521
+ // the card ports BEFORE the judge runs, start would not). The
1522
+ // honest cure derives first, then judges — the roadmap row names
1523
+ // the projection requirement; a bare judge is a false refusal.
1524
+ const compiled = compileFlowInline(inline, knownEngines);
1525
+ if ("payload" in compiled)
1526
+ throw toRemoteError(compiled);
1527
+ // THE REPLAY ARM RE-EXTRACTS THE INITIALS: a queued flow run's
1528
+ // durable request body is its flow_inline doc (the shim deleted
1529
+ // the flow name), so a run that rehydrates on the next boot
1530
+ // arrives here with no flow arm to extract, and its `$spell`s
1531
+ // would die unlinkable at the engine merge. A doc that names a
1532
+ // registry flow yields its declaration and the SAME gate the
1533
+ // flow arm ran — a hand-authored doc carrying a registry id must
1534
+ // not buy itself the initial-carrier privilege while skipping
1535
+ // the traversal, extension and on-disk checks that close it. A
1536
+ // bench-composed doc's id is always "bench"-prefixed (never a
1537
+ // registry name) and a hand-authored one usually names nothing
1538
+ // registered: nothing to recover, nothing refused.
1539
+ const replayId = inline["id"];
1540
+ if (typeof replayId === "string") {
1541
+ const replayDecl = this.ctx.get("meliteFlows").get(replayId);
1542
+ if (replayDecl !== undefined) {
1543
+ const badReplayInitial = registryInitialsError(replayDecl, body, {
1544
+ repoRoot: resolveRepoRoot(),
1545
+ stateRoot,
1546
+ });
1547
+ if (badReplayInitial !== null) {
1548
+ throw new RemoteError("runs/invalid-request", badReplayInitial, {
1549
+ loc: "body",
1550
+ });
1551
+ }
1552
+ const replayExtracted = extractRequestInitials(replayDecl, body);
1553
+ /* v8 ignore next 3 -- the replay initials gate above judged
1554
+ * the same declaration's initialValidators one statement
1555
+ * earlier (a replay body is the authored body, so the values
1556
+ * are the gate-blessed ones), leaving this the extractor's
1557
+ * belt for a caller that skips the gate. */
1558
+ if ("refusal" in replayExtracted) {
1559
+ throw new RemoteError("runs/invalid-request", replayExtracted.refusal, {
1560
+ loc: "body",
1561
+ });
1562
+ }
1563
+ Object.assign(requestInitials, replayExtracted.initials);
1564
+ for (const [k, kind] of Object.entries(replayDecl.initialValidators)) {
1565
+ if ((kind === "photo" || kind === "glb") && k in replayExtracted.initials && !initialFileKeys.includes(k)) {
1566
+ initialFileKeys.push(k);
1567
+ }
1568
+ }
1569
+ }
1570
+ }
1571
+ // THE PARITY JUDGE (audits F-S4/S5 — the kinds split, closed):
1572
+ // the compiled doc judges the SAME kind lattice validate ran,
1573
+ // over the SAME wire rows the door compiled — projected, never
1574
+ // re-derived. A card= stage never reaches this judge (the
1575
+ // gateway refuses the shape before it), so the card-port halves
1576
+ // ride their own doors; what start gains is the durable doc's
1577
+ // own kind consistency — a doc hand-edited between press and
1578
+ // replay dies here, with validate's voice, before it burns a
1579
+ // run. (The card-plane reads a bare judge would need are why the
1580
+ // first cut was NAMED NOT CURED; judging the compiled rows needs
1581
+ // no card plane at all.)
1582
+ try {
1583
+ kindsOk(typeof replayId === "string" ? replayId : "flow_inline", replayJudgeRows(compiled), {}, undefined);
1584
+ }
1585
+ catch (judgeError) {
1586
+ if (judgeError instanceof FlowError) {
1587
+ throw new RemoteError("runs/invalid-request", judgeError.message, { loc: "body" });
1588
+ }
1589
+ throw judgeError;
1590
+ }
1591
+ if (compiled.stages.length !== 1) {
1592
+
1593
+ // resolved): the merged worker was ALWAYS multi-stage — the
1594
+ // engine's merge walk namespaces stages, links cross-stage
1595
+ // channels, rewrites $spells, and harvests per-stage (the
1596
+ // ROW-4 file-slot gate included); only this gateway gate held
1597
+ // the line. A HAND-AUTHORED multi-stage flow_inline stays
1598
+ // refused (unported, exactly the old voice); a doc whose id
1599
+ // names a REGISTRY flow is curated — its stages compile under
1600
+ // the registry walls and the validate one-admission walk — so
1601
+ // it drives (image-upscale: make → polish through ONE merged
1602
+ // submit).
1603
+ // THE CURATED PROOF: reaching here means compileFlowInline
1604
+ // SUCCEEDED on this inline — and its first gate is isRecord, so
1605
+ // the value is proven a non-array object. No re-checking dance
1606
+ // (a typeof/Array.isArray arm here would be dead code).
1607
+ const inlineId = inline["id"];
1608
+
1609
+ // The line this gate holds is "a hand-written multi-stage graph is
1610
+ // unported" — a doc WE composed from the bench, through the same
1611
+ // registry walk a single card start uses, is the opposite case:
1612
+ // its stages carry the registry's own graphs, its edges carry the
1613
+ // bench's own wires, and the merged worker is multi-stage by
1614
+ // construction. So the bench doc is admitted here on the same
1615
+ // footing as a curated registry flow — named, never silent.
1616
+ if (benchComposed) {
1617
+ curatedBenchLog(compiled.stages.length);
1618
+ // fall through to the registration the single-stage path uses
1619
+ }
1620
+ else {
1621
+ const curated = typeof inlineId === "string" &&
1622
+ this.ctx.get("meliteFlows").get(inlineId) !== undefined;
1623
+ if (!curated) {
1624
+ throw toRemoteError(refusePreview("this gateway serves single-stage flow_inline runs only (" +
1625
+ compiled.stages.length +
1626
+ " stages) — multi-stage graphs are unported " +
1627
+ "(curated registry flows except: name a registry flow id, " +
1628
+ "or drive {flow: '<name>'})"));
1629
+ }
1630
+ }
1631
+ }
1632
+ const reg = await registerCompiledRun({
1633
+ compiled,
1634
+ testFlag: checked.testFlag,
1635
+ draftId: checked.draftId,
1636
+ stateRoot,
1637
+ enqueue: (row) => this.core.enqueue(row),
1638
+ // the bench-read warning rides the inline arm too (audit N-S3)
1639
+ warnings: benchWarnings,
1640
+ // THE RUN ID IS AN INPUT, NOT A LABEL (the operator's live
1641
+
1642
+ // run-65dc3ee505ef-…/gen)").
1643
+ //
1644
+ // Every composed graph carries its own `${runId}/gen` output
1645
+ // prefix, so the id the stages were composed under MUST be the
1646
+
1647
+ // on the replay seam, so a normal flow_inline/bench run fell
1648
+ // through to runsStart's own mint — a DIFFERENT value — and
1649
+ // every forward reference in every composed graph then named a
1650
+ // run that was never created. The resolver (rightly) called
1651
+ // them dead sources and the run refused before it registered.
1652
+ //
1653
+ // The id rides ALWAYS. The replay arm (stroke 83) keeps its
1654
+ // meaning: the SAME id, rewritten in place, the pump picking
1655
+ // the rehydrated row up on the boot kick.
1656
+ // THE SNAPSHOT RIDES THE BENCH RUN TOO (the adversarial
1657
+
1658
+ // cardSnapshot + benchSnapshot, and this door passed neither —
1659
+ // so a Run ALL registered a run whose "restore the workflow
1660
+ // that made this" reconstructed from the LIVE bench draft,
1661
+ // which is the exact staleness the snapshot law was built to
1662
+ // kill (the bench has moved on by the time anyone restores).
1663
+ // A bench-composed run knows its own doc (read at submit) and
1664
+ // its own stage list; both ride the door verbatim.
1665
+ door: {
1666
+ runId,
1667
+ pipeline: pipelineOf(body),
1668
+ requestBody: body,
1669
+ ...(Object.keys(requestInitials).length === 0
1670
+ ? {}
1671
+ : { initials: requestInitials }),
1672
+ // THE F5 STAMP: the file-kind keys ride the row so the pump's
1673
+ // claim-time re-probe knows which initials to re-judge on disk.
1674
+ ...(initialFileKeys.length > 0 ? { initialFileKeys: [...initialFileKeys] } : {}),
1675
+ ...(benchDoc === undefined ? {} : { benchDoc }),
1676
+
1677
+ // composed card stages' families ride the row (not the stage
1678
+ // rows — extra=forbid at the wire door) for the pump's
1679
+ // claim-time gate re-run.
1680
+ ...(Object.keys(flowStageFams).length > 0 ? { stageFams: flowStageFams } : {}),
1681
+ },
1682
+ });
1683
+ // THE SOURCE-ECHO REFUSAL (same law on the inline door).
1684
+ if ("payload" in reg)
1685
+ throw toRemoteError(reg);
1686
+ const { run } = reg;
1687
+ void run;
1688
+ if (pressKey !== undefined) {
1689
+ run.pressKey = pressKey; // the row mirror (S-S7)
1690
+ this.rememberPress(pressKey, run.runId);
1691
+ }
1692
+ this.kick();
1693
+ const summary = {
1694
+ run_id: run.runId,
1695
+ status: "queued",
1696
+ queue_position: this.core.queuePosition(run.runId),
1697
+ };
1698
+ // THE TWIN'S ANSWER (the concurrent-press cure): the summary
1699
+ // settles the reservation AFTER rememberPress holds the key —
1700
+ // a third caller replays from the press memory, never re-mints.
1701
+ this.resolvePress(pressKey, summary);
1702
+ return summary;
1703
+ }
1704
+ /** The list arm (REBUILD-7): the restore-port envelope over the
1705
+ * output roots. The raw limit STRING rides from the lane (strict
1706
+ * int() semantics: underscores parse, junk refuses). The drafts
1707
+ * probe rides the drafts remote. */
1708
+ async list(rawLimit, signal, test = false) {
1709
+ signal.throwIfAborted();
1710
+ // The door's 400 text (parseIntOrNull in runsList.ts) — the runs face's invalid-request refusal.
1711
+ // ONLY this parse folds; every other failure stays loud (no absorb).
1712
+ const parsed = parseIntOrNull(rawLimit);
1713
+ if (parsed === null) {
1714
+ throw new RemoteError("runs/invalid-request", "limit must be an integer (got '" + rawLimit + "')", { loc: "query.limit", expected: "integer", got: rawLimit });
1715
+ }
1716
+ const limit = Math.max(1, Math.min(500, parsed));
1717
+ // §23 CROSS-ROOTS: the union list across the manifest (own
1718
+ // root first — own rows win collisions, every row served_from).
1719
+ return await listRunsAcross(this.ctx.queue.stateRoots, limit, async (draftId) => {
1720
+ try {
1721
+ await this.ctx.draftsRemote.get(draftId, signal);
1722
+ return true;
1723
+ }
1724
+ catch (e) {
1725
+ // a caller abort cancels the list (audit N-S4) — it never
1726
+ // folds to "draft missing"; only a genuine miss degrades
1727
+ // the row's draft_id
1728
+ signal.throwIfAborted();
1729
+ void e;
1730
+ return false;
1731
+ }
1732
+ });
1733
+ }
1734
+ /** The validate arm (REBUILD-8): the PURE compile pipeline
1735
+ * (flowFromBody → compile → pin sweep → the 200 row) over the
1736
+ * door's own bodies. The {model}/{flow} arms refuse the
1737
+ * preview refusal (their remotes are later strokes); a 4xx
1738
+ * answer folds to runs/flow-compile | runs/workflow-pin with
1739
+ * the door's payload voices; the 200 serves verbatim. */
1740
+ /** F-6(b) — THE ADMISSION MEMORY WARN (the film lane's tool
1741
+ * half of the pre-flight): a film admitted while the engine's
1742
+ * VRAM sits below the pressure line warns — the caller stamps
1743
+ * the returned warnings on the run (they ride run_status, never
1744
+ * a refusal). Any telemetry failure (config unreadable, engine
1745
+ * unreachable, stats unparseable) returns none — admission never
1746
+ * blocks on a stats read. */
1747
+ async filmAdmissionWarnings(cardId, body) {
1748
+ if (cardId !== "h3-timeline")
1749
+ return [];
1750
+ const load = filmLoadOf(body);
1751
+ if (load === null)
1752
+ return [];
1753
+ let url = "";
1754
+ try {
1755
+ const cfg = loadEndpointConfig();
1756
+ if (typeof cfg["url"] === "string")
1757
+ url = cfg["url"];
1758
+ }
1759
+ catch {
1760
+ url = "";
1761
+ }
1762
+ const warn = filmMemoryWarn(load, await fetchEngineMem(url));
1763
+ return warn === null ? [] : [warn];
1764
+ }
1765
+ async status(runId, signal, includeLog = false) {
1766
+ signal.throwIfAborted();
1767
+ const run = this.liveRun(runId);
1768
+ if (run === undefined) {
1769
+
1770
+ // lane answered "? — 0/0 stage(s)" / runs/unknown-run for runs
1771
+ // whose on-disk _flow.json held status completed + full stage
1772
+ // and artifact rows — the live map is the queue's cache, disk
1773
+ // is the durable record. A status read crossing a registry
1774
+ // reload (or a husk in-memory row) must still answer the truth
1775
+ // the run tree holds. Never fabricated: no disk row → the same
1776
+ // runs/unknown-run refusal as before.
1777
+ const disk = this.diskRunRow(runId);
1778
+ if (disk === undefined) {
1779
+
1780
+
1781
+ // names the trees it searched — the operator sees WHICH
1782
+ // roots answered, never a bare unknown. No branch: the
1783
+ // queue seat owns stateRoot on every boot (the service
1784
+ // refuses root-less — the constructor's law).
1785
+ throw new RemoteError("runs/unknown-run", "unknown run_id \"" + runId + "\" " +
1786
+ searchedVoice(this.ctx.queue.stateRoots), { runId });
1787
+ }
1788
+ return withStageReports({ ...enrichDiskRow(disk.row), from_disk: true, queue_position: 0, served_from: disk.root }, sidecarReaderFor(disk.dir));
1789
+ }
1790
+ const payload = {
1791
+ run_id: run.runId,
1792
+ status: run.status,
1793
+ // §23 CROSS-ROOTS: every row names the root that served it —
1794
+ // live rows ride the seat's own root, disk rows their find.
1795
+ served_from: this.ctx.queue.stateRoot,
1796
+
1797
+ // produced this run — the tab restores via drafts/get (the
1798
+ // draft holds the full card/engine/params stages) + per-stage
1799
+ // bench/add-stage. Additive: older consumers ignore it.
1800
+ draft_id: run.draftId,
1801
+ stages: run.stages,
1802
+ skipped_stages: [...run.skippedStages],
1803
+ // Route-relative (audit #11, proven live by the stroke-82 e2e):
1804
+ // the executor's artifacts are ABSOLUTE DISK PATHS — serving
1805
+ // them raw hands the browser strings the media route cannot
1806
+ // answer (a leading-/ path rides toRunMediaUrl verbatim). The
1807
+ // stage rows' `url` spelling is the truth: <run-id>/<rel>,
1808
+ // computed from the same outRoot the record lives under.
1809
+
1810
+ // the same doubling 023 quoted): relative() off the OUT ROOT
1811
+ // returns `<run-id>/<rel>` (the run dir rides inside), so
1812
+ // prefixing runId again served `<run-id>/<run-id>/<rel>` —
1813
+ // the receipt printed a path that exists nowhere. Relativize
1814
+ // off the RUN DIR: the join restores exactly <run-id>/<rel>.
1815
+ artifacts: [...run.artifacts].map((a) => a.startsWith("/")
1816
+ ? [run.runId, relative(join(outRootFor(this.ctx.queue.stateRoot, run.testFlag), run.runId), a)].join("/")
1817
+ : a),
1818
+ error: run.error,
1819
+ // F-6(b): admission warnings ride the row (additive — older
1820
+ // consumers ignore the key; absent means none were stamped).
1821
+ warnings: [...(run.warnings ?? [])],
1822
+ // THE COMPOSE ECHO, SERVED (the one-press/one-engine law,
1823
+
1824
+ // door served it — the face that pressed Run could not show
1825
+ // what the engine got without shell access). Additive, same
1826
+ // spelling as the sidecar; absent on non-film runs. The disk
1827
+ // fallback below spreads the sidecar row, which carries it.
1828
+ ...(run.composeEcho !== undefined ? { compose_echo: run.composeEcho } : {}),
1829
+ // THE SOURCE ECHO, SERVED (same law: the run's sources ride
1830
+ // the live row too — additive, same spelling as the sidecar).
1831
+ ...(run.sourceEcho !== undefined ? { source_echo: run.sourceEcho } : {}),
1832
+ // THE EXPORT NAME, SERVED (023's self-critique #4/#6: the
1833
+ // design lane's mint rides the live row too — additive,
1834
+ // same spelling as the sidecar; absent on non-export runs.
1835
+ // The disk fallback below spreads the sidecar row, which
1836
+ // carries it).
1837
+ ...(run.exportName !== undefined && run.exportName !== "" ? { export_name: run.exportName } : {}),
1838
+ // THE EXPORT PATH, SERVED (the export FULL PATH): the exact
1839
+ // minted file the engine reported — additive, same spelling
1840
+ // as the sidecar; the disk fallback spreads the sidecar row.
1841
+ ...(run.exportPath !== undefined && run.exportPath !== "" ? { export_path: run.exportPath } : {}),
1842
+
1843
+ // seated tap folded zero engine events before settlement — the
1844
+ // artifacts may predate the request. Additive, same spelling
1845
+ // as the sidecar; absent means voiced execution (or unknown).
1846
+ ...(run.replaySuspect === true ? { replay_suspect: true } : {}),
1847
+ // THE VARIANT, SERVED (commission 033's self-critique #5):
1848
+ // the lane the run rode — additive, same spelling as the
1849
+ // sidecar; the disk fallback spreads the sidecar row, which
1850
+ // carries it. Absent on variant-less runs.
1851
+ ...(run.variant !== undefined && run.variant !== "" ? { variant: run.variant } : {}),
1852
+
1853
+ // compact receipt's data — additive, same spelling as the
1854
+ // sidecar; the disk fallback below spreads the sidecar row,
1855
+ // which carries them.
1856
+ ...(run.loudness !== undefined ? { loudness: run.loudness } : {}),
1857
+ ...(run.voiceFreshness !== undefined ? { voice_freshness: run.voiceFreshness } : {}),
1858
+ // THE TEST FLAG, SERVED (023's self-critique #3): the
1859
+ // agent-facing receipt canonicalizes route-relative artifact
1860
+ // paths against the out root — test runs live under
1861
+ // test-output/, and the row is what names it. Additive.
1862
+ test: run.testFlag,
1863
+ queue_position: this.core.queuePosition(run.runId),
1864
+ };
1865
+ // THE TERMINAL-HUSK RECOVERY (F-5's second face): a live row that
1866
+ // is terminal (completed/failed) yet carries NO stages and NO
1867
+ // artifacts is the husk signature — the queue settled the record
1868
+ // before the executor's rows landed (or a reload raced). Disk
1869
+ // holds the rich row; serve it (marked). A genuinely-empty run
1870
+ // (queued/running with nothing yet, or truly bare) stays live —
1871
+ // only the terminal+empty+disk-richer triple defers.
1872
+ if ((run.status === "completed" || run.status === "failed") &&
1873
+ run.stages.length === 0 && run.artifacts.length === 0) {
1874
+ const disk = this.diskRunRow(runId);
1875
+ const diskStages = disk !== undefined && Array.isArray(disk.row["stages"]) ? disk.row["stages"].length : 0;
1876
+ const diskArts = disk !== undefined && Array.isArray(disk.row["artifacts"]) ? disk.row["artifacts"].length : 0;
1877
+ if (disk !== undefined && (diskStages > 0 || diskArts > 0)) {
1878
+ return withStageReports({ ...enrichDiskRow(disk.row), from_disk: true, queue_position: payload["queue_position"], served_from: disk.root }, sidecarReaderFor(disk.dir));
1879
+ }
1880
+ }
1881
+
1882
+ // a live row that is queued/running yet carries NO stage rows
1883
+ // renders "? — 0/0" at the agent — zero signal for a 20-minute
1884
+ // render, which forced the whole bash-tail poll loop. The plan
1885
+ // is already stamped at registration (graphRows: stage id +
1886
+ // engine; cardId/pipeline; createdAt) — project it, never the
1887
+ // params (a film graph is 50 KB of prompt JSON). The agent sees
1888
+ // "running · plan: 1 stage (h3-timeline) · age 754s" and polls
1889
+ // the cheap door instead of tailing logs.
1890
+ if ((run.status === "queued" || run.status === "running" ||
1891
+ run.status === "stopping") &&
1892
+ run.stages.length === 0) {
1893
+ payload["planned_stages"] = run.graphRows.map((g) => ({
1894
+ id: g.id,
1895
+ engine: g.type,
1896
+ }));
1897
+ payload["card"] = run.cardId ?? run.pipeline;
1898
+ }
1899
+
1900
+ // attempts 14/16's receipts: a long single-stage h3 render shows
1901
+ // "running — 0/1 stage(s)" for ten-plus minutes and the maker
1902
+ // cannot tell progress from stuck): every LIVE row carries
1903
+ // run_age_s, planned or staged — age is the honest liveness
1904
+ // signal the executor owns without asking the engine.
1905
+ if ((run.status === "queued" || run.status === "running" ||
1906
+ run.status === "stopping") &&
1907
+ run.createdAt > 0) {
1908
+ payload["run_age_s"] = Math.max(0, Math.round(Date.now() / 1000 - run.createdAt));
1909
+ }
1910
+ if (includeLog)
1911
+ payload["log_tail"] = runLogTail(payload);
1912
+ // THE REPORT SIDECAR MOUNT, LIVE PATH: the same decorate the
1913
+ // disk fallback serves — a rig run's validate sidecar mounts
1914
+ // whether the row answered from the live map or disk.
1915
+ return withStageReports(payload, sidecarReaderFor(join(outRootFor(this.ctx.queue.stateRoot, run.testFlag), run.runId)));
1916
+ }
1917
+ async stop(runId, signal) {
1918
+ signal.throwIfAborted();
1919
+ const run = this.liveRun(runId);
1920
+ if (run === undefined) {
1921
+ // §23 CROSS-ROOTS: the stop miss names the searched roots
1922
+ // (same law as status — a stop for a maker-owned run says
1923
+ // which trees answered; cross-process stop stays refused by
1924
+ // the unknown code, never a blind guess).
1925
+ throw new RemoteError("runs/run-unknown", "unknown run_id " + JSON.stringify(runId) + " " +
1926
+ searchedVoice(this.ctx.queue.stateRoots), { runId });
1927
+ }
1928
+ if (run.status !== "queued" && run.status !== "running" && run.status !== "stopping") {
1929
+ return { error: "cannot stop run in state " + run.status };
1930
+ }
1931
+ // THE STOPPING STAMP (stroke 83 — the state existed in the
1932
+ // union but nothing ever set it): a stop press on a LIVE run
1933
+ // moves the row to "stopping" immediately, so the status door
1934
+ // reports the truth between the press and the settle (the
1935
+ // settle's stopFlag branch overwrites with "stopped"). A
1936
+ // re-press on an already-stopping row is idempotent.
1937
+ if (run.status === "running")
1938
+ run.status = "stopping";
1939
+ run.stopFlag = true;
1940
+ notifyRunChanged(runId);
1941
+ // The interrupt rides the injected engine service when the
1942
+ // seat exists (best-effort — the flag is the authority).
1943
+ try {
1944
+ const comfy = needComfyUI(this.ctx, "runsRemote stop");
1945
+ void comfy.stopForRunDir(run.dir).catch((e) => {
1946
+ // named (audit N-S5): an interrupt outage is observable in
1947
+ // the log; the worker's stopFlag check still converges
1948
+ console.log("[estate-queue] stop interrupt failed:", e instanceof Error ? e.message : String(e));
1949
+ });
1950
+ }
1951
+ catch {
1952
+ /* no seat: the worker's stop check converges the state */
1953
+ }
1954
+ return { run_id: runId, status: "stopping" };
1955
+ }
1956
+ /** The live map (the queue seat's core registry — rich rows). */
1957
+ liveRun(runId) {
1958
+ return this.core.runs.get(runId);
1959
+ }
1960
+ /** The durable record under the run tree (F-5's fallback read):
1961
+ * the on-disk _flow.json for a run — the SAME file the maker
1962
+ * verified byte-by-byte while status answered husks. The
1963
+ * manifest roots are probed in order (own first), both
1964
+ * out-roots per root (production first, then test) since the
1965
+ * fallback may not know the row's testFlag. Unparseable/absent →
1966
+ * undefined — never a fabricated row. */
1967
+ diskRunRow(runId) {
1968
+
1969
+ // root first, then the stateRoots config extras. Own
1970
+ // writes win; the first root holding the run serves.
1971
+ for (const root of this.ctx.queue.stateRoots) {
1972
+ for (const dir of [join(root, "output", runId), join(root, "test-output", runId)]) {
1973
+ try {
1974
+ const doc = JSON.parse(readFileSync(join(dir, "_flow.json"), "utf8"));
1975
+ if (typeof doc === "object" && doc !== null && !Array.isArray(doc)) {
1976
+ const row = doc;
1977
+
1978
+ // run-level status rode out verbatim — a hand-edited or
1979
+ // foreign _flow.json served "banana" as a run status.
1980
+ // The durable boundary judges it: a status outside the
1981
+ // six-value vocabulary means the row is not ours to
1982
+ // serve, the same verdict as unparseable (undefined —
1983
+ // never a fabricated status, never a fold). The writer
1984
+ // only ever writes the six, so real sidecars pass.
1985
+ if (typeof row["status"] !== "string" || !RUN_STATUSES.has(row["status"])) {
1986
+ continue;
1987
+ }
1988
+ return { row, root, dir };
1989
+ }
1990
+ }
1991
+ catch {
1992
+ /* absent/unreadable in this root — try the next */
1993
+ }
1994
+ }
1995
+ }
1996
+ return undefined;
1997
+ }
1998
+ /** The envelope walk with the AWAITED draft probe (door order
1999
+ * preserved: the probe sits between malformed and unknown). */
2000
+
2001
+
2002
+
2003
+
2004
+
2005
+
2006
+
2007
+ presses = new Map();
2008
+
2009
+
2010
+
2011
+
2012
+
2013
+
2014
+ pendingPresses = new Map();
2015
+ /** The caller's verdict at the press gate: null when it becomes
2016
+ * the minter (its entry is registered before this returns); the
2017
+ * in-flight promise when a concurrent mint owns the key — the
2018
+ * twin awaits and answers with the SAME summary or refusal. */
2019
+ reservePress(pressKey) {
2020
+ const pending = this.pendingPresses.get(pressKey);
2021
+ if (pending !== undefined)
2022
+ return pending.promise;
2023
+ let resolve;
2024
+ let reject;
2025
+ const promise = new Promise((res, rej) => {
2026
+ resolve = res;
2027
+ reject = rej;
2028
+ });
2029
+ promise.catch(() => undefined); // a refused mint rejects the twin's await — never an unhandled rejection
2030
+ this.pendingPresses.set(pressKey, { promise, resolve, reject });
2031
+ return null;
2032
+ }
2033
+ /** The minter's summary settles the twin (no-op without a press —
2034
+ * the door's return sites serve both keyed and keyless starts). */
2035
+ resolvePress(pressKey, summary) {
2036
+ if (pressKey === undefined)
2037
+ return;
2038
+ const pending = this.pendingPresses.get(pressKey);
2039
+ if (pending !== undefined)
2040
+ pending.resolve(summary);
2041
+ }
2042
+
2043
+
2044
+
2045
+
2046
+ failPress(pressKey, error) {
2047
+ const pending = this.pendingPresses.get(pressKey);
2048
+ if (pending !== undefined)
2049
+ pending.reject(error);
2050
+ }
2051
+
2052
+
2053
+
2054
+
2055
+
2056
+
2057
+
2058
+
2059
+
2060
+
2061
+ async awaitTwin(twin, signal) {
2062
+ signal.throwIfAborted();
2063
+ return new Promise((resolve, reject) => {
2064
+ const onAbort = () => reject(signal.reason);
2065
+ signal.addEventListener("abort", onAbort, { once: true });
2066
+ twin.then((summary) => {
2067
+ signal.removeEventListener("abort", onAbort);
2068
+ resolve({ ...summary });
2069
+ }, (error) => {
2070
+ signal.removeEventListener("abort", onAbort);
2071
+ reject(error);
2072
+ });
2073
+ });
2074
+ }
2075
+ rememberPress(pressKey, runId) {
2076
+ this.presses.delete(pressKey); // refresh recency before the cap read
2077
+ this.presses.set(pressKey, runId);
2078
+ while (this.presses.size > RunsRuntimeService.PRESS_MEMORY_MAX) {
2079
+ const oldest = this.presses.keys().next();
2080
+ if (oldest.done)
2081
+ break;
2082
+ this.presses.delete(oldest.value);
2083
+ }
2084
+ }
2085
+ /** Kick the serial pump (door-verbatim guard). */
2086
+ kick() {
2087
+ // THE PUMP FENCE (audit N-S7): every hop inside self-swallows or
2088
+ // is caught per-row today — this arm is the day one escapes. A
2089
+ // stranded claim (tryDequeue pins activeId before the awaits)
2090
+ // would stall the queue until reboot with no voice; the fence
2091
+ // releases the claim and says so.
2092
+ void this.pump().catch((e) => {
2093
+ this.core.releaseActive();
2094
+ console.log("[estate-queue] pump scaffold escape — active claim released:", e instanceof Error ? e.message : String(e));
2095
+ });
2096
+ }
2097
+ /** The serial worker: claim the FIFO head, execute, settle —
2098
+ * one GPU run machine-wide, strict submit order. */
2099
+ async pump() {
2100
+ if (this.pumping)
2101
+ return;
2102
+ this.pumping = true;
2103
+ try {
2104
+ for (;;) {
2105
+ // THE TEARDOWN CLAIM GATE: a disposed fiber claims nothing
2106
+ // more — the queued rows stay queued for the next boot's
2107
+ // reconcile (their replay law), and the in-flight run rides
2108
+ // the stopFlags the dispose effect pressed.
2109
+ if (this.tearingDown)
2110
+ return;
2111
+ // The remote only ever enqueues RICH rows (RunRecord
2112
+ // extends the core's row — one object, one voice), so the
2113
+ // claim is this map's own row.
2114
+ const run = this.core.tryDequeue();
2115
+ if (run === null)
2116
+ return;
2117
+
2118
+ // while this row sat queued must not cost a full render —
2119
+ // the stop flag is otherwise read only inside runOne, after
2120
+ // the merged submit. A claimed row whose stop flag is already
2121
+ // set goes straight to stopped: settled, no engine call. The
2122
+ // claim persist still lands (stopped on disk, the replay law
2123
+ // keeps the receipt).
2124
+ if (run.stopFlag) {
2125
+ run.status = "stopped";
2126
+ await claimPersist(run);
2127
+ await this.settle(run);
2128
+ continue;
2129
+ }
2130
+
2131
+ // lane gate ran at press; weights can leave between press
2132
+ // and claim (a removal, a prune, a moved store). A claimed
2133
+
2134
+ // the same lane voice — never an unnamed engine-side death.
2135
+ // Best-effort on the seat: a lane without a primed registry
2136
+ // leaves the engine-side gate standing.
2137
+ const fams = [];
2138
+ if (typeof run.fam === "string" && run.fam !== "")
2139
+ fams.push(run.fam);
2140
+ const ledger = run.stageFams;
2141
+ if (typeof ledger === "object" && ledger !== null && !Array.isArray(ledger)) {
2142
+ for (const f of Object.values(ledger)) {
2143
+ if (typeof f === "string" && f !== "" && !fams.includes(f))
2144
+ fams.push(f);
2145
+ }
2146
+ }
2147
+ if (fams.length > 0) {
2148
+ // the gate's contract is THROW-on-miss (phase1Card's pinned
2149
+ // shape) — the catch IS the miss arm; a non-CardArmError
2150
+ // (no booted registry on this lane) leaves the engine-side
2151
+ // checkpoint load as the remaining gate.
2152
+ let laneMiss = null;
2153
+ try {
2154
+ for (const f of fams)
2155
+ lanePresenceRefusal(f);
2156
+ }
2157
+ catch (e) {
2158
+ if (e instanceof CardArmError)
2159
+ laneMiss = e;
2160
+ }
2161
+ if (laneMiss !== null) {
2162
+ run.status = "failed";
2163
+ run.error = laneMiss.message;
2164
+ for (const stage of run.stages) {
2165
+ const st = stage["status"];
2166
+ if (st === "queued" || st === "pending" || st === undefined) {
2167
+ stage["status"] = "failed";
2168
+ stage["error"] = laneMiss.message;
2169
+ }
2170
+ }
2171
+ await claimPersist(run);
2172
+ await this.settle(run);
2173
+ continue;
2174
+ }
2175
+ }
2176
+ // THE CLAIM-TIME INITIALS RE-PROBE (audit F5, the round-25
2177
+ // scout's cure): the press gate validated the file initials
2178
+ // with sync isFile, minutes before the engine merge uses
2179
+ // them — a file deleted, pruned, or lost to a crash-orphan
2180
+ // reclaim in between died engine-side, unnamed. The row's
2181
+ // initialFileKeys name the file-kind entries; the re-probe
2182
+ // judges them over the press gate's OWN candidate trees
2183
+ // (initialFileCandidates — the same set, never the wider
2184
+ // §23 manifest) and fails the row with the press text, so
2185
+ // both moments read as one door. Text and bake_params keys
2186
+ // never ride the stamp — nothing to re-probe.
2187
+ const fileKeys = run.initialFileKeys;
2188
+ if (Array.isArray(fileKeys) && fileKeys.length > 0) {
2189
+ const roots = { stateRoot: this.ctx.queue.stateRoot, repoRoot: resolveRepoRoot() };
2190
+ let initialMiss = null;
2191
+ for (const key of fileKeys) {
2192
+ if (typeof key !== "string")
2193
+ continue;
2194
+ const raw = run.initials[key];
2195
+ if (typeof raw !== "string")
2196
+ continue; // merged-worker arm owns absent/linked values
2197
+ if (!initialFileCandidates(raw.trim(), roots).some((cand) => isFile(cand))) {
2198
+ initialMiss = "initial " + JSON.stringify(key) + " is not on disk (" + raw.trim() + ")";
2199
+ break;
2200
+ }
2201
+ }
2202
+ if (initialMiss !== null) {
2203
+ run.status = "failed";
2204
+ run.error = initialMiss;
2205
+ for (const stage of run.stages) {
2206
+ const st = stage["status"];
2207
+ if (st === "queued" || st === "pending" || st === undefined) {
2208
+ stage["status"] = "failed";
2209
+ stage["error"] = initialMiss;
2210
+ }
2211
+ }
2212
+ await claimPersist(run);
2213
+ await this.settle(run);
2214
+ continue;
2215
+ }
2216
+ }
2217
+
2218
+ // 'running' lands on disk at claim time, not only at settle —
2219
+ // claimPersist (runsTypes.ts) owns the crash window it closes.
2220
+ await claimPersist(run);
2221
+ // Cache the engine seat WHILE this fiber lives — the
2222
+ // teardown effect's interrupt rides this cache (a ctx.get
2223
+ // from a dying fiber refuses). Best-effort: a claim
2224
+ // without a seat leaves the cache untouched, never fails
2225
+ // the run (the worker converges on its own errors).
2226
+ if (this.engineSeat === undefined) {
2227
+ try {
2228
+ this.engineSeat = needComfyUI(this.ctx, "runsRemote pump");
2229
+ }
2230
+ catch {
2231
+ /* no seat yet — the card-plane rigs never have one */
2232
+ }
2233
+ }
2234
+ try {
2235
+ await runOne(run, this.ctx, (r) => this.settle(r));
2236
+ }
2237
+ catch (exc) {
2238
+ // THE CLAIM-RELEASE LAW (audit R1's arm, completed
2239
+
2240
+ // escape between claim and settle — a seat lookup on a
2241
+ // dying fiber, a persist fault — left activeId held with
2242
+ // the pump exited: every later run stranded behind a
2243
+ // claim nobody owned (the commission wedge's queue
2244
+ // half). The pump settles the row failed loud itself and
2245
+ // keeps claiming: the queue may delay a run, never
2246
+ // strand it.
2247
+ const text = "run seat escape (pump settle): " + errText(exc);
2248
+ for (const stage of run.stages) {
2249
+ if (stage["status"] === "running") {
2250
+ stage["status"] = "failed";
2251
+ stage["error"] = text;
2252
+ }
2253
+ }
2254
+ run.status = "failed";
2255
+ run.error = text;
2256
+ try {
2257
+ await this.settle(run);
2258
+ }
2259
+ catch {
2260
+ /* a dying fiber refuses its own seats — settle's very
2261
+ * capture throws. Nothing is left to free HERE: the
2262
+ * claim persist already wrote 'running' on disk, the
2263
+ * fiber's in-memory claim dies with the fiber, and the
2264
+ * next boot's sweep retires the row (queueSweep's law).
2265
+ * Touching this.core would re-read the dead ctx and
2266
+ * escape the pump — the exact shape this catch closes. */
2267
+ }
2268
+ }
2269
+ }
2270
+ }
2271
+ finally {
2272
+ this.pumping = false;
2273
+ }
2274
+ }
2275
+ /** The run's engine id (stroke 53): the first stage's engine,
2276
+ * defaulting to 'comfyui' for pre-seam rows (the only engine
2277
+ * that ever was). Single-stage gateway = one engine per run. */
2278
+ /** The engine read (static delegate to the extracted plane). */
2279
+ static runEngine(run) {
2280
+ return runEngineOf(run);
2281
+ }
2282
+ /** Terminal settle (queue core row + the settle persist). */
2283
+ async settle(run) {
2284
+ // Capture the queue seat before the first await: a settle that
2285
+ // resumes after fiber dispose must not re-read the dead ctx
2286
+ // injection (the persist still completes; the bookkeeping runs
2287
+ // on the captured instance).
2288
+ const queue = this.ctx.queue;
2289
+ await settlePersist(run, queue.stateRoot);
2290
+ queue.core.releaseActive();
2291
+ queue.core.evictSettled();
2292
+
2293
+ // run-4610e1c38d75 settled while its draft row read 'running'
2294
+ // forever — the only patcher was the browser tab's poller, and
2295
+ // the push era retired it). The seat now mirrors the terminal
2296
+ // outcome into the draft row itself: a closed or wedged tab can
2297
+ // never own the row's answer. Best-effort: the RUN doc is the
2298
+ // answer of record — a mirror refusal (unknown draft, a stage id
2299
+ // the draft never had) is bookkeeping, and a live tab's own
2300
+ // patch path writes the same words anyway. The patches come
2301
+ // from settleMirrorPatches (the pure seam the walls drive);
2302
+ // telemetry never fences, so expectRev 0 is never spent.
2303
+ if (run.draftId !== "") {
2304
+ const sig = new AbortController().signal;
2305
+ for (const { stageId, patch } of settleMirrorPatches(run)) {
2306
+ try {
2307
+ await this.ctx.draftsRemote.patch(run.draftId, stageId, patch, 0, sig);
2308
+ }
2309
+ catch {
2310
+ /* the mirror is bookkeeping; the run doc answers */
2311
+ }
2312
+ }
2313
+ }
2314
+ // THE SETTLE WAKE: the change seam's contract lists the settle
2315
+ // among its emitters ("a claim, a settle, an artifacts harvest,
2316
+ // a stop press" — runsChange.ts), but this path never fired it;
2317
+ // a watcher parked on the running row never learned of the
2318
+ // terminal write. Firing after the evict so the re-read serves
2319
+ // the terminal row.
2320
+ notifyRunChanged(run.runId);
2321
+ }
2322
+ }
2323
+ /** The single-stage bench doc's DRAFT row id (the model arm's
2324
+ * identity seam): exactly one stage row with a string id → that id;
2325
+ * any other shape composes ambiguous → undefined (the mirror falls
2326
+ * back to the run row's id, the legacy coincidental path). */
2327
+ function benchStageIdOf(benchDoc, skeleton) {
2328
+ if (benchDoc === undefined)
2329
+ return undefined;
2330
+ const rows = benchDoc["stages"];
2331
+ if (!Array.isArray(rows) || rows.length !== 1)
2332
+ return undefined;
2333
+ const first = rows[0];
2334
+ const id = first?.["id"];
2335
+ return typeof id === "string" && id !== "" ? id : skeleton;
2336
+ }
2337
+ /** THE SETTLE MIRROR (pure — the walls' seam, bench-trail/runs-remote
2338
+ * W4–W8): per draft stage, the terminal outcome patch the runs seat
2339
+ * mirrors into the draft doc at settle, with no browser tab alive.
2340
+ *
2341
+ * Identity: the DRAFT row id (benchStageId, the compose's stamp) —
2342
+ * the run row's `id` may be the card skeleton's, a namespace the
2343
+ * draft doc never heard of (draft.ts's own admission). Legacy rows
2344
+ * without the stamp fall back to `id`.
2345
+ *
2346
+ * Words: the draft row's terminal vocabulary. completed→done (the
2347
+ * client's word, cards-resource tileStatusFromVerdict),
2348
+ * failed→failed, stopped→stopped; a STOPPED run's untouched
2349
+ * (queued/pending/running) stage rows mirror the run's word — the
2350
+ * queued-stop arm settles without stamping stages (the defect-hunt
2351
+ * §1 P1: the closed-tab row would read running forever).
2352
+ *
2353
+ * The result face: run_id always; the run-relative media url of the
2354
+ * stage's own output when one exists (the husk clobber's other
2355
+ * half — a bookkeeping mirror never blanks a hero it can name); the
2356
+ * error voice (stage's, else the run's) when the word is failed. */
2357
+ export function settleMirrorPatches(run) {
2358
+ const out = [];
2359
+ for (const stage of run.stages) {
2360
+ const word = stage.status === "completed" ? "done"
2361
+ : stage.status === "failed" ? "failed"
2362
+ : stage.status === "stopped" ? "stopped"
2363
+ : run.status === "stopped" ? "stopped"
2364
+ : undefined;
2365
+ if (word === undefined)
2366
+ continue;
2367
+ const stageId = typeof stage.benchStageId === "string" && stage.benchStageId !== ""
2368
+ ? stage.benchStageId
2369
+ : stage.id;
2370
+ const extras = stage;
2371
+ const relUrl = typeof extras["url"] === "string" && extras["url"] !== "" ? extras["url"] : undefined;
2372
+ const gallery = Array.isArray(extras["gallery"]) ? extras["gallery"] : [];
2373
+ const galleryName = gallery.length > 0 && typeof gallery[0]["name"] === "string" ? gallery[0]["name"] : undefined;
2374
+ const mediaUrl = relUrl !== undefined || galleryName !== undefined
2375
+ ? RUN_MEDIA_PREFIX + "/" + run.runId + "/" + (relUrl ?? galleryName)
2376
+ : undefined;
2377
+ const voice = typeof stage["error"] === "string" && stage["error"] !== ""
2378
+ ? stage["error"]
2379
+ : word === "failed" && typeof run.error === "string" ? run.error : undefined;
2380
+ out.push({
2381
+ stageId,
2382
+ patch: {
2383
+ runStatus: word,
2384
+ result: {
2385
+ run_id: run.runId,
2386
+ ...(mediaUrl !== undefined ? { url: mediaUrl } : {}),
2387
+ ...(voice !== undefined ? { error: voice } : {}),
2388
+ },
2389
+ },
2390
+ });
2391
+ }
2392
+ return out;
2393
+ }
2394
+ //# sourceMappingURL=runsRegistry.js.map