quilltap 4.15.0-dev.112 → 4.15.0-dev.149

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
@@ -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 > `QUILLTAP_DATA_DIR` > 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.
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
 
@@ -442,7 +442,7 @@ quilltap maintenance status --instance Friday --json
442
442
  quilltap maintenance run --instance Friday # Run the sweeps once (lock-gated; refuses while the server is up)
443
443
  ```
444
444
 
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`.
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 (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
446
 
447
447
  ## Logs
448
448
 
@@ -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
+ });
@@ -84,6 +84,24 @@ describe('instances default --json', () => {
84
84
  });
85
85
  });
86
86
 
87
+ describe('instances remove', () => {
88
+ it('clears the default when the default instance is removed (issue #360)', () => {
89
+ addInstance('Friday');
90
+ addInstance('Ignite');
91
+ run('default', 'Friday');
92
+ expect(run('remove', 'Friday')).toMatch(/default is now cleared/);
93
+ expect(run('default')).toBe('(none)');
94
+ });
95
+
96
+ it('keeps the default when another instance is removed', () => {
97
+ addInstance('Friday');
98
+ addInstance('Ignite');
99
+ run('default', 'Friday');
100
+ expect(run('remove', 'Ignite')).not.toMatch(/default is now cleared/);
101
+ expect(run('default')).toBe('Friday');
102
+ });
103
+ });
104
+
87
105
  describe('instances list --json', () => {
88
106
  it('emits the registry as an array', () => {
89
107
  expect(JSON.parse(run('list', '--json'))).toEqual([]);
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `quilltap logs --tail 0` means the whole file (issue #361).
3
+ *
4
+ * The flag was parsed as `parseInt(value, 10) || 100`, and 0 is falsy, so the
5
+ * documented "0 = full file" became the default of 100 lines.
6
+ *
7
+ * @jest-environment node
8
+ */
9
+
10
+ 'use strict';
11
+
12
+ const { parseFlags } = require('../logs-commands');
13
+
14
+ describe('logs --tail', () => {
15
+ it('defaults to 100 lines', () => {
16
+ expect(parseFlags([]).tail).toBe(100);
17
+ });
18
+
19
+ it('keeps 0, which means the whole file', () => {
20
+ expect(parseFlags(['--tail', '0']).tail).toBe(0);
21
+ });
22
+
23
+ it('takes a positive count', () => {
24
+ expect(parseFlags(['--tail', '250']).tail).toBe(250);
25
+ });
26
+
27
+ it.each(['abc', '-5', ''])('falls back to 100 for %p', (value) => {
28
+ expect(parseFlags(['--tail', value]).tail).toBe(100);
29
+ });
30
+ });
@@ -0,0 +1,84 @@
1
+ /**
2
+ * `quilltap maintenance run`, step 3: the orphaned mount-index file sweep.
3
+ *
4
+ * A mount index whose tables came from the schema translator carries no
5
+ * foreign keys, so deleting a `doc_mount_files` row cascades to nothing. The
6
+ * sweep therefore deletes an orphan's document and blob payload itself, as the
7
+ * server's `gcOrphanedFileRow` does. A bare `DELETE FROM doc_mount_files`
8
+ * (what this step used to run) left that payload behind for good.
9
+ *
10
+ * @jest-environment node
11
+ */
12
+
13
+ 'use strict';
14
+
15
+ const path = require('path');
16
+ // The real driver, by absolute path: jest maps the bare specifier to a mock.
17
+ const Database = require(path.join(process.cwd(), 'node_modules', 'better-sqlite3'));
18
+ const { sweepOrphanedMountFiles } = require('../maintenance-commands');
19
+
20
+ // The tables as the schema translator creates them: no REFERENCES anywhere.
21
+ function createIndex({ withDocuments = true, withBlobs = true } = {}) {
22
+ const db = new Database(':memory:');
23
+ db.exec('CREATE TABLE doc_mount_files (id TEXT PRIMARY KEY, sha256 TEXT)');
24
+ db.exec('CREATE TABLE doc_mount_file_links (id TEXT PRIMARY KEY, fileId TEXT, mountPointId TEXT)');
25
+ if (withDocuments) db.exec('CREATE TABLE doc_mount_documents (id TEXT PRIMARY KEY, fileId TEXT, content TEXT)');
26
+ if (withBlobs) db.exec('CREATE TABLE doc_mount_blobs (id TEXT PRIMARY KEY, fileId TEXT, data BLOB)');
27
+ return db;
28
+ }
29
+
30
+ const ids = (db, table, column = 'id') =>
31
+ db.prepare(`SELECT ${column} AS v FROM ${table} ORDER BY v`).all().map((row) => row.v);
32
+
33
+ describe('sweepOrphanedMountFiles', () => {
34
+ it('deletes an orphaned file row together with its document and blob payload', () => {
35
+ const db = createIndex();
36
+ db.exec(`
37
+ INSERT INTO doc_mount_files VALUES ('linked', 'a'), ('orphan-doc', 'b'), ('orphan-blob', 'c');
38
+ INSERT INTO doc_mount_file_links VALUES ('link-1', 'linked', 'mp-1');
39
+ INSERT INTO doc_mount_documents VALUES ('d-linked', 'linked', 'kept'), ('d-orphan', 'orphan-doc', 'gone');
40
+ INSERT INTO doc_mount_blobs VALUES ('b-linked', 'linked', x'01'), ('b-orphan', 'orphan-blob', x'02');
41
+ `);
42
+
43
+ expect(sweepOrphanedMountFiles(db)).toBe(2);
44
+
45
+ expect(ids(db, 'doc_mount_files')).toEqual(['linked']);
46
+ expect(ids(db, 'doc_mount_documents')).toEqual(['d-linked']);
47
+ expect(ids(db, 'doc_mount_blobs')).toEqual(['b-linked']);
48
+ expect(ids(db, 'doc_mount_file_links')).toEqual(['link-1']);
49
+ });
50
+
51
+ it('leaves content alone while any link, in any store, still references it', () => {
52
+ const db = createIndex();
53
+ db.exec(`
54
+ INSERT INTO doc_mount_files VALUES ('shared', 'a');
55
+ INSERT INTO doc_mount_file_links VALUES ('link-1', 'shared', 'mp-1'), ('link-2', 'shared', 'mp-2');
56
+ INSERT INTO doc_mount_documents VALUES ('d-shared', 'shared', 'kept');
57
+ `);
58
+
59
+ expect(sweepOrphanedMountFiles(db)).toBe(0);
60
+ expect(ids(db, 'doc_mount_files')).toEqual(['shared']);
61
+ expect(ids(db, 'doc_mount_documents')).toEqual(['d-shared']);
62
+ });
63
+
64
+ it('copes with an index that never created a payload table', () => {
65
+ // Both payload tables are minted lazily; a document-only index has no
66
+ // `doc_mount_blobs`, and deleting from a missing table would throw.
67
+ const db = createIndex({ withBlobs: false });
68
+ db.exec(`
69
+ INSERT INTO doc_mount_files VALUES ('orphan', 'a');
70
+ INSERT INTO doc_mount_documents VALUES ('d-orphan', 'orphan', 'gone');
71
+ `);
72
+
73
+ expect(sweepOrphanedMountFiles(db)).toBe(1);
74
+ expect(ids(db, 'doc_mount_documents')).toEqual([]);
75
+
76
+ const bare = createIndex({ withDocuments: false, withBlobs: false });
77
+ bare.exec("INSERT INTO doc_mount_files VALUES ('orphan', 'a')");
78
+ expect(sweepOrphanedMountFiles(bare)).toBe(1);
79
+ });
80
+
81
+ it('does nothing on a database with no mount-index tables', () => {
82
+ expect(sweepOrphanedMountFiles(new Database(':memory:'))).toBe(0);
83
+ });
84
+ });
@@ -13,7 +13,7 @@
13
13
  const fs = require('fs');
14
14
  const path = require('path');
15
15
 
16
- const { extractMigrationId } = require('../migrations-commands');
16
+ const { extractMigrationId, extractMigrationsFromSource, loadMigrationList } = require('../migrations-source');
17
17
 
18
18
  describe('extractMigrationId', () => {
19
19
  it('reads a string-literal id', () => {
@@ -52,3 +52,17 @@ describe('every migration script yields an id', () => {
52
52
  expect(missing).toEqual([]);
53
53
  });
54
54
  });
55
+
56
+ describe('the migration list an npm-installed CLI reads (issue #362)', () => {
57
+ const scriptsDir = path.join(__dirname, '..', '..', '..', '..', 'migrations', 'scripts');
58
+
59
+ it('ships a generated list that matches the source', () => {
60
+ expect(require('../migrations.generated.js')).toEqual(extractMigrationsFromSource(scriptsDir));
61
+ });
62
+
63
+ it('falls back to the generated list when there is no source folder', () => {
64
+ const list = loadMigrationList(path.join(__dirname, 'no-such-folder'));
65
+ expect(list).toBe(require('../migrations.generated.js'));
66
+ expect(list.length).toBeGreaterThan(100);
67
+ });
68
+ });
package/lib/db-helpers.js CHANGED
@@ -31,8 +31,9 @@ function resolveDataDir(overrideDir) {
31
31
  // Precedence order (highest to lowest):
32
32
  // 1. --data-dir (explicit override)
33
33
  // 2. --instance (explicit instance)
34
- // 3. registered default instance
35
- // 4. QUILLTAP_DATA_DIR env var
34
+ // 3. QUILLTAP_DATA_DIR env var (an Ariel terminal sets it, so a bare
35
+ // `quilltap` there addresses the instance the terminal belongs to)
36
+ // 4. registered default instance
36
37
  // 5. OS platform default
37
38
  //
38
39
  // Returns `usedPlatformDefault: true` only when falling back to the true
@@ -36,9 +36,15 @@ const STAT_BLOCK_BYTES = 512;
36
36
  // and the partially-materialized file (blocks > 0 but blocks*512 < size) — the
37
37
  // latter still fails SQLite open with "file is not a database". A fully-resident
38
38
  // file always reports blocks*512 >= size (allocation rounds up), so this never
39
- // flags a healthy file. Zero-byte files are never flagged. Other platforms fall
40
- // through as a no-op for now.
41
- function isDatalessStat(stat) {
39
+ // flags a healthy file. Zero-byte files are never flagged. Other platforms are a
40
+ // no-op, as in the server's materializeCloudFiles: on Linux a sparse or
41
+ // compressed file would read as evicted, and Windows reports no block count.
42
+ function isDetectionSupported(platform = process.platform) {
43
+ return platform === 'darwin';
44
+ }
45
+
46
+ function isDatalessStat(stat, platform = process.platform) {
47
+ if (!isDetectionSupported(platform)) return false;
42
48
  return stat.size > 0 && stat.blocks * STAT_BLOCK_BYTES < stat.size;
43
49
  }
44
50
 
@@ -166,11 +172,20 @@ async function fileVerifyCommand(args) {
166
172
  // resolved.dataDir already points at the instance's data/ directory.
167
173
  const targetDir = resolved.dataDir;
168
174
 
175
+ const supported = isDetectionSupported();
176
+ if (!supported && !flags.json) {
177
+ console.log(
178
+ 'Evicted-file detection is supported on macOS only; on this platform no file is reported as evicted.' +
179
+ (flags.all ? '' : ' Pass --all to read every top-level file anyway.'),
180
+ );
181
+ }
182
+
169
183
  const files = listTopLevelFiles(targetDir);
170
184
  const targets = flags.all ? files : files.filter((f) => f.dataless);
171
185
 
172
186
  const summary = {
173
187
  dataDir: targetDir,
188
+ detectionSupported: supported,
174
189
  checked: files.length,
175
190
  targeted: targets.length,
176
191
  downloaded: 0,
@@ -226,4 +241,6 @@ async function fileVerifyCommand(args) {
226
241
 
227
242
  module.exports = {
228
243
  fileVerifyCommand,
244
+ isDatalessStat,
245
+ isDetectionSupported,
229
246
  };
@@ -54,8 +54,8 @@ will also accept --instance <name>:
54
54
  quilltap docs --instance Lebanon list
55
55
 
56
56
  Default Instance:
57
- When no --instance or --data-dir is specified, the CLI uses the registered
58
- default (if one is set), then QUILLTAP_DATA_DIR (if set), then the OS platform
57
+ When no --instance or --data-dir is specified, the CLI uses QUILLTAP_DATA_DIR
58
+ (if set), then the registered default (if one is set), then the OS platform
59
59
  default. Marked with * in list output.
60
60
 
61
61
  quilltap instances default Friday # set Friday as the default
@@ -223,8 +223,12 @@ function cmdRemove(args) {
223
223
  console.error('Usage: quilltap instances remove <name>');
224
224
  process.exit(1);
225
225
  }
226
+ const defaultBefore = getDefaultInstance();
226
227
  const key = removeInstance(name);
227
228
  console.log(`Removed instance "${key}".`);
229
+ if (defaultBefore === key) {
230
+ console.log('It was the default instance; the default is now cleared.');
231
+ }
228
232
  }
229
233
 
230
234
  async function cmdSetPassphrase(args) {
package/lib/instances.js CHANGED
@@ -198,6 +198,11 @@ function removeInstance(name) {
198
198
  throw new Error(`Unknown instance "${name}".`);
199
199
  }
200
200
  delete registry.instances[key];
201
+ // A default that names a removed instance would send every flagless command
202
+ // to the platform default without a word (issue #360).
203
+ if (registry.defaultInstance === key) {
204
+ registry.defaultInstance = null;
205
+ }
201
206
  writeInstances(registry);
202
207
  return key;
203
208
  }
@@ -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
  };
@@ -1,13 +1,12 @@
1
1
  'use strict';
2
2
 
3
- const fs = require('fs');
4
- const path = require('path');
5
3
  const {
6
4
  resolveDataDirAndPassphrase,
7
5
  printDefaultInstanceHint,
8
6
  openMainDb,
9
7
  loadDbKey,
10
8
  } = require('./db-helpers');
9
+ const { extractMigrationId, loadMigrationList } = require('./migrations-source');
11
10
 
12
11
  // ---------- argument parsing ----------
13
12
 
@@ -41,84 +40,6 @@ function parseFlags(args) {
41
40
  return { flags, positional };
42
41
  }
43
42
 
44
- // ---------- migration list parsing ----------
45
-
46
- /**
47
- * A migration's id is either a string literal on the object (`id: 'foo-v1'`)
48
- * or a module constant (`id: MIGRATION_ID` beside `const MIGRATION_ID = 'foo-v1'`).
49
- * Missing the constant form drops those migrations from "source", which then
50
- * report as retired on every instance that ran them.
51
- */
52
- function extractMigrationId(fileContent) {
53
- const constMatch = fileContent.match(/^\s*const\s+MIGRATION_ID\s*(?::\s*\w+\s*)?=\s*['"]([^'"]+)['"]/m);
54
- if (constMatch && /^\s*id:\s*MIGRATION_ID\b/m.test(fileContent)) return constMatch[1];
55
- const literalMatch = fileContent.match(/^\s*id:\s*['"]([^'"]+)['"]/m);
56
- return literalMatch ? literalMatch[1] : null;
57
- }
58
-
59
- // Reads the registered migration list from migrations/scripts/index.ts and resolves each
60
- // entry's real `id:` value by reading the imported source file. Heuristic camelCase→kebab
61
- // conversion is unreliable (some migrations omit `-v1`, others use `-v2`), so we always
62
- // trust the file.
63
- function extractMigrationsFromSource() {
64
- const scriptsDir = path.join(__dirname, '../../..', 'migrations/scripts');
65
- const indexPath = path.join(scriptsDir, 'index.ts');
66
- if (!fs.existsSync(indexPath)) {
67
- return [];
68
- }
69
- const indexContent = fs.readFileSync(indexPath, 'utf-8');
70
-
71
- // Pass 1: build name → { filePath, comment } from imports and preceding comments.
72
- const lines = indexContent.split('\n');
73
- const importInfo = {};
74
- let lastComment = '';
75
- for (const line of lines) {
76
- if (line.match(/^\s*\/\/\s+/)) {
77
- lastComment = line.replace(/^\s*\/\/\s+/, '').trim();
78
- continue;
79
- }
80
- const importMatch = line.match(/import\s+\{\s*(\w+)\s*\}\s+from\s+['"]\.\/([^'"]+)['"]/);
81
- if (importMatch) {
82
- const [, name, filePath] = importMatch;
83
- importInfo[name] = { filePath, comment: lastComment || '' };
84
- lastComment = '';
85
- } else if (line.trim() && !line.match(/^\s*\/\//) && !line.includes('import type')) {
86
- // Reset comment if we hit a non-comment non-import line
87
- if (!line.match(/^\s*$/)) lastComment = '';
88
- }
89
- }
90
-
91
- // Pass 2: find the active migrations array section and collect names in order.
92
- const arrayStart = indexContent.indexOf('export const migrations: Migration[] = [');
93
- if (arrayStart === -1) return [];
94
- const arrayEnd = indexContent.indexOf('];', arrayStart);
95
- if (arrayEnd === -1) return [];
96
- const arrayContent = indexContent.substring(arrayStart, arrayEnd);
97
-
98
- const activeNames = arrayContent.match(/\b([a-zA-Z]\w*Migration)\b/g) || [];
99
- const seen = new Set();
100
-
101
- // Pass 3: for each active name, read the corresponding file and extract the real `id:`.
102
- const migrations = [];
103
- for (const name of activeNames) {
104
- if (seen.has(name)) continue;
105
- seen.add(name);
106
- const info = importInfo[name];
107
- if (!info) continue;
108
- const filePath = path.join(scriptsDir, info.filePath + '.ts');
109
- if (!fs.existsSync(filePath)) continue;
110
- const fileContent = fs.readFileSync(filePath, 'utf-8');
111
- const id = extractMigrationId(fileContent);
112
- if (!id) continue;
113
- migrations.push({
114
- id,
115
- description: info.comment || id,
116
- });
117
- }
118
-
119
- return migrations;
120
- }
121
-
122
43
  // ---------- help text ----------
123
44
 
124
45
  function printHelp() {
@@ -178,7 +99,7 @@ async function handleStatus(flags) {
178
99
  }
179
100
 
180
101
  const applied = getAppliedMigrations(db);
181
- const source = extractMigrationsFromSource();
102
+ const source = loadMigrationList();
182
103
 
183
104
  const appliedIds = new Set(applied.map(m => m.id));
184
105
  const sourceIds = new Set(source.map(m => m.id));
@@ -227,7 +148,7 @@ async function handlePending(flags) {
227
148
  }
228
149
 
229
150
  const applied = getAppliedMigrations(db);
230
- const source = extractMigrationsFromSource();
151
+ const source = loadMigrationList();
231
152
 
232
153
  const appliedIds = new Set(applied.map(m => m.id));
233
154
  const pending = source.filter(m => !appliedIds.has(m.id));
@@ -265,7 +186,7 @@ async function handleRun(flags) {
265
186
  }
266
187
 
267
188
  const applied = getAppliedMigrations(db);
268
- const source = extractMigrationsFromSource();
189
+ const source = loadMigrationList();
269
190
 
270
191
  const appliedIds = new Set(applied.map(m => m.id));
271
192
  const pending = source.filter(m => !appliedIds.has(m.id));
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The list of migrations this version of Quilltap contains, for
5
+ * `quilltap migrations`.
6
+ *
7
+ * In a source checkout the list is read live from migrations/scripts/. The npm
8
+ * package ships only bin/ and lib/, so an installed CLI has no such folder; it
9
+ * reads migrations.generated.js instead, which scripts/build-cli-migrations.mjs
10
+ * writes from the same parser (issue #362). `npm run lint` fails while that
11
+ * file is stale.
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+
17
+ const SOURCE_SCRIPTS_DIR = path.join(__dirname, '../../..', 'migrations/scripts');
18
+
19
+ /**
20
+ * A migration's id is either a string literal on the object (`id: 'foo-v1'`)
21
+ * or a module constant (`id: MIGRATION_ID` beside `const MIGRATION_ID = 'foo-v1'`).
22
+ * Missing the constant form drops those migrations from "source", which then
23
+ * report as retired on every instance that ran them.
24
+ */
25
+ function extractMigrationId(fileContent) {
26
+ const constMatch = fileContent.match(/^\s*const\s+MIGRATION_ID\s*(?::\s*\w+\s*)?=\s*['"]([^'"]+)['"]/m);
27
+ if (constMatch && /^\s*id:\s*MIGRATION_ID\b/m.test(fileContent)) return constMatch[1];
28
+ const literalMatch = fileContent.match(/^\s*id:\s*['"]([^'"]+)['"]/m);
29
+ return literalMatch ? literalMatch[1] : null;
30
+ }
31
+
32
+ // Reads the registered migration list from migrations/scripts/index.ts and resolves each
33
+ // entry's real `id:` value by reading the imported source file. Heuristic camelCase→kebab
34
+ // conversion is unreliable (some migrations omit `-v1`, others use `-v2`), so we always
35
+ // trust the file.
36
+ function extractMigrationsFromSource(scriptsDir = SOURCE_SCRIPTS_DIR) {
37
+ const indexPath = path.join(scriptsDir, 'index.ts');
38
+ if (!fs.existsSync(indexPath)) {
39
+ return [];
40
+ }
41
+ const indexContent = fs.readFileSync(indexPath, 'utf-8');
42
+
43
+ // Pass 1: build name → { filePath, comment } from imports and preceding comments.
44
+ const lines = indexContent.split('\n');
45
+ const importInfo = {};
46
+ let lastComment = '';
47
+ for (const line of lines) {
48
+ if (line.match(/^\s*\/\/\s+/)) {
49
+ lastComment = line.replace(/^\s*\/\/\s+/, '').trim();
50
+ continue;
51
+ }
52
+ const importMatch = line.match(/import\s+\{\s*(\w+)\s*\}\s+from\s+['"]\.\/([^'"]+)['"]/);
53
+ if (importMatch) {
54
+ const [, name, filePath] = importMatch;
55
+ importInfo[name] = { filePath, comment: lastComment || '' };
56
+ lastComment = '';
57
+ } else if (line.trim() && !line.match(/^\s*\/\//) && !line.includes('import type')) {
58
+ // Reset comment if we hit a non-comment non-import line
59
+ if (!line.match(/^\s*$/)) lastComment = '';
60
+ }
61
+ }
62
+
63
+ // Pass 2: find the active migrations array section and collect names in order.
64
+ const arrayStart = indexContent.indexOf('export const migrations: Migration[] = [');
65
+ if (arrayStart === -1) return [];
66
+ const arrayEnd = indexContent.indexOf('];', arrayStart);
67
+ if (arrayEnd === -1) return [];
68
+ const arrayContent = indexContent.substring(arrayStart, arrayEnd);
69
+
70
+ const activeNames = arrayContent.match(/\b([a-zA-Z]\w*Migration)\b/g) || [];
71
+ const seen = new Set();
72
+
73
+ // Pass 3: for each active name, read the corresponding file and extract the real `id:`.
74
+ const migrations = [];
75
+ for (const name of activeNames) {
76
+ if (seen.has(name)) continue;
77
+ seen.add(name);
78
+ const info = importInfo[name];
79
+ if (!info) continue;
80
+ const filePath = path.join(scriptsDir, info.filePath + '.ts');
81
+ if (!fs.existsSync(filePath)) continue;
82
+ const fileContent = fs.readFileSync(filePath, 'utf-8');
83
+ const id = extractMigrationId(fileContent);
84
+ if (!id) continue;
85
+ migrations.push({
86
+ id,
87
+ description: info.comment || id,
88
+ });
89
+ }
90
+
91
+ return migrations;
92
+ }
93
+
94
+ /**
95
+ * The migration list: live from a source checkout when there is one, otherwise
96
+ * the generated list shipped in the package.
97
+ */
98
+ function loadMigrationList(scriptsDir = SOURCE_SCRIPTS_DIR) {
99
+ if (fs.existsSync(path.join(scriptsDir, 'index.ts'))) {
100
+ return extractMigrationsFromSource(scriptsDir);
101
+ }
102
+ return require('./migrations.generated.js');
103
+ }
104
+
105
+ module.exports = {
106
+ extractMigrationId,
107
+ extractMigrationsFromSource,
108
+ loadMigrationList,
109
+ };