@melite/estate-queue 0.2.0-alpha → 0.2.3-rc.4

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 (87) hide show
  1. package/README.md +0 -5
  2. package/lib/bench.js +30 -3
  3. package/lib/cardsCompose.d.ts +31 -0
  4. package/lib/cardsCompose.js +65 -1
  5. package/lib/cardsDangling.js +17 -7
  6. package/lib/cardsDroppable.d.ts +11 -0
  7. package/lib/cardsDroppable.js +50 -0
  8. package/lib/cardsFacts.d.ts +37 -0
  9. package/lib/cardsFacts.js +47 -1
  10. package/lib/cardsLanes.d.ts +18 -0
  11. package/lib/cardsLanes.js +2 -1
  12. package/lib/cardsRegistry.d.ts +12 -20
  13. package/lib/cardsRegistry.js +288 -96
  14. package/lib/discloseRegistry.d.ts +5 -0
  15. package/lib/discloseRegistry.js +3 -3
  16. package/lib/filmLead.js +9 -1
  17. package/lib/filmMemoryWarn.js +1 -0
  18. package/lib/flowsData.d.ts +110 -21
  19. package/lib/flowsData.js +201 -23
  20. package/lib/flowsFamilyCompose.js +1 -0
  21. package/lib/flowsParamsOverlay.d.ts +8 -1
  22. package/lib/flowsParamsOverlay.js +47 -2
  23. package/lib/flowsRegistryRows.d.ts +0 -4
  24. package/lib/flowsRegistryRows.js +177 -371
  25. package/lib/index.d.ts +0 -1
  26. package/lib/index.js +0 -4
  27. package/lib/ledgerTail.js +1 -0
  28. package/lib/loadPlane.d.ts +46 -4
  29. package/lib/loadPlane.js +109 -7
  30. package/lib/loadRegistry.js +9 -2
  31. package/lib/managePlane.d.ts +5 -0
  32. package/lib/managePlane.js +412 -51
  33. package/lib/managePreflight.js +38 -6
  34. package/lib/manageProbe.d.ts +35 -0
  35. package/lib/manageProbe.js +141 -2
  36. package/lib/manageRegistry.d.ts +10 -0
  37. package/lib/manageRegistry.js +7 -1
  38. package/lib/managerRail.js +1 -0
  39. package/lib/queueCore.js +3 -1
  40. package/lib/queueLock.js +22 -10
  41. package/lib/queueResurrect.d.ts +0 -3
  42. package/lib/queueResurrect.js +5 -3
  43. package/lib/queueRetry.d.ts +12 -10
  44. package/lib/queueRetry.js +2 -4
  45. package/lib/queueSidecar.d.ts +36 -1
  46. package/lib/queueSidecar.js +30 -2
  47. package/lib/queueSubmit.d.ts +4 -1
  48. package/lib/queueSubmit.js +28 -5
  49. package/lib/queueSweep.d.ts +38 -11
  50. package/lib/queueSweep.js +73 -16
  51. package/lib/runsChange.d.ts +5 -4
  52. package/lib/runsExecute.d.ts +16 -1
  53. package/lib/runsExecute.js +102 -50
  54. package/lib/runsGates.d.ts +11 -3
  55. package/lib/runsGates.js +12 -3
  56. package/lib/runsList.d.ts +59 -3
  57. package/lib/runsList.js +228 -36
  58. package/lib/runsRegistry.d.ts +87 -6
  59. package/lib/runsRegistry.js +664 -98
  60. package/lib/runsSourceEcho.js +9 -3
  61. package/lib/runsStart.d.ts +6 -4
  62. package/lib/runsStart.js +32 -25
  63. package/lib/runsTypes.d.ts +54 -1
  64. package/lib/runsTypes.js +82 -3
  65. package/lib/runsValidate.d.ts +1 -0
  66. package/lib/runsValidate.js +5 -0
  67. package/lib/runsValidateArms.js +48 -2
  68. package/lib/runsValidateServe.js +15 -12
  69. package/lib/runsValidateShared.d.ts +8 -10
  70. package/lib/runsValidateShared.js +41 -15
  71. package/lib/runsValidateStages.d.ts +1 -1
  72. package/lib/runsValidateStages.js +90 -50
  73. package/lib/runtimeProvision.js +10 -2
  74. package/lib/skillAuthored.d.ts +50 -0
  75. package/lib/skillAuthored.js +178 -0
  76. package/lib/skillFs.js +3 -0
  77. package/lib/skillPlane.d.ts +40 -2
  78. package/lib/skillPlane.js +63 -13
  79. package/lib/skillRegistry.d.ts +24 -1
  80. package/lib/skillRegistry.js +69 -5
  81. package/lib/skillRows.d.ts +13 -3
  82. package/lib/skillRows.js +52 -9
  83. package/lib/vocab.d.ts +29 -0
  84. package/lib/vocab.js +78 -0
  85. package/package.json +24 -14
  86. package/lib/resurrect.d.ts +0 -6
  87. package/lib/resurrect.js +0 -18
@@ -11,7 +11,7 @@ import { isEstateSidecarName, mediaKindOf } from "./mediaKinds.js";
11
11
  // RemoteError with the runs/* codes declared HERE (the producing
12
12
  // package, next to the throws).
13
13
  import { CARD_PLANE_ENGINE, RUN_MEDIA_PREFIX } from "@melite/contracts/benchStage";
14
- import { join, relative } from "node:path";
14
+ import { isAbsolute, join, relative, sep } from "node:path";
15
15
  import { Service } from "@deepseek-ai/cordis";
16
16
  import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
17
17
  import { stageEngineOf } from "@melite/contracts/benchStage";
@@ -19,7 +19,9 @@ import { draftIdOf } from "@melite/contracts/benchStage";
19
19
  import { benchResultDefects } from "@melite/contracts/benchResult";
20
20
  import { remoteErrorOf } from "@deepseek-ai/dsh-typert-protocol";
21
21
  import { needComfyUI } from "@melite/comfyui-cordis";
22
+ import { STAGE_RESERVED_PARAMS } from "@melite/comfyui-cordis";
22
23
  import { expandRegistryFlow, extractRequestInitials, initialFileCandidates, registryFlowToInline, inlineStagesNameCards, registryInitialsError, } from "./flowsData.js";
24
+ import { stageReservedKeyLifts } from "./cardsFacts.js";
23
25
  import { isFile } from "./skillFs.js";
24
26
  import { kindsOk } from "./runsValidateStages.js";
25
27
  import { replayJudgeRows } from "./runsStart.js";
@@ -31,6 +33,7 @@ import { fetchEngineMem, filmLoadOf, filmMemoryWarn } from "./filmMemoryWarn.js"
31
33
  import { searchedVoice } from "./rootsManifest.js";
32
34
  import { newRunId, outRootFor, pipelineOf, strictBodyCheck, planResurrect, bootSweep, appendLedger, refusal, walkSubmitEnvelope } from "./queue.js";
33
35
  import { graphReceiptOf, graphReceiptStageOf } from "./queueSidecar.js";
36
+ import { attributionPersist, galleryLabelPersist } from "./runsTypes.js";
34
37
  import { sweepRunIds } from "./queueCore.js";
35
38
  import { cardRefusal, toRemoteError, refusePreview } from "./runsRefusalVoices.js";
36
39
  import { lifecycleInFlight } from "./lifecycleLatch.js";
@@ -40,13 +43,13 @@ import { coerceSnapshotBody } from "./runsValidateStages.js";
40
43
  import { applyFlowParamsOverride, overlayDecls } from "./flowsParamsOverlay.js";
41
44
  export { toRemoteError } from "./runsRefusalVoices.js";
42
45
  import { readFileSync } from "node:fs";
43
- import { CardArmError, liftCardParams, } from "./cardsRegistry.js";
46
+ import { CARD_ENVELOPE_KEYS, CardArmError, liftCardParams, } from "./cardsRegistry.js";
44
47
  import { FLOW_ID_RE } from "./runsGates.js";
45
48
  import { compileFlowInline, registerCompiledRun, selectSubmitDoor, } from "./runsStart.js";
46
49
  import { expandSeedSweep } from "./queueSubmit.js";
47
50
  import { listRunsAcross, parseIntOrNull } from "./runsList.js";
48
51
  import { claimPersist, errText, runLogTail, settlePersist, RUN_STATUSES, } from "./runsTypes.js";
49
- import { runOne, runEngine as runEngineOf } from "./runsExecute.js";
52
+ import { runOne, runEngine as runEngineOf, stampUnansweredRows } from "./runsExecute.js";
50
53
  import { engineFilmName } from "./filmLead.js";
51
54
  import { validate as validateArm, modelValidateArm } from "./runsValidateArms.js";
52
55
  import { BENCH_DRAFT_PREFIX_RE, benchDraftIdOf } from '@melite/contracts/benchStage';
@@ -61,6 +64,10 @@ import { BENCH_DRAFT_PREFIX_RE, benchDraftIdOf } from '@melite/contracts/benchSt
61
64
  // both sides — which no program did until the walls did.
62
65
  /** The refusal codes this remote serves, folded to the
63
66
  * protocol's vocabulary — a literal table, no dynamic key. */
67
+
68
+ // served artifact tail normalizes at the mint — a native separator
69
+ // never rides a url or gallery name.
70
+ const wireTail = (tail) => tail.split(sep).join('/');
64
71
  export function enrichDiskRow(row) {
65
72
  const stages = Array.isArray(row['stages']) ? row['stages'] : [];
66
73
  const artifacts = Array.isArray(row['artifacts'])
@@ -97,7 +104,24 @@ export function enrichDiskRow(row) {
97
104
  const relative = (value) => {
98
105
  const marker = `/${runId}/`;
99
106
  const at = value.lastIndexOf(marker);
100
- return at >= 0 ? value.slice(at + marker.length) : value.replace(/^\/+/, '');
107
+ if (at >= 0)
108
+ return wireTail(value.slice(at + marker.length));
109
+
110
+ // artifacts bound the run-id segment with backslashes (often
111
+ // mixed with posix tails stored earlier) — the posix marker
112
+ // never matches there and the absolute rode the wire raw. On a
113
+ // Windows-rooted value, hunt the segment bounded by either
114
+ // separator; a posix value is never drive- or UNC-rooted, so it
115
+ // keeps the old miss path byte-for-byte.
116
+ if (!/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/])/u.test(value))
117
+ return value.replace(/^\/+/, '');
118
+ const seg = (c) => c === '/' || c === '\\';
119
+ for (let at = value.lastIndexOf(runId); at > 0; at = value.lastIndexOf(runId, at - 1)) {
120
+ if (seg(value[at - 1]) && seg(value[at + runId.length])) {
121
+ return wireTail(value.slice(at + runId.length + 1));
122
+ }
123
+ }
124
+ return value.replace(/^\/+/, '');
101
125
  };
102
126
 
103
127
  // hero's ONLY media law — it carried avif|m4v|avi the contract's
@@ -143,6 +167,7 @@ export function sidecarReaderFor(dir) {
143
167
  return (name) => {
144
168
  try {
145
169
  return readFileSync(join(dir, name), 'utf8');
170
+ // a missing or unreadable sidecar file means there is nothing to mount — absence is a valid decorate answer, so the miss reads as null and never throws
146
171
  }
147
172
  catch {
148
173
  return null;
@@ -288,6 +313,11 @@ function curatedBenchLog(stageCount) {
288
313
  console.log("[runs] bench run admitted — " + String(stageCount) +
289
314
  " composed stage(s) with their FromStage links riding as stage inputs");
290
315
  }
316
+ /** The estate run-id grammar (queueCore's newRunId mint:
317
+ * run-<12hex>-<8hex>, plus the seed sweep's `-s<k>` family seat).
318
+ * The upscale door's ONLY registry-resolving spelling — every other
319
+ * chain_run value is a store name and passes untouched. */
320
+ const ESTATE_RUN_ID_RE = /^run-[0-9a-f]+(?:-[0-9a-f]+)*(?:-s\d+)?$/;
291
321
  /** The card plane's engine is the CONTRACT's (benchStage.ts) — the
292
322
  * bench is the card bench, and that is where it is stated. This arm
293
323
  * applies it to a flow document's card= rows only: an mcp/flow
@@ -405,6 +435,7 @@ export class RunsRuntimeService extends Service {
405
435
  const comfy = this.engineSeat ?? (() => {
406
436
  try {
407
437
  return needComfyUI(this.ctx, "runsRemote teardown");
438
+ // needComfyUI throws when no ComfyUI seat is registered — undefined only skips the interrupt and the stopFlags still converge the worker loop (teardown must not fail)
408
439
  }
409
440
  catch {
410
441
  return undefined;
@@ -630,14 +661,55 @@ export class RunsRuntimeService extends Service {
630
661
  const params = (typeof row["params"] === "object" && row["params"] !== null && !Array.isArray(row["params"]))
631
662
  ? { ...row["params"] }
632
663
  : {};
664
+
665
+ // stage-policy keys (comfyui-merge.ts STAGE_RESERVED_PARAMS — the
666
+ // unload boundary's knob, the merged VRAM budget) live on the
667
+ // STAGE row, not the card surface. Admission stays the declared
668
+ // CARD law, so the reserved keys are lifted OUT of the compose
669
+ // walk here (phase 1 would refuse them as undeclared card params —
670
+ // the live P7 press's refusal) and carried back onto the COMPOSED
671
+ // row's params additively, so planMerge's paramsByStage reads the
672
+ // bag the bench stored. The copy above keeps the original row
673
+ // untouched; the graph receipt below still judges the doc
674
+ // verbatim.
675
+
676
+ // reserved key the card's own DECLARATION admits is NOT a policy
677
+ // key on this stage — it is the card's param, and it WALKS (h3's
678
+ // declared output_name threads the deliverable save prefixes at
679
+ // compose; the settle's label mint reads it from the composed row
680
+ // either way). The spared truth is the same one admission judges
681
+ // (the DECL's schemaNames + admits — cardAdmits via cardsFacts
682
+ // stageReservedKeyLifts, the ONE spelling this loop and the write
683
+ // door's lift both ride); an undeclared reserved key on any other
684
+ // family keeps lifting verbatim, so the all-families label
685
+ // blanket survives.
686
+ const reserved = {};
687
+ const spared = {};
633
688
  const card = String(row["card"] ?? "");
689
+ const decl = card !== "" ? this.ctx.cardRegistry.cardDecls()[card] : undefined;
690
+ for (const k of STAGE_RESERVED_PARAMS) {
691
+ if (params[k] === undefined)
692
+ continue;
693
+ if (!stageReservedKeyLifts(decl, k)) {
694
+ // A declared reserved key WALKS (the card's own param) — and
695
+ // still rides the composed row's params bag below, so the
696
+ // settle's label mint and planMerge's paramsByStage read the
697
+ // same stem the compose threaded into the prefixes.
698
+ spared[k] = params[k];
699
+ }
700
+ else {
701
+ reserved[k] = params[k];
702
+ delete params[k];
703
+ }
704
+ }
634
705
  // STROKE 3'S FALLBACK (the validate walk's own shape —
635
706
  // runsValidateArms: a family-less card stage composes by its OWN
636
707
  // card id — mid alone, never an injected body.model, which would
637
708
  // hit the board check before prepareCardParams resolved the
638
709
  // card-unit arm). The old `?? ""` handed prepareCardParams an
639
- // empty mid — "model id \"\" is not a legal identifier" on the
640
- // body-to-somax rig hop and every family-less flow stage after
710
+ // empty mid — "model id \"\" is not a legal identifier" on a
711
+ // family-less flow stage's card hop (the af-move commission's
712
+
641
713
 
642
714
 
643
715
  // effective routing key rode an EXPLICIT spelling — params.model
@@ -693,6 +765,10 @@ export class RunsRuntimeService extends Service {
693
765
  " but the stage wires no input of that name — the merge would refuse it at run time. " +
694
766
  "Wire the input (an inputs edge from a prior stage, or an initial binding) or replace the $spell with a concrete value.", { loc: "stages" });
695
767
  }
768
+ // THE INITIAL-TENSOR REFUSAL (the initial-grammar law, audit
769
+
770
+ // composed graph — the seat a spell lands in is only visible
771
+ // there. See the gate below the phase try/catch.
696
772
  let p1;
697
773
  let composed;
698
774
  try {
@@ -743,20 +819,100 @@ export class RunsRuntimeService extends Service {
743
819
  }
744
820
  throw e;
745
821
  }
746
- const stageOutputs = (typeof row["outputs"] === "object" && row["outputs"] !== null && !Array.isArray(row["outputs"])
822
+ // THE INITIAL-TENSOR REFUSAL (the initial-grammar law, audit
823
+
824
+ // resolves at the merge to the initial's VALUE — legal on a
825
+ // value seat (a STRING/INT/FLOAT dial) or a Load* file slot, a
826
+ // BURN on a tensor slot (the F48 voices→ref_audios class: the
827
+ // node received a string where the engine wants a link —
828
+ // TypeError at run time, after the kind gate stayed green). The
829
+ // SEAT is only visible in the composed graph, so the gate rides
830
+ // after phase2, judging every initial-bound spell against the
831
+ // engine's own served slot types (the live /object_info census —
832
+ // the same table the pack gate refuses closed on). This is the
833
+ // mirror of the merge's ROW-4 file-slot gate
834
+ // (comfyui-merge.ts): ROW-4 refuses a producer LINK in a Load*
835
+ // slot; this refuses an initial VALUE in a tensor slot. The
836
+ // media KIND cannot judge this — rig's mesh_glb is a "mesh"
837
+ // port that legally takes an initial $glb (a LoadGLB path seat;
838
+ // the rig card's auto lane runs green) while upscale's
839
+ // input_image tensor seat refuses the same shape.
840
+ {
841
+ const census = cards.objectInfo();
842
+ if (census !== null) {
843
+ const initialBound = new Set();
844
+ if (typeof row["inputs"] === "object" && row["inputs"] !== null && !Array.isArray(row["inputs"])) {
845
+ for (const [wire, edge] of Object.entries(row["inputs"])) {
846
+ if (typeof edge === "object" && edge !== null && !Array.isArray(edge) &&
847
+ typeof edge["initial"] === "string") {
848
+ initialBound.add(wire);
849
+ }
850
+ }
851
+ }
852
+ if (initialBound.size > 0) {
853
+ const VALUE_SLOT_TYPES = new Set(["STRING", "INT", "FLOAT", "BOOLEAN"]);
854
+ const wf = (composed.graph ?? {});
855
+ for (const node of Object.values(wf)) {
856
+ const cls = String(node["class_type"] ?? "");
857
+ if (cls.startsWith("Load"))
858
+ continue;
859
+ const info = census[cls]?.input;
860
+ const ins = node["inputs"];
861
+ if (typeof ins !== "object" || ins === null || Array.isArray(ins))
862
+ continue;
863
+ for (const [slot, val] of Object.entries(ins)) {
864
+ if (typeof val !== "string" || !val.startsWith("$") || val.length < 2)
865
+ continue;
866
+ if (!initialBound.has(val.slice(1)))
867
+ continue;
868
+ const decl = info?.required?.[slot] ?? info?.optional?.[slot];
869
+ // a type tuple ["IMAGE", {…}] declares its slot type; a
870
+ // combo list (nested array) or an absent entry takes a
871
+ // value by construction — never refused here. A "*"
872
+ // wildcard is a LINK seat the node's own code types
873
+ // (the reference bundle's inputs) — an initial VALUE
874
+ // there is the F48 burn class, so it refuses too.
875
+ const slotType = Array.isArray(decl) && typeof decl[0] === "string" ? decl[0] : null;
876
+ if (slotType === null || VALUE_SLOT_TYPES.has(slotType))
877
+ continue;
878
+ throw new RemoteError("runs/invalid-request", label + JSON.stringify(id) + ": node " + JSON.stringify(cls) +
879
+ " input " + JSON.stringify(slot) + " carries " + val +
880
+ " but input " + JSON.stringify(val.slice(1)) +
881
+ " is an initial binding — the initial's VALUE would land in the engine's " +
882
+ JSON.stringify(slotType) + " slot, which wants a link (a tensor seat needs a producer). " +
883
+ "Wire the input from a prior stage's output, or feed the file through the card's own loader param.", { loc: "stages" });
884
+ }
885
+ }
886
+ }
887
+ }
888
+ }
889
+ const rowOutputs = (typeof row["outputs"] === "object" && row["outputs"] !== null && !Array.isArray(row["outputs"])
747
890
  && Object.keys(row["outputs"]).length > 0)
748
891
  ? { ...row["outputs"] }
749
- // THE BENCH'S OUTPUTS WIN ONLY WHEN THEY CARRY CHANNELS
750
- // (the work audit's R1 — a regression the card-ports law
751
- // introduced here): a card stage's stored outputs are `{}` by
752
- // design (the channels derive from the card's own ports at
753
- // compose), and this line kept that `{}` verbatim — so the
754
- // merged worker published ZERO channels and every $spell
755
- // consumer downstream got nothing where the old fabricated
756
- // `{default: 'image'}` at least published one. An EMPTY
757
- // channel map means "unfilled": the compose's own ports
758
- // answer, exactly as the single-card path already does.
759
- : composed.outputs;
892
+ : undefined;
893
+ const rowCardIo = (typeof row["card_io"] === "object" && row["card_io"] !== null && !Array.isArray(row["card_io"])
894
+ && Object.keys(row["card_io"]).length > 0)
895
+ ? { ...row["card_io"] }
896
+ : undefined;
897
+ const composedOuts = (typeof composed.outputs === "object" && composed.outputs !== null
898
+ && Object.keys(composed.outputs).length > 0)
899
+ ? { ...composed.outputs }
900
+ : undefined;
901
+ const cardDeclaredOuts = cards.defsSync().get(card)?.flowKinds?.outputs;
902
+ const cardDeclared = (typeof cardDeclaredOuts === "object" && cardDeclaredOuts !== null
903
+ && Object.keys(cardDeclaredOuts).length > 0)
904
+ ? { ...cardDeclaredOuts }
905
+ : undefined;
906
+ const stageOutputs =
907
+
908
+ // they carry channels (the work audit's R1 — preserved: a
909
+ // regression the card-ports law introduced here), then the
910
+ // compose's own ports (the card's bindings, the mask-produce
911
+ // law's seat), then the row's declared cardIo table, then the
912
+ // card's declared output kinds. An EMPTY channel map means
913
+ // "undeclared" at every leg — the start door refuses it loud
914
+ // (never a fabricated {default: <engine kind>}).
915
+ rowOutputs ?? composedOuts ?? rowCardIo ?? cardDeclared ?? {};
760
916
  // THE OUTPUT RENAME FOLLOWS THE BINDINGS (the run-9f8bd60f8cb8
761
917
 
762
918
  // channels (outputs {body: "mesh"} over the card's own
@@ -805,12 +961,19 @@ export class RunsRuntimeService extends Service {
805
961
  params: {
806
962
  workflow: composed.graph,
807
963
  output_nodes: (renamedAny ? renamedNodes : cardNodes),
964
+ // THE STAGE-RESERVED CARRY (F-C): the merge plane's own keys
965
+ // ride beside the composed graph — additive, never a card key.
966
+ // A SPARED reserved key (declared on the card — h3's
967
+ // output_name) rides the same bag: the label mint and the
968
+ // file-plane compose read ONE stem.
969
+ ...reserved,
970
+ ...spared,
808
971
  },
809
972
 
810
973
  // `expected` for its kindsOk walk and defaults an absent bag to
811
974
  // {} — so a composed stage that dropped it would compile with NO
812
975
  // kind assertion on its own inputs. The registry rows declare
813
- // them (audio-native-tts: { text: "text" }), and the check is
976
+ // them (anny-hmr-estimator: { photo: "photo" }), and the check is
814
977
  // theirs, not the composer's to discard.
815
978
  //
816
979
 
@@ -850,6 +1013,7 @@ export class RunsRuntimeService extends Service {
850
1013
 
851
1014
 
852
1015
 
1016
+
853
1017
  async composeRegistryFlowStages(inlineDoc, runId,
854
1018
 
855
1019
 
@@ -857,17 +1021,23 @@ export class RunsRuntimeService extends Service {
857
1021
  /** THE GRAPH-RECEIPT LEDGER (P1): filled with {stageId: row}
858
1022
  * for every composed card stage (composeCardStageRow's seat). */
859
1023
  receiptsOut) {
1024
+ // registryFlowToInline always projects an array of object rows
1025
+ // and the raw door's junkFree gate admits only arrays of object
1026
+ // rows — the non-array fallback never fires (the bench twin's
1027
+ // own pruned dead leg, composeBenchStages). The assertion names
1028
+ // the callers' guaranteed shape, never unknown (the sniff wall
1029
+ // counts as-unknown sites against the baseline).
860
1030
  const rows = inlineDoc["stages"];
861
- // registryFlowToInline always projects an array of object rows, so
862
- // the non-array answer needs no second shape (the compile-time
863
- // gate below judges the same value).
864
- if (!Array.isArray(rows))
865
- return inlineDoc;
866
1031
  const out = [];
867
1032
  for (const [i, st] of rows.entries()) {
868
- if (typeof st !== "object" || st === null)
1033
+ const item = st;
1034
+ /* v8 ignore next -- both callers guarantee object rows (the
1035
+ * projection above, the raw door's junkFree gate), so the junk
1036
+ * skip never fires here — the walk's belt for a caller that
1037
+ * skips the gates. */
1038
+ if (typeof item !== "object" || item === null)
869
1039
  continue;
870
- const row = st;
1040
+ const row = item;
871
1041
  const card = typeof row["card"] === "string" ? row["card"] : "";
872
1042
  const id = typeof row["id"] === "string" && row["id"] !== "" ? row["id"] : "s_" + String(i);
873
1043
  out.push(card === ""
@@ -927,6 +1097,55 @@ export class RunsRuntimeService extends Service {
927
1097
  * run id when replaying its _request.json — the remote surface
928
1098
  * never passes this (two-arg wire calls only). */
929
1099
  reuse) {
1100
+ try {
1101
+ return await this.startInner(doc, signal, reuse);
1102
+ }
1103
+ catch (error) {
1104
+ this.ledgerPressRefused(doc, error, reuse);
1105
+ throw error;
1106
+ }
1107
+ }
1108
+
1109
+
1110
+
1111
+
1112
+
1113
+
1114
+
1115
+
1116
+
1117
+
1118
+
1119
+
1120
+
1121
+
1122
+
1123
+
1124
+
1125
+
1126
+
1127
+ ledgerPressRefused(doc, error, reuse) {
1128
+ try {
1129
+ const stateRoot = this.ctx.queue.stateRoot;
1130
+ const remote = remoteErrorOf(error);
1131
+ const body = JSON.stringify(doc) ?? "unserializable";
1132
+ const CAPPED = 4000;
1133
+ appendLedger(stateRoot, "press.refused", {
1134
+ code: remote?.code ?? "throw",
1135
+ voice: errText(error).slice(0, 400),
1136
+ draft_id: typeof doc === "object" && doc !== null
1137
+ ? (doc["draft_id"] ?? null)
1138
+ : null,
1139
+ ...(reuse !== undefined ? { replay_of: reuse.runId } : {}),
1140
+ request: body.length > CAPPED ? body.slice(0, CAPPED) + "…+trunc" : body,
1141
+ });
1142
+ }
1143
+ catch {
1144
+ /* the echo never replaces the refusal (appendLedger already
1145
+ * self-swallows I/O; this guards the stateRoot read itself) */
1146
+ }
1147
+ }
1148
+ async startInner(doc, signal, reuse) {
930
1149
  signal.throwIfAborted();
931
1150
  // The pre-registration chain, order (queue.ts's envelope
932
1151
  // walk with the draft probe handed in): non-object, test-bool,
@@ -1199,22 +1418,32 @@ export class RunsRuntimeService extends Service {
1199
1418
  // row says so.
1200
1419
  let benchDoc;
1201
1420
  const benchWarnings = [];
1202
- try {
1203
- // R7 CURE (round-14 race audit, LOW — the run-press live alias):
1204
- // the drafts read answers the CACHED doc by reference (the
1205
- // cached-object law), so composing + snapshotting from it naked
1206
- // let a mutation landing between press and snapshot straddle
1207
- // the two (a snapshot that was not quite a snapshot). The
1208
- // press now owns a DEEP copy: what the run composes and what
1209
- // the sidecar snapshots is the SAME frozen instant, no matter
1210
- // what the live bench does next.
1211
- benchDoc = structuredClone(await this.ctx.draftsRemote.get(checked.draftId, signal));
1212
- }
1213
- catch (e) {
1214
- benchDoc = undefined;
1215
- benchWarnings.push("bench snapshot read failed at press (" +
1216
- (e instanceof Error ? e.message : String(e)) +
1217
- ") — only the card snapshot rode; restore reconstructs from the live bench");
1421
+ // THE FLOW-DOC EXEMPTION'S READ GATE (flows-are-compositions
1422
+ // slice C): a {flow}/{flow_inline} press with no draft_id has no
1423
+ // bench to snapshot — skipping the read is the legal shape, not
1424
+ // an outage, so no warning rides (the run row is the record;
1425
+ // restore reconstructs from the live registry, the run-rooted
1426
+ // face Slice A served). A PRESENT draft_id (the materialized
1427
+ // bench the melite_flow press lands) snapshots exactly as the
1428
+ // card arm does.
1429
+ if (checked.draftId !== undefined) {
1430
+ try {
1431
+ // R7 CURE (round-14 race audit, LOW — the run-press live alias):
1432
+ // the drafts read answers the CACHED doc by reference (the
1433
+ // cached-object law), so composing + snapshotting from it naked
1434
+ // let a mutation landing between press and snapshot straddle
1435
+ // the two (a snapshot that was not quite a snapshot). The
1436
+ // press now owns a DEEP copy: what the run composes and what
1437
+ // the sidecar snapshots is the SAME frozen instant, no matter
1438
+ // what the live bench does next.
1439
+ benchDoc = structuredClone(await this.ctx.draftsRemote.get(checked.draftId, signal));
1440
+ }
1441
+ catch (e) {
1442
+ benchDoc = undefined;
1443
+ benchWarnings.push("bench snapshot read failed at press (" +
1444
+ (e instanceof Error ? e.message : String(e)) +
1445
+ ") — only the card snapshot rode; restore reconstructs from the live bench");
1446
+ }
1218
1447
  }
1219
1448
  // THE ONE RUN ID, MINTED ONCE (the operator's live refusal,
1220
1449
 
@@ -1280,30 +1509,90 @@ export class RunsRuntimeService extends Service {
1280
1509
  let benchComposed = false;
1281
1510
  if (selected.door === "draft" && benchDoc !== undefined) {
1282
1511
  const wired = benchWiring(benchDoc);
1283
- // THE BENCH RUN, COMPOSED (the draft door): this door composes
1284
- // EVERY card stage of the bench — through the SAME registry walk
1285
- // a single card start uses, laws and all — and submits ONE
1286
- // merged run whose stages carry their `inputs` edges for the
1287
- // worker to link. A $spell survives into the composed graph on
1288
- // purpose: the merge resolves it into the upstream stage's
1289
- // output (that is what a FromStage link IS).
1290
1512
 
1291
- // "run sources resolve nowhere (1 dead: run-65dc3ee505ef-…/
1292
- // gen)"). The bench run minted the id TWICE: once here, to
1293
- // compose the stages — and again below, to register the run.
1294
- // Every composed graph carries its own `${runId}/gen` output
1295
- // prefix, so the second mint left every forward reference
1296
- // naming a run that was never created; the source resolver
1297
- // (rightly) treated them as dead sources and the run refused
1298
- // before it registered. The id is minted ONCE, here, and both
1299
- // the compose and the registration take it — one derivation,
1300
- // and a wall drives the pair.
1513
+ // "running flows that don't show up on the bench"). A body
1514
+ // carrying bench_stage_id names the ONE row the caller
1515
+ // pressed — until now this door ignored the claim and
1516
+ // composed the WHOLE bench into one merged run: every
1517
+ // sibling stage re-executed on the GPU, the run's stage
1518
+ // digest named every row (so a failure poisoned every
1519
+ // tile's last_run), and the settle mirror stamped 'stopped'
1520
+ // onto rows nobody pressed. The claim arm composes ONLY the
1521
+ // claimed row — the same ONE-PRESS ONE-CARD law the {model:}
1522
+ // door owns, reached from the familyless walk. The claim is
1523
+ // JUDGED (benchStageIdOf's membership law: a stale or
1524
+ // foreign id refuses loud, never a stamp on a row nobody
1525
+ // pressed); an archived claim refuses in the archived skip's
1526
+ // own voice.
1527
+ const claimRaw = body["bench_stage_id"];
1528
+ const claim = typeof claimRaw === "string" && claimRaw !== "" ? claimRaw : undefined;
1301
1529
  const benchFams = {};
1302
1530
  // THE GRAPH-RECEIPT LEDGER (P1): the bench rows' per-stage
1303
1531
  // queue-time evidence rides the same function-scope ledger
1304
1532
  // as the fams (the seat the registration door reads).
1305
1533
  const benchReceipts = {};
1306
- const composed = await this.composeBenchStages(benchDoc, runId, benchFams, benchReceipts);
1534
+ let composed;
1535
+ if (claim !== undefined) {
1536
+ benchStageIdOf(benchDoc, "", claim, checked.draftId ?? draftIdOf(""));
1537
+ const claimRows = benchDoc["stages"];
1538
+ /* v8 ignore next 1 -- pinned by benchStageIdOf's membership law above: a non-array stages list can never contain the claimed id, so the door refused before this read; the fallback stays as the read's own contract */
1539
+ const allRows = Array.isArray(claimRows) ? claimRows : [];
1540
+ const claimed = allRows.find((r) => typeof r === "object" && r !== null && r["id"] === claim);
1541
+ // benchStageIdOf judged membership above — the find reads
1542
+ // the same ledger once, for the row itself.
1543
+ /* v8 ignore next 7 -- pinned by benchStageIdOf's membership law above (runsRegistry's own benchStageIdOf refuses any id that names no stage row before this block runs); the backstop stays in case the two reads ever diverge */
1544
+ if (claimed === undefined) {
1545
+ throw toRemoteError(refusal(400, "bench_stage_id " + JSON.stringify(claim) + " names no stage row of draft " +
1546
+ JSON.stringify(String(checked.draftId ?? "")) + " — the press names the row it came from, and that row must exist on the bench (reopen the tab and press again)", "invalid_request"));
1547
+ }
1548
+ if (claimed["archived"] === true) {
1549
+ throw toRemoteError(refusal(400, "bench stage " + JSON.stringify(claim) + " is archived — a spent stage composes nowhere; unarchive it to run it again", "invalid_request"));
1550
+ }
1551
+ // THE WIRE RESOLUTION LAW, server half: a single-stage press
1552
+ // has no upstream stages to merge, so every wire must arrive
1553
+ // RESOLVED — the caller's concrete params overlay the row's
1554
+ // own bag (the client resolves each $spell to the upstream's
1555
+ // last result before the start; the same law the {model:}
1556
+ // door's body rides). The row's `inputs` edges are dropped
1557
+ // here ON PURPOSE: there is no upstream stage in this run to
1558
+ // link, and a $spell the caller did NOT resolve rides the
1559
+ // unwired-spell gate's refusal (composeCardStageRow) — the
1560
+ // honest wall, never a link to nowhere at the merge.
1561
+ const overlay = {};
1562
+ for (const [k, v] of Object.entries(body)) {
1563
+ if (!CARD_ENVELOPE_KEYS.includes(k))
1564
+ overlay[k] = v;
1565
+ }
1566
+ const rowParams = typeof claimed["params"] === "object" && claimed["params"] !== null && !Array.isArray(claimed["params"])
1567
+ ? { ...claimed["params"] } : {};
1568
+ const single = {
1569
+ ...claimed,
1570
+ params: { ...rowParams, ...overlay },
1571
+ };
1572
+ delete single["inputs"];
1573
+ composed = [await this.composeCardStageRow(single, claim, runId, "bench stage ", benchFams, benchReceipts)];
1574
+ }
1575
+ else {
1576
+ // THE BENCH RUN, COMPOSED (the draft door): this door composes
1577
+ // EVERY card stage of the bench — through the SAME registry walk
1578
+ // a single card start uses, laws and all — and submits ONE
1579
+ // merged run whose stages carry their `inputs` edges for the
1580
+ // worker to link. A $spell survives into the composed graph on
1581
+ // purpose: the merge resolves it into the upstream stage's
1582
+ // output (that is what a FromStage link IS).
1583
+
1584
+ // "run sources resolve nowhere (1 dead: run-65dc3ee505ef-…/
1585
+ // gen)"). The bench run minted the id TWICE: once here, to
1586
+ // compose the stages — and again below, to register the run.
1587
+ // Every composed graph carries its own `${runId}/gen` output
1588
+ // prefix, so the second mint left every forward reference
1589
+ // naming a run that was never created; the source resolver
1590
+ // (rightly) treated them as dead sources and the run refused
1591
+ // before it registered. The id is minted ONCE, here, and both
1592
+ // the compose and the registration take it — one derivation,
1593
+ // and a wall drives the pair.
1594
+ composed = await this.composeBenchStages(benchDoc, runId, benchFams, benchReceipts);
1595
+ }
1307
1596
  // the bench-composed stages' families reach the same claim
1308
1597
  // re-probe ledger the flow arm feeds (S-S4): the empty-ledger
1309
1598
  // carve-out below is the card-single path alone, never this
@@ -1328,8 +1617,10 @@ export class RunsRuntimeService extends Service {
1328
1617
  // the run's own log line says what happened — a re-route is
1329
1618
  // never silent (NO SILENT BEHAVIOR, the same order as the
1330
1619
  // spell gate below)
1331
- console.log("[runs] the draft-door bench run composed " + String(composed.length) +
1332
- " stages, wires " + JSON.stringify(wired.cross) + " riding as stage inputs");
1620
+ console.log(claim !== undefined
1621
+ ? "[runs] the draft-door claimed-stage press composed 1 stage (" + claim + ") — the bench's other rows were not pressed"
1622
+ : "[runs] the draft-door bench run composed " + String(composed.length) +
1623
+ " stages, wires " + JSON.stringify(wired.cross) + " riding as stage inputs");
1333
1624
  }
1334
1625
  if (selected.door === "model") {
1335
1626
  // The card start arm (handleCardStart 1016-1136, second
@@ -1349,6 +1640,11 @@ export class RunsRuntimeService extends Service {
1349
1640
  throw toRemoteError(cardRefusal(e));
1350
1641
  throw e;
1351
1642
  }
1643
+ // THE CHAIN-STORE RUN-ID DOOR (the F35 write side, session 2):
1644
+ // the upscale bag's run-id bindings resolve to their stores
1645
+ // BEFORE compose — a store-less id refuses here (the honest
1646
+ // plain-film voice), a store spelling passes untouched.
1647
+ p1 = this.resolveUpscaleChainRunIds(p1);
1352
1648
  let composed;
1353
1649
  try {
1354
1650
  composed = await cards.phase2Card(p1, runId);
@@ -1481,7 +1777,13 @@ export class RunsRuntimeService extends Service {
1481
1777
  // run-4610e1c38d75 was "edit" here vs "s_2" in the draft
1482
1778
  // doc). Multi-row benches compose through the bench loop,
1483
1779
  // which stamps each row's own id.
1484
- benchStageId: benchStageIdOf(benchDoc, skeleton, typeof body["bench_stage_id"] === "string" ? body["bench_stage_id"] : undefined, checked.draftId),
1780
+ benchStageId: benchStageIdOf(benchDoc, skeleton, typeof body["bench_stage_id"] === "string" ? body["bench_stage_id"] : undefined,
1781
+ // the {model:} door always carries a draft_id (the CARD
1782
+ // BIRTH LAW binds it; the envelope's flow-doc exemption
1783
+ // admits only flow/flow_inline bodies) — the ?? covers the
1784
+ // type, never a real press
1785
+ /* v8 ignore next 1 -- the CARD BIRTH LAW pins checked.draftId on this arm; the ?? covers the type, never a real press */
1786
+ checked.draftId ?? draftIdOf("")),
1485
1787
  // The {model:} card door's engine (the compose plane is
1486
1788
  // ComfyUI's — the card arm rides it by construction).
1487
1789
  engine: CARD_PLANE_ENGINE,
@@ -1511,15 +1813,29 @@ export class RunsRuntimeService extends Service {
1511
1813
  compiled: { stages: [cardStage] },
1512
1814
  testFlag: checked.testFlag,
1513
1815
  executeCeilMs: checked.ceilMs,
1514
- draftId: checked.draftId,
1816
+ // the {model:} door always carries a draft_id (CARD BIRTH
1817
+ // LAW; the flow-doc exemption never reaches this arm) — the
1818
+ // ?? covers the type, never a real press
1819
+ /* v8 ignore next 1 -- the CARD BIRTH LAW pins checked.draftId on this arm; the ?? covers the type, never a real press */
1820
+ draftId: checked.draftId ?? draftIdOf(""),
1515
1821
  stateRoot,
1516
1822
  enqueue: (row) => this.core.enqueue(row),
1517
1823
  // F-6(b): the admission warn computes pre-registration so
1518
1824
  // it rides the record AND the queued sidecar (disk rows
1519
1825
  // carry it after a reload).
1826
+ // THE PROMPT GATE'S RECEIPT HALF (the VID GEN handoff,
1827
+
1828
+ // prompt gate's warn severities and every NAMED waiver
1829
+ // (params.prompt_waivers) as one line each — rides the same
1830
+ // stamp: a waived rule passes the press and is recorded,
1831
+ // never silent. The lines derive from the card's own gate
1832
+ // over the admitted doc (cardRequestBody — the same doc the
1833
+ // compose judged), so the receipt and the refusal can never
1834
+ // disagree.
1520
1835
  warnings: [
1521
1836
  ...benchWarnings,
1522
1837
  ...(await this.filmAdmissionWarnings(p1.card, body)),
1838
+ ...((cards.defsSync().get(p1.card)?.admissionWarns?.(cardRequestBody)) ?? []),
1523
1839
  ],
1524
1840
  door: {
1525
1841
  runId,
@@ -1646,9 +1962,23 @@ export class RunsRuntimeService extends Service {
1646
1962
  // the flow door. The overlay law is SHARED (round-21 flows
1647
1963
  // audit F1): applyFlowParamsOverride below, the same helper the
1648
1964
  // validate door rides.
1965
+
1966
+ // a {flow:} press reads card knobs from params — a seed at
1967
+ // the top lands in NO stage (every stage mints fresh) while
1968
+ // _request.json carries it like a promise, so the flow cannot
1969
+ // reproduce. Refuse LOUD with the corrected spelling, never
1970
+ // mint behind a knob that died silently.
1971
+ if (body["seed"] !== undefined) {
1972
+ throw new RemoteError("runs/invalid-request", "flow " + JSON.stringify(name) + " carries a top-level " +
1973
+ JSON.stringify("seed") + " — a {flow:} press reads card " +
1974
+ "knobs from params, so a top-level seed reaches no stage. " +
1975
+ "State it inside params ({seed: N}) to pin every stage " +
1976
+ "this flow's tool overlay names; the flow's initials " +
1977
+ "stay top-level.", { loc: "params" });
1978
+ }
1649
1979
  const overrideRaw = body["params"];
1650
1980
  if (overrideRaw !== undefined) {
1651
- applyFlowParamsOverride(name, expanded.stages, overrideRaw, overlayDecls(this.ctx.cardRegistry), String(body["model"] ?? ""));
1981
+ applyFlowParamsOverride(name, expanded.stages, overrideRaw, overlayDecls(this.ctx.cardRegistry), String(body["model"] ?? ""), decl.tool?.overlays ?? []);
1652
1982
  const rest = { ...body };
1653
1983
  delete rest["params"];
1654
1984
  body = rest;
@@ -1873,12 +2203,21 @@ export class RunsRuntimeService extends Service {
1873
2203
  // first cut was NAMED NOT CURED; judging the compiled rows needs
1874
2204
  // no card plane at all.)
1875
2205
  try {
1876
- kindsOk(typeof replayId === "string" ? replayId : "flow_inline", replayJudgeRows(compiled), {}, undefined);
2206
+ kindsOk(typeof replayId === "string" ? replayId : "flow_inline", replayJudgeRows(compiled), undefined);
1877
2207
  }
1878
2208
  catch (judgeError) {
2209
+
1879
2210
  if (judgeError instanceof FlowError) {
1880
2211
  throw new RemoteError("runs/invalid-request", judgeError.message, { loc: "body" });
1881
2212
  }
2213
+ /* v8 ignore next -- kindsOk judges the rows this same press
2214
+ * just compiled: its non-FlowError arms (needCardRegistry's
2215
+ * plain Error, the row-shape guards) judge caller-authored
2216
+ * rows, while compiled rows arrive well-shaped — the compiler
2217
+ * refused anything else — with no card stages left
2218
+ * (composition consumed them). Only the kind lattice
2219
+ * (FlowError) can fire here; the rethrow is the belt for a
2220
+ * future kindsOk arm that throws outside the lattice. */
1882
2221
  throw judgeError;
1883
2222
  }
1884
2223
  if (compiled.stages.length !== 1) {
@@ -1926,7 +2265,10 @@ export class RunsRuntimeService extends Service {
1926
2265
  compiled,
1927
2266
  testFlag: checked.testFlag,
1928
2267
  executeCeilMs: checked.ceilMs,
1929
- draftId: checked.draftId,
2268
+ // the flow arms may run doc-less (the flow-doc exemption): the
2269
+ // empty id records exactly that — no draft, the run row is the
2270
+ // record; a materialized flow press carries its bench id here
2271
+ draftId: checked.draftId ?? draftIdOf(""),
1930
2272
  stateRoot,
1931
2273
  enqueue: (row) => this.core.enqueue(row),
1932
2274
  // the bench-read warning rides the inline arm too (audit N-S3)
@@ -2003,8 +2345,12 @@ export class RunsRuntimeService extends Service {
2003
2345
  /** The list arm (REBUILD-7): the restore-port envelope over the
2004
2346
  * output roots. The raw limit STRING rides from the lane (strict
2005
2347
  * int() semantics: underscores parse, junk refuses). The drafts
2006
- * probe rides the drafts remote. */
2007
- async list(rawLimit, signal, test = false) {
2348
+ * probe rides the drafts remote. The optional draft/stage
2349
+ * filters (the stale-two-run chat audit's cure 3 — runsList.ts
2350
+ * RunsListFilter) narrow the served rows to one draft's takes;
2351
+ * an empty string reads ABSENT (the parse_qs blank law), never
2352
+ * as a match against the empty id. */
2353
+ async list(rawLimit, signal, draftId, benchStageId) {
2008
2354
  signal.throwIfAborted();
2009
2355
  // The door's 400 text (parseIntOrNull in runsList.ts) — the runs face's invalid-request refusal.
2010
2356
  // ONLY this parse folds; every other failure stays loud (no absorb).
@@ -2015,9 +2361,20 @@ export class RunsRuntimeService extends Service {
2015
2361
  const limit = Math.max(1, Math.min(500, parsed));
2016
2362
  // §23 CROSS-ROOTS: the union list across the manifest (own
2017
2363
  // root first — own rows win collisions, every row served_from).
2018
- return await listRunsAcross(this.ctx.queue.stateRoots, limit, async (draftId) => {
2364
+
2365
+ // the scan covers BOTH out seats per root — test:true runs
2366
+ // list with `test: true` stamped (listRunsAcross owns the
2367
+ // seats; there is no flag-filtered list, hiding by query is
2368
+ // not a door this estate serves).
2369
+ const filter = (draftId !== undefined && draftId !== "") || (benchStageId !== undefined && benchStageId !== "")
2370
+ ? {
2371
+ ...(draftId !== undefined && draftId !== "" ? { draftId } : {}),
2372
+ ...(benchStageId !== undefined && benchStageId !== "" ? { benchStageId } : {}),
2373
+ }
2374
+ : undefined;
2375
+ return await listRunsAcross(this.ctx.queue.stateRoots, limit, async (probeId) => {
2019
2376
  try {
2020
- await this.ctx.draftsRemote.get(draftId, signal);
2377
+ await this.ctx.draftsRemote.get(probeId, signal);
2021
2378
  return true;
2022
2379
  }
2023
2380
  catch (e) {
@@ -2028,7 +2385,7 @@ export class RunsRuntimeService extends Service {
2028
2385
  void e;
2029
2386
  return false;
2030
2387
  }
2031
- });
2388
+ }, filter);
2032
2389
  }
2033
2390
  /** The validate arm (REBUILD-8): the PURE compile pipeline
2034
2391
  * (flowFromBody → compile → pin sweep → the 200 row) over the
@@ -2054,6 +2411,7 @@ export class RunsRuntimeService extends Service {
2054
2411
  const cfg = loadEndpointConfig();
2055
2412
  if (typeof cfg["url"] === "string")
2056
2413
  url = cfg["url"];
2414
+ // an unreadable endpoint config leaves the engine url empty — the admission stats read is best-effort and a stats failure never blocks admission
2057
2415
  }
2058
2416
  catch {
2059
2417
  url = "";
@@ -2061,6 +2419,84 @@ export class RunsRuntimeService extends Service {
2061
2419
  const warn = filmMemoryWarn(load, await fetchEngineMem(url));
2062
2420
  return warn === null ? [] : [warn];
2063
2421
  }
2422
+ /** THE CHAIN-STORE RUN-ID DOOR (the F35 write side, session 2): an
2423
+ * h3-timeline doc's upscale entry may bind its source by ESTATE
2424
+ * RUN ID — resolved HERE, before compose, through the run row the
2425
+ * harvest registrar stamped (result_outputs.chain_store.run_name),
2426
+ * so the composed manager carries a BARE STORE NAME and the
2427
+ * execute door's existing law (gates-h3-chain-selection-door)
2428
+ * keeps judging name→store — one judge per edge. A store-spelling
2429
+ * binding (swap_…/picture_… — anything off the run-id grammar)
2430
+ * passes byte-untouched with ZERO registry reads: the store stays
2431
+ * the only existence truth, judged where it is already walled. An
2432
+ * id-grammar spelling with no row — or a row whose stages carry no
2433
+ * chain_store — refuses LOUD at this door naming the plain-film
2434
+ * law, never the execute door's typo-reading 404 (the run row,
2435
+ * not the store, answers "was this a chain run"). The determinism
2436
+ * corner: the grammar resolves through the registry ONLY and never
2437
+ * falls through to the store, so a store literally named like a
2438
+ * run id binds by its exact spelling only when it does NOT match
2439
+ * the grammar. Runs between phase 1 (the doc validated) and phase
2440
+ * 2 (the graph composed) — a refusal names the field, never a
2441
+ * zombie slot. */
2442
+ resolveUpscaleChainRunIds(p1) {
2443
+ const bag = p1.params?.["upscale"];
2444
+ if (!Array.isArray(bag) || bag.length === 0)
2445
+ return p1;
2446
+ const resolved = [];
2447
+ let changed = false;
2448
+ for (const entry of bag) {
2449
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
2450
+ resolved.push(entry);
2451
+ continue;
2452
+ }
2453
+ const rec = entry;
2454
+ const chainRun = rec["chain_run"];
2455
+ if (typeof chainRun !== "string" || !ESTATE_RUN_ID_RE.test(chainRun)) {
2456
+ // a store spelling (or a shape the upscale arm's own
2457
+ // blank-seat refusal owns): byte-untouched, zero registry reads
2458
+ resolved.push(entry);
2459
+ continue;
2460
+ }
2461
+ const store = this.chainStoreNameOf(chainRun);
2462
+ if (store === null) {
2463
+ throw toRemoteError(refusal(400, "runs/chain-run-unresolved: run \"" + chainRun + "\" left no chain store — " +
2464
+ "plain films don't checkpoint (a film's windows join by file; no scene latents " +
2465
+ "survive). Bind a swap/repair/extend run's chain store (its run row carries " +
2466
+ "chain_store), or re-press the film through a chain seat first", "invalid_request"));
2467
+ }
2468
+ resolved.push({ ...rec, chain_run: store });
2469
+ changed = true;
2470
+ }
2471
+ if (!changed)
2472
+ return p1;
2473
+ return { ...p1, params: { ...p1.params, upscale: resolved } };
2474
+ }
2475
+ /** The store name a run row carries (the registrar's stamp), or
2476
+ * null: the live map first, the durable _flow.json on its miss —
2477
+ * the same two faces the status door reads. */
2478
+ chainStoreNameOf(runId) {
2479
+ const live = this.liveRun(runId);
2480
+ const stages = live !== undefined
2481
+ ? live.stages
2482
+ : this.diskRunRow(runId)?.row["stages"];
2483
+ if (!Array.isArray(stages))
2484
+ return null;
2485
+ for (const st of stages) {
2486
+ if (st === null || typeof st !== "object" || Array.isArray(st))
2487
+ continue;
2488
+ const ro = st["result_outputs"];
2489
+ if (ro === null || typeof ro !== "object" || Array.isArray(ro))
2490
+ continue;
2491
+ const store = ro["chain_store"];
2492
+ if (store === null || typeof store !== "object" || Array.isArray(store))
2493
+ continue;
2494
+ const name = store["run_name"];
2495
+ if (typeof name === "string" && name !== "")
2496
+ return name;
2497
+ }
2498
+ return null;
2499
+ }
2064
2500
  async status(runId, signal, includeLog = false) {
2065
2501
  signal.throwIfAborted();
2066
2502
  const run = this.liveRun(runId);
@@ -2094,6 +2530,11 @@ export class RunsRuntimeService extends Service {
2094
2530
  // the map row now reads the settled verdict.
2095
2531
  if (this.resyncSettledTruth(run)) {
2096
2532
  const disk = this.diskRunRow(runId);
2533
+ /* v8 ignore next -- the synchronous re-read of the row the
2534
+ * resync just adopted: no await sits between the resync's own
2535
+ * read and this one, so the durable row cannot vanish
2536
+ * mid-tick in any seat — the undefined leg is the belt for a
2537
+ * torn durable write between the two reads. */
2097
2538
  if (disk !== undefined) {
2098
2539
  return withStageReports({ ...enrichDiskRow(disk.row), from_disk: true, queue_position: this.core.queuePosition(run.runId), served_from: disk.root }, sidecarReaderFor(disk.dir));
2099
2540
  }
@@ -2123,8 +2564,14 @@ export class RunsRuntimeService extends Service {
2123
2564
  // prefixing runId again served `<run-id>/<run-id>/<rel>` —
2124
2565
  // the receipt printed a path that exists nowhere. Relativize
2125
2566
  // off the RUN DIR: the join restores exactly <run-id>/<rel>.
2126
- artifacts: [...run.artifacts].map((a) => a.startsWith("/")
2127
- ? [run.runId, relative(join(outRootFor(this.ctx.queue.stateRoot, run.testFlag), run.runId), a)].join("/")
2567
+ artifacts: [...run.artifacts].map((a) =>
2568
+ // isAbsolute, not startsWith("/"): a Windows-harvested
2569
+ // artifact is drive-rooted — the posix-only gate served it
2570
+
2571
+ // tail re-spells to posix: the wire face never carries a
2572
+ // native separator.
2573
+ isAbsolute(a)
2574
+ ? [run.runId, wireTail(relative(join(outRootFor(this.ctx.queue.stateRoot, run.testFlag), run.runId), a))].join("/")
2128
2575
  : a),
2129
2576
  error: run.error,
2130
2577
  // F-6(b): admission warnings ride the row (additive — older
@@ -2146,6 +2593,11 @@ export class RunsRuntimeService extends Service {
2146
2593
  // fallback spreads the sidecar row, which carries it).
2147
2594
  // Absent on inline runs (no card composed).
2148
2595
  ...(run.graphReceipt !== undefined ? { graph_receipt: run.graphReceipt } : {}),
2596
+ // THE ATTRIBUTION MARKER, SERVED (D3-07, same law: a missed
2597
+ // stamp-back rides the live row — additive, same spelling as
2598
+ // the sidecar; absent means the stamp landed or was never
2599
+ // owed).
2600
+ ...(run.attribution !== undefined && run.attribution !== "" ? { attribution: run.attribution } : {}),
2149
2601
 
2150
2602
  // exact card + authoring body that ran rides the live row —
2151
2603
  // restore rebuilds the recipe from THIS, never from the
@@ -2275,7 +2727,7 @@ export class RunsRuntimeService extends Service {
2275
2727
  if (run.status === "running")
2276
2728
  run.status = "stopping";
2277
2729
  run.stopFlag = true;
2278
- notifyRunChanged(runId);
2730
+ notifyRunChanged(run.runId);
2279
2731
  // The interrupt rides the injected engine service when the
2280
2732
  // seat exists (best-effort — the flag is the authority).
2281
2733
  try {
@@ -2291,6 +2743,98 @@ export class RunsRuntimeService extends Service {
2291
2743
  }
2292
2744
  return { run_id: runId, status: "stopping" };
2293
2745
  }
2746
+ /** THE ATTRIBUTION DOOR (F3 D3-07, the 15 s bound's third burn —
2747
+ * RIG s_94: a green run whose cards-tab stamp died at the bench
2748
+ * plane's bound). The stamp-back's bounded retry lives client-side
2749
+ * (melite-flow); when every take dies, THIS door carries the miss
2750
+ * on the run row — a different plane than the wedged drafts
2751
+ * PATCH, so the fact lands even when the stamp could not. The
2752
+ * status door and the press receipt then answer "completed — NOT
2753
+ * shown on the tab (stamp missed; re-stamp)" instead of a bare
2754
+ * done. Idempotent: a re-stamp that landed clears it
2755
+ * (value "" unstamps), the persist is best-effort by the
2756
+ * claim/settle law, and the change rides notifyRunChanged so the
2757
+ * tab's poller re-fires on the truth. */
2758
+ async attribute(runId, value, signal) {
2759
+ signal.throwIfAborted();
2760
+ const run = this.liveRun(runId);
2761
+ if (run === undefined) {
2762
+ // the same miss voice as stop: the door names the trees it
2763
+ // searched, never a bare unknown.
2764
+ throw new RemoteError("runs/run-unknown", "unknown run_id " + JSON.stringify(runId) + " " +
2765
+ searchedVoice(this.ctx.queue.stateRoots), { runId });
2766
+ }
2767
+ if (value === "")
2768
+ delete run.attribution;
2769
+ else
2770
+ run.attribution = value;
2771
+ notifyRunChanged(run.runId);
2772
+ await attributionPersist(run);
2773
+ return { run_id: runId, attribution: run.attribution ?? "" };
2774
+ }
2775
+ /** THE OUTPUT-RENAME DOOR (queue 12 Phase B): a settled run's
2776
+ * gallery row gets a new display `label`, post-run — the output_name
2777
+ * mint at settle named the rows once; this door owns every rename
2778
+ * after. The `name` (the machine file key the media route and every
2779
+ * dedup law ride) NEVER moves — the patch rewrites the addressed
2780
+ * row's label alone: no sibling renumbering, no `stem · 2…n`
2781
+ * auto-repair; a caller with several rows to rename patches each
2782
+ * row it wants. Guards speak before any write: unknown run
2783
+ * (runs/run-unknown, the searched-trees voice), a live row (rename
2784
+ * waits for settle), an empty/whitespace label, an out-of-range
2785
+ * stage or gallery index. The patch lands in the live row, the
2786
+ * change rides notifyRunChanged (the tab's poller re-fires), and
2787
+ * the sidecar rewrite persists it (the disk fallback and every
2788
+ * boot re-read spread the new label). */
2789
+ async renameOutput(runId, stageIndex, galleryIndex, label, signal) {
2790
+ signal.throwIfAborted();
2791
+ const run = this.liveRun(runId);
2792
+ if (run === undefined) {
2793
+ // the same miss voice as stop/attribute: the door names the
2794
+ // trees it searched, never a bare unknown.
2795
+ throw new RemoteError("runs/run-unknown", "unknown run_id " + JSON.stringify(runId) + " " +
2796
+ searchedVoice(this.ctx.queue.stateRoots), { runId });
2797
+ }
2798
+ if (run.status === "queued" || run.status === "running" || run.status === "stopping") {
2799
+ // THE SETTLE GUARD: the gallery is the settle's own build — a
2800
+ // rename pressed mid-execution would patch rows the executor
2801
+ // is still minting. The refusal names the wait, never a silent
2802
+ // no-op.
2803
+ throw new RemoteError("runs/invalid-request", "run " + JSON.stringify(runId) + " still executing — rename waits for settle", { loc: "run_id", expected: "a settled run (completed/failed/stopped)", got: run.status });
2804
+ }
2805
+ const trimmed = label.trim();
2806
+ if (trimmed === "") {
2807
+ throw new RemoteError("runs/invalid-request", "rename refused — the label is empty (whitespace is emptiness; a gallery row needs display words)", { loc: "label", expected: "non-empty text", got: JSON.stringify(label) });
2808
+ }
2809
+ const stage = run.stages[stageIndex];
2810
+ if (stage === undefined) {
2811
+ throw new RemoteError("runs/invalid-request", "stage index " + String(stageIndex) + " out of range — run " + JSON.stringify(runId) +
2812
+ " carries " + String(run.stages.length) + " stage(s)", { loc: "stage", expected: "0.." + String(run.stages.length - 1), got: String(stageIndex) });
2813
+ }
2814
+ const gallery = stage["gallery"];
2815
+ if (!Array.isArray(gallery) || gallery.length === 0) {
2816
+ throw new RemoteError("runs/invalid-request", "stage " + String(stageIndex) + " carries no gallery — nothing to rename", { loc: "gallery", expected: "a settled stage with artifacts", got: String(stageIndex) });
2817
+ }
2818
+ if (!Number.isInteger(galleryIndex) || galleryIndex < 0 || galleryIndex >= gallery.length) {
2819
+ throw new RemoteError("runs/invalid-request", "gallery index " + String(galleryIndex) + " out of range — stage " + String(stageIndex) +
2820
+ " carries " + String(gallery.length) + " artifact row(s)", { loc: "gallery", expected: "0.." + String(gallery.length - 1), got: String(galleryIndex) });
2821
+ }
2822
+ const row = gallery[galleryIndex];
2823
+ const name = typeof row["name"] === "string" ? row["name"] : "";
2824
+ // label-only patch: the row keeps its name and position; the
2825
+ // spread rebuilds the row with exactly one field changed.
2826
+ gallery[galleryIndex] = { ...row, label: trimmed };
2827
+ notifyRunChanged(run.runId);
2828
+ await galleryLabelPersist(run);
2829
+ return {
2830
+ run_id: runId,
2831
+ stage: stageIndex,
2832
+ gallery: galleryIndex,
2833
+ name,
2834
+ label: trimmed,
2835
+ status: run.status,
2836
+ };
2837
+ }
2294
2838
  /** The live map (the queue seat's core registry — rich rows). */
2295
2839
  liveRun(runId) {
2296
2840
  return this.core.runs.get(runId);
@@ -2410,6 +2954,12 @@ export class RunsRuntimeService extends Service {
2410
2954
  if (pressKey === undefined)
2411
2955
  return;
2412
2956
  const pending = this.pendingPresses.get(pressKey);
2957
+ /* v8 ignore next -- the minter holds its own reservation: the
2958
+ * key lands in pendingPresses synchronously at reservePress
2959
+ * (before the first await) and leaves in the finally AFTER this
2960
+ * resolve — no path deletes between, so a defined key always
2961
+ * finds its waiter here. The belt for a future caller that
2962
+ * resolves without reserving. */
2413
2963
  if (pending !== undefined)
2414
2964
  pending.resolve(summary);
2415
2965
  }
@@ -2419,6 +2969,11 @@ export class RunsRuntimeService extends Service {
2419
2969
 
2420
2970
  failPress(pressKey, error) {
2421
2971
  const pending = this.pendingPresses.get(pressKey);
2972
+ /* v8 ignore next -- same reservation invariant as resolvePress
2973
+ * above: the failing minter's own key is still held (the
2974
+ * finally deletes AFTER this reject), so the waiter is always
2975
+ * found — the belt for a future caller that fails a key it
2976
+ * never reserved. */
2422
2977
  if (pending !== undefined)
2423
2978
  pending.reject(error);
2424
2979
  }
@@ -2451,6 +3006,9 @@ export class RunsRuntimeService extends Service {
2451
3006
  this.presses.set(pressKey, runId);
2452
3007
  while (this.presses.size > RunsRuntimeService.PRESS_MEMORY_MAX) {
2453
3008
  const oldest = this.presses.keys().next();
3009
+ /* v8 ignore next -- the map holds >0 entries whenever the loop
3010
+ * runs (size > PRESS_MEMORY_MAX > 0), so next() always yields —
3011
+ * the sweep mirror's identical guard carries the same ignore. */
2454
3012
  if (oldest.done)
2455
3013
  break;
2456
3014
  this.presses.delete(oldest.value);
@@ -2535,13 +3093,11 @@ export class RunsRuntimeService extends Service {
2535
3093
  if (laneMiss !== null) {
2536
3094
  run.status = "failed";
2537
3095
  run.error = laneMiss.message;
2538
- for (const stage of run.stages) {
2539
- const st = stage["status"];
2540
- if (st === "queued" || st === "pending" || st === undefined) {
2541
- stage["status"] = "failed";
2542
- stage["error"] = laneMiss.message;
2543
- }
2544
- }
3096
+ // THE PER-ROW TRUTH STAMP (F2): a claim refusal is the
3097
+ // RUN's verdict — nothing ever answered. The sole stage
3098
+ // owns the cause; unanswered peers read stopped and
3099
+ // never carry the borrowed text.
3100
+ stampUnansweredRows(run, laneMiss.message, false);
2545
3101
  await claimPersist(run);
2546
3102
  await this.settle(run);
2547
3103
  continue;
@@ -2563,11 +3119,23 @@ export class RunsRuntimeService extends Service {
2563
3119
  const roots = { stateRoot: this.ctx.queue.stateRoot, repoRoot: resolveRepoRoot() };
2564
3120
  let initialMiss = null;
2565
3121
  for (const key of fileKeys) {
3122
+ /* v8 ignore next -- initialFileKeys is string[]-typed on
3123
+ * the run row and every live row arrives through typed
3124
+ * construction (door, replay, pump) — a non-string key is
3125
+ * unconstructible through every seat that stamps it; the
3126
+ * unknown read is torn-state defense for durable
3127
+ * variance. */
2566
3128
  if (typeof key !== "string")
2567
3129
  continue;
2568
3130
  const raw = run.initials[key];
3131
+ /* v8 ignore next -- the press gate normalizes photo/glb
3132
+ * initials to strings (normalizedInitialValue) or refuses
3133
+ * the press, and the replay path re-runs that same
3134
+ * extractor — so a stamped key carries a string on every
3135
+ * live row. Absent/linked values are the merged worker's
3136
+ * own seat (it resolves them), never the probe's. */
2569
3137
  if (typeof raw !== "string")
2570
- continue; // merged-worker arm owns absent/linked values
3138
+ continue;
2571
3139
  if (!initialFileCandidates(raw.trim(), roots).some((cand) => isFile(cand))) {
2572
3140
  initialMiss = "initial " + JSON.stringify(key) + " is not on disk (" + raw.trim() + ")";
2573
3141
  break;
@@ -2576,13 +3144,10 @@ export class RunsRuntimeService extends Service {
2576
3144
  if (initialMiss !== null) {
2577
3145
  run.status = "failed";
2578
3146
  run.error = initialMiss;
2579
- for (const stage of run.stages) {
2580
- const st = stage["status"];
2581
- if (st === "queued" || st === "pending" || st === undefined) {
2582
- stage["status"] = "failed";
2583
- stage["error"] = initialMiss;
2584
- }
2585
- }
3147
+ // THE PER-ROW TRUTH STAMP (F2): same law as the lane
3148
+ // refusal above — the run owns the verdict, the sole
3149
+ // stage carries it, peers read stopped.
3150
+ stampUnansweredRows(run, initialMiss, false);
2586
3151
  await claimPersist(run);
2587
3152
  await this.settle(run);
2588
3153
  continue;
@@ -2619,12 +3184,10 @@ export class RunsRuntimeService extends Service {
2619
3184
  // keeps claiming: the queue may delay a run, never
2620
3185
  // strand it.
2621
3186
  const text = "run seat escape (pump settle): " + errText(exc);
2622
- for (const stage of run.stages) {
2623
- if (stage["status"] === "running") {
2624
- stage["status"] = "failed";
2625
- stage["error"] = text;
2626
- }
2627
- }
3187
+ // THE PER-ROW TRUTH STAMP (F2): the escape is the run's
3188
+ // receipt — the sole stage carries it, unanswered peers
3189
+ // read stopped with no borrowed text.
3190
+ stampUnansweredRows(run, text, false);
2628
3191
  run.status = "failed";
2629
3192
  run.error = text;
2630
3193
  try {
@@ -2763,7 +3326,10 @@ function benchStageIdOf(benchDoc, skeleton, claimed, pressedDraft) {
2763
3326
  * The result face: run_id always; the run-relative media url of the
2764
3327
  * stage's own output when one exists (the husk clobber's other
2765
3328
  * half — a bookkeeping mirror never blanks a hero it can name); the
2766
- * error voice (stage's, else the run's) when the word is failed. */
3329
+ * error voice is the stage's OWN error, never the run's — the
3330
+ * pass-level cause rides the run doc (run_status answers for the
3331
+ * pass), and a row that borrowed it would name another stage's
3332
+ * cause (qa8 F43, the per-row status law). */
2767
3333
  export function settleMirrorPatches(run) {
2768
3334
  const out = [];
2769
3335
  for (const stage of run.stages) {
@@ -2786,7 +3352,7 @@ export function settleMirrorPatches(run) {
2786
3352
  : undefined;
2787
3353
  const voice = typeof stage["error"] === "string" && stage["error"] !== ""
2788
3354
  ? stage["error"]
2789
- : word === "failed" && typeof run.error === "string" ? run.error : undefined;
3355
+ : undefined;
2790
3356
  out.push({
2791
3357
  stageId,
2792
3358
  patch: {