quilltap 4.15.0-dev.2 → 4.16.0-dev.10

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.
@@ -1,13 +1,46 @@
1
1
  'use strict';
2
2
 
3
+ const crypto = require('crypto');
3
4
  const fs = require('fs');
4
5
  const os = require('os');
5
6
  const path = require('path');
6
- const { execSync } = require('child_process');
7
+ const { execFileSync } = require('child_process');
7
8
 
9
+ // ============================================================================
10
+ // Is this lock held?
11
+ //
12
+ // One predicate answers that for the whole CLI: the writers (`db --write`,
13
+ // `db optimize`, `instances restore-key`, `maintenance run`) through
14
+ // getLockStatus(), and `db --lock-status` / `--lock-clean` / `--lock-override`
15
+ // through assessLock() directly. It mirrors the server's own decision in
16
+ // lib/database/backends/sqlite/instance-lock.ts (decideLockClaim), which this
17
+ // plain-JS package cannot import. So that the two cannot drift, both are run
18
+ // against one table of cases:
19
+ // __tests__/unit/lib/database/instance-lock-verdicts.fixture.json.
20
+ //
21
+ // A hostname that differs from ours does NOT mean a different machine. macOS
22
+ // derives gethostname() dynamically when `scutil --get HostName` is unset, so
23
+ // one Mac reports e.g. "MacBook-Pro.local" and "Mac" at different times (bug
24
+ // 126). Reading "different hostname" as "someone else's dead lock" is how a
25
+ // writer came to open the database beside a running server.
26
+ // ============================================================================
27
+
28
+ /**
29
+ * How long a lock's heartbeat may go unrefreshed before its holder is presumed
30
+ * gone. Must equal HEARTBEAT_FRESH_MS in the server's instance-lock.ts; the
31
+ * shared verdict table pins both.
32
+ */
8
33
  const HEARTBEAT_FRESH_MS = 5 * 60 * 1000;
9
- const VM_ENVIRONMENTS = new Set(['docker']);
10
34
 
35
+ /**
36
+ * How long a lock file that is not a lock record must have sat untouched
37
+ * before it may be removed as a crash's leftover. A writer that creates the
38
+ * file and then fills it in leaves it empty for an instant. Equals
39
+ * CORRUPT_LOCK_SETTLE_MS in the server's instance-lock.ts.
40
+ */
41
+ const CORRUPT_LOCK_SETTLE_MS = 5000;
42
+
43
+ /** Check whether a PID is alive using signal 0. EPERM means it exists. */
11
44
  function isPidAlive(pid) {
12
45
  try {
13
46
  process.kill(pid, 0);
@@ -17,28 +50,27 @@ function isPidAlive(pid) {
17
50
  }
18
51
  }
19
52
 
53
+ /** Command names a Quilltap server runs under; the server's probe uses the same. */
54
+ const QUILLTAP_PROCESS_PATTERN = /node|electron|quilltap|next-server/i;
55
+
56
+ /**
57
+ * Does this PID look like a Node/Quilltap process (best effort)? Conservative:
58
+ * answers true whenever it cannot tell. The server's copy is
59
+ * `pidLooksLikeNode` in lib/database/backends/sqlite/instance-lock.ts.
60
+ */
20
61
  function verifyPidIsNode(pid) {
62
+ if (!Number.isInteger(pid) || pid <= 0) return false;
63
+ const probe = { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'pipe'] };
21
64
  try {
22
65
  if (process.platform === 'linux') {
23
- try {
24
- const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
25
- const cmd = cmdline.split('\0')[0] || '';
26
- return /node|electron|quilltap|next-server/i.test(cmd);
27
- } catch {
28
- return true;
29
- }
66
+ const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
67
+ return QUILLTAP_PROCESS_PATTERN.test(cmdline.split('\0')[0] || '');
30
68
  }
31
69
  if (process.platform === 'darwin') {
32
- const output = execSync(`ps -p ${pid} -o comm=`, {
33
- encoding: 'utf8', timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'],
34
- }).trim();
35
- return /node|electron|quilltap|next-server/i.test(output);
70
+ return QUILLTAP_PROCESS_PATTERN.test(execFileSync('ps', ['-p', String(pid), '-o', 'comm='], probe).trim());
36
71
  }
37
72
  if (process.platform === 'win32') {
38
- const output = execSync(`tasklist /FI "PID eq ${pid}" /NH`, {
39
- encoding: 'utf8', timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'],
40
- }).trim();
41
- return /node|electron|quilltap|next-server/i.test(output);
73
+ return QUILLTAP_PROCESS_PATTERN.test(execFileSync('tasklist', ['/FI', `PID eq ${pid}`, '/NH'], probe).trim());
42
74
  }
43
75
  return true;
44
76
  } catch {
@@ -46,68 +78,143 @@ function verifyPidIsNode(pid) {
46
78
  }
47
79
  }
48
80
 
81
+ /**
82
+ * THE predicate. Pure: every fact about the outside world comes in as an
83
+ * argument, which is what lets the shared verdict table drive it.
84
+ *
85
+ * The rule, which is the server's, case for case:
86
+ * - The PID is alive here and looks like Node/Quilltap: active, under any
87
+ * hostname and however old the heartbeat. On a Mac whose hostname has
88
+ * flipped that PID is the running server, and a heartbeat can be old while
89
+ * the process is asleep or busy.
90
+ * - Same hostname, PID dead: stale at once, whatever the heartbeat says.
91
+ * - Same hostname, PID alive but not Node/Quilltap: the PID has most likely
92
+ * been reused since a crash. `suspect` (held) while the heartbeat is
93
+ * fresh, stale once it is not.
94
+ * - Different hostname otherwise: held while the heartbeat is fresh, in ANY
95
+ * environment, not only Docker.
96
+ *
97
+
98
+ * @param {object} lock The parsed lock record.
99
+ * @param {{ hostname: string, pidAlive: boolean, looksLikeNode: boolean, now: number }} facts
100
+ * `hostname` is the name this machine reports now; `pidAlive` whether
101
+ * lock.pid exists here; `looksLikeNode` whether that process looks like
102
+ * Node/Quilltap (ignored when the PID is dead); `now` in epoch ms.
103
+ * @returns {{ state: 'active'|'suspect'|'stale', reason: string, sameHost: boolean,
104
+ * alive: boolean, isNode: boolean, heartbeatAgeMs: number, heartbeatFresh: boolean }}
105
+ * A writer may claim the lock only when `state` is 'stale'.
106
+ */
107
+ function assessLockRecord(lock, { hostname, pidAlive, looksLikeNode, now }) {
108
+ const sameHost = lock.hostname === hostname;
109
+ const alive = Boolean(pidAlive);
110
+ const isNode = alive && Boolean(looksLikeNode);
111
+ const heartbeatAgeMs = lock.lastHeartbeat
112
+ ? now - new Date(lock.lastHeartbeat).getTime()
113
+ : Infinity;
114
+ const heartbeatFresh = heartbeatAgeMs < HEARTBEAT_FRESH_MS;
115
+ const verdict = (state, reason) => ({
116
+ state, reason, sameHost, alive, isNode, heartbeatAgeMs, heartbeatFresh,
117
+ });
118
+
119
+ if (sameHost) {
120
+ if (!alive) {
121
+ return verdict('stale', `PID ${lock.pid} is no longer running`);
122
+ }
123
+ if (isNode) {
124
+ return verdict('active', `held by PID ${lock.pid} on this host`);
125
+ }
126
+ if (heartbeatFresh) {
127
+ return verdict(
128
+ 'suspect',
129
+ `PID ${lock.pid} is alive but does not look like a Quilltap process, and its heartbeat is still fresh`,
130
+ );
131
+ }
132
+ return verdict(
133
+ 'stale',
134
+ `PID ${lock.pid} is alive but does not look like a Quilltap process, and the lock has no recent heartbeat — the PID has been reused`,
135
+ );
136
+ }
137
+
138
+ if (isNode) {
139
+ return verdict(
140
+ 'active',
141
+ `held by PID ${lock.pid}, which is alive on this machine (the lock was recorded under hostname ${lock.hostname})`,
142
+ );
143
+ }
144
+ if (heartbeatFresh) {
145
+ const ageStr = Math.round(heartbeatAgeMs / 1000) + 's';
146
+ return verdict(
147
+ 'active',
148
+ `held by ${lock.environment || 'unknown'} instance on ${lock.hostname} (heartbeat ${ageStr} ago)`,
149
+ );
150
+ }
151
+ return verdict('stale', `held by ${lock.hostname} but no recent heartbeat`);
152
+ }
153
+
154
+ /**
155
+ * The predicate applied to this machine, now: probes the PID and reads the
156
+ * clock, then defers to assessLockRecord(). The PID is probed whatever
157
+ * hostname the lock records.
158
+ */
159
+ function assessLock(lock, hostname = os.hostname()) {
160
+ const pidAlive = isPidAlive(lock.pid);
161
+ const looksLikeNode = pidAlive ? verifyPidIsNode(lock.pid) : false;
162
+ return assessLockRecord(lock, { hostname, pidAlive, looksLikeNode, now: Date.now() });
163
+ }
164
+
165
+ /**
166
+ * Read the lock file.
167
+ *
168
+ * @returns {{ state: 'absent' } | { state: 'corrupt', error: Error } | { state: 'ok', lock: object }}
169
+ * `corrupt` covers a file that cannot be read and one that is not a JSON
170
+ * object; either way nothing here may be taken for "no lock".
171
+ */
172
+ function readLockRecord(lockPath) {
173
+ let raw;
174
+ try {
175
+ raw = fs.readFileSync(lockPath, 'utf8');
176
+ } catch (err) {
177
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return { state: 'absent' };
178
+ return { state: 'corrupt', error: err };
179
+ }
180
+ let lock;
181
+ try {
182
+ lock = JSON.parse(raw);
183
+ } catch (err) {
184
+ return { state: 'corrupt', error: err };
185
+ }
186
+ if (lock === null || typeof lock !== 'object' || Array.isArray(lock)) {
187
+ return { state: 'corrupt', error: new Error('lock file is not a JSON object') };
188
+ }
189
+ return { state: 'ok', lock };
190
+ }
191
+
49
192
  /**
50
193
  * Inspect the instance lock at <dataDir>/quilltap.lock and decide whether it
51
194
  * is *actively* held by a live Quilltap process.
52
195
  *
53
196
  * Returns:
54
- * { state: 'absent' } — no lock file
197
+ * { state: 'absent', lockPath } — no lock file
55
198
  * { state: 'corrupt', lockPath } — file exists but unreadable
56
199
  * { state: 'active', lock, lockPath, reason } — held by a live owner
57
200
  * { state: 'stale', lock, lockPath, reason } — owner is gone
58
201
  * { state: 'suspect', lock, lockPath, reason } — PID alive but not Quilltap-shaped
202
+ *
203
+ * The last three are assessLock()'s verdict, unaltered.
59
204
  */
60
205
  function getLockStatus(dataDir) {
61
206
  const lockPath = path.join(dataDir, 'quilltap.lock');
207
+ const read = readLockRecord(lockPath);
62
208
 
63
- if (!fs.existsSync(lockPath)) {
209
+ if (read.state === 'absent') {
64
210
  return { state: 'absent', lockPath };
65
211
  }
66
-
67
- let lock;
68
- try {
69
- lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
70
- } catch {
212
+ if (read.state === 'corrupt') {
71
213
  return { state: 'corrupt', lockPath };
72
214
  }
73
215
 
74
- const hostname = os.hostname();
75
- const sameHost = lock.hostname === hostname;
76
-
77
- if (sameHost) {
78
- const alive = isPidAlive(lock.pid);
79
- if (!alive) {
80
- return { state: 'stale', lock, lockPath, reason: `PID ${lock.pid} is no longer running` };
81
- }
82
- const isNode = verifyPidIsNode(lock.pid);
83
- if (!isNode) {
84
- return {
85
- state: 'suspect',
86
- lock, lockPath,
87
- reason: `PID ${lock.pid} is alive but does not look like a Quilltap process`,
88
- };
89
- }
90
- return { state: 'active', lock, lockPath, reason: `held by PID ${lock.pid} on this host` };
91
- }
92
-
93
- // Different hostname — could be a VM/container sharing the data dir.
94
- const isVM = VM_ENVIRONMENTS.has(lock.environment);
95
- const heartbeatAgeMs = lock.lastHeartbeat
96
- ? Date.now() - new Date(lock.lastHeartbeat).getTime()
97
- : Infinity;
98
- if (isVM && heartbeatAgeMs < HEARTBEAT_FRESH_MS) {
99
- const ageStr = Math.round(heartbeatAgeMs / 1000) + 's';
100
- return {
101
- state: 'active',
102
- lock, lockPath,
103
- reason: `held by ${lock.environment} instance on ${lock.hostname} (heartbeat ${ageStr} ago)`,
104
- };
105
- }
106
- return {
107
- state: 'stale',
108
- lock, lockPath,
109
- reason: `held by ${lock.hostname} but no recent heartbeat`,
110
- };
216
+ const { state, reason } = assessLock(read.lock);
217
+ return { state, lock: read.lock, lockPath, reason };
111
218
  }
112
219
 
113
220
  // ============================================================================
@@ -174,6 +281,7 @@ function resolveServerPort({ port, instance, dataDir } = {}) {
174
281
  };
175
282
  }
176
283
 
284
+
177
285
  // ============================================================================
178
286
  // Write-lock acquire / release
179
287
  //
@@ -192,12 +300,29 @@ function resolveServerPort({ port, instance, dataDir } = {}) {
192
300
 
193
301
  const MAX_HISTORY_ENTRIES = 50;
194
302
 
195
- // Module-level record of the lock path we currently own, so release is safe to
196
- // call repeatedly (exit handler + explicit finally) and from signal handlers.
197
- let ownedLockPath = null;
303
+ // The lock record this process wrote, captured at write time: where it is, and
304
+ // the PID and acquisition timestamp in it. "Is this lock mine" is answered
305
+ // against this snapshot, the way the server answers it — never by comparing
306
+ // hostnames, which can change under a long `db --repl --write` session and
307
+ // would then make us drop our own heartbeat and leave our own lock behind.
308
+ // Any process that takes the lock overwrites both fields, so a real takeover
309
+ // still shows.
310
+ let ownedLock = null;
198
311
  let heartbeatTimer = null;
199
312
  let exitHandlersRegistered = false;
200
313
 
314
+ function rememberOwnedLock(lockPath, content) {
315
+ ownedLock = { lockPath, pid: content.pid, startedAt: content.startedAt };
316
+ }
317
+
318
+ /** Is the record at `lockPath` still the one this process wrote? */
319
+ function isOwnedLock(lockPath, lock) {
320
+ return ownedLock !== null &&
321
+ ownedLock.lockPath === lockPath &&
322
+ lock.pid === ownedLock.pid &&
323
+ lock.startedAt === ownedLock.startedAt;
324
+ }
325
+
201
326
  /**
202
327
  * Detect the runtime environment for lock metadata. JS port of the server's
203
328
  * detectEnvironmentType() so a CLI run inside Docker writes the right
@@ -241,9 +366,18 @@ function addHistoryEntry(content, event, detail) {
241
366
  return { ...content, history };
242
367
  }
243
368
 
244
- /** Write lock content atomically via tmp + rename (matches the server). */
369
+ /**
370
+ * A temp name beside the lock that no other writer will pick. Two processes
371
+ * sharing one temp name could rename each other's half-written file into
372
+ * place, and a file at the lock path must always be a complete record.
373
+ */
374
+ function tempPathFor(lockPath) {
375
+ return `${lockPath}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
376
+ }
377
+
378
+ /** Replace the lock file atomically via tmp + rename (matches the server). */
245
379
  function writeLockFileAtomic(lockPath, content) {
246
- const tmpPath = lockPath + '.tmp';
380
+ const tmpPath = tempPathFor(lockPath);
247
381
  try {
248
382
  fs.writeFileSync(tmpPath, JSON.stringify(content, null, 2) + '\n', 'utf8');
249
383
  fs.renameSync(tmpPath, lockPath);
@@ -253,6 +387,73 @@ function writeLockFileAtomic(lockPath, content) {
253
387
  }
254
388
  }
255
389
 
390
+ /** Write `data` to an open descriptor and push it to disk where the filesystem can. */
391
+ function writeAndSync(fd, data) {
392
+ fs.writeSync(fd, data, 0, 'utf8');
393
+ try { fs.fsyncSync(fd); } catch { /* not every filesystem can; nothing depends on it */ }
394
+ }
395
+
396
+ /**
397
+ * Create the lock file, failing if one exists, so that it is never visible
398
+ * half-written (matches the server's createLockFileExclusive).
399
+ *
400
+ * The record is written to a temp file and hard-linked into place: link()
401
+ * fails with EEXIST when a lock is already there, and the name appears with
402
+ * the whole record behind it. The server claims a lock file that is not a
403
+ * complete record as left over from a crash, which is only safe if no live
404
+ * writer ever shows one — an exclusive create followed by a write does.
405
+ *
406
+ * @returns {boolean} true if we created the lock; false if one is there.
407
+ */
408
+ function createLockFileExclusive(lockPath, content) {
409
+ const data = JSON.stringify(content, null, 2) + '\n';
410
+ const tmpPath = tempPathFor(lockPath);
411
+ try {
412
+ const fd = fs.openSync(tmpPath, 'wx');
413
+ try {
414
+ writeAndSync(fd, data);
415
+ } finally {
416
+ fs.closeSync(fd);
417
+ }
418
+ try {
419
+ fs.linkSync(tmpPath, lockPath);
420
+ return true;
421
+ } catch (err) {
422
+ if (err.code === 'EEXIST') return false;
423
+ // Anything else, having just written a file in this directory, means the
424
+ // filesystem has no hard links (exFAT, some network mounts). Fall through.
425
+ }
426
+ } finally {
427
+ try { fs.unlinkSync(tmpPath); } catch { /* ignore cleanup failure */ }
428
+ }
429
+ return createLockFileWithoutHardLinks(lockPath, content, data);
430
+ }
431
+
432
+ /**
433
+ * Exclusive create for a filesystem without hard links. Still exclusive, but
434
+ * the file exists empty for an instant before the record lands in it, and a
435
+ * process reading it in that instant takes it for a crash leftover and claims
436
+ * it. So the create only counts if our record is what is there afterwards.
437
+ */
438
+ function createLockFileWithoutHardLinks(lockPath, content, data) {
439
+ let fd;
440
+ try {
441
+ fd = fs.openSync(lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY);
442
+ } catch (err) {
443
+ if (err.code === 'EEXIST') return false;
444
+ throw err;
445
+ }
446
+ try {
447
+ writeAndSync(fd, data);
448
+ } finally {
449
+ fs.closeSync(fd);
450
+ }
451
+ const read = readLockRecord(lockPath);
452
+ return read.state === 'ok' &&
453
+ read.lock.pid === content.pid &&
454
+ read.lock.startedAt === content.startedAt;
455
+ }
456
+
256
457
  function startHeartbeat(lockPath) {
257
458
  stopHeartbeat();
258
459
  // 60s like the server. unref() so a one-shot command (which exits in
@@ -260,14 +461,18 @@ function startHeartbeat(lockPath) {
260
461
  // sessions ever actually beat.
261
462
  heartbeatTimer = setInterval(() => {
262
463
  try {
263
- const raw = fs.readFileSync(lockPath, 'utf8');
264
- const lock = JSON.parse(raw);
265
- if (lock.pid !== process.pid || lock.hostname !== os.hostname()) {
464
+ const read = readLockRecord(lockPath);
465
+ // Gone, or unreadable this tick: nothing to refresh. Try again next tick.
466
+ if (read.state !== 'ok') return;
467
+ if (!isOwnedLock(lockPath, read.lock)) {
266
468
  // We no longer own the lock — stop beating, don't fight over it.
267
469
  stopHeartbeat();
268
470
  return;
269
471
  }
472
+ const lock = read.lock;
270
473
  lock.lastHeartbeat = new Date().toISOString();
474
+ // The hostname is a label; keep it current when the OS renames us.
475
+ lock.hostname = os.hostname();
271
476
  writeLockFileAtomic(lockPath, lock);
272
477
  } catch { /* best effort */ }
273
478
  }, 60_000);
@@ -309,8 +514,9 @@ function acquireWriteLock(dataDir) {
309
514
  if (status.state === 'active') {
310
515
  lines.push('Stop the running Quilltap instance before opening the database read-write.');
311
516
  } else {
312
- lines.push('This may be a stale lock from a reused PID. Inspect it with');
313
- lines.push('`quilltap db --lock-status` and clean it with `quilltap db --lock-clean` if safe.');
517
+ // `--lock-clean` refuses a fresh heartbeat, and a suspect lock has one.
518
+ lines.push('Its PID may have been reused since a crash. The lock is claimed automatically once its');
519
+ lines.push(`heartbeat is ${Math.round(HEARTBEAT_FRESH_MS / 60000)} minutes old; try again then.`);
314
520
  }
315
521
  lines.push('(See `quilltap db --lock-status` for details.)');
316
522
  const err = new Error(lines.join('\n'));
@@ -326,94 +532,87 @@ function acquireWriteLock(dataDir) {
326
532
 
327
533
  if (status.state === 'stale') {
328
534
  // Dead PID / no recent heartbeat — claim it, preserving history.
329
- claimStaleLock(lockPath, status.lock, status.reason);
330
- finishAcquire(dataDir, lockPath);
535
+ finishAcquire(dataDir, lockPath, claimStaleLock(lockPath, status.lock, status.reason));
331
536
  return;
332
537
  }
333
538
 
334
- // Absent — atomic create so we lose cleanly to any racing process.
539
+ // Absent — exclusive create so we lose cleanly to any racing process.
335
540
  const content = addHistoryEntry(buildLockContent(), 'acquired', 'Read-write CLI session (quilltap db --write)');
336
- const jsonData = JSON.stringify(content, null, 2) + '\n';
337
- try {
338
- const fd = fs.openSync(lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY);
339
- try {
340
- fs.writeSync(fd, jsonData, 0, 'utf8');
341
- } finally {
342
- fs.closeSync(fd);
343
- }
344
- finishAcquire(dataDir, lockPath);
541
+ if (createLockFileExclusive(lockPath, content)) {
542
+ finishAcquire(dataDir, lockPath, content);
345
543
  return;
346
- } catch (err) {
347
- if (err.code !== 'EEXIST') throw err;
348
- // Someone created the lock between our check and our create. Re-decide.
349
- const recheck = getLockStatus(dataDir);
350
- if (recheck.state === 'active' || recheck.state === 'suspect' || recheck.state === 'corrupt') {
351
- const e = new Error(
352
- `Database is currently in use — ${recheck.reason || 'lock just claimed by another process'}.\n` +
353
- 'Stop the running Quilltap instance before opening the database read-write.',
354
- );
355
- e.locked = true;
356
- throw e;
357
- }
358
- // Now stale (or absent again) — claim it.
359
- claimStaleLock(lockPath, recheck.lock || buildLockContent(), recheck.reason || 'reclaimed after race');
360
- finishAcquire(dataDir, lockPath);
361
544
  }
545
+
546
+ // Someone created the lock between our check and our create. Re-decide.
547
+ const recheck = getLockStatus(dataDir);
548
+ if (recheck.state === 'active' || recheck.state === 'suspect' || recheck.state === 'corrupt') {
549
+ const e = new Error(
550
+ `Database is currently in use — ${recheck.reason || 'lock just claimed by another process'}.\n` +
551
+ 'Stop the running Quilltap instance before opening the database read-write.',
552
+ );
553
+ e.locked = true;
554
+ throw e;
555
+ }
556
+ // Now stale (or absent again) — claim it.
557
+ finishAcquire(
558
+ dataDir,
559
+ lockPath,
560
+ claimStaleLock(lockPath, recheck.lock || buildLockContent(), recheck.reason || 'reclaimed after race'),
561
+ );
362
562
  }
363
563
 
364
- /** Overwrite a stale lock with our process info, preserving prior history. */
564
+ /**
565
+ * Overwrite a stale lock with our process info, preserving prior history.
566
+ * Returns the record written.
567
+ */
365
568
  function claimStaleLock(lockPath, existing, reason) {
366
569
  let content = { ...buildLockContent(), history: (existing && existing.history) || [] };
367
570
  content = addHistoryEntry(content, 'stale-detected', reason);
368
571
  content = addHistoryEntry(content, 'stale-claimed', `Claimed by PID ${process.pid} (quilltap db --write)`);
369
572
  writeLockFileAtomic(lockPath, content);
573
+ return content;
370
574
  }
371
575
 
372
- function finishAcquire(dataDir, lockPath) {
373
- ownedLockPath = lockPath;
576
+ function finishAcquire(dataDir, lockPath, content) {
577
+ rememberOwnedLock(lockPath, content);
374
578
  startHeartbeat(lockPath);
375
579
  registerExitHandlers(dataDir);
376
580
  }
377
581
 
378
582
  /**
379
- * Release the lock if (and only if) we own it. Idempotent; never throws.
583
+ * Release the lock if (and only if) it is still the record this process
584
+ * wrote. Idempotent; never throws.
380
585
  */
381
586
  function releaseWriteLock(dataDir) {
382
587
  stopHeartbeat();
383
588
  const lockPath = path.join(dataDir, 'quilltap.lock');
384
- if (ownedLockPath !== lockPath && ownedLockPath !== null) {
385
- // Owned a different path (shouldn't happen in one CLI run) — be conservative.
386
- }
387
589
  try {
388
- if (!fs.existsSync(lockPath)) { ownedLockPath = null; return; }
389
- let lock;
390
- try {
391
- lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
392
- } catch {
393
- // Corrupt — don't touch a lock we can't prove is ours.
394
- ownedLockPath = null;
395
- return;
396
- }
397
- if (lock.pid !== process.pid || lock.hostname !== os.hostname()) {
398
- ownedLockPath = null;
399
- return;
400
- }
401
- const updated = addHistoryEntry(lock, 'released', `Released by PID ${process.pid} (quilltap db --write)`);
590
+ const read = readLockRecord(lockPath);
591
+ // Gone already, or unreadable — don't touch a lock we can't prove is ours.
592
+ if (read.state !== 'ok') return;
593
+ if (!isOwnedLock(lockPath, read.lock)) return;
594
+ const updated = addHistoryEntry(read.lock, 'released', `Released by PID ${process.pid} (quilltap db --write)`);
402
595
  try { writeLockFileAtomic(lockPath, updated); } catch { /* best effort */ }
403
596
  try { fs.unlinkSync(lockPath); } catch { /* best effort */ }
404
597
  } catch {
405
598
  /* never throw from release */
406
599
  } finally {
407
- ownedLockPath = null;
600
+ if (ownedLock !== null && ownedLock.lockPath === lockPath) ownedLock = null;
408
601
  }
409
602
  }
410
603
 
411
604
  module.exports = {
605
+ HEARTBEAT_FRESH_MS,
606
+ CORRUPT_LOCK_SETTLE_MS,
412
607
  getLockStatus,
608
+ assessLock,
609
+ assessLockRecord,
610
+ readLockRecord,
413
611
  isPidAlive,
414
612
  verifyPidIsNode,
415
613
  acquireWriteLock,
416
614
  releaseWriteLock,
615
+ writeLockFileAtomic,
417
616
  detectEnvironmentType,
418
617
  resolveServerPort,
419
618
  DEFAULT_SERVER_PORT,
@@ -71,6 +71,17 @@ function colorizeLogLine(line) {
71
71
  return `${color}${line}${RESET}`;
72
72
  }
73
73
 
74
+ const DEFAULT_TAIL = 100;
75
+
76
+ /**
77
+ * Parse a --tail value. 0 is a real answer (the whole file), so only a value
78
+ * that is not a non-negative integer falls back to the default (issue #361).
79
+ */
80
+ function parseTail(value) {
81
+ const n = parseInt(value, 10);
82
+ return Number.isNaN(n) || n < 0 ? DEFAULT_TAIL : n;
83
+ }
84
+
74
85
  /**
75
86
  * Parse command-line arguments for the logs command.
76
87
  */
@@ -80,7 +91,7 @@ function parseFlags(args) {
80
91
  instance: '',
81
92
  passphrase: '',
82
93
  stream: 'combined',
83
- tail: 100,
94
+ tail: DEFAULT_TAIL,
84
95
  follow: false,
85
96
  grep: '',
86
97
  help: false,
@@ -102,7 +113,7 @@ function parseFlags(args) {
102
113
  } else if (arg === '--stream') {
103
114
  flags.stream = args[++i];
104
115
  } else if (arg === '--tail') {
105
- flags.tail = parseInt(args[++i], 10) || 100;
116
+ flags.tail = parseTail(args[++i]);
106
117
  } else if (arg === '--grep') {
107
118
  flags.grep = args[++i];
108
119
  }
@@ -380,4 +391,5 @@ async function logsCommand(args) {
380
391
 
381
392
  module.exports = {
382
393
  logsCommand,
394
+ parseFlags,
383
395
  };
@@ -228,6 +228,39 @@ async function handleStatus(flags) {
228
228
  }
229
229
  }
230
230
 
231
+ /**
232
+ * Delete every `doc_mount_files` row that no link references, with its
233
+ * payload. Returns how many file rows went.
234
+ *
235
+ * The payload rows (`doc_mount_documents`, `doc_mount_blobs`) are deleted
236
+ * explicitly, before the file row: a mount index whose tables came from the
237
+ * schema translator carries no foreign keys, so nothing cascades and a bare
238
+ * delete of the file row would keep its payload forever. This MIRRORS the
239
+ * server's `gcOrphanedFileRow` (`lib/mount-index/orphan-store-reaper.ts`),
240
+ * which `sweepOrphanedFiles` runs for each orphan. Keep them in step. Both
241
+ * payload tables are created lazily, so each is checked for first.
242
+ *
243
+ * One transaction: a failure part-way leaves nothing half-collected.
244
+ */
245
+ function sweepOrphanedMountFiles(mountsDb) {
246
+ const tableExists = (name) =>
247
+ !!mountsDb.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name);
248
+ if (!tableExists('doc_mount_files') || !tableExists('doc_mount_file_links')) return 0;
249
+
250
+ const orphaned = 'SELECT id FROM doc_mount_files WHERE id NOT IN (SELECT DISTINCT fileId FROM doc_mount_file_links)';
251
+ const sweep = mountsDb.transaction(() => {
252
+ for (const payloadTable of ['doc_mount_documents', 'doc_mount_blobs']) {
253
+ if (tableExists(payloadTable)) {
254
+ mountsDb.prepare(`DELETE FROM ${payloadTable} WHERE fileId IN (${orphaned})`).run();
255
+ }
256
+ }
257
+ return mountsDb
258
+ .prepare('DELETE FROM doc_mount_files WHERE id NOT IN (SELECT DISTINCT fileId FROM doc_mount_file_links)')
259
+ .run().changes;
260
+ });
261
+ return sweep();
262
+ }
263
+
231
264
  async function handleRun(flags) {
232
265
  let resolved;
233
266
  let pepper;
@@ -321,12 +354,7 @@ async function handleRun(flags) {
321
354
  // be absent on older instances — skip gracefully.
322
355
  try {
323
356
  mountsDb = openMountIndexDb(resolved.dataDir, pepper, { readonly: false });
324
- summary.orphanedFiles = mountsDb
325
- .prepare(
326
- 'DELETE FROM doc_mount_files ' +
327
- 'WHERE id NOT IN (SELECT DISTINCT fileId FROM doc_mount_file_links)'
328
- )
329
- .run().changes;
357
+ summary.orphanedFiles = sweepOrphanedMountFiles(mountsDb);
330
358
  } catch {
331
359
  summary.orphanedFiles = 0;
332
360
  }
@@ -391,4 +419,5 @@ async function maintenanceCommand(args) {
391
419
 
392
420
  module.exports = {
393
421
  maintenanceCommand,
422
+ sweepOrphanedMountFiles,
394
423
  };