Skip to content

Commit fb59ebe

Browse files
committed
feat(cli): os migrate list-preferences deletes the retired ui.list.* preference rows (wip)
Claude-Session: https://claude.ai/code/session_01FEkQ5oY5WCqqqBMtn9qt7m Co-Authored-By: Claude <noreply@anthropic.com>
1 parent a5a5312 commit fb59ebe

2 files changed

Lines changed: 495 additions & 0 deletions

File tree

Lines changed: 353 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,353 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { Command, Flags } from '@oclif/core';
4+
import { createInterface } from 'node:readline';
5+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
6+
import { resolve as resolvePath } from 'node:path';
7+
import chalk from 'chalk';
8+
import type { ObjectQL } from '@objectstack/objectql';
9+
import {
10+
printHeader,
11+
printSuccess,
12+
printWarning,
13+
printError,
14+
printInfo,
15+
printStep,
16+
createTimer,
17+
emitJson,
18+
errorCodeFields,
19+
isExitSignal,
20+
} from '../../utils/format.js';
21+
import { bootSchemaStack } from '../../utils/schema-migrate.js';
22+
import { composeProviderForDeclarations } from '../../utils/schema-migration-plugins.js';
23+
import { absentTableReads } from '../../utils/absent-table-reads.js';
24+
import { describeDriverSqliteFile } from '../../utils/connection-display.js';
25+
import { OCCUPANCY_HINT, probeMigrationTarget } from '../../utils/migrate-occupancy-gate.js';
26+
import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js';
27+
import type { ListPreferenceExport, ListPreferencePlan } from '../../utils/list-preference-sweep.js';
28+
29+
/**
30+
* `os migrate list-preferences` — delete the per-reader list preference rows
31+
* an earlier Console stored in `sys_user_preference` under `ui.list.<object>`
32+
* (#35955).
33+
*
34+
* The Console no longer reads or writes that key family: a sort, filter or
35+
* column change on a list is an unsaved draft, and the column widths, row
36+
* height and view-tab order live in the reader's browser. The stored rows are
37+
* not migrated anywhere — the maintainer ruled them cleared — so after an
38+
* upgrade they are dead weight that no door reads. This command removes them.
39+
* The family, and why the delete matches it byte for byte, is documented on
40+
* `../../utils/list-preference-sweep.ts`.
41+
*
42+
* ## The shape is `os db orphans`', with the `os migrate` flags
43+
*
44+
* 1. An explicit operator command. ⛔ Nothing on any boot, upgrade, migrate
45+
* or lifecycle path invokes it, and it must not grow such a caller
46+
* (`list-preferences.no-auto-run.test.ts` holds it).
47+
* 2. The default run is a dry-run report that writes no row or table: counts
48+
* per key and the readers holding each, never a value. The report boots
49+
* READ-ONLY, the boot `os migrate plan` takes.
50+
* 3. `--apply` deletes, and only with `--export`: every row the run deletes,
51+
* as stored, written owner-only (`0600`), created here or not at all
52+
* (`wx`), and READ BACK before the first delete. Any failure there
53+
* refuses the whole run with nothing deleted.
54+
* 4. Each delete is the engine's by-id delete in the system context, on every
55+
* organization's rows: the family is read from the driver, unscoped.
56+
* 5. Judged by what is gone, never by what a delete returned: after the
57+
* deletes the family is read again, and any row still there (one that
58+
* failed, or one an older Console wrote since the export) exits 1.
59+
*
60+
* Re-runnable: a second run finds nothing, writes no export and deletes
61+
* nothing. `ui.record.*` and every other preference key are untouched.
62+
*/
63+
export default class MigrateListPreferences extends Command {
64+
static override description =
65+
'Delete the per-reader list preference rows an earlier Console stored in sys_user_preference under ' +
66+
'"ui.list.<object>" (column widths, row height, tab order and, before that, sorts and filters), which the ' +
67+
'Console no longer reads. Dry run by default: counts per key, writes no row. --apply deletes them, only with ' +
68+
'--export, after writing every row it deletes to an owner-only file and reading it back.';
69+
70+
static override examples = [
71+
'$ os migrate list-preferences',
72+
'$ os migrate list-preferences --json',
73+
'$ os migrate list-preferences --apply --export ./list-preferences-backup.json',
74+
'$ os migrate list-preferences --apply --export ./list-preferences-backup.json --yes --json',
75+
];
76+
77+
static override flags = {
78+
'database-url': Flags.string({
79+
description: 'Database URL to migrate (defaults to $OS_DATABASE_URL / the project DB)',
80+
env: 'OS_DATABASE_URL',
81+
}),
82+
apply: Flags.boolean({
83+
description:
84+
'Delete the listed rows (default is a read-only dry run that writes no row or table). Requires --export.',
85+
default: false,
86+
}),
87+
export: Flags.string({
88+
description:
89+
'Path for the MANDATORY pre-delete export: every row the run deletes, as stored, written owner-only and '
90+
+ 'read back before the first delete. Refuses to overwrite.',
91+
}),
92+
yes: Flags.boolean({ char: 'y', description: 'Skip the --apply confirmation prompt', default: false }),
93+
force: Flags.boolean({
94+
description: 'Apply even when another process is using the database (SQLite occupancy check)',
95+
default: false,
96+
}),
97+
json: Flags.boolean({
98+
description: 'Output as JSON (implies non-interactive; requires --yes to apply)',
99+
default: false,
100+
}),
101+
};
102+
103+
async run(): Promise<void> {
104+
const { flags } = await this.parse(MigrateListPreferences);
105+
const timer = createTimer();
106+
const json = flags.json;
107+
const apply = flags.apply;
108+
109+
if (!json) printHeader('Migrate · list-preferences');
110+
111+
if (apply && !flags.export) {
112+
const message =
113+
'Refusing to delete without --export. The pre-delete export is mandatory: it is the only copy of the '
114+
+ 'rows this run deletes. Name a path for it.';
115+
if (json) { await emitJson({ error: 'export_required', message }, 1, { compact: true }); return; }
116+
printError(message);
117+
this.exit(1);
118+
return;
119+
}
120+
121+
const exportPath = flags.export ? resolvePath(flags.export) : undefined;
122+
if (exportPath && existsSync(exportPath)) {
123+
const message = `Refusing to overwrite an existing export at ${exportPath}. Name a new path.`;
124+
if (json) { await emitJson({ error: 'export_exists', message, path: exportPath }, 1, { compact: true }); return; }
125+
printError(message);
126+
this.exit(1);
127+
return;
128+
}
129+
130+
// A live server on the same SQLite file may write rows mid-run.
131+
const occupancy = await probeMigrationTarget(flags['database-url']);
132+
if (occupancy.status === 'busy' && apply && !flags.force) {
133+
if (json) {
134+
await emitJson(
135+
{ error: 'database_busy', database: occupancy.filename, signal: occupancy.signal, detail: occupancy.detail, hint: OCCUPANCY_HINT },
136+
1,
137+
{ compact: true },
138+
);
139+
return;
140+
}
141+
printError(describeOccupancy(occupancy));
142+
printWarning(OCCUPANCY_HINT);
143+
this.exit(1);
144+
return;
145+
}
146+
if (occupancy.status === 'busy' && !json) {
147+
printWarning(apply
148+
? `--force: ${describeOccupancy(occupancy)} Deleting anyway — the live process may write rows mid-run.`
149+
: `${describeOccupancy(occupancy)} The dry run below writes no row or table, but its counts may shift while that process is running. ${JOURNAL_MODE_SWITCH_NOTE}`);
150+
}
151+
if (occupancy.status === 'unknown' && !json) {
152+
printWarning(`Could not check whether the database is in use — ${occupancy.detail}`);
153+
}
154+
155+
if (!json) printStep(apply ? 'Booting (APPLY mode)…' : 'Booting (dry run)…');
156+
157+
// Loaded at the point of use, never at module load: oclif `import()`s every
158+
// command module on every invocation while building its table.
159+
const { LIST_PREFERENCE_OBJECT, buildListPreferenceExport, exportedIds, planListPreferenceSweep, readListPreferenceRows } =
160+
await import('../../utils/list-preference-sweep.js');
161+
const { createIdentityObjectsPlugin } = await import('@objectstack/plugin-auth');
162+
163+
let stack;
164+
try {
165+
stack = await bootSchemaStack({
166+
jsonOutput: json,
167+
databaseUrl: flags['database-url'],
168+
// `sys_user_preference` is an identity object: registered for its
169+
// declaration only — no auth manager, no hook, nothing started.
170+
extraPlugins: [composeProviderForDeclarations(createIdentityObjectsPlugin())],
171+
// The dry run boots READ-ONLY, the boot `os migrate plan` takes.
172+
// `--apply` keeps the plain boot: it deletes rows.
173+
...(apply ? {} : { deferSchemaDdl: true, readOnlyProbe: true }),
174+
});
175+
} catch (error) {
176+
const message = messageOf(error);
177+
if (json) { await emitJson({ error: 'boot_failed', message, ...errorCodeFields(error) }, 1, { compact: true }); return; }
178+
printError(message);
179+
this.exit(1);
180+
return;
181+
}
182+
183+
try {
184+
// Either mode's connect may have switched a SQLite file's journal mode,
185+
// which rewrites its header and no row, so no line below says nothing changed.
186+
const journalNote = describeDriverSqliteFile(stack.driver?.config) !== undefined
187+
? ` ${JOURNAL_MODE_SWITCH_NOTE}`
188+
: '';
189+
const engine = stack.kernel.getService('objectql') as ListPreferenceEngine | undefined;
190+
const driver = engine?.getDriverForObject(LIST_PREFERENCE_OBJECT);
191+
if (!engine || !driver) {
192+
const message = `No ObjectQL engine or driver serves ${LIST_PREFERENCE_OBJECT} on this runtime, so no row can be read.`;
193+
if (json) { await emitJson({ error: 'no_engine', message }, 1, { compact: true }); return; }
194+
printError(message);
195+
this.exit(1);
196+
return;
197+
}
198+
199+
// A table the read-only boot measured absent stores nothing, so it is not read.
200+
const reads = absentTableReads(stack, (object) => engine.getConfigs()[object]);
201+
const readFamily = (): Promise<Record<string, unknown>[]> =>
202+
reads.rows(LIST_PREFERENCE_OBJECT, () => readListPreferenceRows(driver));
203+
const rows = await readFamily();
204+
const plan = planListPreferenceSweep(rows);
205+
reads.notice(json);
206+
207+
if (!apply) {
208+
if (json) { await emitJson({ mode: 'report', database: stack.dbLabel, plan }, 0, { compact: true }); return; }
209+
printInfo(`Database: ${chalk.white(stack.dbLabel)}`);
210+
renderPlan(plan);
211+
printInfo(`Dry run only — no row or table was written or deleted.${journalNote} (${timer.display()})`);
212+
if (plan.counts.rows > 0) printInfo('Re-run with --apply --export <path> to delete the listed rows.');
213+
return;
214+
}
215+
216+
if (rows.length === 0) {
217+
if (json) { await emitJson({ mode: 'apply', database: stack.dbLabel, plan, deleted: 0, failed: [], remaining: 0 }, 0, { compact: true }); return; }
218+
renderPlan(plan);
219+
printSuccess('Nothing to delete — no export was written.');
220+
return;
221+
}
222+
223+
if (!json) {
224+
renderPlan(plan);
225+
printWarning(
226+
`About to permanently delete ${rows.length} ${LIST_PREFERENCE_OBJECT} row(s). The export below is the only copy that survives.`,
227+
);
228+
}
229+
if (!flags.yes) {
230+
if (json) { await emitJson({ error: 'confirmation_required', hint: 'pass --yes' }, 1, { compact: true }); return; }
231+
const ok = await confirm(chalk.yellow(` Delete ${rows.length} row(s) after writing the export? [y/N] `));
232+
if (!ok) { printInfo(`Aborted — no export was written and no row was deleted.${journalNote}`); return; }
233+
}
234+
235+
// ── The export, written and READ BACK before anything is deleted ──────
236+
const ids = rows.map((row) => String(row.id));
237+
let verified: Set<string>;
238+
try {
239+
const doc = buildListPreferenceExport({ rows, producedBy: `${this.config.bin} migrate list-preferences --apply` });
240+
// Owner-only, and CREATED here or not written at all: the existence check
241+
// above runs before the boot and the prompt, so it is a pre-check, never
242+
// the guarantee. `wx` makes the guarantee atomic. Then read back rather
243+
// than trusting the write: a short or unreadable file would leave the
244+
// delete with no copy at all, and look like a clean run.
245+
writeFileSync(exportPath!, `${JSON.stringify(doc, null, 2)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
246+
verified = exportedIds(JSON.parse(readFileSync(exportPath!, 'utf8')) as ListPreferenceExport);
247+
} catch (error) {
248+
const message =
249+
`Refusing to delete: the pre-delete export could not be written and read back at ${exportPath} — ${messageOf(error)}`;
250+
if (json) { await emitJson({ error: 'export_failed', message }, 1, { compact: true }); return; }
251+
printError(message);
252+
this.exit(1);
253+
return;
254+
}
255+
const missing = ids.filter((id) => !verified.has(id));
256+
if (missing.length > 0) {
257+
const message =
258+
`Refusing to delete: the export at ${exportPath} does not hold ${missing.length} of the ${ids.length} `
259+
+ 'row(s) to be deleted.';
260+
if (json) { await emitJson({ error: 'export_incomplete', message, missing }, 1, { compact: true }); return; }
261+
printError(message);
262+
this.exit(1);
263+
return;
264+
}
265+
if (!json) printSuccess(`Pre-delete export written (owner-only): ${exportPath}`);
266+
267+
// ── Only the exported rows, each by id, as the system ─────────────────
268+
const refusals = new Map<string, unknown>();
269+
for (const id of ids) {
270+
try {
271+
await engine.delete(LIST_PREFERENCE_OBJECT, { where: { id }, context: { isSystem: true } });
272+
} catch (error) {
273+
refusals.set(id, error);
274+
}
275+
}
276+
277+
// Judged by what is gone, never by what a delete returned.
278+
const left = await readFamily();
279+
const leftIds = new Set(left.map((row) => String(row.id)));
280+
const failed = ids
281+
.filter((id) => leftIds.has(id))
282+
.map((id) => {
283+
const refusal = refusals.get(id);
284+
return {
285+
id,
286+
message: refusal ? messageOf(refusal) : 'the delete returned, but the row is still stored',
287+
...(refusal ? errorCodeFields(refusal) : {}),
288+
};
289+
});
290+
const deleted = ids.length - failed.length;
291+
const unlisted = left.length - failed.length;
292+
293+
if (json) {
294+
await emitJson(
295+
{ mode: 'apply', database: stack.dbLabel, export: exportPath, plan, deleted, failed, remaining: left.length },
296+
left.length > 0 ? 1 : 0,
297+
{ compact: true },
298+
);
299+
return;
300+
}
301+
printSuccess(`Deleted ${deleted} ${LIST_PREFERENCE_OBJECT} row(s) in ${timer.display()}.`);
302+
for (const f of failed) printError(` ${f.id}: ${f.message}`);
303+
if (unlisted > 0) {
304+
printError(
305+
` ${unlisted} row(s) of the family appeared after the export was written (a Console that still writes `
306+
+ 'them is running?). They were not deleted; re-run with a new --export path.',
307+
);
308+
}
309+
printInfo(`Keep ${exportPath} until you are certain the sweep was correct — it is the only copy.`);
310+
if (left.length > 0) this.exit(1);
311+
} catch (error) {
312+
// A read the run could not make is a refusal, and under `--json` a
313+
// refusal is still one JSON document.
314+
if (isExitSignal(error)) throw error;
315+
const message = messageOf(error);
316+
if (json) { await emitJson({ error: 'scan_failed', message, ...errorCodeFields(error) }, 1, { compact: true }); return; }
317+
printError(message);
318+
this.exit(1);
319+
} finally {
320+
await stack.shutdown();
321+
}
322+
}
323+
}
324+
325+
/** The engine slice this command reads, and the one write verb it uses. */
326+
type ListPreferenceEngine = Pick<ObjectQL, 'delete' | 'getConfigs' | 'getDriverForObject'>;
327+
328+
function messageOf(error: unknown): string {
329+
return error instanceof Error ? error.message : String(error);
330+
}
331+
332+
async function confirm(question: string): Promise<boolean> {
333+
if (!process.stdin.isTTY) return false; // non-interactive → require --yes
334+
const rl = createInterface({ input: process.stdin, output: process.stdout });
335+
try {
336+
const answer: string = await new Promise((resolve) => rl.question(question, resolve));
337+
return /^y(es)?$/i.test(answer.trim());
338+
} finally {
339+
rl.close();
340+
}
341+
}
342+
343+
/** Render the plan for a human: counts only, never a value. */
344+
function renderPlan(plan: ListPreferencePlan): void {
345+
console.log(chalk.bold(`\n ${plan.object} rows keyed ${plan.prefix}<object>`));
346+
printInfo(
347+
`${plan.counts.rows} row(s) · ${plan.counts.users} reader(s) · ${plan.counts.organizations} organization(s)`,
348+
);
349+
for (const entry of plan.byKey) {
350+
console.log(` ${chalk.white(entry.key)}: ${entry.rows} row(s), ${entry.users} reader(s)`);
351+
}
352+
console.log('');
353+
}

0 commit comments

Comments
 (0)