@melite/estate-queue 0.1.5-pre-alpha → 0.2.0-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 (61) hide show
  1. package/LICENSE +561 -457
  2. package/lib/cardsArmError.d.ts +52 -3
  3. package/lib/cardsArmError.js +7 -1
  4. package/lib/cardsCompose.js +43 -7
  5. package/lib/cardsFacts.d.ts +16 -0
  6. package/lib/cardsFacts.js +25 -1
  7. package/lib/cardsLanes.d.ts +51 -3
  8. package/lib/cardsLanes.js +337 -13
  9. package/lib/cardsLanesCopy.d.ts +21 -0
  10. package/lib/cardsLanesCopy.js +22 -0
  11. package/lib/cardsRegistry.d.ts +102 -5
  12. package/lib/cardsRegistry.js +668 -45
  13. package/lib/cardsVariant.d.ts +12 -7
  14. package/lib/cardsVariant.js +196 -58
  15. package/lib/discloseRegistry.d.ts +36 -6
  16. package/lib/discloseRegistry.js +153 -15
  17. package/lib/filmLead.js +5 -3
  18. package/lib/flowsData.d.ts +1 -1
  19. package/lib/flowsData.js +7 -4
  20. package/lib/flowsFamilyCompose.js +12 -1
  21. package/lib/flowsRegistryRows.d.ts +1 -0
  22. package/lib/flowsRegistryRows.js +193 -35
  23. package/lib/index.d.ts +1 -0
  24. package/lib/index.js +6 -0
  25. package/lib/loadPlane.js +9 -0
  26. package/lib/manageOps.js +2 -1
  27. package/lib/managePlane.d.ts +11 -1
  28. package/lib/managePlane.js +559 -24
  29. package/lib/managePreflight.d.ts +26 -0
  30. package/lib/managePreflight.js +179 -0
  31. package/lib/manageProbe.d.ts +17 -0
  32. package/lib/manageProbe.js +61 -1
  33. package/lib/queueCore.d.ts +14 -1
  34. package/lib/queueCore.js +13 -0
  35. package/lib/queueResurrect.d.ts +7 -2
  36. package/lib/queueResurrect.js +25 -6
  37. package/lib/queueSidecar.d.ts +110 -1
  38. package/lib/queueSidecar.js +177 -7
  39. package/lib/queueSubmit.d.ts +67 -4
  40. package/lib/queueSubmit.js +133 -4
  41. package/lib/runsErrorCodes.js +5 -3
  42. package/lib/runsExecute.js +44 -4
  43. package/lib/runsGates.d.ts +5 -1
  44. package/lib/runsGates.js +6 -2
  45. package/lib/runsList.d.ts +43 -3
  46. package/lib/runsList.js +159 -39
  47. package/lib/runsRefusalVoices.js +50 -1
  48. package/lib/runsRegistry.d.ts +84 -6
  49. package/lib/runsRegistry.js +515 -105
  50. package/lib/runsStart.d.ts +24 -3
  51. package/lib/runsStart.js +128 -13
  52. package/lib/runsTypes.d.ts +27 -2
  53. package/lib/runsTypes.js +23 -6
  54. package/lib/runsValidateServe.js +20 -10
  55. package/lib/runsValidateShared.d.ts +9 -0
  56. package/lib/runsValidateShared.js +14 -0
  57. package/lib/runsValidateStages.js +21 -9
  58. package/lib/runtimeProvision.d.ts +119 -0
  59. package/lib/runtimeProvision.js +243 -0
  60. package/lib/skillRows.js +7 -2
  61. package/package.json +18 -18
@@ -13,18 +13,21 @@
13
13
  import { execFile } from "node:child_process";
14
14
  import { promisify } from "node:util";
15
15
  import { readFileSync } from "node:fs";
16
- import { join } from "node:path";
16
+ import { dirname, join } from "node:path";
17
+ import { resolveRuntimeProvision, nodeRuntimeFs, runtimeEnvView, engineOutputDir, engineRootOf, sentinelHit } from "./runtimeProvision.js";
17
18
  import { ComfyError, endpointConfigPath, invalidateObjectInfo, liveObjectInfo, loadEndpointConfig, resolveEngineBaseUrl, } from "@melite/comfyui-cordis";
18
19
  import { writeJsonAtomic } from "./queueLock.js";
19
- import { installUserLora, installUserLoraBytes, loraNamesFromObjectInfo, readUserLoraRows, resolveEngineLorasDir, unboardedRows, userLorasPath, } from "@melite/comfyui-cordis/user-loras";
20
- import { AcquireBusyError } from "@melite/estate-provisioning";
20
+ import { installUserLora, installUserLoraBytes, loraNamesFromObjectInfo, readUserLoraRows, refmodNamesFromObjectInfo, resolveEngineLorasDir, unboardedRows, userLorasPath, validateUserLoraRow, } from "@melite/comfyui-cordis/user-loras";
21
+ import { AcquireBusyError, LIVE_ACQUIRE_STATES } from "@melite/estate-provisioning";
21
22
  import { ManagerApiError, managerGet, managerPost, planeUnavailable } from "./managerRail.js";
22
- import { probeEndpoint, activeRuns, managerSecurity, engineQueueView } from "./manageProbe.js";
23
+ import { probeEndpoint, activeRuns, managerSecurity, engineQueueView, settleStaleClaims } from "./manageProbe.js";
24
+ import { runPreflight, preflightLine } from "./managePreflight.js";
23
25
  import { base, mapManagerRefused, mapRail, railMs, estateOnly, awaitQueueDrained, systemctl, guardLifecycle } from "./manageOps.js";
24
26
  import { holdLifecycle } from "./lifecycleLatch.js";
25
27
  import { deadline as deadlineOf, timeoutOf } from "@deepseek-ai/dsh-timeout";
26
28
  import { segmentConfined } from "@melite/contracts/mediaKinds";
27
29
  import { artifactFileName } from "@melite/contracts/benchResult";
30
+ import { cellArtifactCoordinates } from "@melite/contracts/laneRelations";
28
31
  const execFileAsync = promisify(execFile);
29
32
  // ── SSOT vocabulary ─────────────────────────────────────────────────
30
33
  // Closed vocabulary — a typo is a 422, not a silent miss.
@@ -40,16 +43,65 @@ export const ACTIONS = [
40
43
  "download_model",
41
44
  "provision_model",
42
45
  "acquire_weight",
46
+
47
+ // the run-rescue runtime banner fires — links the engine tree's
48
+ // data/runtime/<name> to the repo's healthy seed (SYMLINK, never a
49
+ // copy). Decided by the same core the press-time gate reads
50
+ // (runtimeProvision.ts): gate and verb can never disagree.
51
+ "provision_runtime",
52
+ // THE RESCUE VERBS (ERRORS.md k2 + the purge plan's P5 rescue
53
+ // honesty): a settled-failed acquire is retryable — a fresh fetch
54
+ // on the dead row's ref, the dead row's truth kept — and the dead
55
+ // row is discardable — evicted, so a later poll 404s. The k2 burn's
56
+ // own words, "no retry, no delete, just stuck", die here.
57
+ "acquire_retry",
58
+ "acquire_discard",
43
59
  "restart",
44
60
  "stop",
45
61
  "launch",
46
62
  "update",
47
63
  "switch_version",
48
64
  "free",
65
+
66
+ // sidecars from before a rebuild. The lifecycle guard is sync and
67
+ // fail-closed — it cannot consult the engine — so the historical
68
+ // claims it refuses on are retired by explicit operator gesture,
69
+ // never by the guard looking away.
70
+ "settle_stale",
49
71
  "snapshot_save",
50
72
  "snapshot_restore",
51
73
  "lora_list",
52
74
  "lora_install",
75
+
76
+ // LORA-FROM-URL burn, ROADMAP line 7892: "Can you add this lora
77
+ // to krea 2" + a HuggingFace URL is the ONE download an operator
78
+ // actually does, and nothing served it — the session fell to raw
79
+ // bash archaeology against the no-loras-remote rule). THE
80
+ // AMENDED LAW, voiced here where the verb lives: the rule is
81
+ // amended, NOT deleted — no SILENT remote fetch; a stated URL
82
+ // rides the provisioning service (download_model's own stack:
83
+ // range resume, kept parts, live ledger, honest voices) behind
84
+ // the human's operator_confirmed gate, lands under the FAMILY
85
+ // subfolder the engine already serves (loras/<family>/<file> —
86
+ // the combo lists '<family>/<file>'), and the landing drops the
87
+ // estate's cached /object_info doc so the next lora_list re-asks.
88
+ // download_model's own loras refusal STAYS (its comment names
89
+ // this verb as the supersession). Recipe: add a lora to <family>:
90
+ // lora_fetch url → auto restart → the mod appears in the family's
91
+ // mods.
92
+ "lora_fetch",
93
+
94
+ // square): the H3 refmods loader's own mod_N combo, read off the
95
+ // same cached /object_info doc lora_list rides — the stems, sorted.
96
+ "refmods_list",
97
+
98
+ // every setup miss (engine reachable? Manager present? required
99
+ // declared packs landed? store root on disk? wiring visible?) —
100
+ // each miss names its door, instead of null presence + mid-run
101
+ // burns. A READ on any posture (BYO is its primary audience — no
102
+ // estateOnly); a probe that throws is a named miss, so the answer
103
+ // can never degrade to all-green over an unchecked axis.
104
+ "preflight",
53
105
  ];
54
106
  /** The status reconcile bound (the wall law — see hStatus): status
55
107
  * answers inside the plane's 5s wall; the digest-verifying
@@ -186,6 +238,7 @@ export function parseReq(doc) {
186
238
  model: str("model"),
187
239
  variant: str("variant"),
188
240
  quant: str("quant"),
241
+ runtime: str("runtime"),
189
242
  tail: num("tail", 200),
190
243
  query: str("query"),
191
244
  version: str("version"),
@@ -207,6 +260,8 @@ export function parseReq(doc) {
207
260
  filename: str("filename") || str("file"),
208
261
  families: Array.isArray(d["families"]) ? d["families"].map(String).filter((s) => s !== "") : [],
209
262
  operation_id: str("operation_id"),
263
+ // THE LORA-FETCH VERIFY (see Req.sha256)
264
+ sha256: str("sha256"),
210
265
  };
211
266
  }
212
267
  function need(req, ...fields) {
@@ -461,7 +516,7 @@ async function hStatus(req, ctx) {
461
516
  const engineIdle = engineQueue !== null && engineQueue.running === 0 && engineQueue.pending === 0;
462
517
  const activeView = engineIdle ? [] : active;
463
518
  const staleClaims = engineIdle
464
- ? active.map((name) => name + " (claimed live; engine queue empty — historical: the sidecar never settled; the boot sweep retires its own root at restart)")
519
+ ? active.map((name) => name + " (claimed live; engine queue empty — historical: the sidecar never settled; retire it with the settle_stale action)")
465
520
  : [];
466
521
  const routing = { mode: cfg["provision"] === "managed" ? "managed" : "byo" };
467
522
  let manager = {};
@@ -523,6 +578,18 @@ async function hStatus(req, ctx) {
523
578
  ...resource,
524
579
  ...(resource.operationId === undefined ? {} : { operation_id: resource.operationId }),
525
580
  }));
581
+
582
+ // status budget cannot sha256-census a healthy estate, and the
583
+ // truncated list served as the whole "Declared resources" truth —
584
+ // "1/1 failed" over files that sat byte-exact on disk). Any
585
+ // 'unknown' ROW is the scan's own artifact — and so is any
586
+ // 'unknown' ITEM (audit F1: a failed item over unchecked siblings
587
+ // aggregates the row to 'failed', a real verdict that must stand,
588
+ // but the partial mark must still fire or the sidebar titles a
589
+ // partial scan as the whole truth). The mark derives from both
590
+ // levels: row OR item unknown.
591
+ const censusPartial = resourceRows.some((row) => row.state === "unknown")
592
+ || resourceRows.some((row) => (row.items ?? []).some((item) => item.state === "unknown"));
526
593
  const state = endpoint.reachable ? "up" : "down";
527
594
  const nextAction = nextActionFor(endpoint.reachable, normalized, routing.mode === "managed");
528
595
  const catalog = modelOptions(ctx.models);
@@ -550,6 +617,7 @@ async function hStatus(req, ctx) {
550
617
  routing,
551
618
  auto_provision: ctx.autoProvision,
552
619
  resources: resourceRows,
620
+ ...(censusPartial ? { census_partial: true } : {}),
553
621
  operations,
554
622
  ...(resourcesDetail === undefined ? {} : { resources_detail: resourcesDetail }),
555
623
  };
@@ -578,7 +646,12 @@ async function hLogs(req, ctx) {
578
646
  return ok(req.action, lines.length + " log line(s) from " + ctx.comfyUnit, lines);
579
647
  }
580
648
  async function hSearch(req, ctx) {
581
- need(req, "query");
649
+
650
+
651
+ // exploring the catalog hit a refusal instead of the roster. An
652
+ // omitted or empty query lists the whole cache (capped); a carried
653
+ // query filters it. The filter syntax rides the unfiltered detail
654
+ // so the agent learns it from the answer itself.
582
655
  const cfg = ctx.endpoint();
583
656
  estateOnly(req, cfg);
584
657
  let doc;
@@ -589,12 +662,18 @@ async function hSearch(req, ctx) {
589
662
  throw mapRail(e, req.action);
590
663
  }
591
664
  const models = doc["models"] ?? [];
592
- const q = req.query.toLowerCase();
665
+ const raw = typeof req.query === "string" ? req.query : "";
666
+ const q = raw.toLowerCase();
593
667
  const hits = models.filter((m) => {
668
+ if (q === "")
669
+ return true;
594
670
  const hay = [m["name"], m["type"], m["base"], m["filename"]].map((v) => String(v ?? "").toLowerCase()).join(" ");
595
671
  return hay.includes(q);
596
672
  }).slice(0, 50);
597
- return ok(req.action, hits.length + " hit(s) from Manager external catalog for '" + req.query + "'", hits);
673
+ const detail = q === ""
674
+ ? hits.length + " model(s) in the Manager external catalog (no filter — pass query to narrow: it case-folds over name/type/base/filename)"
675
+ : hits.length + " hit(s) from Manager external catalog for '" + req.query + "'";
676
+ return ok(req.action, detail, hits);
598
677
  }
599
678
  async function withManageTimeout(req, ctx, work, boundMs = railMs(req)) {
600
679
  throwIfAborted(ctx.signal);
@@ -638,13 +717,16 @@ function externalModelPath(req) {
638
717
  if (folder.includes("..") || folder.startsWith("/")) {
639
718
  throw badRequest("relative_path must stay under the models root: " + req.relative_path);
640
719
  }
641
- // THE NO-LORAS-REMOTE LAW, enforced at the one fetch door: the
642
- // operator's rule ("THERE SHOULD NOT BE A LORAS REMOTE / IT'S
643
- // ALL BUILT IN") — a LoRA arrives by COPY through lora_install
644
- // or the user rows file, never by url. Before this arm the door
645
- // could fetch into models/loras and contradict the stated law.
720
+
721
+ // ROADMAP line 7892): the rule is amended, not deleted — no
722
+ // SILENT remote fetch; a stated URL now rides its OWN verb,
723
+ // lora_fetch (the provisioning service's full progress face,
724
+ // family subfolder, operator_confirmed gate). THIS door keeps
725
+ // its refusal: the generic model fetch never writes the loras
726
+ // dir — that is the lora verb's ground, and a checkpoint URL
727
+ // has no business masquerading as a LoRA.
646
728
  if (folder === "loras" || folder.startsWith("loras/")) {
647
- throw badRequest("download_model refuses the loras dir — LoRAs arrive by copy or upload (lora_install), never by url");
729
+ throw badRequest("download_model refuses the loras dir — a LoRA URL rides the lora_fetch verb (operator order 2026-11-09: the provisioning service lands it under the family's loras subfolder); this generic model door never writes loras");
648
730
  }
649
731
 
650
732
  // rides the SSOT the cell artifacts ride — a URL's query and
@@ -943,6 +1025,141 @@ async function hDownloadModel(req, ctx) {
943
1025
  ctx.rearmWeights?.();
944
1026
  return provisionEnvelope(req.action, result);
945
1027
  }
1028
+
1029
+
1030
+
1031
+
1032
+
1033
+
1034
+
1035
+
1036
+
1037
+
1038
+
1039
+
1040
+
1041
+
1042
+ async function hLoraFetch(req, ctx) {
1043
+ need(req, "url");
1044
+ estateOnly(req, ctx.endpoint());
1045
+ // ONE family — the subfolder the file lands under; the combo
1046
+ // name is '<family>/<filename>' and the mods plane scopes the
1047
+ // offer by it
1048
+ if (req.families.length !== 1) {
1049
+ throw badRequest("lora_fetch requires exactly one family (the loras subfolder the engine serves the file under) — families: [\"<family-id>\"]");
1050
+ }
1051
+ const family = req.families[0];
1052
+ if (family.includes("/") || !segmentConfined(family)) {
1053
+ throw badRequest("family must be one safe path segment under the loras root: " + family);
1054
+ }
1055
+ // THE C5 FILENAME LAW (the download_model door's own SSOT): the
1056
+ // URL's query/fragment never names the file
1057
+ const filename = req.filename !== "" ? req.filename : artifactFileName(req.url);
1058
+ if (filename.includes("/") || !segmentConfined(filename)) {
1059
+ throw badRequest("filename must be a bare name under the loras root");
1060
+ }
1061
+ // THE ROW GRAMMAR OWNS WHAT A LORA FILE IS (one spelling with
1062
+ // the user rows: the same extension judge the picker's rows
1063
+ // serve — probe rides validateUserLoraRow and reads only its
1064
+ // problem)
1065
+ const probe = validateUserLoraRow({ id: "probe", filename: family + "/" + filename, families: [family] }, 0);
1066
+ if (probe.problem !== undefined)
1067
+ throw badRequest("lora_fetch: " + probe.problem);
1068
+ // THE SEAT ASKS FIRST (the hProvisionModel order law), then the
1069
+ // gate below the shape guards: a request refused on its own
1070
+ // merits never needs the human's flag
1071
+ const provisioner = provisioningOf(ctx);
1072
+ const confirmed = operatorConfirmGate(req, "lora_fetch");
1073
+ if (confirmed !== null)
1074
+ return confirmed;
1075
+ const result = await withManageTimeout(req, ctx, (signal) => provisioner.acquireExternal({
1076
+ kind: "model",
1077
+ url: req.url,
1078
+ relativePath: "loras/" + family,
1079
+ filename,
1080
+ ...(req.sha256 === "" ? {} : { sha256: req.sha256 }),
1081
+ }, { operatorConfirmed: req.operator_confirmed }, signal));
1082
+ // THE UNCONDITIONAL DROP (the download_model law this verb
1083
+ // rides): the boot-time /object_info memo must not outlive a
1084
+ // landed file — the next lora_list (and the next form-spec
1085
+ // serve) re-asks, and the engine's mtime-based folder scan
1086
+ // serves the new name. ZERO restarts estate-side; the engine
1087
+ // reboot below is a separate, voiced concern.
1088
+ invalidateLiveObjectInfo(ctx);
1089
+ ctx.rearmWeights?.();
1090
+ const comboName = family + "/" + filename;
1091
+ // THE COMBO ASK, PRE-RESTART: a modern core re-scans the loras
1092
+ // folder per read, so the name may already serve; an unreachable
1093
+ // engine proves nothing (the null-doc contract) and refuses
1094
+ // nothing — the deadline refusal is folded by the same honesty.
1095
+ let inComboNow = false;
1096
+ try {
1097
+ inComboNow = loraNamesFromObjectInfo(await objectInfoDoc(ctx, railMs(req))).includes(comboName);
1098
+ }
1099
+ catch {
1100
+ inComboNow = false;
1101
+ }
1102
+ // THE RESTART CHAIN (the operator's design: the Manager reloads
1103
+ // ComfyUI). The chain rides the guarded restart door; ANY fold —
1104
+ // the guard's 409 (runs live), a rail error, a dead engine —
1105
+ // leaves the fetch ok and voices the owed restart.
1106
+ let restartVoice;
1107
+ try {
1108
+ await hRestart({ ...req, action: "restart" }, ctx);
1109
+ restartVoice = {
1110
+ restart_required: false,
1111
+ next_action: "status",
1112
+ note: "engine restart issued (the Manager reloads ComfyUI)",
1113
+ };
1114
+ }
1115
+ catch (e) {
1116
+ const why = e instanceof Refused ? e.message : e instanceof Error ? e.message : String(e);
1117
+ restartVoice = {
1118
+ restart_required: true,
1119
+ next_action: "restart",
1120
+ note: "the lora LANDED; the engine restart is owed and did not fire: " + why,
1121
+ };
1122
+ }
1123
+ const detail = comboName + " landed for " + family + " — " + restartVoice.note +
1124
+ (inComboNow ? " (already in the engine's combo)" : " (not yet in the engine's combo read)");
1125
+ const first = result.items[0];
1126
+ const data = {
1127
+ family,
1128
+ filename: comboName,
1129
+ url: req.url,
1130
+ operation_id: result.operationId,
1131
+ state: result.state,
1132
+ ...(first?.path !== undefined ? { path: first.path } : {}),
1133
+ in_combo_now: inComboNow,
1134
+ restart_required: restartVoice.restart_required,
1135
+ next_action: restartVoice.next_action,
1136
+ // THE ROW SUGGESTION (the lora_install door's pattern): paste
1137
+ // this into the family's user rows (or the DECL) and the
1138
+ // picker's id-pick composes; the engine name serves as the
1139
+ // candidate either way (the mods union)
1140
+ row_suggestion: {
1141
+ id: comboName,
1142
+ filename: comboName,
1143
+ families: [family],
1144
+ source_url: req.url,
1145
+ label: filename.replace(/\.[^.]+$/, ""),
1146
+ },
1147
+ };
1148
+ return [
1149
+ 200,
1150
+ {
1151
+ action: req.action,
1152
+ ok: true,
1153
+ detail,
1154
+ status: 200,
1155
+ state: result.state,
1156
+ next_action: restartVoice.next_action,
1157
+ operation_id: result.operationId,
1158
+ restart_required: restartVoice.restart_required,
1159
+ data,
1160
+ },
1161
+ ];
1162
+ }
946
1163
  function familyModelDeclared(ctx, id) {
947
1164
  return ctx.models.allDecls().some((decl) => decl.id === id || decl.variants.some((variant) => variant.route === id || variant.cells.some((cell) => cell.route === id)));
948
1165
  }
@@ -1017,6 +1234,83 @@ async function hProvisionModel(req, ctx) {
1017
1234
  }, [operationRow(req.model, result, ref, plan)]);
1018
1235
  });
1019
1236
  }
1237
+
1238
+
1239
+
1240
+
1241
+
1242
+
1243
+
1244
+
1245
+
1246
+
1247
+
1248
+
1249
+ async function hProvisionRuntime(req, ctx) {
1250
+ need(req, "runtime");
1251
+ estateOnly(req, ctx.endpoint());
1252
+ const decls = ctx.models.allDecls();
1253
+ const rt = decls.map((d) => d.runtime).find((r) => r !== undefined && r.name === req.runtime);
1254
+ if (rt === undefined) {
1255
+ const declared = [...new Set(decls.map((d) => d.runtime?.name).filter((n) => n !== undefined))];
1256
+ throw badRequest("unknown runtime '" + req.runtime + "' — no family DECL declares a runtime by this name (declared runtimes: " +
1257
+ (declared.length === 0 ? "none" : declared.join(", ")) + ")");
1258
+ }
1259
+ const root = engineRootOf();
1260
+ const decision = resolveRuntimeProvision(rt, {
1261
+ engineRoot: root,
1262
+ walkStart: root === null ? "" : engineOutputDir(root),
1263
+ env: runtimeEnvView(rt.env),
1264
+ repoSeedHome: join(ctx.repoRoot, "data", "runtime", rt.name),
1265
+ fs: nodeRuntimeFs,
1266
+ });
1267
+ if (decision.kind === "refused") {
1268
+ throw new Refused(decision.reason === "no-engine-root" || decision.reason === "env-invalid" ? 422 : 409, decision.detail, { kind: decision.reason, runtime: rt.name });
1269
+ }
1270
+ if (decision.kind === "linkable") {
1271
+ nodeRuntimeFs.mkdir(dirname(decision.target));
1272
+ nodeRuntimeFs.symlink(decision.seed, decision.target);
1273
+ // THE THROUGH-THE-LINK VERIFY (the operator's own gate): the
1274
+ // sentinels are re-read THROUGH the new link — a link that does
1275
+ // not resolve is a loud refusal, never a success envelope.
1276
+ const verified = rt.sentinel.filter((s) => sentinelHit(decision.target, s));
1277
+ if (verified.length !== rt.sentinel.length) {
1278
+ throw new Refused(500, "provision_runtime: the link " + decision.target + " → " + decision.seed +
1279
+ " landed but does not resolve every sentinel (" + rt.sentinel.join(", ") +
1280
+ ") — remove the link by hand and press again", { kind: "broken-seed", runtime: rt.name });
1281
+ }
1282
+ return ok(req.action, "provision_runtime " + rt.name + ": linked " + decision.target + " → " + decision.seed +
1283
+ " (symlink — the engine tree holds a link, the repo seed stays the source of truth); sentinels verified through the link: " +
1284
+ verified.join(", "), {
1285
+ runtime: rt.name,
1286
+ state: "active",
1287
+ provisioned: true,
1288
+ strategy: "symlink",
1289
+ link: { seed: decision.seed, target: decision.target },
1290
+ sentinels_verified: [...verified],
1291
+ restart_required: false,
1292
+ next_action: "status",
1293
+ });
1294
+ }
1295
+ // THE ALREADY-PRESENT RECEIPT names where the runtime stood, and —
1296
+ // for a lanes.env-sourced value — states the engine-visibility
1297
+
1298
+ // file: the lane process may predate the edit; a restart arms it).
1299
+ const presentClause = decision.source === "lanes.env"
1300
+ ? " — value read from the endpoint's lanes_env_file; this assumes the engine's lane reads the same file (EnvironmentFile), so restart the lane to arm a fresh edit"
1301
+ : decision.source === "walk-up"
1302
+ ? " (walk-up from the engine's own output)"
1303
+ : "";
1304
+ return ok(req.action, "provision_runtime " + rt.name + ": already present at " + decision.home + " (" + decision.source + ")" + presentClause, {
1305
+ runtime: rt.name,
1306
+ state: "active",
1307
+ provisioned: false,
1308
+ home: decision.home,
1309
+ source: decision.source,
1310
+ restart_required: false,
1311
+ next_action: "status",
1312
+ });
1313
+ }
1020
1314
  /** THE F9 ACQUISITION DOOR (run-press acquisition — ONE door, TWO
1021
1315
  * callers): the bench popup's Download button and the agent's
1022
1316
  * comfy_manage acquire_weight seat both land here. It starts the
@@ -1029,12 +1323,17 @@ async function hAcquireWeight(req, ctx) {
1029
1323
  const provisioner = provisioningOf(ctx);
1030
1324
  // THE POLL (the tracker's read): same action, operation id only —
1031
1325
  // no model, no fetch, no wait. Unknown ids 404 (never a fake
1032
- // zero — the tracker must render the truth).
1326
+ // zero — the tracker must render the truth). The cross-process
1327
+
1328
+ // the SHARED STORE — the transient seat's poll sees the durable
1329
+ // seat's states without sharing its memory.
1033
1330
  if (req.operation_id !== "") {
1034
1331
  if (typeof provisioner.progressOf !== "function") {
1035
1332
  throw unavailable("acquire_weight progress is not configured on this lane");
1036
1333
  }
1037
- const progress = provisioner.progressOf(req.operation_id);
1334
+ const progress = typeof provisioner.readProgress === "function"
1335
+ ? await provisioner.readProgress(req.operation_id)
1336
+ : provisioner.progressOf(req.operation_id);
1038
1337
  if (progress === null || progress === undefined) {
1039
1338
  throw notFound("unknown acquire_weight operation: " + req.operation_id);
1040
1339
  }
@@ -1050,13 +1349,19 @@ async function hAcquireWeight(req, ctx) {
1050
1349
  ctx.rearmWeights?.();
1051
1350
  }
1052
1351
  return ok(req.action, "acquire_weight " + progress.operationId + ": " + String(progress.bytes) + "/" + String(progress.total)
1053
- + " bytes (" + progress.state + ")", {
1352
+ + " bytes (" + progress.state
1353
+ // THE LIVE-PHASE VOICE (audit F2): a frozen byte count with a
1354
+ // live phase names it (verifying:verify) — the popup's only
1355
+ // liveness window rides this text. Phaseless rows keep the
1356
+ // old shape.
1357
+ + (progress.phase === undefined ? "" : ":" + progress.phase) + ")", {
1054
1358
  operation_id: progress.operationId,
1055
1359
  state: progress.state,
1056
1360
  bytes: progress.bytes,
1057
1361
  total: progress.total,
1058
1362
  next_action: "acquire_weight",
1059
1363
  ...(progress.detail === undefined ? {} : { detail: progress.detail }),
1364
+ ...(progress.phase === undefined ? {} : { phase: progress.phase }),
1060
1365
  });
1061
1366
  }
1062
1367
  // THE START (the Download press): model required, the missing file
@@ -1112,13 +1417,41 @@ async function hAcquireWeight(req, ctx) {
1112
1417
 
1113
1418
  // downloads every row of a multi-GB family. The name maps to plan
1114
1419
  // 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.
1420
+ // keys them (extension → id, else name — the snapshot channel
1421
+ // keys its trees by name, the row the missing-file refusal
1422
+ // voices); an unknown filename is the item-not-found refusal,
1423
+ // never a whole-family fetch.
1117
1424
  let acquireOptions;
1118
1425
  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));
1426
+ const itemsNamed = (p) => p.items
1427
+ .filter((item) => (item.kind === "extension" ? item.id : item.name) === req.filename)
1428
+ .map((item) => (item.kind === "extension" ? item.id : item.name));
1429
+ let wanted = itemsNamed(plan);
1430
+
1431
+ // a filename of a NON-default lane's cell artifact matched no item —
1432
+ // the family plan resolves ONE coordinate (the stated one, else the
1433
+ // family default), so every kroma weight refused item-not-found at
1434
+ // the ONE download door while the refusal's own anchor spoke the
1435
+ // URL ("they didn't get the URLs"). Derive the file's own
1436
+ // (variant, quant) from the DECL's cell artifacts and re-plan at
1437
+ // that coordinate — the DECL owns the fetch source (the names-only
1438
+ // law), the re-plan carries exactly the named row, and the
1439
+ // coordinate-scoped key (T-S4) keeps the dedupe honest.
1440
+ if (wanted.length === 0 && ref.kind === "model" && ref.owner === "family") {
1441
+ const decl = ctx.models.allDecls().find((d) => d.id === ref.id);
1442
+ const coords = decl === undefined
1443
+ ? null
1444
+ : cellArtifactCoordinates(decl.variants ?? [], req.filename);
1445
+ if (coords !== null && coords.variant !== "") {
1446
+ ref = {
1447
+ ...ref,
1448
+ variant: coords.variant,
1449
+ ...(coords.quant !== "" ? { quant: coords.quant } : {}),
1450
+ };
1451
+ plan = await withManageTimeout(req, ctx, async () => await provisioner.plan(ref));
1452
+ wanted = itemsNamed(plan);
1453
+ }
1454
+ }
1122
1455
  if (wanted.length === 0) {
1123
1456
  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
1457
  }
@@ -1126,10 +1459,23 @@ async function hAcquireWeight(req, ctx) {
1126
1459
  }
1127
1460
  // THE BUSY MAP (audit I-S4): a plane at its concurrency cap is a
1128
1461
  // wait, not a failure — the 429 carries retry_after_ms and points
1129
- // the caller back at the poll arm
1462
+ // the caller back at the poll arm.
1463
+
1464
+ // starts the fetch HERE (the GUI press, the lane's own lifetime);
1465
+ // a transient seat (an agent session) QUEUES — but ONLY while a
1466
+ // FRESH claimer heartbeat from another seat answers on the shared
1467
+ // store (the dead-queue impossibility: no live claimer, no queue —
1468
+ // the press takes the wire itself). The queue arm never takes a
1469
+ // concurrency slot and never throws busy.
1470
+ const queueReady = provisioner.durableDownloads?.() !== true
1471
+ && provisioner.requestWeightAcquire !== undefined
1472
+ && (await provisioner.durableClaimerLive?.()) === true;
1473
+ const requestAcquire = queueReady ? provisioner.requestWeightAcquire : undefined;
1130
1474
  let operationId;
1131
1475
  try {
1132
- operationId = await withManageTimeout(req, ctx, async () => await startAcquire.call(provisioner, ref, acquireOptions));
1476
+ operationId = await withManageTimeout(req, ctx, async () => requestAcquire !== undefined
1477
+ ? await requestAcquire.call(provisioner, ref)
1478
+ : await startAcquire.call(provisioner, ref, acquireOptions));
1133
1479
  }
1134
1480
  catch (error) {
1135
1481
  if (error instanceof AcquireBusyError) {
@@ -1150,6 +1496,20 @@ async function hAcquireWeight(req, ctx) {
1150
1496
  const total = progress?.total ?? 0;
1151
1497
  const state = progress?.state ?? "acquiring";
1152
1498
  const file = req.filename !== "" ? " (" + req.filename + ")" : "";
1499
+
1500
+ // acquiring text — the operator/agent reads WHERE the fetch runs
1501
+ // (the durable lane seat), never a started-here lie.
1502
+ if (state === "requested") {
1503
+ return ok(req.action, "queued " + req.model + file + " for the durable lane seat — the fetch starts there, never in this session (poll acquire_weight operation_id=" + operationId + ")", {
1504
+ operation_id: operationId,
1505
+ operationId,
1506
+ state,
1507
+ bytes,
1508
+ total,
1509
+ model: req.model,
1510
+ next_action: "acquire_weight",
1511
+ });
1512
+ }
1153
1513
  return ok(req.action, "acquiring " + req.model + file + " — " + String(bytes) + "/" + String(total)
1154
1514
  + " bytes (poll acquire_weight operation_id=" + operationId + ")", {
1155
1515
  operation_id: operationId,
@@ -1162,6 +1522,105 @@ async function hAcquireWeight(req, ctx) {
1162
1522
  ...(req.variant === "" ? {} : { variant: req.variant }),
1163
1523
  ...(req.quant === "" ? {} : { quant: req.quant }),
1164
1524
  next_action: "acquire_weight",
1525
+ // the start answers the opening phase with the row (the face's
1526
+ // first paint already names the re-check, never a phaseless 0)
1527
+ ...(progress?.phase === undefined ? {} : { phase: progress.phase }),
1528
+ });
1529
+ }
1530
+ // ── THE RESCUE VERBS (k2: "no retry, no delete, just stuck") ────────
1531
+ // The acquire door's own ledger judges both: a row whose fetch
1532
+ // stopped progressing (the service's stall budget settles it FAILED)
1533
+ // must leave the operator one press to re-fetch and one press to
1534
+ // clear the wedge.
1535
+ /** The shared live-refusal for both rescue verbs: a settled operation
1536
+ * passes; a live one (the provisioning contract's LIVE_ACQUIRE_STATES
1537
+ * — one spelling with the run gate's in-flight voice) answers 409
1538
+ * pointing back at the poll.
1539
+ * @param req the verb's request (names the verb in the voice).
1540
+ * @param progress the polled ledger row.
1541
+ * @returns void.
1542
+ * @throws Refused 409 when the row is still in flight. */
1543
+ function settledAcquireOrRefuse(req, progress) {
1544
+ if (LIVE_ACQUIRE_STATES.has(progress.state)) {
1545
+ throw new Refused(409, "acquire_weight " + progress.operationId + " is still in flight (" + progress.state + ", "
1546
+ + String(progress.bytes) + "/" + String(progress.total) + " bytes) — poll acquire_weight operation_id="
1547
+ + progress.operationId + "; " + req.action + " is for a settled operation");
1548
+ }
1549
+ }
1550
+ /** acquire_retry — a fresh fetch on a settled-failed row's ref. The
1551
+ * dead row's truth stays (the face keeps its why); the answer's
1552
+ * operation_id is the FRESH fetch (never a resurrect of the dead
1553
+ * row). A live row refuses 409; a landed row refuses 409 (the
1554
+ * weights are on the store — nothing to retry); an unknown id 404s. */
1555
+ async function hAcquireRetry(req, ctx) {
1556
+ need(req, "operation_id");
1557
+ estateOnly(req, ctx.endpoint());
1558
+ const provisioner = provisioningOf(ctx);
1559
+ if (typeof provisioner.progressOf !== "function" || typeof provisioner.startWeightAcquire !== "function") {
1560
+ throw unavailable("acquire_retry is not configured on this lane");
1561
+ }
1562
+ const progress = provisioner.progressOf(req.operation_id);
1563
+ if (progress === null || progress === undefined) {
1564
+ throw notFound("unknown acquire_weight operation: " + req.operation_id);
1565
+ }
1566
+ settledAcquireOrRefuse(req, progress);
1567
+ if (progress.state === "installed" || progress.state === "restart_required" || progress.state === "active") {
1568
+ throw new Refused(409, "acquire_weight " + progress.operationId + " already landed (" + progress.state
1569
+ + ") — the weights are on the store, nothing to retry");
1570
+ }
1571
+ const startAcquire = provisioner.startWeightAcquire;
1572
+ let operationId;
1573
+ try {
1574
+ operationId = await withManageTimeout(req, ctx, async () => await startAcquire.call(provisioner, progress.ref));
1575
+ }
1576
+ catch (error) {
1577
+ // THE BUSY MAP (audit I-S4): the same wait-not-failure face the
1578
+ // start arm answers — a plane at its cap is a retry_after, and
1579
+ // the dead row stays exactly as it was
1580
+ if (error instanceof AcquireBusyError) {
1581
+ return [429, {
1582
+ action: req.action,
1583
+ ok: false,
1584
+ state: "busy",
1585
+ status: 429,
1586
+ detail: error.message,
1587
+ next_action: "acquire_weight",
1588
+ retry_after_ms: error.retryAfterMs,
1589
+ }];
1590
+ }
1591
+ throw error;
1592
+ }
1593
+ return ok(req.action, "retrying " + progress.operationId + " (" + progress.state + ") as a fresh fetch — poll acquire_weight operation_id="
1594
+ + operationId + " (the dead row's truth is kept)", {
1595
+ operation_id: operationId,
1596
+ operationId,
1597
+ state: "acquiring",
1598
+ retried_operation_id: progress.operationId,
1599
+ next_action: "acquire_weight",
1600
+ });
1601
+ }
1602
+ /** acquire_discard — a settled acquire row is evicted (ledger entry,
1603
+ * by-ref pointer, stored row) so the wedge is clearable and a later
1604
+ * acquire_weight poll answers 404. A live row refuses 409; an
1605
+ * unknown id 404s. */
1606
+ async function hAcquireDiscard(req, ctx) {
1607
+ need(req, "operation_id");
1608
+ estateOnly(req, ctx.endpoint());
1609
+ const provisioner = provisioningOf(ctx);
1610
+ if (typeof provisioner.progressOf !== "function" || typeof provisioner.discardAcquire !== "function") {
1611
+ throw unavailable("acquire_discard is not configured on this lane");
1612
+ }
1613
+ const progress = provisioner.progressOf(req.operation_id);
1614
+ if (progress === null || progress === undefined) {
1615
+ throw notFound("unknown acquire_weight operation: " + req.operation_id);
1616
+ }
1617
+ settledAcquireOrRefuse(req, progress);
1618
+ provisioner.discardAcquire(req.operation_id);
1619
+ ctx.rearmWeights?.();
1620
+ return ok(req.action, "discarded acquire_weight " + progress.operationId + " (" + progress.state + ") — a later poll answers 404", {
1621
+ operation_id: progress.operationId,
1622
+ state: progress.state,
1623
+ next_action: "status",
1165
1624
  });
1166
1625
  }
1167
1626
  async function hRestart(req, ctx) {
@@ -1315,6 +1774,37 @@ async function hFree(req, ctx) {
1315
1774
  }
1316
1775
  return ok(req.action, "free issued (next worker iteration)", { next_action: "status" });
1317
1776
  }
1777
+
1778
+
1779
+
1780
+
1781
+
1782
+
1783
+
1784
+
1785
+
1786
+
1787
+
1788
+ const SETTLE_GRACE_MS = 120_000;
1789
+ async function hSettleStale(req, ctx) {
1790
+ const queue = await engineQueueView(ctx);
1791
+ if (queue === null) {
1792
+ throw new Refused(409, "settle_stale refused: the engine queue is unreachable — no corroboration, nothing settles (fail-closed)");
1793
+ }
1794
+ if (queue.running > 0 || queue.pending > 0) {
1795
+ throw new Refused(409, "settle_stale refused: the engine is working (running " + queue.running + " · pending " + queue.pending +
1796
+ ") — every live-worded sidecar may be live; settle only against an idle engine");
1797
+ }
1798
+ const boot = engineBootRow(ctx);
1799
+ const bootAt = boot["known"] === true ? Date.parse(String(boot["boot_at"])) : NaN;
1800
+ const now = Date.now();
1801
+ const outcome = settleStaleClaims(ctx.stateRoots, (_name, mtimeMs) => {
1802
+ if (Number.isFinite(bootAt) && mtimeMs < bootAt)
1803
+ return true;
1804
+ return mtimeMs < now - SETTLE_GRACE_MS;
1805
+ });
1806
+ return ok(req.action, "settled " + outcome.settled.length + " stale claim(s), skipped " + outcome.skipped.length, { next_action: "status", settled: outcome.settled, skipped: outcome.skipped });
1807
+ }
1318
1808
  // ── endpoint_set: the operator's server URL change ────────────────
1319
1809
  // Validates FIRST (a live /system_stats probe — an unreachable URL
1320
1810
  // is refused, never written), then rewrites ONLY `url` in the
@@ -1484,6 +1974,28 @@ async function hSnapshotList(req, ctx) {
1484
1974
  const items = snapshotItems(doc);
1485
1975
  return withNextAction(ok(req.action, items.length + " snapshot(s)", items), "snapshot_save");
1486
1976
  }
1977
+ // THE PREFLIGHT HANDLER (audit 019 C3): the five-axis read — one
1978
+ // row per axis, misses named with their doors, never a degraded
1979
+ // green (a probe throw IS a miss — see managePreflight.ts). ok
1980
+ // stays true: the read succeeded; the misses are the read's
1981
+ // payload, voiced by the render and the estate's boot note.
1982
+ async function hPreflight(req, ctx) {
1983
+ const rows = await runPreflight(ctx);
1984
+ const misses = rows.filter((r) => r.state === "miss");
1985
+ const lines = rows.map(preflightLine);
1986
+ return [
1987
+ 200,
1988
+ {
1989
+ action: req.action,
1990
+ ok: true,
1991
+ detail: rows.length + " axis(es) checked, " +
1992
+ (misses.length === 0 ? "all green" : misses.length + " miss(es): " + misses.map((m) => m.axis).join(", ")),
1993
+ rows: lines,
1994
+ misses: misses.map(preflightLine),
1995
+ data: { axes: rows },
1996
+ },
1997
+ ];
1998
+ }
1487
1999
  async function hSnapshotSave(req, ctx) {
1488
2000
  const cfg = ctx.endpoint();
1489
2001
  estateOnly(req, cfg);
@@ -1641,6 +2153,22 @@ async function loraInstalled(req, ctx, dir, result, verb) {
1641
2153
  },
1642
2154
  });
1643
2155
  }
2156
+
2157
+
2158
+
2159
+
2160
+
2161
+
2162
+
2163
+
2164
+
2165
+
2166
+ async function hRefmodsList(req, ctx) {
2167
+ const cfg = ctx.endpoint();
2168
+ estateOnly(req, cfg);
2169
+ const stems = refmodNamesFromObjectInfo(await objectInfoDoc(ctx, railMs(req)));
2170
+ return ok(req.action, stems.length + " refmods pack(s) the engine accepts", { stems });
2171
+ }
1644
2172
  /** The engine's node declaration, or null when the engine is
1645
2173
  * unreachable (the cross-check then proves nothing and refuses
1646
2174
  * nothing — never a throw across the sidebar). ONE reader, the
@@ -1713,17 +2241,24 @@ const HANDLERS = {
1713
2241
  install_extension_url: hInstallExtensionUrl,
1714
2242
  download_model: hDownloadModel,
1715
2243
  provision_model: hProvisionModel,
2244
+ provision_runtime: hProvisionRuntime,
1716
2245
  acquire_weight: hAcquireWeight,
2246
+ acquire_retry: hAcquireRetry,
2247
+ acquire_discard: hAcquireDiscard,
1717
2248
  restart: hRestart,
1718
2249
  stop: hStop,
1719
2250
  launch: hLaunch,
1720
2251
  update: hUpdate,
1721
2252
  switch_version: hSwitchVersion,
1722
2253
  free: hFree,
2254
+ settle_stale: hSettleStale,
1723
2255
  snapshot_save: hSnapshotSave,
1724
2256
  snapshot_restore: hSnapshotRestore,
1725
2257
  lora_list: hLoraList,
1726
2258
  lora_install: hLoraInstall,
2259
+ lora_fetch: hLoraFetch,
2260
+ refmods_list: hRefmodsList,
2261
+ preflight: hPreflight,
1727
2262
  };
1728
2263
  function refusalDataFields(data) {
1729
2264
  if (typeof data !== "object" || data === null)