@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,124 @@
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 ==
89
+ * completed|failed ONLY (stopped rows stay — a deliberate stop
90
+ * is a live receipt, not garbage); past 500 the oldest
91
+ * created_at leaves first. Returns evicted ids. */
92
+ evictSettled() {
93
+ const settled = [...this.runs.values()].filter((r) => r.status === "completed" || r.status === "failed");
94
+ const excess = settled.length - MAX_SETTLED_RUNS;
95
+ if (excess <= 0)
96
+ return [];
97
+ settled.sort((a, b) => a.createdAt - b.createdAt === 0
98
+ ? (a.runId < b.runId ? -1 : 1)
99
+ : a.createdAt - b.createdAt);
100
+ const evicted = [];
101
+ for (const r of settled.slice(0, excess)) {
102
+ this.runs.delete(r.runId);
103
+ evicted.push(r.runId);
104
+ }
105
+ return evicted;
106
+ }
107
+ }
108
+ /** run-<12hex>-<8hex> ids (submit 1267: uuid4 hex + time-ms low 32).
109
+ * The mint is one of the brand's two producers; the return cast is
110
+ * the construction door. */
111
+ export function newRunId() {
112
+ const rand = randomBytes(6).toString("hex");
113
+ const ts = ((Date.now() & 0xffffffff) >>> 0)
114
+ .toString(16)
115
+ .padStart(8, "0");
116
+ return "run-" + rand + "-" + ts;
117
+ }
118
+ /** The terminal broadcast frame (worker 1413-1414): every
119
+ * subscriber gets the final status exactly once. Shape pinned
120
+ * here so the P6 bus port inherits it. */
121
+ export function terminalFrame(status) {
122
+ return { type: "run", status };
123
+ }
124
+ //# sourceMappingURL=queueCore.js.map
@@ -0,0 +1,26 @@
1
+ import type { QueueRefusal } from "./queueSubmit.js";
2
+ export type LifecycleState = "queued" | "running" | "completed" | "failed" | "stopped" | "stopping";
3
+ /** stop, unknown run (Gateway.stop 2042-2045). */
4
+ export declare function refuseUnknownStop(runId: string): QueueRefusal;
5
+ /** stop, settled run: 200 with error ONLY (no code
6
+ * the dispatcher normalizes 4xx alone, and this is a 200). */
7
+ export declare function refuseTerminalStop(state: string): QueueRefusal;
8
+ /** resume, live run (resume 1919-1925). */
9
+ export declare function refuseLiveResume(runId: string, liveStatus: string): QueueRefusal;
10
+ /** resume/reproduce, no durable record (1930-1932 / 2011-2014). */
11
+ export declare function refuseNoDurableRecord(runId: string): QueueRefusal;
12
+ /** resume, completed run. */
13
+ export declare function refuseCompletedResume(runId: string): QueueRefusal;
14
+ /** resume, neither failed nor stopped. */
15
+ export declare function refuseUnresumable(runId: string, status: string): QueueRefusal;
16
+ /** resume, draft gone or half-written. */
17
+ export declare function refuseUnusableRecord(runId: string): QueueRefusal;
18
+ /** reproduce, live run. */
19
+ export declare function refuseLiveReproduce(runId: string, liveStatus: string): QueueRefusal;
20
+ /** reproduce, cardless legacy row. */
21
+ export declare function refuseCardlessReplay(runId: string): QueueRefusal;
22
+ /** reproduce, request body missing. */
23
+ export declare function refuseMissingRequest(runId: string): QueueRefusal;
24
+ /** reproduce, request non-object. */
25
+ export declare function refuseNonObjectRequest(runId: string, gotType: string): QueueRefusal;
26
+ //# sourceMappingURL=queueLifecycle.d.ts.map
@@ -0,0 +1,65 @@
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 { refusal } from "./queueSubmit.js";
8
+ /** stop, unknown run (Gateway.stop 2042-2045). */
9
+ export function refuseUnknownStop(runId) {
10
+ return refusal(400, "unknown run_id " + JSON.stringify(runId), "run_unknown", "run_id");
11
+ }
12
+ /** stop, settled run: 200 with error ONLY (no code
13
+ * the dispatcher normalizes 4xx alone, and this is a 200). */
14
+ export function refuseTerminalStop(state) {
15
+ return {
16
+ status: 200,
17
+ payload: { error: "cannot stop run in state " + state },
18
+ };
19
+ }
20
+ /** resume, live run (resume 1919-1925). */
21
+ export function refuseLiveResume(runId, liveStatus) {
22
+ return refusal(400, "run " + runId + " is still " + liveStatus + " — stop it before resuming", "run_live", "run_id", "failed|stopped", liveStatus);
23
+ }
24
+ /** resume/reproduce, no durable record (1930-1932 / 2011-2014). */
25
+ export function refuseNoDurableRecord(runId) {
26
+ return refusal(400, "no durable record for run " + JSON.stringify(runId), "run_unknown", "run_id");
27
+ }
28
+ /** resume, completed run. */
29
+ export function refuseCompletedResume(runId) {
30
+ return refusal(400, "run " + runId + " completed — nothing to resume", "run_completed", "run_id", "failed|stopped", "completed");
31
+ }
32
+ /** resume, neither failed nor stopped. */
33
+ export function refuseUnresumable(runId, status) {
34
+ const got = status === "" ? "unknown" : status;
35
+ return refusal(400, "run " + runId + " is " + JSON.stringify(got) + " — resume needs failed or stopped", "run_not_resumable", "run_id", "failed|stopped", got);
36
+ }
37
+ /** resume, draft gone or half-written. */
38
+ export function refuseUnusableRecord(runId) {
39
+ return refusal(400, "run " +
40
+ runId +
41
+ " record is unusable (draft doc gone or half-written) — resubmit instead", "run_record_unusable", "run_id");
42
+ }
43
+ /** reproduce, live run. */
44
+ export function refuseLiveReproduce(runId, liveStatus) {
45
+ return refusal(400, "run " +
46
+ runId +
47
+ " is still " +
48
+ liveStatus +
49
+ " — wait for it to settle or stop it first", "run_live", "run_id", "completed|failed|stopped", liveStatus);
50
+ }
51
+ /** reproduce, cardless legacy row. */
52
+ export function refuseCardlessReplay(runId) {
53
+ return refusal(400, "run " +
54
+ runId +
55
+ " is a cardless legacy row (no draft_id) — compose a fresh card to replay it", "run_cardless", "draft_id", "doc-backed draft id", "absent");
56
+ }
57
+ /** reproduce, request body missing. */
58
+ export function refuseMissingRequest(runId) {
59
+ return refusal(400, "run " + runId + " has no recorded request body — cannot replay", "run_record_unusable", "run_id");
60
+ }
61
+ /** reproduce, request non-object. */
62
+ export function refuseNonObjectRequest(runId, gotType) {
63
+ return refusal(400, "run " + runId + " recorded a non-object request body", "run_record_unusable", "run_id", "object", gotType);
64
+ }
65
+ //# sourceMappingURL=queueLifecycle.js.map
@@ -0,0 +1,54 @@
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
+ /** State root — MELITE_STATE_ROOT else <repo>/data/runs. */
13
+ export declare function resolveStateRoot(repoRoot: string): string;
14
+ /** Run-dir root — TEST_OUT_ROOT on test:true else OUT_ROOT (L3). */
15
+ export declare function outRootFor(stateRoot: string, testFlag: boolean): string;
16
+ /** Append-only journal path (LEDGER_PATH 2180: OUT_ROOT/_ledger). */
17
+ export declare function ledgerPathFor(stateRoot: string): string;
18
+ /** Lock path (acquire_lock 4416: STATE_ROOT/gateway.lock). */
19
+ export declare function lockPathFor(stateRoot: string): string;
20
+ export interface LockResult {
21
+ readonly ok: boolean;
22
+ readonly note: string;
23
+ }
24
+ /** Signal-0 probe (_pid_alive 4469-4479: ESRCH-dead false, EPERM
25
+ * still ALIVE — the whole point of the guard). */
26
+ export declare function isPidAlive(pid: number): boolean;
27
+ /** R2 single-writer: O_CREAT|O_EXCL acquire; on
28
+ * collision the holder pid decides — alive refuses loud (the
29
+ * caller exits before any boot side effect), dead-or-garbage
30
+ * steals (unlink + re-acquire, ledgered server.lock_stolen). */
31
+ export declare function acquireLock(stateRoot: string, pid?: number, nowS?: number): LockResult;
32
+ /** PID-CHECKED release (release_lock 4450-4468): a boot that never
33
+ * owned the lock frees only its OWN, never the live holder's (the
34
+ * watcher-storm lesson — a blind unlink let each retry steal +
35
+ * boot-sweep LIVE runs). */
36
+ export declare function releaseLock(stateRoot: string, pid?: number): boolean;
37
+ /** Pre-boot gate (main 4474-4480): acquire BEFORE any boot side
38
+ * effect — resurrection, sweep, worker, listen. A second writer
39
+ * exits here, loud, having touched nothing (but the steal ledger
40
+ * row, when it stole from the dead). */
41
+ export declare function bootGate(stateRoot: string, pid?: number): LockResult;
42
+ /** Journal data writer: canonical JSON, UTF-8. */
43
+ export declare function dumpsLedgerData(data: Record<string, unknown>): string;
44
+ /** Append-only activity journal: one JSON object per line,
45
+ * close-per-line (durable), mkdir-parents, NEVER throws.
46
+ * Line shape: {ts, event, data} — compact envelope. */
47
+ export declare function appendLedger(stateRoot: string, event: string, data?: Record<string, unknown> | null, nowS?: number): void;
48
+ /** Atomic indent-2 JSON write — the atomicity is
49
+ * `writeFileAtomic`'s (symlink-safe exclusive-create temp, mode
50
+ * carried through the rename, parent directories created, temp
51
+ * removed on failure); this adds only the JSON encoding the call
52
+ * sites share. */
53
+ export declare function writeJsonAtomic(filePath: string, obj: unknown): Promise<void>;
54
+ //# sourceMappingURL=queueLock.d.ts.map
@@ -0,0 +1,195 @@
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
+ /** State root — MELITE_STATE_ROOT else <repo>/data/runs. */
26
+ export function resolveStateRoot(repoRoot) {
27
+ const override = process.env["MELITE_STATE_ROOT"] ?? "";
28
+ if (override !== "")
29
+ return override;
30
+ return join(repoRoot, "data", "runs");
31
+ }
32
+ /** Run-dir root — TEST_OUT_ROOT on test:true else OUT_ROOT (L3). */
33
+ export function outRootFor(stateRoot, testFlag) {
34
+ return join(stateRoot, testFlag ? "test-output" : "output");
35
+ }
36
+ /** Append-only journal path (LEDGER_PATH 2180: OUT_ROOT/_ledger). */
37
+ export function ledgerPathFor(stateRoot) {
38
+ return join(stateRoot, "output", "_ledger.jsonl");
39
+ }
40
+ /** Lock path (acquire_lock 4416: STATE_ROOT/gateway.lock). */
41
+ export function lockPathFor(stateRoot) {
42
+ return join(stateRoot, LOCK_NAME);
43
+ }
44
+ /** Signal-0 probe (_pid_alive 4469-4479: ESRCH-dead false, EPERM
45
+ * still ALIVE — the whole point of the guard). */
46
+ export function isPidAlive(pid) {
47
+ try {
48
+ process.kill(pid, 0);
49
+ return true;
50
+ }
51
+ catch (exc) {
52
+ // (process.kill throws SystemErrors — always objects with .code.)
53
+ const code = String(exc.code);
54
+
55
+
56
+
57
+ if (code === "EPERM" || code === "EACCES")
58
+ return true;
59
+ return false;
60
+ }
61
+ }
62
+ function writePidFile(lockPath, pid) {
63
+ let fd = -1;
64
+ try {
65
+ fd = openSync(lockPath, "wx", 0o644);
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ try {
71
+ writeSync(fd, String(pid));
72
+
73
+
74
+ }
75
+ catch {
76
+ try {
77
+ closeSync(fd);
78
+ }
79
+ catch {
80
+ /* gone */
81
+ }
82
+ return false;
83
+ /* v8 ignore stop */
84
+ }
85
+ try {
86
+ closeSync(fd);
87
+ }
88
+ catch {
89
+ /* closed */
90
+ }
91
+ return true;
92
+ }
93
+ /** R2 single-writer: O_CREAT|O_EXCL acquire; on
94
+ * collision the holder pid decides — alive refuses loud (the
95
+ * caller exits before any boot side effect), dead-or-garbage
96
+ * steals (unlink + re-acquire, ledgered server.lock_stolen). */
97
+ export function acquireLock(stateRoot, pid = process.pid, nowS = Math.floor(Date.now() / 1000)) {
98
+ const lockPath = lockPathFor(stateRoot);
99
+ mkdirSync(stateRoot, { recursive: true });
100
+ if (writePidFile(lockPath, pid))
101
+ return { ok: true, note: "acquired" };
102
+ let holder = "";
103
+ try {
104
+ holder = readFileSync(lockPath, "utf8").trim();
105
+ }
106
+ catch {
107
+ holder = "";
108
+ }
109
+ let hpid = -1;
110
+ const parsed = Number(holder);
111
+ if (holder !== "" && Number.isInteger(parsed))
112
+ hpid = parsed;
113
+ if (hpid > 0 && isPidAlive(hpid)) {
114
+ return { ok: false, note: "gateway.lock held by live pid " + hpid };
115
+ }
116
+ try {
117
+ unlinkSync(lockPath);
118
+ }
119
+ catch {
120
+ /* already gone */
121
+ }
122
+ appendLedger(stateRoot, "server.lock_stolen", { stale_pid: hpid }, nowS);
123
+ if (writePidFile(lockPath, pid)) {
124
+ return { ok: true, note: "stolen from dead pid " + hpid };
125
+ }
126
+ return { ok: false, note: "lock steal failed: " + lockPath };
127
+ }
128
+ /** PID-CHECKED release (release_lock 4450-4468): a boot that never
129
+ * owned the lock frees only its OWN, never the live holder's (the
130
+ * watcher-storm lesson — a blind unlink let each retry steal +
131
+ * boot-sweep LIVE runs). */
132
+ export function releaseLock(stateRoot, pid = process.pid) {
133
+ const lockPath = lockPathFor(stateRoot);
134
+ let holder = "";
135
+ try {
136
+ holder = readFileSync(lockPath, "utf8").trim();
137
+ }
138
+ catch {
139
+ return false;
140
+ }
141
+ if (holder !== String(pid))
142
+ return false;
143
+ try {
144
+ unlinkSync(lockPath);
145
+ }
146
+ catch {
147
+ return false;
148
+ }
149
+ return true;
150
+ }
151
+ /** Pre-boot gate (main 4474-4480): acquire BEFORE any boot side
152
+ * effect — resurrection, sweep, worker, listen. A second writer
153
+ * exits here, loud, having touched nothing (but the steal ledger
154
+ * row, when it stole from the dead). */
155
+ export function bootGate(stateRoot, pid = process.pid) {
156
+ return acquireLock(stateRoot, pid);
157
+ }
158
+ // ── journal + atomic write ────────────────
159
+ /** Journal data writer: canonical JSON, UTF-8. */
160
+ export function dumpsLedgerData(data) {
161
+ // (data is a record — JSON.stringify never yields undefined here.)
162
+ return JSON.stringify(data);
163
+ }
164
+ /** Append-only activity journal: one JSON object per line,
165
+ * close-per-line (durable), mkdir-parents, NEVER throws.
166
+ * Line shape: {ts, event, data} — compact envelope. */
167
+ export function appendLedger(stateRoot, event, data = null, nowS = Math.floor(Date.now() / 1000)) {
168
+ try {
169
+ const outRoot = join(stateRoot, "output");
170
+ mkdirSync(outRoot, { recursive: true });
171
+ appendFileSync(join(outRoot, "_ledger.jsonl"), '{"ts":' +
172
+ nowS +
173
+ ',"event":' +
174
+ JSON.stringify(event) +
175
+ ',"data":' +
176
+ dumpsLedgerData(data ?? {}) +
177
+ "}\n", "utf8");
178
+ }
179
+ catch {
180
+ /* the journal must never take the queue down */
181
+ }
182
+ }
183
+ /** The permission bits the queue's own files carry — the lock file
184
+ * opens at `0o644`, so its data files match it. */
185
+ const QUEUE_FILE_MODE = 0o644;
186
+ /** Atomic indent-2 JSON write — the atomicity is
187
+ * `writeFileAtomic`'s (symlink-safe exclusive-create temp, mode
188
+ * carried through the rename, parent directories created, temp
189
+ * removed on failure); this adds only the JSON encoding the call
190
+ * sites share. */
191
+ export async function writeJsonAtomic(filePath, obj) {
192
+ const text = JSON.stringify(obj, null, 2) ?? "null";
193
+ await writeFileAtomic(filePath, text, { mode: QUEUE_FILE_MODE });
194
+ }
195
+ //# 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