@melite/estate-queue 0.1.4-alpha → 0.2.0-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 (106) hide show
  1. package/LICENSE +561 -457
  2. package/README.md +55 -0
  3. package/lib/bench.d.ts +19 -11
  4. package/lib/bench.js +47 -57
  5. package/lib/cardsArmError.d.ts +94 -2
  6. package/lib/cardsArmError.js +34 -4
  7. package/lib/cardsCompose.d.ts +13 -1
  8. package/lib/cardsCompose.js +151 -67
  9. package/lib/cardsDangling.d.ts +2 -2
  10. package/lib/cardsDangling.js +82 -37
  11. package/lib/cardsFacts.d.ts +32 -3
  12. package/lib/cardsFacts.js +39 -1
  13. package/lib/cardsLanes.d.ts +62 -4
  14. package/lib/cardsLanes.js +407 -20
  15. package/lib/cardsLanesCopy.d.ts +21 -0
  16. package/lib/cardsLanesCopy.js +22 -0
  17. package/lib/cardsRegistry.d.ts +195 -10
  18. package/lib/cardsRegistry.js +959 -67
  19. package/lib/cardsVariant.d.ts +22 -8
  20. package/lib/cardsVariant.js +243 -52
  21. package/lib/discloseRegistry.d.ts +42 -11
  22. package/lib/discloseRegistry.js +163 -23
  23. package/lib/filmLead.js +5 -3
  24. package/lib/flowsData.d.ts +68 -13
  25. package/lib/flowsData.js +236 -107
  26. package/lib/flowsFamilyCompose.d.ts +5 -8
  27. package/lib/flowsFamilyCompose.js +25 -14
  28. package/lib/flowsParamsOverlay.d.ts +55 -0
  29. package/lib/flowsParamsOverlay.js +197 -0
  30. package/lib/flowsRegistryRows.d.ts +4 -1
  31. package/lib/flowsRegistryRows.js +325 -25
  32. package/lib/index.d.ts +1 -3
  33. package/lib/index.js +20 -5
  34. package/lib/lifecycleLatch.d.ts +16 -0
  35. package/lib/lifecycleLatch.js +42 -0
  36. package/lib/loadPlane.d.ts +3 -2
  37. package/lib/loadPlane.js +34 -8
  38. package/lib/loadRegistry.js +1 -1
  39. package/lib/manageOps.d.ts +8 -2
  40. package/lib/manageOps.js +28 -7
  41. package/lib/managePlane.d.ts +42 -1
  42. package/lib/managePlane.js +911 -101
  43. package/lib/managePreflight.d.ts +26 -0
  44. package/lib/managePreflight.js +179 -0
  45. package/lib/manageProbe.d.ts +15 -7
  46. package/lib/manageProbe.js +79 -8
  47. package/lib/manageRegistry.d.ts +42 -4
  48. package/lib/manageRegistry.js +45 -7
  49. package/lib/mediaKinds.d.ts +1 -1
  50. package/lib/mediaKinds.js +1 -1
  51. package/lib/queue.js +14 -10
  52. package/lib/queueCore.d.ts +21 -5
  53. package/lib/queueCore.js +22 -5
  54. package/lib/queueLifecycle.d.ts +0 -24
  55. package/lib/queueLifecycle.js +9 -63
  56. package/lib/queueLock.d.ts +8 -2
  57. package/lib/queueLock.js +9 -6
  58. package/lib/queueResurrect.d.ts +7 -2
  59. package/lib/queueResurrect.js +25 -6
  60. package/lib/queueSidecar.d.ts +114 -1
  61. package/lib/queueSidecar.js +178 -7
  62. package/lib/queueSubmit.d.ts +124 -10
  63. package/lib/queueSubmit.js +251 -48
  64. package/lib/queueSweep.js +13 -2
  65. package/lib/runsChange.d.ts +8 -0
  66. package/lib/runsChange.js +21 -5
  67. package/lib/runsErrorCodes.d.ts +1 -1
  68. package/lib/runsErrorCodes.js +35 -0
  69. package/lib/runsExecute.d.ts +26 -0
  70. package/lib/runsExecute.js +184 -6
  71. package/lib/runsGates.d.ts +5 -1
  72. package/lib/runsGates.js +10 -5
  73. package/lib/runsList.d.ts +43 -3
  74. package/lib/runsList.js +172 -58
  75. package/lib/runsRefusalVoices.js +101 -0
  76. package/lib/runsRegistry.d.ts +188 -12
  77. package/lib/runsRegistry.js +1233 -179
  78. package/lib/runsSourceEcho.d.ts +27 -0
  79. package/lib/runsSourceEcho.js +84 -18
  80. package/lib/runsStart.d.ts +80 -17
  81. package/lib/runsStart.js +303 -49
  82. package/lib/runsTypes.d.ts +62 -2
  83. package/lib/runsTypes.js +30 -6
  84. package/lib/runsValidateArms.js +61 -7
  85. package/lib/runsValidateServe.d.ts +2 -2
  86. package/lib/runsValidateServe.js +46 -14
  87. package/lib/runsValidateShared.d.ts +10 -1
  88. package/lib/runsValidateShared.js +14 -0
  89. package/lib/runsValidateStages.d.ts +10 -3
  90. package/lib/runsValidateStages.js +44 -12
  91. package/lib/runtimeProvision.d.ts +119 -0
  92. package/lib/runtimeProvision.js +243 -0
  93. package/lib/service.d.ts +24 -6
  94. package/lib/service.js +19 -11
  95. package/lib/skillFs.d.ts +9 -4
  96. package/lib/skillFs.js +12 -14
  97. package/lib/skillPlane.d.ts +3 -2
  98. package/lib/skillPlane.js +12 -6
  99. package/lib/skillRegistry.js +1 -1
  100. package/lib/skillRows.d.ts +4 -3
  101. package/lib/skillRows.js +21 -14
  102. package/lib/toolProjection.d.ts +1 -1
  103. package/lib/toolProjection.js +1 -1
  104. package/package.json +18 -17
  105. package/lib/runStatus.d.ts +0 -7
  106. package/lib/runStatus.js +0 -21
package/lib/runsStart.js CHANGED
@@ -14,14 +14,130 @@ import { CARD_PLANE_ENGINE } from "@melite/contracts/benchStage";
14
14
  // refusals that remain are the ones listed at their own arms: the
15
15
  // compile gates (an unknown node, an undeclared input, a dead wire,
16
16
  // a self-wire) and the initial gate (a missing FromStage initial).
17
- import { mkdirSync } from "node:fs";
17
+ import { mkdirSync, rmSync } from "node:fs";
18
18
  import { join } from "node:path";
19
- import { engineIdOk } from "@melite/engine-contract";
19
+ import { FlowError } from "./runsValidateShared.js";
20
+ import { AGENT_ENGINE_ID, CRAFT_ENGINE_ID, COMFYUI_ENGINE_ID, engineIdOk, } from "@melite/engine-contract";
20
21
  import { FLOW_INLINE_TOP_VOICE, INLINE_TOP_KEYS, STAGE_KEYS, checkFlowInlineTop, checkFlowStage, } from "./runsGates.js";
21
- import { appendLedger, outRootFor, refusal, sidecarDoc, sidecarStageOf, variantOfBodies, writeJsonAtomic } from "./queue.js";
22
+ import { appendLedger, graphReceiptFoldOf, outRootFor, refusal, sidecarDoc, sidecarStageOf, variantOfBodies, writeJsonAtomic } from "./queue.js";
23
+ import { lifecycleInFlight } from "./lifecycleLatch.js";
24
+ import { toRemoteError } from "./runsRefusalVoices.js";
25
+ import { engineDefaultOutput } from "./runsValidateShared.js";
22
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";
23
34
  import { saveBenchSnapshotStages } from "@melite/contracts/benchSnapshot";
24
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
+ }
25
141
  /** flow_inline structural compile — door-verbatim (structure via
26
142
  * the admission verdicts, voice here; the engine policy +
27
143
  * default-fills below are value-domain, not type structure).
@@ -68,7 +184,12 @@ export function compileFlowInline(inline, knownEngines = [CARD_PLANE_ENGINE]) {
68
184
  " (extra=forbid at the door)", "invalid_request");
69
185
  }
70
186
  if (checked.kind === "bad-id") {
71
- const sid = String(checked.st["id"] ?? "");
187
+ // (purge §7 P7 F-2 — the absence voice): a MISSING id must not
188
+ // render as an invented empty string (present-but-empty). Only
189
+ // the absent leg substitutes; an illegal-but-present id rides
190
+ // verbatim. Walled at
191
+ // tests/walls/ts/suites/run-door-single-resolve.spec.ts F-2.
192
+ const sid = String(checked.st["id"] ?? "<absent>");
72
193
  return refusal(400, "stage id " + JSON.stringify(sid) + " is not a legal identifier", "invalid_request");
73
194
  }
74
195
  const st = checked.st;
@@ -89,7 +210,10 @@ export function compileFlowInline(inline, knownEngines = [CARD_PLANE_ENGINE]) {
89
210
  JSON.stringify(sid) +
90
211
  " names engine " +
91
212
  JSON.stringify(engine) +
92
- " — engine ids are '" + CARD_PLANE_ENGINE + "' or 'mcp:<server>' ([A-Za-z0-9_-]{1,32})", "invalid_request");
213
+ " — engine ids are " +
214
+ COMFYUI_ENGINE_ID + ", " + CRAFT_ENGINE_ID + ", " +
215
+ AGENT_ENGINE_ID +
216
+ " or 'mcp:<server>' ([A-Za-z0-9_-]{1,32})", "invalid_request");
93
217
  }
94
218
  if (!knownEngines.includes(engine)) {
95
219
  return refusal(400, "flow_inline stage " +
@@ -155,9 +279,53 @@ export function compileFlowInline(inline, knownEngines = [CARD_PLANE_ENGINE]) {
155
279
  const params = typeof st["params"] === "object" && st["params"] !== null && !Array.isArray(st["params"])
156
280
  ? st["params"]
157
281
  : {};
158
- const outputs = typeof st["outputs"] === "object" && st["outputs"] !== null && !Array.isArray(st["outputs"])
159
- ? st["outputs"]
160
- : { default: "image" }; // the engine DEFAULT_OUTPUT fill
282
+ // THE NESTED CONTAINER rides the same law (P7 B2): params is the
283
+ // stage's own object, but params.output_nodes is the
284
+ // artifact-binding surface — a malformed value is refused here,
285
+ // not dropped into {}. Absent stays legal (the fill below).
286
+ const rawNodes = params["output_nodes"];
287
+ if (rawNodes !== undefined &&
288
+ (typeof rawNodes !== "object" || rawNodes === null || Array.isArray(rawNodes))) {
289
+ return refusal(400, "flow_inline stage " + JSON.stringify(sid) + ": params.output_nodes" +
290
+ " must be an object (got " +
291
+ (rawNodes === null ? "null" : Array.isArray(rawNodes) ? "array" : typeof rawNodes) +
292
+ "); a shape that cannot be read is refused here, not dropped — a dropped " +
293
+ "output_nodes makes the run register without it", "invalid_request");
294
+ }
295
+
296
+ // latent: one read, both doors): validate's lattice treats an
297
+ // EMPTY outputs map as stageless and judges the stage by the
298
+ // engine's table def (craft->image, agent->text) — start's old
299
+ // flat "image" bound a different kind than the lattice judged,
300
+ // by coincidence agreeing on every reachable engine. The fill
301
+ // now reads engineDefaultOutput (the lattice's own rule: mcp leg
302
+ // + table). The undefined leg is the future-split guard: the
303
+ // engine gate above admits only grammatical, registered ids, so
304
+ // no reachable engine reads it — a grammar id the table has not
305
+ // learned yet refuses HERE, in the door's voice, instead of
306
+ // validating-refuse/start-accepting.
307
+ const declaredOutputs = st["outputs"];
308
+ const outputsDeclared = typeof declaredOutputs === "object" && declaredOutputs !== null &&
309
+ !Array.isArray(declaredOutputs) &&
310
+ Object.keys(declaredOutputs).length > 0;
311
+ let outputs;
312
+ if (outputsDeclared) {
313
+ outputs = declaredOutputs;
314
+ }
315
+ else {
316
+ const kind = engineDefaultOutput(engine);
317
+ /* v8 ignore next -- the engine gate above admits only grammatical,
318
+ registered ids (all table- or mcp-leg-covered); the undefined
319
+ leg is the future-split guard, unreachable until the grammar
320
+ grows a table-unknown id. */
321
+ if (kind === undefined) {
322
+ return refusal(400, "flow_inline stage " + JSON.stringify(sid) + ": engine " +
323
+ JSON.stringify(engine) +
324
+ " has no default output kind — the engine table names no row for it" +
325
+ " (a grammar id the table has not learned yet); name it in the table", "invalid_request");
326
+ }
327
+ outputs = { default: kind };
328
+ }
161
329
  const expected = typeof st["expected"] === "object" && st["expected"] !== null && !Array.isArray(st["expected"])
162
330
  ? st["expected"]
163
331
  : {};
@@ -212,62 +380,36 @@ export function compileFlowInline(inline, knownEngines = [CARD_PLANE_ENGINE]) {
212
380
  JSON.stringify([...new Set(ghosts)].sort()) +
213
381
  " 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");
214
382
  }
215
- stages.push({ id: sid, engine, params, outputs, expected, outputNodes, inputNames });
383
+ stages.push({ id: sid, engine, params, outputs, outputsDeclared, expected, outputNodes, inputNames });
216
384
  }
217
385
  return { stages };
218
386
  }
219
387
  /** The door-selection gate: exactly one of flow / flow_inline /
220
388
  * model, in DOOR order for the ambiguity text (resolve_request
221
- * 302). Returns the selected door key, or the refusal. */
222
- export function selectSubmitDoor(body) {
223
- const doors = ["flow", "flow_inline", "model"].filter((k) => k in body);
389
+ * 302). Returns the selected door key, or the refusal. The
390
+ * `draftBench` option admits the DRAFT DOOR: a body with no door
391
+ * key over a live bench draft (the tool's familyless bench walk
392
+ * presses {test, draft_id} alone — a model key would select the
393
+ * card arm and hit the board check), which the caller restages
394
+ * onto the wired-bench compose. */
395
+ export function selectSubmitDoor(body, opts = {}) {
396
+ const doors = submitDoorsOf(body);
224
397
  if (doors.length > 1) {
225
- return refusal(400, "ambiguous request: names " +
226
- JSON.stringify(doors) +
227
- " — provide exactly one of flow, flow_inline, model", "invalid_request");
398
+ return ambiguousDoorsRefusal(doors);
228
399
  }
229
400
  if (doors.length === 0) {
230
- return refusal(400, "no flow selected: provide flow, flow_inline or model", "invalid_request");
401
+ if (opts.draftBench === true)
402
+ return { door: "draft" };
403
+ return noDoorRefusal();
231
404
  }
232
405
  return { door: doors[0] };
233
406
  }
234
- /** The envelope refusal texts (door-verbatim, for the remote's
235
- * envelope walk). Kept as a table — one voice each, like the
236
- * admission gate's static tables. */
237
- export function envelopeRefusal(kind, doc, detail) {
238
- switch (kind) {
239
- case "not-object":
240
- return refusal(400, "request body must be a JSON object", "bad_envelope", "body", "object", Array.isArray(doc) ? "array" : typeof doc);
241
- case "bad-test":
242
- return refusal(400, "test flag must be a boolean (got " +
243
- (typeof detail?.testFlag) +
244
- " " +
245
- JSON.stringify(detail?.testFlag) +
246
- ")", "bad_envelope", "test", "boolean", (typeof detail?.testFlag));
247
- case "missing-draft":
248
- return refusal(400, "draft_id is required — every run is born from an " +
249
- "action card (CARD BIRTH LAW); compose the card first: " +
250
- "POST /v1/flows/drafts, then start with its draft_id", "draft_required", "draft_id", "doc-backed draft id", "absent");
251
- case "malformed-draft":
252
- return refusal(400, "draft_id malformed (96 char cap, [A-Za-z0-9_-] only): " +
253
- JSON.stringify(detail?.draftId ?? ""), "draft_malformed", "draft_id", "[A-Za-z0-9_-]{1,96}", (detail?.draftId ?? "").slice(0, 60));
254
- }
255
- }
256
- /** The unknown-draft refusal (door-verbatim; the probe rides the
257
- * caller's drafts domain — the remote hops the ctx seat). */
258
- export function unknownDraftRefusal(draftId) {
259
- return refusal(400, "unknown draft_id " +
260
- JSON.stringify(draftId) +
261
- " — no card doc at drafts/" +
262
- draftId +
263
- ".json; compose the card first: POST /v1/flows/drafts", "draft_unknown", "draft_id", "existing card doc", draftId.slice(0, 60));
264
- }
265
407
  /** The registration tail (door-verbatim): mint the id, route the
266
408
  * out root on the test flag, build the rich run row. The caller
267
409
  * (the remote) enqueues it on the queue core + kicks the pump.
268
410
  * Returns the row and its queue position. */
269
411
  export async function registerCompiledRun(args) {
270
- const { compiled, testFlag, draftId, stateRoot, enqueue, door } = args;
412
+ const { compiled, testFlag, executeCeilMs, draftId, stateRoot, enqueue, door } = args;
271
413
  // THE ONE RUN ID (see the type above): the caller's. There is no
272
414
  // second producer here, and there cannot be one without failing the
273
415
  // compiler.
@@ -310,6 +452,7 @@ export async function registerCompiledRun(args) {
310
452
  status: "queued",
311
453
  stages: compiled.stages.map((st, i) => ({
312
454
  id: st.id,
455
+ ...(st.benchStageId !== undefined ? { benchStageId: st.benchStageId } : {}),
313
456
  name: st.id,
314
457
  index: i,
315
458
  status: "pending",
@@ -323,6 +466,7 @@ export async function registerCompiledRun(args) {
323
466
  draftId,
324
467
  dir,
325
468
  testFlag,
469
+ executeCeilMs,
326
470
  stopFlag: false,
327
471
  params: compiled.stages.map((st) => ({ ...st.params })),
328
472
  createdAt,
@@ -330,6 +474,9 @@ export async function registerCompiledRun(args) {
330
474
  graphRows,
331
475
  outputNodes: compiled.stages.map((st) => ({ ...st.outputNodes })),
332
476
  initials: { ...door.initials },
477
+ ...(door.initialFileKeys !== undefined && door.initialFileKeys.length > 0
478
+ ? { initialFileKeys: [...door.initialFileKeys] }
479
+ : {}),
333
480
  };
334
481
  run.inputNames = Object.fromEntries(compiled.stages.map((st) => [st.id, { ...st.inputNames }]));
335
482
  if (args.warnings !== undefined && args.warnings.length > 0) {
@@ -344,6 +491,16 @@ export async function registerCompiledRun(args) {
344
491
  run.pipeline = door.pipeline;
345
492
  if (door.cardId !== undefined)
346
493
  run.cardId = door.cardId;
494
+
495
+ // gate ran at press; weights can leave between press and claim.
496
+ // The row carries the card arm's family so the pump re-probes at
497
+ // claim and fails loud with the lane voice — never an unnamed
498
+ // engine-side death. Flow stages stamp fam per stage row.
499
+ if (door.fam !== undefined && door.fam !== "")
500
+ run.fam = door.fam;
501
+ if (door.stageFams !== undefined && Object.keys(door.stageFams).length > 0) {
502
+ run.stageFams = door.stageFams;
503
+ }
347
504
  // THE CARD SNAPSHOT LAW (stroke 45, the operator's wand complaint):
348
505
  // _flow.json's stage faces are HOLLOW (ids/status only) — the card
349
506
  // + params that actually ran were recorded nowhere, so "restore the
@@ -364,12 +521,38 @@ export async function registerCompiledRun(args) {
364
521
  card: door.cardId,
365
522
  params: door.requestBody,
366
523
  };
524
+ if (door.cardRecipe !== undefined)
525
+ run.cardRecipe = door.cardRecipe;
367
526
  }
368
527
  if (door.benchDoc !== undefined) {
369
528
  const benchStages = Array.isArray(door.benchDoc["stages"])
370
529
  ? door.benchDoc["stages"]
371
530
  : undefined;
372
- if (benchStages !== undefined && benchStages.length > 0) {
531
+ if (benchStages === undefined &&
532
+ "stages" in door.benchDoc &&
533
+ door.benchDoc["stages"] !== undefined) {
534
+ // THE MALFORMED-STAGES VOICE (P7 B3): a benchDoc carrying a
535
+ // stages key that is not a stage list skipped the whole
536
+ // snapshot with NO voice — restore then reconstructed from
537
+ // the LIVE bench, unvoiced. The read-failure path warns
538
+ // (runsRegistry N-S3); the malformed leg rides the same
539
+ // shape: what was skipped and what restore falls back to.
540
+ // Absent/empty stages keep their pinned silence (an empty
541
+ // bench stamps nothing; a rev-only doc carries no list) — and
542
+ // a present-but-undefined stages reads as absent: the door's
543
+ // coercion spread materializes `stages: undefined` for a
544
+ // stages-less draft, and JSON drops that key on the sidecar
545
+ // anyway, so voicing it would warn every stages-less bench
546
+ // run for the spread's own artifact.
547
+ const rawStages = door.benchDoc["stages"];
548
+ run.warnings = [
549
+ ...(run.warnings ?? []),
550
+ "bench snapshot: bench stages is not a usable stage list (got " +
551
+ (rawStages === null ? "null" : Array.isArray(rawStages) ? "array" : typeof rawStages) +
552
+ ") — only the card snapshot rode; restore reconstructs from the live bench",
553
+ ];
554
+ }
555
+ else if (benchStages !== undefined && benchStages.length > 0) {
373
556
 
374
557
  // finding): card-mode runs MINT their bench (the CARD BIRTH
375
558
  // law wants a doc-backed draft) while a studio user HAND-
@@ -467,8 +650,54 @@ export async function registerCompiledRun(args) {
467
650
  run.variant = regVariant;
468
651
  console.log(`[variant] run=${runId} draft=${draftId} variant=${regVariant}`);
469
652
  }
653
+ // THE GRAPH-RECEIPT STAMP (the silent UI-drop purge's P1 — the
654
+ // seated cure): the per-stage rows the compose ledgers folded into
655
+ // the run-level receipt — "which stated scalars did the composed
656
+ // graphs actually carry" — beside compose_echo: the run record +
657
+ // the console + the queued ledger row. EVIDENCE, never a refusal:
658
+ // a dropped key is a receipt fact (the P0 census consumes it).
659
+ // Card-composed runs ride it; inline runs carry no rows (nothing
660
+ // composed) and stamp nothing. Rows fold in COMPILED stage order
661
+ // (registration order, never ledger key order).
662
+ if (door.graphReceipts !== undefined && Object.keys(door.graphReceipts).length > 0) {
663
+ const rows = [];
664
+ for (const st of compiled.stages) {
665
+ const row = door.graphReceipts[st.id];
666
+ if (row !== undefined)
667
+ rows.push(row);
668
+ }
669
+ if (rows.length > 0) {
670
+ run.graphReceipt = graphReceiptFoldOf(rows);
671
+ const receipt = run.graphReceipt;
672
+ console.log(`[graph-receipt] run=${runId} draft=${draftId} stages=${rows.length} nodes=${receipt.nodes} ` +
673
+ `carried=${receipt.carried.length} dropped=${receipt.dropped.length} verdict=${receipt.verdict}` +
674
+ (receipt.dropped.length > 0 ? ` dropped=[${receipt.dropped.join(",")}]` : ""));
675
+ }
676
+ }
470
677
  await writeJsonAtomic(join(dir, "_request.json"), requestBody);
471
678
  await writeJsonAtomic(join(dir, "_flow.json"), sidecarDocFor(run));
679
+
680
+ // the press read the latch five awaits ago (RunsRegistry.start's
681
+ // gate); a teardown whose guard passed on the then-empty census can
682
+ // hold it by now. The sidecar above made this run visible to the
683
+ // census, so any teardown from here on is refused by the guard —
684
+ // the refused press removes the minted dir and answers the same
685
+ // named code, having told the ledger nothing.
686
+ const heldLifecycle = lifecycleInFlight();
687
+ if (heldLifecycle !== null) {
688
+ // The unlink is best-effort: a failed removal must not replace the
689
+ // named 409 (the client would lose the retry-hint code) — but the
690
+ // leftover queued sidecar poisons the teardown guard until a sweep
691
+ // clears it, so the failure is logged loudly, never swallowed.
692
+ try {
693
+ rmSync(dir, { recursive: true, force: true });
694
+ }
695
+ catch (cleanupError) {
696
+ console.error(`[runs] refused press could not remove ${dir}:`, cleanupError);
697
+ }
698
+ throw toRemoteError(refusal(409, "refused: lifecycle " + heldLifecycle +
699
+ " in flight — retry the press when it settles (the teardown holds the run gate until it completes)", "lifecycle_inflight"));
700
+ }
472
701
  if (echoCalls.length > 0) {
473
702
  appendLedger(stateRoot, "run.queued", {
474
703
  run_id: runId,
@@ -479,6 +708,18 @@ export async function registerCompiledRun(args) {
479
708
  calls: echoCalls.length,
480
709
  bench_rev: benchRev,
481
710
  sources: sources.length,
711
+ // THE GRAPH-RECEIPT RIDES THE QUEUED ROW TOO (the [graph-receipt]
712
+ // console line's durable twin — compact triad, the full receipt
713
+ // lives on the sidecar).
714
+ ...(run.graphReceipt !== undefined
715
+ ? {
716
+ graph_receipt: {
717
+ nodes: run.graphReceipt.nodes,
718
+ verdict: run.graphReceipt.verdict,
719
+ dropped: [...run.graphReceipt.dropped],
720
+ },
721
+ }
722
+ : {}),
482
723
  });
483
724
  }
484
725
  else {
@@ -488,6 +729,16 @@ export async function registerCompiledRun(args) {
488
729
  pipeline: run.pipeline,
489
730
  ...(regVariant !== undefined ? { variant: regVariant } : {}),
490
731
  sources: sources.length,
732
+ // THE GRAPH-RECEIPT RIDES THE QUEUED ROW TOO (same law).
733
+ ...(run.graphReceipt !== undefined
734
+ ? {
735
+ graph_receipt: {
736
+ nodes: run.graphReceipt.nodes,
737
+ verdict: run.graphReceipt.verdict,
738
+ dropped: [...run.graphReceipt.dropped],
739
+ },
740
+ }
741
+ : {}),
491
742
  });
492
743
  }
493
744
  const queuePosition = enqueue(run);
@@ -517,6 +768,9 @@ function sidecarDocFor(run) {
517
768
  // THE COMPOSE ECHO: what the engine received rides the queued
518
769
  // sidecar too (the wand/restore reads disk, not memory).
519
770
  composeEcho: run.composeEcho,
771
+ // THE GRAPH RECEIPT: the queue-time doc→graph evidence rides the
772
+ // queued sidecar too (same law — no card-composed run, no key).
773
+ graphReceipt: run.graphReceipt,
520
774
  // THE SOURCE ECHO: the files that created the run ride the
521
775
  // queued sidecar too.
522
776
  sourceEcho: run.sourceEcho,
@@ -1,5 +1,6 @@
1
1
  import type { EngineJson } from "@melite/comfyui-cordis";
2
- import type { GraphRow } from "./queue.js";
2
+ import type { DraftId } from "@melite/contracts/benchStage";
3
+ import type { GraphReceipt, GraphRow } from "./queue.js";
3
4
  import type { RunId } from "./queueCore.js";
4
5
  /** Stage statuses — the run worker's vocabulary (inherited from the retired oracle). */
5
6
  export type RunStatus = "queued" | "running" | "completed" | "failed" | "stopped" | "stopping";
@@ -11,6 +12,13 @@ export declare const RUN_STATUSES: ReadonlySet<string>;
11
12
  /** One stage row — key order mirrors submit's literal. */
12
13
  export interface RunStageRow {
13
14
  id: string;
15
+
16
+
17
+
18
+
19
+
20
+
21
+ benchStageId?: string;
14
22
  name: string;
15
23
  index: number;
16
24
  status: string;
@@ -34,7 +42,7 @@ export interface RunRecord {
34
42
  skippedStages: string[];
35
43
  artifacts: string[];
36
44
  error: string;
37
- draftId: string;
45
+ draftId: DraftId;
38
46
  dir: string;
39
47
  testFlag: boolean;
40
48
  stopFlag: boolean;
@@ -46,6 +54,20 @@ export interface RunRecord {
46
54
  * Empty for runs whose flow declares no initials and for a
47
55
  * failed resurrect's floor row. */
48
56
  initials: Record<string, EngineJson>;
57
+ /** THE PER-RUN EXECUTE CEILING (the F8 burn): the start body's own
58
+ * `execute_ceil_ms` overrides the queue config for THIS run —
59
+ * `<= 0` disables the fuse (a whole-film window loop outlasts the
60
+ * deployment default; a 30-min kill stranded finished windows
61
+ * engine-side). Absent = the queue config's value. */
62
+ executeCeilMs?: number;
63
+ /** The FILE-kind subset of initials' keys (photo | glb — the
64
+ * kinds whose values must exist on disk), stamped beside
65
+ * initials so the claim-time re-probe knows which entries to
66
+ * re-judge without re-deriving kinds (the stageFams ledger
67
+ * law: the row carries the judgment's input, not a new
68
+ * lookup). Absent = nothing to re-probe (no file initials, a
69
+ * card run, or a floor row). */
70
+ initialFileKeys?: string[];
49
71
  /** The settle persist (R3 mirror): registration stamps these so
50
72
  * settle can rewrite the sidecar + ledger row. createdAt is
51
73
  * epoch seconds. */
@@ -58,11 +80,26 @@ export interface RunRecord {
58
80
  /** The card door's id (stamped at registration; inline runs leave
59
81
  * it absent — never a guessed card). */
60
82
  cardId?: string;
83
+
84
+
85
+
86
+
87
+
88
+ pressKey?: string;
61
89
  /** THE CARD SNAPSHOT (stroke 45): the exact card + body that ran
62
90
  * ({card, params}) — the wand restores from this, never from the
63
91
  * living bench. Stamped at registration, carried through settle
64
92
  * (the settle rewrite must not wipe it). */
65
93
  cardSnapshot?: unknown;
94
+
95
+
96
+
97
+
98
+
99
+ cardRecipe?: {
100
+ card: string;
101
+ params: Record<string, unknown>;
102
+ };
66
103
  /** THE BENCH SNAPSHOT (stroke 45d): the full workflow as it stood
67
104
  * at Run press ({stages, intent}) — same carry law as the card
68
105
  * snapshot. */
@@ -77,6 +114,20 @@ export interface RunRecord {
77
114
 
78
115
 
79
116
 
117
+ replaySuspect?: boolean;
118
+
119
+
120
+
121
+ fam?: string;
122
+ /** The flow arm's {stageId: fam} ledger (the claim-time presence
123
+ * re-probe reads it beside fam). */
124
+ stageFams?: Record<string, string>;
125
+
126
+
127
+
128
+
129
+
130
+
80
131
 
81
132
  exportName?: string;
82
133
 
@@ -130,6 +181,15 @@ export interface RunRecord {
130
181
  calls: number;
131
182
  benchRev: number | null;
132
183
  };
184
+ /** THE SERVED-GRAPH RECEIPT (the silent UI-drop purge's P1):
185
+ * the queue-time doc→graph evidence — which doc scalars the
186
+ * composed graph carries, which it dropped, per stage. Stamped
187
+ * at registration; the claim and settle sidecar rewrites carry
188
+ * it; the execute outcome fold stamps the engine's prompt_id.
189
+ * Card-composed runs stamp a rollup; inline runs stamp nothing
190
+ * (the receipt judges the card compose, never the verbatim
191
+ * inline envelope). */
192
+ graphReceipt?: GraphReceipt;
133
193
 
134
194
 
135
195
 
package/lib/runsTypes.js CHANGED
@@ -56,12 +56,14 @@ export function errText(err) {
56
56
  export async function settlePersist(run, stateRoot) {
57
57
  // THE EXPORT-NAME STAMP (023's self-critique #4/#6): a
58
58
  // design/export lane's voice_name rides the submitted body — lift
59
- // the first non-empty one onto the row so the receipt names the
60
- // mint (the preview flac carries the design sample; the .qvoice
61
- // is the deliverable and rides no artifact list). The compiled
62
- // stage params are engine-shaped (the compose may consume card
63
- // keys into the workflow — 024 proved voice_name missing there),
64
- // so the card snapshot (the exact submitted body) is the fallback.
59
+ // THE EXPORT-NAME STAMP (023's self-critique #4/#6, re-stated
60
+
61
+ // Design mod's popup states the save name; unstated runs mint
62
+ // it): a stated voice_name wins here; the mint-named file lifts
63
+ // below. The params loop also keeps pre-refinement runs replayed
64
+ // through this settle honest (their snapshots carry whatever the
65
+ // door admitted at their time; a replay must not lose its
66
+ // receipt).
65
67
  let exportName;
66
68
  const bodies = [...run.params];
67
69
  const snap = run.cardSnapshot;
@@ -103,6 +105,17 @@ export async function settlePersist(run, stateRoot) {
103
105
  break;
104
106
  }
105
107
  }
108
+ // THE MINT NAMES ITSELF (the qvoice boolean law, operator
109
+
110
+ // the minted file's stem (voice-<runId>.qvoice → voice-<runId>).
111
+ if (exportName === undefined && exportPath !== undefined) {
112
+ const base = exportPath.split("/").pop() ?? "";
113
+ const stem = base.endsWith(".qvoice") ? base.slice(0, -".qvoice".length) : base;
114
+ if (stem !== "") {
115
+ exportName = stem;
116
+ run.exportName = exportName;
117
+ }
118
+ }
106
119
 
107
120
  // reading and the voice-mint receipt off the stage result_outputs
108
121
  // — same law as the export path (the engine's harvest carries
@@ -141,6 +154,7 @@ export async function settlePersist(run, stateRoot) {
141
154
  variant,
142
155
  loudness: run.loudness,
143
156
  voiceFreshness: run.voiceFreshness,
157
+ replaySuspect: run.replaySuspect,
144
158
  }));
145
159
  }
146
160
  catch {
@@ -154,6 +168,9 @@ export async function settlePersist(run, stateRoot) {
154
168
  // queued row named it at birth; the terminal row names it at
155
169
  // rest — one grep tells design from performing, state to state.
156
170
  ...(variant !== undefined ? { variant } : {}),
171
+ // THE REPLAY VERDICT RIDES IT TOO (D11): one grep tells a
172
+ // replayed film from an executed one, state to state.
173
+ ...(run.replaySuspect === true ? { replay_suspect: true } : {}),
157
174
  });
158
175
 
159
176
 
@@ -185,6 +202,7 @@ function sidecarFacesOf(run) {
185
202
  // re-renders the document from the row — the snapshots stamped
186
203
  // at registration ride along, never wiped.
187
204
  cardSnapshot: run.cardSnapshot,
205
+ cardRecipe: run.cardRecipe,
188
206
  benchSnapshot: run.benchSnapshot,
189
207
  // F-6(b): the admission warnings ride every rewrite too (a disk
190
208
  // row keeps what the live row warned).
@@ -192,9 +210,15 @@ function sidecarFacesOf(run) {
192
210
  // THE COMPOSE ECHO rides every rewrite too (a disk row keeps
193
211
  // what the engine received at start).
194
212
  composeEcho: run.composeEcho,
213
+ // THE SERVED-GRAPH RECEIPT rides every rewrite too (a disk row
214
+ // keeps the queue-time evidence — ordered beside the echo).
215
+ graphReceipt: run.graphReceipt,
195
216
  // THE SOURCE ECHO rides every rewrite too (a disk row keeps the
196
217
  // files that created the run).
197
218
  sourceEcho: run.sourceEcho,
219
+ // THE REPLAY VERDICT rides every rewrite too (D11 — a disk row
220
+ // keeps what the executor's tap witnessed).
221
+ replaySuspect: run.replaySuspect,
198
222
  };
199
223
  }
200
224