@melite/estate-queue 0.1.4-alpha → 0.1.5-pre-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +55 -0
  2. package/lib/bench.d.ts +19 -11
  3. package/lib/bench.js +47 -57
  4. package/lib/cardsArmError.d.ts +45 -2
  5. package/lib/cardsArmError.js +28 -4
  6. package/lib/cardsCompose.d.ts +13 -1
  7. package/lib/cardsCompose.js +109 -61
  8. package/lib/cardsDangling.d.ts +2 -2
  9. package/lib/cardsDangling.js +82 -37
  10. package/lib/cardsFacts.d.ts +16 -3
  11. package/lib/cardsFacts.js +14 -0
  12. package/lib/cardsLanes.d.ts +12 -2
  13. package/lib/cardsLanes.js +73 -10
  14. package/lib/cardsRegistry.d.ts +93 -5
  15. package/lib/cardsRegistry.js +323 -54
  16. package/lib/cardsVariant.d.ts +10 -1
  17. package/lib/cardsVariant.js +66 -13
  18. package/lib/discloseRegistry.d.ts +6 -5
  19. package/lib/discloseRegistry.js +11 -9
  20. package/lib/flowsData.d.ts +67 -12
  21. package/lib/flowsData.js +230 -104
  22. package/lib/flowsFamilyCompose.d.ts +5 -8
  23. package/lib/flowsFamilyCompose.js +13 -13
  24. package/lib/flowsParamsOverlay.d.ts +55 -0
  25. package/lib/flowsParamsOverlay.js +197 -0
  26. package/lib/flowsRegistryRows.d.ts +3 -1
  27. package/lib/flowsRegistryRows.js +148 -6
  28. package/lib/index.d.ts +0 -3
  29. package/lib/index.js +14 -5
  30. package/lib/lifecycleLatch.d.ts +16 -0
  31. package/lib/lifecycleLatch.js +42 -0
  32. package/lib/loadPlane.d.ts +3 -2
  33. package/lib/loadPlane.js +25 -8
  34. package/lib/loadRegistry.js +1 -1
  35. package/lib/manageOps.d.ts +8 -2
  36. package/lib/manageOps.js +26 -6
  37. package/lib/managePlane.d.ts +31 -0
  38. package/lib/managePlane.js +360 -85
  39. package/lib/manageProbe.d.ts +1 -10
  40. package/lib/manageProbe.js +18 -7
  41. package/lib/manageRegistry.d.ts +42 -4
  42. package/lib/manageRegistry.js +45 -7
  43. package/lib/mediaKinds.d.ts +1 -1
  44. package/lib/mediaKinds.js +1 -1
  45. package/lib/queue.js +14 -10
  46. package/lib/queueCore.d.ts +7 -4
  47. package/lib/queueCore.js +9 -5
  48. package/lib/queueLifecycle.d.ts +0 -24
  49. package/lib/queueLifecycle.js +9 -63
  50. package/lib/queueLock.d.ts +8 -2
  51. package/lib/queueLock.js +9 -6
  52. package/lib/queueSidecar.d.ts +4 -0
  53. package/lib/queueSidecar.js +1 -0
  54. package/lib/queueSubmit.d.ts +61 -10
  55. package/lib/queueSubmit.js +120 -46
  56. package/lib/queueSweep.js +13 -2
  57. package/lib/runsChange.d.ts +8 -0
  58. package/lib/runsChange.js +21 -5
  59. package/lib/runsErrorCodes.d.ts +1 -1
  60. package/lib/runsErrorCodes.js +33 -0
  61. package/lib/runsExecute.d.ts +26 -0
  62. package/lib/runsExecute.js +143 -5
  63. package/lib/runsGates.js +4 -3
  64. package/lib/runsList.js +13 -19
  65. package/lib/runsRefusalVoices.js +52 -0
  66. package/lib/runsRegistry.d.ts +105 -7
  67. package/lib/runsRegistry.js +744 -100
  68. package/lib/runsSourceEcho.d.ts +27 -0
  69. package/lib/runsSourceEcho.js +84 -18
  70. package/lib/runsStart.d.ts +56 -14
  71. package/lib/runsStart.js +184 -45
  72. package/lib/runsTypes.d.ts +35 -0
  73. package/lib/runsTypes.js +7 -0
  74. package/lib/runsValidateArms.js +61 -7
  75. package/lib/runsValidateServe.d.ts +2 -2
  76. package/lib/runsValidateServe.js +26 -4
  77. package/lib/runsValidateShared.d.ts +1 -1
  78. package/lib/runsValidateStages.d.ts +10 -3
  79. package/lib/runsValidateStages.js +23 -3
  80. package/lib/service.d.ts +24 -6
  81. package/lib/service.js +19 -11
  82. package/lib/skillFs.d.ts +9 -4
  83. package/lib/skillFs.js +12 -14
  84. package/lib/skillPlane.d.ts +3 -2
  85. package/lib/skillPlane.js +12 -6
  86. package/lib/skillRegistry.js +1 -1
  87. package/lib/skillRows.d.ts +4 -3
  88. package/lib/skillRows.js +14 -12
  89. package/lib/toolProjection.d.ts +1 -1
  90. package/lib/toolProjection.js +1 -1
  91. package/package.json +8 -7
  92. package/lib/runStatus.d.ts +0 -7
  93. package/lib/runStatus.js +0 -21
@@ -1,4 +1,4 @@
1
- import { mediaKindOf } from "./mediaKinds.js";
1
+ import { isEstateSidecarName, mediaKindOf } from "./mediaKinds.js";
2
2
  // runsRegistry.ts — the live-run registry as a HOST Cordis service
3
3
  // (REBUILD-6, gateway kill). Owns the rich run map + the serial
4
4
  // pump over the queue seat's QueueCore (one machine — the door's
@@ -10,7 +10,7 @@ import { mediaKindOf } from "./mediaKinds.js";
10
10
  // delegating to this seat. Failures throw the protocol's ONE
11
11
  // RemoteError with the runs/* codes declared HERE (the producing
12
12
  // package, next to the throws).
13
- import { CARD_PLANE_ENGINE } from "@melite/contracts/benchStage";
13
+ import { CARD_PLANE_ENGINE, RUN_MEDIA_PREFIX } from "@melite/contracts/benchStage";
14
14
  import { join, relative } from "node:path";
15
15
  import { Service } from "@deepseek-ai/cordis";
16
16
  import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
@@ -18,21 +18,28 @@ import { stageEngineOf } from "@melite/contracts/benchStage";
18
18
  import { benchResultDefects } from "@melite/contracts/benchResult";
19
19
  import { remoteErrorOf } from "@deepseek-ai/dsh-typert-protocol";
20
20
  import { needComfyUI } from "@melite/comfyui-cordis";
21
- import { expandRegistryFlow, extractRequestInitials, getRegistryFlow, registryFlowToInline, inlineStagesNameCards, registryInitialsError, } from "./flowsData.js";
21
+ import { expandRegistryFlow, extractRequestInitials, initialFileCandidates, registryFlowToInline, inlineStagesNameCards, registryInitialsError, } from "./flowsData.js";
22
+ import { isFile } from "./skillFs.js";
23
+ import { kindsOk } from "./runsValidateStages.js";
24
+ import { replayJudgeRows } from "./runsStart.js";
25
+ import { FlowError } from "./runsValidateShared.js";
22
26
  import { composeFamilyStages, liveFamilySeat } from "./flowsFamilyCompose.js";
23
27
  import { resolveRepoRoot } from "@melite/comfyui-cordis";
24
28
  import { loadEndpointConfig } from "@melite/comfyui-cordis";
25
29
  import { fetchEngineMem, filmLoadOf, filmMemoryWarn } from "./filmMemoryWarn.js";
26
- import { rootsManifest, searchedVoice } from "./rootsManifest.js";
27
- import { newRunId, outRootFor, pipelineOf, strictBodyCheck, draftIdOk, planResurrect, bootSweep, appendLedger, refusal } from "./queue.js";
30
+ import { searchedVoice } from "./rootsManifest.js";
31
+ import { newRunId, outRootFor, pipelineOf, strictBodyCheck, planResurrect, bootSweep, appendLedger, refusal, walkSubmitEnvelope } from "./queue.js";
28
32
  import { cardRefusal, toRemoteError, refusePreview } from "./runsRefusalVoices.js";
33
+ import { lifecycleInFlight } from "./lifecycleLatch.js";
34
+ import { lanePresenceRefusal } from "./cardsLanes.js";
29
35
  import { installRunsChangeSeam, notifyRunChanged, onRunChange } from "./runsChange.js";
30
36
  import { coerceSnapshotBody } from "./runsValidateStages.js";
37
+ import { applyFlowParamsOverride, overlayDecls } from "./flowsParamsOverlay.js";
31
38
  export { toRemoteError } from "./runsRefusalVoices.js";
32
39
  import { readFileSync } from "node:fs";
33
40
  import { CardArmError, } from "./cardsRegistry.js";
34
41
  import { FLOW_ID_RE } from "./runsGates.js";
35
- import { compileFlowInline, envelopeRefusal, registerCompiledRun, selectSubmitDoor, unknownDraftRefusal, } from "./runsStart.js";
42
+ import { compileFlowInline, registerCompiledRun, selectSubmitDoor, } from "./runsStart.js";
36
43
  import { listRunsAcross, parseIntOrNull } from "./runsList.js";
37
44
  import { claimPersist, errText, runLogTail, settlePersist, RUN_STATUSES, } from "./runsTypes.js";
38
45
  import { runOne, runEngine as runEngineOf } from "./runsExecute.js";
@@ -73,7 +80,13 @@ export function enrichDiskRow(row) {
73
80
  // gallery while an .avif was hero'd but unclassifiable. The
74
81
  // classifier is the contract's mediaKindOf now, shared with the
75
82
  // run list and the gallery client — the seats cannot disagree.
83
+
84
+ // text kind now (SaveText's own format set), so classification
85
+
86
+ // law does. `_request.json` is a sidecar by NAME, never media;
87
+ // a real `result.json` artifact stays eligible.
76
88
  const names = [...new Set(artifacts.map(relative))]
89
+ .filter((name) => !isEstateSidecarName(name))
77
90
  .filter((name) => mediaKindOf(name) !== undefined);
78
91
  if (names.length === 0)
79
92
  return row;
@@ -286,6 +299,10 @@ export function benchWiring(benchDoc) {
286
299
  return { cross, self };
287
300
  }
288
301
  export class RunsRuntimeService extends Service {
302
+
303
+
304
+
305
+ static PRESS_MEMORY_MAX = 64;
289
306
  static inject = ["queue", "draftsRemote", "cardRegistry"];
290
307
  /** The pump reentrancy guard (door-verbatim — a public field:
291
308
  * cordis proxies services, and private #fields do not cross the
@@ -363,7 +380,11 @@ export class RunsRuntimeService extends Service {
363
380
  })();
364
381
  if (comfy !== undefined) {
365
382
  for (const run of inFlight) {
366
- void comfy.stopForRunDir(run.dir).catch(() => { });
383
+ void comfy.stopForRunDir(run.dir).catch((e) => {
384
+ // named (audit N-S5): an interrupt outage is
385
+ // observable; the stopFlags still converge
386
+ console.log("[estate-queue] teardown interrupt failed:", e instanceof Error ? e.message : String(e));
387
+ });
367
388
  }
368
389
  }
369
390
  }
@@ -421,6 +442,7 @@ export class RunsRuntimeService extends Service {
421
442
  // the orphan list silently.
422
443
  const plan = planResurrect(stateRoot, undefined, undefined, () => true);
423
444
  const revived = [];
445
+ const deferred = [];
424
446
  for (const runId of plan.order) {
425
447
  if (disposed())
426
448
  return revived;
@@ -446,13 +468,24 @@ export class RunsRuntimeService extends Service {
446
468
  });
447
469
  }
448
470
  catch (exc) {
471
+ // THE TRANSIENT REFUSAL (round-20 lifecycle audit Q2): a
472
+ // teardown holding the latch at replay time is not a poison
473
+ // request — settling the row failed would be permanent poison
474
+ // for a refusal a retry cures. The row stays queued, loudly,
475
+ // and rides the sweep's live set so the same pass cannot
476
+ // retire what it just deferred.
477
+ if (exc instanceof RemoteError && exc.code === "runs/lifecycle-inflight") {
478
+ console.warn(`[runs] replay of ${runId} deferred: a lifecycle teardown is in flight (the row stays queued)`);
479
+ deferred.push(runId);
480
+ continue;
481
+ }
449
482
  // LOUD, in place: the sidecar moves to failed with the
450
483
  // door's refusal text — a poison request can never haunt
451
484
  // the next boot as "queued" forever.
452
485
  await this.settleReplayRefusal(stateRoot, runId, errText(exc));
453
486
  }
454
487
  }
455
- await bootSweep(stateRoot, revived);
488
+ await bootSweep(stateRoot, [...revived, ...deferred]);
456
489
  if (revived.length > 0)
457
490
  this.kick();
458
491
  return revived;
@@ -547,13 +580,41 @@ export class RunsRuntimeService extends Service {
547
580
  * through exactly ONE implementation and one refusal voice).
548
581
  * `label` names the seat in a refusal ("bench stage " / "flow
549
582
  * stage "). */
550
- async composeCardStageRow(row, id, runId, label) {
583
+ async composeCardStageRow(row, id, runId, label,
584
+
585
+
586
+
587
+
588
+ famsOut) {
551
589
  const cards = this.ctx.cardRegistry;
552
590
  const params = (typeof row["params"] === "object" && row["params"] !== null && !Array.isArray(row["params"]))
553
591
  ? { ...row["params"] }
554
592
  : {};
555
593
  const card = String(row["card"] ?? "");
556
- const mid = String(params["model"] ?? row["service"] ?? "");
594
+ // STROKE 3'S FALLBACK (the validate walk's own shape —
595
+ // runsValidateArms: a family-less card stage composes by its OWN
596
+ // card id — mid alone, never an injected body.model, which would
597
+ // hit the board check before prepareCardParams resolved the
598
+ // card-unit arm). The old `?? ""` handed prepareCardParams an
599
+ // empty mid — "model id \"\" is not a legal identifier" on the
600
+ // body-to-somax rig hop and every family-less flow stage after
601
+
602
+
603
+ // effective routing key rode an EXPLICIT spelling — params.model
604
+ // or the row's service key — the compose lanes that value while
605
+ // the admission judge reads body.model only, so a service-bearing
606
+ // row ran in the routing family's lane UNGATED by the board law
607
+ // (live receipt: the tts+krea-2 row composing image-gen's voice).
608
+ // The stamp hands the judge the value that lanes. The ?? card
609
+ // fallback is NEVER stamped: for a family-less card mid is the
610
+ // card-unit alias's own spelling (mid alone; the GUI's explicit
611
+ // card-id press rides the alias arm at admitStageModel), and a
612
+ // boarded card with no model picked keeps its honest phase-2
613
+ // refusal ("requires a model id").
614
+ const service = typeof row["service"] === "string" && row["service"] !== "" ? row["service"] : undefined;
615
+ const mid = String(params["model"] ?? service ?? card);
616
+ if (params["model"] === undefined && service !== undefined)
617
+ params["model"] = service;
557
618
  let p1;
558
619
  let composed;
559
620
  try {
@@ -593,12 +654,68 @@ export class RunsRuntimeService extends Service {
593
654
  }
594
655
  throw e;
595
656
  }
657
+ const stageOutputs = (typeof row["outputs"] === "object" && row["outputs"] !== null && !Array.isArray(row["outputs"])
658
+ && Object.keys(row["outputs"]).length > 0)
659
+ ? { ...row["outputs"] }
660
+ // THE BENCH'S OUTPUTS WIN ONLY WHEN THEY CARRY CHANNELS
661
+ // (the work audit's R1 — a regression the card-ports law
662
+ // introduced here): a card stage's stored outputs are `{}` by
663
+ // design (the channels derive from the card's own ports at
664
+ // compose), and this line kept that `{}` verbatim — so the
665
+ // merged worker published ZERO channels and every $spell
666
+ // consumer downstream got nothing where the old fabricated
667
+ // `{default: 'image'}` at least published one. An EMPTY
668
+ // channel map means "unfilled": the compose's own ports
669
+ // answer, exactly as the single-card path already does.
670
+ : composed.outputs;
671
+ // THE OUTPUT RENAME FOLLOWS THE BINDINGS (the run-9f8bd60f8cb8
672
+
673
+ // channels (outputs {body: "mesh"} over the card's own
674
+ // {default: "mesh"}), but params.output_nodes kept the card's
675
+ // naming — the merged worker then bound the artifact under
676
+ // "default" while the declared channel was "body": the unbound
677
+ // ext sweep published "body" fine, and the receipt gate refused
678
+ // binding channel "default" as produced-no-artifact although the
679
+ // GLB sat fetched on disk. When the row renames, the bindings
680
+ // rename with it — kind-matched, one-to-one; an ambiguous kind
681
+ // (two declared channels of one kind) leaves the card naming
682
+ // verbatim and the receipt gate names the ambiguity loud.
683
+ const cardOuts = (composed.outputs ?? {});
684
+ const cardNodes = (composed.outputNodes ?? {});
685
+ const rowChannelsByKind = {};
686
+ for (const [ch, kind] of Object.entries(stageOutputs)) {
687
+ (rowChannelsByKind[String(kind)] ??= []).push(ch);
688
+ }
689
+ const renamedNodes = {};
690
+ let renamedAny = false;
691
+ for (const [ch, node] of Object.entries(cardNodes)) {
692
+ const targets = rowChannelsByKind[String(cardOuts[ch] ?? "")] ?? [];
693
+ if (targets.length === 1 && stageOutputs[ch] === undefined) {
694
+ renamedNodes[targets[0]] = node;
695
+ renamedAny = true;
696
+ }
697
+ else {
698
+ renamedNodes[ch] = node;
699
+ }
700
+ }
701
+ // benchExpected: the derivation law's bench half (J-E1 comment
702
+ // at the spread below) — the card's declared input kinds fill the
703
+ // absent slots, the hand-written row wins per input.
704
+ const cardDef = cards.defsSync().get(card);
705
+ const cardInputs = cardDef?.flowKinds?.inputs;
706
+ const cardAliases = cardDef?.flowKinds?.legacyAliases;
707
+ const rowExpected = (typeof row["expected"] === "object" && row["expected"] !== null && !Array.isArray(row["expected"]))
708
+ ? row["expected"]
709
+ : {};
710
+ const benchExpected = cardInputs === undefined && cardAliases === undefined
711
+ ? { ...rowExpected }
712
+ : { ...(cardInputs ?? {}), ...(cardAliases ?? {}), ...rowExpected };
596
713
  const stage = {
597
714
  id,
598
715
  engine: stageEngineOf(row),
599
716
  params: {
600
717
  workflow: composed.graph,
601
- output_nodes: composed.outputNodes,
718
+ output_nodes: (renamedAny ? renamedNodes : cardNodes),
602
719
  },
603
720
 
604
721
  // `expected` for its kindsOk walk and defaults an absent bag to
@@ -606,29 +723,25 @@ export class RunsRuntimeService extends Service {
606
723
  // kind assertion on its own inputs. The registry rows declare
607
724
  // them (audio-native-tts: { text: "text" }), and the check is
608
725
  // theirs, not the composer's to discard.
609
- ...(typeof row["expected"] === "object" && row["expected"] !== null && !Array.isArray(row["expected"])
610
- ? { expected: { ...row["expected"] } }
611
- : {}),
726
+ //
727
+
728
+ // law runs at the compose too, not only in validate's kindsOk —
729
+ // a bench row carries inputs with no hand-written expected, and
730
+ // an empty bag queued the run with no kind assertion on its own
731
+ // wired inputs. The card's declared input kinds (legacy aliases
732
+ // included, the naming law's lattice half) fill the absent
733
+ // slots; a hand-written row still wins per input, because the
734
+ // override exists for initials the card cannot know.
735
+ ...(Object.keys(benchExpected).length > 0 ? { expected: benchExpected } : {}),
612
736
  // THE WIRES RIDE (the whole point): the bench's own edges,
613
737
  // verbatim, for the merged worker to link.
614
738
  ...(typeof row["inputs"] === "object" && row["inputs"] !== null && !Array.isArray(row["inputs"])
615
739
  ? { inputs: { ...row["inputs"] } }
616
740
  : {}),
617
- // THE BENCH'S OUTPUTS WIN ONLY WHEN THEY CARRY CHANNELS
618
- // (the work audit's R1 — a regression the card-ports law
619
- // introduced here): a card stage's stored outputs are `{}` by
620
- // design (the channels derive from the card's own ports at
621
- // compose), and this line kept that `{}` verbatim — so the
622
- // merged worker published ZERO channels and every $spell
623
- // consumer downstream got nothing where the old fabricated
624
- // `{default: 'image'}` at least published one. An EMPTY
625
- // channel map means "unfilled": the compose's own ports
626
- // answer, exactly as the single-card path already does.
627
- outputs: (typeof row["outputs"] === "object" && row["outputs"] !== null && !Array.isArray(row["outputs"])
628
- && Object.keys(row["outputs"]).length > 0)
629
- ? { ...row["outputs"] }
630
- : composed.outputs,
741
+ outputs: stageOutputs,
631
742
  };
743
+ if (famsOut !== undefined)
744
+ famsOut[id] = p1.fam;
632
745
  return stage;
633
746
  }
634
747
 
@@ -648,7 +761,10 @@ export class RunsRuntimeService extends Service {
648
761
 
649
762
 
650
763
 
651
- async composeRegistryFlowStages(inlineDoc, runId) {
764
+ async composeRegistryFlowStages(inlineDoc, runId,
765
+
766
+
767
+ stageFams) {
652
768
  const rows = inlineDoc["stages"];
653
769
  // registryFlowToInline always projects an array of object rows, so
654
770
  // the non-array answer needs no second shape (the compile-time
@@ -664,11 +780,17 @@ export class RunsRuntimeService extends Service {
664
780
  const id = typeof row["id"] === "string" && row["id"] !== "" ? row["id"] : "s_" + String(i);
665
781
  out.push(card === ""
666
782
  ? { ...row }
667
- : await this.composeCardStageRow(row, id, runId, "flow stage "));
783
+ : await this.composeCardStageRow(row, id, runId, "flow stage ", stageFams));
668
784
  }
669
785
  return { ...inlineDoc, stages: out };
670
786
  }
671
- async composeBenchStages(benchDoc, runId) {
787
+ async composeBenchStages(benchDoc, runId,
788
+
789
+
790
+
791
+
792
+
793
+ famsOut) {
672
794
  // the sole caller arrives gated on benchWiring(...).cross being
673
795
  // non-empty, and benchWiring answers [] unless stages is an
674
796
  // array — the non-array fallback here was a dead leg, pruned
@@ -686,7 +808,7 @@ export class RunsRuntimeService extends Service {
686
808
  throw new RemoteError("runs/invalid-request", "bench stage " + JSON.stringify(id) +
687
809
  " names no card — the bench run composes card stages; an mcp/flow stage belongs in a flow, not the bench", { loc: "stages" });
688
810
  }
689
- out.push(await this.composeCardStageRow(row, id, runId, "bench stage "));
811
+ out.push(await this.composeCardStageRow(row, id, runId, "bench stage ", famsOut));
690
812
  }
691
813
  /* v8 ignore next 4 -- this bench is only composed when
692
814
  * benchWiring found a CROSS wire, and benchWiring reaches wires
@@ -722,27 +844,140 @@ export class RunsRuntimeService extends Service {
722
844
  throw error;
723
845
  }
724
846
  };
725
- // The envelope walk sits HERE (not queue.ts's sync
726
- // validateSubmitEnvelope) because the draft probe is an
727
- // AWAITED seat hop — the ORDER is preserved exactly.
728
- const checked = await this.walkEnvelope(doc, draftExists);
847
+ // The envelope walk sits HERE (the one shared walker,
848
+ // walkSubmitEnvelope — the S3 twin cure deleted the sync face)
849
+ // because the draft probe is an AWAITED seat hop — the ORDER is
850
+ // preserved exactly.
851
+ const checked = await walkSubmitEnvelope(doc, draftExists);
729
852
  // THE REFUSAL FIRST (stroke 48: the bench read below needs
730
853
  // checked.draftId, which only the ok arm carries — refusing here
731
854
  // is the same throw, minus the wasted draft probe).
732
855
  if (checked.kind === "refusal")
733
856
  throw toRemoteError(checked.refusal);
857
+
858
+ // refuses the press BEFORE the replay, the reserve and the mint —
859
+ // a run born now would tear mid-render. Named code, and the
860
+ // replay cannot launder it (the check sits above the replay).
861
+ const lifecycleHeld = lifecycleInFlight();
862
+ if (lifecycleHeld !== null) {
863
+ throw toRemoteError(refusal(409, "refused: lifecycle " + lifecycleHeld + " in flight — retry the press when it settles (the teardown holds the run gate until it completes)", "lifecycle_inflight"));
864
+ }
865
+
866
+ // answered names a run that exists — return ITS summary, mint
867
+ // nothing, enqueue nothing. The row is gone (swept, or its seat
868
+ // restarted) → the key is stale, a retry may run again.
869
+ const pressKey = typeof checked.body["press_key"] === "string"
870
+ ? checked.body["press_key"]
871
+ : undefined;
872
+ if (pressKey !== undefined) {
873
+ const replay = this.pressReplay(pressKey);
874
+ if (replay !== null)
875
+ return replay;
876
+ // THE CONCURRENT-PRESS RESERVATION (the double-mint cure,
877
+
878
+ // first mint registers — two concurrent starts with one key
879
+ // both saw the empty map and minted twice (two runs, two
880
+ // enqueues, double GPU spend). The reservation goes in
881
+ // SYNCHRONOUSLY after a miss (no await sits between), so
882
+ // exactly one caller becomes the minter; the twin rides its
883
+ // promise — one run_id, one enqueue, the same answer face.
884
+ // The reservation's identity is the key STRING, not the body:
885
+ // a second body under one key is the same press (the client
886
+ // re-sent it), so the twin answers the minting body's outcome.
887
+ const twin = this.reservePress(pressKey);
888
+ if (twin !== null)
889
+ return await this.awaitTwin(twin, signal);
890
+ try {
891
+ return await this.startReserved(pressKey, checked, signal, reuse);
892
+ }
893
+ catch (error) {
894
+ this.failPress(pressKey, error);
895
+ throw error;
896
+ }
897
+ finally {
898
+ this.pendingPresses.delete(pressKey);
899
+ }
900
+ }
901
+ return this.startReserved(undefined, checked, signal, reuse);
902
+ }
903
+
904
+
905
+
906
+
907
+
908
+ pressReplay(pressKey) {
909
+ const seen = this.presses.get(pressKey);
910
+ if (seen !== undefined) {
911
+ const row = this.core.runs.get(seen);
912
+ if (row !== undefined) {
913
+ return {
914
+ run_id: row.runId,
915
+ status: row.status,
916
+ queue_position: this.core.queuePosition(row.runId),
917
+ };
918
+ }
919
+ this.presses.delete(pressKey);
920
+ }
921
+ else {
922
+
923
+ // the key while its run still lives (a queued press behind a
924
+ // long render outlives 64 newer presses routinely). The row's
925
+ // own stamp answers the replay — the double-spend window the
926
+ // press memory was built to close stays closed past the cap.
927
+ // the registry stores full RunRecords in the queue's map
928
+ // (liveRun's own cast — QueueRunRow is the queue's narrow view)
929
+ for (const row of this.core.runs.values()) {
930
+ if (row.pressKey !== pressKey)
931
+ continue;
932
+ this.rememberPress(pressKey, row.runId); // re-admit to the map
933
+ return {
934
+ run_id: row.runId,
935
+ status: row.status,
936
+ queue_position: this.core.queuePosition(row.runId),
937
+ };
938
+ }
939
+ }
940
+ return null;
941
+ }
942
+ /** THE START ARMS under a settled replay/reservation verdict: the
943
+ * bench-composed arm and the flow_inline arm, behavior-verbatim
944
+ * from before the concurrent-press cure split them behind the
945
+ * shell (the split's only edits are the two summary settles). */
946
+ async startReserved(pressKey, checked, signal, reuse) {
947
+
948
+ // arm scope owns it — the registerCompiledRun door reads it
949
+ // after the name/flow_inline blocks close (flow arms AND the
950
+ // bench-composed arm feed it; the single-card run alone rides
951
+ // its fam key).
952
+ let flowStageFams = {};
734
953
  // THE BENCH SNAPSHOT (stroke 45d, the operator's question: "the
735
954
  // FULL workflow, or just the card that ran?"): the run is born
736
955
  // from the bench doc (CARD BIRTH LAW — draft_id = the bench);
737
956
  // the doc read at THIS moment is the whole workflow as it stood
738
- // when the user pressed Run. A read failure stamps nothing (the
739
- // card snapshot below still carries the exact card + params).
957
+ // when the user pressed Run. A read failure stamps a warning on
958
+ // the row (audit N-S3): draftExists probed true a moment ago, so
959
+ // a failure HERE is a transient drafts outage — the run proceeds
960
+ // on the card snapshot alone and the wand will restore from the
961
+ // LIVE bench, the exact staleness the snapshot law kills. The
962
+ // row says so.
740
963
  let benchDoc;
964
+ const benchWarnings = [];
741
965
  try {
742
- benchDoc = (await this.ctx.draftsRemote.get(checked.draftId, signal));
966
+ // R7 CURE (round-14 race audit, LOW — the run-press live alias):
967
+ // the drafts read answers the CACHED doc by reference (the
968
+ // cached-object law), so composing + snapshotting from it naked
969
+ // let a mutation landing between press and snapshot straddle
970
+ // the two (a snapshot that was not quite a snapshot). The
971
+ // press now owns a DEEP copy: what the run composes and what
972
+ // the sidecar snapshots is the SAME frozen instant, no matter
973
+ // what the live bench does next.
974
+ benchDoc = structuredClone(await this.ctx.draftsRemote.get(checked.draftId, signal));
743
975
  }
744
- catch {
976
+ catch (e) {
745
977
  benchDoc = undefined;
978
+ benchWarnings.push("bench snapshot read failed at press (" +
979
+ (e instanceof Error ? e.message : String(e)) +
980
+ ") — only the card snapshot rode; restore reconstructs from the live bench");
746
981
  }
747
982
  // THE ONE RUN ID, MINTED ONCE (the operator's live refusal,
748
983
 
@@ -769,7 +1004,17 @@ export class RunsRuntimeService extends Service {
769
1004
  const strict = strictBodyCheck(body);
770
1005
  if (strict !== null)
771
1006
  throw toRemoteError(strict);
772
- let selected = selectSubmitDoor(body);
1007
+ let selected = selectSubmitDoor(body, {
1008
+ // THE BENCH-SHAPE GATE: a draft-only press is the bench door
1009
+ // only over a draft that IS a bench — a doc carrying a
1010
+ // non-empty stages array. Anything else (the envelope spec's
1011
+ // bare d1 doc, an emptied bench) is a shapeless body: the
1012
+ // gate's own "no flow selected" stands.
1013
+ draftBench: benchDoc !== undefined &&
1014
+ "draft_id" in body &&
1015
+ Array.isArray(benchDoc["stages"]) &&
1016
+ benchDoc["stages"].length > 0,
1017
+ });
773
1018
  if ("payload" in selected)
774
1019
  throw toRemoteError(selected);
775
1020
  // Later strokes own these lanes; both refuse LOUD here (the
@@ -794,9 +1039,14 @@ export class RunsRuntimeService extends Service {
794
1039
  // riding as stage inputs. There is no third shape: a bench with
795
1040
  // wires is a flow, whatever the caller named.
796
1041
  let benchComposed = false;
797
- if (selected.door === "model" && benchDoc !== undefined) {
1042
+ if ((selected.door === "model" || selected.door === "draft") &&
1043
+ benchDoc !== undefined) {
798
1044
  const wired = benchWiring(benchDoc);
799
- if (wired.cross.length > 0) {
1045
+ // The DRAFT door composes unconditionally: the body names the
1046
+ // bench — pressing the bench is the meaning of the press. The
1047
+ // model door keeps its wire gate (a card Run over an unwired
1048
+ // bench stays a card run).
1049
+ if (selected.door === "draft" || wired.cross.length > 0) {
800
1050
 
801
1051
  // behind it: there was no path that ran a WIRED bench. The
802
1052
  // GUI ran cards one at a time, each its own run, so a FromStage
@@ -819,7 +1069,13 @@ export class RunsRuntimeService extends Service {
819
1069
  // before it registered. The id is minted ONCE, here, and both
820
1070
  // the compose and the registration take it — one derivation,
821
1071
  // and a wall drives the pair.
822
- const composed = await this.composeBenchStages(benchDoc, runId);
1072
+ const benchFams = {};
1073
+ const composed = await this.composeBenchStages(benchDoc, runId, benchFams);
1074
+ // the bench-composed stages' families reach the same claim
1075
+ // re-probe ledger the flow arm feeds (S-S4): the empty-ledger
1076
+ // carve-out below is the card-single path alone, never this
1077
+ // one.
1078
+ flowStageFams = benchFams;
823
1079
  const rest = { ...body };
824
1080
  delete rest["model"];
825
1081
  delete rest["card"];
@@ -986,6 +1242,16 @@ export class RunsRuntimeService extends Service {
986
1242
  }
987
1243
  const cardStage = {
988
1244
  id: skeleton,
1245
+
1246
+ // card over the bench doc — the draft row that declared it is
1247
+ // the doc's single stage row, and the settle mirror addresses
1248
+ // the draft row by THAT id, never by the card skeleton the
1249
+ // run row carries as `id` (the two namespaces diverge on
1250
+ // every {model:} bench run; the motivating wound
1251
+ // run-4610e1c38d75 was "edit" here vs "s_2" in the draft
1252
+ // doc). Multi-row benches compose through the bench loop,
1253
+ // which stamps each row's own id.
1254
+ benchStageId: benchStageIdOf(benchDoc, skeleton),
989
1255
  // The {model:} card door's engine (the compose plane is
990
1256
  // ComfyUI's — the card arm rides it by construction).
991
1257
  engine: CARD_PLANE_ENGINE,
@@ -994,6 +1260,9 @@ export class RunsRuntimeService extends Service {
994
1260
  output_nodes: composed.outputNodes,
995
1261
  },
996
1262
  outputs: composed.outputs,
1263
+ // the card compose computes the card's channels itself —
1264
+ // nothing here is an engine-table fill
1265
+ outputsDeclared: true,
997
1266
  expected: {},
998
1267
  outputNodes: composed.outputNodes,
999
1268
  inputNames: {},
@@ -1007,11 +1276,17 @@ export class RunsRuntimeService extends Service {
1007
1276
  // F-6(b): the admission warn computes pre-registration so
1008
1277
  // it rides the record AND the queued sidecar (disk rows
1009
1278
  // carry it after a reload).
1010
- warnings: await this.filmAdmissionWarnings(p1.card, body),
1279
+ warnings: [
1280
+ ...benchWarnings,
1281
+ ...(await this.filmAdmissionWarnings(p1.card, body)),
1282
+ ],
1011
1283
  door: {
1012
1284
  runId,
1013
1285
  pipeline: pipelineOf(body),
1014
1286
  cardId: p1.card,
1287
+
1288
+ // the row so the pump re-runs the presence gate at claim.
1289
+ fam: p1.fam,
1015
1290
  // THE SNAPSHOT-COERCION LAW: the sidecar's request body
1016
1291
  // carries the numbers the card received (the same wire
1017
1292
  // family the compose seat runs), not dsh's stringly
@@ -1046,12 +1321,21 @@ export class RunsRuntimeService extends Service {
1046
1321
  throw toRemoteError(reg);
1047
1322
  const { run } = reg;
1048
1323
  void run;
1324
+ if (pressKey !== undefined) {
1325
+ run.pressKey = pressKey; // the row mirror (S-S7)
1326
+ this.rememberPress(pressKey, run.runId);
1327
+ }
1049
1328
  this.kick();
1050
- return {
1329
+ const summary = {
1051
1330
  run_id: run.runId,
1052
1331
  status: "queued",
1053
1332
  queue_position: this.core.queuePosition(run.runId),
1054
1333
  };
1334
+ // THE TWIN'S ANSWER (the concurrent-press cure): the summary
1335
+ // settles the reservation AFTER rememberPress holds the key —
1336
+ // a third caller replays from the press memory, never re-mints.
1337
+ this.resolvePress(pressKey, summary);
1338
+ return summary;
1055
1339
  }
1056
1340
  // The request initials this start carries (declared at this
1057
1341
  // scope so the registration below can carry them on the door).
@@ -1059,6 +1343,10 @@ export class RunsRuntimeService extends Service {
1059
1343
  // flow_inline arm that recovers the declaration from the doc's
1060
1344
  // registry id (the boot replay's shape).
1061
1345
  const requestInitials = {};
1346
+ // The FILE-kind subset (photo | glb) — the keys whose values the
1347
+ // claim-time re-probe re-judges on disk (the F5 cure): the gate
1348
+ // ran at press, minutes can pass before the merge uses the file.
1349
+ const initialFileKeys = [];
1062
1350
  if (selected.door === "flow") {
1063
1351
  // THE NAMED-FLOW SHIM (REBUILD-13; the dead door's own law):
1064
1352
  // the registry flow expands (from_flow links
@@ -1082,13 +1370,42 @@ export class RunsRuntimeService extends Service {
1082
1370
  // produced named nothing, which was half the old defect.
1083
1371
  "flow id " + JSON.stringify(raw) + " is not a legal identifier", { loc: "flow" });
1084
1372
  }
1085
- const decl = getRegistryFlow(name);
1373
+ const decl = this.ctx.get("meliteFlows").get(name);
1086
1374
  if (decl === undefined) {
1087
1375
  // The door's unknown-name voice (rendered invalid_request —
1088
1376
  // the start-door envelope norm for bad requests).
1089
1377
  throw new RemoteError("runs/invalid-request", "no flow named " + name + " in the registry", { loc: "flow" });
1090
1378
  }
1091
- const expanded = expandRegistryFlow(decl);
1379
+ // THE EXPANSION FOLD (round-21 flows audit F4): expansion's
1380
+ // authoring throws (dangling from_flow links, raw-workflow
1381
+ // shapes) are bare Errors — without this fold they escaped
1382
+ // the door as 500-class. They ride the door's invalid-request
1383
+ // voice with the expansion's own text, mirroring the
1384
+ // family-compose fold below.
1385
+ let expanded;
1386
+ try {
1387
+ expanded = expandRegistryFlow(decl, this.ctx.get("meliteFlows"));
1388
+ }
1389
+ catch (e) {
1390
+ throw new RemoteError("runs/invalid-request", e instanceof Error ? e.message : String(e), { loc: "stages" });
1391
+ }
1392
+ // THE FLOW PARAMS OVERRIDE DOOR (the af-move commission's press,
1393
+
1394
+ // overlaid on the expanded stages' row params, refused BEFORE
1395
+ // any run registers (the initial-gate law). Without this door
1396
+ // the template's params were final: the maker's
1397
+ // `file_format: "fbx"` rode top-level and died silently
1398
+ // (run-6cb3a8e094fc), leaving the FBX export unreachable from
1399
+ // the flow door. The overlay law is SHARED (round-21 flows
1400
+ // audit F1): applyFlowParamsOverride below, the same helper the
1401
+ // validate door rides.
1402
+ const overrideRaw = body["params"];
1403
+ if (overrideRaw !== undefined) {
1404
+ applyFlowParamsOverride(name, expanded.stages, overrideRaw, overlayDecls(this.ctx.cardRegistry), String(body["model"] ?? ""));
1405
+ const rest = { ...body };
1406
+ delete rest["params"];
1407
+ body = rest;
1408
+ }
1092
1409
  // THE COMPILE-TIME INITIAL GATE (REBUILD-21; the dead door's
1093
1410
  // law): present initials refuse BEFORE any run registers —
1094
1411
  // validate runs the same gate, so start can never queue what
@@ -1097,6 +1414,11 @@ export class RunsRuntimeService extends Service {
1097
1414
  repoRoot: resolveRepoRoot(),
1098
1415
  stateRoot,
1099
1416
  });
1417
+
1418
+ // start-arm scope owns it: the flow door at registerCompiledRun
1419
+ // reads it after the name and flow_inline blocks close
1420
+ // (bench-composed runs ride the same door with an empty ledger).
1421
+ let flowStageFams = {};
1100
1422
  if (badInitial !== null) {
1101
1423
  throw new RemoteError("runs/invalid-request", badInitial, {
1102
1424
  loc: "body",
@@ -1123,6 +1445,11 @@ export class RunsRuntimeService extends Service {
1123
1445
  });
1124
1446
  }
1125
1447
  Object.assign(requestInitials, extracted.initials);
1448
+ for (const [k, kind] of Object.entries(decl.initialValidators)) {
1449
+ if ((kind === "photo" || kind === "glb") && k in extracted.initials && !initialFileKeys.includes(k)) {
1450
+ initialFileKeys.push(k);
1451
+ }
1452
+ }
1126
1453
  // THE FAMILY-ACTION STAGES COMPOSE HERE (the atom vocabulary,
1127
1454
  // stroke 4): a stage naming family+action composes its graph
1128
1455
  // from the family DECL at expansion — the wire downstream sees
@@ -1142,11 +1469,11 @@ export class RunsRuntimeService extends Service {
1142
1469
  composedFlow = composeFamilyStages(expanded, seat.decls, seat.state);
1143
1470
  }
1144
1471
  catch (e) {
1145
- /* v8 ignore next -- every throw inside composeFamilyStages,
1146
- * liveFamilySeat and the family DECL actions they call is a
1147
- * constructed Error (flowsFamilyCompose.ts raises only
1148
- * new Error), so the non-Error spelling is a belt for a
1149
- * callee that throws a bare value. */
1472
+ /* v8 ignore next -- composeFamilyStages, liveFamilySeat and
1473
+ * declaredAction raise constructed Errors; a family build's
1474
+ * throw class is the family module's own contract (nothing
1475
+ * here owns it), so the non-Error spelling is the belt that
1476
+ * folds any bare-value throw too (round-23 audit Q6). */
1150
1477
  throw new RemoteError("runs/invalid-request", e instanceof Error ? e.message : String(e), { loc: "stages" });
1151
1478
  }
1152
1479
  let inlineDoc = registryFlowToInline(composedFlow);
@@ -1156,7 +1483,9 @@ export class RunsRuntimeService extends Service {
1156
1483
  // card walk composes them here, so a named flow RUNS the way the
1157
1484
  // bench runs, and the compiler only ever sees compiled stages.
1158
1485
  if (inlineStagesNameCards(inlineDoc)) {
1159
- inlineDoc = await this.composeRegistryFlowStages(inlineDoc, runId);
1486
+ const stageFams = {};
1487
+ inlineDoc = await this.composeRegistryFlowStages(inlineDoc, runId, stageFams);
1488
+ flowStageFams = stageFams;
1160
1489
  console.log("[runs] the flow " + name +
1161
1490
  " composes its card stages through the card plane (" +
1162
1491
  inlineDoc["stages"].length + " stages)");
@@ -1185,6 +1514,13 @@ export class RunsRuntimeService extends Service {
1185
1514
  const knownEngines = enginesSeat !== undefined && typeof enginesSeat.ids === "function"
1186
1515
  ? enginesSeat.ids()
1187
1516
  : [CARD_PLANE_ENGINE];
1517
+
1518
+ // kind lattice (kindsOk, inside flowFromBody) is validate-only —
1519
+ // a raw pre-flight here would REFUSE real benches (bench rows
1520
+ // carry inputs without expected; validate derives the kinds from
1521
+ // the card ports BEFORE the judge runs, start would not). The
1522
+ // honest cure derives first, then judges — the roadmap row names
1523
+ // the projection requirement; a bare judge is a false refusal.
1188
1524
  const compiled = compileFlowInline(inline, knownEngines);
1189
1525
  if ("payload" in compiled)
1190
1526
  throw toRemoteError(compiled);
@@ -1202,7 +1538,7 @@ export class RunsRuntimeService extends Service {
1202
1538
  // registered: nothing to recover, nothing refused.
1203
1539
  const replayId = inline["id"];
1204
1540
  if (typeof replayId === "string") {
1205
- const replayDecl = getRegistryFlow(replayId);
1541
+ const replayDecl = this.ctx.get("meliteFlows").get(replayId);
1206
1542
  if (replayDecl !== undefined) {
1207
1543
  const badReplayInitial = registryInitialsError(replayDecl, body, {
1208
1544
  repoRoot: resolveRepoRoot(),
@@ -1225,8 +1561,33 @@ export class RunsRuntimeService extends Service {
1225
1561
  });
1226
1562
  }
1227
1563
  Object.assign(requestInitials, replayExtracted.initials);
1564
+ for (const [k, kind] of Object.entries(replayDecl.initialValidators)) {
1565
+ if ((kind === "photo" || kind === "glb") && k in replayExtracted.initials && !initialFileKeys.includes(k)) {
1566
+ initialFileKeys.push(k);
1567
+ }
1568
+ }
1228
1569
  }
1229
1570
  }
1571
+ // THE PARITY JUDGE (audits F-S4/S5 — the kinds split, closed):
1572
+ // the compiled doc judges the SAME kind lattice validate ran,
1573
+ // over the SAME wire rows the door compiled — projected, never
1574
+ // re-derived. A card= stage never reaches this judge (the
1575
+ // gateway refuses the shape before it), so the card-port halves
1576
+ // ride their own doors; what start gains is the durable doc's
1577
+ // own kind consistency — a doc hand-edited between press and
1578
+ // replay dies here, with validate's voice, before it burns a
1579
+ // run. (The card-plane reads a bare judge would need are why the
1580
+ // first cut was NAMED NOT CURED; judging the compiled rows needs
1581
+ // no card plane at all.)
1582
+ try {
1583
+ kindsOk(typeof replayId === "string" ? replayId : "flow_inline", replayJudgeRows(compiled), {}, undefined);
1584
+ }
1585
+ catch (judgeError) {
1586
+ if (judgeError instanceof FlowError) {
1587
+ throw new RemoteError("runs/invalid-request", judgeError.message, { loc: "body" });
1588
+ }
1589
+ throw judgeError;
1590
+ }
1230
1591
  if (compiled.stages.length !== 1) {
1231
1592
 
1232
1593
  // resolved): the merged worker was ALWAYS multi-stage — the
@@ -1257,7 +1618,8 @@ export class RunsRuntimeService extends Service {
1257
1618
  // fall through to the registration the single-stage path uses
1258
1619
  }
1259
1620
  else {
1260
- const curated = typeof inlineId === "string" && getRegistryFlow(inlineId) !== undefined;
1621
+ const curated = typeof inlineId === "string" &&
1622
+ this.ctx.get("meliteFlows").get(inlineId) !== undefined;
1261
1623
  if (!curated) {
1262
1624
  throw toRemoteError(refusePreview("this gateway serves single-stage flow_inline runs only (" +
1263
1625
  compiled.stages.length +
@@ -1273,6 +1635,8 @@ export class RunsRuntimeService extends Service {
1273
1635
  draftId: checked.draftId,
1274
1636
  stateRoot,
1275
1637
  enqueue: (row) => this.core.enqueue(row),
1638
+ // the bench-read warning rides the inline arm too (audit N-S3)
1639
+ warnings: benchWarnings,
1276
1640
  // THE RUN ID IS AN INPUT, NOT A LABEL (the operator's live
1277
1641
 
1278
1642
  // run-65dc3ee505ef-…/gen)").
@@ -1305,7 +1669,15 @@ export class RunsRuntimeService extends Service {
1305
1669
  ...(Object.keys(requestInitials).length === 0
1306
1670
  ? {}
1307
1671
  : { initials: requestInitials }),
1672
+ // THE F5 STAMP: the file-kind keys ride the row so the pump's
1673
+ // claim-time re-probe knows which initials to re-judge on disk.
1674
+ ...(initialFileKeys.length > 0 ? { initialFileKeys: [...initialFileKeys] } : {}),
1308
1675
  ...(benchDoc === undefined ? {} : { benchDoc }),
1676
+
1677
+ // composed card stages' families ride the row (not the stage
1678
+ // rows — extra=forbid at the wire door) for the pump's
1679
+ // claim-time gate re-run.
1680
+ ...(Object.keys(flowStageFams).length > 0 ? { stageFams: flowStageFams } : {}),
1309
1681
  },
1310
1682
  });
1311
1683
  // THE SOURCE-ECHO REFUSAL (same law on the inline door).
@@ -1313,12 +1685,21 @@ export class RunsRuntimeService extends Service {
1313
1685
  throw toRemoteError(reg);
1314
1686
  const { run } = reg;
1315
1687
  void run;
1688
+ if (pressKey !== undefined) {
1689
+ run.pressKey = pressKey; // the row mirror (S-S7)
1690
+ this.rememberPress(pressKey, run.runId);
1691
+ }
1316
1692
  this.kick();
1317
- return {
1693
+ const summary = {
1318
1694
  run_id: run.runId,
1319
1695
  status: "queued",
1320
1696
  queue_position: this.core.queuePosition(run.runId),
1321
1697
  };
1698
+ // THE TWIN'S ANSWER (the concurrent-press cure): the summary
1699
+ // settles the reservation AFTER rememberPress holds the key —
1700
+ // a third caller replays from the press memory, never re-mints.
1701
+ this.resolvePress(pressKey, summary);
1702
+ return summary;
1322
1703
  }
1323
1704
  /** The list arm (REBUILD-7): the restore-port envelope over the
1324
1705
  * output roots. The raw limit STRING rides from the lane (strict
@@ -1335,12 +1716,17 @@ export class RunsRuntimeService extends Service {
1335
1716
  const limit = Math.max(1, Math.min(500, parsed));
1336
1717
  // §23 CROSS-ROOTS: the union list across the manifest (own
1337
1718
  // root first — own rows win collisions, every row served_from).
1338
- return await listRunsAcross(rootsManifest(this.ctx.queue.stateRoot), limit, async (draftId) => {
1719
+ return await listRunsAcross(this.ctx.queue.stateRoots, limit, async (draftId) => {
1339
1720
  try {
1340
1721
  await this.ctx.draftsRemote.get(draftId, signal);
1341
1722
  return true;
1342
1723
  }
1343
- catch {
1724
+ catch (e) {
1725
+ // a caller abort cancels the list (audit N-S4) — it never
1726
+ // folds to "draft missing"; only a genuine miss degrades
1727
+ // the row's draft_id
1728
+ signal.throwIfAborted();
1729
+ void e;
1344
1730
  return false;
1345
1731
  }
1346
1732
  });
@@ -1397,7 +1783,7 @@ export class RunsRuntimeService extends Service {
1397
1783
  // queue seat owns stateRoot on every boot (the service
1398
1784
  // refuses root-less — the constructor's law).
1399
1785
  throw new RemoteError("runs/unknown-run", "unknown run_id \"" + runId + "\" " +
1400
- searchedVoice(rootsManifest(this.ctx.queue.stateRoot)), { runId });
1786
+ searchedVoice(this.ctx.queue.stateRoots), { runId });
1401
1787
  }
1402
1788
  return withStageReports({ ...enrichDiskRow(disk.row), from_disk: true, queue_position: 0, served_from: disk.root }, sidecarReaderFor(disk.dir));
1403
1789
  }
@@ -1453,6 +1839,11 @@ export class RunsRuntimeService extends Service {
1453
1839
  // minted file the engine reported — additive, same spelling
1454
1840
  // as the sidecar; the disk fallback spreads the sidecar row.
1455
1841
  ...(run.exportPath !== undefined && run.exportPath !== "" ? { export_path: run.exportPath } : {}),
1842
+
1843
+ // seated tap folded zero engine events before settlement — the
1844
+ // artifacts may predate the request. Additive, same spelling
1845
+ // as the sidecar; absent means voiced execution (or unknown).
1846
+ ...(run.replaySuspect === true ? { replay_suspect: true } : {}),
1456
1847
  // THE VARIANT, SERVED (commission 033's self-critique #5):
1457
1848
  // the lane the run rode — additive, same spelling as the
1458
1849
  // sidecar; the disk fallback spreads the sidecar row, which
@@ -1532,7 +1923,7 @@ export class RunsRuntimeService extends Service {
1532
1923
  // which trees answered; cross-process stop stays refused by
1533
1924
  // the unknown code, never a blind guess).
1534
1925
  throw new RemoteError("runs/run-unknown", "unknown run_id " + JSON.stringify(runId) + " " +
1535
- searchedVoice(rootsManifest(this.ctx.queue.stateRoot)), { runId });
1926
+ searchedVoice(this.ctx.queue.stateRoots), { runId });
1536
1927
  }
1537
1928
  if (run.status !== "queued" && run.status !== "running" && run.status !== "stopping") {
1538
1929
  return { error: "cannot stop run in state " + run.status };
@@ -1551,7 +1942,11 @@ export class RunsRuntimeService extends Service {
1551
1942
  // seat exists (best-effort — the flag is the authority).
1552
1943
  try {
1553
1944
  const comfy = needComfyUI(this.ctx, "runsRemote stop");
1554
- void comfy.stopForRunDir(run.dir).catch(() => { });
1945
+ void comfy.stopForRunDir(run.dir).catch((e) => {
1946
+ // named (audit N-S5): an interrupt outage is observable in
1947
+ // the log; the worker's stopFlag check still converges
1948
+ console.log("[estate-queue] stop interrupt failed:", e instanceof Error ? e.message : String(e));
1949
+ });
1555
1950
  }
1556
1951
  catch {
1557
1952
  /* no seat: the worker's stop check converges the state */
@@ -1571,9 +1966,9 @@ export class RunsRuntimeService extends Service {
1571
1966
  * undefined — never a fabricated row. */
1572
1967
  diskRunRow(runId) {
1573
1968
 
1574
- // root first, then the maker's tree (MELITE_STATE_ROOTS). Own
1969
+ // root first, then the stateRoots config extras. Own
1575
1970
  // writes win; the first root holding the run serves.
1576
- for (const root of rootsManifest(this.ctx.queue.stateRoot)) {
1971
+ for (const root of this.ctx.queue.stateRoots) {
1577
1972
  for (const dir of [join(root, "output", runId), join(root, "test-output", runId)]) {
1578
1973
  try {
1579
1974
  const doc = JSON.parse(readFileSync(join(dir, "_flow.json"), "utf8"));
@@ -1602,46 +1997,102 @@ export class RunsRuntimeService extends Service {
1602
1997
  }
1603
1998
  /** The envelope walk with the AWAITED draft probe (door order
1604
1999
  * preserved: the probe sits between malformed and unknown). */
1605
- async walkEnvelope(doc, draftExists) {
1606
- if (typeof doc !== "object" || doc === null || Array.isArray(doc)) {
1607
- return { kind: "refusal", refusal: envelopeRefusal("not-object", doc) };
1608
- }
1609
- const body = doc;
1610
- // ONE ENVELOPE LAW with checkFlowsStartEnvelope (runsGates) and the
1611
- // queue door: absent/null test means false — a chat tool's start
1612
- // doc may carry test:null (LLM serializers emit nulls for omitted
1613
- // booleans) and the retired gate (submit 1179-1270) never refused
1614
- // it. This copy had drifted to a bare read, refusing legal calls
1615
-
1616
- // "test flag must be a boolean (got unknown null)").
1617
- const testFlag = body["test"] ?? false;
1618
- if (typeof testFlag !== "boolean") {
1619
- return {
1620
- kind: "refusal",
1621
- refusal: envelopeRefusal("bad-test", doc, { testFlag }),
1622
- };
1623
- }
1624
- const draftId = body["draft_id"];
1625
- if (typeof draftId !== "string" || draftId === "") {
1626
- return {
1627
- kind: "refusal",
1628
- refusal: envelopeRefusal("missing-draft", doc),
1629
- };
1630
- }
1631
- if (!draftIdOk(draftId)) {
1632
- return {
1633
- kind: "refusal",
1634
- refusal: envelopeRefusal("malformed-draft", doc, { draftId }),
1635
- };
1636
- }
1637
- if (!(await draftExists(draftId))) {
1638
- return { kind: "refusal", refusal: unknownDraftRefusal(draftId) };
2000
+
2001
+
2002
+
2003
+
2004
+
2005
+
2006
+
2007
+ presses = new Map();
2008
+
2009
+
2010
+
2011
+
2012
+
2013
+
2014
+ pendingPresses = new Map();
2015
+ /** The caller's verdict at the press gate: null when it becomes
2016
+ * the minter (its entry is registered before this returns); the
2017
+ * in-flight promise when a concurrent mint owns the key — the
2018
+ * twin awaits and answers with the SAME summary or refusal. */
2019
+ reservePress(pressKey) {
2020
+ const pending = this.pendingPresses.get(pressKey);
2021
+ if (pending !== undefined)
2022
+ return pending.promise;
2023
+ let resolve;
2024
+ let reject;
2025
+ const promise = new Promise((res, rej) => {
2026
+ resolve = res;
2027
+ reject = rej;
2028
+ });
2029
+ promise.catch(() => undefined); // a refused mint rejects the twin's await — never an unhandled rejection
2030
+ this.pendingPresses.set(pressKey, { promise, resolve, reject });
2031
+ return null;
2032
+ }
2033
+ /** The minter's summary settles the twin (no-op without a press —
2034
+ * the door's return sites serve both keyed and keyless starts). */
2035
+ resolvePress(pressKey, summary) {
2036
+ if (pressKey === undefined)
2037
+ return;
2038
+ const pending = this.pendingPresses.get(pressKey);
2039
+ if (pending !== undefined)
2040
+ pending.resolve(summary);
2041
+ }
2042
+
2043
+
2044
+
2045
+
2046
+ failPress(pressKey, error) {
2047
+ const pending = this.pendingPresses.get(pressKey);
2048
+ if (pending !== undefined)
2049
+ pending.reject(error);
2050
+ }
2051
+
2052
+
2053
+
2054
+
2055
+
2056
+
2057
+
2058
+
2059
+
2060
+
2061
+ async awaitTwin(twin, signal) {
2062
+ signal.throwIfAborted();
2063
+ return new Promise((resolve, reject) => {
2064
+ const onAbort = () => reject(signal.reason);
2065
+ signal.addEventListener("abort", onAbort, { once: true });
2066
+ twin.then((summary) => {
2067
+ signal.removeEventListener("abort", onAbort);
2068
+ resolve({ ...summary });
2069
+ }, (error) => {
2070
+ signal.removeEventListener("abort", onAbort);
2071
+ reject(error);
2072
+ });
2073
+ });
2074
+ }
2075
+ rememberPress(pressKey, runId) {
2076
+ this.presses.delete(pressKey); // refresh recency before the cap read
2077
+ this.presses.set(pressKey, runId);
2078
+ while (this.presses.size > RunsRuntimeService.PRESS_MEMORY_MAX) {
2079
+ const oldest = this.presses.keys().next();
2080
+ if (oldest.done)
2081
+ break;
2082
+ this.presses.delete(oldest.value);
1639
2083
  }
1640
- return { kind: "ok", body, testFlag: testFlag, draftId };
1641
2084
  }
1642
2085
  /** Kick the serial pump (door-verbatim guard). */
1643
2086
  kick() {
1644
- void this.pump();
2087
+ // THE PUMP FENCE (audit N-S7): every hop inside self-swallows or
2088
+ // is caught per-row today — this arm is the day one escapes. A
2089
+ // stranded claim (tryDequeue pins activeId before the awaits)
2090
+ // would stall the queue until reboot with no voice; the fence
2091
+ // releases the claim and says so.
2092
+ void this.pump().catch((e) => {
2093
+ this.core.releaseActive();
2094
+ console.log("[estate-queue] pump scaffold escape — active claim released:", e instanceof Error ? e.message : String(e));
2095
+ });
1645
2096
  }
1646
2097
  /** The serial worker: claim the FIFO head, execute, settle —
1647
2098
  * one GPU run machine-wide, strict submit order. */
@@ -1664,6 +2115,106 @@ export class RunsRuntimeService extends Service {
1664
2115
  if (run === null)
1665
2116
  return;
1666
2117
 
2118
+ // while this row sat queued must not cost a full render —
2119
+ // the stop flag is otherwise read only inside runOne, after
2120
+ // the merged submit. A claimed row whose stop flag is already
2121
+ // set goes straight to stopped: settled, no engine call. The
2122
+ // claim persist still lands (stopped on disk, the replay law
2123
+ // keeps the receipt).
2124
+ if (run.stopFlag) {
2125
+ run.status = "stopped";
2126
+ await claimPersist(run);
2127
+ await this.settle(run);
2128
+ continue;
2129
+ }
2130
+
2131
+ // lane gate ran at press; weights can leave between press
2132
+ // and claim (a removal, a prune, a moved store). A claimed
2133
+
2134
+ // the same lane voice — never an unnamed engine-side death.
2135
+ // Best-effort on the seat: a lane without a primed registry
2136
+ // leaves the engine-side gate standing.
2137
+ const fams = [];
2138
+ if (typeof run.fam === "string" && run.fam !== "")
2139
+ fams.push(run.fam);
2140
+ const ledger = run.stageFams;
2141
+ if (typeof ledger === "object" && ledger !== null && !Array.isArray(ledger)) {
2142
+ for (const f of Object.values(ledger)) {
2143
+ if (typeof f === "string" && f !== "" && !fams.includes(f))
2144
+ fams.push(f);
2145
+ }
2146
+ }
2147
+ if (fams.length > 0) {
2148
+ // the gate's contract is THROW-on-miss (phase1Card's pinned
2149
+ // shape) — the catch IS the miss arm; a non-CardArmError
2150
+ // (no booted registry on this lane) leaves the engine-side
2151
+ // checkpoint load as the remaining gate.
2152
+ let laneMiss = null;
2153
+ try {
2154
+ for (const f of fams)
2155
+ lanePresenceRefusal(f);
2156
+ }
2157
+ catch (e) {
2158
+ if (e instanceof CardArmError)
2159
+ laneMiss = e;
2160
+ }
2161
+ if (laneMiss !== null) {
2162
+ run.status = "failed";
2163
+ run.error = laneMiss.message;
2164
+ for (const stage of run.stages) {
2165
+ const st = stage["status"];
2166
+ if (st === "queued" || st === "pending" || st === undefined) {
2167
+ stage["status"] = "failed";
2168
+ stage["error"] = laneMiss.message;
2169
+ }
2170
+ }
2171
+ await claimPersist(run);
2172
+ await this.settle(run);
2173
+ continue;
2174
+ }
2175
+ }
2176
+ // THE CLAIM-TIME INITIALS RE-PROBE (audit F5, the round-25
2177
+ // scout's cure): the press gate validated the file initials
2178
+ // with sync isFile, minutes before the engine merge uses
2179
+ // them — a file deleted, pruned, or lost to a crash-orphan
2180
+ // reclaim in between died engine-side, unnamed. The row's
2181
+ // initialFileKeys name the file-kind entries; the re-probe
2182
+ // judges them over the press gate's OWN candidate trees
2183
+ // (initialFileCandidates — the same set, never the wider
2184
+ // §23 manifest) and fails the row with the press text, so
2185
+ // both moments read as one door. Text and bake_params keys
2186
+ // never ride the stamp — nothing to re-probe.
2187
+ const fileKeys = run.initialFileKeys;
2188
+ if (Array.isArray(fileKeys) && fileKeys.length > 0) {
2189
+ const roots = { stateRoot: this.ctx.queue.stateRoot, repoRoot: resolveRepoRoot() };
2190
+ let initialMiss = null;
2191
+ for (const key of fileKeys) {
2192
+ if (typeof key !== "string")
2193
+ continue;
2194
+ const raw = run.initials[key];
2195
+ if (typeof raw !== "string")
2196
+ continue; // merged-worker arm owns absent/linked values
2197
+ if (!initialFileCandidates(raw.trim(), roots).some((cand) => isFile(cand))) {
2198
+ initialMiss = "initial " + JSON.stringify(key) + " is not on disk (" + raw.trim() + ")";
2199
+ break;
2200
+ }
2201
+ }
2202
+ if (initialMiss !== null) {
2203
+ run.status = "failed";
2204
+ run.error = initialMiss;
2205
+ for (const stage of run.stages) {
2206
+ const st = stage["status"];
2207
+ if (st === "queued" || st === "pending" || st === undefined) {
2208
+ stage["status"] = "failed";
2209
+ stage["error"] = initialMiss;
2210
+ }
2211
+ }
2212
+ await claimPersist(run);
2213
+ await this.settle(run);
2214
+ continue;
2215
+ }
2216
+ }
2217
+
1667
2218
  // 'running' lands on disk at claim time, not only at settle —
1668
2219
  // claimPersist (runsTypes.ts) owns the crash window it closes.
1669
2220
  await claimPersist(run);
@@ -1738,6 +2289,28 @@ export class RunsRuntimeService extends Service {
1738
2289
  await settlePersist(run, queue.stateRoot);
1739
2290
  queue.core.releaseActive();
1740
2291
  queue.core.evictSettled();
2292
+
2293
+ // run-4610e1c38d75 settled while its draft row read 'running'
2294
+ // forever — the only patcher was the browser tab's poller, and
2295
+ // the push era retired it). The seat now mirrors the terminal
2296
+ // outcome into the draft row itself: a closed or wedged tab can
2297
+ // never own the row's answer. Best-effort: the RUN doc is the
2298
+ // answer of record — a mirror refusal (unknown draft, a stage id
2299
+ // the draft never had) is bookkeeping, and a live tab's own
2300
+ // patch path writes the same words anyway. The patches come
2301
+ // from settleMirrorPatches (the pure seam the walls drive);
2302
+ // telemetry never fences, so expectRev 0 is never spent.
2303
+ if (run.draftId !== "") {
2304
+ const sig = new AbortController().signal;
2305
+ for (const { stageId, patch } of settleMirrorPatches(run)) {
2306
+ try {
2307
+ await this.ctx.draftsRemote.patch(run.draftId, stageId, patch, 0, sig);
2308
+ }
2309
+ catch {
2310
+ /* the mirror is bookkeeping; the run doc answers */
2311
+ }
2312
+ }
2313
+ }
1741
2314
  // THE SETTLE WAKE: the change seam's contract lists the settle
1742
2315
  // among its emitters ("a claim, a settle, an artifacts harvest,
1743
2316
  // a stop press" — runsChange.ts), but this path never fired it;
@@ -1747,4 +2320,75 @@ export class RunsRuntimeService extends Service {
1747
2320
  notifyRunChanged(run.runId);
1748
2321
  }
1749
2322
  }
2323
+ /** The single-stage bench doc's DRAFT row id (the model arm's
2324
+ * identity seam): exactly one stage row with a string id → that id;
2325
+ * any other shape composes ambiguous → undefined (the mirror falls
2326
+ * back to the run row's id, the legacy coincidental path). */
2327
+ function benchStageIdOf(benchDoc, skeleton) {
2328
+ if (benchDoc === undefined)
2329
+ return undefined;
2330
+ const rows = benchDoc["stages"];
2331
+ if (!Array.isArray(rows) || rows.length !== 1)
2332
+ return undefined;
2333
+ const first = rows[0];
2334
+ const id = first?.["id"];
2335
+ return typeof id === "string" && id !== "" ? id : skeleton;
2336
+ }
2337
+ /** THE SETTLE MIRROR (pure — the walls' seam, bench-trail/runs-remote
2338
+ * W4–W8): per draft stage, the terminal outcome patch the runs seat
2339
+ * mirrors into the draft doc at settle, with no browser tab alive.
2340
+ *
2341
+ * Identity: the DRAFT row id (benchStageId, the compose's stamp) —
2342
+ * the run row's `id` may be the card skeleton's, a namespace the
2343
+ * draft doc never heard of (draft.ts's own admission). Legacy rows
2344
+ * without the stamp fall back to `id`.
2345
+ *
2346
+ * Words: the draft row's terminal vocabulary. completed→done (the
2347
+ * client's word, cards-resource tileStatusFromVerdict),
2348
+ * failed→failed, stopped→stopped; a STOPPED run's untouched
2349
+ * (queued/pending/running) stage rows mirror the run's word — the
2350
+ * queued-stop arm settles without stamping stages (the defect-hunt
2351
+ * §1 P1: the closed-tab row would read running forever).
2352
+ *
2353
+ * The result face: run_id always; the run-relative media url of the
2354
+ * stage's own output when one exists (the husk clobber's other
2355
+ * half — a bookkeeping mirror never blanks a hero it can name); the
2356
+ * error voice (stage's, else the run's) when the word is failed. */
2357
+ export function settleMirrorPatches(run) {
2358
+ const out = [];
2359
+ for (const stage of run.stages) {
2360
+ const word = stage.status === "completed" ? "done"
2361
+ : stage.status === "failed" ? "failed"
2362
+ : stage.status === "stopped" ? "stopped"
2363
+ : run.status === "stopped" ? "stopped"
2364
+ : undefined;
2365
+ if (word === undefined)
2366
+ continue;
2367
+ const stageId = typeof stage.benchStageId === "string" && stage.benchStageId !== ""
2368
+ ? stage.benchStageId
2369
+ : stage.id;
2370
+ const extras = stage;
2371
+ const relUrl = typeof extras["url"] === "string" && extras["url"] !== "" ? extras["url"] : undefined;
2372
+ const gallery = Array.isArray(extras["gallery"]) ? extras["gallery"] : [];
2373
+ const galleryName = gallery.length > 0 && typeof gallery[0]["name"] === "string" ? gallery[0]["name"] : undefined;
2374
+ const mediaUrl = relUrl !== undefined || galleryName !== undefined
2375
+ ? RUN_MEDIA_PREFIX + "/" + run.runId + "/" + (relUrl ?? galleryName)
2376
+ : undefined;
2377
+ const voice = typeof stage["error"] === "string" && stage["error"] !== ""
2378
+ ? stage["error"]
2379
+ : word === "failed" && typeof run.error === "string" ? run.error : undefined;
2380
+ out.push({
2381
+ stageId,
2382
+ patch: {
2383
+ runStatus: word,
2384
+ result: {
2385
+ run_id: run.runId,
2386
+ ...(mediaUrl !== undefined ? { url: mediaUrl } : {}),
2387
+ ...(voice !== undefined ? { error: voice } : {}),
2388
+ },
2389
+ },
2390
+ });
2391
+ }
2392
+ return out;
2393
+ }
1750
2394
  //# sourceMappingURL=runsRegistry.js.map