@h1r-ai/croche 0.0.0-stage → 0.5.0

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 (86) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +1176 -2
  3. package/THIRD-PARTY-NOTICES +5824 -0
  4. package/dist/archive.d.ts +47 -0
  5. package/dist/archive.js +217 -0
  6. package/dist/atomic-replace.d.ts +18 -0
  7. package/dist/atomic-replace.js +39 -0
  8. package/dist/commands.d.ts +56 -0
  9. package/dist/commands.js +1 -0
  10. package/dist/control.d.ts +62 -0
  11. package/dist/control.js +269 -0
  12. package/dist/core-abi.d.ts +110 -0
  13. package/dist/core-abi.js +1 -0
  14. package/dist/core-bindgen.d.ts +413 -0
  15. package/dist/core-bindgen.js +1533 -0
  16. package/dist/core-runtime.d.ts +214 -0
  17. package/dist/core-runtime.js +837 -0
  18. package/dist/core-wasm-bytes.d.ts +4 -0
  19. package/dist/core-wasm-bytes.js +5 -0
  20. package/dist/core-wasm.d.ts +16 -0
  21. package/dist/core-wasm.js +63 -0
  22. package/dist/debug.d.ts +26 -0
  23. package/dist/debug.js +171 -0
  24. package/dist/file-lock.d.ts +46 -0
  25. package/dist/file-lock.js +300 -0
  26. package/dist/images.d.ts +53 -0
  27. package/dist/images.js +179 -0
  28. package/dist/index.d.ts +14 -0
  29. package/dist/index.js +9 -0
  30. package/dist/markers.d.ts +1 -0
  31. package/dist/markers.js +1 -0
  32. package/dist/node.d.ts +46 -0
  33. package/dist/node.js +281 -0
  34. package/dist/project-core.d.ts +79 -0
  35. package/dist/project-core.js +261 -0
  36. package/dist/project-session.d.ts +44 -0
  37. package/dist/project-session.js +143 -0
  38. package/dist/project-types.d.ts +97 -0
  39. package/dist/project-types.js +1 -0
  40. package/dist/project-wire.d.ts +19 -0
  41. package/dist/project-wire.js +39 -0
  42. package/dist/sse.d.ts +19 -0
  43. package/dist/sse.js +53 -0
  44. package/dist/storage.d.ts +24 -0
  45. package/dist/storage.js +32 -0
  46. package/dist/stream-branch.d.ts +47 -0
  47. package/dist/stream-branch.js +107 -0
  48. package/dist/stream-hub.d.ts +207 -0
  49. package/dist/stream-hub.js +210 -0
  50. package/dist/stream.d.ts +3 -0
  51. package/dist/stream.js +5 -0
  52. package/dist/types.d.ts +930 -0
  53. package/dist/types.js +8 -0
  54. package/dist/wiki.d.ts +15 -0
  55. package/dist/wiki.js +25 -0
  56. package/docs/CODING-AGENT.md +92 -0
  57. package/docs/DEBUGGER.md +230 -0
  58. package/docs/S2-IMPLEMENTATION.md +585 -0
  59. package/docs/SKILL.md +295 -0
  60. package/package.json +52 -4
  61. package/src/archive.ts +188 -0
  62. package/src/atomic-replace.ts +43 -0
  63. package/src/commands.ts +62 -0
  64. package/src/control.ts +179 -0
  65. package/src/core-abi.ts +52 -0
  66. package/src/core-bindgen.ts +1557 -0
  67. package/src/core-runtime.ts +750 -0
  68. package/src/core-wasm-bytes.ts +5 -0
  69. package/src/core-wasm.ts +57 -0
  70. package/src/debug.ts +160 -0
  71. package/src/file-lock.ts +269 -0
  72. package/src/images.ts +174 -0
  73. package/src/index.ts +15 -0
  74. package/src/markers.ts +1 -0
  75. package/src/node.ts +194 -0
  76. package/src/project-core.ts +231 -0
  77. package/src/project-session.ts +118 -0
  78. package/src/project-types.ts +77 -0
  79. package/src/project-wire.ts +39 -0
  80. package/src/sse.ts +57 -0
  81. package/src/storage.ts +30 -0
  82. package/src/stream-branch.ts +112 -0
  83. package/src/stream-hub.ts +249 -0
  84. package/src/stream.ts +7 -0
  85. package/src/types.ts +840 -0
  86. package/src/wiki.ts +25 -0
@@ -0,0 +1,16 @@
1
+ import type { CoreInput, CoreOutput } from './core-abi.js';
2
+ import { CORE_WASM_SHA256 } from './core-wasm-bytes.js';
3
+ import * as bindgen from './core-bindgen.js';
4
+ export { CORE_WASM_SHA256 };
5
+ export declare const CORE_ABI_VERSION = 1;
6
+ /** The shared Rust Core (wasm-bindgen), instantiated once from the embedded bytes. */
7
+ export declare function core(): typeof bindgen;
8
+ /** The entire semantic transition crosses this ABI; there is no TypeScript fallback engine. */
9
+ export declare function coreStep(input: CoreInput): CoreOutput;
10
+ /** Strong host entropy, not a replacement for the Core's identity or policy logic. */
11
+ export declare function coreNonce(): string;
12
+ export declare function parseCoreMarkers(raw: string): {
13
+ raw: string;
14
+ text: string;
15
+ markers: string[];
16
+ };
@@ -0,0 +1,63 @@
1
+ import { CrocheError } from './types.js';
2
+ import { CORE_WASM_BASE64, CORE_WASM_SHA256 } from './core-wasm-bytes.js';
3
+ import * as bindgen from './core-bindgen.js';
4
+ export { CORE_WASM_SHA256 };
5
+ export const CORE_ABI_VERSION = 1;
6
+ let loaded = false;
7
+ const MAX_ABI_BYTES = 32 * 1024 * 1024;
8
+ /** The shared Rust Core (wasm-bindgen), instantiated once from the embedded bytes. */
9
+ export function core() {
10
+ if (loaded)
11
+ return bindgen;
12
+ if (typeof WebAssembly === 'undefined') {
13
+ throw new CrocheError('core_unavailable', 'This host needs WebAssembly or a native Croche Core binding.');
14
+ }
15
+ try {
16
+ const binary = Uint8Array.from(atob(CORE_WASM_BASE64), value => value.charCodeAt(0));
17
+ // Embedded at package build time: installed consumers need no Rust compiler, asset URL,
18
+ // network fetch, eval(), or generated JavaScript functions.
19
+ bindgen.initSync({ module: new WebAssembly.Module(binary) });
20
+ loaded = true;
21
+ return bindgen;
22
+ }
23
+ catch {
24
+ throw new CrocheError('core_unavailable', "Unable to load the shared Rust Core. A browser CSP must allow 'wasm-unsafe-eval' in script-src.");
25
+ }
26
+ }
27
+ /** The entire semantic transition crosses this ABI; there is no TypeScript fallback engine. */
28
+ export function coreStep(input) {
29
+ let text;
30
+ try {
31
+ text = JSON.stringify(input);
32
+ }
33
+ catch {
34
+ throw new CrocheError('invalid_input', 'Core inputs must be JSON serializable.');
35
+ }
36
+ if (text.length > MAX_ABI_BYTES)
37
+ throw new CrocheError('store_full', 'Core state and input exceed the 32 MiB ABI limit.');
38
+ const step = core().step;
39
+ try {
40
+ const output = JSON.parse(step(text));
41
+ if (output.abi !== 2)
42
+ throw new Error('Unsupported Core ABI');
43
+ return output;
44
+ }
45
+ catch {
46
+ throw new CrocheError('core_error', 'The shared Rust Core could not complete its transition. Reopen from durable storage.');
47
+ }
48
+ }
49
+ /** Strong host entropy, not a replacement for the Core's identity or policy logic. */
50
+ export function coreNonce() {
51
+ if (globalThis.crypto?.randomUUID)
52
+ return globalThis.crypto.randomUUID();
53
+ if (!globalThis.crypto?.getRandomValues)
54
+ throw new CrocheError('host_unavailable', 'The host must provide cryptographically secure random values.');
55
+ return Array.from(crypto.getRandomValues(new Uint8Array(16)), value => value.toString(16).padStart(2, '0')).join('');
56
+ }
57
+ export function parseCoreMarkers(raw) {
58
+ const output = coreStep({ abi: 2, config: {}, state: null, machine: null, command: { type: 'parse_markers', raw }, now: new Date().toISOString(), nonce: coreNonce() });
59
+ if (output.error)
60
+ throw new CrocheError(output.error.code, output.error.message);
61
+ const { raw: original, text, markers } = output.result;
62
+ return { raw: original, text, markers };
63
+ }
@@ -0,0 +1,26 @@
1
+ import type { RuntimeDebugEvent } from './types.js';
2
+ export type { RuntimeDebugEvent, RuntimeStateData } from './types.js';
3
+ export interface LocalDebuggerOptions {
4
+ url?: string;
5
+ /** Local collector pairing token, unrelated to Cloud/provider credentials. */
6
+ token: string;
7
+ appName?: string;
8
+ /** Optional transport injection for tests or host networking adapters. */
9
+ fetch?: typeof fetch;
10
+ }
11
+ export interface DebugDeliveryStatus {
12
+ sent: number;
13
+ dropped: number;
14
+ pending: number;
15
+ droppedByReason: Record<string, number>;
16
+ lastError?: string;
17
+ }
18
+ export interface LocalDebugger {
19
+ onEvent(event: RuntimeDebugEvent): void;
20
+ /** Wait for one best-effort delivery of currently queued events; never retries. */
21
+ flush(): Promise<DebugDeliveryStatus>;
22
+ /** Stop accepting events and settle the remaining bounded queue. */
23
+ close(): Promise<DebugDeliveryStatus>;
24
+ }
25
+ /** Browser-compatible, development-only local trace transport. Never used by default. */
26
+ export declare function createLocalDebugger(options: LocalDebuggerOptions): LocalDebugger;
package/dist/debug.js ADDED
@@ -0,0 +1,171 @@
1
+ const MAX_EVENT_BYTES = 128 * 1024;
2
+ const MAX_BATCH_BYTES = 1024 * 1024;
3
+ const MAX_QUEUE_BYTES = 4 * 1024 * 1024;
4
+ const MAX_QUEUE_EVENTS = 500;
5
+ const MAX_BATCH_EVENTS = 100;
6
+ const FLUSH_INTERVAL_MS = 100;
7
+ const REQUEST_TIMEOUT_MS = 2000;
8
+ /** Browser-compatible, development-only local trace transport. Never used by default. */
9
+ export function createLocalDebugger(options) {
10
+ const base = new URL(options.url ?? 'http://127.0.0.1:8790');
11
+ if (!['http:', 'https:'].includes(base.protocol) || !['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname) ||
12
+ base.username || base.password || base.search || base.hash || !['', '/'].includes(base.pathname)) {
13
+ throw new Error('The local debugger URL must be a loopback HTTP(S) origin without credentials or a path.');
14
+ }
15
+ if (!options.token || options.token.length > 4096 || /[\r\n]/.test(options.token))
16
+ throw new Error('A valid local debugger pairing token is required.');
17
+ if (options.appName !== undefined && (typeof options.appName !== 'string' || options.appName.length > 200))
18
+ throw new Error('Debugger appName must contain at most 200 characters.');
19
+ const endpoint = `${base.origin}/api/events`;
20
+ const sourceId = globalThis.crypto.randomUUID();
21
+ const token = options.token;
22
+ const appName = options.appName;
23
+ const transport = options.fetch ?? globalThis.fetch.bind(globalThis);
24
+ const encoder = new TextEncoder();
25
+ const queue = [];
26
+ let queueBytes = 0;
27
+ let sent = 0;
28
+ let dropped = 0;
29
+ let reportedDrops = 0;
30
+ const droppedByReason = {};
31
+ let lastError;
32
+ let closed = false;
33
+ let timer;
34
+ let active;
35
+ let closing;
36
+ const status = () => ({ sent, dropped, pending: queue.length, droppedByReason: { ...droppedByReason }, ...(lastError ? { lastError } : {}) });
37
+ const drop = (count, reason) => {
38
+ dropped += count;
39
+ droppedByReason[reason] = (droppedByReason[reason] ?? 0) + count;
40
+ };
41
+ const schedule = (includeDrops = false) => {
42
+ if (closed || timer || active || (!queue.length && !(includeDrops && dropped > reportedDrops)))
43
+ return;
44
+ timer = setTimeout(() => { timer = undefined; void flush(); }, FLUSH_INTERVAL_MS);
45
+ timer.unref?.();
46
+ };
47
+ const deliver = async () => {
48
+ // Bound one flush even if a busy Runtime continuously emits more diagnostics.
49
+ let remaining = queue.length;
50
+ let metadataOnly = remaining === 0 && dropped > reportedDrops;
51
+ while ((remaining > 0 && queue.length > 0) || metadataOnly) {
52
+ const batch = [];
53
+ let bytes = 4096; // Envelope/drop metadata and punctuation allowance.
54
+ while (queue.length && batch.length < MAX_BATCH_EVENTS && remaining > 0 && bytes + queue[0].bytes < MAX_BATCH_BYTES) {
55
+ const event = queue.shift();
56
+ queueBytes -= event.bytes;
57
+ remaining--;
58
+ batch.push(event);
59
+ bytes += event.bytes + 1;
60
+ }
61
+ if (!batch.length && !metadataOnly)
62
+ break;
63
+ metadataOnly = false;
64
+ const dropCount = dropped;
65
+ const dropMetadata = dropCount > reportedDrops ? `,"dropped":${JSON.stringify({ sourceId, events: dropCount, reasons: droppedByReason })}` : '';
66
+ const body = `{"events":[${batch.map(event => event.json).join(',')}]${dropMetadata}}`;
67
+ const controller = new AbortController();
68
+ let requestTimeout;
69
+ try {
70
+ const timeout = new Promise((_, reject) => {
71
+ requestTimeout = setTimeout(() => { controller.abort(); reject(new Error('timeout')); }, REQUEST_TIMEOUT_MS);
72
+ });
73
+ const response = await Promise.race([transport(endpoint, {
74
+ method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
75
+ body, signal: controller.signal, credentials: 'omit', redirect: 'error',
76
+ }), timeout]);
77
+ if (!response.ok) {
78
+ lastError = `http_${response.status}`;
79
+ drop(batch.length, 'delivery_failed');
80
+ }
81
+ else {
82
+ const acknowledgement = await Promise.race([response.json(), timeout]);
83
+ if (!Array.isArray(acknowledgement.accepted) || !Array.isArray(acknowledgement.duplicate)) {
84
+ lastError = 'invalid_acknowledgement';
85
+ drop(batch.length, 'delivery_failed');
86
+ }
87
+ else {
88
+ const acknowledged = new Set([...acknowledgement.accepted, ...acknowledgement.duplicate]);
89
+ const accepted = batch.filter(event => acknowledged.has(event.id)).length;
90
+ sent += accepted;
91
+ if (accepted < batch.length) {
92
+ drop(batch.length - accepted, 'collector_rejected');
93
+ lastError = 'collector_rejected';
94
+ }
95
+ else
96
+ lastError = undefined;
97
+ reportedDrops = dropCount;
98
+ }
99
+ }
100
+ }
101
+ catch {
102
+ lastError = controller.signal.aborted ? 'request_timeout' : 'network_error';
103
+ drop(batch.length, 'delivery_failed');
104
+ }
105
+ finally {
106
+ clearTimeout(requestTimeout);
107
+ }
108
+ }
109
+ return status();
110
+ };
111
+ const flush = () => {
112
+ if (timer) {
113
+ clearTimeout(timer);
114
+ timer = undefined;
115
+ }
116
+ if (active)
117
+ return active;
118
+ active = deliver();
119
+ void active.finally(() => { active = undefined; schedule(); });
120
+ return active;
121
+ };
122
+ return {
123
+ onEvent(event) {
124
+ if (closed) {
125
+ drop(1, 'closed');
126
+ return;
127
+ }
128
+ try {
129
+ const json = JSON.stringify({ ...event, ...(appName === undefined ? {} : { appName }) });
130
+ const bytes = encoder.encode(json).byteLength;
131
+ if (bytes > MAX_EVENT_BYTES) {
132
+ drop(1, 'event_too_large');
133
+ schedule(true);
134
+ return;
135
+ }
136
+ // Retain the most recent trace when a developer leaves a collector paused/offline.
137
+ while (queue.length >= MAX_QUEUE_EVENTS || queueBytes + bytes > MAX_QUEUE_BYTES) {
138
+ const discarded = queue.shift();
139
+ if (!discarded)
140
+ break;
141
+ queueBytes -= discarded.bytes;
142
+ drop(1, 'queue_full');
143
+ }
144
+ queue.push({ json, bytes, id: event.id });
145
+ queueBytes += bytes;
146
+ schedule();
147
+ }
148
+ catch {
149
+ drop(1, 'invalid_event');
150
+ schedule(true);
151
+ }
152
+ },
153
+ flush,
154
+ close() {
155
+ if (closing)
156
+ return closing;
157
+ closed = true;
158
+ if (timer) {
159
+ clearTimeout(timer);
160
+ timer = undefined;
161
+ }
162
+ closing = (async () => {
163
+ await flush();
164
+ if (queue.length)
165
+ await flush();
166
+ return status();
167
+ })();
168
+ return closing;
169
+ },
170
+ };
171
+ }
@@ -0,0 +1,46 @@
1
+ export type LockRecord = {
2
+ pid: number;
3
+ host: string;
4
+ nonce: string;
5
+ at: number;
6
+ state: 'held' | 'free';
7
+ /** Where the writer's pid means something, and which process it was, where the OS says so
8
+ * without a clock: the OS, the boot, the PID namespace, and (Linux) the process's start in
9
+ * clock ticks since boot. A record with a boot and no `os` was written on Linux, the only
10
+ * scope there was before macOS's. */
11
+ os?: string;
12
+ boot?: string;
13
+ pidns?: string;
14
+ start?: string;
15
+ };
16
+ export type Incarnation = {
17
+ os: 'linux' | 'darwin';
18
+ boot: string;
19
+ pidns: string;
20
+ start?: string;
21
+ };
22
+ /** The PID namespace macOS records name: it has none, so every process shares this one. */
23
+ export declare const DARWIN_PIDNS = "darwin";
24
+ /** This process's scope and incarnation, or null where the OS cannot say (Windows, or anything
25
+ * here failing): then no held record is taken over.
26
+ * - Linux (/proc): the boot id (/proc/sys/kernel/random/boot_id), the PID namespace (the inode in
27
+ * readlink /proc/self/ns/pid, `pid:[N]`), and the start in clock ticks since boot
28
+ * (/proc/self/stat field 22).
29
+ * - macOS: kern.bootsessionuuid (sysctl), and the one PID namespace. No start: the one the OS
30
+ * gives is wall-clock text in the reader's time zone, so the same pid is always this process.
31
+ * None moves with the wall clock, and every thread of the process reads the same values. */
32
+ export declare function incarnation(): Incarnation | null;
33
+ /** The generations of `path` present now, highest first. */
34
+ export declare function generations(path: string): Promise<number[]>;
35
+ /** Record `generation` of `path`: 'absent' if it is gone, null if it cannot be read as one. */
36
+ export declare function lockRecord(path: string, generation: number): Promise<LockRecord | null | 'absent'>;
37
+ export type FileLock = {
38
+ /** Publishes a `free` record above this owner's (only while it is still on top), then runs
39
+ * `released`. */
40
+ release: () => Promise<void>;
41
+ /** The fence: throws `store_busy` unless this owner's record (generation and nonce) is still
42
+ * the one on top. */
43
+ verify: () => Promise<void>;
44
+ };
45
+ /** Holds the lock at `path` for this process, or fails with `store_busy`. */
46
+ export declare function acquireFileLock(path: string, released: () => void): Promise<FileLock>;
@@ -0,0 +1,300 @@
1
+ import { link, open, readdir, readFile, unlink } from 'node:fs/promises';
2
+ import { closeSync, fsyncSync, linkSync, openSync, readFileSync, readlinkSync, unlinkSync, writeSync } from 'node:fs';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { basename, dirname, join } from 'node:path';
5
+ import { hostname } from 'node:os';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { CrocheError } from './types.js';
8
+ // The cross-process lock behind the Node FileStorage (W1). Internal: not a package export.
9
+ //
10
+ // The lock is a chain of generation records `<lock>.<n>`. The highest generation decides who
11
+ // holds it, and nothing ever deletes the highest one:
12
+ // - Each record is written in full to a private file first, then published under its generation
13
+ // name with link(), which fails if that generation exists. There is no empty or half-written
14
+ // record to judge, so a creator paused at any point is never mistaken for a dead one (Atlas,
15
+ // #313 P1-1).
16
+ // - Taking the lock means creating generation n+1, when record n is `free` (released) or held
17
+ // by a process that no longer exists, judged only inside this process's own PID scope (see
18
+ // `keeps`). Exactly one creator gets n+1, and no step
19
+ // removes a file to make room, so no remover can act on a check that has gone stale (Atlas,
20
+ // #313 P1-2). There is no age-based takeover anywhere: time passing proves nothing.
21
+ // - A creator that finds a generation above its own after publishing (it was paused, others went
22
+ // on, and its generation had been cleaned up) withdraws it and reports store_busy.
23
+ // - Records below the highest are cleaned up; removing one never changes who holds the lock.
24
+ // Every unlink here targets a record below the top (or the owner's own, after a `free` record
25
+ // went above it), so no removal can act on ownership, however long its process was paused.
26
+ // - Writes are fenced: the owner checks that its own record is still on top before each write
27
+ // and fails with `store_busy` otherwise (FileStorage).
28
+ // - No clock decides anything. A record's `at` is for people reading it.
29
+ // - A pid means something only inside one PID namespace on one boot of one host. Liveness
30
+ // (`kill(pid, 0)`) and the incarnation are consulted only for a record written in this
31
+ // process's own scope (host, boot id and PID namespace all equal); any other record is
32
+ // ambiguous (another container may be alive with the same pid) and is never taken over
33
+ // (Atlas, #313 at f182e8c).
34
+ // - macOS has a scope too (Keel #393 6087163235): the boot is kern.bootsessionuuid, a random
35
+ // UUID per boot, and there are no PID namespaces. The host is not part of it there: a Mac's
36
+ // hostname follows the network it is on, and equal per-boot UUIDs already name one machine.
37
+ // A record names its OS, and a Linux record and a macOS record are never in one scope (a
38
+ // directory shared with a container). Windows has no scope: nothing held is taken over.
39
+ /** Lock records this module holds, by lock path: the generation and its nonce. */
40
+ const held = new Map();
41
+ let exitHook = false;
42
+ /** How many times an acquisition re-reads after the chain moved under it. */
43
+ const ATTEMPTS = 5;
44
+ /** The PID namespace macOS records name: it has none, so every process shares this one. */
45
+ export const DARWIN_PIDNS = 'darwin';
46
+ /** This process's scope and incarnation, or null where the OS cannot say (Windows, or anything
47
+ * here failing): then no held record is taken over.
48
+ * - Linux (/proc): the boot id (/proc/sys/kernel/random/boot_id), the PID namespace (the inode in
49
+ * readlink /proc/self/ns/pid, `pid:[N]`), and the start in clock ticks since boot
50
+ * (/proc/self/stat field 22).
51
+ * - macOS: kern.bootsessionuuid (sysctl), and the one PID namespace. No start: the one the OS
52
+ * gives is wall-clock text in the reader's time zone, so the same pid is always this process.
53
+ * None moves with the wall clock, and every thread of the process reads the same values. */
54
+ export function incarnation() {
55
+ if (cached !== undefined)
56
+ return cached;
57
+ cached = process.platform === 'darwin' ? darwin() : process.platform === 'linux' ? linux() : null;
58
+ return cached;
59
+ }
60
+ let cached;
61
+ function linux() {
62
+ try {
63
+ const boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
64
+ const pidns = /^pid:\[([0-9]+)\]$/.exec(readlinkSync('/proc/self/ns/pid'))?.[1];
65
+ const stat = readFileSync('/proc/self/stat', 'utf8');
66
+ // Field 2 is the command name in parentheses, which may hold spaces: count from after it.
67
+ const start = stat.slice(stat.lastIndexOf(')') + 2).split(' ')[22 - 3];
68
+ return boot && pidns && /^[0-9]+$/.test(start ?? '') ? { os: 'linux', boot, pidns, start } : null;
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
74
+ const UUID = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
75
+ function darwin() {
76
+ try {
77
+ const boot = execFileSync('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 }).trim();
78
+ return UUID.test(boot) ? { os: 'darwin', boot, pidns: DARWIN_PIDNS } : null;
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }
84
+ /** Whether `pid` may be a live process on this machine. `kill(pid, 0)` sends nothing; it checks
85
+ * existence. Only ESRCH (no such process) means absent. Every other error (EPERM: it exists but
86
+ * belongs to another user; EACCES, ENOSYS, EINVAL, anything unknown) means the check could not
87
+ * prove death, and an unproven death never authorizes a takeover. */
88
+ function alive(pid) {
89
+ try {
90
+ process.kill(pid, 0);
91
+ return true;
92
+ }
93
+ catch (error) {
94
+ return error.code !== 'ESRCH';
95
+ }
96
+ }
97
+ const code = (error) => error.code;
98
+ /** The generations of `path` present now, highest first. */
99
+ export async function generations(path) {
100
+ const prefix = `${basename(path)}.`;
101
+ const names = await readdir(dirname(path)).catch(error => { if (code(error) === 'ENOENT')
102
+ return []; throw error; });
103
+ return names
104
+ .filter(name => name.startsWith(prefix) && /^[1-9][0-9]*$/.test(name.slice(prefix.length)))
105
+ .map(name => Number(name.slice(prefix.length)))
106
+ .filter(Number.isSafeInteger)
107
+ .sort((a, b) => b - a);
108
+ }
109
+ /** Record `generation` of `path`: 'absent' if it is gone, null if it cannot be read as one. */
110
+ export async function lockRecord(path, generation) {
111
+ let text;
112
+ try {
113
+ text = await readFile(`${path}.${generation}`, 'utf8');
114
+ }
115
+ catch (error) {
116
+ if (code(error) === 'ENOENT')
117
+ return 'absent';
118
+ throw error;
119
+ }
120
+ try {
121
+ const value = JSON.parse(text);
122
+ return Number.isInteger(value?.pid) && value.pid > 0 && typeof value.nonce === 'string' && typeof value.host === 'string'
123
+ && (value.state === 'held' || value.state === 'free') ? value : null;
124
+ }
125
+ catch {
126
+ return null;
127
+ }
128
+ }
129
+ const record = (state, nonce) => ({ pid: process.pid, host: hostname(), nonce, at: Date.now(), state, ...(incarnation() ?? {}) });
130
+ const temporary = (path) => join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
131
+ /** Publishes `value` as generation `generation`, complete and fsynced before it is visible.
132
+ * False: that generation already exists. */
133
+ async function publish(path, generation, value) {
134
+ const draft = temporary(path);
135
+ const file = await open(draft, 'wx', 0o600);
136
+ try {
137
+ await file.writeFile(JSON.stringify(value));
138
+ await file.sync();
139
+ }
140
+ finally {
141
+ await file.close();
142
+ }
143
+ try {
144
+ await link(draft, `${path}.${generation}`);
145
+ return true;
146
+ }
147
+ catch (error) {
148
+ if (code(error) === 'EEXIST')
149
+ return false;
150
+ throw error;
151
+ }
152
+ finally {
153
+ await unlink(draft).catch(() => { });
154
+ }
155
+ }
156
+ /** The same, synchronously, for the exit hook. */
157
+ function publishSync(path, generation, value) {
158
+ const draft = temporary(path);
159
+ const fd = openSync(draft, 'wx', 0o600);
160
+ try {
161
+ writeSync(fd, JSON.stringify(value));
162
+ fsyncSync(fd);
163
+ }
164
+ finally {
165
+ closeSync(fd);
166
+ }
167
+ try {
168
+ linkSync(draft, `${path}.${generation}`);
169
+ return true;
170
+ }
171
+ catch (error) {
172
+ if (code(error) === 'EEXIST')
173
+ return false;
174
+ throw error;
175
+ }
176
+ finally {
177
+ try {
178
+ unlinkSync(draft);
179
+ }
180
+ catch { /* best effort */ }
181
+ }
182
+ }
183
+ /** Removes the generations below `top`. None of them decides anything any more. */
184
+ async function prune(path, top) {
185
+ for (const generation of await generations(path).catch(() => [])) {
186
+ if (generation < top)
187
+ await unlink(`${path}.${generation}`).catch(() => { });
188
+ }
189
+ }
190
+ /** Whether `found` was written in this process's own PID scope: this OS, this boot and this PID
191
+ * namespace (and on Linux this host, checked first in `keeps`). Only there does a pid name one
192
+ * process this one can check. A record without the evidence, or a process that has no scope, is
193
+ * never in scope. */
194
+ function inScope(found) {
195
+ const me = incarnation();
196
+ return !!me && typeof found.boot === 'string' && typeof found.pidns === 'string'
197
+ && (found.os ?? 'linux') === me.os && found.boot === me.boot && found.pidns === me.pidns;
198
+ }
199
+ /** Why the record on top keeps the lock, or null when it may be taken. */
200
+ function keeps(found, generation, path) {
201
+ const record = `${path}.${generation}`;
202
+ if (!found) {
203
+ return `its lock record ${record} cannot be read. The lock publishes only complete, fsynced records, so this is damage or a foreign writer; it is never taken over. If no process uses this store, remove the ${basename(path)}.* records`;
204
+ }
205
+ if (found.state === 'free')
206
+ return null;
207
+ // macOS's scope is its boot alone: its hostname follows the network (measured, #393).
208
+ if (found.host !== hostname() && incarnation()?.os !== 'darwin') {
209
+ return `pid ${found.pid} on host ${found.host}, record ${record}. Another host's owner is never taken over, since a shared directory's other host cannot be checked. If that host is gone (a container restarted under a new hostname), remove the ${basename(path)}.* records`;
210
+ }
211
+ if (!inScope(found)) {
212
+ return `pid ${found.pid} on host ${found.host}, record ${record}, written outside this process's PID scope (another OS, boot or PID namespace, or no way to tell here): a store directory shared between containers or PID namespaces, or a container or machine that restarted after a crash. Its owner cannot be checked from here, so it is never taken over. Use one store directory per container (or per host process tree). If no process uses this store any more, stop every user of it, then remove the ${basename(path)}.* records`;
213
+ }
214
+ if (found.pid === process.pid) {
215
+ // The same pid in this scope: this process (another copy of the SDK, a worker thread), or an
216
+ // earlier process that had this pid on this boot and in this namespace (another start). With
217
+ // no start to compare (macOS), it is this process.
218
+ const start = incarnation().start;
219
+ if (typeof found.start === 'string' && typeof start === 'string' && found.start !== start)
220
+ return null;
221
+ return `this process (pid ${found.pid}: another copy of the SDK, or a worker thread), record ${record}`;
222
+ }
223
+ return alive(found.pid) ? `pid ${found.pid}, record ${record}` : null;
224
+ }
225
+ /** Releases what this process still holds if it exits without closing (an exit hook runs only
226
+ * synchronous code). A killed process runs nothing; its record is held by a pid that no longer
227
+ * exists, and the next opener takes the lock over. */
228
+ function releaseAtExit() {
229
+ if (exitHook)
230
+ return;
231
+ exitHook = true;
232
+ process.once('exit', () => {
233
+ for (const [path, mine] of held) {
234
+ try {
235
+ publishSync(path, mine.generation + 1, record('free', mine.nonce));
236
+ unlinkSync(`${path}.${mine.generation}`);
237
+ }
238
+ catch { /* best effort */ }
239
+ }
240
+ });
241
+ }
242
+ /** Holds the lock at `path` for this process, or fails with `store_busy`. */
243
+ export async function acquireFileLock(path, released) {
244
+ const nonce = randomUUID();
245
+ let mine = null;
246
+ let reason = 'the lock kept changing while it was read';
247
+ try {
248
+ for (let attempt = 0; attempt < ATTEMPTS && mine === null; attempt += 1) {
249
+ const [top = 0] = await generations(path);
250
+ if (top > 0) {
251
+ const found = await lockRecord(path, top);
252
+ if (found === 'absent')
253
+ continue;
254
+ const why = keeps(found, top, path);
255
+ if (why) {
256
+ reason = why;
257
+ break;
258
+ }
259
+ }
260
+ if (!(await publish(path, top + 1, record('held', nonce))))
261
+ continue;
262
+ // Paused creators can publish a generation that was already cleaned up below the top.
263
+ const [now = 0] = await generations(path);
264
+ if (now !== top + 1) {
265
+ await unlink(`${path}.${top + 1}`).catch(() => { });
266
+ continue;
267
+ }
268
+ mine = top + 1;
269
+ }
270
+ }
271
+ catch (error) {
272
+ throw new CrocheError('store_busy', `The store's lock file could not be created: ${error.message}`);
273
+ }
274
+ if (mine === null)
275
+ throw new CrocheError('store_busy', `This file namespace is open in another process (${reason}).`);
276
+ await prune(path, mine);
277
+ held.set(path, { generation: mine, nonce });
278
+ releaseAtExit();
279
+ const generation = mine;
280
+ const verify = async () => {
281
+ const [top = 0] = await generations(path);
282
+ const found = top === generation ? await lockRecord(path, generation) : null;
283
+ if (!found || found === 'absent' || found.nonce !== nonce || found.state !== 'held') {
284
+ throw new CrocheError('store_busy', `This owner's lock record ${generation} is no longer the one on top (now ${top || 'none'}); the write was refused.`);
285
+ }
286
+ };
287
+ const release = async () => {
288
+ held.delete(path);
289
+ try {
290
+ const [top = 0] = await generations(path);
291
+ const found = top === generation ? await lockRecord(path, generation) : null;
292
+ if (found && found !== 'absent' && found.nonce === nonce && await publish(path, generation + 1, record('free', nonce))) {
293
+ await unlink(`${path}.${generation}`).catch(() => { });
294
+ }
295
+ }
296
+ catch { /* the next opener checks the pid */ }
297
+ released();
298
+ };
299
+ return { release, verify };
300
+ }