@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,580 @@
1
+ import { servableLeaf } from "@melite/contracts/mediaKinds";
2
+ // runsList.ts — the runs LIST surface (REBUILD-7, gateway kill):
3
+ // the retired runs door's list arm (GET /v1/flows/runs, the restore port) re-homed verbatim into the queue package as the registry's `list` business arm.
4
+ // The sidecar byte-surgery helpers are the door's own bodies, second move unchanged (the section notes below name the reader each helper implements).
5
+ //
6
+ // TWO re-homes ride this stroke (ledgered):
7
+ // - mediaVocab: the media-kinds.json DATA file died with the media
8
+ // client (5cbb5bcc); the vocabulary re-homes as TYPED DATA in
9
+ // ./mediaKinds.ts (same sets, lowered; the $comment laws moved
10
+ // into that file) — no repo-anchored file reads, no cache.
11
+ // - ASSET_URL_PREFIX ("/v1/assets/runs") died with the app: url +
12
+ // thumbnail carry run-RELATIVE names ("run-x/img.png"), the same
13
+ // divergence-by-order law as the live payload (REBUILD-6). The
14
+ // row SCHEMA is byte-pinned by the wall; the web callers migrate
15
+ // on their stroke.
16
+ import { readdirSync, readFileSync, statSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import { mediaVocab } from "./mediaKinds.js";
19
+ import { engineFilmName } from "./filmLead.js";
20
+ /** Leading-int read (sidecar tails): optional space, optional
21
+ * sign, then digits; 0 when no digits lead. */
22
+ export function parseLeadingInt(s) {
23
+ // (group 1 always participates on match — the undefined fence is dead.)
24
+ const m = /^[\s]*([+-]?\d+)/.exec(s);
25
+ if (m === null)
26
+ return 0;
27
+ return Number(m[1]);
28
+ }
29
+ /** sidecar_num: first `"key":`, strtol the tail, default when the key is absent. */
30
+ export function sidecarNum(text, key, dflt) {
31
+ const needle = '"' + key + '":';
32
+ const i = text.indexOf(needle);
33
+ if (i < 0)
34
+ return dflt;
35
+ return parseLeadingInt(text.slice(i + needle.length));
36
+ }
37
+ /** sidecar_str: BYTE-wise exact — first `"key":`, skip spaces/tabs, expect `"`, decode \\n \\r \\t \" \\ (any other escape lands literally — \u stays "u"), stop at cap-1 BYTES. Operates on the UTF-8 bytes (D5). */
38
+ export function sidecarStr(raw, key, cap) {
39
+ const pat = Buffer.from('"' + key + '":', "utf8");
40
+ let at = -1;
41
+ outer: for (let i = 0; i + pat.length <= raw.length; i++) {
42
+ for (let j = 0; j < pat.length; j++) {
43
+ if (raw[i + j] !== pat[j])
44
+ continue outer;
45
+ }
46
+ at = i;
47
+ break;
48
+ }
49
+ if (at < 0)
50
+ return "";
51
+ let p = at + pat.length;
52
+ while (p < raw.length && (raw[p] === 0x20 || raw[p] === 0x09))
53
+ p++;
54
+ if (p >= raw.length || raw[p] !== 0x22)
55
+ return "";
56
+ p++;
57
+ const out = [];
58
+ while (p < raw.length && raw[p] !== 0x22 && out.length + 1 < cap) {
59
+ if (raw[p] === 0x5c && p + 1 < raw.length) {
60
+ p++;
61
+ const e = raw[p];
62
+ out.push(e === 0x6e ? 0x0a : e === 0x72 ? 0x0d : e === 0x74 ? 0x09 : e);
63
+ p++;
64
+ }
65
+ else {
66
+ out.push(raw[p]);
67
+ p++;
68
+ }
69
+ }
70
+ return Buffer.from(out).toString("utf8");
71
+ }
72
+ /** _sidecar_str_impl found-ness: only the runs-list status site reads it — a present-but-empty "status" serves "" (the gate then skips the row), while an absent/non-string key serves "unknown". */
73
+ export function sidecarStrFound(raw, key, cap) {
74
+ const pat = Buffer.from('"' + key + '":', "utf8");
75
+ let at = -1;
76
+ outer: for (let i = 0; i + pat.length <= raw.length; i++) {
77
+ for (let j = 0; j < pat.length; j++) {
78
+ if (raw[i + j] !== pat[j])
79
+ continue outer;
80
+ }
81
+ at = i;
82
+ break;
83
+ }
84
+ if (at < 0)
85
+ return [false, ""];
86
+ let p = at + pat.length;
87
+ while (p < raw.length && (raw[p] === 0x20 || raw[p] === 0x09))
88
+ p++;
89
+ if (p >= raw.length || raw[p] !== 0x22)
90
+ return [false, ""];
91
+ p++;
92
+ const out = [];
93
+ while (p < raw.length && raw[p] !== 0x22 && out.length + 1 < cap) {
94
+ if (raw[p] === 0x5c && p + 1 < raw.length) {
95
+ p++;
96
+ const e = raw[p];
97
+ out.push(e === 0x6e ? 0x0a : e === 0x72 ? 0x0d : e === 0x74 ? 0x09 : e);
98
+ p++;
99
+ }
100
+ else {
101
+ out.push(raw[p]);
102
+ p++;
103
+ }
104
+ }
105
+ return [true, Buffer.from(out).toString("utf8")];
106
+ }
107
+ export function artifactType(name) {
108
+ const kinds = mediaVocab();
109
+ const dot = name.lastIndexOf(".");
110
+ const ext = dot >= 0 ? name.slice(dot + 1).toLowerCase() : "";
111
+ if (kinds.image.includes(ext))
112
+ return "image";
113
+ if (kinds.audio.includes(ext))
114
+ return "audio";
115
+ if (kinds.video.includes(ext))
116
+ return "video";
117
+ if (kinds.model.includes(ext))
118
+ return "model";
119
+ if (ext === "json")
120
+ return "spec";
121
+ if (ext === "txt" || ext === "md" || ext === "yaml")
122
+ return "text";
123
+ return "file";
124
+ }
125
+ /** Byte-wise name order (the sort runs on the surrogateescape bytes — for valid UTF-8, Buffer.compare on the re-encoded name is the same bytes; D5). */
126
+ function byteLess(a, b) {
127
+ return Buffer.compare(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
128
+ }
129
+ function isDir(path) {
130
+ try {
131
+ return statSync(path).isDirectory();
132
+ }
133
+ catch {
134
+ return false;
135
+ }
136
+ }
137
+ function fileSize(path) {
138
+ try {
139
+ return statSync(path).size;
140
+ }
141
+ catch {
142
+ return -1;
143
+ }
144
+ }
145
+ /** _media_candidates: top-level files (non-underscore) then ONE level down (underscore + deeper dirs skipped), each tier byte-sorted. */
146
+ export function mediaCandidates(runDir) {
147
+ const cands = [];
148
+ let names;
149
+ try {
150
+ names = readdirSync(runDir);
151
+ }
152
+ catch {
153
+ return [];
154
+ }
155
+ names.sort(byteLess);
156
+ const subs = [];
157
+ for (const name of names) {
158
+ if (!servableLeaf(name))
159
+ continue; // the estate's own servable law (the poster IS servable)
160
+ const full = join(runDir, name);
161
+ if (isDir(full))
162
+ subs.push(name);
163
+ else
164
+ cands.push({ rel: name, full });
165
+ }
166
+ subs.sort(byteLess);
167
+ for (const sub of subs) {
168
+ let inner;
169
+ try {
170
+ inner = readdirSync(join(runDir, sub));
171
+ }
172
+ catch {
173
+ continue;
174
+ }
175
+ inner.sort(byteLess);
176
+ for (const name of inner) {
177
+ if (!servableLeaf(name))
178
+ continue; // the estate's own servable law (the poster IS servable)
179
+ const full = join(runDir, sub, name);
180
+ if (isDir(full))
181
+ continue;
182
+ cands.push({ rel: sub + "/" + name, full });
183
+ }
184
+ }
185
+ return cands;
186
+ }
187
+ /** run_artifacts: image/video/audio/model rows (image capped at _MAX_IMGS — counted but unlisted past it), everything else skipped; the {truncated,listed,total} marker when entries went unlisted. */
188
+ /** path keeps the "./output/<run>/" literal. */
189
+ export function runArtifacts(runDir, outDirLiteral) {
190
+ const kinds = mediaVocab();
191
+ const maxImgs = kinds.maxListedImages;
192
+ const runBase = (() => {
193
+ const stripped = outDirLiteral.replace(/\/+$/, "");
194
+ const slash = stripped.lastIndexOf("/");
195
+ return slash >= 0 ? stripped.slice(slash + 1) : stripped;
196
+ })();
197
+ const arts = [];
198
+ let mediaTotal = 0;
199
+ let listed = 0;
200
+ let imgs = 0;
201
+ for (const cand of mediaCandidates(runDir)) {
202
+ // A dead candidate (dangling symlink, vanished file — partial
203
+ // cleanup, pruned output) drops from the LIST, never the ROW:
204
+ // one unreadable artifact must not erase a finished run from
205
+ // the restore port (the -1 → artifactRowOk row-refusal path,
206
+ // audit finding, stroke 82 — the bytes gate now holds on what
207
+ // is actually listed).
208
+ const size = fileSize(cand.full);
209
+ if (size < 0)
210
+ continue;
211
+ const base = cand.rel.includes("/")
212
+ ? cand.rel.slice(cand.rel.lastIndexOf("/") + 1)
213
+ : cand.rel;
214
+ const t = artifactType(base);
215
+ if (t === "image") {
216
+ mediaTotal++;
217
+ imgs++;
218
+ if (imgs > maxImgs)
219
+ continue;
220
+ }
221
+ else if (t === "video" || t === "audio" || t === "model") {
222
+ mediaTotal++;
223
+ }
224
+ else {
225
+ continue;
226
+ }
227
+ listed++;
228
+ arts.push({
229
+ name: base,
230
+ path: outDirLiteral + "/" + cand.rel,
231
+ bytes: size,
232
+ url: runBase + "/" + cand.rel,
233
+ type: t,
234
+ size,
235
+ });
236
+ }
237
+ if (mediaTotal > listed) {
238
+ arts.push({ truncated: true, listed, total: mediaTotal });
239
+ }
240
+ const marker = arts.find((art) => art['truncated'] === true);
241
+ const named = arts.filter((art) => art !== marker);
242
+ const film = engineFilmName(named.map((art) => art['name']));
243
+ const ordered = film === null
244
+ ? named
245
+ : [named.find((art) => art['name'] === film), ...named.filter((art) => art['name'] !== film)];
246
+ return marker === undefined ? ordered : [...ordered, marker];
247
+ }
248
+ /** _run_thumbnail: cached poster wins, else the first image candidate (same one-level rule, so nested-only runs still get a poster). */
249
+ export function runThumbnail(runDir, runId) {
250
+ try {
251
+ statSync(join(runDir, "_poster.jpg"));
252
+ return runId + "/_poster.jpg";
253
+ }
254
+ catch {
255
+ /* no poster — fall through to first image */
256
+ }
257
+ for (const cand of mediaCandidates(runDir)) {
258
+ const base = cand.rel.includes("/")
259
+ ? cand.rel.slice(cand.rel.lastIndexOf("/") + 1)
260
+ : cand.rel;
261
+ if (artifactType(base) === "image") {
262
+ return runId + "/" + cand.rel;
263
+ }
264
+ }
265
+ return "";
266
+ }
267
+ /** _run_dir_has_media: the media-FIRST sort key — top-level names, then one level down. */
268
+ /** NOTE the absences: NO `_` skip (a lone `_poster.jpg` counts), NO inner isdir check (a nested DIR named x.mp4 counts) — probed live, mirrored exactly. */
269
+ /** Gallery sets only (svg/bmp classify but do not list — the media-kinds.json contract). */
270
+ export function runDirHasMedia(runDir) {
271
+ const kinds = mediaVocab();
272
+ const has = (name) => {
273
+ const dot = name.lastIndexOf(".");
274
+ const ext = dot >= 0 ? name.slice(dot + 1).toLowerCase() : "";
275
+ return (kinds.galleryVideo.includes(ext) ||
276
+ kinds.galleryImage.includes(ext) ||
277
+ kinds.galleryAudio.includes(ext) ||
278
+ kinds.galleryModel.includes(ext));
279
+ };
280
+ let names;
281
+ try {
282
+ names = readdirSync(runDir);
283
+ }
284
+ catch {
285
+ return false;
286
+ }
287
+ for (const name of names) {
288
+ if (has(name))
289
+ return true;
290
+ }
291
+ for (const name of names) {
292
+ const sub = join(runDir, name);
293
+ try {
294
+ if (!isDir(sub))
295
+ continue;
296
+ for (const inner of readdirSync(sub)) {
297
+ if (has(inner))
298
+ return true;
299
+ }
300
+ }
301
+ catch {
302
+ continue;
303
+ }
304
+ }
305
+ return false;
306
+ }
307
+ // ── the run-row gate (runRowOrNull below owns the row law) ─────
308
+ // A refused reconstruction is SKIPPED (RESILIENCE LAW) but stays in count (the C contract).
309
+ // Extra keys forbid; statuses outside the closed vocab (incl. "queued") refuse.
310
+ //
311
+ // DIVERGENCE (ledgered): the original ArtifactRow admitted image/video/audio only — the image-era vocab.
312
+ // The estate's own emitter half (runArtifacts in this file) counts "model" rows as listable media, mediaKinds.ts carries the galleryModel set, and the img-to-mesh lane is the first producer of model-only runs.
313
+ // Keeping the image-era refusal would drop every completed model run from the restore port (runs/list) — and with it runs/list adoption (fetchLatestRunForDraft) — so the row gate admits "model" alongside the triple.
314
+ const RUN_ID_RE = /^run-[A-Za-z0-9_.@-]+$/;
315
+ // NOT runsTypes.ts's exported RUN_STATUSES: this set is the list-side vocabulary (adds success/unknown, drops queued/stopping — the C-contract fold runsRegistry owns).
316
+ const RUN_STATUS = new Set([
317
+ "running",
318
+ "completed",
319
+ "failed",
320
+ "stopped",
321
+ "success",
322
+ "unknown",
323
+ ]);
324
+ const ARTIFACT_TYPE = new Set([
325
+ "image",
326
+ "video",
327
+ "audio",
328
+ "model",
329
+ ]);
330
+ function isIntGe0(v) {
331
+ return typeof v === "number" && Number.isInteger(v) && v >= 0;
332
+ }
333
+ function artifactRowOk(a) {
334
+ if (typeof a !== "object" || a === null || Array.isArray(a))
335
+ return false;
336
+ const o = a;
337
+ const keys = Object.keys(o);
338
+ const isTrunc = "truncated" in o;
339
+ if (isTrunc) {
340
+ if (keys.length !== 3)
341
+ return false;
342
+ return (o["truncated"] === true && isIntGe0(o["listed"]) && isIntGe0(o["total"]));
343
+ }
344
+ if (keys.length !== 6)
345
+ return false;
346
+ return (typeof o["name"] === "string" &&
347
+ o["name"].length >= 1 &&
348
+ typeof o["path"] === "string" &&
349
+ isIntGe0(o["bytes"]) &&
350
+ typeof o["url"] === "string" &&
351
+ typeof o["type"] === "string" &&
352
+ ARTIFACT_TYPE.has(o["type"]) &&
353
+ isIntGe0(o["size"]));
354
+ }
355
+ /** The RunRow gate — the row dict, or null when the gate refuses it (the caller logs LOUD and skips). */
356
+ /** Key order is the RunRow field order. */
357
+ export function runRowOrNull(row) {
358
+ if (!RUN_ID_RE.test(row.run_id))
359
+ return null;
360
+ if (!RUN_STATUS.has(row.status))
361
+ return null;
362
+ if (!isIntGe0(row.created_at))
363
+ return null;
364
+ if (typeof row.seed !== "number" || !Number.isInteger(row.seed))
365
+ return null;
366
+ for (const a of row.artifacts) {
367
+ if (!artifactRowOk(a))
368
+ return null;
369
+ }
370
+ return {
371
+ run_id: row.run_id,
372
+ name: row.name,
373
+ flow: row.flow,
374
+ status: row.status,
375
+ created_at: row.created_at,
376
+ prompt: row.prompt,
377
+ seed: row.seed,
378
+ thumbnail: row.thumbnail,
379
+ artifacts: row.artifacts,
380
+ params: row.params,
381
+ draft_id: row.draft_id,
382
+ ...(row.stage_ids !== undefined && row.stage_ids.length > 0 ? { stage_ids: [...row.stage_ids] } : {}),
383
+ ...(typeof row.export_name === "string" && row.export_name !== "" ? { export_name: row.export_name } : {}),
384
+ ...(typeof row.export_path === "string" && row.export_path !== "" ? { export_path: row.export_path } : {}),
385
+ };
386
+ }
387
+ /** Strict int parse: surrounding whitespace stripped, one optional
388
+ * sign, ASCII digits with single internal underscores ("1_0" ->
389
+ * 10). null = not an int (the 400 arm). */
390
+ export function parseIntOrNull(s) {
391
+ const m = /^([+-]?)([0-9]+(?:_[0-9]+)*)$/.exec(s.trim());
392
+ // (both groups always participate on match — the fences are dead.)
393
+ if (m === null)
394
+ return null;
395
+ return Number(m[1] + m[2].replace(/_/g, ""));
396
+ }
397
+ /** parse_qs (drops blank values): first non-blank
398
+ * value wins; the shared ctx parseQuery keeps blanks, so the
399
+ * filter lives here (parse_qs default). */
400
+ export function firstQuery(qs, name, dflt) {
401
+ const vals = qs[name];
402
+ if (vals === undefined)
403
+ return dflt;
404
+ for (const v of vals) {
405
+ if (v !== "")
406
+ return v;
407
+ }
408
+ return dflt;
409
+ }
410
+ /** The single-root scan (the file-era walk, intact): PROD output
411
+ * root only (test runs never listed — kept 1:1). */
412
+ function scanRunsRoot(stateRoot) {
413
+ // The PROD output root only (the door's list scanned
414
+ // roots.runsRoot; test runs never listed — kept 1:1).
415
+ const outputRoot = join(stateRoot, "output");
416
+ let names;
417
+ try {
418
+ names = readdirSync(outputRoot);
419
+ }
420
+ catch {
421
+ names = [];
422
+ }
423
+ const ents = [];
424
+ for (const name of names) {
425
+ if (ents.length >= 8192)
426
+ break; // the C's 8192 collected cap
427
+ if (!name.startsWith("run-"))
428
+ continue;
429
+ const runDir = join(outputRoot, name);
430
+ let created = 0;
431
+ let buf = "";
432
+ try {
433
+ buf = readFileSync(join(runDir, "_flow.json"), "utf8").slice(0, 8191);
434
+ }
435
+ catch {
436
+ buf = "";
437
+ }
438
+ if (buf) {
439
+ // created_at (sidecar) first, "created" (C fossil) fallback.
440
+ created = sidecarNum(buf, "created", 0);
441
+ const at = buf.indexOf('"created_at":');
442
+ if (at >= 0)
443
+ created = parseLeadingInt(buf.slice(at + 13));
444
+ }
445
+ ents.push({
446
+ dir: name,
447
+ created,
448
+ media: runDirHasMedia(runDir),
449
+ root: stateRoot,
450
+ });
451
+ }
452
+ return ents;
453
+ }
454
+ /** The per-run card build (the file-era row law, intact): sidecar
455
+ * byte-scan → zombie override → user-surface skip → orphan-draft
456
+ * clearing → runRowOrNull. Null = skipped (never stored, never
457
+ * served — the count still counts the dir). The drafts probe is
458
+ * ASYNC (the drafts remote's birth-certificate face — the legacy
459
+ * drafts/<id>.json stat died with the drafts-door migration;
460
+ * orphans lose their draft link, never the row). */
461
+ async function buildRunCard(outputRoot, ent, hasDraft) {
462
+ const runDir = join(outputRoot, ent.dir);
463
+ let buf = null;
464
+ // NO sidecar (ENOENT) is the file-era completed-run law: it reads
465
+ // the "success" default, pinned by runs-list.spec. A sidecar that
466
+ // EXISTS but cannot be read (torn read, permissions) is different —
467
+
468
+ let torn = false;
469
+ try {
470
+ buf = readFileSync(join(runDir, "_flow.json"), "utf8").slice(0, 8191);
471
+ }
472
+ catch (e) {
473
+ buf = null;
474
+ torn = !(typeof e === "object" && e !== null && e.code === "ENOENT");
475
+ }
476
+ let status = torn ? "unknown" : "success";
477
+ let pipeline = "";
478
+ let prompt = "";
479
+ let draft = "";
480
+ let stageIdsRaw = "";
481
+ let exported = "";
482
+ let exportedPath = "";
483
+ let seed = -1;
484
+ let created = ent.created;
485
+ const rawBytes = buf === null ? Buffer.alloc(0) : Buffer.from(buf, "utf8");
486
+ if (buf !== null) {
487
+ // found-ness matters: absent key -> "unknown" (served); present-but-empty -> "" (gate-skipped).
488
+ const [foundStatus, rawStatus] = sidecarStrFound(rawBytes, "status", 16);
489
+ if (foundStatus) {
490
+ status = rawStatus === "error" ? "failed" : rawStatus;
491
+ // read-time zombie override (sweep=False: report only, D1).
492
+ if (status === "running")
493
+ status = "failed";
494
+ }
495
+ else {
496
+ status = "unknown";
497
+ }
498
+ pipeline = sidecarStr(rawBytes, "pipeline", 64);
499
+ prompt = sidecarStr(rawBytes, "prompt", 2048);
500
+ draft = sidecarStr(rawBytes, "draft_id", 96);
501
+ // THE STAGE-ID DIGEST, LISTED: CSV on disk, array on the row —
502
+ // absent on pre-digest sidecars (the export_name precedent:
503
+ // optional key, never guessed).
504
+ stageIdsRaw = sidecarStr(rawBytes, "stage_ids", 512);
505
+ // THE EXPORT NAME, LISTED (023's self-critique #4/#6): the
506
+ // design lane's mint rides the list row too — additive, same
507
+ // spelling as the sidecar; absent on non-export runs.
508
+ exported = sidecarStr(rawBytes, "export_name", 128);
509
+ // THE EXPORT PATH, LISTED (the export FULL PATH): the engine's
510
+ // minted .qvoice absolute path rides the list row — the voices
511
+ // root is long, so the slice budget doubles the name's.
512
+ exportedPath = sidecarStr(rawBytes, "export_path", 256);
513
+ seed = sidecarNum(buf, "seed", -1);
514
+ const at = buf.indexOf('"created_at":');
515
+ if (at >= 0)
516
+ created = parseLeadingInt(buf.slice(at + 13));
517
+ }
518
+ if (pipeline.startsWith("_"))
519
+ return null; // user-surface law
520
+ if (draft && !(await hasDraft(draft))) {
521
+ draft = "";
522
+ }
523
+ const literal = "./output/" + ent.dir;
524
+ const row = runRowOrNull({
525
+ run_id: ent.dir,
526
+ name: pipeline,
527
+ flow: pipeline,
528
+ status,
529
+ created_at: created,
530
+ prompt,
531
+ seed,
532
+ thumbnail: runThumbnail(runDir, ent.dir),
533
+ artifacts: runArtifacts(runDir, literal),
534
+ params: { seed },
535
+ draft_id: draft,
536
+ ...(stageIdsRaw !== "" ? { stage_ids: stageIdsRaw.split(",") } : {}),
537
+ ...(exported !== "" ? { export_name: exported } : {}),
538
+ ...(exportedPath !== "" ? { export_path: exportedPath } : {}),
539
+ });
540
+ return row; // null = RESILIENCE LAW loud skip
541
+ }
542
+ /** The runs-list envelope (the restore port): the output-root scan, media-first + newest sort, the limit parse (raw STRING — the lane/remote pass the raw text; underscores parse, non-ints refuse), refused cards SKIPPED but counted. */
543
+ /** url/thumbnail are run-RELATIVE (the /v1/assets prefix died with the app — the header's law). */
544
+ export async function listRuns(stateRoot, limit, hasDraft) {
545
+ return listRunsAcross([stateRoot], limit, hasDraft);
546
+ }
547
+
548
+
549
+
550
+
551
+
552
+
553
+
554
+ export async function listRunsAcross(roots, limit, hasDraft) {
555
+ const ents = [];
556
+ for (const root of roots)
557
+ ents.push(...scanRunsRoot(root));
558
+ const count = ents.length;
559
+ ents.sort((a, b) => {
560
+ const am = a.media ? 0 : 1;
561
+ const bm = b.media ? 0 : 1;
562
+ if (am !== bm)
563
+ return am - bm;
564
+ return b.created - a.created; // newest-first; stable
565
+ });
566
+ const sliced = ents.slice(0, limit);
567
+ const seen = new Set();
568
+ const rows = [];
569
+ for (const ent of sliced) {
570
+ if (seen.has(ent.dir))
571
+ continue; // first manifest root wins
572
+ seen.add(ent.dir);
573
+ const row = await buildRunCard(join(ent.root, "output"), ent, hasDraft);
574
+ if (row === null)
575
+ continue; // RESILIENCE LAW: loud skip
576
+ rows.push({ ...row, served_from: ent.root });
577
+ }
578
+ return { count, runs: rows };
579
+ }
580
+ //# sourceMappingURL=runsList.js.map
@@ -0,0 +1,9 @@
1
+ import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
2
+ import type { CardArmError } from "./cardsArmError.js";
3
+ import type { QueueRefusal } from "./queue.js";
4
+ export declare function cardRefusal(err: CardArmError): QueueRefusal;
5
+ /** Fold a door refusal into the protocol's one error class. */
6
+ export declare function toRemoteError(r: QueueRefusal): RemoteError;
7
+ /** The preview-scope refusal (door posture). */
8
+ export declare function refusePreview(message: string): QueueRefusal;
9
+ //# sourceMappingURL=runsRefusalVoices.d.ts.map
@@ -0,0 +1,44 @@
1
+ // runsRefusalVoices.ts — the runs seat's refusal folds. Extracted
2
+ // from runsRegistry (the god-file cut): CardArmError -> QueueRefusal
3
+ // -> RemoteError over the one code table, plus the preview posture.
4
+ import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
5
+ import { RUNS_ERROR_CODES } from "./runsErrorCodes.js";
6
+ function refusalEnvelopeOf(err) {
7
+ const p = { error: err.message, code: err.code };
8
+ if (err.loc !== undefined)
9
+ p["loc"] = err.loc;
10
+ if (err.expected !== undefined)
11
+ p["expected"] = err.expected;
12
+ if (err.got !== undefined)
13
+ p["got"] = err.got;
14
+ return p;
15
+ }
16
+ export function cardRefusal(err) {
17
+ return {
18
+ status: err.status,
19
+ payload: refusalEnvelopeOf(err),
20
+ };
21
+ }
22
+ /** Fold a door refusal into the protocol's one error class. */
23
+ export function toRemoteError(r) {
24
+ const p = r.payload;
25
+ const mapped = RUNS_ERROR_CODES[p["code"]];
26
+ if (mapped === undefined) {
27
+ // A refusal this table does not name is a bug — LOUD, never
28
+ // a silent generic.
29
+ throw new Error("runs remote: unmapped refusal code " + p["code"]);
30
+ }
31
+ const details = {};
32
+ if (p["loc"] !== undefined)
33
+ details["loc"] = p["loc"];
34
+ if (p["expected"] !== undefined)
35
+ details["expected"] = p["expected"];
36
+ if (p["got"] !== undefined)
37
+ details["got"] = p["got"];
38
+ return new RemoteError(mapped, p["error"], details);
39
+ }
40
+ /** The preview-scope refusal (door posture). */
41
+ export function refusePreview(message) {
42
+ return { status: 400, payload: { error: message, code: "preview_scope" } };
43
+ }
44
+ //# sourceMappingURL=runsRefusalVoices.js.map