@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
@@ -3,6 +3,33 @@
3
3
  * like the engine's; the sliced tail keeps its case). */
4
4
  export declare const MEDIA_RUNS_PREFIX: string;
5
5
  export declare const ASSET_RUNS_PREFIX: string;
6
+ /** The gallery's read route (packages/web/infer-gallery/src/index.ts
7
+ * registers this exact path — retyped, never derived: no contract
8
+ * owns the gallery's spelling, so the twin names its owner here).
9
+ * Detection is case-insensitive like the engine's estate prefixes;
10
+ * the decoded tail keeps its case. Exported for the compose sweep
11
+ * (cardsDangling) — one spelling, both readers. */
12
+ export declare const GALLERY_ARTIFACT_PATH = "/infer-gallery/artifact";
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+ export declare function galleryTail(t: string): string | null;
6
33
  export type SourceFace = "run" | "abs";
7
34
  /** A collected pointer: the VERBATIM string (history stamps what
8
35
  * the params held — the engine trims for staging, the record
@@ -1,3 +1,4 @@
1
+ import { isFile } from "./skillFs.js";
1
2
  import { segmentConfined, servableLeaf } from "@melite/contracts/mediaKinds";
2
3
 
3
4
  // every generation run carries history pointing at the files that
@@ -17,6 +18,15 @@ import { segmentConfined, servableLeaf } from "@melite/contracts/mediaKinds";
17
18
  // those arms and refuses them loud itself):
18
19
  // /melite-media/runs/<run>/<rel> (the media route)
19
20
  // /v1/assets/runs/<run>/<rel> (the assets route — same trees)
21
+ // /infer-gallery/artifact?path=<run>/<rel>
22
+ // (the gallery's read route — the
23
+ // restore stamp + the drill's
24
+ // artifact harvest mint this URL-
25
+ // encoded tail; the estate stages
26
+ // what it serves, so the guard
27
+ // reads it back onto the same
28
+ // trees instead of misfiling it
29
+ // as an absolute disk path)
20
30
  // <run-id>/<rel> (runs-relative tails; the first
21
31
  // segment must match the mint
22
32
  // grammar — prose with slashes
@@ -43,21 +53,76 @@ export const MEDIA_RUNS_PREFIX = RUN_MEDIA_PREFIX + "/";
43
53
  export const ASSET_RUNS_PREFIX = LEGACY_RUN_MEDIA_PREFIX + "/";
44
54
  /** The run-dir basename grammar (the mint law — media index.ts). */
45
55
  const RUN_ID = RUN_ID_RE;
56
+ /** The gallery's read route (packages/web/infer-gallery/src/index.ts
57
+ * registers this exact path — retyped, never derived: no contract
58
+ * owns the gallery's spelling, so the twin names its owner here).
59
+ * Detection is case-insensitive like the engine's estate prefixes;
60
+ * the decoded tail keeps its case. Exported for the compose sweep
61
+ * (cardsDangling) — one spelling, both readers. */
62
+ export const GALLERY_ARTIFACT_PATH = "/infer-gallery/artifact";
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+ export function galleryTail(t) {
83
+ const lower = t.toLowerCase();
84
+ if (!lower.startsWith(GALLERY_ARTIFACT_PATH))
85
+ return null;
86
+ const next = lower[GALLERY_ARTIFACT_PATH.length];
87
+ if (next !== undefined && next !== "?")
88
+ return null;
89
+ let path = null;
90
+ try {
91
+ path = new URL(t, "http://source-echo.invalid").searchParams.get("path");
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ if (path === null || path === "")
97
+ return null;
98
+ return path;
99
+ }
46
100
  /** The detection grammar (runs on the trimmed string — the engine
47
101
  * trims before every arm, so detection sees what staging sees):
48
- * either estate prefix (either case), an absolute path, or a
49
- * run-tail whose first segment matches the mint grammar. Prose
50
- * with slashes never qualifies — no false refusals on prompts. */
102
+ * either estate prefix (either case), the gallery's artifact route,
103
+ * an absolute path, or a run-tail whose first segment matches the
104
+ * mint grammar. Prose with slashes never qualifies — no false
105
+ * refusals on prompts. The gallery face returns its tail already
106
+ * decoded (decoded: true) — the per-segment decode below must not
107
+ * run twice (a legal `%` in a filename would false-refuse as a bad
108
+ * escape); confinement still judges every segment. */
51
109
  function detectFace(t) {
52
110
  const lower = t.toLowerCase();
53
111
  // Both estate prefixes end in "/runs/" — one slice serves both
54
112
  // faces (detection is case-insensitive like the engine's; the
55
113
  // tail keeps its case).
56
114
  if (lower.startsWith(MEDIA_RUNS_PREFIX) || lower.startsWith(ASSET_RUNS_PREFIX)) {
57
- return { face: "run", rest: t.slice(lower.indexOf("/runs/") + "/runs/".length) };
115
+ return { face: "run", rest: t.slice(lower.indexOf("/runs/") + "/runs/".length), decoded: false };
58
116
  }
117
+
118
+ // serves — a gallery artifact URL resolves onto the same trees
119
+ // as the media route. Before the absolute arm: the URL starts
120
+ // with "/" and would otherwise misfile as a disk path.
121
+ const tail = galleryTail(t);
122
+ if (tail !== null)
123
+ return { face: "run", rest: tail, decoded: true };
59
124
  if (t.startsWith("/"))
60
- return { face: "abs", rest: t };
125
+ return { face: "abs", rest: t, decoded: false };
61
126
 
62
127
  // `t.includes("..")` substring ban refused a LEGAL name the engine
63
128
  // mints (`still..frame.png`) while judging the whole string —
@@ -78,7 +143,7 @@ function detectFace(t) {
78
143
  }
79
144
  if (!RUN_ID.test(decodedHead))
80
145
  return null;
81
- return { face: "run", rest: t };
146
+ return { face: "run", rest: t, decoded: false };
82
147
  }
83
148
  /** Collect every source pointer in a params tree (deep walk over
84
149
  * objects/arrays — card params nest refs inside calls, clips,
@@ -150,12 +215,21 @@ export function parseSourceRef(ref) {
150
215
  }
151
216
  const relParts = [];
152
217
  for (const seg of parts.slice(1)) {
218
+ // The gallery face arrives already decoded exactly once (the
219
+ // URL parser's doing, twinning the server) — decoding again
220
+ // would corrupt a legal `%` in a filename into a bad escape.
221
+ // Confinement judges every segment on every face.
153
222
  let decoded;
154
- try {
155
- decoded = decodeURIComponent(seg);
223
+ if (det.decoded) {
224
+ decoded = seg;
156
225
  }
157
- catch {
158
- throw new Error("malformed media source (bad percent-escape): " + JSON.stringify(ref));
226
+ else {
227
+ try {
228
+ decoded = decodeURIComponent(seg);
229
+ }
230
+ catch {
231
+ throw new Error("malformed media source (bad percent-escape): " + JSON.stringify(ref));
232
+ }
159
233
  }
160
234
  if (!segmentConfined(decoded)) {
161
235
  throw new Error("media source refuses traversal: " + JSON.stringify(ref));
@@ -187,14 +261,6 @@ function isDir(p) {
187
261
  return false;
188
262
  }
189
263
  }
190
- function isFile(p) {
191
- try {
192
- return statSync(p).isFile();
193
- }
194
- catch {
195
- return false;
196
- }
197
- }
198
264
  /** Resolve every pointer the way the engine stages it — run faces
199
265
  * walk the manifest trees (first root holding the RUN DIR wins,
200
266
  * the file rides under it — the server's and the stager's shared
@@ -1,13 +1,41 @@
1
1
  import type { EngineJson } from "@melite/comfyui-cordis";
2
+ import type { FlowStageRow } from "./runsValidateShared.js";
2
3
  import type { QueueRefusal } from "./queue.js";
4
+ export { envelopeRefusal, unknownDraftRefusal } from "./queueSubmit.js";
3
5
  import type { RunId } from "./queueCore.js";
4
6
  import type { RunRecord } from "./runsTypes.js";
5
7
  /** The door's refusal shape (status carries the HTTP class; the
6
8
  * remote folds it into RemoteError details). */
7
9
  export type StartRefusal = QueueRefusal;
8
- /** One compiled stage (the rim the worker splices). */
10
+ export declare function compiledStageRow(st: CompiledStage): FlowStageRow;
11
+ /** THE DOC-LOCAL DERIVATION (audits F-S4/S5): validate derives a
12
+ * row's expected kinds from the card ports BEFORE the lattice runs;
13
+ * a durable doc carries no cards, so the replay judge derives from
14
+ * the doc's own declared upstream outputs — an absent expected
15
+ * takes the upstream kind, and a wire to an upstream output the doc
16
+ * never declares refuses here with the lattice's link voice
17
+ * (kindsOk's mismatch arm would fire first and name the wrong
18
+ * fact). Declared expected rows re-judge exactly as validate did.
19
+ * An edge to a stage OUTSIDE the doc (the bench lane's cross-wire —
20
+ * the worker injects those stages at compose) is not doc-derivable
21
+ * and drops out of the judged rows: the judge runs only where the
22
+ * kinds were derivable, never a false refusal on the legal wire.
23
+ * A doc with ANY filled-outputs row skips the judge wholesale: its
24
+ * real channels live in the card plane (validate + the compose own
25
+ * those verdicts), and the doc is not self-describing. */
26
+ export declare function replayJudgeRows(compiled: {
27
+ stages: CompiledStage[];
28
+ }): FlowStageRow[];
9
29
  export interface CompiledStage {
10
30
  readonly id: string;
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+ readonly benchStageId?: string;
11
39
  /** The stage's engine id (stroke 53): the card plane's engine or 'mcp:<server>'
12
40
  * — the door's engine gate admits exactly these; carried through
13
41
  * to the run rows so the worker dispatches by it. */
@@ -17,6 +45,11 @@ export interface CompiledStage {
17
45
  readonly expected: Record<string, EngineJson>;
18
46
  readonly outputNodes: Record<string, EngineJson>;
19
47
  readonly inputNames: Record<string, string>;
48
+ /** The stage DECLARED its outputs map (false = the engine-table
49
+ * fill supplied {default: ...}). The replay judge judges only
50
+ * fully-declared docs — a filled row's real channels live in the
51
+ * card plane (validate + the compose own those verdicts). */
52
+ readonly outputsDeclared: boolean;
20
53
  }
21
54
  /** flow_inline structural compile — door-verbatim (structure via
22
55
  * the admission verdicts, voice here; the engine policy +
@@ -33,20 +66,17 @@ export declare function compileFlowInline(inline: unknown, knownEngines?: readon
33
66
  } | StartRefusal;
34
67
  /** The door-selection gate: exactly one of flow / flow_inline /
35
68
  * model, in DOOR order for the ambiguity text (resolve_request
36
- * 302). Returns the selected door key, or the refusal. */
37
- export declare function selectSubmitDoor(body: Record<string, unknown>): {
38
- door: "flow" | "flow_inline" | "model";
69
+ * 302). Returns the selected door key, or the refusal. The
70
+ * `draftBench` option admits the DRAFT DOOR: a body with no door
71
+ * key over a live bench draft (the tool's familyless bench walk
72
+ * presses {test, draft_id} alone — a model key would select the
73
+ * card arm and hit the board check), which the caller restages
74
+ * onto the wired-bench compose. */
75
+ export declare function selectSubmitDoor(body: Record<string, unknown>, opts?: {
76
+ draftBench?: boolean;
77
+ }): {
78
+ door: "flow" | "flow_inline" | "model" | "draft";
39
79
  } | StartRefusal;
40
- /** The envelope refusal texts (door-verbatim, for the remote's
41
- * envelope walk). Kept as a table — one voice each, like the
42
- * admission gate's static tables. */
43
- export declare function envelopeRefusal(kind: "not-object" | "bad-test" | "missing-draft" | "malformed-draft", doc: unknown, detail?: {
44
- testFlag?: unknown;
45
- draftId?: string;
46
- }): StartRefusal;
47
- /** The unknown-draft refusal (door-verbatim; the probe rides the
48
- * caller's drafts domain — the remote hops the ctx seat). */
49
- export declare function unknownDraftRefusal(draftId: string): StartRefusal;
50
80
  /** The registration tail (door-verbatim): mint the id, route the
51
81
  * out root on the test flag, build the rich run row. The caller
52
82
  * (the remote) enqueues it on the queue core + kicks the pump.
@@ -109,10 +139,22 @@ export declare function registerCompiledRun(args: {
109
139
  * initials, on the card arm, and on a hand-authored or
110
140
  * bench-composed inline doc. */
111
141
  initials?: Record<string, EngineJson>;
142
+ /** The FILE-kind subset of initials' keys (photo | glb) — the
143
+ * claim-time re-probe's contract (the row stamps it beside
144
+ * initials so the pump knows which entries to re-judge on
145
+ * disk). Absent when no file initials ride. */
146
+ initialFileKeys?: string[];
112
147
  /** The bench doc read at submit (stroke 45d) — the FULL workflow
113
148
  * the run was born from (all stages + intent), stamped verbatim
114
149
  * so the wand restores the whole flow, not just the ran card. */
115
150
  benchDoc?: Record<string, unknown>;
151
+
152
+
153
+
154
+ fam?: string;
155
+ /** The flow arm's {stageId: fam} ledger for the same probe (the
156
+ * stage rows stay schema-clean). */
157
+ stageFams?: Record<string, string>;
116
158
  };
117
159
  }): Promise<{
118
160
  run: RunRecord;
package/lib/runsStart.js CHANGED
@@ -14,14 +14,130 @@ import { CARD_PLANE_ENGINE } from "@melite/contracts/benchStage";
14
14
  // refusals that remain are the ones listed at their own arms: the
15
15
  // compile gates (an unknown node, an undeclared input, a dead wire,
16
16
  // a self-wire) and the initial gate (a missing FromStage initial).
17
- import { mkdirSync } from "node:fs";
17
+ import { mkdirSync, rmSync } from "node:fs";
18
18
  import { join } from "node:path";
19
- import { engineIdOk } from "@melite/engine-contract";
19
+ import { FlowError } from "./runsValidateShared.js";
20
+ import { AGENT_ENGINE_ID, CRAFT_ENGINE_ID, COMFYUI_ENGINE_ID, engineIdOk, } from "@melite/engine-contract";
20
21
  import { FLOW_INLINE_TOP_VOICE, INLINE_TOP_KEYS, STAGE_KEYS, checkFlowInlineTop, checkFlowStage, } from "./runsGates.js";
21
22
  import { appendLedger, outRootFor, refusal, sidecarDoc, sidecarStageOf, variantOfBodies, writeJsonAtomic } from "./queue.js";
23
+ import { lifecycleInFlight } from "./lifecycleLatch.js";
24
+ import { toRemoteError } from "./runsRefusalVoices.js";
25
+ import { ENGINE_TABLE } from "./runsValidateShared.js";
22
26
  import { rootsManifest } from "./rootsManifest.js";
27
+ // the envelope-refusal SSOT lives in queueSubmit.ts (beside
28
+ // walkSubmitEnvelope, the one walker the registry delegates to) —
29
+ // re-exported here so the registry's import sites stay stable
30
+ export { envelopeRefusal, unknownDraftRefusal } from "./queueSubmit.js";
31
+ // the doors twin's one home (the envelope-twin cure): the door set
32
+ // and both refusal texts ride queueSubmit's helpers
33
+ import { submitDoorsOf, ambiguousDoorsRefusal, noDoorRefusal } from "./queueSubmit.js";
23
34
  import { saveBenchSnapshotStages } from "@melite/contracts/benchSnapshot";
24
35
  import { collectSourceRefs, resolveSourceRefs } from "./runsSourceEcho.js";
36
+ /** One compiled stage (the rim the worker splices). */
37
+ /** THE COMPILED→WIRE PROJECTION (audits F-S4/S5 — the start-side
38
+ * parity judge consumes wire rows, the door compiles its own):
39
+ * inputNames encodes the source ("stage.output" or
40
+ * "__initial__.key") — stage ids are legal identifiers, so the
41
+ * first dot splits a stage ref exactly; only string-valued
42
+ * outputs/expected ride (the wire contract's kind map — anything
43
+ * else skips judgment, never coerced). */
44
+ const kindEntries = (m) => {
45
+ const rows = [];
46
+ for (const [name, v] of Object.entries(m)) {
47
+ if (typeof v === "string")
48
+ rows.push({ name, kind: v });
49
+ }
50
+ return rows;
51
+ };
52
+ export function compiledStageRow(st) {
53
+ return {
54
+ id: st.id,
55
+ engine: st.engine,
56
+ description: "",
57
+ params: st.params,
58
+ inputs: Object.entries(st.inputNames).map(([name, src]) => {
59
+ if (src.startsWith("__initial__.")) {
60
+ return { name, edge: { kind: "initial", key: src.slice("__initial__.".length) } };
61
+ }
62
+ const dot = src.indexOf(".");
63
+ return {
64
+ name,
65
+ edge: { kind: "stage", stage: src.slice(0, dot), output: src.slice(dot + 1) },
66
+ };
67
+ }),
68
+ outputs: kindEntries(st.outputs),
69
+ expected: kindEntries(st.expected),
70
+ card: "",
71
+ cardIo: [],
72
+ skipWhen: null,
73
+ };
74
+ }
75
+ /** THE DOC-LOCAL DERIVATION (audits F-S4/S5): validate derives a
76
+ * row's expected kinds from the card ports BEFORE the lattice runs;
77
+ * a durable doc carries no cards, so the replay judge derives from
78
+ * the doc's own declared upstream outputs — an absent expected
79
+ * takes the upstream kind, and a wire to an upstream output the doc
80
+ * never declares refuses here with the lattice's link voice
81
+ * (kindsOk's mismatch arm would fire first and name the wrong
82
+ * fact). Declared expected rows re-judge exactly as validate did.
83
+ * An edge to a stage OUTSIDE the doc (the bench lane's cross-wire —
84
+ * the worker injects those stages at compose) is not doc-derivable
85
+ * and drops out of the judged rows: the judge runs only where the
86
+ * kinds were derivable, never a false refusal on the legal wire.
87
+ * A doc with ANY filled-outputs row skips the judge wholesale: its
88
+ * real channels live in the card plane (validate + the compose own
89
+ * those verdicts), and the doc is not self-describing. */
90
+ export function replayJudgeRows(compiled) {
91
+ if (compiled.stages.some((st) => !st.outputsDeclared))
92
+ return [];
93
+ const rows = compiled.stages.map(compiledStageRow);
94
+ const docStages = new Set(rows.map((r) => r.id));
95
+ const outputsByStage = new Map(rows.map((r) => [r.id, new Map(r.outputs.map((o) => [o.name, o.kind]))]));
96
+ const judged = [];
97
+ for (const row of rows) {
98
+ const expected = new Set(row.expected.map((e) => e.name));
99
+ const inputs = [];
100
+ for (const inp of row.inputs) {
101
+ if (inp.edge.kind === "stage" && !docStages.has(inp.edge.stage)) {
102
+ // the edge is undecidable without its stage — the declared
103
+ // expected rides the same undecidability and drops with it
104
+ row.expected = row.expected.filter((e) => e.name !== inp.name);
105
+ continue;
106
+ }
107
+ inputs.push(inp);
108
+ if (inp.edge.kind !== "stage")
109
+ continue;
110
+ const upstream = outputsByStage.get(inp.edge.stage);
111
+ if (upstream === undefined)
112
+ continue;
113
+ const upstreamKind = upstream.get(inp.edge.output);
114
+ if (upstreamKind === undefined) {
115
+ throw new FlowError("flow stage " +
116
+ JSON.stringify(row.id) +
117
+ " input " +
118
+ JSON.stringify(inp.name) +
119
+ ": stage " +
120
+ JSON.stringify(inp.edge.stage) +
121
+ " has no output named " +
122
+ JSON.stringify(inp.edge.output) +
123
+ " (declared outputs: " +
124
+ JSON.stringify([...upstream.keys()].sort()) +
125
+ ")");
126
+ }
127
+ if (!expected.has(inp.name))
128
+ row.expected.push({ name: inp.name, kind: upstreamKind });
129
+ }
130
+ row.inputs = inputs;
131
+ // A declared expected whose input never wired in-doc is supplied
132
+ // by the compose plane (the card-port rows) — same
133
+ // non-self-describing class as a filled output: skip the doc.
134
+ const wired = new Set(inputs.map((i) => i.name));
135
+ if (row.expected.some((e) => !wired.has(e.name)))
136
+ return [];
137
+ judged.push(row);
138
+ }
139
+ return judged;
140
+ }
25
141
  /** flow_inline structural compile — door-verbatim (structure via
26
142
  * the admission verdicts, voice here; the engine policy +
27
143
  * default-fills below are value-domain, not type structure).
@@ -89,7 +205,10 @@ export function compileFlowInline(inline, knownEngines = [CARD_PLANE_ENGINE]) {
89
205
  JSON.stringify(sid) +
90
206
  " names engine " +
91
207
  JSON.stringify(engine) +
92
- " — engine ids are '" + CARD_PLANE_ENGINE + "' or 'mcp:<server>' ([A-Za-z0-9_-]{1,32})", "invalid_request");
208
+ " — engine ids are " +
209
+ COMFYUI_ENGINE_ID + ", " + CRAFT_ENGINE_ID + ", " +
210
+ AGENT_ENGINE_ID +
211
+ " or 'mcp:<server>' ([A-Za-z0-9_-]{1,32})", "invalid_request");
93
212
  }
94
213
  if (!knownEngines.includes(engine)) {
95
214
  return refusal(400, "flow_inline stage " +
@@ -155,9 +274,19 @@ export function compileFlowInline(inline, knownEngines = [CARD_PLANE_ENGINE]) {
155
274
  const params = typeof st["params"] === "object" && st["params"] !== null && !Array.isArray(st["params"])
156
275
  ? st["params"]
157
276
  : {};
158
- const outputs = typeof st["outputs"] === "object" && st["outputs"] !== null && !Array.isArray(st["outputs"])
159
- ? st["outputs"]
160
- : { default: "image" }; // the engine DEFAULT_OUTPUT fill
277
+
278
+ // validate's lattice treats an EMPTY outputs map as stageless
279
+ // and judges the stage by the engine's table def (craft->image,
280
+ // agent->text); start's flat "image" bound a different kind than
281
+ // the lattice judged. One fill law, both doors: empty-or-absent
282
+ // outputs take the table's default channel.
283
+ const declaredOutputs = st["outputs"];
284
+ const outputsDeclared = typeof declaredOutputs === "object" && declaredOutputs !== null &&
285
+ !Array.isArray(declaredOutputs) &&
286
+ Object.keys(declaredOutputs).length > 0;
287
+ const outputs = outputsDeclared
288
+ ? declaredOutputs
289
+ : { default: ENGINE_TABLE[engine] !== undefined ? ENGINE_TABLE[engine].def : "image" };
161
290
  const expected = typeof st["expected"] === "object" && st["expected"] !== null && !Array.isArray(st["expected"])
162
291
  ? st["expected"]
163
292
  : {};
@@ -212,56 +341,30 @@ export function compileFlowInline(inline, knownEngines = [CARD_PLANE_ENGINE]) {
212
341
  JSON.stringify([...new Set(ghosts)].sort()) +
213
342
  " but the stage wires no input of that name — the merge would refuse it at run time ('$name' must name a FromStage-wired input or a request initial; name it or wire it)", "invalid_request");
214
343
  }
215
- stages.push({ id: sid, engine, params, outputs, expected, outputNodes, inputNames });
344
+ stages.push({ id: sid, engine, params, outputs, outputsDeclared, expected, outputNodes, inputNames });
216
345
  }
217
346
  return { stages };
218
347
  }
219
348
  /** The door-selection gate: exactly one of flow / flow_inline /
220
349
  * model, in DOOR order for the ambiguity text (resolve_request
221
- * 302). Returns the selected door key, or the refusal. */
222
- export function selectSubmitDoor(body) {
223
- const doors = ["flow", "flow_inline", "model"].filter((k) => k in body);
350
+ * 302). Returns the selected door key, or the refusal. The
351
+ * `draftBench` option admits the DRAFT DOOR: a body with no door
352
+ * key over a live bench draft (the tool's familyless bench walk
353
+ * presses {test, draft_id} alone — a model key would select the
354
+ * card arm and hit the board check), which the caller restages
355
+ * onto the wired-bench compose. */
356
+ export function selectSubmitDoor(body, opts = {}) {
357
+ const doors = submitDoorsOf(body);
224
358
  if (doors.length > 1) {
225
- return refusal(400, "ambiguous request: names " +
226
- JSON.stringify(doors) +
227
- " — provide exactly one of flow, flow_inline, model", "invalid_request");
359
+ return ambiguousDoorsRefusal(doors);
228
360
  }
229
361
  if (doors.length === 0) {
230
- return refusal(400, "no flow selected: provide flow, flow_inline or model", "invalid_request");
362
+ if (opts.draftBench === true)
363
+ return { door: "draft" };
364
+ return noDoorRefusal();
231
365
  }
232
366
  return { door: doors[0] };
233
367
  }
234
- /** The envelope refusal texts (door-verbatim, for the remote's
235
- * envelope walk). Kept as a table — one voice each, like the
236
- * admission gate's static tables. */
237
- export function envelopeRefusal(kind, doc, detail) {
238
- switch (kind) {
239
- case "not-object":
240
- return refusal(400, "request body must be a JSON object", "bad_envelope", "body", "object", Array.isArray(doc) ? "array" : typeof doc);
241
- case "bad-test":
242
- return refusal(400, "test flag must be a boolean (got " +
243
- (typeof detail?.testFlag) +
244
- " " +
245
- JSON.stringify(detail?.testFlag) +
246
- ")", "bad_envelope", "test", "boolean", (typeof detail?.testFlag));
247
- case "missing-draft":
248
- return refusal(400, "draft_id is required — every run is born from an " +
249
- "action card (CARD BIRTH LAW); compose the card first: " +
250
- "POST /v1/flows/drafts, then start with its draft_id", "draft_required", "draft_id", "doc-backed draft id", "absent");
251
- case "malformed-draft":
252
- return refusal(400, "draft_id malformed (96 char cap, [A-Za-z0-9_-] only): " +
253
- JSON.stringify(detail?.draftId ?? ""), "draft_malformed", "draft_id", "[A-Za-z0-9_-]{1,96}", (detail?.draftId ?? "").slice(0, 60));
254
- }
255
- }
256
- /** The unknown-draft refusal (door-verbatim; the probe rides the
257
- * caller's drafts domain — the remote hops the ctx seat). */
258
- export function unknownDraftRefusal(draftId) {
259
- return refusal(400, "unknown draft_id " +
260
- JSON.stringify(draftId) +
261
- " — no card doc at drafts/" +
262
- draftId +
263
- ".json; compose the card first: POST /v1/flows/drafts", "draft_unknown", "draft_id", "existing card doc", draftId.slice(0, 60));
264
- }
265
368
  /** The registration tail (door-verbatim): mint the id, route the
266
369
  * out root on the test flag, build the rich run row. The caller
267
370
  * (the remote) enqueues it on the queue core + kicks the pump.
@@ -310,6 +413,7 @@ export async function registerCompiledRun(args) {
310
413
  status: "queued",
311
414
  stages: compiled.stages.map((st, i) => ({
312
415
  id: st.id,
416
+ ...(st.benchStageId !== undefined ? { benchStageId: st.benchStageId } : {}),
313
417
  name: st.id,
314
418
  index: i,
315
419
  status: "pending",
@@ -330,6 +434,9 @@ export async function registerCompiledRun(args) {
330
434
  graphRows,
331
435
  outputNodes: compiled.stages.map((st) => ({ ...st.outputNodes })),
332
436
  initials: { ...door.initials },
437
+ ...(door.initialFileKeys !== undefined && door.initialFileKeys.length > 0
438
+ ? { initialFileKeys: [...door.initialFileKeys] }
439
+ : {}),
333
440
  };
334
441
  run.inputNames = Object.fromEntries(compiled.stages.map((st) => [st.id, { ...st.inputNames }]));
335
442
  if (args.warnings !== undefined && args.warnings.length > 0) {
@@ -344,6 +451,16 @@ export async function registerCompiledRun(args) {
344
451
  run.pipeline = door.pipeline;
345
452
  if (door.cardId !== undefined)
346
453
  run.cardId = door.cardId;
454
+
455
+ // gate ran at press; weights can leave between press and claim.
456
+ // The row carries the card arm's family so the pump re-probes at
457
+ // claim and fails loud with the lane voice — never an unnamed
458
+ // engine-side death. Flow stages stamp fam per stage row.
459
+ if (door.fam !== undefined && door.fam !== "")
460
+ run.fam = door.fam;
461
+ if (door.stageFams !== undefined && Object.keys(door.stageFams).length > 0) {
462
+ run.stageFams = door.stageFams;
463
+ }
347
464
  // THE CARD SNAPSHOT LAW (stroke 45, the operator's wand complaint):
348
465
  // _flow.json's stage faces are HOLLOW (ids/status only) — the card
349
466
  // + params that actually ran were recorded nowhere, so "restore the
@@ -469,6 +586,28 @@ export async function registerCompiledRun(args) {
469
586
  }
470
587
  await writeJsonAtomic(join(dir, "_request.json"), requestBody);
471
588
  await writeJsonAtomic(join(dir, "_flow.json"), sidecarDocFor(run));
589
+
590
+ // the press read the latch five awaits ago (RunsRegistry.start's
591
+ // gate); a teardown whose guard passed on the then-empty census can
592
+ // hold it by now. The sidecar above made this run visible to the
593
+ // census, so any teardown from here on is refused by the guard —
594
+ // the refused press removes the minted dir and answers the same
595
+ // named code, having told the ledger nothing.
596
+ const heldLifecycle = lifecycleInFlight();
597
+ if (heldLifecycle !== null) {
598
+ // The unlink is best-effort: a failed removal must not replace the
599
+ // named 409 (the client would lose the retry-hint code) — but the
600
+ // leftover queued sidecar poisons the teardown guard until a sweep
601
+ // clears it, so the failure is logged loudly, never swallowed.
602
+ try {
603
+ rmSync(dir, { recursive: true, force: true });
604
+ }
605
+ catch (cleanupError) {
606
+ console.error(`[runs] refused press could not remove ${dir}:`, cleanupError);
607
+ }
608
+ throw toRemoteError(refusal(409, "refused: lifecycle " + heldLifecycle +
609
+ " in flight — retry the press when it settles (the teardown holds the run gate until it completes)", "lifecycle_inflight"));
610
+ }
472
611
  if (echoCalls.length > 0) {
473
612
  appendLedger(stateRoot, "run.queued", {
474
613
  run_id: runId,
@@ -11,6 +11,13 @@ export declare const RUN_STATUSES: ReadonlySet<string>;
11
11
  /** One stage row — key order mirrors submit's literal. */
12
12
  export interface RunStageRow {
13
13
  id: string;
14
+
15
+
16
+
17
+
18
+
19
+
20
+ benchStageId?: string;
14
21
  name: string;
15
22
  index: number;
16
23
  status: string;
@@ -46,6 +53,14 @@ export interface RunRecord {
46
53
  * Empty for runs whose flow declares no initials and for a
47
54
  * failed resurrect's floor row. */
48
55
  initials: Record<string, EngineJson>;
56
+ /** The FILE-kind subset of initials' keys (photo | glb — the
57
+ * kinds whose values must exist on disk), stamped beside
58
+ * initials so the claim-time re-probe knows which entries to
59
+ * re-judge without re-deriving kinds (the stageFams ledger
60
+ * law: the row carries the judgment's input, not a new
61
+ * lookup). Absent = nothing to re-probe (no file initials, a
62
+ * card run, or a floor row). */
63
+ initialFileKeys?: string[];
49
64
  /** The settle persist (R3 mirror): registration stamps these so
50
65
  * settle can rewrite the sidecar + ledger row. createdAt is
51
66
  * epoch seconds. */
@@ -58,6 +73,12 @@ export interface RunRecord {
58
73
  /** The card door's id (stamped at registration; inline runs leave
59
74
  * it absent — never a guessed card). */
60
75
  cardId?: string;
76
+
77
+
78
+
79
+
80
+
81
+ pressKey?: string;
61
82
  /** THE CARD SNAPSHOT (stroke 45): the exact card + body that ran
62
83
  * ({card, params}) — the wand restores from this, never from the
63
84
  * living bench. Stamped at registration, carried through settle
@@ -77,6 +98,20 @@ export interface RunRecord {
77
98
 
78
99
 
79
100
 
101
+ replaySuspect?: boolean;
102
+
103
+
104
+
105
+ fam?: string;
106
+ /** The flow arm's {stageId: fam} ledger (the claim-time presence
107
+ * re-probe reads it beside fam). */
108
+ stageFams?: Record<string, string>;
109
+
110
+
111
+
112
+
113
+
114
+
80
115
 
81
116
  exportName?: string;
82
117