quilltap 4.15.0-dev.2 → 4.16.0-dev.7
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 +26 -13
- package/bin/quilltap.js +88 -110
- package/lib/__tests__/docs-write-base64.test.js +155 -0
- package/lib/__tests__/file-verify-platform.test.js +31 -0
- package/lib/__tests__/find-mount-by-former-name.test.js +60 -0
- package/lib/__tests__/instances-default-json.test.js +18 -0
- package/lib/__tests__/logs-tail-flag.test.js +30 -0
- package/lib/__tests__/maintenance-orphan-sweep.test.js +84 -0
- package/lib/__tests__/migrations-source-ids.test.js +15 -1
- package/lib/db-commands.js +4 -4
- package/lib/db-helpers.js +31 -2
- package/lib/docs-commands.js +45 -11
- package/lib/file-verify-commands.js +20 -3
- package/lib/instances-commands.js +6 -2
- package/lib/instances.js +5 -0
- package/lib/lock-helpers.js +319 -120
- package/lib/logs-commands.js +14 -2
- package/lib/maintenance-commands.js +35 -6
- package/lib/migrations-commands.js +4 -83
- package/lib/migrations-source.js +109 -0
- package/lib/migrations.generated.js +1055 -0
- package/lib/sync-command.js +7 -0
- package/lib/theme-engine.generated.js +47 -47
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -106,7 +106,7 @@ quilltap instances path # Print the path to ins
|
|
|
106
106
|
quilltap instances set-passphrase Friday # Change or clear the stored passphrase (prompts hidden)
|
|
107
107
|
quilltap instances default Friday # Make it the fall-through for flag-free runs
|
|
108
108
|
quilltap instances rename Friday Weekday # Rename, preserving the stored passphrase
|
|
109
|
-
quilltap instances remove Friday # Unregister (aliases: rm, delete)
|
|
109
|
+
quilltap instances remove Friday # Unregister (aliases: rm, delete); clears the default if it was Friday
|
|
110
110
|
quilltap instances restore-key Friday # Rebuild a lost or passphrase-locked .dbkey
|
|
111
111
|
quilltap instances default --clear # Revert to the OS platform default
|
|
112
112
|
quilltap instances list --json # The registry as JSON, for scripts
|
|
@@ -118,7 +118,7 @@ If an instance's `quilltap.dbkey` goes missing — or its passphrase does — `i
|
|
|
118
118
|
|
|
119
119
|
**It does not re-encrypt character archive bundles.** Those are keyed on the *passphrase*, not the pepper; only the server's Change Passphrase card rewrites them. Bundles made under a passphrase you have just replaced still want the old one.
|
|
120
120
|
|
|
121
|
-
Every subcommand then accepts `--instance <name>` in place of `--data-dir`. The registry lives at `<app-support>/Quilltap/instances.json` (mode 0600; e.g. `~/Library/Application Support/Quilltap/instances.json` on macOS). **Resolution precedence:** `--data-dir` > `--instance` > registered default >
|
|
121
|
+
Every subcommand then accepts `--instance <name>` in place of `--data-dir`. The registry lives at `<app-support>/Quilltap/instances.json` (mode 0600; e.g. `~/Library/Application Support/Quilltap/instances.json` on macOS). **Resolution precedence:** `--data-dir` > `--instance` > `QUILLTAP_DATA_DIR` > registered default > the OS platform default. Pass the **instance root** (e.g. `~/iCloud/Quilltap/Friday`), not its `data/` subdirectory — the CLI appends `data/quilltap.db` itself. `instances list --json` emits the registry (`name`, `path`, `hasPassphrase`, `isDefault`) for scripting.
|
|
122
122
|
|
|
123
123
|
## Database Tool
|
|
124
124
|
|
|
@@ -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
|
-
###
|
|
214
|
+
### When a lock counts as held
|
|
215
215
|
|
|
216
|
-
|
|
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
|
-
|
|
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
|
|
|
@@ -271,7 +284,7 @@ quilltap docs mvdir <mount> <fromPath> <toPath> # Rename/move a fo
|
|
|
271
284
|
|
|
272
285
|
`ls` flags: `--recursive` / `-R` lists every file below the path, grouped by folder; `--sort name|time|size|links` (default `name`) with `--reverse` / `-r` to flip it; `--links` lists the other mount/path entries under each file that has more than one hard link. `tree` takes `--depth N` (default 20), `--max-nodes N` (default 1000) and `--long`, which is accepted but reserved — it does not yet add columns.
|
|
273
286
|
|
|
274
|
-
Mount arguments accept the mount name (case-insensitive) or a UUID; ambiguous names print candidates and exit non-zero. `--json` is supported by every verb; `reindex`, `embed`, `link`, `rmdir`, and `mvdir` refuse to run without a reachable server. `grep --semantic` goes through `POST /api/v1/mount-points?action=semantic-search`, because the embedding provider lives in the server; it defaults to `--top 20`, `--threshold 0.5`, `--port 3000`.
|
|
287
|
+
Mount arguments accept the mount name (case-insensitive) or a UUID; ambiguous names print candidates and exit non-zero. A renamed store still answers to a name it used to carry (the `formerNames` column), with a note on stderr saying which store was found, until another store takes that name; the UUID is the reference that never changes. `--json` is supported by every verb; `reindex`, `embed`, `link`, `rmdir`, and `mvdir` refuse to run without a reachable server. `grep --semantic` goes through `POST /api/v1/mount-points?action=semantic-search`, because the embedding provider lives in the server; it defaults to `--top 20`, `--threshold 0.5`, `--port 3000`.
|
|
275
288
|
|
|
276
289
|
### Addressing documents with `qtap://` URIs
|
|
277
290
|
|
|
@@ -284,7 +297,7 @@ quilltap docs grep --mount qtap://notes/ "TODO"
|
|
|
284
297
|
quilltap docs find --uri Manifesto
|
|
285
298
|
```
|
|
286
299
|
|
|
287
|
-
The URI authority is matched name-first, UUID
|
|
300
|
+
The URI authority is matched name-first, then UUID, then a former name — the same rule as a bare `<mount>` (`qtap://<store name>/…` or `qtap://<uuid>/…`). Two-target verbs (`move` / `copy` / `link` / `mvdir`) take either two `qtap://` URIs or the four legacy positionals; `find` and `grep` take one via `--mount`.
|
|
288
301
|
|
|
289
302
|
**CLI limitation:** the CLI addresses document stores only. `qtap://self/…` needs a character context, and there is none at a shell prompt, so it is rejected with guidance; `qtap://project/…` and `qtap://general/…` are likewise not CLI-addressable — pass a store name or UUID instead.
|
|
290
303
|
|
|
@@ -292,7 +305,7 @@ The URI authority is matched name-first, UUID as fallback — the same rule as a
|
|
|
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
|
|
|
@@ -442,7 +455,7 @@ quilltap maintenance status --instance Friday --json
|
|
|
442
455
|
quilltap maintenance run --instance Friday # Run the sweeps once (lock-gated; refuses while the server is up)
|
|
443
456
|
```
|
|
444
457
|
|
|
445
|
-
`maintenance run` is a DB writer: it claims `<dataDir>/quilltap.lock` and **refuses while a running Quilltap server holds it** — stop the server first. Because it can only run with the server down, it performs the sweeps expressible as direct SQL/filesystem work: reaping finished background jobs (COMPLETED after 7 days, DEAD after 30, keyed off `completedAt`), closed terminal sessions older than 30 days plus their transcript files, and orphaned mount-index files. The **stale-chat asset collapse** (superseded story-backgrounds and wardrobe avatars) needs the server's file-storage machinery and runs only on the server's daily tick — `status` reports a stale-chat count so you can see the backlog. Retention windows mirror `lib/background-jobs/maintenance/retention-constants.ts`.
|
|
458
|
+
`maintenance run` is a DB writer: it claims `<dataDir>/quilltap.lock` and **refuses while a running Quilltap server holds it** — stop the server first. Because it can only run with the server down, it performs the sweeps expressible as direct SQL/filesystem work: reaping finished background jobs (COMPLETED after 7 days, DEAD after 30, keyed off `completedAt`), closed terminal sessions older than 30 days plus their transcript files, and orphaned mount-index files (each with its stored document or blob content). The **stale-chat asset collapse** (superseded story-backgrounds and wardrobe avatars) needs the server's file-storage machinery and runs only on the server's daily tick — `status` reports a stale-chat count so you can see the backlog. Retention windows mirror `lib/background-jobs/maintenance/retention-constants.ts`.
|
|
446
459
|
|
|
447
460
|
## Logs
|
|
448
461
|
|
|
@@ -467,11 +480,11 @@ quilltap migrations pending # Just the not-yet-recorded list
|
|
|
467
480
|
quilltap migrations run --dry-run # List what would run (refuses without --dry-run)
|
|
468
481
|
```
|
|
469
482
|
|
|
470
|
-
`--json` works on all three. "Not yet recorded" includes migrations whose `shouldRun()` is `false` on this instance — the CLI doesn't evaluate the predicate, so it can't distinguish "would skip" from "would run."
|
|
483
|
+
`--json` works on all three. Run from a source checkout, the CLI reads the migration list live from `migrations/scripts/`; an npm-installed CLI uses the list bundled with its release, so it reports the migrations that version of Quilltap contains. "Not yet recorded" includes migrations whose `shouldRun()` is `false` on this instance — the CLI doesn't evaluate the predicate, so it can't distinguish "would skip" from "would run."
|
|
471
484
|
|
|
472
485
|
## File Verification
|
|
473
486
|
|
|
474
|
-
`quilltap file-verify` force-downloads an instance's cloud-evicted (dataless) top-level data files so the databases are fully local before anything opens them. It reads each placeholder, which faults it in through the cloud provider (iCloud Drive, etc.). Safe to run repeatedly — a no-op when nothing is evicted. macOS only for now.
|
|
487
|
+
`quilltap file-verify` force-downloads an instance's cloud-evicted (dataless) top-level data files so the databases are fully local before anything opens them. It reads each placeholder, which faults it in through the cloud provider (iCloud Drive, etc.). Safe to run repeatedly — a no-op when nothing is evicted. Evicted-file detection is macOS only for now: on other platforms no file is reported as evicted (a sparse or compressed Linux file would otherwise look evicted), the command says so, and `--all` still reads every top-level file.
|
|
475
488
|
|
|
476
489
|
```bash
|
|
477
490
|
quilltap file-verify --instance Ignite # Fault in only the dataless top-level files
|
|
@@ -479,7 +492,7 @@ quilltap file-verify --instance Friday --all # Read every top-level file, not j
|
|
|
479
492
|
quilltap file-verify --instance Friday --json # Machine-readable report
|
|
480
493
|
```
|
|
481
494
|
|
|
482
|
-
Only the **top-level** files of the data directory are considered; the `backups/` subdirectory is left alone. Flags: `--all` (read every top-level file, not just dataless ones), `--stall-ms <ms>` (treat a download as stalled after this many ms with no bytes per chunk; default 30000), `--json
|
|
495
|
+
Only the **top-level** files of the data directory are considered; the `backups/` subdirectory is left alone. Flags: `--all` (read every top-level file, not just dataless ones), `--stall-ms <ms>` (treat a download as stalled after this many ms with no bytes per chunk; default 30000), `--json` (the report includes `detectionSupported`, `false` off macOS). Resolves the instance via the usual `--instance` / `--data-dir` plumbing.
|
|
483
496
|
|
|
484
497
|
## Theme Management
|
|
485
498
|
|
package/bin/quilltap.js
CHANGED
|
@@ -458,53 +458,27 @@ async function main() {
|
|
|
458
458
|
// Instance Lock CLI Commands
|
|
459
459
|
// ============================================================================
|
|
460
460
|
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
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
|
-
|
|
561
|
-
|
|
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
|
-
|
|
571
|
-
|
|
572
|
-
|
|
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
|
|
627
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
720
|
-
|
|
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 (
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
console.
|
|
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 (
|
|
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
|
-
(
|
|
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
|
-
|
|
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
|
|
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
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `quilltap file-verify` detects evicted files on macOS only (issue #359).
|
|
3
|
+
*
|
|
4
|
+
* The blocks*512 < size test also matches a sparse or compressed file on
|
|
5
|
+
* Linux, and Windows reports no block count, so other platforms must never
|
|
6
|
+
* flag a file. Mirrors the darwin gate in lib/startup/materialize-cloud-files.ts.
|
|
7
|
+
*
|
|
8
|
+
* @jest-environment node
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
'use strict';
|
|
12
|
+
|
|
13
|
+
const { isDatalessStat, isDetectionSupported } = require('../file-verify-commands');
|
|
14
|
+
|
|
15
|
+
describe('file-verify evicted-file detection', () => {
|
|
16
|
+
const sparse = { size: 10 * 1024 * 1024, blocks: 0 };
|
|
17
|
+
const resident = { size: 4096, blocks: 8 };
|
|
18
|
+
|
|
19
|
+
it('flags an under-allocated file on macOS', () => {
|
|
20
|
+
expect(isDetectionSupported('darwin')).toBe(true);
|
|
21
|
+
expect(isDatalessStat(sparse, 'darwin')).toBe(true);
|
|
22
|
+
expect(isDatalessStat(resident, 'darwin')).toBe(false);
|
|
23
|
+
expect(isDatalessStat({ size: 0, blocks: 0 }, 'darwin')).toBe(false);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it.each(['linux', 'win32'])('never flags a file on %s', (platform) => {
|
|
27
|
+
expect(isDetectionSupported(platform)).toBe(false);
|
|
28
|
+
expect(isDatalessStat(sparse, platform)).toBe(false);
|
|
29
|
+
expect(isDatalessStat({ size: 4096, blocks: undefined }, platform)).toBe(false);
|
|
30
|
+
});
|
|
31
|
+
});
|