@melite/estate-queue 0.0.0-stage → 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 (131) hide show
  1. package/LICENSE +557 -0
  2. package/README.md +54 -2
  3. package/lib/bakeParams.d.ts +17 -0
  4. package/lib/bakeParams.js +182 -0
  5. package/lib/bench.d.ts +32 -0
  6. package/lib/bench.js +111 -0
  7. package/lib/cardsArmError.d.ts +61 -0
  8. package/lib/cardsArmError.js +57 -0
  9. package/lib/cardsCompose.d.ts +53 -0
  10. package/lib/cardsCompose.js +295 -0
  11. package/lib/cardsDangling.d.ts +16 -0
  12. package/lib/cardsDangling.js +213 -0
  13. package/lib/cardsFacts.d.ts +87 -0
  14. package/lib/cardsFacts.js +78 -0
  15. package/lib/cardsLanes.d.ts +43 -0
  16. package/lib/cardsLanes.js +178 -0
  17. package/lib/cardsRegistry.d.ts +404 -0
  18. package/lib/cardsRegistry.js +1543 -0
  19. package/lib/cardsVariant.d.ts +37 -0
  20. package/lib/cardsVariant.js +243 -0
  21. package/lib/discloseRegistry.d.ts +95 -0
  22. package/lib/discloseRegistry.js +156 -0
  23. package/lib/filmLead.d.ts +4 -0
  24. package/lib/filmLead.js +17 -0
  25. package/lib/filmMemoryWarn.d.ts +27 -0
  26. package/lib/filmMemoryWarn.js +99 -0
  27. package/lib/flowsData.d.ts +234 -0
  28. package/lib/flowsData.js +673 -0
  29. package/lib/flowsFamilyCompose.d.ts +45 -0
  30. package/lib/flowsFamilyCompose.js +191 -0
  31. package/lib/flowsParamsOverlay.d.ts +55 -0
  32. package/lib/flowsParamsOverlay.js +197 -0
  33. package/lib/flowsRegistryRows.d.ts +12 -0
  34. package/lib/flowsRegistryRows.js +520 -0
  35. package/lib/index.d.ts +47 -0
  36. package/lib/index.js +75 -0
  37. package/lib/ledgerTail.d.ts +20 -0
  38. package/lib/ledgerTail.js +123 -0
  39. package/lib/lifecycleLatch.d.ts +16 -0
  40. package/lib/lifecycleLatch.js +42 -0
  41. package/lib/loadPlane.d.ts +94 -0
  42. package/lib/loadPlane.js +570 -0
  43. package/lib/loadRegistry.d.ts +22 -0
  44. package/lib/loadRegistry.js +55 -0
  45. package/lib/manageOps.d.ts +27 -0
  46. package/lib/manageOps.js +162 -0
  47. package/lib/managePlane.d.ts +151 -0
  48. package/lib/managePlane.js +1790 -0
  49. package/lib/manageProbe.d.ts +48 -0
  50. package/lib/manageProbe.js +165 -0
  51. package/lib/manageRegistry.d.ts +66 -0
  52. package/lib/manageRegistry.js +113 -0
  53. package/lib/managerRail.d.ts +33 -0
  54. package/lib/managerRail.js +91 -0
  55. package/lib/mediaKinds.d.ts +3 -0
  56. package/lib/mediaKinds.js +2 -0
  57. package/lib/queue.d.ts +9 -0
  58. package/lib/queue.js +80 -0
  59. package/lib/queueCore.d.ts +72 -0
  60. package/lib/queueCore.js +128 -0
  61. package/lib/queueLifecycle.d.ts +2 -0
  62. package/lib/queueLifecycle.js +11 -0
  63. package/lib/queueLock.d.ts +60 -0
  64. package/lib/queueLock.js +198 -0
  65. package/lib/queueResurrect.d.ts +59 -0
  66. package/lib/queueResurrect.js +249 -0
  67. package/lib/queueRetry.d.ts +36 -0
  68. package/lib/queueRetry.js +24 -0
  69. package/lib/queueSidecar.d.ts +149 -0
  70. package/lib/queueSidecar.js +183 -0
  71. package/lib/queueSubmit.d.ts +82 -0
  72. package/lib/queueSubmit.js +191 -0
  73. package/lib/queueSweep.d.ts +30 -0
  74. package/lib/queueSweep.js +132 -0
  75. package/lib/resurrect.d.ts +6 -0
  76. package/lib/resurrect.js +18 -0
  77. package/lib/rootsManifest.d.ts +11 -0
  78. package/lib/rootsManifest.js +11 -0
  79. package/lib/runsChange.d.ts +61 -0
  80. package/lib/runsChange.js +79 -0
  81. package/lib/runsErrorCodes.d.ts +2 -0
  82. package/lib/runsErrorCodes.js +48 -0
  83. package/lib/runsExecute.d.ts +52 -0
  84. package/lib/runsExecute.js +494 -0
  85. package/lib/runsGates.d.ts +161 -0
  86. package/lib/runsGates.js +307 -0
  87. package/lib/runsList.d.ts +78 -0
  88. package/lib/runsList.js +574 -0
  89. package/lib/runsRefusalVoices.d.ts +9 -0
  90. package/lib/runsRefusalVoices.js +96 -0
  91. package/lib/runsRegistry.d.ts +351 -0
  92. package/lib/runsRegistry.js +2394 -0
  93. package/lib/runsSourceEcho.d.ts +81 -0
  94. package/lib/runsSourceEcho.js +341 -0
  95. package/lib/runsStart.d.ts +163 -0
  96. package/lib/runsStart.js +667 -0
  97. package/lib/runsTypes.d.ts +218 -0
  98. package/lib/runsTypes.js +289 -0
  99. package/lib/runsValidate.d.ts +5 -0
  100. package/lib/runsValidate.js +31 -0
  101. package/lib/runsValidateArms.d.ts +7 -0
  102. package/lib/runsValidateArms.js +339 -0
  103. package/lib/runsValidateInline.d.ts +6 -0
  104. package/lib/runsValidateInline.js +82 -0
  105. package/lib/runsValidateRefusals.d.ts +7 -0
  106. package/lib/runsValidateRefusals.js +18 -0
  107. package/lib/runsValidateServe.d.ts +15 -0
  108. package/lib/runsValidateServe.js +276 -0
  109. package/lib/runsValidateShared.d.ts +84 -0
  110. package/lib/runsValidateShared.js +88 -0
  111. package/lib/runsValidateStages.d.ts +32 -0
  112. package/lib/runsValidateStages.js +511 -0
  113. package/lib/runsValidateSweeps.d.ts +6 -0
  114. package/lib/runsValidateSweeps.js +143 -0
  115. package/lib/service.d.ts +63 -0
  116. package/lib/service.js +89 -0
  117. package/lib/skillFrontmatter.d.ts +11 -0
  118. package/lib/skillFrontmatter.js +46 -0
  119. package/lib/skillFs.d.ts +24 -0
  120. package/lib/skillFs.js +78 -0
  121. package/lib/skillPlane.d.ts +99 -0
  122. package/lib/skillPlane.js +269 -0
  123. package/lib/skillRegistry.d.ts +23 -0
  124. package/lib/skillRegistry.js +55 -0
  125. package/lib/skillRows.d.ts +127 -0
  126. package/lib/skillRows.js +468 -0
  127. package/lib/toolProjection.d.ts +30 -0
  128. package/lib/toolProjection.js +142 -0
  129. package/lib/vocab.d.ts +6 -0
  130. package/lib/vocab.js +18 -0
  131. package/package.json +48 -4
@@ -0,0 +1,72 @@
1
+ import type { Branded } from "@deepseek-ai/dsh-brand";
2
+ import type { LifecycleState } from "./queueLifecycle.js";
3
+ /** The run id: run-<12hex>-<8hex>, opaque as it crosses wire, queue
4
+ * and file (branded at its two producers — the mint below and the
5
+ * resurrect fs door — per the dsh-brand convention). */
6
+ export type RunId = Branded<"RunId">;
7
+ export interface QueueRunRow {
8
+ runId: RunId;
9
+ status: LifecycleState;
10
+ /** Terminal failure text ("<Type>: <msg>") — "" until failed. */
11
+ error: string;
12
+ createdAt: number;
13
+ draftId: string;
14
+ testFlag: boolean;
15
+ stopFlag: boolean;
16
+ }
17
+ /** The serial-GPU registry: runs + submission-order list + the one
18
+ * active run. The worker is the only popper (single-writer under
19
+ * one loop); submission order is append order (strict FIFO — no
20
+ * priority lane exists, see the header). */
21
+ export declare class QueueCore {
22
+ readonly runs: Map<string, QueueRunRow>;
23
+ readonly order: string[];
24
+ activeId: string | null;
25
+ readonly bootAt: number;
26
+ /** Registration tail (submit 1341-1342): the run row joins the
27
+ * registry, its id appends the order list. Returns the queue
28
+ * position (append index). */
29
+ enqueue(run: QueueRunRow): number;
30
+ /** The worker's claim (worker 1356-1360): while active is set the
31
+ * next pop BLOCKS (one GPU run machine-wide); else the head
32
+ * leaves the order list and becomes active. Null = idle. A ghost
33
+ * id at the head (row swept mid-queue — resurrect, bootSweep) is
34
+ * SKIPPED, not treated as idle: returning null on a consumed
35
+ * ghost made the pump read a NON-empty queue as idle and strand
36
+ * every run behind the ghost until a later kick (audit R8,
37
+ * stroke 82). */
38
+ tryDequeue(): QueueRunRow | null;
39
+ /** Release the active claim (worker finally: active null). */
40
+ releaseActive(): void;
41
+ /** Terminal mapping (worker 1366-1371): stopped iff the stop flag
42
+ * is set, else completed on success / failed on exception with
43
+ * the "<Type>: <msg>" error. Returns the settled status. */
44
+ settleRun(run: QueueRunRow, failureText: string | null): LifecycleState;
45
+ /** queue_position (status door 2973-2975): order index, else 0
46
+ * (active/finished runs read 0). */
47
+ queuePosition(runId: string): number;
48
+ /** The queue snapshot (_h_queue 2893-2900): key order . */
49
+ snapshot(): {
50
+ queued: number;
51
+ running: number;
52
+ active: string;
53
+ queued_ids: string[];
54
+ };
55
+ /** Settled-row eviction (_evict_settled 1137-1151): settled is
56
+ * every terminal status — completed, failed, AND stopped (audit
57
+ * F-S11: stopped was exempt as "a live receipt", but terminal is
58
+ * terminal — a stop-heavy session minted rows the cap never
59
+ * touched, and the receipt lives on in the persist regardless;
60
+ * the 500-row window serves any interactive read). Past 500 the
61
+ * oldest created_at leaves first. Returns evicted ids. */
62
+ evictSettled(): string[];
63
+ }
64
+ /** run-<12hex>-<8hex> ids (submit 1267: uuid4 hex + time-ms low 32).
65
+ * The mint is one of the brand's two producers; the return cast is
66
+ * the construction door. */
67
+ export declare function newRunId(): RunId;
68
+ /** The terminal broadcast frame (worker 1413-1414): every
69
+ * subscriber gets the final status exactly once. Shape pinned
70
+ * here so the P6 bus port inherits it. */
71
+ export declare function terminalFrame(status: LifecycleState): Record<string, string>;
72
+ //# sourceMappingURL=queueCore.d.ts.map
@@ -0,0 +1,128 @@
1
+
2
+ // pure move, zero logic changes — the queue.ts barrel re-exports
3
+ // every symbol, so the public surface is byte-identical).
4
+ //
5
+ // Erasable-syntax TS only (node --experimental-strip-types): no
6
+ // enums, import type for types, .ts specifiers for relative imports.
7
+ import { randomBytes } from "node:crypto";
8
+ import { MAX_SETTLED_RUNS } from "./queueLock.js";
9
+ import { notifyRunChanged } from "./runsChange.js";
10
+ /** The serial-GPU registry: runs + submission-order list + the one
11
+ * active run. The worker is the only popper (single-writer under
12
+ * one loop); submission order is append order (strict FIFO — no
13
+ * priority lane exists, see the header). */
14
+ export class QueueCore {
15
+ runs = new Map();
16
+ order = [];
17
+ activeId = null;
18
+ bootAt = Date.now() / 1000;
19
+ /** Registration tail (submit 1341-1342): the run row joins the
20
+ * registry, its id appends the order list. Returns the queue
21
+ * position (append index). */
22
+ enqueue(run) {
23
+ this.runs.set(run.runId, run);
24
+ this.order.push(run.runId);
25
+ return this.order.length - 1;
26
+ }
27
+ /** The worker's claim (worker 1356-1360): while active is set the
28
+ * next pop BLOCKS (one GPU run machine-wide); else the head
29
+ * leaves the order list and becomes active. Null = idle. A ghost
30
+ * id at the head (row swept mid-queue — resurrect, bootSweep) is
31
+ * SKIPPED, not treated as idle: returning null on a consumed
32
+ * ghost made the pump read a NON-empty queue as idle and strand
33
+ * every run behind the ghost until a later kick (audit R8,
34
+ * stroke 82). */
35
+ tryDequeue() {
36
+ if (this.activeId !== null)
37
+ return null;
38
+ while (this.order.length > 0) {
39
+ const runId = this.order.shift();
40
+ const run = this.runs.get(runId);
41
+ if (run === undefined)
42
+ continue;
43
+ run.status = "running";
44
+ this.activeId = runId;
45
+ notifyRunChanged(runId);
46
+ return run;
47
+ }
48
+ return null;
49
+ }
50
+ /** Release the active claim (worker finally: active null). */
51
+ releaseActive() {
52
+ this.activeId = null;
53
+ }
54
+ /** Terminal mapping (worker 1366-1371): stopped iff the stop flag
55
+ * is set, else completed on success / failed on exception with
56
+ * the "<Type>: <msg>" error. Returns the settled status. */
57
+ settleRun(run, failureText) {
58
+ if (run.stopFlag) {
59
+ run.status = "stopped";
60
+ notifyRunChanged(run.runId);
61
+ return run.status;
62
+ }
63
+ if (failureText === null) {
64
+ run.status = "completed";
65
+ notifyRunChanged(run.runId);
66
+ return run.status;
67
+ }
68
+ run.status = "failed";
69
+ run.error = failureText;
70
+ notifyRunChanged(run.runId);
71
+ return run.status;
72
+ }
73
+ /** queue_position (status door 2973-2975): order index, else 0
74
+ * (active/finished runs read 0). */
75
+ queuePosition(runId) {
76
+ const i = this.order.indexOf(runId);
77
+ return i < 0 ? 0 : i;
78
+ }
79
+ /** The queue snapshot (_h_queue 2893-2900): key order . */
80
+ snapshot() {
81
+ return {
82
+ queued: this.order.length,
83
+ running: this.activeId !== null ? 1 : 0,
84
+ active: this.activeId ?? "",
85
+ queued_ids: [...this.order],
86
+ };
87
+ }
88
+ /** Settled-row eviction (_evict_settled 1137-1151): settled is
89
+ * every terminal status — completed, failed, AND stopped (audit
90
+ * F-S11: stopped was exempt as "a live receipt", but terminal is
91
+ * terminal — a stop-heavy session minted rows the cap never
92
+ * touched, and the receipt lives on in the persist regardless;
93
+ * the 500-row window serves any interactive read). Past 500 the
94
+ * oldest created_at leaves first. Returns evicted ids. */
95
+ evictSettled() {
96
+ const settled = [...this.runs.values()].filter((r) => r.status === "completed" || r.status === "failed" ||
97
+ r.status === "stopped");
98
+ const excess = settled.length - MAX_SETTLED_RUNS;
99
+ if (excess <= 0)
100
+ return [];
101
+ settled.sort((a, b) => a.createdAt - b.createdAt === 0
102
+ ? (a.runId < b.runId ? -1 : 1)
103
+ : a.createdAt - b.createdAt);
104
+ const evicted = [];
105
+ for (const r of settled.slice(0, excess)) {
106
+ this.runs.delete(r.runId);
107
+ evicted.push(r.runId);
108
+ }
109
+ return evicted;
110
+ }
111
+ }
112
+ /** run-<12hex>-<8hex> ids (submit 1267: uuid4 hex + time-ms low 32).
113
+ * The mint is one of the brand's two producers; the return cast is
114
+ * the construction door. */
115
+ export function newRunId() {
116
+ const rand = randomBytes(6).toString("hex");
117
+ const ts = ((Date.now() & 0xffffffff) >>> 0)
118
+ .toString(16)
119
+ .padStart(8, "0");
120
+ return "run-" + rand + "-" + ts;
121
+ }
122
+ /** The terminal broadcast frame (worker 1413-1414): every
123
+ * subscriber gets the final status exactly once. Shape pinned
124
+ * here so the P6 bus port inherits it. */
125
+ export function terminalFrame(status) {
126
+ return { type: "run", status };
127
+ }
128
+ //# sourceMappingURL=queueCore.js.map
@@ -0,0 +1,2 @@
1
+ export type LifecycleState = "queued" | "running" | "completed" | "failed" | "stopped" | "stopping";
2
+ //# sourceMappingURL=queueLifecycle.d.ts.map
@@ -0,0 +1,11 @@
1
+ // queueLifecycle.ts — the queue row's lifecycle state union (split
2
+
3
+ // constructors that once lived here were deleted (the wire-chain
4
+
5
+ // throw RemoteError with their own runs/* codes directly — while
6
+ // carrying six envelope codes no table row owned, a latent
7
+ // unmapped-throw for the first future caller. Erasable-syntax TS
8
+ // only (node --experimental-strip-types): no enums, import type for
9
+ // types, .ts specifiers for relative imports.
10
+ export {};
11
+ //# sourceMappingURL=queueLifecycle.js.map
@@ -0,0 +1,60 @@
1
+ /** Lock file name under STATE_ROOT (acquire_lock 4416). */
2
+ export declare const LOCK_NAME: string;
3
+ /** Worker poll cadence (worker 1354: asyncio.sleep(0.05)). */
4
+ /** Registry bound (MAX_SETTLED_RUNS 2187: settled completed/failed
5
+ * rows past 500 leave; the sidecar stays SSOT). */
6
+ export declare const MAX_SETTLED_RUNS: number;
7
+ /** Stage retries range (flow spec: retries 0..5). */
8
+ export declare const RETRIES_MAX: number;
9
+ /** The stderr line main() prints before exit(1).
10
+ * NOTE the em-dash — byte-identical. */
11
+ export declare function refuseStartLine(note: string): string;
12
+
13
+
14
+
15
+
16
+ export declare function resolveStateRoot(config: Readonly<{
17
+ repoRoot?: string;
18
+ stateRoot?: string;
19
+ }>): string;
20
+ /** Run-dir root — TEST_OUT_ROOT on test:true else OUT_ROOT (L3). */
21
+ export declare function outRootFor(stateRoot: string, testFlag: boolean): string;
22
+ /** Append-only journal path (LEDGER_PATH 2180: OUT_ROOT/_ledger). */
23
+ export declare function ledgerPathFor(stateRoot: string): string;
24
+ /** Lock path (acquire_lock 4416: STATE_ROOT/gateway.lock). */
25
+ export declare function lockPathFor(stateRoot: string): string;
26
+ export interface LockResult {
27
+ readonly ok: boolean;
28
+ readonly note: string;
29
+ }
30
+ /** Signal-0 probe (_pid_alive 4469-4479: ESRCH-dead false, EPERM
31
+ * still ALIVE — the whole point of the guard). */
32
+ export declare function isPidAlive(pid: number): boolean;
33
+ /** R2 single-writer: O_CREAT|O_EXCL acquire; on
34
+ * collision the holder pid decides — alive refuses loud (the
35
+ * caller exits before any boot side effect), dead-or-garbage
36
+ * steals (unlink + re-acquire, ledgered server.lock_stolen). */
37
+ export declare function acquireLock(stateRoot: string, pid?: number, nowS?: number): LockResult;
38
+ /** PID-CHECKED release (release_lock 4450-4468): a boot that never
39
+ * owned the lock frees only its OWN, never the live holder's (the
40
+ * watcher-storm lesson — a blind unlink let each retry steal +
41
+ * boot-sweep LIVE runs). */
42
+ export declare function releaseLock(stateRoot: string, pid?: number): boolean;
43
+ /** Pre-boot gate (main 4474-4480): acquire BEFORE any boot side
44
+ * effect — resurrection, sweep, worker, listen. A second writer
45
+ * exits here, loud, having touched nothing (but the steal ledger
46
+ * row, when it stole from the dead). */
47
+ export declare function bootGate(stateRoot: string, pid?: number): LockResult;
48
+ /** Journal data writer: canonical JSON, UTF-8. */
49
+ export declare function dumpsLedgerData(data: Record<string, unknown>): string;
50
+ /** Append-only activity journal: one JSON object per line,
51
+ * close-per-line (durable), mkdir-parents, NEVER throws.
52
+ * Line shape: {ts, event, data} — compact envelope. */
53
+ export declare function appendLedger(stateRoot: string, event: string, data?: Record<string, unknown> | null, nowS?: number): void;
54
+ /** Atomic indent-2 JSON write — the atomicity is
55
+ * `writeFileAtomic`'s (symlink-safe exclusive-create temp, mode
56
+ * carried through the rename, parent directories created, temp
57
+ * removed on failure); this adds only the JSON encoding the call
58
+ * sites share. */
59
+ export declare function writeJsonAtomic(filePath: string, obj: unknown): Promise<void>;
60
+ //# sourceMappingURL=queueLock.d.ts.map
@@ -0,0 +1,198 @@
1
+
2
+ // pure move, zero logic changes — the queue.ts barrel re-exports
3
+ // every symbol, so the public surface is byte-identical).
4
+ //
5
+ // Erasable-syntax TS only (node --experimental-strip-types): no
6
+ // enums, import type for types, .ts specifiers for relative imports.
7
+ import { appendFileSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync, closeSync, } from "node:fs";
8
+ import { writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
9
+ import { join } from "node:path";
10
+ // ── constants (cites inline) ──────────────────────────────────
11
+ /** Lock file name under STATE_ROOT (acquire_lock 4416). */
12
+ export const LOCK_NAME = "gateway.lock";
13
+ /** Worker poll cadence (worker 1354: asyncio.sleep(0.05)). */
14
+ /** Registry bound (MAX_SETTLED_RUNS 2187: settled completed/failed
15
+ * rows past 500 leave; the sidecar stays SSOT). */
16
+ export const MAX_SETTLED_RUNS = 500;
17
+ /** Stage retries range (flow spec: retries 0..5). */
18
+ export const RETRIES_MAX = 5;
19
+ /** The stderr line main() prints before exit(1).
20
+ * NOTE the em-dash — byte-identical. */
21
+ export function refuseStartLine(note) {
22
+ return ("[gateway] REFUSING TO START: " + note + " — one writer per state root");
23
+ }
24
+ // ── roots (STATE_ROOT/OUT_ROOT/TEST_OUT_ROOT) ───
25
+
26
+
27
+
28
+
29
+ export function resolveStateRoot(config) {
30
+ const named = config.stateRoot ?? "";
31
+ if (named !== "")
32
+ return named;
33
+ return join(config.repoRoot ?? "", "data", "runs");
34
+ }
35
+ /** Run-dir root — TEST_OUT_ROOT on test:true else OUT_ROOT (L3). */
36
+ export function outRootFor(stateRoot, testFlag) {
37
+ return join(stateRoot, testFlag ? "test-output" : "output");
38
+ }
39
+ /** Append-only journal path (LEDGER_PATH 2180: OUT_ROOT/_ledger). */
40
+ export function ledgerPathFor(stateRoot) {
41
+ return join(stateRoot, "output", "_ledger.jsonl");
42
+ }
43
+ /** Lock path (acquire_lock 4416: STATE_ROOT/gateway.lock). */
44
+ export function lockPathFor(stateRoot) {
45
+ return join(stateRoot, LOCK_NAME);
46
+ }
47
+ /** Signal-0 probe (_pid_alive 4469-4479: ESRCH-dead false, EPERM
48
+ * still ALIVE — the whole point of the guard). */
49
+ export function isPidAlive(pid) {
50
+ try {
51
+ process.kill(pid, 0);
52
+ return true;
53
+ }
54
+ catch (exc) {
55
+ // (process.kill throws SystemErrors — always objects with .code.)
56
+ const code = String(exc.code);
57
+
58
+
59
+
60
+ if (code === "EPERM" || code === "EACCES")
61
+ return true;
62
+ return false;
63
+ }
64
+ }
65
+ function writePidFile(lockPath, pid) {
66
+ let fd = -1;
67
+ try {
68
+ fd = openSync(lockPath, "wx", 0o644);
69
+ }
70
+ catch {
71
+ return false;
72
+ }
73
+ try {
74
+ writeSync(fd, String(pid));
75
+
76
+
77
+ }
78
+ catch {
79
+ try {
80
+ closeSync(fd);
81
+ }
82
+ catch {
83
+ /* gone */
84
+ }
85
+ return false;
86
+ /* v8 ignore stop */
87
+ }
88
+ try {
89
+ closeSync(fd);
90
+ }
91
+ catch {
92
+ /* closed */
93
+ }
94
+ return true;
95
+ }
96
+ /** R2 single-writer: O_CREAT|O_EXCL acquire; on
97
+ * collision the holder pid decides — alive refuses loud (the
98
+ * caller exits before any boot side effect), dead-or-garbage
99
+ * steals (unlink + re-acquire, ledgered server.lock_stolen). */
100
+ export function acquireLock(stateRoot, pid = process.pid, nowS = Math.floor(Date.now() / 1000)) {
101
+ const lockPath = lockPathFor(stateRoot);
102
+ mkdirSync(stateRoot, { recursive: true });
103
+ if (writePidFile(lockPath, pid))
104
+ return { ok: true, note: "acquired" };
105
+ let holder = "";
106
+ try {
107
+ holder = readFileSync(lockPath, "utf8").trim();
108
+ }
109
+ catch {
110
+ holder = "";
111
+ }
112
+ let hpid = -1;
113
+ const parsed = Number(holder);
114
+ if (holder !== "" && Number.isInteger(parsed))
115
+ hpid = parsed;
116
+ if (hpid > 0 && isPidAlive(hpid)) {
117
+ return { ok: false, note: "gateway.lock held by live pid " + hpid };
118
+ }
119
+ try {
120
+ unlinkSync(lockPath);
121
+ }
122
+ catch {
123
+ /* already gone */
124
+ }
125
+ appendLedger(stateRoot, "server.lock_stolen", { stale_pid: hpid }, nowS);
126
+ if (writePidFile(lockPath, pid)) {
127
+ return { ok: true, note: "stolen from dead pid " + hpid };
128
+ }
129
+ return { ok: false, note: "lock steal failed: " + lockPath };
130
+ }
131
+ /** PID-CHECKED release (release_lock 4450-4468): a boot that never
132
+ * owned the lock frees only its OWN, never the live holder's (the
133
+ * watcher-storm lesson — a blind unlink let each retry steal +
134
+ * boot-sweep LIVE runs). */
135
+ export function releaseLock(stateRoot, pid = process.pid) {
136
+ const lockPath = lockPathFor(stateRoot);
137
+ let holder = "";
138
+ try {
139
+ holder = readFileSync(lockPath, "utf8").trim();
140
+ }
141
+ catch {
142
+ return false;
143
+ }
144
+ if (holder !== String(pid))
145
+ return false;
146
+ try {
147
+ unlinkSync(lockPath);
148
+ }
149
+ catch {
150
+ return false;
151
+ }
152
+ return true;
153
+ }
154
+ /** Pre-boot gate (main 4474-4480): acquire BEFORE any boot side
155
+ * effect — resurrection, sweep, worker, listen. A second writer
156
+ * exits here, loud, having touched nothing (but the steal ledger
157
+ * row, when it stole from the dead). */
158
+ export function bootGate(stateRoot, pid = process.pid) {
159
+ return acquireLock(stateRoot, pid);
160
+ }
161
+ // ── journal + atomic write ────────────────
162
+ /** Journal data writer: canonical JSON, UTF-8. */
163
+ export function dumpsLedgerData(data) {
164
+ // (data is a record — JSON.stringify never yields undefined here.)
165
+ return JSON.stringify(data);
166
+ }
167
+ /** Append-only activity journal: one JSON object per line,
168
+ * close-per-line (durable), mkdir-parents, NEVER throws.
169
+ * Line shape: {ts, event, data} — compact envelope. */
170
+ export function appendLedger(stateRoot, event, data = null, nowS = Math.floor(Date.now() / 1000)) {
171
+ try {
172
+ const outRoot = join(stateRoot, "output");
173
+ mkdirSync(outRoot, { recursive: true });
174
+ appendFileSync(join(outRoot, "_ledger.jsonl"), '{"ts":' +
175
+ nowS +
176
+ ',"event":' +
177
+ JSON.stringify(event) +
178
+ ',"data":' +
179
+ dumpsLedgerData(data ?? {}) +
180
+ "}\n", "utf8");
181
+ }
182
+ catch {
183
+ /* the journal must never take the queue down */
184
+ }
185
+ }
186
+ /** The permission bits the queue's own files carry — the lock file
187
+ * opens at `0o644`, so its data files match it. */
188
+ const QUEUE_FILE_MODE = 0o644;
189
+ /** Atomic indent-2 JSON write — the atomicity is
190
+ * `writeFileAtomic`'s (symlink-safe exclusive-create temp, mode
191
+ * carried through the rename, parent directories created, temp
192
+ * removed on failure); this adds only the JSON encoding the call
193
+ * sites share. */
194
+ export async function writeJsonAtomic(filePath, obj) {
195
+ const text = JSON.stringify(obj, null, 2) ?? "null";
196
+ await writeFileAtomic(filePath, text, { mode: QUEUE_FILE_MODE });
197
+ }
198
+ //# sourceMappingURL=queueLock.js.map
@@ -0,0 +1,59 @@
1
+ import type { RunId } from "./queueCore.js";
2
+ export interface ResurrectPlan {
3
+ /** run_ids to re-queue, FIFO by created_at (order survives). */
4
+ readonly order: RunId[];
5
+ /** run_ids swept below (orphans / half-written). */
6
+ readonly orphans: string[];
7
+ }
8
+ /** input_from refs for a NodeRow: arrays ride element-wise;
9
+ * falsy rides []; anything else is the raise road (the caller
10
+ * orphans the record). */
11
+ export declare function refList(value: unknown): unknown[] | null;
12
+ /** entries for the row maps: plain objects ride their entries;
13
+ * falsy rides {}; anything else is the raise road. */
14
+ export declare function recordEntries(value: unknown): [string, unknown][] | null;
15
+ /** One graph row usable: id/type are non-empty strings;
16
+ * input_from rides refList with every ref a non-blank string;
17
+ * input_names/outputs ride recordEntries with string values;
18
+ * duplicate node ids refuse. seen carries the gate across rows. */
19
+ export declare function nodeRowUsable(row: unknown, seen: Set<string>): boolean;
20
+ /** The durable graph check (doc.get("graph") or [] 2324): falsy
21
+ * (missing/None/False/0/"") rides the empty FlowGraph — zero nodes
22
+ * construct fine, so the record resurrects; a truthy non-list dies
23
+ * iterating (strings/dicts/numbers orphan); every row must be
24
+ * NodeRow-usable (extra keys ignored, mistypes orphan). */
25
+ export declare function graphRowsUsable(graph: unknown): boolean;
26
+ /** list coerce for stages/skipped: arrays ride; falsy rides [];
27
+ * anything else throws (the raise road: plan + build agree on the
28
+ * skip, never throw out). */
29
+ export declare function sidecarList(value: unknown): unknown[];
30
+ /** artifact names: the sidecar list filtered to non-empty strings. */
31
+ export declare function artifactStrings(value: unknown): string[];
32
+ /** created_at coerce: finite numbers ride; numeric strings parse;
33
+ * everything else rides 0 and never throws (boot order for
34
+ * records without a usable timestamp). */
35
+ export declare function coerceCreatedAt(value: unknown): number;
36
+
37
+
38
+
39
+
40
+
41
+ export declare function durableRecordUsable(sidecarText: string, requestText: string, draftExists: boolean): boolean;
42
+ /** Plan the resurrect (fs reads + order; the caller appends +
43
+ * ledgers, or use bootResurrect below for the whole seam). */
44
+ export declare function planResurrect(stateRoot: string, readSidecar?: (runId: string) => string | null, readRequest?: (runId: string) => string | null, draftExists?: (draftId: string) => boolean): ResurrectPlan;
45
+ /** The state-root triple every boot seam takes (server.ts
46
+ * bootState passes defaultAssetRoots through; the canonical layout
47
+ * is runsRoot == stateRoot/output and ledgerPath ==
48
+ * runsRoot/_ledger.jsonl — the core derives both from stateRoot,
49
+ * so a non-canonical triple is honored for READS and canonical
50
+ * for WRITES, documented at the service's bootReconcile). */
51
+ export interface QueueRoots {
52
+ readonly stateRoot: string;
53
+ readonly runsRoot: string;
54
+ readonly ledgerPath: string;
55
+ }
56
+ /** One rebuilt queued run — RETIRED (stroke 83): the hollow
57
+ * requeue road is deleted; the service's bootReconcile REPLAYS _request.json
58
+ * through the start door so revived rows carry REAL params. */
59
+ //# sourceMappingURL=queueResurrect.d.ts.map