quilltap 4.15.0 → 4.16.0-dev.12

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.
package/README.md CHANGED
@@ -211,11 +211,18 @@ In the REPL, `.cols <table>` and `.find <text>` mirror the subcommand helpers.
211
211
 
212
212
  Everything that writes to an instance claims `<dataDir>/quilltap.lock` — the same lockfile the server itself uses — for the duration, and releases it on exit. That is `db --write` (including `db --repl --write`), `db optimize`, `maintenance run`, and `instances restore-key`. All four **refuse while the lock is held**: stop the server first. Read-only work — plain `db`, the `docs` read verbs, `memories`, `logs`, `migrations`, `maintenance status`, `db backup`, `db integrity` — never touches the lock and is safe alongside a running instance.
213
213
 
214
- ### The five-minute heartbeat window
214
+ ### When a lock counts as held
215
215
 
216
- A lock counts as held until its heartbeat is **five minutes** stale, whether or not the process that set it is still alive. Freshness is the fallback for every environment, not just containers: a PID check is not reliable everywhere, and cleaning a *live* instance's lock is much the worse failure.
216
+ The server and the CLI's writers decide the same way, case for case; one table of cases is tested against both.
217
217
 
218
- So for up to five minutes after stopping the server, `--write`, `optimize`, `maintenance run`, `restore-key`, and `--lock-clean` all still refuse. That is correct behaviour, not a stale lock. Wait it out; the next startup reclaims the lock regardless.
218
+ - **The recorded PID is alive on this machine and looks like Node or Quilltap.** The lock is held, under any hostname and however old its heartbeat. On a Mac whose reported hostname has changed, that process is the running server, and a heartbeat can be old while it is asleep or busy.
219
+ - **The lock was written on this machine, under the hostname it reports now, and its process is gone.** The lock is stale at once, and the next writer (a server starting, `--write`, `optimize`, `maintenance run`, `restore-key`) claims it.
220
+ - **The lock was written under this hostname, and its PID is alive but is not Node or Quilltap** — typically a crash, after which the PID went to some other program. The lock is held only until its heartbeat is **five minutes** stale, then claimed like any other stale lock. `--lock-status` calls it SUSPECT until then.
221
+ - **The lock was written under another hostname** (a Docker container, another machine sharing the folder, or a Mac whose reported hostname has changed) and its PID cannot be confirmed here. The heartbeat decides: the lock is held until its heartbeat is **five minutes** stale.
222
+
223
+ The server writes the heartbeat every minute. If it cannot (permissions, a full disk, a synced or network volume refusing the rename), its log says so with a warning at the first failure and an error from the third in a row, because a heartbeat that stops lets the lock go stale under a live server.
224
+
225
+ `--lock-status` and `--lock-clean` are more cautious than a writer. They treat any lock with a fresh heartbeat as active, even when its process is gone, and `--lock-clean` will not remove it until the heartbeat is five minutes stale. Cleaning a *live* instance's lock is much the worse failure.
219
226
 
220
227
  ```bash
221
228
  quilltap db --lock-status # Who holds it, and how old the heartbeat is
@@ -232,7 +239,13 @@ Wait it out, or use --lock-override to force.
232
239
 
233
240
  When a live process really does hold the lock, it refuses with "Lock is held by a live Quilltap process" instead.
234
241
 
235
- **`--lock-override` exists and is almost never the right answer** — it defeats the protection the lock provides. Reach for `--lock-status` first.
242
+ **`--lock-override` exists and is almost never the right answer** — it defeats the protection the lock provides. Reach for `--lock-status` first. It removes the lock whatever the verdict, and says which it overrode: a stale lock plainly, a held one (`active` or `suspect`) with a warning that its holder may still be writing.
243
+
244
+ When the server itself refuses to start over a held lock, its message names the remedies that work on that lock — wait for the heartbeat to go stale, stop the holder, or `--lock-override` — and not `--lock-clean`, which refuses every lock the server does.
245
+
246
+ ### A damaged lock file
247
+
248
+ A crash or power loss while the lock is being created can leave `quilltap.lock` empty or half-written. The server claims such a file at start-up, with a warning in its log, once the file has sat untouched for five seconds. The CLI's writers refuse it and say it is corrupt; `quilltap db --lock-clean` removes it (also only after those five seconds, in case another process is still writing it). A lock file that exists but cannot be read at all, for example because of its permissions, is never claimed or removed: fix the permissions, or delete the file yourself once nothing is using the instance.
236
249
 
237
250
  ## Document Stores (Scriptorium)
238
251
 
@@ -292,7 +305,7 @@ The URI authority is matched name-first, then UUID, then a former name — the s
292
305
 
293
306
  ### `--base64` flag
294
307
 
295
- `write --base64`: reads the source bytes and sends them to the server via `PUT /api/v1/mount-points/{mountId}/files/{path}` with `{content: <base64>, encoding: "base64"}`. This is the portable path the file browser uses and handles arbitrary binary files cleanly. Server-required; the direct filesystem fallback is not available with this flag.
308
+ `write --base64`: reads the source bytes and sends them to the server via `PUT /api/v1/mount-points/{mountId}/files/{path}` with `{content: <base64>, encoding: "base64", force}`. This is the portable path the file browser uses and handles arbitrary binary files cleanly. Like the default write, it refuses to replace an existing file (`DEST_EXISTS`, exit code 2) unless `--force` is given. A database-backed store converts bitmap images to WebP, so the file lands at a `.webp` path with the WebP's checksum; the CLI reports the stored path and does not treat the different checksum as an error, and the existing-file check applies to that stored path. Server-required; the direct filesystem fallback is not available with this flag.
296
309
 
297
310
  `read --base64`: fetches raw bytes via `GET /api/v1/mount-points/{mountId}/files/{path}?encoding=base64` and emits the decoded bytes to stdout, suitable for binary round-trips. Server-required.
298
311
 
package/bin/quilltap.js CHANGED
@@ -458,53 +458,27 @@ async function main() {
458
458
  // Instance Lock CLI Commands
459
459
  // ============================================================================
460
460
 
461
- /**
462
- * Check whether a PID is alive using signal 0.
463
- */
464
- function isPidAlive(pid) {
465
- try {
466
- process.kill(pid, 0);
467
- return true;
468
- } catch (err) {
469
- return err.code === 'EPERM'; // EPERM = exists but no permission
470
- }
471
- }
472
-
473
- /**
474
- * Verify a PID looks like a Node/Quilltap process (best-effort).
475
- */
476
- function verifyPidIsNode(pid, expectedArgv0) {
477
- try {
478
- if (process.platform === 'linux') {
479
- try {
480
- const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
481
- const cmd = cmdline.split('\0')[0] || '';
482
- return /node|electron|quilltap|next-server/i.test(cmd);
483
- } catch {
484
- return true; // Can't read — assume match
485
- }
486
- }
487
- if (process.platform === 'darwin') {
488
- const { execSync } = require('child_process');
489
- const output = execSync(`ps -p ${pid} -o comm=`, {
490
- encoding: 'utf8', timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'],
491
- }).trim();
492
- return /node|electron|quilltap|next-server/i.test(output);
493
- }
494
- if (process.platform === 'win32') {
495
- const { execSync } = require('child_process');
496
- const output = execSync(`tasklist /FI "PID eq ${pid}" /NH`, {
497
- encoding: 'utf8', timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'],
498
- }).trim();
499
- return /node|electron|quilltap|next-server/i.test(output);
500
- }
501
- return true;
502
- } catch {
503
- return true;
504
- }
505
- }
506
-
507
- const HEARTBEAT_FRESH_MS = 5 * 60 * 1000;
461
+ // The lock is read and judged in ../lib/lock-helpers.js. `assessLock` there is
462
+ // the one predicate for "is this lock held", shared with the commands that
463
+ // write (`db --write`, `db optimize`, `instances restore-key`, `maintenance
464
+ // run`); nothing in this file probes a PID or measures a heartbeat itself.
465
+ //
466
+ // The arms below word their output from the verdict it returns (`state`,
467
+ // `reason`) and the facts behind it (`alive`, `isNode`, `heartbeatFresh`,
468
+ // ...). In one case they are more cautious than its verdict: a fresh heartbeat
469
+ // over a dead PID recorded under our own hostname. The verdict there is stale
470
+ // — the server and the writers claim such a lock at once — but `--lock-status`
471
+ // shows it as ACTIVE by heartbeat and `--lock-clean` refuses to remove it
472
+ // until the heartbeat has aged out (lock-clean-refusal.test.ts pins that
473
+ // wording). `--lock-override` forces whatever the verdict, and words its
474
+ // warning from it.
475
+ const {
476
+ HEARTBEAT_FRESH_MS,
477
+ CORRUPT_LOCK_SETTLE_MS,
478
+ assessLock,
479
+ readLockRecord,
480
+ writeLockFileAtomic,
481
+ } = require('../lib/lock-helpers');
508
482
 
509
483
  /**
510
484
  * The freshness window in words, derived from the constant the check actually
@@ -518,37 +492,6 @@ function describeFreshWindow() {
518
492
  return minutes === 1 ? '1 minute' : `${minutes} minutes`;
519
493
  }
520
494
 
521
- /**
522
- * Decide whether a lock record belongs to a live process.
523
- *
524
- * A hostname that differs from ours does NOT mean a different machine: macOS
525
- * derives gethostname() dynamically when `scutil --get HostName` is unset, so
526
- * one Mac reports e.g. "MacBook-Pro.local" and "Mac" at different times. So
527
- * check PID liveness regardless of the recorded name, and fall back to
528
- * heartbeat freshness for any environment rather than only for containers.
529
- * See bug 126.
530
- */
531
- function assessLock(lock, hostname) {
532
- const sameHost = lock.hostname === hostname;
533
- const alive = isPidAlive(lock.pid);
534
- const isNode = alive ? verifyPidIsNode(lock.pid, lock.processArgv0 || '') : false;
535
- const heartbeatAgeMs = lock.lastHeartbeat
536
- ? Date.now() - new Date(lock.lastHeartbeat).getTime()
537
- : Infinity;
538
- const heartbeatFresh = heartbeatAgeMs < HEARTBEAT_FRESH_MS;
539
-
540
- return {
541
- sameHost,
542
- alive,
543
- isNode,
544
- heartbeatAgeMs,
545
- heartbeatFresh,
546
- // Held by something running: a confirmed local process, or any holder
547
- // still refreshing its heartbeat.
548
- live: (alive && isNode) || heartbeatFresh,
549
- };
550
- }
551
-
552
495
  /**
553
496
  * Handle --lock-status, --lock-clean, --lock-override commands.
554
497
  */
@@ -557,23 +500,45 @@ function handleLockCommand(dataDir, opts) {
557
500
  const hostname = require('os').hostname();
558
501
 
559
502
  // Read lock file
560
- let lock = null;
561
- try {
562
- if (fs.existsSync(lockPath)) {
563
- const raw = fs.readFileSync(lockPath, 'utf8');
564
- lock = JSON.parse(raw);
565
- }
566
- } catch (err) {
503
+ const read = readLockRecord(lockPath);
504
+ if (read.state === 'corrupt') {
567
505
  if (opts.lockStatus) {
568
506
  console.log('Lock file exists but is corrupt or unreadable.');
569
507
  console.log(` Path: ${lockPath}`);
570
- if (opts.lockClean) {
571
- fs.unlinkSync(lockPath);
572
- console.log(' Removed corrupt lock file.');
508
+ }
509
+ // `--lock-clean` works on its own here too: it is what `db --write` tells
510
+ // the operator to run when it meets a corrupt lock, and it used to do
511
+ // nothing unless `--lock-status` came with it.
512
+ if (opts.lockClean) {
513
+ // A file that could not be read at all (permissions, an I/O error) may be
514
+ // a live holder's lock, so it is not ours to remove. Only a file that
515
+ // was read and is not a lock record is a crash's leftover.
516
+ if (read.error && read.error.code) {
517
+ console.error(`Lock file could not be read (${read.error.code}), so it will not be removed: ${lockPath}`);
518
+ console.error('Fix what is stopping the read, or delete the file yourself once nothing is using the instance.');
519
+ process.exit(1);
573
520
  }
521
+ // A file written moments ago may be a lock some process is still filling
522
+ // in (the same grace the server gives before it claims one).
523
+ let ageMs = Infinity;
524
+ try { ageMs = Date.now() - fs.statSync(lockPath).mtimeMs; } catch { /* gone, or not ours to stat */ }
525
+ if (ageMs < CORRUPT_LOCK_SETTLE_MS) {
526
+ console.error(
527
+ `Lock file is corrupt but was written ${Math.round(ageMs / 1000)}s ago; another process may still be creating it.`
528
+ );
529
+ console.error(`Run --lock-clean again in a few seconds. Path: ${lockPath}`);
530
+ process.exit(1);
531
+ }
532
+ fs.unlinkSync(lockPath);
533
+ console.log(opts.lockStatus ? ' Removed corrupt lock file.' : `Removed corrupt lock file: ${lockPath}`);
534
+ } else if (!opts.lockStatus) {
535
+ console.error(`Lock file exists but is corrupt or unreadable: ${lockPath}`);
536
+ console.error('Remove it with `quilltap db --lock-clean` once nothing is using the instance.');
537
+ process.exit(1);
574
538
  }
575
539
  return;
576
540
  }
541
+ const lock = read.state === 'ok' ? read.lock : null;
577
542
 
578
543
  // --lock-status: display current lock state
579
544
  if (opts.lockStatus) {
@@ -583,20 +548,24 @@ function handleLockCommand(dataDir, opts) {
583
548
  return;
584
549
  }
585
550
 
586
- const { sameHost, alive, isNode, heartbeatAgeMs, heartbeatFresh } =
551
+ const { state, sameHost, alive, isNode, heartbeatAgeMs, heartbeatFresh } =
587
552
  assessLock(lock, hostname);
588
553
 
589
554
  // Status line
590
555
  let status;
591
556
  if (alive && isNode) {
592
557
  status = '\x1b[32mACTIVE\x1b[0m (process confirmed running)';
558
+ } else if (state === 'suspect') {
559
+ const ageStr = Math.round(heartbeatAgeMs / 1000) + 's';
560
+ status = `\x1b[33mSUSPECT\x1b[0m (PID alive but does not look like Quilltap — possible PID reuse; heartbeat ${ageStr} ago)` +
561
+ ` — will be auto-claimed once the heartbeat is ${describeFreshWindow()} stale`;
593
562
  } else if (heartbeatFresh) {
594
563
  const ageStr = Math.round(heartbeatAgeMs / 1000) + 's';
595
564
  status = `\x1b[32mACTIVE\x1b[0m (${lock.environment || 'unknown'}, heartbeat ${ageStr} ago)`;
596
- } else if (alive && !isNode) {
597
- status = '\x1b[33mSUSPECT\x1b[0m (PID alive but does not look like Quilltap — possible PID reuse)';
598
565
  } else if (!sameHost) {
599
566
  status = `\x1b[33mSTALE (${lock.environment || 'unknown'} on ${lock.hostname}, no recent heartbeat)\x1b[0m — will be auto-claimed on next startup`;
567
+ } else if (alive) {
568
+ status = '\x1b[33mSTALE (PID alive but does not look like Quilltap, and no recent heartbeat — PID reused)\x1b[0m — will be auto-claimed on next startup';
600
569
  } else {
601
570
  status = '\x1b[31mSTALE (process dead)\x1b[0m — will be auto-claimed on next startup';
602
571
  }
@@ -623,8 +592,10 @@ function handleLockCommand(dataDir, opts) {
623
592
  } else {
624
593
  heartbeatDisplay = `${Math.round(heartbeatAge / 3600)}h ago`;
625
594
  }
626
- // Warn if heartbeat is older than 5 minutes (process may be hung)
627
- if (alive && heartbeatAge > 300) {
595
+ // Warn if a Quilltap-shaped holder's heartbeat is older than the
596
+ // freshness window (process may be hung). A PID that is not Quilltap's
597
+ // is a reused one, not a hung server.
598
+ if (alive && isNode && heartbeatAge > Math.round(HEARTBEAT_FRESH_MS / 1000)) {
628
599
  heartbeatDisplay = `\x1b[33m${heartbeatDisplay} (stale — process may be hung)\x1b[0m`;
629
600
  }
630
601
  console.log(` Heartbeat: ${heartbeatDisplay}`);
@@ -694,9 +665,11 @@ function handleLockCommand(dataDir, opts) {
694
665
  detail: `Cleaned via CLI (quilltap db --lock-clean)`,
695
666
  });
696
667
 
697
- // Write final state then remove
668
+ // Write final state then remove. Replaced whole, never rewritten in place:
669
+ // a lock file caught half-written reads as a crash leftover to a server
670
+ // starting at that moment.
698
671
  try {
699
- fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf8');
672
+ writeLockFileAtomic(lockPath, lock);
700
673
  } catch { /* best effort */ }
701
674
 
702
675
  try {
@@ -709,27 +682,32 @@ function handleLockCommand(dataDir, opts) {
709
682
  return;
710
683
  }
711
684
 
712
- // --lock-override: forcibly claim the lock
685
+ // --lock-override: remove the lock whatever its verdict
713
686
  if (opts.lockOverride) {
714
687
  if (!lock) {
715
688
  console.log('No lock file found. Nothing to override.');
716
689
  return;
717
690
  }
718
691
 
719
- const sameHost = lock.hostname === hostname;
720
- const alive = sameHost && isPidAlive(lock.pid);
692
+ // Override forces whatever the verdict. The verdict — the same one the
693
+ // server and the writers act on — only chooses what it warns about.
694
+ const { state, reason, alive, isNode, heartbeatAgeMs } = assessLock(lock, hostname);
721
695
 
722
- if (alive) {
723
- const isNode = verifyPidIsNode(lock.pid, lock.processArgv0 || '');
724
- if (!isNode) {
725
- console.error(`Lock override rejected: PID ${lock.pid} is alive but does not appear to be`);
726
- console.error('a Quilltap/Node process. The PID may have been reused. Verify manually.');
727
- process.exit(1);
696
+ if (state === 'active') {
697
+ if (alive && isNode) {
698
+ console.log(`WARNING: Overriding lock held by live process (PID ${lock.pid}, ${lock.environment || 'unknown'}).`);
699
+ } else {
700
+ console.log(`WARNING: Overriding a lock that is still held — ${reason}.`);
728
701
  }
729
- console.log(`WARNING: Overriding lock held by live process (PID ${lock.pid}, ${lock.environment || 'unknown'}).`);
730
702
  console.log('The other instance may corrupt the database if it is still writing.');
703
+ } else if (state === 'suspect') {
704
+ console.log(
705
+ `WARNING: Overriding a lock whose PID ${lock.pid} is alive but does not look like a Quilltap process, ` +
706
+ `with a heartbeat only ${Math.round(heartbeatAgeMs / 1000)}s old.`
707
+ );
708
+ console.log('The PID has probably been reused, but if a Quilltap instance is still writing, it may corrupt the database.');
731
709
  } else {
732
- console.log(`Overriding stale lock (PID ${lock.pid} is no longer running).`);
710
+ console.log(`Overriding stale lock (${reason}).`);
733
711
  }
734
712
 
735
713
  // Record override in history
@@ -739,13 +717,13 @@ function handleLockCommand(dataDir, opts) {
739
717
  pid: process.pid,
740
718
  hostname: hostname,
741
719
  timestamp: new Date().toISOString(),
742
- detail: `Manual override via CLI (quilltap db --lock-override)` +
743
- (alive ? ` — overriding live PID ${lock.pid}` : ` — PID ${lock.pid} was dead`),
720
+ detail: `Manual override via CLI (quilltap db --lock-override) — ` +
721
+ (state === 'stale' ? `stale: ${reason}` : `overriding a held lock (${state}): ${reason}`),
744
722
  });
745
723
 
746
724
  // Write final state then remove so next startup gets a clean acquire
747
725
  try {
748
- fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n', 'utf8');
726
+ writeLockFileAtomic(lockPath, lock);
749
727
  } catch { /* best effort */ }
750
728
 
751
729
  try {
@@ -850,7 +828,7 @@ Low-level options (legacy; still supported):
850
828
  Instance Lock Commands:
851
829
  --lock-status Show the current instance lock state
852
830
  --lock-clean Remove stale locks (dead processes only)
853
- --lock-override Forcibly claim the lock for this process
831
+ --lock-override Remove the lock even if it is still held (warns first)
854
832
 
855
833
  If a passphrase is required and not provided via --passphrase, the tool
856
834
  will check the QUILLTAP_DB_PASSPHRASE environment variable, then prompt
@@ -0,0 +1,155 @@
1
+ /**
2
+ * `quilltap docs write --base64` and `docs delete` against the item route
3
+ * (#396, #397).
4
+ *
5
+ * The server is a stubbed `fetch`; the mount-index database is a stub that
6
+ * knows one store. What is pinned:
7
+ * - DEST_EXISTS from the server exits 2 (as the non-base64 path does);
8
+ * - `--force` is sent as `force: true`;
9
+ * - a bitmap the server transcoded (stored path differs, sha is of the
10
+ * stored bytes) is a success, not a "Checksum mismatch";
11
+ * - a sha mismatch at the path we asked for is still an error;
12
+ * - `delete` on a path the server answers 404 for is a no-op, not a failure.
13
+ *
14
+ * @jest-environment node
15
+ */
16
+
17
+ 'use strict';
18
+
19
+ const fs = require('fs');
20
+ const os = require('os');
21
+ const path = require('path');
22
+ const crypto = require('crypto');
23
+
24
+ const MOUNT_ID = '11111111-2222-3333-4444-555555555555';
25
+
26
+ jest.mock('../db-helpers', () => ({
27
+ resolveDataDirAndPassphrase: () => ({ dataDir: '/nowhere', passphrase: '' }),
28
+ printDefaultInstanceHint: () => {},
29
+ loadDbKey: async () => 'pepper',
30
+ openMountIndexDb: () => ({
31
+ prepare: (sql) => ({
32
+ get: () => (/sqlite_master/.test(sql) ? { ok: 1 } : { id: '11111111-2222-3333-4444-555555555555', name: 'Lore', mountType: 'database' }),
33
+ all: () => [],
34
+ }),
35
+ close: () => {},
36
+ }),
37
+ findMountByFormerName: () => null,
38
+ }));
39
+
40
+ const { docsCommand } = require('../docs-commands');
41
+
42
+ let tmpDir;
43
+ let stdout;
44
+ let stderr;
45
+ let exitCodes;
46
+
47
+ function fetchStub(status, body) {
48
+ const calls = [];
49
+ global.fetch = jest.fn(async (url, init) => {
50
+ calls.push({ url, init });
51
+ return { ok: status >= 200 && status < 300, status, json: async () => body };
52
+ });
53
+ return calls;
54
+ }
55
+
56
+ async function run(args) {
57
+ try {
58
+ await docsCommand(args);
59
+ return null;
60
+ } catch (e) {
61
+ return e;
62
+ }
63
+ }
64
+
65
+ beforeEach(() => {
66
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'docs-write-'));
67
+ stdout = [];
68
+ stderr = [];
69
+ exitCodes = [];
70
+ jest.spyOn(console, 'log').mockImplementation((...a) => { stdout.push(a.join(' ')); });
71
+ jest.spyOn(console, 'error').mockImplementation((...a) => { stderr.push(a.join(' ')); });
72
+ jest.spyOn(process.stdout, 'write').mockImplementation((s) => { stdout.push(String(s)); return true; });
73
+ jest.spyOn(process, 'exit').mockImplementation((code) => { exitCodes.push(code); throw new Error(`exit:${code}`); });
74
+ });
75
+
76
+ afterEach(() => {
77
+ jest.restoreAllMocks();
78
+ fs.rmSync(tmpDir, { recursive: true, force: true });
79
+ delete global.fetch;
80
+ });
81
+
82
+ describe('docs write --base64', () => {
83
+ it('exits 2 when the server refuses an existing destination', async () => {
84
+ const src = path.join(tmpDir, 'draft.md');
85
+ fs.writeFileSync(src, 'new');
86
+ fetchStub(409, { error: 'Destination already exists: today.md. Use force to overwrite.', code: 'DEST_EXISTS' });
87
+ const err = await run(['write', '--base64', MOUNT_ID, 'today.md', src]);
88
+ // process.exit is the real thing's last word; the stub throws, so only the
89
+ // first code is the command's own.
90
+ expect(exitCodes[0]).toBe(2);
91
+ expect(stderr.join('\n')).toContain('Destination already exists');
92
+ });
93
+
94
+ it('sends force: true with --force', async () => {
95
+ const src = path.join(tmpDir, 'draft.md');
96
+ fs.writeFileSync(src, 'new');
97
+ const sha = crypto.createHash('sha256').update('new').digest('hex');
98
+ const calls = fetchStub(200, { relativePath: 'today.md', sha256: sha, sizeBytes: 3 });
99
+ await run(['write', '--base64', '--force', MOUNT_ID, 'today.md', src]);
100
+ expect(JSON.parse(calls[0].init.body)).toMatchObject({ encoding: 'base64', force: true });
101
+ });
102
+
103
+ it('sends force: false without it', async () => {
104
+ const src = path.join(tmpDir, 'draft.md');
105
+ fs.writeFileSync(src, 'new');
106
+ const sha = crypto.createHash('sha256').update('new').digest('hex');
107
+ const calls = fetchStub(200, { relativePath: 'today.md', sha256: sha, sizeBytes: 3 });
108
+ await run(['write', '--base64', MOUNT_ID, 'today.md', src]);
109
+ expect(JSON.parse(calls[0].init.body).force).toBe(false);
110
+ });
111
+
112
+ it('treats a transcoded bitmap (stored path and sha differ) as a success', async () => {
113
+ const src = path.join(tmpDir, 'pic.png');
114
+ fs.writeFileSync(src, 'png-bytes');
115
+ fetchStub(200, { relativePath: 'art/pic.webp', sha256: 'f'.repeat(64), sizeBytes: 5 });
116
+ const err = await run(['write', '--base64', MOUNT_ID, 'art/pic.png', src]);
117
+ expect(err).toBeNull();
118
+ expect(stderr.join('\n')).not.toContain('Checksum mismatch');
119
+ expect(stdout.join('\n')).toContain('art/pic.webp');
120
+ });
121
+
122
+ it('flags a transcode in --json output', async () => {
123
+ const src = path.join(tmpDir, 'pic.png');
124
+ fs.writeFileSync(src, 'png-bytes');
125
+ fetchStub(200, { relativePath: 'pic.webp', sha256: 'f'.repeat(64), sizeBytes: 5 });
126
+ await run(['write', '--base64', '--json', MOUNT_ID, 'pic.png', src]);
127
+ const out = JSON.parse(stdout.join(''));
128
+ expect(out.transcoded).toBe(true);
129
+ expect(out.relativePath).toBe('pic.webp');
130
+ });
131
+
132
+ it('still fails a sha mismatch at the path it asked for', async () => {
133
+ const src = path.join(tmpDir, 'draft.md');
134
+ fs.writeFileSync(src, 'new');
135
+ fetchStub(200, { relativePath: 'today.md', sha256: 'e'.repeat(64), sizeBytes: 3 });
136
+ const err = await run(['write', '--base64', MOUNT_ID, 'today.md', src]);
137
+ expect(exitCodes[0]).toBe(1);
138
+ expect(stderr.join('\n')).toContain('Checksum mismatch');
139
+ });
140
+ });
141
+
142
+ describe('docs delete', () => {
143
+ it('treats the server\'s 404 as the no-op it has always been', async () => {
144
+ fetchStub(404, { error: 'File not found' });
145
+ const err = await run(['delete', MOUNT_ID, 'gone.md']);
146
+ expect(err).toBeNull();
147
+ expect(stdout.join('\n')).toContain('did not exist');
148
+ });
149
+
150
+ it('still fails on other errors', async () => {
151
+ fetchStub(500, { error: 'boom' });
152
+ const err = await run(['delete', MOUNT_ID, 'a.md']);
153
+ expect(exitCodes[0]).toBe(1);
154
+ });
155
+ });
@@ -15,7 +15,7 @@ const {
15
15
  resolveChat,
16
16
  resolveProject,
17
17
  } = require('./db-helpers');
18
- const { getLockStatus } = require('./lock-helpers');
18
+ const { getLockStatus, HEARTBEAT_FRESH_MS } = require('./lock-helpers');
19
19
  const { decodeText } = require('./text-codec');
20
20
 
21
21
  // Tables grouped by domain for `db schema` (with-no-arg) overview, and for
@@ -1398,9 +1398,9 @@ function cmdOptimize(args, ctx) {
1398
1398
  ? `Database is currently in use — ${lockStatus.reason}.\n` +
1399
1399
  `Stop the running Quilltap instance before optimizing, then try again.\n` +
1400
1400
  `(See \`quilltap db --lock-status\` for details.)`
1401
- : `Lock file ${lockStatus.reason}.\n` +
1402
- `This may be a stale lock from a reused PID. Inspect it with\n` +
1403
- `\`quilltap db --lock-status\` and clean it up with \`quilltap db --lock-clean\` if safe.`;
1401
+ : `Database lock looks suspect — ${lockStatus.reason}.\n` +
1402
+ `Its PID may have been reused since a crash. The lock is claimed automatically once its\n` +
1403
+ `heartbeat is ${Math.round(HEARTBEAT_FRESH_MS / 60000)} minutes old; try again then. (See \`quilltap db --lock-status\` for details.)`;
1404
1404
  const err = new Error(msg);
1405
1405
  err.locked = true;
1406
1406
  throw err;
@@ -23,6 +23,14 @@ const CYAN = '\x1b[36m';
23
23
  const TEXT_FILE_TYPES = new Set(['markdown', 'txt', 'json', 'jsonl']);
24
24
  const BINARY_FILE_TYPES = new Set(['pdf', 'docx', 'blob']);
25
25
 
26
+ // Where a link's bytes live, as the server's link projection reports it: a link
27
+ // in a database-backed store reads from the database whatever its content row
28
+ // says. A content row is shared by every link to the same bytes, and one
29
+ // written before 4.16 can say `filesystem` under a database store's link
30
+ // (#398), so `f.source` alone is not to be trusted.
31
+ const LINK_SOURCE_SQL = `(CASE WHEN (SELECT mp.mountType FROM doc_mount_points mp WHERE mp.id = l.mountPointId) = 'database'
32
+ THEN 'database' ELSE f.source END) AS source`;
33
+
26
34
  // Single-character markers for the `ls` "text" column:
27
35
  // = raw bytes are already textual (markdown/txt/json/jsonl)
28
36
  // T separately-extracted plaintext is stored on the link row
@@ -665,7 +673,7 @@ async function handleFiles(flags, id) {
665
673
  if (flags.folder) {
666
674
  const prefix = flags.folder.replace(/\/+$/, '') + '/';
667
675
  rows = db.prepare(`
668
- SELECT l.relativePath, f.fileType, f.source, f.fileSizeBytes,
676
+ SELECT l.relativePath, f.fileType, ${LINK_SOURCE_SQL}, f.fileSizeBytes,
669
677
  l.chunkCount, l.conversionStatus
670
678
  FROM doc_mount_file_links l
671
679
  JOIN doc_mount_files f ON f.id = l.fileId
@@ -674,7 +682,7 @@ async function handleFiles(flags, id) {
674
682
  `).all(mount.id, prefix + '%');
675
683
  } else {
676
684
  rows = db.prepare(`
677
- SELECT l.relativePath, f.fileType, f.source, f.fileSizeBytes,
685
+ SELECT l.relativePath, f.fileType, ${LINK_SOURCE_SQL}, f.fileSizeBytes,
678
686
  l.chunkCount, l.conversionStatus
679
687
  FROM doc_mount_file_links l
680
688
  JOIN doc_mount_files f ON f.id = l.fileId
@@ -761,7 +769,7 @@ function lsFileColumns(db) {
761
769
  ${linkGroupId} AS linkGroupId,
762
770
  l.id AS linkId, l.fileId, l.relativePath, l.fileName, l.lastModified,
763
771
  l.extractionStatus, l.extractedTextSha256, l.chunkCount,
764
- f.fileType, f.fileSizeBytes, f.source, f.sha256,
772
+ f.fileType, f.fileSizeBytes, ${LINK_SOURCE_SQL}, f.sha256,
765
773
  ${linkCount} AS linkCount,
766
774
  (SELECT COUNT(*) FROM doc_mount_chunks
767
775
  WHERE linkId = l.id AND embedding IS NOT NULL) AS embeddedChunkCount
@@ -1388,7 +1396,7 @@ async function handleRead(flags, id, relativePath) {
1388
1396
 
1389
1397
  function readRaw(db, mount, relativePath, flags) {
1390
1398
  const file = db.prepare(`
1391
- SELECT l.fileId, f.source, f.fileType
1399
+ SELECT l.fileId, ${LINK_SOURCE_SQL}, f.fileType
1392
1400
  FROM doc_mount_file_links l
1393
1401
  JOIN doc_mount_files f ON f.id = l.fileId
1394
1402
  WHERE l.mountPointId = ? AND l.relativePath = ?
@@ -1448,7 +1456,7 @@ function readRendered(db, mount, relativePath) {
1448
1456
  // 1. Look up the link row (it carries extractedText now).
1449
1457
  const file = db.prepare(`
1450
1458
  SELECT l.id AS linkId, l.fileId, l.extractedText,
1451
- f.source, f.fileType
1459
+ ${LINK_SOURCE_SQL}, f.fileType
1452
1460
  FROM doc_mount_file_links l
1453
1461
  JOIN doc_mount_files f ON f.id = l.fileId
1454
1462
  WHERE l.mountPointId = ? AND l.relativePath = ?
@@ -1529,7 +1537,7 @@ async function handleExport(flags, id, outputDir) {
1529
1537
  const mount = requireMount(db, id);
1530
1538
 
1531
1539
  const files = db.prepare(`
1532
- SELECT l.fileId, l.relativePath, f.source, f.fileType
1540
+ SELECT l.fileId, l.relativePath, ${LINK_SOURCE_SQL}, f.fileType
1533
1541
  FROM doc_mount_file_links l
1534
1542
  JOIN doc_mount_files f ON f.id = l.fileId
1535
1543
  WHERE l.mountPointId = ?
@@ -1821,15 +1829,22 @@ async function handleWrite(flags, positional) {
1821
1829
  process.exit(http.code === 'DEST_EXISTS' ? 2 : 1);
1822
1830
  }
1823
1831
  const r = http.result;
1824
- if (r.sha256 !== sourceSha) {
1832
+ // A database-backed store transcodes bitmaps to WebP, so it reports a
1833
+ // different stored path and the sha256 of the stored bytes. That is the
1834
+ // store doing its job, not corruption: only a mismatch at the path we
1835
+ // asked for is one.
1836
+ const storedPath = r.relativePath ?? relativePath;
1837
+ const transcoded = storedPath.replace(/^\/+/, '') !== relativePath.replace(/^\/+/, '');
1838
+ if (r.sha256 !== sourceSha && !transcoded) {
1825
1839
  console.error(`Checksum mismatch: source ${sourceSha} != dest ${r.sha256}`);
1826
1840
  process.exit(1);
1827
1841
  }
1828
1842
  if (flags.json) {
1829
- process.stdout.write(JSON.stringify({ ...r, sourceSha256: sourceSha }, null, 2) + '\n');
1843
+ process.stdout.write(JSON.stringify({ ...r, sourceSha256: sourceSha, transcoded }, null, 2) + '\n');
1830
1844
  return;
1831
1845
  }
1832
- console.log(`${GREEN}Wrote${RESET} ${mount.name}:${r.relativePath ?? relativePath} (${formatBytes(r.sizeBytes)}, sha=${r.sha256.slice(0, 12)}…)`);
1846
+ const note = transcoded ? ` ${DIM}[stored as ${storedPath}; the store converted it]${RESET}` : '';
1847
+ console.log(`${GREEN}Wrote${RESET} ${mount.name}:${storedPath} (${formatBytes(r.sizeBytes)}, sha=${r.sha256.slice(0, 12)}…)${note}`);
1833
1848
  return;
1834
1849
  }
1835
1850
 
@@ -1924,6 +1939,17 @@ async function handleDelete(flags, positional) {
1924
1939
 
1925
1940
  const http = await deleteViaHttp(flags.port, mount.id, relativePath);
1926
1941
  if (http.reachable) {
1942
+ if (!http.ok && http.status === 404) {
1943
+ // The server answers 404 for a path that holds nothing; for the CLI that
1944
+ // is still the no-op it has always been.
1945
+ const r = { deleted: false, mountPointId: mount.id, path: relativePath };
1946
+ if (flags.json) {
1947
+ process.stdout.write(JSON.stringify(r, null, 2) + '\n');
1948
+ return;
1949
+ }
1950
+ console.log(`${DIM}No-op${RESET} ${mount.name}:${relativePath} (did not exist)`);
1951
+ return;
1952
+ }
1927
1953
  if (!http.ok) {
1928
1954
  console.error(`Delete failed: ${http.error}`);
1929
1955
  process.exit(1);
@@ -2630,7 +2656,7 @@ async function handleGrep(flags, positional) {
2630
2656
 
2631
2657
  const linksByMount = db.prepare(`
2632
2658
  SELECT l.id AS linkId, l.fileId, l.relativePath, l.extractedText,
2633
- f.source, f.fileType
2659
+ ${LINK_SOURCE_SQL}, f.fileType
2634
2660
  FROM doc_mount_file_links l
2635
2661
  JOIN doc_mount_files f ON f.id = l.fileId
2636
2662
  WHERE l.mountPointId = ?