@melite/estate-queue 0.0.0-stage → 0.1.4-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 (129) hide show
  1. package/LICENSE +557 -0
  2. package/lib/bakeParams.d.ts +17 -0
  3. package/lib/bakeParams.js +182 -0
  4. package/lib/bench.d.ts +24 -0
  5. package/lib/bench.js +121 -0
  6. package/lib/cardsArmError.d.ts +18 -0
  7. package/lib/cardsArmError.js +33 -0
  8. package/lib/cardsCompose.d.ts +41 -0
  9. package/lib/cardsCompose.js +247 -0
  10. package/lib/cardsDangling.d.ts +16 -0
  11. package/lib/cardsDangling.js +168 -0
  12. package/lib/cardsFacts.d.ts +74 -0
  13. package/lib/cardsFacts.js +64 -0
  14. package/lib/cardsLanes.d.ts +33 -0
  15. package/lib/cardsLanes.js +115 -0
  16. package/lib/cardsRegistry.d.ts +316 -0
  17. package/lib/cardsRegistry.js +1274 -0
  18. package/lib/cardsVariant.d.ts +28 -0
  19. package/lib/cardsVariant.js +190 -0
  20. package/lib/discloseRegistry.d.ts +94 -0
  21. package/lib/discloseRegistry.js +154 -0
  22. package/lib/filmLead.d.ts +4 -0
  23. package/lib/filmLead.js +17 -0
  24. package/lib/filmMemoryWarn.d.ts +27 -0
  25. package/lib/filmMemoryWarn.js +99 -0
  26. package/lib/flowsData.d.ts +179 -0
  27. package/lib/flowsData.js +547 -0
  28. package/lib/flowsFamilyCompose.d.ts +48 -0
  29. package/lib/flowsFamilyCompose.js +191 -0
  30. package/lib/flowsRegistryRows.d.ts +10 -0
  31. package/lib/flowsRegistryRows.js +378 -0
  32. package/lib/index.d.ts +50 -0
  33. package/lib/index.js +66 -0
  34. package/lib/ledgerTail.d.ts +20 -0
  35. package/lib/ledgerTail.js +123 -0
  36. package/lib/loadPlane.d.ts +93 -0
  37. package/lib/loadPlane.js +553 -0
  38. package/lib/loadRegistry.d.ts +22 -0
  39. package/lib/loadRegistry.js +55 -0
  40. package/lib/manageOps.d.ts +21 -0
  41. package/lib/manageOps.js +142 -0
  42. package/lib/managePlane.d.ts +120 -0
  43. package/lib/managePlane.js +1515 -0
  44. package/lib/manageProbe.d.ts +57 -0
  45. package/lib/manageProbe.js +154 -0
  46. package/lib/manageRegistry.d.ts +28 -0
  47. package/lib/manageRegistry.js +75 -0
  48. package/lib/managerRail.d.ts +33 -0
  49. package/lib/managerRail.js +91 -0
  50. package/lib/mediaKinds.d.ts +3 -0
  51. package/lib/mediaKinds.js +2 -0
  52. package/lib/queue.d.ts +9 -0
  53. package/lib/queue.js +76 -0
  54. package/lib/queueCore.d.ts +69 -0
  55. package/lib/queueCore.js +124 -0
  56. package/lib/queueLifecycle.d.ts +26 -0
  57. package/lib/queueLifecycle.js +65 -0
  58. package/lib/queueLock.d.ts +54 -0
  59. package/lib/queueLock.js +195 -0
  60. package/lib/queueResurrect.d.ts +59 -0
  61. package/lib/queueResurrect.js +249 -0
  62. package/lib/queueRetry.d.ts +36 -0
  63. package/lib/queueRetry.js +24 -0
  64. package/lib/queueSidecar.d.ts +145 -0
  65. package/lib/queueSidecar.js +182 -0
  66. package/lib/queueSubmit.d.ts +31 -0
  67. package/lib/queueSubmit.js +117 -0
  68. package/lib/queueSweep.d.ts +30 -0
  69. package/lib/queueSweep.js +121 -0
  70. package/lib/resurrect.d.ts +6 -0
  71. package/lib/resurrect.js +18 -0
  72. package/lib/rootsManifest.d.ts +11 -0
  73. package/lib/rootsManifest.js +11 -0
  74. package/lib/runStatus.d.ts +7 -0
  75. package/lib/runStatus.js +21 -0
  76. package/lib/runsChange.d.ts +53 -0
  77. package/lib/runsChange.js +63 -0
  78. package/lib/runsErrorCodes.d.ts +2 -0
  79. package/lib/runsErrorCodes.js +15 -0
  80. package/lib/runsExecute.d.ts +26 -0
  81. package/lib/runsExecute.js +356 -0
  82. package/lib/runsGates.d.ts +161 -0
  83. package/lib/runsGates.js +306 -0
  84. package/lib/runsList.d.ts +78 -0
  85. package/lib/runsList.js +580 -0
  86. package/lib/runsRefusalVoices.d.ts +9 -0
  87. package/lib/runsRefusalVoices.js +44 -0
  88. package/lib/runsRegistry.d.ts +253 -0
  89. package/lib/runsRegistry.js +1750 -0
  90. package/lib/runsSourceEcho.d.ts +54 -0
  91. package/lib/runsSourceEcho.js +275 -0
  92. package/lib/runsStart.d.ts +121 -0
  93. package/lib/runsStart.js +528 -0
  94. package/lib/runsTypes.d.ts +183 -0
  95. package/lib/runsTypes.js +282 -0
  96. package/lib/runsValidate.d.ts +5 -0
  97. package/lib/runsValidate.js +31 -0
  98. package/lib/runsValidateArms.d.ts +7 -0
  99. package/lib/runsValidateArms.js +285 -0
  100. package/lib/runsValidateInline.d.ts +6 -0
  101. package/lib/runsValidateInline.js +82 -0
  102. package/lib/runsValidateRefusals.d.ts +7 -0
  103. package/lib/runsValidateRefusals.js +18 -0
  104. package/lib/runsValidateServe.d.ts +15 -0
  105. package/lib/runsValidateServe.js +254 -0
  106. package/lib/runsValidateShared.d.ts +84 -0
  107. package/lib/runsValidateShared.js +88 -0
  108. package/lib/runsValidateStages.d.ts +25 -0
  109. package/lib/runsValidateStages.js +491 -0
  110. package/lib/runsValidateSweeps.d.ts +6 -0
  111. package/lib/runsValidateSweeps.js +143 -0
  112. package/lib/service.d.ts +45 -0
  113. package/lib/service.js +81 -0
  114. package/lib/skillFrontmatter.d.ts +11 -0
  115. package/lib/skillFrontmatter.js +46 -0
  116. package/lib/skillFs.d.ts +19 -0
  117. package/lib/skillFs.js +80 -0
  118. package/lib/skillPlane.d.ts +98 -0
  119. package/lib/skillPlane.js +263 -0
  120. package/lib/skillRegistry.d.ts +23 -0
  121. package/lib/skillRegistry.js +55 -0
  122. package/lib/skillRows.d.ts +126 -0
  123. package/lib/skillRows.js +466 -0
  124. package/lib/toolProjection.d.ts +30 -0
  125. package/lib/toolProjection.js +142 -0
  126. package/lib/vocab.d.ts +6 -0
  127. package/lib/vocab.js +18 -0
  128. package/package.json +47 -4
  129. package/README.md +0 -3
@@ -0,0 +1,1274 @@
1
+ // cardsRegistry.ts — the card registry as a HOST Cordis service
2
+ // (REBUILD-9, gateway kill): the dead flowsCard.ts second-move
3
+ // verbatim (the registry, the resolve/prepare/overlay pipeline, the
4
+ // in-process compose — line cites riding along). The runs
5
+ // plane's {model:} arms (start phase-1/phase-2 + validate) ride
6
+ // this service; the estate row mounts it before the runs registry.
7
+ //
8
+ // PATHS: facts + object_info ride the ENGINE package's data dir
9
+ // (the Decl x Facts unification — same as the door). The service
10
+ // name stays "cardRegistry" (ctx.cardRegistry).
11
+
12
+ //
13
+ // WHAT THIS SERVES (the cordis
14
+ // plane): the card-run derivation resolve_card_model +
15
+ // submit's phase-2 arm + the rim wrap (card_hooks.compose), with
16
+ // the survey's verdict: import
17
+ // @melite/comfyui IN-PROCESS — no template SSOT, no subprocess, no
18
+ // class-tree port. The graph truth already lives in TS
19
+ // (the card packages — stable);
20
+ // this arm only changes the CALL PATH (subprocess shell -> import).
21
+ //
22
+ // THE CHAIN (order, mirrored step-for-step):
23
+ // 1. envelope/draft/strict/exclusivity — OWNED by the start
24
+ // door (handleFlowsStart, already ported); this arm starts past it.
25
+ // 2. model-id legality (validate-door voice) + existence
26
+ // (resolve_model's voice: "no model unit ...") + the
27
+ // non-cordis arm refusal.
28
+ // 3. artifact-ref sweep (find_dangling_refs semantics — every
29
+ // /v1/assets/... URL must
30
+ // exist on served mounts BEFORE compose).
31
+ // 4. route-lens stamp overlay (_route_stamp_overlay 705-751):
32
+ // family defaults + the SELECTED variant's resolver_defaults,
33
+ // absent-keys-only, filtered to the card field surface
34
+ // (schema keys + admits). Facts carry every input
35
+ // (model-facts.json variants[].resolver_defaults).
36
+ // 5. R1 variant/quant wire contract (survey §5.3 + §6 R1): body `variant`/`quant` keys select the matrix cell when stated (matched against facts variant id/route + cell quant).
37
+ // Unstated coordinates fall to the FIRST non-Recipe variant / first cell (selectCardVariant in cardsVariant.ts, re-exported through this file's surface).
38
+ // Route-id-as-model is preserved (resolveCardFamily).
39
+ // The keys are CONSUMED (never reach compose — no card declares them).
40
+ // 6. envelope lift (card_compose_body 363-372: body minus
41
+ // CARD_ENVELOPE_KEYS restaged as {params}) + the nested-stanza
42
+ // unwrap (cli.ts:82-91 — a `params` dict key IS the stanza).
43
+ // 7. $spell phase-1 rule (composeOnce in cardsCompose.ts): a phaseless call (run_id "") whose spell params carry $ values composes NO graph.
44
+ // 8. admission-contract gate (the cli door's verbatim voice).
45
+ // 9. in-process compose: ONE Context + ComfyUIService +
46
+ // auto-loaded cards (the cli loop), setFacts +
47
+ // setObjectInfo (live /object_info doc via the SDK client —
48
+ // R3: an unreachable engine refuses CLOSED, never composes
49
+ // unauthenticated), ctx.comfyui.compose(card, family, params,
50
+ // runId) — the same call the cli door makes. ComposeRefusal.code
51
+ // maps to the refusal detail.
52
+ // 10. Stage-row wrap (the rim, composeOnce in cardsCompose.ts): {id: skeleton (the card definition, fallback: the posted mid), engine comfyui, params: {workflow: graph}}.
53
+ // The row rides the EXISTING engine layer (engine/comfyui.ts executeFlow) exactly like flow_inline runs (L3 routing, upload walk, harvest, interrupt, timeout all reused untouched).
54
+ //
55
+ // REFUSAL VOICES: every card-lane failure carries
56
+ // `card_compose phase <N>: <detail>` (the phase framing; the
57
+
58
+ // the execFileSync itself), where <detail> is the CLI-line shape
59
+ // (`<code>: <msg>` for ComposeRefusal; `compose-door: ...` for the
60
+ // admission die). The
61
+ // (comfyui.comfyui) prefix rides the ENGINE_TABLE derivation
62
+ // (plugin dir name + engine type, as scan_engines reports them —
63
+ // the validate door pins the same table). Pre-compose
64
+ // request failures (illegal id, no unit, dangling ref) keep their
65
+ // existing validate-door voices (code invalid_request) so
66
+ // start+validate agree field-for-field.
67
+ //
68
+ // Erasable-syntax TS only (node --experimental-strip-types): no
69
+ // enums, import type for types, .ts specifiers for relative imports.
70
+ import { Service } from "@deepseek-ai/cordis";
71
+ // CROSS-COPY LAW (the estate's documented topology): the engine
72
+ // package resolves the REGISTRY cordis instance; this package's
73
+ // "@deepseek-ai/cordis" is the vendor instance. The service TYPE
74
+ // and the compose-rim Context CLASS come from the engine's own
75
+ // copy (the deep path — the walls' established pattern), so the
76
+ // engine's ComfyUIService mounts on the instance it was built for.
77
+ /** The engine's OWN cordis Context — re-exported by the engine
78
+ * package (the registry-keyed instance ComfyUIService mounts on),
79
+ * imported through the engine's public surface like every other
80
+ * engine dep. No deep path, no runtime-only dodge. */
81
+ import { bootModels, cardDefsNow, ComposeRefusal, getModel, liveScanOrder, loadCardDefs, loadFacts, registryIds, registryModel, resolveCardFlowOutputs, theService } from "@melite/comfyui-cordis";
82
+ import { DOOR_KEYS } from "./runsGates.js";
83
+ import { getRegistryFlow } from "./flowsData.js";
84
+ import { CardArmError, EnvelopeRefusal, phaseRefusal } from "./cardsArmError.js";
85
+ export { CardArmError } from "./cardsArmError.js";
86
+ import { factsPath, deriveDecls } from "./cardsFacts.js";
87
+ import { WIRE_STAGE_KEYS } from "@melite/contracts/benchStage";
88
+ import { judgeLaneBounds, judgeLaneRelations, judgeLaneSurface, laneBoundsOf, laneSurfaceOf, RELATION_WORDS } from "@melite/contracts/laneRelations";
89
+ import { lanePresenceRefusal } from "./cardsLanes.js";
90
+ import { selectCardVariant, liftCardParams } from "./cardsVariant.js";
91
+ // the extracted planes re-export through the registry's public
92
+ // surface (the walls import these names from here — one door)
93
+ export { selectCardVariant, stampCardOverlay, liftCardParams } from "./cardsVariant.js";
94
+ import { deriveWiringDoc, liveObjectInfo, resolveEngineBaseUrl } from "@melite/comfyui-cordis";
95
+ import { admissionRefusal, composeOnce, liftStanza, prepareCardParams } from "./cardsCompose.js";
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+ export const CARD_ENVELOPE_KEYS = [
114
+ ...DOOR_KEYS,
115
+ // …every wire coordinate EXCEPT `params` — and the exception is the
116
+ // load-bearing one. `params` is the row's knob CONTAINER: the run
117
+ // body's `{model, params:{…}}` stanza is what liftCardParams
118
+ // unwraps (the stanza law, benchStage's own), and filtering the
119
+ // container BEFORE that unwrap would drop every knob a caller sent
120
+ // — the first cut of this list did exactly that and turned every
121
+ // run into "this lane requires 'prompt'". A coordinate selects the
122
+ // graph; the knobs ride inside `params`, never as a key of it.
123
+ ...WIRE_STAGE_KEYS.filter((k) => k !== "params"),
124
+ "draft_id",
125
+ "test",
126
+ "service",
127
+ // the bench row's own non-wire coordinates (benchStage's stage row
128
+ // carries these beside the wire keys; they select, they never ride)
129
+ "author",
130
+ "rev",
131
+ "stage",
132
+ "title",
133
+ "inputOutputs",
134
+ "result",
135
+ "runStatus",
136
+ "expect_rev",
137
+ "provenance",
138
+ "capability",
139
+ ];
140
+ /** The card-lane refusal: status + the _refusal envelope shape
141
+ * (error, code, then loc/expected/got) — the door maps it through
142
+ * the local refusal path. */
143
+ /** The family's DECL face ("MOSS-SFX v2") — registryModel in a
144
+ * guard (it THROWS on unknown ids); the id is the fallback.
145
+ * Exported for the wall (both arms pin: the face serves, the
146
+ * unknown degrades to the id — never a throw into a serve). */
147
+ export function familyFace(fam) {
148
+ try {
149
+ return registryModel(fam).label;
150
+ }
151
+ catch {
152
+ return fam;
153
+ }
154
+ }
155
+
156
+
157
+
158
+ // ── the CardRegistry as a Cordis Service (stroke 2a,
159
+ // DSH-AS-LANGUAGE LAW) ────────────────────────────────────────────
160
+ // SERVICE NAME: 'cardRegistry' (ctx.cardRegistry) — the short
161
+ // camelCase service key per the sibling-stroke precedent and the
162
+ // sibling stroke 2b ('runs'). Defined where the registry lives
163
+ // (this file, the cards side) for the same cycle reason 2b records:
164
+ // doors import this module; defining the service anywhere doorside
165
+ // would force this file to import it back.
166
+ //
167
+ // OWNS: the primed defs map, the facts/decls projections, the
168
+ // mtime-keyed object_info pin snapshot, the catalog mids set, and
169
+ // every registry-derived operation (resolve/prepare/overlay/
170
+ // phase-1/phase-2). The pure helpers below (select/stamp/lift/
171
+ // sweep) stay module functions — they take explicit args
172
+ // and hold no state. Every door with registry reads injects
173
+ // 'cardRegistry' and uses ctx.cardRegistry; request-path helpers
174
+ // take an explicit service param (no module handle, no ACTIVE
175
+ // fallback — nothing reaches the cards plane without a Context
176
+ // except the boot sites, which route through
177
+ // ctx.get('cardRegistry') — see main.ts).
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+
198
+
199
+
200
+
201
+
202
+
203
+
204
+
205
+
206
+
207
+
208
+ function incompleteDraftViolations(violations) {
209
+ return violations.filter((v) => !v.message.startsWith("this lane requires"));
210
+ }
211
+ export class CardRegistryService extends Service {
212
+ /** The primed card definitions (null until prime()). */
213
+ defs = null;
214
+ /** The frozen model facts (lazy — strict load, throws LOUD). */
215
+ facts = null;
216
+ /** Route address → family owner from the registry-derived facts. */
217
+ owners = {};
218
+ /** Registry reads for the row derivation (primed with the models boot). */
219
+ reads = null;
220
+ /** The decl projection (lazy — derived from defs + facts). */
221
+ decls = null;
222
+ /** The engine's live node-definitions doc (/object_info via the
223
+ * SDK client, cached per process on the engine side; primed by
224
+ * primeObjectInfo before any compose). null = not yet primed or
225
+ * the engine is unreachable. */
226
+ oi = null;
227
+ /** The catalog existence set (lazy — strict load, throws LOUD). */
228
+ mids = null;
229
+ constructor(ctx) {
230
+ super(ctx, "cardRegistry");
231
+ }
232
+ /** Prime the registry (service init — replaces the retired
233
+ * primeCardRegistry()): the registry loads async (dynamic
234
+ * card-module imports) but the validate/disclosure rims are sync,
235
+ * so every boot primes and the request path projects
236
+ * synchronously. Safe to call multiple times (unconditional
237
+ * reload — mirrors the old both-boot-sites prime); re-prime
238
+ * drops the defs-derived decls (facts/mids are disk-derived and
239
+ * stay). The provider's apply primes, and both main.ts boot
240
+ * sites re-prime belt-and-braces. */
241
+ async prime() {
242
+ this.defs = await loadCardDefs();
243
+ this.decls = null;
244
+ // the models boot feeds the row derivation (facts.ts renders
245
+ // rows through these reads — one spelling, no frozen matrix).
246
+ await bootModels();
247
+ this.reads = { getModel, registryIds, registryModel };
248
+ this.facts = null;
249
+ this.owners = {};
250
+ // ARM THE SINGLETON for the presence reads (stroke 18): the
251
+ // compose path builds a FRESH service per run (armed with the
252
+ // live doc below), but the serving surfaces (the spec's packs
253
+ // block, the load bundle's pack hints) read theService() —
254
+ // without this arm every pack marks unknown (null) on a healthy
255
+ // lane. Same live doc + same facts file the compose gate reads:
256
+ // one truth, two seats, one spelling of the check.
257
+ await this.primeObjectInfo();
258
+ try {
259
+ const svc = theService();
260
+ svc.setObjectInfo(this.objectInfo());
261
+ svc.setFacts(loadFacts(factsPath(), this.readsSync()));
262
+ }
263
+ catch {
264
+ // the singleton is not resolvable in this context — the
265
+ // serving surfaces degrade to unknown marks (never a throw on
266
+ // the prime path; compose still arms its own fresh service)
267
+ }
268
+ }
269
+ /** Test seam: drop all registry state (walls boot fresh processes;
270
+ * belt-and-braces for in-process reuse — the RunsService behavior). */
271
+ resetForTests() {
272
+ this.defs = null;
273
+ this.facts = null;
274
+ this.owners = {};
275
+ this.reads = null;
276
+ this.decls = null;
277
+ this.oi = null;
278
+ this.mids = null;
279
+ }
280
+ /** Sync read of the primed registry (the disclosure projection
281
+ * serves from the registry, and the disclosure doors are sync —
282
+ * unprimed access throws LOUD, never a fallback). */
283
+ defsSync() {
284
+ if (this.defs === null) {
285
+ throw new Error("[card_registry] unprimed: boot must await the estate-card-registry " +
286
+ "provider (or ctx.cardRegistry.prime()) before the " +
287
+ "disclosure rim serves (the estate composition's " +
288
+ "estate-card-registry row primes; boot rigs settle-poll " +
289
+ "for the seats)");
290
+ }
291
+
292
+ // loadCardDefs()'s module cache and refreshCardDefs() swaps it;
293
+
294
+ // live-mounted hot card served in forms and REFUSED at
295
+ // POST /v1/flows/validate ("is not a registered card") — the
296
+ // boot snapshot forked the truth. The prime stays (boot must
297
+ // still build the cache + models + object info, and this.defs
298
+ // is the primed proof); the READ rides the one cache. Cold and
299
+ // steady-state boots are byte-identical: cardDefsNow() is the
300
+ // same object prime() captured until a refresh swaps it.
301
+
302
+
303
+
304
+
305
+ return cardDefsNow() ?? this.defs;
306
+ }
307
+ /** The frozen model facts (strict — a missing file throws LOUD;
308
+ * the validate door keeps its absent-file degrade by catching
309
+ * this at its own call site). */
310
+ /** Sync read of the primed registry reads (unprimed access throws LOUD). */
311
+ readsSync() {
312
+ if (this.reads === null) {
313
+ throw new Error("[card_registry] unprimed: boot must await the estate-card-registry " +
314
+ "provider (or ctx.cardRegistry.prime()) before rows derive " +
315
+ "(the models boot feeds facts.ts through these reads)");
316
+ }
317
+ return this.reads;
318
+ }
319
+ modelFacts() {
320
+ if (this.facts !== null)
321
+ return this.facts;
322
+ // rows assemble from the registry + frozen card slices (the
323
+ // derivation is the single matrix — no frozen spelling).
324
+ const doc = loadFacts(factsPath(), this.readsSync());
325
+ this.facts = doc.models;
326
+ this.owners = { ...doc.owners };
327
+ return this.facts;
328
+ }
329
+ /** The decl projection — derived from defs + the strict facts, or
330
+ * from defs + caller-supplied facts (the validate door's
331
+ * degraded read; derived fresh, never cached over foreign facts). */
332
+ cardDecls(facts) {
333
+ if (facts !== undefined)
334
+ return deriveDecls(this.defsSync(), facts);
335
+ if (this.decls !== null)
336
+ return this.decls;
337
+ const derived = deriveDecls(this.defsSync(), this.modelFacts());
338
+ this.decls = derived;
339
+ return this.decls;
340
+ }
341
+ /** The primed live doc (sync face for the sweeps/spec fakes).
342
+ * null = never primed, or the engine was unreachable at prime. */
343
+ objectInfo() {
344
+ return this.oi;
345
+ }
346
+ /** Prime the live node-definitions doc off the engine (/object_info
347
+ * via the SDK, cached per process). Never throws: false = the
348
+ * engine is unreachable and the doc stays null (the compose gate
349
+ * refuses CLOSED on that; the serving surfaces degrade). */
350
+ async primeObjectInfo() {
351
+ try {
352
+ this.oi = await liveObjectInfo(resolveEngineBaseUrl());
353
+ this.armWiringFromDoc(this.oi);
354
+ return true;
355
+ }
356
+ catch {
357
+ this.oi = null;
358
+ this.armWiringFromDoc(null);
359
+ return false;
360
+ }
361
+ }
362
+
363
+
364
+
365
+
366
+
367
+
368
+
369
+
370
+ armWiringFromDoc(doc) {
371
+ const wiring = this.ctx.get("comfyuiWiring");
372
+ if (wiring === undefined)
373
+ return;
374
+ if (doc === null) {
375
+ wiring.disarm();
376
+ return;
377
+ }
378
+ const { nodes, inputs } = deriveWiringDoc(doc);
379
+ wiring.arm(nodes, inputs);
380
+ }
381
+
382
+
383
+
384
+
385
+
386
+
387
+
388
+
389
+ modelMids() {
390
+ if (this.mids !== null)
391
+ return this.mids;
392
+ let ids;
393
+ try {
394
+ ids = liveScanOrder();
395
+ }
396
+ catch {
397
+
398
+
399
+ ids = [];
400
+ /* v8 ignore stop */
401
+ }
402
+ this.mids = new Set(ids);
403
+ return this.mids;
404
+ }
405
+ /** The owning family for mid: mid itself, or the facts model whose
406
+ * variant/cell route owns mid (mirrors _route_family;
407
+ * route-id-as-model is preserved — the graph is addressed by the
408
+ * family). Reads the strict facts unless the caller passes its
409
+ * own (the validate door's degraded read). */
410
+ resolveCardFamily(mid, facts) {
411
+ const table = facts ?? this.modelFacts();
412
+ if (facts === undefined || facts === this.facts) {
413
+ const owner = this.owners[mid];
414
+ if (owner !== undefined && owner !== mid && owner in table)
415
+ return owner;
416
+ }
417
+ if (mid in table) {
418
+
419
+ // operator's "(registered: …)" receipt's twin): the facts
420
+ // projection registers per-ROUTE rows (the flattener's one-
421
+ // owner-per-route picker rows, receipt: the address row
422
+ // 'qwen3-tts-voicedesign-design' exists as its own facts key
423
+ // with defaults {model: 'qwen3-tts-voicedesign', variant:
424
+
425
+ // if it were a family, and every family-resolution consumer
426
+ // downstream answered the models registry's unknown-model
427
+ // voice. The row's OWN defaults name the owning atom: fold
428
+ // to it. The address row itself keeps serving the picker
429
+ // (this is the resolution lens, never the serve table); a
430
+ // real family row's defaults point at itself and returns
431
+ // unchanged.
432
+ const owner = table[mid].defaults?.["model"];
433
+ if (typeof owner === "string" && owner !== mid && owner in table)
434
+ return owner;
435
+ return mid;
436
+ }
437
+ // (every real route is also a catalog mid — the mid/family/mids
438
+
439
+ // mids — the lens arms never fire through this path.)
440
+ for (const [fam, row] of Object.entries(table)) {
441
+ for (const v of row.variants ?? []) {
442
+ /* v8 ignore next */
443
+ if (v.route === mid)
444
+ return fam;
445
+ for (const c of v.cells ?? []) {
446
+ /* v8 ignore next */
447
+ if (c.route === mid)
448
+ return fam;
449
+ }
450
+ }
451
+ }
452
+ return mid;
453
+ }
454
+ /** THE RESOLVED SERVE (hour-26 stroke 15, the 1:1 run law): the
455
+ * map the NEXT RUN composes from a stage row — prepareCardParams'
456
+ * stamped + lifted body (variant resolver_defaults + family
457
+ * defaults injected for absent keys, surface-filtered, envelope
458
+ * keys + variant/quant consumed), the exact input the {model:}
459
+ * door hands compose. The drafts serve carries it on the stage
460
+ * row; the form renders it UNDER the user layer — ONE resolver,
461
+ * served to the visual, never a second client-side truth. Null
462
+ * when the row names no resolvable unit (registry-less lanes and
463
+ * model-less rows fall back to the client derive). */
464
+ /** The card's boarded families WITH PRESENCE (the no-silent-drop
465
+ * law, hour 26 stroke 17: a boarded family the machine has not
466
+ * downloaded is SERVED, marked absent — never silently dropped
467
+ * from any surface). Present = the live catalog offer
468
+ * (buildCatalog's served keys, route-id-as-model). */
469
+ cardFamilies(card) {
470
+ const def = this.defsSync().get(card);
471
+ const mids = this.modelMids();
472
+ // Label = the family DECL's own face (registryModel —
473
+ // "MOSS-SFX v2", never the composed variant+quant row):
474
+ // SUPERSEDES the stroke-19 ids-only law (the operator,
475
+
476
+ // is ambiguous between v1 and v2; the family label is the
477
+ // model's face, the variant axes stay the axes).
478
+ return (def?.boarded ?? []).map((fam) => ({
479
+ id: fam,
480
+ present: mids.has(fam),
481
+ // registryModel THROWS on an unknown id (never returns
482
+ // undefined) — the guard catches, the id is the label-less
483
+ // fallback. The catch arm fires only on a boarded-but-
484
+ // unregistered family (no live caller boards one — the walls
485
+ // refuse it); it stays armed for the honest degrade.
486
+ label: familyFace(fam),
487
+ }));
488
+ }
489
+ /** ADMISSION (the door half of the no-silent-drop law, re-cut
490
+ * hour 26 stroke 18 per the operator: a BOARDED model is
491
+ * OFFERED — the write lands even when the weights are not yet
492
+ * downloaded; absence is a DOWNLOAD PROMPT on the surfaces, never
493
+ * a block). The model's OWNING family (resolveCardFamily —
494
+ * variant routes resolve to their family) must be BOARDED on the
495
+ * card; anything else refuses AT WRITE TIME with the card's
496
+ * board — the writer (agent or human patch) gets the error the
497
+ * moment it lands, never at run time. Model-less rows pass (they
498
+ * compose on the card's default family). */
499
+ admitStageModel(card, model) {
500
+
501
+ // agent loaded flow 'image-upscale' as a card stage and wiped
502
+
503
+ // flow id (or a typo) sailed onto the bench unquestioned. An
504
+ // unknown card refuses AT WRITE TIME with the flow hint when
505
+ // the id names a flow.
506
+ const def = this.defsSync().get(card);
507
+ if (def === undefined) {
508
+
509
+ // even load"): the ONE engine-served card with NO card
510
+ // definition (the picker's row and its form ride the engine
511
+ // arm, never the registry's defs). It is admitted against the
512
+ // LIVE engines-seat census: the card exists iff at least one
513
+ // mcp:<server> engine is seated — the standalone-subagent
514
+ // spawn needs a server to provide (the card's face is the
515
+ // AGENT card doc; the servers are its MCPs tiles' census, the
516
+ // same fold the catalog/forms doors serve). A dead server
517
+ // pick refuses AT WRITE TIME with the seated list, same
518
+ // voice as a card board.
519
+ if (card === "mcp") {
520
+ const seated = this.seatedMcpEngines();
521
+ if (seated.length === 0) {
522
+ return {
523
+ ok: false,
524
+ error: "card 'mcp' has no seated MCP server on this lane (no mcp:<server> engine registered) — the card composes nothing",
525
+ offered: [],
526
+ };
527
+ }
528
+ if (typeof model === "string" && model !== "" && !seated.includes(model)) {
529
+ return {
530
+ ok: false,
531
+ error: "model '" + model + "' is not a seated MCP server (seated: " + seated.join(", ") + ")",
532
+ offered: seated,
533
+ };
534
+ }
535
+ return { ok: true };
536
+ }
537
+ const flow = getRegistryFlow(card);
538
+ if (flow !== undefined) {
539
+ // The stage list names BOTH planes' riders: card stages by
540
+ // card id, family stages by family.action (the five census
541
+ // flows carry no card at all — compose-at-expansion, stroke 4).
542
+ const cardRiders = [];
543
+ const familyRiders = [];
544
+ for (const s of flow.stages) {
545
+ const stage = s;
546
+ if (typeof stage.card === "string" && stage.card !== "") {
547
+ cardRiders.push(stage.card);
548
+ }
549
+ else if (typeof stage.family === "string" && stage.family !== "") {
550
+ familyRiders.push(stage.family + "." +
551
+ (typeof stage.action === "string" ? stage.action : "?"));
552
+ }
553
+ }
554
+ return {
555
+ ok: false,
556
+ // The honest split: card riders compose onto the bench
557
+ // with add_stage; family riders (family.action) compose
558
+ // at expansion when the FLOW runs — the bench has no
559
+ // family-stage seat, so promising add_stage for them
560
+ // sent makers hunting a door that does not exist (the
561
+
562
+ error: "'" + card + "' is a flow, not a card — run it through the run doors " +
563
+ "(melite_flow) where its stages compose at expansion: card riders (" +
564
+ ([...new Set(cardRiders)].join(", ") || "none") +
565
+ ") may also be benched with add_stage; family riders (" +
566
+ ([...new Set(familyRiders)].join(", ") || "none") +
567
+ ") ride the flow itself (melite_load names the wiring)",
568
+ offered: [],
569
+ };
570
+ }
571
+ return {
572
+ ok: false,
573
+ error: "card '" + card + "' has no registered card definition",
574
+ offered: [],
575
+ };
576
+ }
577
+ if (typeof model !== "string" || model === "")
578
+ return { ok: true };
579
+ // (CardDefinition pins boarded: readonly string[] — required, and
580
+ // every live def carries it — so no undefined fallback here.)
581
+ const boarded = def.boarded;
582
+ const mids = this.modelMids();
583
+ const downloaded = boarded.filter((fam) => mids.has(fam));
584
+
585
+ // audit's BROKEN-A: this folded ANY declared route onto its
586
+ // owning family, so `qwen3-tts-voicedesign-base` — a variant
587
+ // route the card does NOT offer — was admitted, and then
588
+ // composed the family HEAD's lane: the stored id named base while
589
+ // the run spoke. The card's board and the tool's offer are the
590
+ // SAME set (the tts card's own law); an address the board does
591
+ // not name is not offered, however valid a route it is.
592
+ if (!boarded.includes(model)) {
593
+ return {
594
+ ok: false,
595
+ error: "model '" + model + "' is not offered by card '" + card +
596
+ "' (boards: " + (boarded.join(", ") || "none") +
597
+ "; downloaded here: " + (downloaded.join(", ") || "none") + ")",
598
+ // the OFFER is the board itself (absent weights are
599
+ // offered too — downloadable; the prompt handles them)
600
+ offered: [...boarded],
601
+ };
602
+ }
603
+ // boarded = offered = admitted. Not-yet-downloaded weights are
604
+ // the user's download prompt (provision_model), never a refusal
605
+ return { ok: true };
606
+ }
607
+
608
+
609
+
610
+
611
+
612
+
613
+
614
+
615
+
616
+
617
+
618
+
619
+
620
+
621
+
622
+
623
+
624
+
625
+ admitStageRelations(card, params) {
626
+ // THE WRITE DOOR'S OWN CALL passes admitIncomplete — the ONLY
627
+ // seat that admits an unstated required word (the law above).
628
+ const verdict = this.laneVerdict(card, params, true);
629
+ return verdict === null ? { ok: true } : { ok: false, error: verdict };
630
+ }
631
+
632
+
633
+
634
+
635
+
636
+
637
+
638
+
639
+
640
+ /** The draft (model-less) row's verdict: the words EVERY boarded
641
+ * declaring family states, judged over the raw params — the
642
+ * intersection law (see the model-less branch above). Bounds
643
+ * intersect per field (the tightest span all families agree
644
+ * holds); relation rows bind when every family states the row
645
+ * verbatim. A card with no declaring family stays null (the
646
+ * familyless tolerance). */
647
+ modellessDraftVerdict(card, params, admitIncomplete) {
648
+ const def = this.defsSync().get(card);
649
+ /* v8 ignore next -- laneVerdict's own defsSync-miss guard (the
650
+ * same lookup, earlier in the same request) already returned on
651
+ * a missing card — this arm wants a table that mutates between
652
+ * two same-request reads, which the frozen cache forbids. */
653
+ if (def === undefined)
654
+ return null;
655
+ const facts = this.modelFacts();
656
+ // (boarded is required on every live def — same reasoning as
657
+ // admitStageModel's read above; no undefined fallback.)
658
+ const boarded = def.boarded;
659
+ const declaring = [
660
+ ...new Set(boarded.map((id) => this.resolveCardFamily(id, facts))),
661
+ ]
662
+ .map((fam) => facts[fam])
663
+ .filter((row) => row !== undefined && row.params !== undefined);
664
+ if (declaring.length === 0)
665
+ return null;
666
+ const lift = liftCardParams(params);
667
+ // relation rows: serialized-row intersection across families
668
+ // A row AGREES by its MEMBERS, not its prose: the cure text may
669
+ // differ between two families stating the same word (and did —
670
+ // the first cut's verbatim JSON key emptied the intersection
671
+ // and the word silently stopped judging). The key is the row
672
+ // minus `cure`, every array sorted.
673
+ const rowKey = (r) => {
674
+ if (r === null || typeof r !== "object")
675
+ return JSON.stringify(r);
676
+ const row = { ...r };
677
+ delete row["cure"];
678
+ for (const k of Object.keys(row)) {
679
+ const v = row[k];
680
+ if (Array.isArray(v))
681
+ row[k] = [...v].map((x) => JSON.stringify(x)).sort();
682
+ }
683
+ return JSON.stringify(row);
684
+ };
685
+
686
+ // four-agent contract audit): this tuple was a THIRD hand
687
+ // enumeration of the vocabulary — a seventh word would intersect
688
+ // only the words this list happened to name, silently emptying
689
+ // every word it missed. One key list, derived from the judged
690
+ // floor, so the intersection cannot fall behind the grammar.
691
+ const WORDS = Object.keys(RELATION_WORDS);
692
+ const perFamily = declaring.map((row) => {
693
+ const fam = row.relations;
694
+ const rows = [];
695
+ for (const word of WORDS) {
696
+ const list = fam?.[word] ?? [];
697
+ for (const r of list)
698
+ rows.push({ key: word + ":" + rowKey(r), word, row: r });
699
+ }
700
+ return rows;
701
+ });
702
+
703
+
704
+
705
+ const first = perFamily[0] ?? [];
706
+ const agreed = first.filter((x) => perFamily.every((rows) => rows.some((y) => y.key === x.key)));
707
+ const relations = {};
708
+ for (const entry of agreed) {
709
+ const list = relations[entry.word] ?? [];
710
+ list.push(entry.row);
711
+ relations[entry.word] = list;
712
+ }
713
+ // bounds: per-field intersection (the tightest common span)
714
+ let bounds = null;
715
+ for (const row of declaring) {
716
+ const famBounds = row.bounds ?? null;
717
+ if (famBounds === null) {
718
+ bounds = null;
719
+ break;
720
+ }
721
+ if (bounds === null) {
722
+ bounds = { ...famBounds };
723
+ continue;
724
+ }
725
+ for (const field of Object.keys(bounds)) {
726
+ const other = famBounds[field];
727
+ if (other === undefined) {
728
+ delete bounds[field];
729
+ continue;
730
+ }
731
+ const cur = bounds[field];
732
+ const min = Math.max(cur.min ?? -Infinity, other.min ?? -Infinity);
733
+ const max = Math.min(cur.max ?? Infinity, other.max ?? Infinity);
734
+ if (min > max) {
735
+ delete bounds[field];
736
+ continue;
737
+ }
738
+ bounds[field] = {
739
+ ...(Number.isFinite(min) ? { min } : {}),
740
+ ...(Number.isFinite(max) ? { max } : {}),
741
+ };
742
+ }
743
+ }
744
+ // the surface judgment stays the undeclared-key gate's voice
745
+ // (it already ran above); only the WORDS and the SPANS judge here
746
+ // — the incomplete-draft filter applies ONLY at the write seat
747
+ const judged = [
748
+ ...judgeLaneRelations([relations], lift),
749
+ ...judgeLaneBounds(bounds, lift),
750
+ ];
751
+ const violations = admitIncomplete
752
+ ? incompleteDraftViolations(judged)
753
+ : [...judged];
754
+ if (violations.length > 0) {
755
+ return "lane (draft, model-less) refuses the state: " +
756
+ violations.map((v) => v.message).join("; ");
757
+ }
758
+ return null;
759
+ }
760
+ laneVerdict(card, params, admitIncomplete = false) {
761
+ const def = this.defsSync().get(card);
762
+ if (def === undefined)
763
+ return null; // mcp/flow ids — not lane-admitted
764
+ const mid = params["model"];
765
+ if (typeof mid !== "string" || mid === "") {
766
+ // THE UNDECLARED-KEY GATE HAS ITS OWN SEAT (the behavioural
767
+ // re-check's BYPASS 3: the contract's self-naming strip removes
768
+ // `model: 'anny'` at store, so a patched row became model-less
769
+ // and the model-less tolerance below stood the whole judgment
770
+ // down — `frobnicate` landed). A key no card declares needs no
771
+ // family and no lane: it is judged here, over the raw params
772
+ // minus the envelope, before any tolerance.
773
+ try {
774
+ admissionRefusal(this, card, "", liftCardParams(params), "admission");
775
+ }
776
+ catch (e) {
777
+ // a CardArmError is this seat's own refusal; anything else —
778
+ // a facts file that will not read, a shape fault — stays loud
779
+ // and keeps its identity instead of becoming a verdict string
780
+ if (!(e instanceof CardArmError))
781
+ throw e;
782
+ return e.message;
783
+ }
784
+ // THE MODEL-LESS ROW STILL MEETS THE WORDS EVERY FAMILY AGREES
785
+ // ON (the audit's GAP 7: the form judged a model-less tts
786
+ // row's `required: text` while the bench returned null — a
787
+ // state the authoring surface refused was bench-admitted, the
788
+ // parity law's false admit). A model-less row is a draft (no
789
+ // variant selected), so the only honest law is the
790
+ // INTERSECTION: a word every boarded declaring family states
791
+ // binds the draft too (whichever family later composes, the
792
+ // word was already declared); a word only some families state
793
+ // stays the run door's voice. No union — a union would refuse
794
+ // states the composing family admits.
795
+ return this.modellessDraftVerdict(card, params, admitIncomplete); // null when no family agrees on any word
796
+ }
797
+ let prep;
798
+ try {
799
+ prep = prepareCardParams(this, params, mid, "admission");
800
+ }
801
+ catch (e) {
802
+ // THE ENVELOPE IS A DECL-OWN WORD (the audit's GAP 1: this
803
+
804
+ // the bench admitted krea-2 turbo `steps: 50` — envelope
805
+ // [4,8] — and the run refused it: a write the door accepted
806
+ // became a run the bench could not produce, the exact false
807
+ // admit the parity law forbids). It refuses HERE, at the
808
+ // write seat, in the same voice the run door speaks.
809
+ if (e instanceof EnvelopeRefusal)
810
+ return e.message;
811
+
812
+ // bench: 'bench stage "s_0": card_compose phase 1: unknown
813
+ // quant "" for model "z-image" variant "turbo" (known: int8)')
814
+ // — a stated EMPTY variant/quant/model is not a selection, it
815
+ // is an authoring surface's unchosen control written as a
816
+ // value. The run door refuses it, so admitting it here is the
817
+ // false admit the parity law forbids (the envelope GAP-1
818
+ // shape, one axis over). Refuse HERE, in the run door's own
819
+ // voice — one spelling, both seats. A stated WRONG selection
820
+ // still passes (the tolerance below: repairable, the run
821
+ // names it); an ABSENT one still passes (compose defaults
822
+ // it). The form's own half of the law: seedAxisValues omits
823
+ // an empty axis key (card-base/src/spec.ts) so the GUI never
824
+ // authors the empty string in the first place.
825
+ if (e instanceof CardArmError &&
826
+ (params["variant"] === "" || params["quant"] === "" || params["model"] === "")) {
827
+ return e.message;
828
+ }
829
+ // selection/dangling failures keep the run door's voice —
830
+ // this seat judges only the DECL's own words
831
+ return null;
832
+ }
833
+ // THE UNDECLARED-KEY GATE, family side (a key no card declares
834
+ // needs no family — but with a family named, the same gate judges
835
+ // the LIFTED view the run seat composes).
836
+ try {
837
+ admissionRefusal(this, prep.card, prep.fam, prep.params, "admission");
838
+ }
839
+ catch (e) {
840
+ /* v8 ignore next -- admissionRefusal throws only
841
+ * CardArmError, so the rethrow keeps an unknown error loud,
842
+ * never read as a verdict. */
843
+ if (!(e instanceof CardArmError))
844
+ throw e;
845
+ return e.message;
846
+ }
847
+ const facts = this.modelFacts();
848
+ const famRow = prep.fam === "" ? undefined : facts[prep.fam];
849
+ if (famRow === undefined)
850
+ return null; // familyless card unit — no lane
851
+ // A FAMILY THAT DECLARES RELATIONS BUT NO SURFACE still gets its
852
+
853
+
854
+ // surface-less family with a declared law bound NOTHING, silently.
855
+ // laneSurfaceOf(null, …) already returns null, and judgeLane-
856
+ // Surface(null, …) judges nothing — dropping the return costs
857
+ // legacy families exactly the nothing they had.
858
+ let sel;
859
+ try {
860
+ sel = selectCardVariant(mid, famRow, params, "admission");
861
+ }
862
+ catch {
863
+ /* v8 ignore next -- prepareCardParams already ran the SAME
864
+ * selection on the same mid/famRow/body (cardsCompose.ts:296)
865
+ * one statement above; every refusal it can raise was raised
866
+ * there and absorbed by the tolerance catch above, so a throw
867
+ * here is the same refusal arriving twice. */
868
+ return null; // the run door's voice, same tolerance as above
869
+ }
870
+ // THE LANE IS THE SELECTED VARIANT (probe receipt, corrected
871
+
872
+ // address ('qwen3-tts-base') does NOT by itself name the clone
873
+ // lane. The run composes from the FAMILY row plus the selected
874
+ // variant's resolver_defaults, and a route's own lane_inputs
875
+ // reach the card only when those stamps carry the route address
876
+ // (variant:'base' → model:'qwen3-tts-base'). A bare route
877
+ // address with no body variant selects the family HEAD and
878
+ // composes the synth lane, where a stated ref_audio fires
879
+ // nothing. So the judged lane is exactly the selection, never
880
+ // the address: reading the address' facts row (which does carry
881
+ // synth_lane:'clone') admitted states the run then refused — a
882
+ // false admit, the worse half of the two errors.
883
+ const laneVariantId = sel.variantId;
884
+ const variantRow = famRow.variants.find((v) => v.id === laneVariantId);
885
+ const relations = [];
886
+ if (famRow.relations !== undefined)
887
+ relations.push(famRow.relations);
888
+ if (variantRow?.relations !== undefined)
889
+ relations.push(variantRow.relations);
890
+ const surface = laneSurfaceOf(famRow.params, variantRow?.params);
891
+
892
+ // own numeric domains ride the DECL beside the words — family
893
+ // rows, per-field REPLACED by a variant row that states the
894
+ // field, per-ENDPOINT within it (the family's floor survives a
895
+ // ceiling-only variant; laneBoundsOf is the one spelling — the
896
+ // docs, this seat and the served contract all state the same
897
+ // grain). width -50 admitted at every door while the engine
898
+ // produced garbage; the floor and the ceiling are the
899
+ // declaration's, judged in the same voice as the words.
900
+ const bounds = laneBoundsOf(famRow.bounds ?? null, variantRow?.bounds ?? null);
901
+ // THE INCOMPLETE-DRAFT LAW rides the family arm too (see the
902
+ // helper): the unstated required word is the run door's voice —
903
+ // so the filter applies ONLY when the WRITE seat is asking.
904
+ const judgedFam = [
905
+ ...judgeLaneSurface(surface, prep.decl.schemaNames, prep.params),
906
+ ...judgeLaneRelations(relations, prep.params),
907
+ ...judgeLaneBounds(bounds, prep.params),
908
+ ];
909
+ const violations = admitIncomplete
910
+ ? incompleteDraftViolations(judgedFam)
911
+ : [...judgedFam];
912
+ if (violations.length > 0) {
913
+ return "lane '" + prep.fam + "/" + laneVariantId + "' refuses the state: " +
914
+ violations.map((v) => v.message).join("; ");
915
+ }
916
+
917
+ // behavioural audit's BROKEN-B: `params: {model, text,
918
+ // frobnicate: 1}` was ADMITTED at the bench and refused only at
919
+ // the run door — so a write the door accepted became a run the
920
+ // bench could not produce. The bench and the run must speak the
921
+ // same voice about a key no card declares; admissionRefusal is
922
+ // that voice, and it now runs on BOTH seats (the lane voice
923
+ // first, because it is the more specific law).
924
+ try {
925
+ admissionRefusal(this, prep.card, prep.fam, prep.params, "admission");
926
+ }
927
+ catch (e) {
928
+ // the gate speaks by THROWING on the run seat; this door's
929
+ // contract is a VERDICT, so the refusal is translated here
930
+ // rather than escaping as an unmapped error. The FIRST
931
+ // admissionRefusal call above judged the same prepared state
932
+ // and already returned on a throw; this repeat is the recorded
933
+ // belt (the undeclared-key gate rides both seats), so neither
934
+ // line below runs: the gate throws only CardArmError — its
935
+ // decls and facts are loaded and cached by the first call —
936
+ // and that refusal would have left this function above.
937
+ /* v8 ignore next -- the belt's unknown-error guard. */
938
+ if (!(e instanceof CardArmError))
939
+ throw e;
940
+ /* v8 ignore next -- the belt's verdict line. */
941
+ return e.message;
942
+ }
943
+ return null;
944
+ }
945
+
946
+
947
+
948
+
949
+
950
+
951
+
952
+
953
+
954
+
955
+
956
+
957
+
958
+
959
+
960
+
961
+
962
+
963
+
964
+
965
+
966
+ repairStageModel(card, model) {
967
+ const def = this.defsSync().get(card);
968
+ if (def === undefined)
969
+ return null;
970
+ const facts = this.modelFacts();
971
+ // Ladder 1 — the route table (the facts' own address rows and
972
+ // the owning family's variants BOTH carry the route; the owner
973
+ // with the variant that DECLARES the route wins over a bare
974
+ // address-row default).
975
+ for (const [fam, row] of Object.entries(facts)) {
976
+ for (const v of row.variants ?? []) {
977
+ if (v.route === model && def.boarded.includes(fam)) {
978
+ return { model: fam, variant: v.id };
979
+ }
980
+ for (const c of v.cells ?? []) {
981
+ if (c.route === model && def.boarded.includes(fam)) {
982
+ return { model: fam, variant: v.id };
983
+ }
984
+ }
985
+ }
986
+ }
987
+ // Ladder 2 — the boarded-family dash-prefix (era junk suffix).
988
+ const candidates = def.boarded
989
+ .filter((fam) => model.startsWith(fam + "-"))
990
+ .sort((a, b) => b.length - a.length);
991
+ const fam = candidates[0];
992
+ if (fam === undefined)
993
+ return null;
994
+ const suffix = model.slice(fam.length + 1);
995
+ const variant = (facts[fam]?.variants ?? []).some((v) => v.id === suffix)
996
+ ? suffix
997
+ : undefined;
998
+ return variant === undefined ? { model: fam } : { model: fam, variant };
999
+ }
1000
+ /** The seated mcp:<server> engine ids, sorted — the generic MCP
1001
+ * card's LIVE board (the same census the catalog/forms folds
1002
+ * serve). The same lane-read spelling runsRegistry's flow_inline
1003
+ * compile uses: the implicit seat get returns undefined when no
1004
+ * engines service is registered — a registry-only boot (walls,
1005
+ * fixtures) folds an empty census and card 'mcp' refuses with its
1006
+ * own voice, never a silent pass. */
1007
+ seatedMcpEngines() {
1008
+ const seat = this.ctx.get("engines");
1009
+ if (seat === undefined || typeof seat.ids !== "function")
1010
+ return [];
1011
+ return seat
1012
+ .ids()
1013
+ .filter((id) => id.startsWith("mcp:"))
1014
+ .sort();
1015
+ }
1016
+ resolveStageParams(body) {
1017
+ const mid = body["model"];
1018
+ if (typeof mid !== "string" || mid === "")
1019
+ return null;
1020
+ try {
1021
+ return prepareCardParams(this, body, mid, "serve").params;
1022
+ }
1023
+ catch {
1024
+ return null;
1025
+ }
1026
+ }
1027
+
1028
+
1029
+
1030
+
1031
+
1032
+
1033
+
1034
+
1035
+ async composeValidateCard(card, fam, params,
1036
+ // the body's OWN model address, when the caller still holds it: the
1037
+ // `params` this arm receives has been through the overlay, so
1038
+ // `model` is already consumed — deriving it from there fell back
1039
+ // to the FAMILY and both run-seat fixes were skipped (the live
1040
+ // verification caught exactly that: an unoffered address still
1041
+ // answered ok, and a lawful `variant: base` clone still refused).
1042
+ mid,
1043
+ // the RAW body, when the caller has already overlaid: `variant`
1044
+ // is consumed by the overlay (it is a selection coordinate, never
1045
+ // a param), so the prepare must see the body to select the lane —
1046
+ // preparing from the overlay's product silently composed the head
1047
+ // and refused a lawful `variant: base` clone.
1048
+ rawBody) {
1049
+
1050
+ // question: "HOW DID THE VALIDATE RETURN SUCCESS WHEN THE INPUT
1051
+ // IMAGE DID NOT GO"): the {model:} door composes ONE stage and
1052
+ // resolves NO wires — a $spell param is a promise only a flow's
1053
+ // FromStage links can keep. composeOnce TOLERATES spells (the
1054
+ // lane bakes them into the graph; legal on the flow path, lethal
1055
+ // on a single-card run — run 880aaa85d928 died at the merge
1056
+ // while validate passed this very body). The door's start arm
1057
+
1058
+ // bodies with the SAME voice — the two doors can never disagree.
1059
+ const spellSweep = (v, found) => {
1060
+ if (typeof v === "string") {
1061
+ if (v.startsWith("$") && v.length > 1)
1062
+ found.add(v);
1063
+ }
1064
+ else if (Array.isArray(v)) {
1065
+ for (const x of v)
1066
+ spellSweep(x, found);
1067
+ }
1068
+ else if (typeof v === "object" && v !== null) {
1069
+ for (const x of Object.values(v)) {
1070
+ spellSweep(x, found);
1071
+ }
1072
+ }
1073
+ };
1074
+ const spells = new Set();
1075
+ spellSweep(params, spells);
1076
+ if (spells.size > 0) {
1077
+ return {
1078
+ message: "params carry " +
1079
+ JSON.stringify([...spells].sort()) +
1080
+ " but a single-card run resolves no wires and no initials — the merge would refuse them at run time. Wire the input (run the bench flow so FromStage links ride) or replace the $spell with a concrete value.",
1081
+ code: "invalid_request",
1082
+ };
1083
+ }
1084
+ // THE VALIDATE SEAT RIDES THE SAME PREPARED CARD (the final live
1085
+ // verification, FIX A: this arm composed the raw FAMILY atom, so
1086
+ // it missed BOTH run-seat fixes — an unoffered address answered
1087
+ // ok:true here while the bench refused it, and a LAWFUL
1088
+ // `variant: base` clone was refused here ("fires nothing outside
1089
+ // the Base variant") while the bench admitted the same state. The
1090
+ // seats disagreed in BOTH directions because this one door never
1091
+ // shared the run seat's preparation: the board check, the lane
1092
+ // judgment and the resolved route all live there.)
1093
+ const address = mid ??
1094
+ (typeof params["model"] === "string"
1095
+ ? params["model"]
1096
+ : fam);
1097
+ const boardCheck = this.admitStageModel(card, address);
1098
+ if (!boardCheck.ok)
1099
+ return { message: boardCheck.error, code: "invalid_request" };
1100
+ let prep;
1101
+ try {
1102
+ prep = prepareCardParams(this, rawBody ?? params, address, "1");
1103
+ }
1104
+ catch (e) {
1105
+ // no factsArg is passed to composeValidateCard, so prepare's own
1106
+ // strict facts load sits inside this try: a CardArmError is this
1107
+ // seat's refusal, and every other throw keeps its identity
1108
+ if (!(e instanceof CardArmError))
1109
+ throw e;
1110
+ return { message: e.message, code: e.code };
1111
+ }
1112
+ // THE LANE JUDGES THE BODY, NEVER THE OVERLAY (the work audit's
1113
+ // CRITICAL — a THIRD half-landed fix, and the exact one phase1's
1114
+ // own comment warns about: `model` is an envelope key, so the
1115
+ // overlaid params carry no address, laneVerdict's model-less arm
1116
+ // stands down, and the lane surface + relation laws NEVER RAN at
1117
+ // validate — an export conflict answered ok:true here while the
1118
+ // bench and the start door both refused it). The run seat already
1119
+ // judges `body`; the seats now judge the same thing.
1120
+ const laneRefusal = this.laneVerdict(card, rawBody ?? params);
1121
+ if (laneRefusal !== null) {
1122
+ return { message: laneRefusal, code: "lane_refusal" };
1123
+ }
1124
+ try {
1125
+ await composeOnce(this, prep.card, prep.modelId, prep.params, "", "1");
1126
+ return null;
1127
+ }
1128
+ catch (e) {
1129
+ if (e instanceof CardArmError) {
1130
+ return { message: e.message, code: e.code };
1131
+ }
1132
+ throw e;
1133
+ }
1134
+ }
1135
+ /** Phase 1 (run_id ""): validates shape/admission/boarding before
1136
+ * registration. The $spell branch composes NO graph (the pool
1137
+ * passes — the two-card-flow handoff). */
1138
+ async phase1Card(body, mid) {
1139
+ const prep = prepareCardParams(this, body, mid, "1");
1140
+ // THE BOARD CHECK RIDES THE RUN SEAT TOO (the behavioural
1141
+ // re-check's BYPASS 1: the bench refused an unoffered model
1142
+ // address, but `validate` with the SAME address composed the
1143
+ // family HEAD and answered ok — two seats, one law, opposite
1144
+ // verdicts). The same exact-address check the write door runs,
1145
+ // here at the door that composes.
1146
+ const boardCheck = this.admitStageModel(prep.card, body["model"]);
1147
+ if (!boardCheck.ok) {
1148
+ // the constructor takes the code as its THIRD param (the
1149
+ // object-literal spelling passed `{code: undefined}` as the
1150
+ // code — the runs door then answered "unmapped refusal code
1151
+ // undefined"); same code the write door stamps for a board
1152
+ // refusal.
1153
+ throw new CardArmError(400, boardCheck.error, "invalid_request");
1154
+ }
1155
+
1156
+ // ADMISSION runs before the lane-presence gate — a body-shape
1157
+ // refusal is knowable without any weights (box-independent);
1158
+ // presence is an environment question and follows. Before this
1159
+ // order a weight-absent box heard the presence voice even for
1160
+ // garbage bodies, and the compose-smoke /recipe/ wall held only
1161
+ // on boxes carrying the encoders.
1162
+ admissionRefusal(this, prep.card, prep.fam, liftStanza(prep.params), "1");
1163
+
1164
+ // bench-write door judges the DECL's surface + relation words
1165
+ // when a state is BUILT, but a RESTORED row (the archive loads,
1166
+ // Run teaches) and any writer that predates the door arrive here
1167
+ // unjudged. The run seat is where the declaration gets its second
1168
+ // voice — ONE spelling (laneVerdict), the same judgment the form
1169
+ // renders and the write door refuses on, so no card needs a
1170
+ // hand-written copy of the law to be safe at Run.
1171
+ //
1172
+ // THE BODY, NOT THE PREPARED PARAMS (the second probe, the same
1173
+ // hour): `model` is a card-envelope key — liftCardParams consumes
1174
+ // it — so judging prep.params here reads no model at all and
1175
+ // judges NOTHING. The write door judges the body, so the run seat
1176
+ // judges the body: laneVerdict runs its own prepareCardParams (one
1177
+ // resolution, the same one composeOnce gets) and reaches the same
1178
+ // verdict. (Confirmed by the door audit's receipt: judging
1179
+ // prep.params made every state admit.)
1180
+ const laneRefusal = this.laneVerdict(prep.card, body);
1181
+ if (laneRefusal !== null) {
1182
+ throw phaseRefusal("1", laneRefusal);
1183
+ }
1184
+ // THE LANE PRESENCE GATE (one pattern, every family): before any
1185
+ // graph composes, the family's declared lane files must stand on
1186
+ // disk. Img Gen vs Img Edit was luck, not law — this is the law.
1187
+ // (The gate throws on a missing lane file and returns null when
1188
+ // the lane stands — the refusal is a throw, never a value, so
1189
+ // there is no return-value arm here.) A FAMILYLESS card-unit
1190
+ // (the Run-press compose) skips it: no family row declares
1191
+ // lanes, and the card's own pins gate loud at the engine's load
1192
+ // (the YOLO/SAM2 checkpoints refuse hard when absent).
1193
+ if (prep.familyless !== true) {
1194
+ lanePresenceRefusal(prep.fam);
1195
+ }
1196
+ const spells = prep.decl.spells;
1197
+ const pool = {};
1198
+ for (const k of spells) {
1199
+ const v = prep.params[k];
1200
+ if (k in prep.params && typeof v === "string" && v.startsWith("$"))
1201
+ pool[k] = v;
1202
+ }
1203
+ if (Object.keys(pool).length > 0) {
1204
+ return { ...prep, spell: { skeleton: prep.skeleton, inputs: pool } };
1205
+ }
1206
+ // the RESOLVED address, not the family atom (BROKEN-C)
1207
+ await composeOnce(this, prep.card, prep.modelId, prep.params, "", "1");
1208
+ return { ...prep, spell: null };
1209
+ }
1210
+ /** Phase 2 (the real run id): composes the SAME overlaid body phase
1211
+ * 1 validated (submit 1294-1301 — idempotent, absent-keys-only;
1212
+ * the editor's seeded stamps pass through byte-identical).
1213
+ * A $spell body composes VERBATIM here (run context — the $spell
1214
+ * wires into the Load* file slot; the merged path refuses a
1215
+ * link-in-file-slot LOUDLY, test_two_card_flow). */
1216
+ async phase2Card(p1, runId) {
1217
+ const graph = await composeOnce(this, p1.card, p1.modelId, p1.params, runId, "2");
1218
+
1219
+
1220
+ if (typeof graph !== "object" || graph === null || Array.isArray(graph)) {
1221
+ throw new CardArmError(400, "card_compose produced an empty graph for " + p1.mid, "invalid_request");
1222
+ }
1223
+ const def = this.defsSync().get(p1.card);
1224
+ if (def === undefined) {
1225
+ throw new CardArmError(400, `unknown card ${p1.card}`, "card_compose");
1226
+ }
1227
+ let flow;
1228
+ try {
1229
+ flow = resolveCardFlowOutputs(def, p1.params, graph);
1230
+ }
1231
+ catch (error) {
1232
+ if (error instanceof ComposeRefusal) {
1233
+ throw new CardArmError(400, `${error.code}: ${error.message}`, "card_compose");
1234
+ }
1235
+ throw error;
1236
+ }
1237
+ return { graph, skeleton: p1.skeleton, spell: p1.spell, ...flow };
1238
+ }
1239
+ }
1240
+ /** The provider plugin (fiber-owned): owns the CardRegistryService
1241
+ * lifetime and primes it at load, so inject-gated consumers apply
1242
+ * only after the registry is primed. Manifest row
1243
+ * estate-card-registry rides BEFORE every consumer (validate,
1244
+ * flows-start, chrome, planes — the stroke-2b row placement rule).
1245
+ * (The DSH leaf discipline — addressed code loads by address,
1246
+ * never as a `cordis:` builtin.) */
1247
+ /** The host row (estate naming — the gateway manifest died with
1248
+ * the app; this is what the estate composition mounts). */
1249
+ export const cardRegistryProvider = {
1250
+ name: "estate-card-registry",
1251
+ // NO comfyui inject: the compose rim property-reads ctx.comfyui on
1252
+ // its OWN throwaway EngineContext (which mounts ComfyUIService
1253
+ // itself at the rim head) — never on the host fiber, so no read
1254
+ // contract is owed to the composition.
1255
+ async apply(ctx) {
1256
+ const svc = new CardRegistryService(ctx);
1257
+ await svc.prime();
1258
+ },
1259
+ };
1260
+ /** Resolve the service for request-path helpers that take it as an
1261
+ * optional trailing param (the stroke-2b shape): an explicit arg
1262
+ * wins. Null = the caller forgot to thread ctx.cardRegistry — a
1263
+ * bug, so reads throw LOUD (a registry read without a registry is
1264
+ * never an empty answer). Door listeners MUST pass
1265
+ * ctx.cardRegistry (their inject declares it). */
1266
+ export function needCardRegistry(cards, where) {
1267
+ if (cards === null || cards === undefined) {
1268
+ throw new Error("[card_registry] no CardRegistryService for " + where +
1269
+ " — doors inject 'cardRegistry' and pass ctx.cardRegistry " +
1270
+ "(the manifest's estate-card-registry row primes at boot)");
1271
+ }
1272
+ return cards;
1273
+ }
1274
+ //# sourceMappingURL=cardsRegistry.js.map