@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,667 @@
1
+ import { CARD_PLANE_ENGINE } from "@melite/contracts/benchStage";
2
+ // runsStart.ts — the start arm's pure chain, re-homed VERBATIM from
3
+ // the dead flowsRun door (REBUILD-6): the flow_inline structural
4
+ // compile (frozen texts over the admission verdicts in
5
+ // ./runsGates.ts) and the registration tail (mint + dir + the rich
6
+ // run row). Refusals keep the door's byte-pinned prose as tagged
7
+ // unions — the remote maps them to the protocol's ONE RemoteError.
8
+ //
9
+
10
+ // a scope two strokes out of date and now contradicted its own body):
11
+ // this module is the start arm's chain for EVERY run shape the runs
12
+ // service registers — {model:} card runs, {flow:} registry runs,
13
+ // {flow_inline:} inline runs, and MULTI-STAGE bench rows. The
14
+ // refusals that remain are the ones listed at their own arms: the
15
+ // compile gates (an unknown node, an undeclared input, a dead wire,
16
+ // a self-wire) and the initial gate (a missing FromStage initial).
17
+ import { mkdirSync, rmSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { FlowError } from "./runsValidateShared.js";
20
+ import { AGENT_ENGINE_ID, CRAFT_ENGINE_ID, COMFYUI_ENGINE_ID, engineIdOk, } from "@melite/engine-contract";
21
+ import { FLOW_INLINE_TOP_VOICE, INLINE_TOP_KEYS, STAGE_KEYS, checkFlowInlineTop, checkFlowStage, } from "./runsGates.js";
22
+ import { appendLedger, outRootFor, refusal, sidecarDoc, sidecarStageOf, variantOfBodies, writeJsonAtomic } from "./queue.js";
23
+ import { lifecycleInFlight } from "./lifecycleLatch.js";
24
+ import { toRemoteError } from "./runsRefusalVoices.js";
25
+ import { ENGINE_TABLE } from "./runsValidateShared.js";
26
+ import { rootsManifest } from "./rootsManifest.js";
27
+ // the envelope-refusal SSOT lives in queueSubmit.ts (beside
28
+ // walkSubmitEnvelope, the one walker the registry delegates to) —
29
+ // re-exported here so the registry's import sites stay stable
30
+ export { envelopeRefusal, unknownDraftRefusal } from "./queueSubmit.js";
31
+ // the doors twin's one home (the envelope-twin cure): the door set
32
+ // and both refusal texts ride queueSubmit's helpers
33
+ import { submitDoorsOf, ambiguousDoorsRefusal, noDoorRefusal } from "./queueSubmit.js";
34
+ import { saveBenchSnapshotStages } from "@melite/contracts/benchSnapshot";
35
+ import { collectSourceRefs, resolveSourceRefs } from "./runsSourceEcho.js";
36
+ /** One compiled stage (the rim the worker splices). */
37
+ /** THE COMPILED→WIRE PROJECTION (audits F-S4/S5 — the start-side
38
+ * parity judge consumes wire rows, the door compiles its own):
39
+ * inputNames encodes the source ("stage.output" or
40
+ * "__initial__.key") — stage ids are legal identifiers, so the
41
+ * first dot splits a stage ref exactly; only string-valued
42
+ * outputs/expected ride (the wire contract's kind map — anything
43
+ * else skips judgment, never coerced). */
44
+ const kindEntries = (m) => {
45
+ const rows = [];
46
+ for (const [name, v] of Object.entries(m)) {
47
+ if (typeof v === "string")
48
+ rows.push({ name, kind: v });
49
+ }
50
+ return rows;
51
+ };
52
+ export function compiledStageRow(st) {
53
+ return {
54
+ id: st.id,
55
+ engine: st.engine,
56
+ description: "",
57
+ params: st.params,
58
+ inputs: Object.entries(st.inputNames).map(([name, src]) => {
59
+ if (src.startsWith("__initial__.")) {
60
+ return { name, edge: { kind: "initial", key: src.slice("__initial__.".length) } };
61
+ }
62
+ const dot = src.indexOf(".");
63
+ return {
64
+ name,
65
+ edge: { kind: "stage", stage: src.slice(0, dot), output: src.slice(dot + 1) },
66
+ };
67
+ }),
68
+ outputs: kindEntries(st.outputs),
69
+ expected: kindEntries(st.expected),
70
+ card: "",
71
+ cardIo: [],
72
+ skipWhen: null,
73
+ };
74
+ }
75
+ /** THE DOC-LOCAL DERIVATION (audits F-S4/S5): validate derives a
76
+ * row's expected kinds from the card ports BEFORE the lattice runs;
77
+ * a durable doc carries no cards, so the replay judge derives from
78
+ * the doc's own declared upstream outputs — an absent expected
79
+ * takes the upstream kind, and a wire to an upstream output the doc
80
+ * never declares refuses here with the lattice's link voice
81
+ * (kindsOk's mismatch arm would fire first and name the wrong
82
+ * fact). Declared expected rows re-judge exactly as validate did.
83
+ * An edge to a stage OUTSIDE the doc (the bench lane's cross-wire —
84
+ * the worker injects those stages at compose) is not doc-derivable
85
+ * and drops out of the judged rows: the judge runs only where the
86
+ * kinds were derivable, never a false refusal on the legal wire.
87
+ * A doc with ANY filled-outputs row skips the judge wholesale: its
88
+ * real channels live in the card plane (validate + the compose own
89
+ * those verdicts), and the doc is not self-describing. */
90
+ export function replayJudgeRows(compiled) {
91
+ if (compiled.stages.some((st) => !st.outputsDeclared))
92
+ return [];
93
+ const rows = compiled.stages.map(compiledStageRow);
94
+ const docStages = new Set(rows.map((r) => r.id));
95
+ const outputsByStage = new Map(rows.map((r) => [r.id, new Map(r.outputs.map((o) => [o.name, o.kind]))]));
96
+ const judged = [];
97
+ for (const row of rows) {
98
+ const expected = new Set(row.expected.map((e) => e.name));
99
+ const inputs = [];
100
+ for (const inp of row.inputs) {
101
+ if (inp.edge.kind === "stage" && !docStages.has(inp.edge.stage)) {
102
+ // the edge is undecidable without its stage — the declared
103
+ // expected rides the same undecidability and drops with it
104
+ row.expected = row.expected.filter((e) => e.name !== inp.name);
105
+ continue;
106
+ }
107
+ inputs.push(inp);
108
+ if (inp.edge.kind !== "stage")
109
+ continue;
110
+ const upstream = outputsByStage.get(inp.edge.stage);
111
+ if (upstream === undefined)
112
+ continue;
113
+ const upstreamKind = upstream.get(inp.edge.output);
114
+ if (upstreamKind === undefined) {
115
+ throw new FlowError("flow stage " +
116
+ JSON.stringify(row.id) +
117
+ " input " +
118
+ JSON.stringify(inp.name) +
119
+ ": stage " +
120
+ JSON.stringify(inp.edge.stage) +
121
+ " has no output named " +
122
+ JSON.stringify(inp.edge.output) +
123
+ " (declared outputs: " +
124
+ JSON.stringify([...upstream.keys()].sort()) +
125
+ ")");
126
+ }
127
+ if (!expected.has(inp.name))
128
+ row.expected.push({ name: inp.name, kind: upstreamKind });
129
+ }
130
+ row.inputs = inputs;
131
+ // A declared expected whose input never wired in-doc is supplied
132
+ // by the compose plane (the card-port rows) — same
133
+ // non-self-describing class as a filled output: skip the doc.
134
+ const wired = new Set(inputs.map((i) => i.name));
135
+ if (row.expected.some((e) => !wired.has(e.name)))
136
+ return [];
137
+ judged.push(row);
138
+ }
139
+ return judged;
140
+ }
141
+ /** flow_inline structural compile — door-verbatim (structure via
142
+ * the admission verdicts, voice here; the engine policy +
143
+ * default-fills below are value-domain, not type structure).
144
+ *
145
+ * THE ENGINE GATE (stroke 53, the engine-generics seam): the
146
+ * engine id must be GRAMMATICAL (the card plane's engine or 'mcp:<server>',
147
+ * engine-contract's engineIdOk) AND known to the caller. The
148
+ * caller passes the live registry ids (the 'engines' seat when
149
+ * mounted); the default (CARD_PLANE_ENGINE) keeps every seat-less boot
150
+ * (fixtures, walls) on the pre-seam voice. */
151
+ export function compileFlowInline(inline, knownEngines = [CARD_PLANE_ENGINE]) {
152
+ const top = checkFlowInlineTop(inline);
153
+ if (top.kind === "not-object" || top.kind === "bad-stages") {
154
+ return refusal(400, FLOW_INLINE_TOP_VOICE[top.kind], "invalid_request");
155
+ }
156
+ if (top.kind === "unknown-keys") {
157
+ return refusal(400, "flow body carries unknown keys " +
158
+ JSON.stringify(top.dead) +
159
+ " — allowed: " +
160
+ JSON.stringify([...INLINE_TOP_KEYS].sort()), "invalid_request");
161
+ }
162
+ if (top.kind === "missing-id-stages") {
163
+ return refusal(400, "flow body needs at least id and stages — got keys " +
164
+ JSON.stringify(top.keys), "invalid_request");
165
+ }
166
+ const rec = top.rec;
167
+ const stages = [];
168
+ const rows = rec["stages"];
169
+ for (let i = 0; i < rows.length; i++) {
170
+ const checked = checkFlowStage(rows[i]);
171
+ if (checked.kind === "not-object") {
172
+ return refusal(400, "stage[" + i + "] must be an object", "invalid_request");
173
+ }
174
+ if (checked.kind === "unknown-fields") {
175
+ const st = checked.st;
176
+ return refusal(400, "stage[" +
177
+ i +
178
+ "] " +
179
+ JSON.stringify(String(st["id"] ?? "<no id>")) +
180
+ ": body carries unknown field(s) " +
181
+ JSON.stringify(checked.extras) +
182
+ " — the schema declares " +
183
+ JSON.stringify([...STAGE_KEYS].sort()) +
184
+ " (extra=forbid at the door)", "invalid_request");
185
+ }
186
+ if (checked.kind === "bad-id") {
187
+ const sid = String(checked.st["id"] ?? "");
188
+ return refusal(400, "stage id " + JSON.stringify(sid) + " is not a legal identifier", "invalid_request");
189
+ }
190
+ const st = checked.st;
191
+ // (the bad-id gate above refuses id-less stages — the id is a
192
+ // string here.)
193
+ const sid = st["id"];
194
+ const engine = String(st["engine"] ?? "");
195
+ if (engine === "") {
196
+ return refusal(400, "stage " + JSON.stringify(sid) + ": no engine named", "invalid_request");
197
+ }
198
+ if (engine !== CARD_PLANE_ENGINE) {
199
+ // Grammar first (drift in the id itself), then membership
200
+ // (an id the gateway cannot serve). Both refuse with the
201
+ // engine named — never a silent skip. The seat-less default
202
+ // (the card plane's engine) keeps the pre-seam refusal for foreign ids.
203
+ if (!engineIdOk(engine)) {
204
+ return refusal(400, "flow_inline stage " +
205
+ JSON.stringify(sid) +
206
+ " names engine " +
207
+ JSON.stringify(engine) +
208
+ " — engine ids are " +
209
+ COMFYUI_ENGINE_ID + ", " + CRAFT_ENGINE_ID + ", " +
210
+ AGENT_ENGINE_ID +
211
+ " or 'mcp:<server>' ([A-Za-z0-9_-]{1,32})", "invalid_request");
212
+ }
213
+ if (!knownEngines.includes(engine)) {
214
+ return refusal(400, "flow_inline stage " +
215
+ JSON.stringify(sid) +
216
+ " names engine " +
217
+ JSON.stringify(engine) +
218
+ " — this gateway serves registered engines only (" +
219
+ (knownEngines.length === 0
220
+ ? "none registered"
221
+ : knownEngines.slice().sort().join(", ")) +
222
+ ")", "preview_scope");
223
+ }
224
+ }
225
+ // No branch pruning on this gateway: skip_when is unported.
226
+ if (st["skip_when"] !== undefined && st["skip_when"] !== null) {
227
+ return refusal(400, "flow_inline stage " +
228
+ JSON.stringify(sid) +
229
+ ": skip_when is unported on this gateway", "preview_scope");
230
+ }
231
+ // (the undefined guard above fired — the ?? below is dead.)
232
+ if (st["card"] !== undefined && String(st["card"]) !== "") {
233
+ return refusal(400, "flow_inline stage " +
234
+ JSON.stringify(sid) +
235
+ ": card= stages are unported on this gateway", "preview_scope");
236
+ }
237
+ // A MALFORMED CONTAINER IS REFUSED, NOT COERCED (the coverage
238
+ // audit's HIGH finding, proven independently by two auditors).
239
+
240
+ // absent: the run registered "clean", the operator saw a
241
+ // completed run with its wiring silently gone, and
242
+ // runs-start.spec.ts ASSERTED that silence. The bench door
243
+ // refuses the same shapes (bench/bad-wire) — two seats, one
244
+ // shape, opposite judgments. The bench is right: a container that
245
+ // cannot be read is not an absent container.
246
+ for (const key of ["params", "inputs", "outputs", "expected"]) {
247
+ const raw = st[key];
248
+ if (raw === undefined)
249
+ continue;
250
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
251
+ return refusal(400, "flow_inline stage " + JSON.stringify(sid) + ": " + key +
252
+ " must be an object (got " +
253
+ (raw === null ? "null" : Array.isArray(raw) ? "array" : typeof raw) +
254
+ "); a shape that cannot be read is refused here, not dropped — a dropped " +
255
+ key + " makes the run register without it", "invalid_request");
256
+ }
257
+ }
258
+ // AND A MALFORMED BINDING inside a well-formed container, for the
259
+ // same reason: `{stage: "up"}` with no output channel is a wire
260
+ // that resolves to nothing, and dropping it is indistinguishable
261
+ // from never having wired it.
262
+ const rawInputs = st["inputs"];
263
+ for (const [name, ref] of Object.entries(rawInputs ?? {})) {
264
+ const rr = ref;
265
+ const shaped = typeof rr === "object" && rr !== null && !Array.isArray(rr);
266
+ if (shaped && (typeof rr["stage"] === "string" && typeof rr["output"] === "string"))
267
+ continue;
268
+ if (shaped && typeof rr["initial"] === "string")
269
+ continue;
270
+ return refusal(400, "flow_inline stage " + JSON.stringify(sid) + ": input " + JSON.stringify(name) +
271
+ " is neither {stage, output} nor {initial} (got " + JSON.stringify(ref) +
272
+ ") — a wire that cannot be read is refused here, not dropped", "invalid_request");
273
+ }
274
+ const params = typeof st["params"] === "object" && st["params"] !== null && !Array.isArray(st["params"])
275
+ ? st["params"]
276
+ : {};
277
+
278
+ // validate's lattice treats an EMPTY outputs map as stageless
279
+ // and judges the stage by the engine's table def (craft->image,
280
+ // agent->text); start's flat "image" bound a different kind than
281
+ // the lattice judged. One fill law, both doors: empty-or-absent
282
+ // outputs take the table's default channel.
283
+ const declaredOutputs = st["outputs"];
284
+ const outputsDeclared = typeof declaredOutputs === "object" && declaredOutputs !== null &&
285
+ !Array.isArray(declaredOutputs) &&
286
+ Object.keys(declaredOutputs).length > 0;
287
+ const outputs = outputsDeclared
288
+ ? declaredOutputs
289
+ : { default: ENGINE_TABLE[engine] !== undefined ? ENGINE_TABLE[engine].def : "image" };
290
+ const expected = typeof st["expected"] === "object" && st["expected"] !== null && !Array.isArray(st["expected"])
291
+ ? st["expected"]
292
+ : {};
293
+ const outputNodes = typeof params["output_nodes"] === "object" &&
294
+ params["output_nodes"] !== null &&
295
+ !Array.isArray(params["output_nodes"])
296
+ ? params["output_nodes"]
297
+ : {};
298
+ const inputNames = {};
299
+ const inputs = st["inputs"];
300
+ if (typeof inputs === "object" && inputs !== null && !Array.isArray(inputs)) {
301
+ for (const [name, ref] of Object.entries(inputs)) {
302
+ const rr = ref;
303
+ if (typeof rr === "object" && rr !== null && !Array.isArray(rr) &&
304
+ typeof rr["stage"] === "string" && typeof rr["output"] === "string") {
305
+ inputNames[name] = String(rr["stage"]) + "." + String(rr["output"]);
306
+ }
307
+ else {
308
+ // the binding wall above already refused every entry that
309
+ // is neither {stage, output} nor {initial} — reaching the
310
+ // else means the {initial} shape, no re-test needed
311
+ inputNames[name] = "__initial__." + String(rr["initial"]);
312
+ }
313
+ }
314
+ }
315
+
316
+ // $spell in params resolves against EXACTLY this inputNames map
317
+ // at the merge (rewriteSpells) — a spell naming no wired input
318
+
319
+ // $image1'. THE DOOR COVERS WHAT THE RUN WILL DO: refuse here,
320
+ // in the door's voice, naming the spell and the fix.
321
+ const ghosts = [];
322
+ const sweep = (v) => {
323
+ if (typeof v === "string") {
324
+ if (v.startsWith("$") && !(v.slice(1) in inputNames))
325
+ ghosts.push(v);
326
+ }
327
+ else if (Array.isArray(v)) {
328
+ for (const x of v)
329
+ sweep(x);
330
+ }
331
+ else if (typeof v === "object" && v !== null) {
332
+ for (const x of Object.values(v))
333
+ sweep(x);
334
+ }
335
+ };
336
+ sweep(params);
337
+ if (ghosts.length > 0) {
338
+ return refusal(400, "flow_inline stage " +
339
+ JSON.stringify(sid) +
340
+ ": params carry " +
341
+ JSON.stringify([...new Set(ghosts)].sort()) +
342
+ " but the stage wires no input of that name — the merge would refuse it at run time ('$name' must name a FromStage-wired input or a request initial; name it or wire it)", "invalid_request");
343
+ }
344
+ stages.push({ id: sid, engine, params, outputs, outputsDeclared, expected, outputNodes, inputNames });
345
+ }
346
+ return { stages };
347
+ }
348
+ /** The door-selection gate: exactly one of flow / flow_inline /
349
+ * model, in DOOR order for the ambiguity text (resolve_request
350
+ * 302). Returns the selected door key, or the refusal. The
351
+ * `draftBench` option admits the DRAFT DOOR: a body with no door
352
+ * key over a live bench draft (the tool's familyless bench walk
353
+ * presses {test, draft_id} alone — a model key would select the
354
+ * card arm and hit the board check), which the caller restages
355
+ * onto the wired-bench compose. */
356
+ export function selectSubmitDoor(body, opts = {}) {
357
+ const doors = submitDoorsOf(body);
358
+ if (doors.length > 1) {
359
+ return ambiguousDoorsRefusal(doors);
360
+ }
361
+ if (doors.length === 0) {
362
+ if (opts.draftBench === true)
363
+ return { door: "draft" };
364
+ return noDoorRefusal();
365
+ }
366
+ return { door: doors[0] };
367
+ }
368
+ /** The registration tail (door-verbatim): mint the id, route the
369
+ * out root on the test flag, build the rich run row. The caller
370
+ * (the remote) enqueues it on the queue core + kicks the pump.
371
+ * Returns the row and its queue position. */
372
+ export async function registerCompiledRun(args) {
373
+ const { compiled, testFlag, draftId, stateRoot, enqueue, door } = args;
374
+ // THE ONE RUN ID (see the type above): the caller's. There is no
375
+ // second producer here, and there cannot be one without failing the
376
+ // compiler.
377
+ const runId = door.runId;
378
+
379
+ // compiled stage's params are swept for source pointers BEFORE the
380
+ // run dir exists — a dead source refuses here with its URL named,
381
+ // never mid-render, and nothing registers. The roots are the
382
+ // manifest (own root first — the media server's own walk); tails
383
+ // fall through to the lane cwd, the stager's own order. The run's
384
+ // own id is exempt (the compose writes its future output path
385
+ // into the graph — a forward reference, not a source).
386
+ const roots = rootsManifest(stateRoot);
387
+ let sources;
388
+ try {
389
+ sources = resolveSourceRefs(collectSourceRefs(compiled.stages.map((s) => s.params)), roots, process.cwd(), runId);
390
+ }
391
+ catch (e) {
392
+ return refusal(400, e.message, "invalid_request", "params");
393
+ }
394
+ const dir = join(outRootFor(stateRoot, testFlag), runId);
395
+ mkdirSync(dir, { recursive: true });
396
+
397
+ // compiled stage rides the run row — one GraphRow + one RunStageRow +
398
+ // one params/outputNodes slot each, input_names carrying the
399
+ // cross-stage wiring the merged walk consumes. The single-stage
400
+ // shape is the N=1 case of this SAME loop (byte-identical row for
401
+ // the one-stage docs the gateway served before).
402
+ const createdAt = Date.now() / 1000;
403
+ const graphRows = compiled.stages.map((st) => ({
404
+ id: st.id,
405
+ type: st.engine,
406
+ input_from: [],
407
+ input_names: { ...st.inputNames },
408
+ outputs: { ...st.outputs },
409
+ params: { ...st.params },
410
+ }));
411
+ const run = {
412
+ runId,
413
+ status: "queued",
414
+ stages: compiled.stages.map((st, i) => ({
415
+ id: st.id,
416
+ ...(st.benchStageId !== undefined ? { benchStageId: st.benchStageId } : {}),
417
+ name: st.id,
418
+ index: i,
419
+ status: "pending",
420
+ engine: st.engine,
421
+ outputs: { ...st.outputs },
422
+ expected: { ...st.expected },
423
+ })),
424
+ skippedStages: [],
425
+ artifacts: [],
426
+ error: "",
427
+ draftId,
428
+ dir,
429
+ testFlag,
430
+ stopFlag: false,
431
+ params: compiled.stages.map((st) => ({ ...st.params })),
432
+ createdAt,
433
+ pipeline: "flow_inline",
434
+ graphRows,
435
+ outputNodes: compiled.stages.map((st) => ({ ...st.outputNodes })),
436
+ initials: { ...door.initials },
437
+ ...(door.initialFileKeys !== undefined && door.initialFileKeys.length > 0
438
+ ? { initialFileKeys: [...door.initialFileKeys] }
439
+ : {}),
440
+ };
441
+ run.inputNames = Object.fromEntries(compiled.stages.map((st) => [st.id, { ...st.inputNames }]));
442
+ if (args.warnings !== undefined && args.warnings.length > 0) {
443
+ run.warnings = [...args.warnings];
444
+ }
445
+ // THE DOOR IS REQUIRED (the run id is read from it above) — the
446
+ // door-undefined guards and the `?.`/`??` vestiges of the old
447
+ // optional door were dead legs, pruned with the door law. (The
448
+ // re-audit caught three survivors this comment once overclaimed
449
+ // as gone — the benchDoc gate, the benchRec read, and the
450
+
451
+ run.pipeline = door.pipeline;
452
+ if (door.cardId !== undefined)
453
+ run.cardId = door.cardId;
454
+
455
+ // gate ran at press; weights can leave between press and claim.
456
+ // The row carries the card arm's family so the pump re-probes at
457
+ // claim and fails loud with the lane voice — never an unnamed
458
+ // engine-side death. Flow stages stamp fam per stage row.
459
+ if (door.fam !== undefined && door.fam !== "")
460
+ run.fam = door.fam;
461
+ if (door.stageFams !== undefined && Object.keys(door.stageFams).length > 0) {
462
+ run.stageFams = door.stageFams;
463
+ }
464
+ // THE CARD SNAPSHOT LAW (stroke 45, the operator's wand complaint):
465
+ // _flow.json's stage faces are HOLLOW (ids/status only) — the card
466
+ // + params that actually ran were recorded nowhere, so "restore the
467
+ // workflow that made this image" could only re-read the MUTABLE
468
+ // bench draft and serve whatever it holds NOW. The card arm knows
469
+ // the exact card + body here; they ride the sidecar verbatim. The
470
+ // wand reconstructs from THIS, never from the living bench.
471
+ // THE SNAPSHOT IS NOT THE CARD ARM'S PRIVILEGE (the adversarial
472
+
473
+ // `cardId !== undefined`, which a BENCH-COMPOSED run never sets —
474
+ // so Run ALL registered a run with no snapshot at all, and the
475
+ // wand's "restore the workflow that made this" fell back to the
476
+ // LIVE bench draft, which is exactly the staleness this law was
477
+ // built to kill. The card identity and the bench identity are
478
+ // separate facts and each rides when it exists.
479
+ if (door.cardId !== undefined) {
480
+ run.cardSnapshot = {
481
+ card: door.cardId,
482
+ params: door.requestBody,
483
+ };
484
+ }
485
+ if (door.benchDoc !== undefined) {
486
+ const benchStages = Array.isArray(door.benchDoc["stages"])
487
+ ? door.benchDoc["stages"]
488
+ : undefined;
489
+ if (benchStages !== undefined && benchStages.length > 0) {
490
+
491
+ // finding): card-mode runs MINT their bench (the CARD BIRTH
492
+ // law wants a doc-backed draft) while a studio user HAND-
493
+ // COMPOSES one through melite_construct — and the snapshot
494
+ // alone could not tell them apart. The bench's OWN log head
495
+ // can: its author + kind say who wrote the bench the run was
496
+ // born from, verbatim from the domain row (never a synthesized
497
+ // label, never a guess — absent log, the key rides undefined
498
+ // and the snapshot says only what was provably read).
499
+ const benchLog = door.benchDoc?.["log"];
500
+ const head = Array.isArray(benchLog) && benchLog.length > 0 &&
501
+ typeof benchLog[0] === "object" && benchLog[0] !== null &&
502
+ !Array.isArray(benchLog[0])
503
+ ? { ...benchLog[0] }
504
+ : undefined;
505
+
506
+ // "the saving should 100% be a schemamaster contract, that
507
+ // way we know 100% if it will load again"): the writer stamps
508
+ // bench_snapshot THROUGH the shared contract in
509
+ // @melite/contracts/benchSnapshot, never raw — run memory and
510
+ // the era's self-naming model strip AT SAVE, provenance rides
511
+ // 'restored' (the admission repair law's coordinate), and a
512
+ // row that cannot load is DROPPED with a warning on the
513
+ // sidecar (visible loss, never persisted-unloadable). The
514
+ // guarantee is exact: everything saved under the contract
515
+ // parses on the load side.
516
+ const contracted = saveBenchSnapshotStages(benchStages);
517
+ if (contracted.warnings.length > 0) {
518
+ run.warnings = [
519
+ ...(run.warnings ?? []),
520
+ ...contracted.warnings.map((w) => `bench snapshot: ${w}`),
521
+ ];
522
+ }
523
+ if (contracted.stages.length > 0) {
524
+ run.benchSnapshot = {
525
+ stages: contracted.stages,
526
+ intent: typeof door.benchDoc?.["intent"] === "string"
527
+ ? door.benchDoc?.["intent"]
528
+ : "",
529
+ ...(head !== undefined ? { bench_head: head } : {}),
530
+ };
531
+ }
532
+ }
533
+ }
534
+ // R3 durable queue (submit 1317-1351): the request rides
535
+ // _request.json, the compiled document rides _flow.json,
536
+ // and run.queued in the ledger is what a restart reconciles
537
+ // against. The card door passes its body — coerced through the
538
+ // snapshot-coercion law at the door (declared numerics restored,
539
+ // BRIEF14 finding #2: the sidecar proves type integrity, the
540
+ // seam/structure evidence rides unchanged); the inline door passes
541
+ // the envelope's flow_inline doc below (same writes, same order).
542
+ const requestBody = door.requestBody;
543
+
544
+ // operator pressed carried, the engine received cut, and the run
545
+ // left NO voice saying which — the film was 15 minutes of the
546
+ // wrong seam and the post-mortem could only infer). Computed BEFORE
547
+ // the durable writes, stamped ON them: the run record + the console
548
+ // + the ledger row name the doc revision the compose read and the
549
+ // seam values the engine actually received. "What did ComfyUI get?"
550
+ // is one grep away, forever, on every run — the read-side half of
551
+ // the law (the write-side half is the client's run gate: the engine
552
+ // never composes from a doc the press has not confirmed).
553
+ const bodyRec = requestBody;
554
+ const echoCalls = Array.isArray(bodyRec?.["calls"])
555
+ ? bodyRec["calls"]
556
+ : [];
557
+ const benchRec = door.benchDoc;
558
+ const benchRev = typeof benchRec?.bench?.rev === "number" ? benchRec.bench.rev : null;
559
+ if (echoCalls.length > 0) {
560
+ const seam = echoCalls
561
+ .map((c) => (typeof c["transition"] === "string" ? c["transition"] : "carry"))
562
+ .join(",");
563
+ run.composeEcho = { seam, calls: echoCalls.length, benchRev };
564
+ console.log(`[compose] run=${runId} draft=${draftId} calls=${echoCalls.length} seam=${seam} bench_rev=${benchRev ?? "?"}`);
565
+ }
566
+ // THE SOURCE ECHO STAMP (the same law, source-side): the resolved
567
+ // files ride the record, the console, and the ledger row — "what
568
+ // created this run" is one grep away, forever. Sourceless runs
569
+ // stamp nothing.
570
+ if (sources.length > 0) {
571
+ run.sourceEcho = { refs: sources.map((s) => ({ url: s.url, file: s.file })) };
572
+ console.log(`[sources] run=${runId} draft=${draftId} refs=${sources.length} ${sources.map((s) => s.url).join(",")}`);
573
+ }
574
+ // THE VARIANT STAMP (commission 033's self-critique #5,
575
+
576
+ // customvoice) names itself at BIRTH — the 033 ledger read
577
+ // pipeline qwen3-tts-voicedesign on both a design run and a
578
+ // performing run, indistinguishable. run.params first, the exact
579
+ // submitted body (card snapshot / request body) as fallback —
580
+ // the export-name stamp's 024 lesson. Variant-less runs stamp
581
+ // nothing (the lift returns undefined; absent, never guessed).
582
+ const regVariant = variantOfBodies([...run.params, door.requestBody]);
583
+ if (regVariant !== undefined) {
584
+ run.variant = regVariant;
585
+ console.log(`[variant] run=${runId} draft=${draftId} variant=${regVariant}`);
586
+ }
587
+ await writeJsonAtomic(join(dir, "_request.json"), requestBody);
588
+ await writeJsonAtomic(join(dir, "_flow.json"), sidecarDocFor(run));
589
+
590
+ // the press read the latch five awaits ago (RunsRegistry.start's
591
+ // gate); a teardown whose guard passed on the then-empty census can
592
+ // hold it by now. The sidecar above made this run visible to the
593
+ // census, so any teardown from here on is refused by the guard —
594
+ // the refused press removes the minted dir and answers the same
595
+ // named code, having told the ledger nothing.
596
+ const heldLifecycle = lifecycleInFlight();
597
+ if (heldLifecycle !== null) {
598
+ // The unlink is best-effort: a failed removal must not replace the
599
+ // named 409 (the client would lose the retry-hint code) — but the
600
+ // leftover queued sidecar poisons the teardown guard until a sweep
601
+ // clears it, so the failure is logged loudly, never swallowed.
602
+ try {
603
+ rmSync(dir, { recursive: true, force: true });
604
+ }
605
+ catch (cleanupError) {
606
+ console.error(`[runs] refused press could not remove ${dir}:`, cleanupError);
607
+ }
608
+ throw toRemoteError(refusal(409, "refused: lifecycle " + heldLifecycle +
609
+ " in flight — retry the press when it settles (the teardown holds the run gate until it completes)", "lifecycle_inflight"));
610
+ }
611
+ if (echoCalls.length > 0) {
612
+ appendLedger(stateRoot, "run.queued", {
613
+ run_id: runId,
614
+ draft_id: draftId,
615
+ pipeline: run.pipeline,
616
+ ...(regVariant !== undefined ? { variant: regVariant } : {}),
617
+ seam: run.composeEcho?.seam,
618
+ calls: echoCalls.length,
619
+ bench_rev: benchRev,
620
+ sources: sources.length,
621
+ });
622
+ }
623
+ else {
624
+ appendLedger(stateRoot, "run.queued", {
625
+ run_id: runId,
626
+ draft_id: draftId,
627
+ pipeline: run.pipeline,
628
+ ...(regVariant !== undefined ? { variant: regVariant } : {}),
629
+ sources: sources.length,
630
+ });
631
+ }
632
+ const queuePosition = enqueue(run);
633
+ return { run, queuePosition };
634
+ }
635
+ /** The queued sidecar doc for a registered run (the queue.ts
636
+ * sidecarDoc over the row's live stage faces — the same writer
637
+ * the settle path rides). */
638
+ function sidecarDocFor(run) {
639
+ return sidecarDoc({
640
+ runId: run.runId,
641
+ status: "queued",
642
+ error: "",
643
+ stages: run.stages.map((s) => sidecarStageOf(s)),
644
+ skippedStages: [],
645
+ artifacts: [],
646
+ createdAt: run.createdAt,
647
+ testFlag: run.testFlag,
648
+ draftId: run.draftId,
649
+ pipeline: run.pipeline,
650
+ graph: run.graphRows,
651
+ cardSnapshot: run.cardSnapshot,
652
+ benchSnapshot: run.benchSnapshot,
653
+ // F-6(b): admission warnings ride the queued sidecar (disk
654
+ // rows carry them after a reload).
655
+ warnings: run.warnings,
656
+ // THE COMPOSE ECHO: what the engine received rides the queued
657
+ // sidecar too (the wand/restore reads disk, not memory).
658
+ composeEcho: run.composeEcho,
659
+ // THE SOURCE ECHO: the files that created the run ride the
660
+ // queued sidecar too.
661
+ sourceEcho: run.sourceEcho,
662
+ // THE VARIANT: the lane rides the queued sidecar too (the
663
+ // wand/restore reads disk, not memory).
664
+ variant: run.variant,
665
+ });
666
+ }
667
+ //# sourceMappingURL=runsStart.js.map