@indigoai-us/hq-cli 5.345.214 → 5.345.215-beta.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 (103) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/command-catalog.generated.d.ts +134 -7
  3. package/dist/command-catalog.generated.js +168 -7
  4. package/dist/commands/agents.d.ts +51 -1
  5. package/dist/commands/agents.js +154 -2
  6. package/dist/commands/bot-jobs.d.ts +2 -15
  7. package/dist/commands/bot-jobs.js +2 -94
  8. package/dist/commands/bot-runtime.d.ts +46 -5
  9. package/dist/commands/bot-runtime.js +228 -18
  10. package/dist/commands/bot.d.ts +16 -9
  11. package/dist/commands/bot.js +169 -51
  12. package/dist/commands/cloud.d.ts +66 -13
  13. package/dist/commands/cloud.js +120 -39
  14. package/dist/commands/company-restore.d.ts +23 -0
  15. package/dist/commands/company-restore.js +128 -0
  16. package/dist/commands/company.js +2 -0
  17. package/dist/commands/integrations-connect.d.ts +10 -3
  18. package/dist/commands/integrations-connect.js +87 -13
  19. package/dist/commands/lanes.js +26 -9
  20. package/dist/commands/sources.js +6 -0
  21. package/dist/commands/storage-offload.d.ts +12 -0
  22. package/dist/commands/storage-offload.js +41 -3
  23. package/dist/commands/sync-mode.js +5 -0
  24. package/dist/commands/whoami.js +4 -0
  25. package/dist/lib/bot/config.d.ts +1 -0
  26. package/dist/lib/bot/config.js +10 -0
  27. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  28. package/dist/lib/bot/eventbridge-cron.js +104 -0
  29. package/dist/lib/bot/fleet-local.d.ts +33 -1
  30. package/dist/lib/bot/fleet-local.js +215 -31
  31. package/dist/lib/bot/fleet-python.d.ts +3 -0
  32. package/dist/lib/bot/fleet-python.js +34 -4
  33. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  34. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  35. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  36. package/dist/lib/bot/legacy-provider-login.js +19 -2
  37. package/dist/lib/bot/prompt.js +1 -1
  38. package/dist/lib/bot/readiness.d.ts +8 -0
  39. package/dist/lib/bot/readiness.js +17 -3
  40. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  41. package/dist/lib/bot/runtime-auth.js +94 -3
  42. package/dist/lib/bot/status.d.ts +2 -0
  43. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  44. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  45. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  46. package/dist/lib/capacity/collectors/grok.js +56 -5
  47. package/dist/lib/daemon/catalog.js +11 -1
  48. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  49. package/dist/lib/db/sqlite-binding.js +1 -1
  50. package/dist/lib/delivery/artifacts.d.ts +99 -0
  51. package/dist/lib/delivery/artifacts.js +548 -0
  52. package/dist/lib/delivery/backup.d.ts +78 -0
  53. package/dist/lib/delivery/backup.js +343 -0
  54. package/dist/lib/delivery/cache.d.ts +29 -0
  55. package/dist/lib/delivery/cache.js +33 -0
  56. package/dist/lib/delivery/contracts.d.ts +142 -0
  57. package/dist/lib/delivery/contracts.js +289 -0
  58. package/dist/lib/delivery/credentials.d.ts +54 -0
  59. package/dist/lib/delivery/credentials.js +119 -0
  60. package/dist/lib/delivery/enrollment.d.ts +142 -0
  61. package/dist/lib/delivery/enrollment.js +382 -0
  62. package/dist/lib/delivery/identity.d.ts +25 -0
  63. package/dist/lib/delivery/identity.js +82 -0
  64. package/dist/lib/delivery/inbox.d.ts +116 -0
  65. package/dist/lib/delivery/inbox.js +260 -0
  66. package/dist/lib/delivery/migrations.d.ts +139 -0
  67. package/dist/lib/delivery/migrations.js +623 -0
  68. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  69. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  70. package/dist/lib/delivery/mqtt.d.ts +61 -0
  71. package/dist/lib/delivery/mqtt.js +112 -0
  72. package/dist/lib/delivery/outbox.d.ts +95 -0
  73. package/dist/lib/delivery/outbox.js +187 -0
  74. package/dist/lib/delivery/provenance.d.ts +129 -0
  75. package/dist/lib/delivery/provenance.js +93 -0
  76. package/dist/lib/delivery/reconciler.d.ts +151 -0
  77. package/dist/lib/delivery/reconciler.js +492 -0
  78. package/dist/lib/delivery/restore.d.ts +35 -0
  79. package/dist/lib/delivery/restore.js +134 -0
  80. package/dist/lib/delivery/store.d.ts +161 -0
  81. package/dist/lib/delivery/store.js +940 -0
  82. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  83. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  84. package/dist/lib/delivery/workers/macos.d.ts +176 -0
  85. package/dist/lib/delivery/workers/macos.js +901 -0
  86. package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
  87. package/dist/lib/delivery/workers/windows-boundary.js +693 -0
  88. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  89. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  90. package/dist/lib/delivery/workers/windows.d.ts +241 -0
  91. package/dist/lib/delivery/workers/windows.js +608 -0
  92. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  93. package/dist/lib/install/provider-wrappers.js +68 -3
  94. package/dist/utils/cognito-callback-port.d.ts +14 -0
  95. package/dist/utils/cognito-callback-port.js +24 -0
  96. package/dist/utils/cognito-session.js +3 -3
  97. package/dist/utils/deleted-company-notice.d.ts +59 -0
  98. package/dist/utils/deleted-company-notice.js +156 -0
  99. package/dist/utils/login-browser.d.ts +1 -1
  100. package/dist/utils/login-browser.js +7 -5
  101. package/dist/utils/resident-package-preload.js +30 -15
  102. package/dist/utils/vault-api.js +7 -0
  103. package/package.json +7 -7
@@ -0,0 +1,940 @@
1
+ /**
2
+ * Durable local store for delivery runs, jobs, dependencies and attempts (US-003).
3
+ *
4
+ * Authority: `state.json` is a plain file holding the committed state,
5
+ * `{ storeSchemaVersion, sha256, state }` (see migrations.ts). It is the only
6
+ * source of committed state. `owner.lock` names the one controller allowed to
7
+ * write it: { controllerId, host, pid, epoch, acquiredAt }. Every commit
8
+ * writes the complete new state to a fresh temp file and fsyncs it, then
9
+ * renames it over state.json and fsyncs the directory, so after a crash
10
+ * state.json holds either the previous commit or the new one. Temp files left
11
+ * by a crash were never committed; open() deletes them and reports their
12
+ * names.
13
+ *
14
+ * Serialization: every change to owner.lock (claim, takeover, release) and
15
+ * every rename onto state.json happens inside a write transaction (BEGIN
16
+ * IMMEDIATE) on `owner.db`, a SQLite control database opened through the
17
+ * declared better-sqlite3 dependency. SQLite takes that lock with an OS file
18
+ * lock, so one connection in any process holds it at a time. The transaction
19
+ * writes nothing; owner.db holds no state. A writer takes the lock, checks
20
+ * that owner.lock still names it exactly, renames its temp file over
21
+ * state.json and only then ends the transaction. A new owner takes the lock,
22
+ * judges the old owner.lock, reads its base from state.json and installs its
23
+ * own lock before ending the transaction. So a write that reports success
24
+ * landed before every later claim and is in every later owner's base, and a
25
+ * superseded writer can never rename over a newer owner's state. A lock is
26
+ * released only by its own holder, under the store lock, and only while it
27
+ * still names that holder.
28
+ *
29
+ * Busy lock: a controller that finds the store lock held waits up to
30
+ * gateWaitMs (default 2000, better-sqlite3's busy timeout), then refuses with
31
+ * CONTROLLER_AMBIGUOUS and changes nothing. There is no break path: an
32
+ * operator override applies only to owner.lock and never to the store lock.
33
+ * The OS drops the lock when its holder exits, so a crash leaves nothing to
34
+ * delete. An owner.gate or owner.gate.break file left by an older build is
35
+ * refused (CONTROLLER_AMBIGUOUS, naming the file) and never removed.
36
+ *
37
+ * Filesystem limits: the store lock is only as good as the filesystem's
38
+ * POSIX advisory locks. On NFS, SMB, or any directory shared by several
39
+ * hosts, SQLite locking can be missing or broken, and then serialization is
40
+ * not guaranteed. Without an override, a lock held from another host is still
41
+ * refused as ambiguous, so two hosts do not both own the store by default.
42
+ * With an override while the other host's owner is still live, or with two
43
+ * hosts racing through check-then-rename on owner.lock, a committed write can
44
+ * be lost. owner.lock plus fail-closed refusal therefore does not prevent
45
+ * lost writes across hosts. Keep the store directory on a local disk used by
46
+ * one host.
47
+ *
48
+ * Ownership: a second controller that finds a live or ambiguous owner is
49
+ * refused. A stale lock is taken over only when that is provable on this host
50
+ * (same host and the owner pid is gone) or when the operator passes an
51
+ * explicit override. The new lock is written to a temp file and renamed over
52
+ * owner.lock, so the lock path is never empty during a takeover. The old lock
53
+ * is kept as owner.lock.superseded-e<epoch>-<hash>-<random>, created
54
+ * exclusively, so records never overwrite each other. The new epoch is one
55
+ * more than the epoch in state.json and in the previous lock. There is no
56
+ * quorum or cross-host consensus: a lock held from another host is ambiguous
57
+ * and refused.
58
+ *
59
+ * FENCED: a write from a handle whose lock no longer names it, or from the
60
+ * wrong epoch, is rejected with FENCED. A FENCED write was not persisted:
61
+ * the check happens under the store lock before the rename, and the temp file is
62
+ * removed.
63
+ *
64
+ * On-disk results of a failed open: every refusal (CONTROLLER_OWNED,
65
+ * CONTROLLER_AMBIGUOUS, STORE_CORRUPT and other load errors) happens before
66
+ * the lock is touched, so it leaves the store unchanged. A migration backup
67
+ * is written only after every refusal check has passed. A failure after the
68
+ * claim (an fsync or close while installing the lock, temp cleanup or first
69
+ * commit failed, or a crash) leaves state.json unchanged; the new lock is
70
+ * removed when the process can still clean up, and
71
+ * after a takeover the previous lock stays in its superseded record. If
72
+ * removing a previous-layout epoch file fails after the first commit, the
73
+ * commit stays and the new lock is released. A crash that leaves the new lock
74
+ * behind is recovered by a later stale-pid takeover.
75
+ *
76
+ * Limits: stale-pid proof assumes one PID namespace per hostname. Containers
77
+ * that share a hostname but have separate PID namespaces can see a live owner
78
+ * as gone; give each container its own hostname, or do not share the store.
79
+ * The Windows rename and EPERM paths have not been run on Windows. A rename
80
+ * or temp-file open that fails with EPERM, EACCES or EBUSY is reported as
81
+ * STORE_IO with nothing written; there is no fallback that writes in place.
82
+ *
83
+ * Older layouts: a plain state.json from an older build is read and migrated.
84
+ * The previous layout of this build (state.json as a symlink to
85
+ * state.e<N>.json epoch files) is read from the newest epoch file, then
86
+ * replaced by a plain state.json and the epoch files are deleted on the first
87
+ * commit.
88
+ */
89
+ import { createHash, randomBytes } from "node:crypto";
90
+ import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, unlinkSync, writeSync, } from "node:fs";
91
+ import { hostname } from "node:os";
92
+ import { join } from "node:path";
93
+ import { DeliveryStoreError, emptyState, parseStoreText, serializeState, validateState, } from "./migrations.js";
94
+ import { isNativeBindingError, loadBetterSqlite3 } from "../db/sqlite-binding.js";
95
+ export { DeliveryStoreError } from "./migrations.js";
96
+ export const STATE_FILE = "state.json";
97
+ export const LOCK_FILE = "owner.lock";
98
+ /**
99
+ * SQLite control database; a write transaction on it is the store's serialization lock.
100
+ * Never open, read or close owner.db in this process except through the better-sqlite3
101
+ * connection in withStoreLock: closing any file descriptor on it drops every fcntl lock
102
+ * this process holds on it, which would silently end the store lock.
103
+ */
104
+ export const CONTROL_DB_FILE = "owner.db";
105
+ /**
106
+ * US-010: written into a store that a restored controller replaced. Its
107
+ * presence refuses every later open, so the old controller cannot regain
108
+ * authority (including by stale-pid takeover).
109
+ */
110
+ export const RETIRED_FILE = "retired.json";
111
+ /** US-010: written by restore; the store refuses to open until activateRestore removes it. */
112
+ export const RESTORE_PENDING_FILE = "restore.pending.json";
113
+ /** Serialization files of an older build. Their presence is refused, never removed. */
114
+ const OLD_GATE_FILES = ["owner.gate", "owner.gate.break"];
115
+ const STATE_TEMP_PREFIX = `${STATE_FILE}.tmp-`;
116
+ const LOCK_TEMP_PREFIX = `${LOCK_FILE}.tmp-`;
117
+ /** Epoch files written by the previous layout of this build. */
118
+ const LEGACY_EPOCH_FILE_PATTERN = /^state\.e(\d+)\.json$/;
119
+ const PREVIOUS_OWNER_LIMIT = 500;
120
+ const DEFAULT_LOCK_WAIT_MS = 2000;
121
+ const IO_CODES = ["EPERM", "EACCES", "EBUSY"];
122
+ /** True if a process with this pid exists (EPERM counts as alive). */
123
+ export function pidIsAlive(pid) {
124
+ try {
125
+ process.kill(pid, 0);
126
+ return true;
127
+ }
128
+ catch (err) {
129
+ return err.code === "EPERM";
130
+ }
131
+ }
132
+ function sha(text) {
133
+ return createHash("sha256").update(text).digest("hex");
134
+ }
135
+ function errCode(err) {
136
+ return err?.code;
137
+ }
138
+ function writeAll(fd, buf) {
139
+ let offset = 0;
140
+ while (offset < buf.length)
141
+ offset += writeSync(fd, buf, offset, buf.length - offset);
142
+ }
143
+ /** Create `path` exclusively with `text`, fsynced. False if it already exists. */
144
+ function createExclusive(path, text) {
145
+ let fd;
146
+ try {
147
+ fd = openSync(path, "wx");
148
+ }
149
+ catch (err) {
150
+ if (errCode(err) === "EEXIST")
151
+ return false;
152
+ throw err;
153
+ }
154
+ try {
155
+ writeAll(fd, Buffer.from(text));
156
+ fsyncSync(fd);
157
+ }
158
+ finally {
159
+ closeSync(fd);
160
+ }
161
+ return true;
162
+ }
163
+ function fsyncDir(dir) {
164
+ let fd;
165
+ try {
166
+ fd = openSync(dir, "r");
167
+ fsyncSync(fd);
168
+ }
169
+ catch (err) {
170
+ // Some platforms cannot fsync a directory; the rename is still atomic there.
171
+ if (!["EISDIR", "EINVAL", "EPERM", "EBADF"].includes(errCode(err) ?? ""))
172
+ throw err;
173
+ }
174
+ finally {
175
+ if (fd !== undefined)
176
+ closeSync(fd);
177
+ }
178
+ }
179
+ function readIfExists(path) {
180
+ try {
181
+ return readFileSync(path, "utf8");
182
+ }
183
+ catch (err) {
184
+ if (errCode(err) === "ENOENT")
185
+ return null;
186
+ throw err;
187
+ }
188
+ }
189
+ function unlinkIfExists(path) {
190
+ try {
191
+ unlinkSync(path);
192
+ }
193
+ catch (err) {
194
+ if (errCode(err) !== "ENOENT")
195
+ throw err;
196
+ }
197
+ }
198
+ /** Best-effort removal while another error is already being reported. */
199
+ function unlinkQuietly(path) {
200
+ try {
201
+ unlinkSync(path);
202
+ }
203
+ catch {
204
+ // The original error is the one to report.
205
+ }
206
+ }
207
+ /** Map a permission or busy error to STORE_IO; anything else is rethrown as is. */
208
+ function ioError(err, what, path) {
209
+ const code = errCode(err);
210
+ if (code === undefined || !IO_CODES.includes(code))
211
+ return err;
212
+ return new DeliveryStoreError("STORE_IO", {
213
+ found: `${code} while ${what} ${path}`,
214
+ expected: `${path} to be writable by this controller`,
215
+ action: "Nothing was written. Close any program holding files in the store directory (editors, backup or antivirus tools), check its permissions, then retry.",
216
+ });
217
+ }
218
+ /**
219
+ * Map an error from installing owner.lock. Permission and busy errors keep the
220
+ * ioError text; any other errno (EIO, ENOSPC, ...) is also STORE_IO here, with
221
+ * the original message; the caller has already tried to remove our lock.
222
+ */
223
+ function installError(err, lockPath) {
224
+ const code = errCode(err);
225
+ if (err instanceof DeliveryStoreError || code === undefined || IO_CODES.includes(code)) {
226
+ return ioError(err, "installing", lockPath);
227
+ }
228
+ return new DeliveryStoreError("STORE_IO", {
229
+ found: `${code} while installing ${lockPath}: ${err.message}`,
230
+ expected: `${lockPath} to be written and flushed to disk`,
231
+ action: "The store state was not changed, and this controller tried to remove any owner.lock it wrote. Check the disk or file system holding the store directory for errors, then retry. If the retry is refused because owner.lock still names this controller, that removal failed: stop this process, then retry.",
232
+ });
233
+ }
234
+ /** Parse a lock file. null when it is not exactly an OwnerLock. */
235
+ export function parseLock(text) {
236
+ let v;
237
+ try {
238
+ v = JSON.parse(text);
239
+ }
240
+ catch {
241
+ return null;
242
+ }
243
+ if (typeof v !== "object" || v === null || Array.isArray(v))
244
+ return null;
245
+ const o = v;
246
+ if (Object.keys(o).sort().join(",") !== "acquiredAt,controllerId,epoch,host,pid")
247
+ return null;
248
+ const ok = typeof o.controllerId === "string" &&
249
+ o.controllerId !== "" &&
250
+ typeof o.host === "string" &&
251
+ typeof o.pid === "number" &&
252
+ Number.isInteger(o.pid) &&
253
+ o.pid > 0 &&
254
+ (o.epoch === null || (typeof o.epoch === "number" && Number.isInteger(o.epoch) && o.epoch >= 0)) &&
255
+ typeof o.acquiredAt === "string";
256
+ return ok ? o : null;
257
+ }
258
+ function describeLock(lock) {
259
+ return `controller ${lock.controllerId} (pid ${lock.pid} on host ${lock.host}, epoch ${lock.epoch ?? "unset"})`;
260
+ }
261
+ function sameLock(a, b) {
262
+ return (a !== null &&
263
+ a.controllerId === b.controllerId &&
264
+ a.pid === b.pid &&
265
+ a.host === b.host &&
266
+ a.acquiredAt === b.acquiredAt &&
267
+ a.epoch === b.epoch);
268
+ }
269
+ function readLock(lockPath) {
270
+ const text = readIfExists(lockPath);
271
+ return text === null ? null : parseLock(text);
272
+ }
273
+ const OVERRIDE_ACTION = "Make sure no other controller is using this store, then reopen with an explicit operator override. Its later writes will be fenced.";
274
+ const CONCURRENT_START_ACTION = "Another controller is starting at the same time. Wait for it, then retry.";
275
+ const LOCK_BUSY_ACTION = "Another controller is changing ownership of this store or publishing to it right now. Retry in a moment. " +
276
+ "The lock is released by the operating system when that process exits, even if it crashed, so do not delete any file.";
277
+ /** Map a better-sqlite3 error on the control database to a DeliveryStoreError; anything else is rethrown as is. */
278
+ function controlDbError(err, path) {
279
+ const code = err?.code;
280
+ if (typeof code !== "string" || !code.startsWith("SQLITE_"))
281
+ return ioError(err, "opening", path);
282
+ const message = err.message;
283
+ if (code.startsWith("SQLITE_BUSY") || code.startsWith("SQLITE_LOCKED")) {
284
+ return new DeliveryStoreError("CONTROLLER_AMBIGUOUS", {
285
+ found: `${path} is locked by another controller (${code}: ${message})`,
286
+ expected: "no other controller changing ownership or publishing at the same time",
287
+ action: LOCK_BUSY_ACTION,
288
+ });
289
+ }
290
+ if (code.startsWith("SQLITE_NOTADB")) {
291
+ return new DeliveryStoreError("STORE_CORRUPT", {
292
+ found: `${path} is not a SQLite database (${message})`,
293
+ expected: `${CONTROL_DB_FILE} to be the store's control database`,
294
+ action: `${path} holds no store data. Stop every controller using this store, then delete ${path} and retry; it is recreated empty.`,
295
+ });
296
+ }
297
+ if (/^SQLITE_(PERM|READONLY|IOERR|CANTOPEN|FULL)/.test(code)) {
298
+ return new DeliveryStoreError("STORE_IO", {
299
+ found: `${code} (${message}) while opening ${path}`,
300
+ expected: `${path} to be readable and writable by this controller`,
301
+ action: "Nothing was written. Check the store directory's permissions and free space and that it is on a local disk, close any program holding files in it, then retry.",
302
+ });
303
+ }
304
+ return err;
305
+ }
306
+ function bindingLoadError(err) {
307
+ return new DeliveryStoreError("STORE_IO", {
308
+ found: `better-sqlite3 did not load in Node ${process.version}: ${err.message}`,
309
+ expected: "the better-sqlite3 native binary, which the store uses for its lock",
310
+ action: "Nothing was written. Reinstall with scripts allowed for better-sqlite3 (npm install -g @indigoai-us/hq-cli --allow-scripts=better-sqlite3), then retry.",
311
+ });
312
+ }
313
+ function openControlDb(path, waitMs) {
314
+ let Database;
315
+ try {
316
+ Database = loadBetterSqlite3();
317
+ }
318
+ catch (err) {
319
+ throw bindingLoadError(err);
320
+ }
321
+ try {
322
+ return new Database(path, { timeout: waitMs });
323
+ }
324
+ catch (err) {
325
+ // better-sqlite3 loads its native addon in the constructor, so a missing
326
+ // or mismatched binary first fails here.
327
+ if (isNativeBindingError(err))
328
+ throw bindingLoadError(err);
329
+ throw controlDbError(err, path);
330
+ }
331
+ }
332
+ /**
333
+ * Run `fn` while holding the store's serialization lock: a write transaction
334
+ * (BEGIN IMMEDIATE) on owner.db through better-sqlite3. SQLite takes that
335
+ * lock with an OS file lock, so only one connection in any process holds it,
336
+ * a waiter retries for `waitMs` and then gets SQLITE_BUSY, and the lock ends
337
+ * when the transaction ends or the process dies. The transaction writes
338
+ * nothing, so a crash leaves no journal behind.
339
+ */
340
+ function withStoreLock(dir, waitMs, fn) {
341
+ const path = join(dir, CONTROL_DB_FILE);
342
+ const db = openControlDb(path, waitMs);
343
+ try {
344
+ try {
345
+ db.exec("BEGIN IMMEDIATE");
346
+ }
347
+ catch (err) {
348
+ throw controlDbError(err, path);
349
+ }
350
+ let done = false;
351
+ try {
352
+ const out = fn();
353
+ done = true;
354
+ return out;
355
+ }
356
+ finally {
357
+ try {
358
+ db.exec(done ? "COMMIT" : "ROLLBACK");
359
+ }
360
+ catch {
361
+ // Closing the connection below ends the transaction and releases the lock.
362
+ }
363
+ }
364
+ }
365
+ finally {
366
+ db.close();
367
+ }
368
+ }
369
+ /** Refuse, read only, when a serialization file from an older build is present. */
370
+ function refuseOldGateFiles(dir) {
371
+ for (const name of OLD_GATE_FILES) {
372
+ const path = join(dir, name);
373
+ if (!existsSync(path))
374
+ continue;
375
+ throw new DeliveryStoreError("CONTROLLER_AMBIGUOUS", {
376
+ found: `${path} exists; it was written by an older build of this controller`,
377
+ expected: `no ${name}; this build serializes through ${CONTROL_DB_FILE}`,
378
+ action: `The store state was not changed (${CONTROL_DB_FILE} may have been created; it holds no state). Stop every controller from an older build that uses this store, then remove ${path} and retry.`,
379
+ });
380
+ }
381
+ }
382
+ /** Refuse, read only, a store retired by a restore or a restore not yet activated (US-010). */
383
+ function refuseRetiredOrPending(dir) {
384
+ const retired = readIfExists(join(dir, RETIRED_FILE));
385
+ if (retired !== null) {
386
+ throw new DeliveryStoreError("STORE_RETIRED", {
387
+ found: `${join(dir, RETIRED_FILE)}: ${retired.trim().slice(0, 300)}`,
388
+ expected: "a store that has not been replaced by a restored controller",
389
+ action: "This store was retired by a restore and must not be used. Run the controller against the restored store named in the record.",
390
+ });
391
+ }
392
+ if (existsSync(join(dir, RESTORE_PENDING_FILE))) {
393
+ throw new DeliveryStoreError("RESTORE_PENDING", {
394
+ found: `${join(dir, RESTORE_PENDING_FILE)} exists`,
395
+ expected: "an activated restore",
396
+ action: "Run activateRestore for this directory first, which retires the old controller and moves authority here. Nothing was changed.",
397
+ });
398
+ }
399
+ }
400
+ /**
401
+ * Run `fn` with the committed state.json text while holding the store lock,
402
+ * so no commit lands during `fn` (US-010 backups). Read only; does not need
403
+ * or touch ownership. Refuses a retired store.
404
+ */
405
+ export function withStoreSnapshot(dir, waitMs, fn) {
406
+ if (!existsSync(join(dir, STATE_FILE))) {
407
+ throw new DeliveryStoreError("STORE_CORRUPT", {
408
+ found: `no ${STATE_FILE} in ${dir}`,
409
+ expected: "a delivery store directory",
410
+ action: "Point the backup at the controller's store directory. Nothing was written.",
411
+ });
412
+ }
413
+ return withStoreLock(dir, waitMs, () => {
414
+ refuseOldGateFiles(dir);
415
+ refuseRetiredOrPending(dir);
416
+ const text = readIfExists(join(dir, STATE_FILE));
417
+ if (text === null) {
418
+ throw new DeliveryStoreError("STORE_CORRUPT", {
419
+ found: `${STATE_FILE} in ${dir} disappeared`,
420
+ expected: "a committed store file",
421
+ action: "Nothing was written. Check the store directory.",
422
+ });
423
+ }
424
+ return fn(text);
425
+ });
426
+ }
427
+ /**
428
+ * US-010: retire a store whose authority moves to a restored controller.
429
+ * Under the store lock: record the highest epoch it reached in retired.json
430
+ * (created exclusively), then move owner.lock to a superseded record. The
431
+ * old owner's next commit finds no lock naming it and is FENCED; every later
432
+ * open is refused with STORE_RETIRED. Idempotent for the same successor.
433
+ */
434
+ export function retireStore(dir, input) {
435
+ return withStoreLock(dir, input.waitMs ?? DEFAULT_LOCK_WAIT_MS, () => {
436
+ const retiredPath = join(dir, RETIRED_FILE);
437
+ const existing = readIfExists(retiredPath);
438
+ if (existing !== null) {
439
+ const rec = JSON.parse(existing);
440
+ if (rec.successorDir === input.successorDir && rec.backupId === input.backupId)
441
+ return rec;
442
+ throw new DeliveryStoreError("STORE_RETIRED", {
443
+ found: `${retiredPath} names successor ${rec.successorDir} (backup ${rec.backupId})`,
444
+ expected: `no retirement, or one for ${input.successorDir}`,
445
+ action: "This store was already retired in favour of another restore. Activate that one or investigate. Nothing was changed.",
446
+ });
447
+ }
448
+ const lockPath = join(dir, LOCK_FILE);
449
+ const lockText = readIfExists(lockPath);
450
+ const lockEpoch = lockText === null ? 0 : (parseLock(lockText)?.epoch ?? 0);
451
+ const stateEpoch = loadBase(dir).state.epoch;
452
+ const rec = {
453
+ successorDir: input.successorDir,
454
+ backupId: input.backupId,
455
+ observedEpoch: Math.max(lockEpoch, stateEpoch),
456
+ retiredAt: input.now,
457
+ };
458
+ if (!createExclusive(retiredPath, `${JSON.stringify(rec)}\n`)) {
459
+ throw new DeliveryStoreError("CONTROLLER_AMBIGUOUS", {
460
+ found: `${retiredPath} appeared while this process held the store lock`,
461
+ expected: `every writer to use the lock on ${CONTROL_DB_FILE}`,
462
+ action: CONCURRENT_START_ACTION,
463
+ });
464
+ }
465
+ if (lockText !== null) {
466
+ renameSync(lockPath, `${lockPath}.superseded-retired-${sha(lockText).slice(0, 12)}-${randomBytes(4).toString("hex")}`);
467
+ }
468
+ fsyncDir(dir);
469
+ return rec;
470
+ });
471
+ }
472
+ // ---------------------------------------------------------------------------
473
+ // Ownership.
474
+ /** Throw CONTROLLER_OWNED / CONTROLLER_AMBIGUOUS unless the existing lock may be taken over. */
475
+ function judgeLock(lockPath, existingText, me, opts) {
476
+ const existing = parseLock(existingText);
477
+ const isPidAlive = opts.isPidAlive ?? pidIsAlive;
478
+ if (opts.operatorOverride)
479
+ return "operator-override";
480
+ if (existing === null) {
481
+ throw new DeliveryStoreError("CONTROLLER_AMBIGUOUS", {
482
+ found: `${lockPath} exists but is not a readable controller lock`,
483
+ expected: "no lock, or a lock with controllerId, host, pid and epoch",
484
+ action: OVERRIDE_ACTION,
485
+ });
486
+ }
487
+ if (existing.host !== me.host) {
488
+ throw new DeliveryStoreError("CONTROLLER_AMBIGUOUS", {
489
+ found: `${lockPath} held by ${describeLock(existing)}`,
490
+ expected: `no owner, or an owner on this host (${me.host}) whose process is gone`,
491
+ action: `Whether a process on host ${existing.host} is alive cannot be proven from here. Stop that controller, then reopen with an explicit operator override.`,
492
+ });
493
+ }
494
+ if (isPidAlive(existing.pid)) {
495
+ throw new DeliveryStoreError("CONTROLLER_OWNED", {
496
+ found: `${lockPath} held by live ${describeLock(existing)}`,
497
+ expected: "no live owner",
498
+ action: `Stop controller ${existing.controllerId} (pid ${existing.pid}) or wait for it to close. If it is wedged, reopen with an explicit operator override; its later writes will be fenced.`,
499
+ });
500
+ }
501
+ return "stale-pid";
502
+ }
503
+ function lockWaitMs(opts) {
504
+ return opts.gateWaitMs ?? DEFAULT_LOCK_WAIT_MS;
505
+ }
506
+ /** Remove owner.lock under the store lock, only if it is still exactly `mine`. */
507
+ function releaseLock(dir, mine, waitMs) {
508
+ const lockPath = join(dir, LOCK_FILE);
509
+ withStoreLock(dir, waitMs, () => {
510
+ if (sameLock(readLock(lockPath), mine))
511
+ unlinkSync(lockPath);
512
+ });
513
+ }
514
+ /** Remove data temps (state.json.tmp-*), including pointer temps from the previous layout. */
515
+ function removeStateTemps(dir) {
516
+ const names = readdirSync(dir).filter((n) => n.startsWith(STATE_TEMP_PREFIX));
517
+ for (const n of names)
518
+ unlinkIfExists(join(dir, n));
519
+ return names;
520
+ }
521
+ /** Keep the original bytes of a file about to be migrated. Never overwrites. */
522
+ function writeBackup(dir, version, text) {
523
+ const path = join(dir, `${STATE_FILE}.${version}.${sha(text).slice(0, 12)}.backup`);
524
+ if (!createExclusive(path, text) && readFileSync(path, "utf8") !== text) {
525
+ throw new DeliveryStoreError("STORE_CORRUPT", {
526
+ found: `${path} exists with different content`,
527
+ expected: "no backup, or an identical one",
528
+ action: "Move the conflicting backup aside, then reopen. The store was not changed.",
529
+ });
530
+ }
531
+ fsyncDir(dir);
532
+ return path;
533
+ }
534
+ /** Epoch numbers of leftover state.e<N>.json files from the previous layout, ascending. */
535
+ function legacyEpochFiles(dir) {
536
+ return readdirSync(dir)
537
+ .map((n) => LEGACY_EPOCH_FILE_PATTERN.exec(n))
538
+ .filter((m) => m !== null)
539
+ .map((m) => Number(m[1]))
540
+ .sort((a, b) => a - b);
541
+ }
542
+ /**
543
+ * Read the committed state. Read only. state.json is authoritative; a newer
544
+ * leftover epoch file from the previous layout is preferred over it.
545
+ */
546
+ function loadBase(dir) {
547
+ const path = join(dir, STATE_FILE);
548
+ const text = readIfExists(path);
549
+ if (text === null) {
550
+ let isLink = false;
551
+ try {
552
+ isLink = lstatSync(path).isSymbolicLink();
553
+ }
554
+ catch (err) {
555
+ if (errCode(err) !== "ENOENT")
556
+ throw err;
557
+ }
558
+ if (isLink) {
559
+ throw new DeliveryStoreError("STORE_CORRUPT", {
560
+ found: `${path} is a link to a file that does not exist`,
561
+ expected: "a plain store file, or a link to an existing state.e<N>.json from the previous layout",
562
+ action: "The store was not changed. A store file is missing; restore it from a backup.",
563
+ });
564
+ }
565
+ }
566
+ let best = text === null ? { state: emptyState(), fromVersion: null, text: null } : { ...parsedBase(text, path), text };
567
+ const newest = legacyEpochFiles(dir).at(-1);
568
+ if (newest !== undefined && newest > best.state.epoch) {
569
+ const legacyPath = join(dir, `state.e${newest}.json`);
570
+ const legacyText = readFileSync(legacyPath, "utf8");
571
+ best = { ...parsedBase(legacyText, legacyPath), text: legacyText };
572
+ }
573
+ return best;
574
+ }
575
+ function parsedBase(text, path) {
576
+ const parsed = parseStoreText(text, path);
577
+ return { state: parsed.state, fromVersion: parsed.fromVersion };
578
+ }
579
+ /**
580
+ * Under the store lock: judge the current lock, read the base, then install
581
+ * our lock. Every refusal happens before anything on disk changes.
582
+ */
583
+ function claimStore(dir, me, opts) {
584
+ const lockPath = join(dir, LOCK_FILE);
585
+ return withStoreLock(dir, lockWaitMs(opts), () => {
586
+ refuseOldGateFiles(dir);
587
+ refuseRetiredOrPending(dir);
588
+ const prevText = readIfExists(lockPath);
589
+ const reason = prevText === null ? null : judgeLock(lockPath, prevText, me, opts);
590
+ const base = loadBase(dir);
591
+ const backupPath = base.fromVersion === null || base.text === null ? null : writeBackup(dir, base.fromVersion, base.text);
592
+ const prevEpoch = prevText === null ? 0 : (parseLock(prevText)?.epoch ?? 0);
593
+ const lock = { ...me, epoch: Math.max(base.state.epoch, prevEpoch) + 1 };
594
+ const lockText = JSON.stringify(lock);
595
+ let takeover = null;
596
+ try {
597
+ if (prevText === null || reason === null) {
598
+ if (!createExclusive(lockPath, lockText)) {
599
+ throw new DeliveryStoreError("CONTROLLER_AMBIGUOUS", {
600
+ found: `${lockPath} appeared while this controller held the store lock`,
601
+ expected: `every controller to change owner.lock only while holding the lock on ${CONTROL_DB_FILE}`,
602
+ action: `A controller that does not use ${CONTROL_DB_FILE} (an older build) is running against this store. Stop it, then retry.`,
603
+ });
604
+ }
605
+ }
606
+ else {
607
+ const supersededLockPath = `${lockPath}.superseded-e${lock.epoch}-${sha(prevText).slice(0, 12)}-${randomBytes(4).toString("hex")}`;
608
+ if (!createExclusive(supersededLockPath, prevText)) {
609
+ throw new DeliveryStoreError("CONTROLLER_AMBIGUOUS", {
610
+ found: `${supersededLockPath} already exists`,
611
+ expected: "a fresh superseded-lock record",
612
+ action: CONCURRENT_START_ACTION,
613
+ });
614
+ }
615
+ takeover = { reason, previousOwner: prevText, supersededLockPath };
616
+ for (const n of readdirSync(dir).filter((x) => x.startsWith(LOCK_TEMP_PREFIX)))
617
+ unlinkIfExists(join(dir, n));
618
+ const temp = join(dir, `${LOCK_TEMP_PREFIX}${randomBytes(8).toString("hex")}`);
619
+ try {
620
+ createExclusive(temp, lockText);
621
+ renameSync(temp, lockPath);
622
+ }
623
+ catch (err) {
624
+ unlinkQuietly(temp);
625
+ throw err;
626
+ }
627
+ }
628
+ fsyncDir(dir);
629
+ }
630
+ catch (err) {
631
+ // Still under the store lock. If our lock bytes reached owner.lock (an fsync or
632
+ // close failed after the write, or the directory fsync after the create or
633
+ // rename), remove exactly that lock; after a takeover the previous owner stays in
634
+ // its superseded record and is not revived. If the old lock was never replaced,
635
+ // the superseded record is dropped instead. A rollback failure is not reported.
636
+ try {
637
+ const current = readIfExists(lockPath);
638
+ if (current !== null && sameLock(parseLock(current), lock))
639
+ unlinkQuietly(lockPath);
640
+ else if (takeover !== null && current === prevText)
641
+ unlinkQuietly(takeover.supersededLockPath);
642
+ }
643
+ catch {
644
+ // The install error is the one to report.
645
+ }
646
+ throw installError(err, lockPath);
647
+ }
648
+ // Temps from an older owner were never committed; that owner is fenced at its rename.
649
+ let removedTempFiles;
650
+ try {
651
+ removedTempFiles = removeStateTemps(dir);
652
+ }
653
+ catch (err) {
654
+ // Still under the store lock: remove only the lock we just installed. After a
655
+ // takeover the previous owner stays in its superseded record and is not revived.
656
+ if (sameLock(readLock(lockPath), lock))
657
+ unlinkQuietly(lockPath);
658
+ throw ioError(err, "removing a leftover state temp in", dir);
659
+ }
660
+ return { lock, takeover, base, backupPath, removedTempFiles };
661
+ });
662
+ }
663
+ /**
664
+ * A single-writer handle on a store directory. Obtain with DeliveryStore.open;
665
+ * most callers want openDeliveryController in reconciler.ts instead.
666
+ */
667
+ export class DeliveryStore {
668
+ dir;
669
+ epoch;
670
+ report;
671
+ lock;
672
+ clock;
673
+ crashPoint;
674
+ lockWaitMs;
675
+ current;
676
+ status = "open";
677
+ seq = 0;
678
+ constructor(dir, lock, state, report, opts) {
679
+ this.dir = dir;
680
+ this.lock = lock;
681
+ this.epoch = report.epoch;
682
+ this.current = state;
683
+ this.report = report;
684
+ this.clock = opts.clock ?? Date.now;
685
+ this.crashPoint = opts.crashPoint;
686
+ this.lockWaitMs = lockWaitMs(opts);
687
+ }
688
+ /**
689
+ * Acquire ownership, load and validate the store (migrating a known older
690
+ * version), and commit the new epoch. A refusal leaves the store unchanged;
691
+ * see the header for what a failure after the claim leaves on disk.
692
+ */
693
+ static open(opts) {
694
+ if (typeof opts.controllerId !== "string" || opts.controllerId.trim() === "") {
695
+ throw new DeliveryStoreError("INVALID_RECORD", {
696
+ found: "an empty controllerId",
697
+ expected: "a non-empty controller id",
698
+ action: "Pass a stable controllerId when opening the store.",
699
+ });
700
+ }
701
+ const clock = opts.clock ?? Date.now;
702
+ const acquiredAt = new Date(clock()).toISOString();
703
+ const me = {
704
+ controllerId: opts.controllerId,
705
+ host: opts.host ?? hostname(),
706
+ pid: opts.pid ?? process.pid,
707
+ acquiredAt,
708
+ };
709
+ mkdirSync(opts.dir, { recursive: true });
710
+ refuseRetiredOrPending(opts.dir);
711
+ // Refuse a corrupt or newer store before owner.db exists, so a refused
712
+ // open leaves the directory as it was. claimStore reads it again under the lock.
713
+ loadBase(opts.dir);
714
+ const { lock, takeover, base, backupPath, removedTempFiles } = claimStore(opts.dir, me, opts);
715
+ const epoch = lock.epoch;
716
+ const report = { epoch, migratedFrom: base.fromVersion, backupPath, takeover, removedTempFiles };
717
+ let store = null;
718
+ try {
719
+ opts.crashPoint?.("claimed");
720
+ store = new DeliveryStore(opts.dir, lock, base.state, report, opts);
721
+ store.commit(epoch, (draft) => {
722
+ draft.epoch = epoch;
723
+ draft.controllers.push({
724
+ epoch,
725
+ controllerId: me.controllerId,
726
+ host: me.host,
727
+ pid: me.pid,
728
+ acquiredAt,
729
+ takeover: takeover
730
+ ? {
731
+ reason: takeover.reason,
732
+ previousOwner: takeover.previousOwner.slice(0, PREVIOUS_OWNER_LIMIT),
733
+ note: opts.operatorOverride?.reason ?? null,
734
+ }
735
+ : null,
736
+ });
737
+ });
738
+ }
739
+ catch (err) {
740
+ try {
741
+ releaseLock(opts.dir, lock, lockWaitMs(opts));
742
+ }
743
+ catch {
744
+ // The lock stays; a later open takes it over as stale. Report the original error.
745
+ }
746
+ throw err;
747
+ }
748
+ // state.json now durably holds our epoch; leftover epoch files from the previous layout are obsolete.
749
+ // They are older than state.json, so one left behind is never read as the base.
750
+ try {
751
+ for (const n of legacyEpochFiles(opts.dir))
752
+ unlinkIfExists(join(opts.dir, `state.e${n}.json`));
753
+ }
754
+ catch (err) {
755
+ try {
756
+ store.close();
757
+ }
758
+ catch {
759
+ // The lock stays; a later open takes it over as stale. Report the original error.
760
+ }
761
+ throw ioError(err, "removing a previous-layout epoch file in", opts.dir);
762
+ }
763
+ return store;
764
+ }
765
+ /** The committed state. Read only: change it through commit(). */
766
+ get state() {
767
+ return this.current;
768
+ }
769
+ /** ISO timestamp from the injected clock. */
770
+ now() {
771
+ return new Date(this.clock()).toISOString();
772
+ }
773
+ /**
774
+ * Apply `mutate` to a copy of the state, validate the result and commit it
775
+ * atomically. `epoch` is the caller's fencing epoch; a write from any epoch
776
+ * other than the current owner's is rejected with FENCED. When mutate
777
+ * throws, nothing is written. Success means the write is in every later
778
+ * owner's base. STORE_IO and CONTROLLER_AMBIGUOUS mean nothing was written
779
+ * and the handle stays usable, so the commit can be retried.
780
+ */
781
+ commit(epoch, mutate) {
782
+ this.assertWritable(epoch);
783
+ const draft = structuredClone(this.current);
784
+ mutate(draft);
785
+ const errors = validateState(draft);
786
+ if (errors.length > 0) {
787
+ throw new DeliveryStoreError("INVALID_RECORD", {
788
+ found: errors.slice(0, 5).join("; "),
789
+ expected: "a store state where every record is valid under the US-001 contracts",
790
+ action: "Fix the input. Nothing was written.",
791
+ });
792
+ }
793
+ try {
794
+ this.writeAtomic(serializeState(draft));
795
+ }
796
+ catch (err) {
797
+ const retryable = err instanceof DeliveryStoreError && (err.code === "STORE_IO" || err.code === "CONTROLLER_AMBIGUOUS");
798
+ // Otherwise the disk may hold either state now; this handle must not guess. A fence stays a fence.
799
+ if (this.status === "open" && !retryable)
800
+ this.status = "failed";
801
+ throw err;
802
+ }
803
+ this.current = draft;
804
+ }
805
+ /**
806
+ * Release ownership. Idempotent. A fenced handle leaves the new owner's
807
+ * lock alone. If the release cannot run (the store lock is busy), the handle stays
808
+ * as it was and close can be retried.
809
+ */
810
+ close() {
811
+ if (this.status === "open" || this.status === "failed")
812
+ releaseLock(this.dir, this.lock, this.lockWaitMs);
813
+ if (this.status !== "fenced")
814
+ this.status = "closed";
815
+ }
816
+ /**
817
+ * Throw unless this handle is open and owner.lock still names it: STORE_CLOSED
818
+ * for a closed or failed handle, FENCED (and the handle is fenced) when
819
+ * another controller owns the store. Read only.
820
+ */
821
+ assertOwner() {
822
+ this.assertWritable(this.epoch);
823
+ }
824
+ fence(found) {
825
+ this.status = "fenced";
826
+ throw new DeliveryStoreError("FENCED", {
827
+ found,
828
+ expected: `writes only from the current owner`,
829
+ action: `Controller ${this.lock.controllerId} at epoch ${this.epoch} was superseded; this write was not persisted. Stop it and do not retry the write; the current owner holds the store.`,
830
+ });
831
+ }
832
+ /** Fence unless owner.lock still names exactly this handle. */
833
+ assertLockMine(epoch) {
834
+ const lock = readLock(join(this.dir, LOCK_FILE));
835
+ if (!sameLock(lock, this.lock)) {
836
+ this.fence(`a write from epoch ${epoch}, but ${LOCK_FILE} now names ${lock ? describeLock(lock) : "no readable owner"}`);
837
+ }
838
+ }
839
+ assertWritable(epoch) {
840
+ if (this.status === "closed") {
841
+ throw new DeliveryStoreError("STORE_CLOSED", {
842
+ found: "a closed store handle",
843
+ expected: "an open handle",
844
+ action: "Open the store again.",
845
+ });
846
+ }
847
+ if (this.status === "failed") {
848
+ throw new DeliveryStoreError("STORE_CLOSED", {
849
+ found: "a handle whose last commit did not finish",
850
+ expected: "an open handle",
851
+ action: "Reopen the store; the last committed state is recovered on open.",
852
+ });
853
+ }
854
+ if (this.status === "fenced")
855
+ this.fence(`a write from epoch ${epoch} on a handle already fenced`);
856
+ if (epoch !== this.epoch) {
857
+ throw new DeliveryStoreError("FENCED", {
858
+ found: `a write carrying epoch ${epoch}`,
859
+ expected: `the owner epoch ${this.epoch}`,
860
+ action: "Pass the epoch of the handle that owns the store. Nothing was written.",
861
+ });
862
+ }
863
+ this.assertLockMine(epoch);
864
+ }
865
+ /**
866
+ * The temp file is gone, so a takeover removed it. Fence if ownership
867
+ * moved; otherwise something else touched the store.
868
+ */
869
+ tempVanished(temp) {
870
+ this.assertLockMine(this.epoch);
871
+ throw new DeliveryStoreError("STORE_CORRUPT", {
872
+ found: `${temp} disappeared during a commit while this controller still owns the store`,
873
+ expected: "the temp file to stay until it is renamed",
874
+ action: "Stop this controller and reopen the store; the last committed state is recovered on open.",
875
+ });
876
+ }
877
+ writeAtomic(text) {
878
+ this.seq += 1;
879
+ const temp = join(this.dir, `${STATE_TEMP_PREFIX}${this.epoch}-${this.seq}`);
880
+ const target = join(this.dir, STATE_FILE);
881
+ const buf = Buffer.from(text);
882
+ const half = Math.floor(buf.length / 2);
883
+ let fd;
884
+ try {
885
+ fd = openSync(temp, "wx");
886
+ }
887
+ catch (err) {
888
+ throw ioError(err, "creating", temp);
889
+ }
890
+ try {
891
+ writeAll(fd, buf.subarray(0, half));
892
+ this.crashPoint?.("temp-partial");
893
+ writeAll(fd, buf.subarray(half));
894
+ fsyncSync(fd);
895
+ }
896
+ finally {
897
+ closeSync(fd);
898
+ }
899
+ this.crashPoint?.("temp-written");
900
+ let entered = false;
901
+ try {
902
+ withStoreLock(this.dir, this.lockWaitMs, () => {
903
+ entered = true;
904
+ try {
905
+ this.assertLockMine(this.epoch);
906
+ }
907
+ catch (err) {
908
+ unlinkQuietly(temp);
909
+ throw err;
910
+ }
911
+ try {
912
+ renameSync(temp, target);
913
+ }
914
+ catch (err) {
915
+ if (errCode(err) === "ENOENT")
916
+ this.tempVanished(temp);
917
+ unlinkQuietly(temp);
918
+ throw ioError(err, "renaming onto", target);
919
+ }
920
+ fsyncDir(this.dir);
921
+ });
922
+ }
923
+ catch (err) {
924
+ // The store lock could not be taken: nothing was renamed, so the temp is ours to remove.
925
+ if (!entered)
926
+ unlinkQuietly(temp);
927
+ throw err;
928
+ }
929
+ this.crashPoint?.("renamed");
930
+ }
931
+ }
932
+ /** True if `dir` holds a store file. */
933
+ export function storeExists(dir) {
934
+ if (!existsSync(dir))
935
+ return false;
936
+ if (existsSync(join(dir, STATE_FILE)))
937
+ return true;
938
+ return legacyEpochFiles(dir).length > 0;
939
+ }
940
+ //# sourceMappingURL=store.js.map