@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
@@ -14,9 +14,46 @@ export function refusal(status, error, code, loc, expected, got) {
14
14
  payload["got"] = got;
15
15
  return { status, payload };
16
16
  }
17
+ /** The envelope refusal texts (door-verbatim, the ONE voice — both
18
+ * the submit envelope validator below and the registry's envelope
19
+ * walk delegate here; one copy, no drift). Kept as a table — one
20
+ * voice each, like the admission gate's static tables. */
21
+ export function envelopeRefusal(kind, doc, detail) {
22
+ switch (kind) {
23
+ case "not-object":
24
+ return refusal(400, "request body must be a JSON object", "bad_envelope", "body", "object", Array.isArray(doc) ? "array" : typeof doc);
25
+ case "bad-test":
26
+ return refusal(400, "test flag must be a boolean (got " +
27
+ (typeof detail?.testFlag) +
28
+ " " +
29
+ JSON.stringify(detail?.testFlag) +
30
+ ")", "bad_envelope", "test", "boolean", (typeof detail?.testFlag));
31
+ case "missing-draft":
32
+ return refusal(400, "draft_id is required — every run is born from an " +
33
+ "action card (CARD BIRTH LAW); compose the card first: " +
34
+ "POST /v1/flows/drafts, then start with its draft_id", "draft_required", "draft_id", "doc-backed draft id", "absent");
35
+ case "malformed-draft":
36
+ return refusal(400, "draft_id malformed (96 char cap, [A-Za-z0-9_-] only): " +
37
+ JSON.stringify(detail?.draftId ?? ""), "draft_malformed", "draft_id", "[A-Za-z0-9_-]{1,96}", (detail?.draftId ?? "").slice(0, 60));
38
+ default:
39
+ // Closed union: a new refusal kind fails loud at compile, not
40
+ // silently undefined at the door. assertNever from
41
+ // @deepseek-ai/dsh-util-values (maintained helper, not a handroll).
42
+ return assertNever(kind, "queueSubmit.envelopeRefusal");
43
+ }
44
+ }
45
+ /** The unknown-draft refusal (door-verbatim; the probe rides the
46
+ * caller's drafts domain — the remote hops the ctx seat). */
47
+ export function unknownDraftRefusal(draftId) {
48
+ return refusal(400, "unknown draft_id " +
49
+ JSON.stringify(draftId) +
50
+ " — no card doc at drafts/" +
51
+ draftId +
52
+ ".json; compose the card first: POST /v1/flows/drafts", "draft_unknown", "draft_id", "existing card doc", draftId.slice(0, 60));
53
+ }
17
54
  /** Draft id rule (draftIdOk in @melite/estate-drafts, re-exported below): <=96 chars of [A-Za-z0-9_-]. */
18
55
  /** This core re-checks nothing: it BUILDS the refusal for a caller-computed verdict (the check is one regex, owned by the drafts package so envelope validation is whole). */
19
- /** Callers pass the raw draft_id; the malformed/unknown split needs the existence probe too — see validateSubmitEnvelope. */
56
+ /** Callers pass the raw draft_id; the malformed/unknown split needs the existence probe too — see walkSubmitEnvelope. */
20
57
 
21
58
 
22
59
 
@@ -30,6 +67,7 @@ export { draftIdOk } from "@melite/estate-drafts";
30
67
  // these re-exports keep the @melite/gateway-queue barrel stable.
31
68
  export { RETIRED_RUNNER_KNOBS, RETIRED_CARRY_KEYS, DOOR_KEYS, } from "./vocab.js";
32
69
  import { RETIRED_RUNNER_KNOBS, RETIRED_CARRY_KEYS, DOOR_KEYS, } from "./vocab.js";
70
+ import { assertNever } from "@deepseek-ai/dsh-util-values";
33
71
  import { draftIdOk } from "@melite/estate-drafts";
34
72
  /** The strict-body gate (_strict_body 248-276). */
35
73
  export function strictBodyCheck(body) {
@@ -55,63 +93,99 @@ export function strictBodyCheck(body) {
55
93
  }
56
94
  return null;
57
95
  }
58
- /** Door-selection order (resolve_request 302: flow/flow_inline/
59
- * model fixed order — ambiguity lists in DOOR order, not sorted). */
60
- export const SUBMIT_DOORS = [
61
- "flow",
62
- "flow_inline",
63
- "model",
64
- ];
65
- /** The whole pre-registration chain in order: non-object body
66
- * (bad_envelope/body) -> non-bool test (bad_envelope/test) ->
67
- * draft required (draft_required) -> malformed (draft_malformed)
68
- * -> unknown doc (draft_unknown) -> strict knobs/carry ->
69
- * ambiguity (verbatim) -> no-door. draftExists is the caller's
70
- * `drafts/<id>.json is_file` probe (existence is I/O — the core
71
- * owns the TEXT, the door owns the fs). Returns null when the
72
- * envelope may proceed to graph resolution. */
73
- export function validateSubmitEnvelope(doc, draftExists) {
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+ export function submitEnvelopeStructuralRefusal(doc) {
74
110
  if (typeof doc !== "object" || doc === null || Array.isArray(doc)) {
75
- return refusal(400, "request body must be a JSON object", "bad_envelope", "body", "object", (typeof doc));
111
+ return envelopeRefusal("not-object", doc);
76
112
  }
77
113
  const body = doc;
78
114
  const testFlag = body["test"] ?? false;
79
115
  if (typeof testFlag !== "boolean") {
80
- return refusal(400, "test flag must be a boolean (got " +
81
- (typeof testFlag) +
82
- " " +
83
- JSON.stringify(testFlag) +
84
- ")", "bad_envelope", "test", "boolean", (typeof testFlag));
116
+ return envelopeRefusal("bad-test", doc, { testFlag });
85
117
  }
86
118
  const draftId = body["draft_id"];
87
119
  if (typeof draftId !== "string" || draftId === "") {
88
- return refusal(400, "draft_id is required — every run is born from an " +
89
- "action card (CARD BIRTH LAW); compose the card first: " +
90
- "POST /v1/flows/drafts, then start with its draft_id", "draft_required", "draft_id", "doc-backed draft id", "absent");
120
+ return envelopeRefusal("missing-draft", doc);
91
121
  }
92
122
  if (!draftIdOk(draftId)) {
93
- return refusal(400, "draft_id malformed (96 char cap, [A-Za-z0-9_-] only): " +
94
- JSON.stringify(draftId), "draft_malformed", "draft_id", "[A-Za-z0-9_-]{1,96}", draftId.slice(0, 60));
95
- }
96
- if (!draftExists(draftId)) {
97
- return refusal(400, "unknown draft_id " +
98
- JSON.stringify(draftId) +
99
- " — no card doc at drafts/" +
100
- draftId +
101
- ".json; compose the card first: POST /v1/flows/drafts", "draft_unknown", "draft_id", "existing card doc", draftId.slice(0, 60));
102
- }
103
- const strict = strictBodyCheck(body);
104
- if (strict !== null)
105
- return strict;
106
- const doors = SUBMIT_DOORS.filter((k) => Object.prototype.hasOwnProperty.call(body, k));
107
- if (doors.length > 1) {
108
- return refusal(400, "ambiguous request: names " +
109
- JSON.stringify(doors) +
110
- " — provide exactly one of flow, flow_inline, model", "invalid_request");
123
+ return envelopeRefusal("malformed-draft", doc, { draftId });
111
124
  }
112
- if (doors.length === 0) {
113
- return refusal(400, "no flow selected: provide flow, flow_inline or model", "invalid_request");
125
+ // THE PRESS KEY (audit N-E1): an OPTIONAL client-minted id naming
126
+ // THE PRESS — a transport retry or a double-fire of one press
127
+ // replays the same key, and the registry answers the FIRST run
128
+ // instead of minting a second one. Absent = the legacy behavior
129
+ // (every call is a new press). Opaque: bounded length, safe
130
+ // charset, never interpreted.
131
+ const pressKey = body["press_key"];
132
+ if (pressKey !== undefined) {
133
+ if (typeof pressKey !== "string" || !/^[-A-Za-z0-9_.]{8,128}$/.test(pressKey)) {
134
+ return refusal(400, "press_key must be 8-128 chars of [-A-Za-z0-9_.] — it names ONE press across retries", "invalid_request", "press_key");
135
+ }
114
136
  }
115
137
  return null;
116
138
  }
139
+ /** Door-selection order (resolve_request 302: flow/flow_inline/
140
+ * model fixed order — ambiguity lists in DOOR order, not sorted). */
141
+ export const SUBMIT_DOORS = [
142
+ "flow",
143
+ "flow_inline",
144
+ "model",
145
+ ];
146
+ /** The walker's chain in order: non-object body (bad_envelope/body)
147
+ * -> non-bool test (bad_envelope/test) -> draft required
148
+ * (draft_required) -> malformed (draft_malformed) -> unknown doc
149
+ * (draft_unknown). The probe is the caller's seat (existence is
150
+ * I/O — the walker owns the TEXT, the seat owns the fs). Strict
151
+ * knobs and door selection judge past the walk, at startReserved. */
152
+ /** The door-selection helpers, ONE HOME (the envelope-twin cure's
153
+ * doors half): the shared door set and the runs seat's
154
+ * selectSubmitDoor derive the door set and both
155
+ * refusal texts from HERE — the wire contract cannot drift
156
+ * between the two seats. hasOwnProperty (never `in`): a door is a
157
+ * body-own key, not a prototype inheritance. */
158
+ export function submitDoorsOf(body) {
159
+ return SUBMIT_DOORS.filter((k) => Object.prototype.hasOwnProperty.call(body, k));
160
+ }
161
+ /** The too-many-doors refusal (text is the wire contract). */
162
+ export function ambiguousDoorsRefusal(doors) {
163
+ return refusal(400, "ambiguous request: names " +
164
+ JSON.stringify(doors) +
165
+ " — provide exactly one of flow, flow_inline, model", "invalid_request");
166
+ }
167
+ /** The no-door refusal (text is the wire contract). */
168
+ export function noDoorRefusal() {
169
+ return refusal(400, "no flow selected: provide flow, flow_inline or model", "invalid_request");
170
+ }
171
+ /** THE ONE ENVELOPE WALKER (the S3 twin cure): the structural
172
+ * faces, the draft probe ordering and the ok face live HERE and
173
+ * the runs registration delegates — there is no second sync face
174
+ * to drift against. draftExists is the caller's probe (the runs
175
+ * seat hops to the drafts service and awaits; a sync caller passes
176
+ * a sync probe — one signature carries both). Returns the ok face
177
+ * when the envelope may proceed to door selection, which the live
178
+ * face owns at startReserved (strict then doors, after the
179
+ * replay/reservation verdict). */
180
+ export async function walkSubmitEnvelope(doc, draftExists) {
181
+ const structural = submitEnvelopeStructuralRefusal(doc);
182
+ if (structural !== null)
183
+ return { kind: "refusal", refusal: structural };
184
+ const body = doc;
185
+ const draftId = body["draft_id"];
186
+ if (!(await draftExists(draftId))) {
187
+ return { kind: "refusal", refusal: unknownDraftRefusal(draftId) };
188
+ }
189
+ return { kind: "ok", body, testFlag: body["test"] === true, draftId };
190
+ }
117
191
  //# sourceMappingURL=queueSubmit.js.map
package/lib/queueSweep.js CHANGED
@@ -4,7 +4,7 @@
4
4
  //
5
5
  // Erasable-syntax TS only (node --experimental-strip-types): no
6
6
  // enums, import type for types, .ts specifiers for relative imports.
7
- import { readdirSync, readFileSync } from "node:fs";
7
+ import { readdirSync, readFileSync, rmSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { appendLedger, writeJsonAtomic } from "./queueLock.js";
10
10
  /** Patch a stale sidecar (pure half of sweep_sidecar): every
@@ -102,7 +102,18 @@ export async function bootSweep(stateRoot, liveRunIds = [], nowS = Math.floor(Da
102
102
  // not vanish from the sweep silently — the QUEUE LANE LAW
103
103
  // wants every boot disposition ledgered so the operator can
104
104
  // reconcile (the old bare continue left an unaudited row).
105
- appendLedger(stateRoot, "run.swept", { run_id: name, state: "unreadable", error: `boot sweep: _flow.json parse failed: ${e instanceof Error ? e.message : String(e)}` }, nowS);
105
+ // THE CRASH-ORPHAN (lifecycle audit Q5): an ABSENT sidecar is
106
+ // the press that died between its two writes — the run was
107
+ // never enqueued, so the id is observed once here and the dir
108
+ // is reclaimed instead of sitting as orphan bytes. A
109
+ // PRESENT-but-unparsable sidecar keeps the ledger-only
110
+ // disposition (operator reconcile owns the genuinely corrupt).
111
+ const orphaned = e instanceof Error && e.code === "ENOENT";
112
+ if (orphaned)
113
+ rmSync(join(outRoot, name), { recursive: true, force: true });
114
+ appendLedger(stateRoot, "run.swept", { run_id: name, state: "unreadable", error: orphaned
115
+ ? "boot sweep: _flow.json absent — crash-orphaned dir dropped"
116
+ : `boot sweep: _flow.json parse failed: ${e instanceof Error ? e.message : String(e)}` }, nowS);
106
117
  continue;
107
118
  }
108
119
  if (typeof current !== "object" || current === null || Array.isArray(current)) {
@@ -13,6 +13,7 @@ declare module "@deepseek-ai/cordis" {
13
13
  * A run row moved — a claim (queued→running), a settle
14
14
  * (terminal), an artifacts harvest, or a stop press (→stopping).
15
15
  * Emitted after the write landed.
16
+ * @mode emit
16
17
  * @param runId - the run whose row moved.
17
18
  */
18
19
  "runs.changed": (runId: string) => void;
@@ -25,6 +26,13 @@ declare module "@deepseek-ai/cordis" {
25
26
  * is single-tenant here, and the failure mode is loud — onRunChange
26
27
  * refuses rather than subscribing to nothing). */
27
28
  export declare function setRunsChangeSeam(seam: RunsChangeSeam | null): void;
29
+ /** Detach the seam ONLY if `seam` is still the installed one — the
30
+ * ownership stamp that keeps dispose honest: a fiber that installed
31
+ * EARLIER (a newer install displaced it) detaches nothing, so the
32
+ * live seam survives the older fiber's unwind.
33
+ * @param seam - the seam instance the caller installed.
34
+ */
35
+ export declare function clearRunsChangeSeam(seam: RunsChangeSeam): void;
28
36
 
29
37
 
30
38
 
package/lib/runsChange.js CHANGED
@@ -8,6 +8,16 @@ let runsChangeSeam = null;
8
8
  export function setRunsChangeSeam(seam) {
9
9
  runsChangeSeam = seam;
10
10
  }
11
+ /** Detach the seam ONLY if `seam` is still the installed one — the
12
+ * ownership stamp that keeps dispose honest: a fiber that installed
13
+ * EARLIER (a newer install displaced it) detaches nothing, so the
14
+ * live seam survives the older fiber's unwind.
15
+ * @param seam - the seam instance the caller installed.
16
+ */
17
+ export function clearRunsChangeSeam(seam) {
18
+ if (runsChangeSeam === seam)
19
+ runsChangeSeam = null;
20
+ }
11
21
 
12
22
 
13
23
 
@@ -24,8 +34,11 @@ export function onRunChange(fn) {
24
34
  try {
25
35
  fn(runId);
26
36
  }
27
- catch {
28
- /* a listener's fault never breaks the write */
37
+ catch (fault) {
38
+
39
+
40
+
41
+ console.error("runs.changed listener fault:", fault);
29
42
  }
30
43
  });
31
44
  }
@@ -48,14 +61,17 @@ export function notifyRunChanged(runId) {
48
61
  export function installRunsChangeSeam(ctx) {
49
62
  let detach = null;
50
63
  ctx.effect(() => {
51
- setRunsChangeSeam({
64
+ const mine = {
52
65
  emit: (runId) => { ctx.emit("runs.changed", runId); },
53
66
  on: (fn) => {
54
67
  const stop = ctx.on("runs.changed", fn);
55
68
  return () => { stop(); };
56
69
  },
57
- });
58
- detach = () => { setRunsChangeSeam(null); };
70
+ };
71
+ setRunsChangeSeam(mine);
72
+ // the ownership stamp: an older fiber's unwind clears only its own
73
+ // install — a displaced seam detaches nothing (clearRunsChangeSeam)
74
+ detach = () => { clearRunsChangeSeam(mine); };
59
75
  return detach;
60
76
  });
61
77
  return () => { detach?.(); };
@@ -1,2 +1,2 @@
1
- export declare const RUNS_ERROR_CODES: Readonly<Record<string, "runs/bad-envelope" | "runs/draft-required" | "runs/draft-malformed" | "runs/draft-unknown" | "runs/invalid-request" | "runs/preview-scope" | "runs/flow-compile" | "runs/workflow-pin" | "runs/card-compose" | "runs/lane-input-missing">>;
1
+ export declare const RUNS_ERROR_CODES: Readonly<Record<string, "runs/bad-envelope" | "runs/draft-required" | "runs/draft-malformed" | "runs/draft-unknown" | "runs/invalid-request" | "runs/preview-scope" | "runs/flow-compile" | "runs/workflow-pin" | "runs/card-compose" | "runs/card-compose-incomplete" | "runs/lane-input-missing" | "runs/lifecycle-inflight">>;
2
2
  //# sourceMappingURL=runsErrorCodes.d.ts.map
@@ -1,5 +1,36 @@
1
1
  // runsErrorCodes.ts — the refusal-code -> HTTP answer-code table
2
2
  // (the one mapping; an unnamed code is a LOUD bug, never generic).
3
+ //
4
+
5
+ // NEW envelope code must touch every seat below in the same change,
6
+ // or it compiles and then bites later —
7
+ // 1. a row HERE (the envelope spelling -> the runs/* wire value);
8
+ // 2. a `RemoteErrorDetailsMap` merge entry in runsRegistry.ts
9
+ // (the compiler enforces table <-> details sync at
10
+ // toRemoteError — details must satisfy the map's row);
11
+ // 3. the CLIENT's refusedCode discrimination (melite-card-view:
12
+ // cards-tab-body's heal-vs-carry split reads the wire value;
13
+ // an untabled class silently takes the default fail-carry —
14
+ // the replay-poison shape this table exists to prevent);
15
+ // 4. the validate-arm guards in runsValidateArms.ts (the two LOUD
16
+ // throw sites that refuse untabled codes at the door);
17
+ // 5. phaseRefusalCode (cardsArmError.ts) — its param is narrowed
18
+ // to this table's keys, so a new throw-site code fails
19
+ // TYPECHECK here first, never at the client.
20
+ // The two spellings are law: the ENVELOPE key (card_compose) rides
21
+ // the throw; the WIRE value (runs/card-compose) is what the client
22
+ // compares. Both live in this table's one row.
23
+ //
24
+
25
+ // wire codes never ride the envelope and are NOT tabled here, by
26
+ // design — `runs/unknown-run` and `runs/run-unknown` are thrown
27
+ // direct with the wire spelling at their own sites (status/stop
28
+ // misses; their details rows live in the RemoteErrorDetailsMap at
29
+ // runsRegistry.ts, not in this envelope table), and `bad_json` is
30
+ // the strict-wire gate's 400 payload (runsGates.ts; its door path
31
+ // has zero production consumers — its deletion call sits with the
32
+ // dead-exports census row, not here). A new code must still take
33
+ // the five seats above; the exemption is closed.
3
34
  export const RUNS_ERROR_CODES = {
4
35
  bad_envelope: "runs/bad-envelope",
5
36
  draft_required: "runs/draft-required",
@@ -10,6 +41,8 @@ export const RUNS_ERROR_CODES = {
10
41
  flow_compile: "runs/flow-compile",
11
42
  workflow_pin: "runs/workflow-pin",
12
43
  card_compose: "runs/card-compose",
44
+ card_compose_incomplete: "runs/card-compose-incomplete",
13
45
  lane_input_missing: "runs/lane-input-missing",
46
+ lifecycle_inflight: "runs/lifecycle-inflight",
14
47
  };
15
48
  //# sourceMappingURL=runsErrorCodes.js.map
@@ -15,6 +15,32 @@ import { type RunRecord } from "./runsTypes.js";
15
15
 
16
16
 
17
17
 
18
+
19
+
20
+ export declare const LIVENESS_NOTIFY_MS = 300;
21
+ export declare const LIVENESS_WATCHDOG_MS = 5000;
22
+ export interface RunLiveness {
23
+ /** The report fold's tail: silence resets + a throttled notify. */
24
+ report(): void;
25
+ /** Clears the watchdog tick — the finally of every execute path. */
26
+ stop(): void;
27
+ }
28
+ export declare function startRunLiveness(run: RunRecord): RunLiveness;
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
18
44
  export declare function declaredPrimaryFirst(names: string[], stem: string | undefined): string[];
19
45
  export type SettleFn = (run: RunRecord) => void | Promise<void>;
20
46
  /** One run through the merged path (door-verbatim: stages ->
@@ -1,5 +1,6 @@
1
1
  import { CARD_PLANE_ENGINE } from "@melite/contracts/benchStage";
2
2
  import { loadCardDefs, needComfyUI, spliceWorkflow } from "@melite/comfyui-cordis";
3
+ import { deadline } from "@deepseek-ai/dsh-timeout";
3
4
  import { errText, runRel } from "./runsTypes.js";
4
5
  import { notifyRunChanged } from "./runsChange.js";
5
6
  import { engineFilmName } from "./filmLead.js";
@@ -14,6 +15,98 @@ import { engineFilmName } from "./filmLead.js";
14
15
 
15
16
 
16
17
 
18
+ async function raceExecuteFuse(p, ceilMs, what) {
19
+ const ceil = ceilMs ?? 0; // undefined (a minimal fake seat) = disabled, like <= 0
20
+ const dl = deadline(undefined, ceil, "RUN_EXECUTE_HUNG");
21
+ try {
22
+ return await Promise.race([
23
+ p,
24
+ new Promise((_, reject) => {
25
+ dl.signal.addEventListener("abort", () => {
26
+ const shown = ceil < 60_000
27
+ ? Math.round(ceil) + "ms"
28
+ : Math.round(ceil / 60_000) + " min";
29
+ reject(new Error("runs/execute-hung: " + what + " exceeded the execute ceiling (" +
30
+ shown +
31
+ ") — a hung engine call must never strand the serial queue; raise the queue config's executeCeilMs or set it <= 0 to disable"));
32
+ }, { once: true });
33
+ }),
34
+ ]);
35
+ }
36
+ finally {
37
+ dl[Symbol.dispose]();
38
+ void p.catch(() => { }); // the losing promise's rejection is already handled
39
+ }
40
+ }
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+ export const LIVENESS_NOTIFY_MS = 300;
59
+ export const LIVENESS_WATCHDOG_MS = 5_000;
60
+ export function startRunLiveness(run) {
61
+ let lastNotify = 0;
62
+ let lastReportAt = Date.now();
63
+ const stampWaiting = () => {
64
+ const waitedS = Math.round((Date.now() - lastReportAt) / 1000);
65
+ for (const stage of run.stages) {
66
+ if (stage["status"] === "running") {
67
+ stage["activity"] =
68
+ "waiting on engine (" + waitedS + "s — no engine events)";
69
+ }
70
+ }
71
+ };
72
+ const tick = () => {
73
+ // settled runs own no stamp (the terminal writer deleted the
74
+ // activity lines); only a still-running row may move.
75
+ if (run.status !== "running")
76
+ return;
77
+ if (Date.now() - lastReportAt < LIVENESS_WATCHDOG_MS)
78
+ return;
79
+ stampWaiting();
80
+ lastNotify = Date.now();
81
+ notifyRunChanged(run.runId);
82
+ };
83
+ const handle = setInterval(tick, LIVENESS_WATCHDOG_MS);
84
+ handle.unref?.();
85
+ return {
86
+ report() {
87
+ lastReportAt = Date.now();
88
+ const now = Date.now();
89
+ if (now - lastNotify < LIVENESS_NOTIFY_MS)
90
+ return;
91
+ lastNotify = now;
92
+ notifyRunChanged(run.runId);
93
+ },
94
+ stop() {
95
+ clearInterval(handle);
96
+ },
97
+ };
98
+ }
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
17
110
 
18
111
 
19
112
 
@@ -59,6 +152,24 @@ export async function runOne(run, ctx, settle) {
59
152
  // tryDequeue returned null — all inference bricked until
60
153
  // restart (audit R1, stroke 82).
61
154
  try {
155
+
156
+ // EVERY stage row to the ONE executor resolved from the first
157
+ // stage's engine (runEngine's rule below) — a flow whose
158
+ // stages name two engines would mis-submit rows to the wrong
159
+ // engine. Refuse loud at claim, inside this same settle-failed
160
+ // scope, never mid-flight.
161
+ const seen = [];
162
+ for (const stage of run.stages) {
163
+ const e = stage["engine"];
164
+ const name = typeof e === "string" && e !== "" ? e : CARD_PLANE_ENGINE;
165
+ if (!seen.includes(name))
166
+ seen.push(name);
167
+ }
168
+ if (seen.length > 1) {
169
+ throw new Error("runs/mixed-engines: the flow's stages name " +
170
+ seen.join(" + ") +
171
+ " — the seat submits every row to one executor (the first stage's engine); a mixed-engine flow is refused, never mis-dispatched");
172
+ }
62
173
  seatExecutor = enginesSeat.resolve(runEngine(run)).executor;
63
174
  }
64
175
  catch (exc) {
@@ -208,6 +319,10 @@ export async function runOne(run, ctx, settle) {
208
319
  }
209
320
  }
210
321
  }
322
+ // THE LIVE ROW's owner: created before the submit path, stopped
323
+ // in the finally — every execute path (success, throw, fuse)
324
+ // retires the watchdog exactly once.
325
+ const live = startRunLiveness(run);
211
326
  try {
212
327
 
213
328
  // the comfyui progress webhooks like before"): the engine
@@ -230,6 +345,9 @@ export async function runOne(run, ctx, settle) {
230
345
  stage["progress"] = { value: pRec["value"], max: pRec["max"] };
231
346
  }
232
347
  }
348
+ // THE LIVE ROW (the module law above): the stamps are memory
349
+ // until this notify — the push-only tail never re-reads.
350
+ live.report();
233
351
  };
234
352
  const shouldStop = () => run.stopFlag;
235
353
  let result;
@@ -251,18 +369,21 @@ export async function runOne(run, ctx, settle) {
251
369
  outputs: { ...stage.outputs },
252
370
  params: { ...run.params[i] },
253
371
  }));
254
- const outcome = await seatExecutor.executeStages(genericRows, run.dir, inputNames, { shouldStop, report },
372
+ const outcome = await raceExecuteFuse(seatExecutor.executeStages(genericRows, run.dir, inputNames, { shouldStop, report, stateRoots: ctx.queue.stateRoots },
255
373
  // The run's request initials ride every engine submit: the
256
374
  // gate-blessed values the start door extracted for this
257
375
  // flow's declared initials, so `$spell` params resolve at
258
376
  // the engine's merge. Engines whose param dialect has no
259
377
  // `$spells` ignore the record.
260
- run.initials);
378
+ run.initials), ctx.queue.executeCeilMs, "the seat executor");
261
379
  result = {
262
380
  stages: Object.fromEntries(outcome.stages.map((s) => [
263
381
  s.stageId,
264
382
  { outputs: s.outputs, artifacts: [...s.artifacts] },
265
383
  ])),
384
+ // THE REPLAY VERDICT (D11): forwarded, never re-derived —
385
+ // the executor's seated tap is the only witness.
386
+ replaySuspect: outcome.replaySuspect,
266
387
  };
267
388
  }
268
389
  else {
@@ -273,11 +394,13 @@ export async function runOne(run, ctx, settle) {
273
394
  "merged submit (" + rows.length + " stages, " + nodeCount + " nodes)";
274
395
  }
275
396
  // Same law as the seat path above: the run's request initials
276
- // resolve the `$spells` at this merge.
277
- result = await engine.executeFlow(rows, run.dir, inputNames, run.initials, {
397
+ // resolve the `$spells` at this merge. The hung-run fuse wraps
398
+ // BOTH executors (one law, no escape hatch).
399
+ result = await raceExecuteFuse(engine.executeFlow(rows, run.dir, inputNames, run.initials, {
278
400
  shouldStop,
279
401
  report,
280
- });
402
+ stateRoots: ctx.queue.stateRoots,
403
+ }), ctx.queue.executeCeilMs, "the engine submit");
281
404
  }
282
405
  for (const stage of run.stages) {
283
406
  const row = result.stages[stage.id] ?? { outputs: {}, artifacts: [] };
@@ -325,6 +448,18 @@ export async function runOne(run, ctx, settle) {
325
448
  delete stage["activity"];
326
449
  }
327
450
  run.status = run.stopFlag ? "stopped" : "completed";
451
+
452
+ // folded zero engine events before settlement — the engine
453
+ // served memo'd outputs without executing (byte-identical
454
+ // graphs replay the previous film in ~0.01s, no ws events, the
455
+ // tile frozen at "merged submit"). The run still completes —
456
+ // the harvest is what the engine said — but the row tells the
457
+ // truth: this film may predate the request. A dead tap
458
+ // withholds the verdict (its own warn, never a replay claim).
459
+ if (result.replaySuspect === true) {
460
+ run.replaySuspect = true;
461
+ console.warn(`[runs] ${run.runId} completed with no engine progress events — the film may be a replay of an earlier identical submit (the request's inputs never executed)`);
462
+ }
328
463
  await settle(run);
329
464
  }
330
465
  catch (exc) {
@@ -346,6 +481,9 @@ export async function runOne(run, ctx, settle) {
346
481
  run.error = text;
347
482
  await settle(run);
348
483
  }
484
+ finally {
485
+ live.stop();
486
+ }
349
487
  }
350
488
  export function runEngine(run) {
351
489
  const first = run.stages[0];
package/lib/runsGates.js CHANGED
@@ -82,9 +82,10 @@ export const FLOW_ID_RE = /^[a-z_][a-z0-9_-]*$/;
82
82
  // OWNS the rule (DRAFT_ID_RE, 1..96) and this module re-exports that
83
83
  // exact object — the drafts spec's own JSDoc says the queue
84
84
  // re-exports it, which was false while the queue kept its own
85
- // byte-identical copy. draft-id-grammar.spec.ts still pins the two
86
- // as equal, and now that equality is the identity of one object
87
- // rather than the luck of two copies.
85
+ // byte-identical copy. (The draft-id-grammar wall's old equality
86
+ // arm is deleted — with the mirror gone it compared one object
87
+ // with itself; the one-declaration law lives in closure-gate
88
+ // RULE 4d, and the sampling arms exercise the ONE grammar.)
88
89
  export { DRAFT_ID_RE };
89
90
  /** Decode one strict body: "" decodes as {} (body.decode() or
90
91
  * "{}"). The TEXT embeds the host parser's message — walls assert