@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
@@ -12,14 +12,19 @@
12
12
  // Erasable-syntax TS only (node --experimental-strip-types).
13
13
  import { execFile } from "node:child_process";
14
14
  import { promisify } from "node:util";
15
- import { writeFileSync, readFileSync } from "node:fs";
15
+ import { readFileSync } from "node:fs";
16
16
  import { join } from "node:path";
17
- import { endpointConfigPath, invalidateObjectInfo, liveObjectInfo, loadEndpointConfig, resolveEngineBaseUrl, } from "@melite/comfyui-cordis";
17
+ import { ComfyError, endpointConfigPath, invalidateObjectInfo, liveObjectInfo, loadEndpointConfig, resolveEngineBaseUrl, } from "@melite/comfyui-cordis";
18
+ import { writeJsonAtomic } from "./queueLock.js";
18
19
  import { installUserLora, installUserLoraBytes, loraNamesFromObjectInfo, readUserLoraRows, resolveEngineLorasDir, unboardedRows, userLorasPath, } from "@melite/comfyui-cordis/user-loras";
20
+ import { AcquireBusyError } from "@melite/estate-provisioning";
19
21
  import { ManagerApiError, managerGet, managerPost, planeUnavailable } from "./managerRail.js";
20
22
  import { probeEndpoint, activeRuns, managerSecurity, engineQueueView } from "./manageProbe.js";
21
- import { base, mapManagerRefused, mapRail, railMs, estateOnly, awaitQueueDrained, systemctl, guardLifecycle, COMFY_UNIT } from "./manageOps.js";
23
+ import { base, mapManagerRefused, mapRail, railMs, estateOnly, awaitQueueDrained, systemctl, guardLifecycle } from "./manageOps.js";
24
+ import { holdLifecycle } from "./lifecycleLatch.js";
22
25
  import { deadline as deadlineOf, timeoutOf } from "@deepseek-ai/dsh-timeout";
26
+ import { segmentConfined } from "@melite/contracts/mediaKinds";
27
+ import { artifactFileName } from "@melite/contracts/benchResult";
23
28
  const execFileAsync = promisify(execFile);
24
29
  // ── SSOT vocabulary ─────────────────────────────────────────────────
25
30
  // Closed vocabulary — a typo is a 422, not a silent miss.
@@ -174,6 +179,7 @@ export function parseReq(doc) {
174
179
  action: action,
175
180
  nodes: Array.isArray(d["nodes"]) ? d["nodes"].map(String).filter((s) => s !== "") : [],
176
181
  url: str("url"),
182
+ ref: str("ref"),
177
183
  relative_path: str("relative_path"),
178
184
  wait: typeof d["wait"] === "boolean" ? d["wait"] : null,
179
185
  timeout_seconds: num("timeout_seconds", 300),
@@ -186,6 +192,7 @@ export function parseReq(doc) {
186
192
  target: str("target") || "comfy",
187
193
  extra_args: Array.isArray(d["extra_args"]) ? d["extra_args"].map(String) : [],
188
194
  force: d["force"] === true,
195
+ operator_confirmed: d["operator_confirmed"] === true,
189
196
  snapshot: str("snapshot"),
190
197
 
191
198
  // ENGINE will accept (its own combo) plus the user's own rows;
@@ -240,11 +247,22 @@ function withNextAction(response, nextAction) {
240
247
  function engineBootReceiptPath(ctx) {
241
248
  return join(ctx.repoRoot, "data", "runtime", "comfyui", ".estate-engine-boot.json");
242
249
  }
243
- function recordEngineBoot(ctx, source) {
250
+ async function recordEngineBoot(ctx, source) {
244
251
  try {
245
- writeFileSync(engineBootReceiptPath(ctx), JSON.stringify({ boot_at: Date.now(), source }) + "\n", "utf8");
252
+ // J6: the receipt rides the package's atomic writer — a bare
253
+ // writeFileSync could tear the file across a crash, and a torn
254
+ // receipt is a FALSE blindness signal for the status reader.
255
+ await writeJsonAtomic(engineBootReceiptPath(ctx), { boot_at: Date.now(), source });
246
256
  }
247
257
  catch {
258
+ // Swallowed with reason: the engine IS rebooting regardless; a
259
+ // failed receipt write must never fail the restart answer — with
260
+ // ONE exception (MP-R2, round 19): the caller's own abort. An
261
+ // abort surfacing inside this write must propagate (the hRestart
262
+ // finally still drops the cache for the issued reboot) instead of
263
+ // being laundered into a success the caller cancelled.
264
+ if (signalIsAborted(ctx.signal))
265
+ throw abortReason(ctx.signal);
248
266
  return;
249
267
  }
250
268
  }
@@ -280,51 +298,55 @@ function safeStatusItems(items) {
280
298
  ...(item.detail === undefined ? {} : { detail: item.detail }),
281
299
  }));
282
300
  }
283
- function normalizedResources(resources, provisioning) {
284
- return resources.map((resource) => {
285
- let operationId = resource.operationId;
286
- let state = resource.state;
287
- let items = resource.items;
288
- let detail = resource.detail;
289
- // NO SEAT = no operation merge, not a throw: a resource status the
290
- // door can still report beats a status door that cannot answer.
301
+ async function normalizedResources(resources, provisioning) {
302
+ const rows = [];
303
+ for (const resource of resources) {
304
+ rows.push(await normalizeResource(resource, provisioning));
305
+ }
306
+ return rows;
307
+ }
308
+
309
+
310
+
311
+
312
+
313
+
314
+
315
+
316
+
317
+ async function normalizeResource(resource, provisioning) {
318
+ const row = (operationId, state, items, detail) => ({
319
+ ...resource,
320
+ state,
321
+ items,
322
+ ...(operationId === undefined ? {} : { operationId }),
323
+ ...(detail === undefined ? {} : { detail }),
324
+ });
325
+ if (provisioning === undefined) {
291
326
 
292
327
 
293
328
 
294
329
 
295
330
 
296
- if (provisioning === undefined) {
297
- return {
298
- ...resource,
299
- state,
300
- items,
301
- ...(operationId === undefined ? {} : { operationId }),
302
- ...(detail === undefined ? {} : { detail }),
303
- };
331
+
332
+ return row(resource.operationId, resource.state, resource.items, resource.detail);
333
+ }
334
+ try {
335
+ const operation = provisioning.operationOf(resource.ref);
336
+ if (operation === undefined) {
337
+ return row(resource.operationId, resource.state, resource.items, resource.detail);
304
338
  }
305
- try {
306
- const operation = provisioning.operationOf(resource.ref);
307
- if (operation !== undefined) {
308
- operationId = operation.operationId;
309
- state = operation.state;
310
- items = operation.items;
311
- detail = detail ?? operation.detail;
312
- }
339
+ const verified = provisioning.verifyOperation === undefined
340
+ ? operation
341
+ : await provisioning.verifyOperation(operation);
342
+ if (verified.state !== operation.state) {
343
+ return row(verified.operationId, verified.state, verified.items, verified.items[0]?.detail ?? resource.detail);
313
344
  }
314
- catch {
315
- operationId = resource.operationId;
316
- state = resource.state;
317
- items = resource.items;
318
- detail = resource.detail;
319
- }
320
- return {
321
- ...resource,
322
- state,
323
- items,
324
- ...(operationId === undefined ? {} : { operationId }),
325
- ...(detail === undefined ? {} : { detail }),
326
- };
327
- });
345
+ return row(operation.operationId, operation.state, operation.items, resource.detail ?? operation.detail);
346
+ }
347
+ catch {
348
+ return row(resource.operationId, resource.state, resource.items, resource.detail);
349
+ }
328
350
  }
329
351
  function operationRows(resources) {
330
352
  return resources.flatMap((resource) => {
@@ -425,7 +447,7 @@ function versionOptions(doc) {
425
447
  async function hStatus(req, ctx) {
426
448
  const cfg = ctx.endpoint();
427
449
  const endpoint = await probeEndpoint(ctx);
428
- const active = activeRuns();
450
+ const active = activeRuns(ctx.stateRoots);
429
451
 
430
452
  // law (unreadable ⇒ active — guardLifecycle refuses restarts on
431
453
  // it), but the STATUS view was asserting every unsettled sidecar
@@ -495,7 +517,7 @@ async function hStatus(req, ctx) {
495
517
  resourcesDetail = error instanceof Error ? error.message : String(error);
496
518
  }
497
519
  }
498
- const normalized = normalizedResources(resources, provisionSeat);
520
+ const normalized = await normalizedResources(resources, provisionSeat);
499
521
  const operations = operationRows(normalized);
500
522
  const resourceRows = normalized.map((resource) => ({
501
523
  ...resource,
@@ -511,7 +533,7 @@ async function hStatus(req, ctx) {
511
533
  manager: {
512
534
  ...manager,
513
535
  security: managerSecurity(ctx.repoRoot),
514
- unit: COMFY_UNIT,
536
+ unit: ctx.comfyUnit,
515
537
  operations,
516
538
  },
517
539
  comfyui_versions: comfyuiVersions,
@@ -526,6 +548,7 @@ async function hStatus(req, ctx) {
526
548
  : {}),
527
549
  engine_boot: engineBootRow(ctx),
528
550
  routing,
551
+ auto_provision: ctx.autoProvision,
529
552
  resources: resourceRows,
530
553
  operations,
531
554
  ...(resourcesDetail === undefined ? {} : { resources_detail: resourcesDetail }),
@@ -537,7 +560,7 @@ async function hLogs(req, ctx) {
537
560
  const tail = Math.max(1, Math.min(Math.trunc(req.tail), 2000));
538
561
  let stdout;
539
562
  try {
540
- const out = await execFileAsync("journalctl", ["--user", "-u", COMFY_UNIT, "-n", String(tail), "--no-pager", "-o", "cat"], {
563
+ const out = await execFileAsync("journalctl", ["--user", "-u", ctx.comfyUnit, "-n", String(tail), "--no-pager", "-o", "cat"], {
541
564
  timeout: 15 * 1000,
542
565
  encoding: "utf8",
543
566
  signal: ctx.signal,
@@ -547,12 +570,12 @@ async function hLogs(req, ctx) {
547
570
  catch (error) {
548
571
  if (signalIsAborted(ctx.signal))
549
572
  throw abortReason(ctx.signal);
550
- throw unavailable("logs need the estate deployment's journal (unit " + COMFY_UNIT + "): " +
573
+ throw unavailable("logs need the estate deployment's journal (unit " + ctx.comfyUnit + "): " +
551
574
  error.message.slice(0, 120));
552
575
  }
553
576
  throwIfAborted(ctx.signal);
554
577
  const lines = stdout.split("\n").filter((ln) => ln !== "");
555
- return ok(req.action, lines.length + " log line(s) from " + COMFY_UNIT, lines);
578
+ return ok(req.action, lines.length + " log line(s) from " + ctx.comfyUnit, lines);
556
579
  }
557
580
  async function hSearch(req, ctx) {
558
581
  need(req, "query");
@@ -583,14 +606,13 @@ async function withManageTimeout(req, ctx, work, boundMs = railMs(req)) {
583
606
  const timedOut = () => timeoutOf(dl.signal, "MANAGE_OP") !== undefined;
584
607
  try {
585
608
  const value = await work(dl.signal);
609
+
610
+ // RESOLVED, its value is real — reporting 504 for a result the
611
+ // caller could have used (the old Date.now arm fired on work that
612
+ // landed one tick past boundAt) serves nobody. An unresolved work
613
+ // still dies at the deadline below (the abort arm).
586
614
  if (signalIsAborted(ctx.signal))
587
615
  throw abortReason(ctx.signal);
588
- if (timedOut() || Date.now() >= boundAt) {
589
- throw new Refused(504, "manage operation timed out", {
590
- state: "timeout",
591
- next_action: "status",
592
- });
593
- }
594
616
  return value;
595
617
  }
596
618
  catch (error) {
@@ -624,8 +646,21 @@ function externalModelPath(req) {
624
646
  if (folder === "loras" || folder.startsWith("loras/")) {
625
647
  throw badRequest("download_model refuses the loras dir — LoRAs arrive by copy or upload (lora_install), never by url");
626
648
  }
627
- const filename = req.filename !== "" ? req.filename : req.url.split("/").pop();
628
- if (filename === "" || filename.includes("/") || filename.includes("..")) {
649
+
650
+ // rides the SSOT the cell artifacts ride — a URL's query and
651
+ // fragment are never the file's name ("...safetensors?download=1"
652
+ // landed bytes under a name the engine never listed), a trailing
653
+ // slash names a directory (the empty name refuses by the bare-name
654
+ // fence below), and %XX escapes decode to the true name.
655
+ const filename = req.filename !== "" ? req.filename : artifactFileName(req.url);
656
+ // The bare-name fence rides the SSOT (the dry-sweep's N5):
657
+ // segmentConfined owns the bytes of a legal segment — inner dots
658
+ // are legal ("model..ckpt" stays under the root; the traversal
659
+ // fence is the slash arm, since the SSOT judges one segment) and
660
+ // the NUL arm is its behavioral wall. The old hand-roll refused
661
+ // every inner ".." and had drifted from the grammar every other
662
+ // door rides.
663
+ if (filename.includes("/") || !segmentConfined(filename)) {
629
664
  throw badRequest("filename must be a bare name under the models root");
630
665
  }
631
666
  return { relativePath: folder, filename };
@@ -847,22 +882,65 @@ async function hInstallExtension(req, ctx) {
847
882
  }, operations);
848
883
  });
849
884
  }
885
+
886
+
887
+
888
+
889
+
890
+
891
+
892
+ function operatorConfirmGate(req, door) {
893
+ if (req.operator_confirmed === true)
894
+ return null;
895
+ return [
896
+ 409,
897
+ {
898
+ action: door,
899
+ ok: false,
900
+ state: "conflict",
901
+ detail: door + ": external acquisitions land bytes from a caller-named URL — pass operator_confirmed=true " +
902
+ "(the human's approval) to proceed. The flag is recorded with the operation.",
903
+ next_action: "operator_confirmed",
904
+ },
905
+ ];
906
+ }
850
907
  async function hInstallExtensionUrl(req, ctx) {
851
908
  need(req, "url");
852
909
  estateOnly(req, ctx.endpoint());
853
- const result = await withManageTimeout(req, ctx, (signal) => provisioningOf(ctx).acquireExternal({ kind: "extension", url: req.url }, { operatorConfirmed: true }, signal));
910
+ // THE SEAT ASKS FIRST (the hProvisionModel order law): a seatless
911
+ // lane names its own 503 before any human flag is demanded
912
+ const provisioner = provisioningOf(ctx);
913
+ const confirmed = operatorConfirmGate(req, "install_extension_url");
914
+ if (confirmed !== null)
915
+ return confirmed;
916
+ const result = await withManageTimeout(req, ctx, (signal) => provisioner.acquireExternal({ kind: "extension", url: req.url, ...(req.ref === "" ? {} : { ref: req.ref }) }, { operatorConfirmed: req.operator_confirmed }, signal));
854
917
  return provisionEnvelope(req.action, result);
855
918
  }
856
919
  async function hDownloadModel(req, ctx) {
857
920
  need(req, "url");
858
921
  estateOnly(req, ctx.endpoint());
859
922
  const path = externalModelPath(req);
860
- const result = await withManageTimeout(req, ctx, (signal) => provisioningOf(ctx).acquireExternal({
923
+ // THE SEAT ASKS FIRST (the hProvisionModel order law), then the
924
+ // gate below the shape guards: a request refused on its own merits
925
+ // never needs the human's flag
926
+ const provisioner = provisioningOf(ctx);
927
+ const confirmed = operatorConfirmGate(req, "download_model");
928
+ if (confirmed !== null)
929
+ return confirmed;
930
+ const result = await withManageTimeout(req, ctx, (signal) => provisioner.acquireExternal({
861
931
  kind: "model",
862
932
  url: req.url,
863
933
  relativePath: path.relativePath,
864
934
  filename: path.filename,
865
- }, { operatorConfirmed: true }, signal));
935
+ }, { operatorConfirmed: req.operator_confirmed }, signal));
936
+
937
+ // living process must not leave the boot-time /object_info doc
938
+ // serving. The old restartRequired guard was dead — the service
939
+ // answers models "active" on every path (only extension installs
940
+ // arm restart_required), so model landings never dropped and the
941
+ // census stayed boot-stale until a reboot.
942
+ invalidateLiveObjectInfo(ctx);
943
+ ctx.rearmWeights?.();
866
944
  return provisionEnvelope(req.action, result);
867
945
  }
868
946
  function familyModelDeclared(ctx, id) {
@@ -919,6 +997,19 @@ async function hProvisionModel(req, ctx) {
919
997
  }
920
998
  throwIfAborted(signal);
921
999
  const result = await provisioner.ensure(ref, undefined, signal);
1000
+ // THE WEIGHTS LANDED UNDER A LIVING PROCESS (cold-drive run 6,
1001
+
1002
+
1003
+ // boot-time /object_info doc — the next compose read an empty combo
1004
+ // ("unet_name allows 0 values"). The engine's own folder scan is
1005
+ // mtime-live, so dropping the cached doc makes the landing visible
1006
+ // without a reboot (same door law as loraInstalled below).
1007
+
1008
+ // dead guard — model items never arm it (service answers "active";
1009
+ // only extensions yield restart_required), so the drop must not
1010
+ // wait on a flag that never fires.
1011
+ invalidateLiveObjectInfo(ctx);
1012
+ ctx.rearmWeights?.();
922
1013
  return provisionEnvelope(req.action, result, {
923
1014
  model: req.model,
924
1015
  files: result.items.filter((item) => item.state === "active").map((item) => item.key),
@@ -947,6 +1038,17 @@ async function hAcquireWeight(req, ctx) {
947
1038
  if (progress === null || progress === undefined) {
948
1039
  throw notFound("unknown acquire_weight operation: " + req.operation_id);
949
1040
  }
1041
+
1042
+ // the files (same door law as hProvisionModel); the next read
1043
+ // re-fetches once and sees the landed weights
1044
+ if (progress.state === "installed" ||
1045
+ progress.state === "restart_required" ||
1046
+ progress.state === "active") {
1047
+ invalidateLiveObjectInfo(ctx);
1048
+ // the presence face re-arms with the doc: the files the engine
1049
+ // will serve are the files the board's present flags claim
1050
+ ctx.rearmWeights?.();
1051
+ }
950
1052
  return ok(req.action, "acquire_weight " + progress.operationId + ": " + String(progress.bytes) + "/" + String(progress.total)
951
1053
  + " bytes (" + progress.state + ")", {
952
1054
  operation_id: progress.operationId,
@@ -966,6 +1068,7 @@ async function hAcquireWeight(req, ctx) {
966
1068
  if (typeof provisioner.startWeightAcquire !== "function" || typeof provisioner.progressOf !== "function") {
967
1069
  throw unavailable("acquire_weight is not configured on this lane");
968
1070
  }
1071
+ const startAcquire = provisioner.startWeightAcquire;
969
1072
  const family = {
970
1073
  kind: "model",
971
1074
  owner: "family",
@@ -973,11 +1076,19 @@ async function hAcquireWeight(req, ctx) {
973
1076
  ...(req.variant === "" ? {} : { variant: req.variant }),
974
1077
  ...(req.quant === "" ? {} : { quant: req.quant }),
975
1078
  };
1079
+ // The provisioner hops ride the same deadline fuse as every
1080
+ // sibling arm (audit N-E2): a stalled provisioner answers 504
1081
+ // inside the request's own railMs, never hangs the door.
976
1082
  let ref = family;
1083
+ let plan = null;
977
1084
  try {
978
- await provisioner.plan(family);
1085
+ plan = await withManageTimeout(req, ctx, async () => await provisioner.plan(family));
979
1086
  }
980
1087
  catch (error) {
1088
+ // the fuse's own refusal keeps its voice (audit F1): a deadline
1089
+ // maps to 504 here, never into the unknown-model 404 below
1090
+ if (error instanceof Refused)
1091
+ throw error;
981
1092
  if (familyModelDeclared(ctx, req.model)) {
982
1093
  throw notFound(error instanceof Error ? error.message : String(error));
983
1094
  }
@@ -989,13 +1100,51 @@ async function hAcquireWeight(req, ctx) {
989
1100
  ...(req.quant === "" ? {} : { quant: req.quant }),
990
1101
  };
991
1102
  try {
992
- await provisioner.plan(ref);
1103
+ plan = await withManageTimeout(req, ctx, async () => await provisioner.plan(ref));
993
1104
  }
994
1105
  catch (nested) {
1106
+ if (nested instanceof Refused)
1107
+ throw nested;
995
1108
  throw notFound(nested instanceof Error ? nested.message : String(nested));
996
1109
  }
997
1110
  }
998
- const operationId = await provisioner.startWeightAcquire(ref);
1111
+
1112
+
1113
+ // downloads every row of a multi-GB family. The name maps to plan
1114
+ // item keys exactly as the provisioner's own options.items filter
1115
+ // keys them (kind model → name, else id); an unknown filename is
1116
+ // the item-not-found refusal, never a whole-family fetch.
1117
+ let acquireOptions;
1118
+ if (req.filename !== "" && plan !== null) {
1119
+ const wanted = plan.items
1120
+ .filter((item) => (item.kind === "model" ? item.name : item.id) === req.filename)
1121
+ .map((item) => (item.kind === "model" ? item.name : item.id));
1122
+ if (wanted.length === 0) {
1123
+ throw badRequest(`acquire_weight file '${req.filename}' matches no provision row of '${req.model}' (item-not-found) — refusing to fetch the whole family for a one-file miss`);
1124
+ }
1125
+ acquireOptions = { items: wanted };
1126
+ }
1127
+ // THE BUSY MAP (audit I-S4): a plane at its concurrency cap is a
1128
+ // wait, not a failure — the 429 carries retry_after_ms and points
1129
+ // the caller back at the poll arm
1130
+ let operationId;
1131
+ try {
1132
+ operationId = await withManageTimeout(req, ctx, async () => await startAcquire.call(provisioner, ref, acquireOptions));
1133
+ }
1134
+ catch (error) {
1135
+ if (error instanceof AcquireBusyError) {
1136
+ return [429, {
1137
+ action: req.action,
1138
+ ok: false,
1139
+ state: "busy",
1140
+ status: 429,
1141
+ detail: error.message,
1142
+ next_action: "acquire_weight",
1143
+ retry_after_ms: error.retryAfterMs,
1144
+ }];
1145
+ }
1146
+ throw error;
1147
+ }
999
1148
  const progress = provisioner.progressOf(operationId);
1000
1149
  const bytes = progress?.bytes ?? 0;
1001
1150
  const total = progress?.total ?? 0;
@@ -1019,13 +1168,24 @@ async function hRestart(req, ctx) {
1019
1168
  guardLifecycle(req, ctx);
1020
1169
  const cfg = ctx.endpoint();
1021
1170
  estateOnly(req, cfg);
1171
+
1172
+ // call so a run pressed mid-reboot refuses instead of tearing.
1173
+ const releaseLifecycle = holdLifecycle(req.action);
1022
1174
  try {
1023
1175
  await managerPost(base(ctx), "/manager/reboot", {}, { ctx, timeoutMs: 10_000 });
1024
- recordEngineBoot(ctx, "estate restart");
1025
-
1026
- // the cached /object_info doc must not outlive it (the refresh
1027
1176
 
1028
- invalidateLiveObjectInfo(ctx);
1177
+ // await — the cached /object_info doc must not outlive it. The
1178
+ // drop rides a finally so an abort inside the receipt write
1179
+ // cannot skip it (the abort still propagates after the drop).
1180
+ try {
1181
+ await recordEngineBoot(ctx, "estate restart");
1182
+ }
1183
+ finally {
1184
+
1185
+ // the cached /object_info doc must not outlive it (the refresh
1186
+
1187
+ invalidateLiveObjectInfo(ctx);
1188
+ }
1029
1189
  return ok(req.action, "reboot issued (systemd re-spawns the engine)", { next_action: "status" });
1030
1190
  }
1031
1191
  catch (e) {
@@ -1033,23 +1193,38 @@ async function hRestart(req, ctx) {
1033
1193
  // The vendor reboots by exiting: the connection can drop after
1034
1194
  // the 200 is sent — same honest answer.
1035
1195
  if (/fetch failed|ECONNRESET|socket/i.test(e.text)) {
1036
- recordEngineBoot(ctx, "estate restart (connection dropped mid-answer)");
1037
- invalidateLiveObjectInfo(ctx);
1196
+ try {
1197
+ await recordEngineBoot(ctx, "estate restart (connection dropped mid-answer)");
1198
+ }
1199
+ finally {
1200
+ invalidateLiveObjectInfo(ctx);
1201
+ }
1038
1202
  return ok(req.action, "reboot issued (connection closed by restart)", { next_action: "status" });
1039
1203
  }
1040
1204
  throw mapManagerRefused(e, req.action);
1041
1205
  }
1042
1206
  throw mapRail(e, req.action);
1043
1207
  }
1208
+ finally {
1209
+ releaseLifecycle();
1210
+ }
1044
1211
  }
1045
1212
  async function hStop(req, ctx) {
1046
1213
  guardLifecycle(req, ctx);
1047
1214
  estateOnly(req, ctx.endpoint());
1048
- return await systemctl(req, "stop", ctx.signal);
1215
+
1216
+ // systemctl call so a run pressed mid-stop refuses.
1217
+ const releaseLifecycle = holdLifecycle(req.action);
1218
+ try {
1219
+ return await systemctl(req, "stop", ctx.comfyUnit, ctx.signal);
1220
+ }
1221
+ finally {
1222
+ releaseLifecycle();
1223
+ }
1049
1224
  }
1050
1225
  async function hLaunch(req, ctx) {
1051
1226
  estateOnly(req, ctx.endpoint());
1052
- return await systemctl(req, "start", ctx.signal);
1227
+ return await systemctl(req, "start", ctx.comfyUnit, ctx.signal);
1053
1228
  }
1054
1229
  async function hUpdate(req, ctx) {
1055
1230
  if (req.target !== "comfy") {
@@ -1058,6 +1233,9 @@ async function hUpdate(req, ctx) {
1058
1233
  guardLifecycle(req, ctx);
1059
1234
  const cfg = ctx.endpoint();
1060
1235
  estateOnly(req, cfg);
1236
+
1237
+ // calls so a run pressed mid-update refuses instead of tearing.
1238
+ const releaseLifecycle = holdLifecycle(req.action);
1061
1239
  try {
1062
1240
  await managerPost(base(ctx), "/manager/queue/update_comfyui", {}, { ctx, timeoutMs: 10_000 });
1063
1241
  await managerPost(base(ctx), "/manager/queue/start", {}, { ctx, timeoutMs: 10_000 });
@@ -1082,12 +1260,18 @@ async function hUpdate(req, ctx) {
1082
1260
  throw e;
1083
1261
  throw mapRail(e, req.action);
1084
1262
  }
1263
+ finally {
1264
+ releaseLifecycle();
1265
+ }
1085
1266
  }
1086
1267
  async function hSwitchVersion(req, ctx) {
1087
1268
  need(req, "version");
1088
1269
  guardLifecycle(req, ctx);
1089
1270
  const cfg = ctx.endpoint();
1090
1271
  estateOnly(req, cfg);
1272
+
1273
+ // switch so a run pressed mid-switch refuses instead of tearing.
1274
+ const releaseLifecycle = holdLifecycle(req.action);
1091
1275
  try {
1092
1276
  const doc = await managerGet(base(ctx), "/comfyui_manager/comfyui_versions", {
1093
1277
  ctx, timeoutMs: 30_000,
@@ -1103,6 +1287,9 @@ async function hSwitchVersion(req, ctx) {
1103
1287
  catch (e) {
1104
1288
  throw mapRail(e, req.action);
1105
1289
  }
1290
+ finally {
1291
+ releaseLifecycle();
1292
+ }
1106
1293
  return ok(req.action, "switch to " + req.version + " issued (restart required)", {
1107
1294
  state: "restart_required",
1108
1295
  restart_required: true,
@@ -1114,12 +1301,18 @@ async function hFree(req, ctx) {
1114
1301
  const b = base(ctx);
1115
1302
  if (b === "")
1116
1303
  throw planeUnavailable(b, "no endpoint url");
1304
+
1305
+ // call so a run pressed mid-free refuses instead of tearing.
1306
+ const releaseLifecycle = holdLifecycle(req.action);
1117
1307
  try {
1118
1308
  await managerPost(b, "/free", { unload_models: true, free_memory: true }, { ctx, timeoutMs: 30_000 });
1119
1309
  }
1120
1310
  catch (e) {
1121
1311
  throw mapRail(e, req.action);
1122
1312
  }
1313
+ finally {
1314
+ releaseLifecycle();
1315
+ }
1123
1316
  return ok(req.action, "free issued (next worker iteration)", { next_action: "status" });
1124
1317
  }
1125
1318
  // ── endpoint_set: the operator's server URL change ────────────────
@@ -1135,6 +1328,19 @@ async function hEndpointSet(req, ctx) {
1135
1328
  }
1136
1329
  // Probe the candidate BEFORE writing (no unreachable URL ever
1137
1330
  // lands in the config; the old URL keeps serving on refusal).
1331
+ // THE ENV FENCE (audit I-S2, the KEY LAW divergence enforced):
1332
+ // resolveEngineBaseUrl reads COMFYUI_URL FIRST, so with the env
1333
+ // set, this file write lands on a plane no reader keys off —
1334
+ // the census, lora doors, and live docs keep answering the env
1335
+ // server while the UI reports the file's. Refuse instead of
1336
+ // warning: the operator unsets COMFYUI_URL (or points it at the
1337
+ // same server) and the write becomes real.
1338
+ const envUrl = (process.env["COMFYUI_URL"] ?? "").trim().replace(/\/+$/, "");
1339
+ if (envUrl !== "" && envUrl !== url) {
1340
+ throw new Refused(409, "endpoint_set: COMFYUI_URL='" + envUrl + "' overrides the config file — " +
1341
+ "every reader keys off the env while this write lands on the file, " +
1342
+ "so the door would silently change nothing. Unset COMFYUI_URL or point it at '" + url + "' first.", { state: "conflict", next_action: "endpoint_set" });
1343
+ }
1138
1344
  const dl = deadlineOf(ctx.signal, 5000, "ENDPOINT_SET_PROBE");
1139
1345
  let stats;
1140
1346
  try {
@@ -1161,14 +1367,48 @@ async function hEndpointSet(req, ctx) {
1161
1367
  throwIfAborted(ctx.signal);
1162
1368
  const cfgPath = endpointConfigPath();
1163
1369
  const cfg = { ...loadEndpointConfig() };
1370
+ // Captured BEFORE the mutation below: priorUrl must read the
1371
+ // PRE-write config url. Reading cfg["url"] after `cfg["url"] = url`
1372
+ // returns the new url twice and the old server's doc never drops
1373
+ // (found by the MP-R2 wall — the drop loop read [url, url]).
1374
+ const priorUrl = (() => {
1375
+ const raw = cfg["url"];
1376
+ return typeof raw === "string" && raw.trim() !== "" ? raw.trim().replace(/\/+$/, "") : url;
1377
+ })();
1164
1378
  cfg["url"] = url;
1165
1379
  try {
1166
- writeFileSync(cfgPath, JSON.stringify(cfg, null, 2) + "\n", "utf8");
1380
+ // J6: the endpoint config rides the atomic writer — a torn
1381
+ // comfyui_endpoint.json would brick every later config read on
1382
+ // this estate. The writer rejects with Error only (fs/promises),
1383
+ // so the Refused narrow still holds.
1384
+ await writeJsonAtomic(cfgPath, cfg);
1167
1385
  }
1168
1386
  catch (e) {
1169
- // writeFileSync throws SystemError (an Error) only — the narrow is the law.
1170
1387
  throw new Refused(500, "endpoint_set: config write failed (" + e.message + ") — the endpoint is unchanged");
1171
1388
  }
1389
+
1390
+ // server's ~3.5MB census doc forever (oiCache is unbounded) — drop
1391
+ // the pre-write config url AND the new one, so neither seat serves
1392
+
1393
+
1394
+ // abort check — the write above already landed, so an abort
1395
+ // delivered between the write and the drop still drops (the old
1396
+ // server's doc must not be served indefinitely). A write that did
1397
+ // NOT land throws above and never reaches this drop.
1398
+ for (const stale of [priorUrl, url]) {
1399
+ try {
1400
+ invalidateObjectInfo(stale);
1401
+ }
1402
+ catch (e) {
1403
+ // no endpoint configured under this spelling — no key was
1404
+ // cached under it. The LIVE key failing is different (audit
1405
+ // N-S6): the stale doc survives and the next census serves the
1406
+ // old server's node set — that failure is voiced, not folded.
1407
+ if (stale === url) {
1408
+ console.log("[estate-queue] endpoint_set: the oiCache drop failed on the LIVE key — the next census may serve the previous server's node set:", e instanceof Error ? e.message : String(e));
1409
+ }
1410
+ }
1411
+ }
1172
1412
  throwIfAborted(ctx.signal);
1173
1413
  const sys = (stats["system"] ?? {});
1174
1414
  return ok(req.action, "endpoint set to " + url + " (ComfyUI " + String(sys["comfyui_version"] ?? "?") + " answered)", { url, comfyui_version: sys["comfyui_version"] ?? null });
@@ -1281,12 +1521,18 @@ async function hSnapshotRestore(req, ctx) {
1281
1521
  guardLifecycle(req, ctx);
1282
1522
  const cfg = ctx.endpoint();
1283
1523
  estateOnly(req, cfg);
1524
+
1525
+ // call so a run pressed mid-restore refuses instead of tearing.
1526
+ const releaseLifecycle = holdLifecycle(req.action);
1284
1527
  try {
1285
1528
  await managerPost(base(ctx), "/snapshot/restore", { target: req.snapshot }, { ctx, timeoutMs: 30_000 });
1286
1529
  }
1287
1530
  catch (e) {
1288
1531
  throw mapRail(e, req.action);
1289
1532
  }
1533
+ finally {
1534
+ releaseLifecycle();
1535
+ }
1290
1536
  return ok(req.action, "restore of " + req.snapshot + " scheduled (restart required)", {
1291
1537
  state: "restart_required",
1292
1538
  restart_required: true,
@@ -1311,7 +1557,7 @@ const LORAS_DIR_UNDECLARED = 'the loras install dir is undeclared — set MELITE
1311
1557
  async function hLoraList(req, ctx) {
1312
1558
  const cfg = ctx.endpoint();
1313
1559
  estateOnly(req, cfg);
1314
- const combo = loraNamesFromObjectInfo(await objectInfoDoc(ctx));
1560
+ const combo = loraNamesFromObjectInfo(await objectInfoDoc(ctx, railMs(req)));
1315
1561
  const file = readUserLoraRows(userLorasPath());
1316
1562
  const unboarded = unboardedRows(file.rows, combo);
1317
1563
  return ok(req.action, combo.length + ' LoRA name(s) the engine accepts; ' + file.rows.length + ' user row(s) offered', {
@@ -1362,16 +1608,21 @@ async function hLoraInstall(req, ctx) {
1362
1608
  return loraInstalled(req, ctx, dir, result, 'copied');
1363
1609
  }
1364
1610
  /** THE ANSWER both arms share: the name, the bytes, whether the
1365
- * engine already lists it, and the restart it needs (core reads its
1366
- * folder list at import — a reboot is the only refresh this repo
1367
- * owns). The row suggestion rides along so the operator's next step
1368
- * is a paste, not a hunt. */
1611
+ * engine already lists it, and the restart it needs. The pinned
1612
+ * core's folder listing is mtime-live (cached_filename_list_
1613
+ * re-stats each folder per read — data/runtime/comfyui/
1614
+ * folder_paths.py:499), so a landed file shows in the next census
1615
+ * WITHOUT a reboot; the harness's own cached /object_info doc is
1616
+ * the stale layer, and the acquisition doors drop it (1a6f773c).
1617
+ * A restart stays required for custom_nodes (import-time), never
1618
+ * for a weight file. The row suggestion rides along so the
1619
+ * operator's next step is a paste, not a hunt. */
1369
1620
  async function loraInstalled(req, ctx, dir, result, verb) {
1370
1621
  // truth at answer time: the engine may have rebooted since the
1371
1622
  // cache filled (an out-of-band restart), so the combo read below
1372
1623
  // must not serve the pre-restart doc — one fresh fetch per install
1373
1624
  invalidateLiveObjectInfo(ctx);
1374
- const combo = loraNamesFromObjectInfo(await objectInfoDoc(ctx));
1625
+ const combo = loraNamesFromObjectInfo(await objectInfoDoc(ctx, railMs(req)));
1375
1626
  const visible = combo.includes(result.filename);
1376
1627
  return ok(req.action, verb + ' ' + result.filename + ' (' + result.bytes + ' bytes) into ' + dir
1377
1628
  + (visible ? ' — already in the engine\'s list' : ' — restart the engine to enter its list'), {
@@ -1400,13 +1651,32 @@ async function loraInstalled(req, ctx, dir, result, verb) {
1400
1651
  * is unreachable. It is the doc (not one node) because the reader
1401
1652
  * that turns it into the LoRA list is the reader's own job, and a
1402
1653
  * per-node hop here would make the two spellings drift. */
1403
- async function objectInfoDoc(ctx) {
1654
+ async function objectInfoDoc(ctx, boundMs) {
1655
+
1656
+
1657
+ // same railMs bound every other manage hop rides. The deadline
1658
+ // refusal is LOUD — a hung engine refuses the door (504), it
1659
+ // never reads as an empty lora combo; only an engine that cannot
1660
+ // be reached at all folds to the null-doc contract.
1661
+ throwIfAborted(ctx.signal);
1662
+ if (ctx.objectInfo !== undefined) {
1663
+ try {
1664
+ return await ctx.objectInfo();
1665
+ }
1666
+ catch {
1667
+ return null;
1668
+ }
1669
+ }
1404
1670
  try {
1405
- return ctx.objectInfo !== undefined
1406
- ? await ctx.objectInfo()
1407
- : await liveObjectInfo(resolveEngineBaseUrl());
1671
+ return await liveObjectInfo(resolveEngineBaseUrl(), ctx.signal, boundMs);
1408
1672
  }
1409
- catch {
1673
+ catch (error) {
1674
+ // only the deadline goes loud; an unreachable or endpoint-less
1675
+ // engine keeps the settled null-doc contract (not-visible), and
1676
+ // an aborted door needs no refusal past its own teardown
1677
+ if (error instanceof ComfyError && error.code === 'deadline') {
1678
+ throw new Refused(504, error.message);
1679
+ }
1410
1680
  return null;
1411
1681
  }
1412
1682
  }
@@ -1414,7 +1684,12 @@ async function objectInfoDoc(ctx) {
1414
1684
  * process serves — the same key objectInfoDoc's live arm reads.
1415
1685
  * A ctx carrying its own objectInfo seam never touches the global
1416
1686
  * cache, so there is nothing to drop; and an endpoint-less
1417
- * resolveEngineBaseUrl refusal means no key was ever cached. */
1687
+ * resolveEngineBaseUrl refusal means no key was ever cached.
1688
+ * KEY LAW: the drop keys off resolveEngineBaseUrl() (env/config),
1689
+ * never ctx.endpoint() — matching the reader. A lane seating a
1690
+ * ctx.endpoint() that differs from the resolved base must point
1691
+ * COMFYUI_URL at the same server, or the drop lands on a key no
1692
+ * census reads and the stale doc survives. */
1418
1693
  function invalidateLiveObjectInfo(ctx) {
1419
1694
  if (ctx.objectInfo !== undefined)
1420
1695
  return;