diff --git a/.changeset/35955-migrate-list-preferences.md b/.changeset/35955-migrate-list-preferences.md new file mode 100644 index 00000000000..d67e4da5a9a --- /dev/null +++ b/.changeset/35955-migrate-list-preferences.md @@ -0,0 +1,18 @@ +--- +'@objectstack/cli': patch +--- + +feat(cli): `os migrate list-preferences` deletes the per-reader list preference rows the Console no longer reads + +Clause-②: no +Metadata-protocol: none + +The Console no longer reads or writes the per-reader list preference rows an earlier Console stored in `sys_user_preference` under `ui.list.` (column widths, row height, view-tab order and, before that, sorts, filters and columns). The rows are not carried anywhere. This new operator command deletes them. + +- `os migrate list-preferences` is a dry run by default: it counts the rows, readers and organizations, and per key the rows and readers holding it. It never prints a value and writes no row, table or file. +- `--apply` deletes, and only with `--export `: every row the run deletes, as stored, is written to an owner-only file (`0600`, never overwriting one) and read back before the first delete. Each delete is the engine's by-id delete in the system context, on every organization's rows. +- After the deletes the family is read again; any row still there exits `1`. A second run finds nothing and exits `0`. +- A row belongs to the family only when its key starts with `ui.list.`, compared exactly. `ui.record.` and every other preference key are untouched. +- Nothing on a boot, upgrade or migrate path runs it. + +Upgrade note: once the upgraded Console is serving, run `os migrate list-preferences` once, a dry run first and then `--apply --export `. Left in place the rows are unread, so it is cleanup, not a gate. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 775060e0890..7ad7937764b 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1546,6 +1546,7 @@ where the data lives. | `os migrate audit-mail-bodies` | Mask the mail bodies (`body_text`, `body_html`) that `sys_audit_log` and `sys_activity` copies of `sys_email` / `sys_identity_email` rows still hold in clear, written before the audit writer masked them. Covers the `archive` datasource `sys_audit_log` archives to as well. Reports counts only. No flag; idempotent. See [below](#os-migrate-audit-mail-bodies) | | `os migrate audit-key-material` | Remove the encrypted key-material columns from the `sys_audit_log` and `sys_activity` copies written before the audit writer omitted them. Covers the `archive` datasource `sys_audit_log` archives to as well. Reports counts only. No flag; idempotent. See [below](#os-migrate-audit-key-material) | | `os migrate audit-side-copies` | Remove the side-copy columns (another record's field values, such as an approval request's `payload_json`) from the `sys_audit_log` and `sys_activity` copies written before the audit writer omitted them. Covers the `archive` datasource `sys_audit_log` archives to as well. `--object` narrows it to one copy table. Reports counts only, per table and store. No flag; idempotent. See [below](#os-migrate-audit-side-copies) | +| `os migrate list-preferences` | Delete the per-reader list preference rows an earlier Console stored in `sys_user_preference` under `ui.list.`, which the Console no longer reads. Dry run by default (counts per key, writes no row); `--apply` deletes, only with an owner-only `--export` written and read back first. Run it once after upgrading. See [below](#os-migrate-list-preferences) | | `os migrate comment-parent-pair` | Stamp the parent pair (`object_name`, `record_id`) on the `sys_comment` rows written before it existed. Until it runs, a broad comment read past 2,000 candidate rows omits comments the reader may see, and its total agrees with the short list, so run it at once after upgrading. No flag; idempotent | | `os migrate meta --stored` | Replay the metadata conversion chain over this deployment's `sys_metadata` rows and rewrite the ones still carrying a pre-protocol shape. Hygiene, not a gate — nothing depends on it having run | | `os migrate security-catalog-overlays` | List the environment-wide permission-set and position rows (the legacy plurals `permissions` / `positions` included) stored over a name a configured package holds — the rows a v18 cold boot refuses — each with the package that holds its name; `--apply` deletes them, one history tombstone per row. Run it before the first v18 boot, with the flags and environment the deployment boots with: the platform security plugin's sets are held only where `os serve` composes it (an auth secret set, and the `auth` tier on), and the step takes `serve`'s `--preset` and `--dev` with `serve`'s meaning. Adopts nothing; exits 1 while it lists a row | @@ -2390,6 +2391,50 @@ the upgraded deployment's schema sync, which an `--apply` run performs itself: a dry run against a database no upgraded process has opened cannot read them, reports the failed read and exits `1`. A failed read or write exits `1`. +#### `os migrate list-preferences` + +An earlier Console remembered each reader's list state on the server: one +`sys_user_preference` row per reader and object, keyed `ui.list.`. It +held the column widths, the row height and the view tabs' order, and before +that the reader's sorts, filters and columns too. The Console no longer reads +or writes those rows: a change on a list is an unsaved draft until the reader +saves it into a view, and the widths, row height and tab order are kept in the +reader's own browser. The stored rows are not carried anywhere; every reader's +lists open as their views declare them. This command deletes the rows. + +```bash +os migrate list-preferences # Dry run: counts per key, writes no rows +os migrate list-preferences --json # the same report, machine-readable +os migrate list-preferences --apply --export ./list-preferences-backup.json +os migrate list-preferences --apply --export ./list-preferences-backup.json --yes --json +``` + +The report counts the rows, the readers and the organizations, and per key +(`ui.list.account`, …) the rows and the readers holding it. It never prints a +value. It reads every organization's rows. A row belongs to the family only when +its key starts with `ui.list.`, compared exactly, dot and case included: +`ui.record.` (the record page's "show empty fields" choice, still read), +`ui.recent` and every other preference key are never touched. + +**Options:** +- `--apply` — delete the listed rows (default off: a read-only dry run) +- `--export ` — **mandatory with `--apply`**: every row the run deletes, as stored, written + owner-only (`0600`) and read back before the first delete; refuses to overwrite an existing file +- `-y, --yes` — skip the confirmation prompt; without it, a run whose stdin is not a terminal (or `--json`) reads + nothing, deletes nothing and exits `1` +- `--force` — apply even when another process is using the SQLite file +- `--database-url `, `--json` + +Each delete is the engine's by-id delete in the system context. After the +deletes the family is read again, and the run exits `1` when any row is still +there: one whose delete was refused, or one a Console that still writes the +family stored after the export. **Re-runnable**: a second run finds nothing, +writes no export and exits `0`. It is never run for you; nothing on any boot, +upgrade, migrate or lifecycle path invokes it. Run it once after the upgraded +Console is serving (an older Console would write the rows again), and keep the +export until you are certain the sweep was right: it is the only copy, and +nothing reads it back into the platform. + #### A database created by this version needs no migration A deployment whose database the platform **creates from empty** records these diff --git a/content/docs/upgrading.mdx b/content/docs/upgrading.mdx index 5f48d0b1765..64d94d8e174 100644 --- a/content/docs/upgrading.mdx +++ b/content/docs/upgrading.mdx @@ -493,6 +493,8 @@ the protocol-18 step, which `os migrate meta --from 17` lists for your sources **Upgrading from 18.5.0 or earlier:** the first [`os migrate plan`](/docs/deployment/cli#schema-migrations) after the move lists a safe `create_index` for each `(created_at, id)` and `(owner_id)` index schema sync now builds without a declaration, and on SQLite a `normalize_boolean_storage` step for boolean cells stored as text; the next sync or `os migrate apply` builds them, and neither is destructive. Where an app declares `lifecycle.seal`, an `os migrate audit-* --apply` run on SQLite or Turso now needs every sealing server stopped and `--sealer-stopped` ([18.6.0 checklist](/docs/releases/v18/18-6#upgrade-checklist)). +**Upgrading from 18.6.0 or earlier:** the Console no longer reads the per-reader list preferences stored in `sys_user_preference` under `ui.list.`, so every reader's lists open on their views' own sorts, filters, columns, widths, row height and tab order; nothing is carried over. Once the upgraded Console is serving, run [`os migrate list-preferences`](/docs/deployment/cli#os-migrate-list-preferences) once, a dry run first and then `--apply --export `; it deletes those rows after writing them to an owner-only export. Left in place they are unread, so it is cleanup, not a gate. + The v17 and v18 lines are broken out per release. Each v17 minor shipped breaking changes under the repo's launch-window convention — which ships a breaking change as `minor` rather than `major`, so the version number is not the diff --git a/packages/cli/src/commands/migrate/list-preferences.integration.test.ts b/packages/cli/src/commands/migrate/list-preferences.integration.test.ts new file mode 100644 index 00000000000..5202ae73230 --- /dev/null +++ b/packages/cli/src/commands/migrate/list-preferences.integration.test.ts @@ -0,0 +1,343 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35955] `os migrate list-preferences` against a real boot and a real + * SQLite database. + * + * ## The fixture + * + * `sys_user_preference` rows written through a SYSTEM insert, in two + * organizations: + * + * - the retired family, `ui.list.`: three readers in organization A, + * one in organization B; + * - rows that must survive: `ui.record.account` (the record page's family, + * still read), `ui.recent`, the bare key `ui.list`, a look-alike prefix + * `ui.listx.account`, and `UI.LIST.account` — together they pin that the + * driver's `$startsWith` read is the family exactly: the trailing dot and + * the case both count. + * + * ## What each case proves + * + * - The dry run counts per key and readers, writes no row, no table and no + * file. + * - `--apply --export` writes the export owner-only first — the first delete + * FINDS it complete on disk (the order pin) — deletes the family in both + * organizations and nothing else, and reads back zero. + * - A second run finds nothing, writes no export and exits 0. + * - The refusals answer their own `error` code and exit 1, with nothing + * deleted. + */ + +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; +import { randomBytes } from 'node:crypto'; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectQL } from '@objectstack/objectql'; +import { createIdentityObjectsPlugin } from '@objectstack/plugin-auth'; +import { isExitSignal } from '../../utils/format.js'; +import { bootSchemaStack } from '../../utils/schema-migrate.js'; +import { composeProviderForDeclarations } from '../../utils/schema-migration-plugins.js'; +import MigrateListPreferences from './list-preferences.js'; + +// Pay the first load of what `bootSchemaStack` and the command reach through +// dynamic `import()`s at MODULE LOAD, outside any clocked case. +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; +import '@objectstack/runtime'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI_ROOT = resolve(HERE, '..', '..', '..'); +const CASE_TIMEOUT_MS = 120_000; +const OVERRIDING_ENV = ['OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME'] as const; +const SYSTEM = { context: { isSystem: true } }; +const TABLE = 'sys_user_preference'; + +const ARTIFACT = { + manifest: { id: 'com.example.list-preferences', name: 'List Preferences', version: '0.0.0', type: 'app' }, + objects: [{ name: 'lp_account', fields: { name: { type: 'text' } } }], +}; + +const ORG_A = 'org_lp_a'; +const ORG_B = 'org_lp_b'; + +/** The retired family, in two organizations. */ +const FAMILY = [ + { id: 'p_u1_account', organization_id: ORG_A, user_id: 'u1', key: 'ui.list.account', value: { perView: { all: { widths: { name: 240 } } } } }, + { id: 'p_u2_account', organization_id: ORG_A, user_id: 'u2', key: 'ui.list.account', value: { viewOrder: ['b', 'a'] } }, + { id: 'p_u1_contact', organization_id: ORG_A, user_id: 'u1', key: 'ui.list.contact', value: { perView: { all: { sort: [{ field: 'name', order: 'asc' }] } } } }, + { id: 'p_u3_account', organization_id: ORG_B, user_id: 'u3', key: 'ui.list.account', value: { perView: { all: { rowHeight: 44 } } } }, +]; + +/** Rows that must survive every run. */ +const SURVIVORS = [ + { id: 's_record', organization_id: ORG_A, user_id: 'u1', key: 'ui.record.account', value: { showEmptyFields: false } }, + { id: 's_recent', organization_id: ORG_A, user_id: 'u1', key: 'ui.recent', value: ['lp_account'] }, + { id: 's_bare', organization_id: ORG_A, user_id: 'u1', key: 'ui.list', value: true }, + { id: 's_lookalike', organization_id: ORG_A, user_id: 'u1', key: 'ui.listx.account', value: true }, + { id: 's_case', organization_id: ORG_B, user_id: 'u3', key: 'UI.LIST.account', value: true }, +]; + +const FAMILY_IDS = FAMILY.map((r) => r.id).sort(); +const SURVIVOR_IDS = SURVIVORS.map((r) => r.id).sort(); + +let dir: string; +let templateDb: string; +const savedEnv: Record = {}; +const savedCwd = process.cwd(); + +/** The table's ids, read on a connection of our own. */ +async function idsOf(dbFile: string): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: dbFile }, useNullAsDefault: true }); + try { + return ((await (driver as any).knex(TABLE).select('id').orderBy('id')) as Array<{ id: string }>).map((r) => r.id); + } finally { + await driver.disconnect(); + } +} + +/** The schema plus every row of every table, as plain JSON. */ +async function readState(dbFile: string): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: dbFile }, useNullAsDefault: true }); + const k = (driver as any).knex; + try { + const schema = await k.raw('SELECT type, name, sql FROM sqlite_master ORDER BY type, name'); + const rows: Record = {}; + for (const entry of schema as Array<{ type: string; name: string }>) { + if (entry.type !== 'table' || entry.name.startsWith('sqlite_')) continue; + rows[entry.name] = await k.raw(`SELECT * FROM "${entry.name}" ORDER BY rowid`); + } + return { schema, rows }; + } finally { + await driver.disconnect(); + } +} + +interface RunResult { payload: any; exitCode: number } + +async function runJson(argv: string[]): Promise { + const savedExit = process.exitCode; + const swallow = ((_chunk: unknown, ...rest: unknown[]) => { + const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined; + if (cb) cb(); + return true; + }) as typeof process.stdout.write; + const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow); + const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(swallow); + const logs = [vi.spyOn(console, 'log'), vi.spyOn(console, 'warn'), vi.spyOn(console, 'error')] + .map((s) => s.mockImplementation(() => {})); + let thrownExit: number | undefined; + try { + try { + await MigrateListPreferences.run(argv, { root: CLI_ROOT }); + } catch (error) { + if (!isExitSignal(error)) throw error; + thrownExit = (error as { oclif?: { exit?: number } }).oclif?.exit; + } + const out = stdout.mock.calls.map((c) => String(c[0])).join('').trim(); + let payload: any; + try { payload = JSON.parse(out); } catch { payload = { unparsed: out.slice(-400) }; } + return { payload, exitCode: thrownExit ?? (process.exitCode as number | undefined) ?? 0 }; + } finally { + process.exitCode = savedExit; + stdout.mockRestore(); + stderr.mockRestore(); + for (const s of logs) s.mockRestore(); + } +} + +let caseSeq = 0; +function prepareCase(): { dbFile: string; caseDir: string; url: string } { + caseSeq += 1; + const caseDir = join(dir, 'cases', String(caseSeq)); + mkdirSync(caseDir, { recursive: true }); + const dbFile = join(caseDir, 'app.db'); + copyFileSync(templateDb, dbFile); + return { dbFile, caseDir, url: `file:${dbFile}` }; +} + +beforeAll(async () => { + for (const key of [...OVERRIDING_ENV, 'OS_ARTIFACT_PATH', 'NODE_ENV', 'OS_SECRET_KEY'] as const) savedEnv[key] = process.env[key]; + for (const key of OVERRIDING_ENV) delete process.env[key]; + process.env.NODE_ENV = 'production'; + process.env.OS_SECRET_KEY = randomBytes(32).toString('hex'); + dir = mkdtempSync(join(tmpdir(), 'os-35955-')); + mkdirSync(join(dir, 'dist'), { recursive: true }); + mkdirSync(join(dir, 'data'), { recursive: true }); + process.env.OS_ARTIFACT_PATH = join(dir, 'dist', 'objectstack.json'); + writeFileSync(process.env.OS_ARTIFACT_PATH, JSON.stringify(ARTIFACT)); + templateDb = join(dir, 'data', 'template.db'); + process.chdir(dir); + const stack = await bootSchemaStack({ + jsonOutput: false, + databaseUrl: `file:${templateDb}`, + projectRoot: dir, + extraPlugins: [composeProviderForDeclarations(createIdentityObjectsPlugin())], + }); + try { + const ql = stack.kernel.getService('objectql') as ObjectQL; + for (const row of [...FAMILY, ...SURVIVORS]) await ql.insert(TABLE, row, SYSTEM); + } finally { + await stack.shutdown(); + } + process.chdir(savedCwd); + // Non-vacuity: the seed is the state every case starts from. + expect(await idsOf(templateDb)).toEqual([...FAMILY_IDS, ...SURVIVOR_IDS].sort()); +}, 180_000); + +afterAll(() => { + process.chdir(savedCwd); + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ } +}); + +beforeEach(() => { process.chdir(dir); }); +afterEach(() => { process.chdir(savedCwd); vi.restoreAllMocks(); }); + +describe('[#35955] os migrate list-preferences — the default run is a dry run that writes nothing', () => { + it('counts the family per key and reader, in every organization, and writes no row, table or file', async () => { + const c = prepareCase(); + const before = await readState(c.dbFile); + + const { payload, exitCode } = await runJson(['--database-url', c.url, '--json']); + + expect(exitCode).toBe(0); + expect(payload.mode).toBe('report'); + expect(payload.plan).toEqual({ + object: TABLE, + prefix: 'ui.list.', + counts: { rows: 4, users: 3, organizations: 2 }, + byKey: [ + { key: 'ui.list.account', rows: 3, users: 3 }, + { key: 'ui.list.contact', rows: 1, users: 1 }, + ], + }); + // Counts only: no stored value reaches the report. + expect(JSON.stringify(payload)).not.toContain('240'); + expect(await readState(c.dbFile)).toEqual(before); + expect(existsSync(join(c.caseDir, 'export.json'))).toBe(false); + }, CASE_TIMEOUT_MS); +}); + +describe('[#35955] os migrate list-preferences --apply --export', () => { + it('writes the export owner-only, deletes the family in both organizations and nothing else, and reads back zero', async () => { + const c = prepareCase(); + const exportPath = join(c.caseDir, 'export.json'); + + const { payload, exitCode } = await runJson(['--apply', '--export', exportPath, '--yes', '--database-url', c.url, '--json']); + + expect(payload.error, JSON.stringify(payload).slice(0, 400)).toBeUndefined(); + expect(exitCode).toBe(0); + expect(payload).toMatchObject({ mode: 'apply', deleted: 4, failed: [], remaining: 0 }); + expect(await idsOf(c.dbFile)).toEqual(SURVIVOR_IDS); + + expect(statSync(exportPath).mode & 0o777).toBe(0o600); + const doc = JSON.parse(readFileSync(exportPath, 'utf8')); + expect(doc.format).toBe('objectstack.list-preferences.pre-delete-export.v1'); + expect(doc.rows.map((r: { id: string }) => r.id).sort()).toEqual(FAMILY_IDS); + // Each row as stored, its organization and value included. + const u3 = doc.rows.find((r: { id: string }) => r.id === 'p_u3_account'); + expect(u3).toMatchObject({ organization_id: ORG_B, user_id: 'u3', key: 'ui.list.account' }); + expect(JSON.stringify(u3.value)).toContain('44'); + }, CASE_TIMEOUT_MS); + + it('the first delete finds the export already on disk, holding every row the run deletes', async () => { + const c = prepareCase(); + const exportPath = join(c.caseDir, 'export.json'); + const original = ObjectQL.prototype.delete; + let seenAtFirstDelete: string[] | 'no file' | undefined; + // Intercept the command's own delete, and only that one. + vi.spyOn(ObjectQL.prototype, 'delete').mockImplementation(async function (this: ObjectQL, object: string, options?: any) { + if (object === TABLE && seenAtFirstDelete === undefined) { + seenAtFirstDelete = existsSync(exportPath) + ? JSON.parse(readFileSync(exportPath, 'utf8')).rows.map((r: { id: string }) => r.id).sort() + : 'no file'; + throw Object.assign(new Error('injected: the first delete refuses'), { code: 'INJECTED_REFUSAL' }); + } + return original.call(this, object, options); + }); + + const { payload, exitCode } = await runJson(['--apply', '--export', exportPath, '--yes', '--database-url', c.url, '--json']); + + // Non-vacuity: the command reached its delete through the intercepted method. + expect(seenAtFirstDelete).toEqual(FAMILY_IDS); + // The refused row is judged by what is still stored, and the run exits 1. + expect(exitCode).toBe(1); + expect(payload.deleted).toBe(3); + expect(payload.remaining).toBe(1); + expect(payload.failed).toEqual([expect.objectContaining({ code: 'INJECTED_REFUSAL' })]); + expect(await idsOf(c.dbFile)).toEqual([payload.failed[0].id, ...SURVIVOR_IDS].sort()); + }, CASE_TIMEOUT_MS); + + it('is re-runnable: a second run finds nothing, writes no export and exits 0', async () => { + const c = prepareCase(); + + const first = await runJson(['--apply', '--export', join(c.caseDir, 'first.json'), '--yes', '--database-url', c.url, '--json']); + expect(first.exitCode).toBe(0); + const second = await runJson(['--apply', '--export', join(c.caseDir, 'second.json'), '--yes', '--database-url', c.url, '--json']); + + expect(second.exitCode).toBe(0); + expect(second.payload).toMatchObject({ mode: 'apply', deleted: 0, remaining: 0, plan: { counts: { rows: 0 } } }); + expect(existsSync(join(c.caseDir, 'second.json'))).toBe(false); + expect(await idsOf(c.dbFile)).toEqual(SURVIVOR_IDS); + }, CASE_TIMEOUT_MS); +}); + +describe('[#35955] os migrate list-preferences — refusals answer their code and exit 1, with nothing deleted', () => { + it('--apply without --export is refused before anything boots', async () => { + const c = prepareCase(); + const before = await readState(c.dbFile); + + const { payload, exitCode } = await runJson(['--apply', '--yes', '--database-url', c.url, '--json']); + + expect(payload.error).toBe('export_required'); + expect(exitCode).toBe(1); + expect(await readState(c.dbFile)).toEqual(before); + }, CASE_TIMEOUT_MS); + + it('an export path that already exists is refused, and left as it was', async () => { + const c = prepareCase(); + const exportPath = join(c.caseDir, 'export.json'); + writeFileSync(exportPath, 'not ours'); + + const { payload, exitCode } = await runJson(['--apply', '--export', exportPath, '--yes', '--database-url', c.url, '--json']); + + expect(payload.error).toBe('export_exists'); + expect(exitCode).toBe(1); + expect(readFileSync(exportPath, 'utf8')).toBe('not ours'); + expect(await idsOf(c.dbFile)).toEqual([...FAMILY_IDS, ...SURVIVOR_IDS].sort()); + }, CASE_TIMEOUT_MS); + + it('an export path that cannot be written refuses the run, with no row deleted', async () => { + const c = prepareCase(); + const exportPath = join(c.caseDir, 'no-such-directory', 'export.json'); + + const { payload, exitCode } = await runJson(['--apply', '--export', exportPath, '--yes', '--database-url', c.url, '--json']); + + expect(payload.error).toBe('export_failed'); + expect(exitCode).toBe(1); + expect(existsSync(exportPath)).toBe(false); + expect(await idsOf(c.dbFile)).toEqual([...FAMILY_IDS, ...SURVIVOR_IDS].sort()); + }, CASE_TIMEOUT_MS); + + it('--apply under --json without --yes asks for it, with nothing written', async () => { + const c = prepareCase(); + const exportPath = join(c.caseDir, 'export.json'); + + const { payload, exitCode } = await runJson(['--apply', '--export', exportPath, '--database-url', c.url, '--json']); + + expect(payload.error).toBe('confirmation_required'); + expect(exitCode).toBe(1); + expect(existsSync(exportPath)).toBe(false); + expect(await idsOf(c.dbFile)).toEqual([...FAMILY_IDS, ...SURVIVOR_IDS].sort()); + }, CASE_TIMEOUT_MS); +}); diff --git a/packages/cli/src/commands/migrate/list-preferences.no-auto-run.test.ts b/packages/cli/src/commands/migrate/list-preferences.no-auto-run.test.ts new file mode 100644 index 00000000000..efd3426a1a2 --- /dev/null +++ b/packages/cli/src/commands/migrate/list-preferences.no-auto-run.test.ts @@ -0,0 +1,95 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35955] Nothing runs `os migrate list-preferences` for you. It deletes + * every reader's stored list state, so it is an explicit operator command: + * nothing on a boot, upgrade, migrate or lifecycle path invokes it, and it + * must not grow such a caller. This is the pin that keeps it true. + * + * The distance between an operator command and an auto-remedy is one import: + * a boot path that reaches for this module, or for the plan it deletes from, + * deletes user data with nobody watching. So the pin reads the source for + * every way a caller could reach it — the command module and the plan module — + * and admits only this command's own files and its tests. + * + * ## A negative result is evidence only after the instrument has produced a + * ## positive one + * + * "No file imports it" is also what a broken scanner says. So every absence + * below is preceded by the SAME scanner finding a call site that really + * exists, including one on the boot path itself (`commands/serve.ts` reaching + * the `kernel:ready` migration gate through a dynamic import, the shape an + * accidental auto-run would take). The shape is `../db/orphans.no-auto-run.test.ts`'s. + */ + +import { describe, it, expect } from 'vitest'; +import { readFileSync, readdirSync, statSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** `packages/cli/src` — this package only; the scan never leaves it. */ +const SRC_ROOT = fileURLToPath(new URL('../../', import.meta.url)); + +function everyTsFile(dir: string, out: string[] = []): string[] { + for (const entry of readdirSync(dir)) { + const full = join(dir, entry); + if (statSync(full).isDirectory()) everyTsFile(full, out); + else if (entry.endsWith('.ts')) out.push(full); + } + return out; +} + +const ALL_FILES = everyTsFile(SRC_ROOT); +const relative = (file: string) => file.slice(SRC_ROOT.length).replaceAll('\\', '/'); +const isTestFile = (path: string) => /\.test\.ts$/.test(path); + +/** A static `from '…'` or a dynamic `import('…')` specifier. Read over raw text: prose naming one is a loud false positive, never a hole. */ +const IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(\s*)['"]([^'"]+)['"]/g; + +/** Files whose relative import RESOLVES to `target` (a path under `src/`), whatever the specifier's spelling. */ +function importersOf(target: string): string[] { + const wanted = join(SRC_ROOT, target); + return ALL_FILES.filter((file) => { + for (const m of readFileSync(file, 'utf8').matchAll(IMPORT_SPECIFIER)) { + const spec = m[1]!; + if (!spec.startsWith('.')) continue; + if (resolve(dirname(file), spec).replace(/\.js$/, '.ts') === wanted) return true; + } + return false; + }).map(relative); +} + +const COMMAND = 'commands/migrate/list-preferences.ts'; +const PLAN = 'utils/list-preference-sweep.ts'; +/** The one-shot boot family's enumeration pin RUNS every bootSchemaStack caller's modes; a test, never a boot path. */ +const FAMILY_PIN = 'utils/schema-migrate.one-shot-family.integration.test.ts'; + +describe('[#35955] the scanner works (positive controls)', () => { + it('finds the CLI’s own boot path reaching the kernel:ready migration gate — a DYNAMIC import', () => { + expect(importersOf('utils/artifact-boot-migration.ts').filter((p) => !isTestFile(p))).toContain('commands/serve.ts'); + }); + + it('finds this command reaching its plan module through a dynamic import', () => { + expect(importersOf(PLAN)).toContain(COMMAND); + }); + + it('the file population itself is real', () => { + expect(ALL_FILES.length).toBeGreaterThan(100); + expect(ALL_FILES.map(relative)).toContain(COMMAND); + }); +}); + +describe('[#35955] nothing on a boot, upgrade, migrate or lifecycle path invokes this command', () => { + it('no source file imports the command — its own tests and the family pin are the only readers', () => { + const importers = importersOf(COMMAND); + expect(importers.filter((p) => !isTestFile(p))).toEqual([]); + expect( + importers.every((p) => p.startsWith('commands/migrate/list-preferences.') || p === FAMILY_PIN), + importers.join(', '), + ).toBe(true); + }); + + it('no source file but the command imports the plan it deletes from', () => { + expect(importersOf(PLAN).filter((p) => !isTestFile(p))).toEqual([COMMAND]); + }); +}); diff --git a/packages/cli/src/commands/migrate/list-preferences.ts b/packages/cli/src/commands/migrate/list-preferences.ts new file mode 100644 index 00000000000..3735a6e32d7 --- /dev/null +++ b/packages/cli/src/commands/migrate/list-preferences.ts @@ -0,0 +1,367 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { Command, Flags } from '@oclif/core'; +import { createInterface } from 'node:readline'; +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { resolve as resolvePath } from 'node:path'; +import chalk from 'chalk'; +import type { ObjectQL } from '@objectstack/objectql'; +import { + printHeader, + printSuccess, + printWarning, + printError, + printInfo, + printStep, + createTimer, + emitJson, + errorCodeFields, + isExitSignal, +} from '../../utils/format.js'; +import { bootSchemaStack } from '../../utils/schema-migrate.js'; +import { composeProviderForDeclarations } from '../../utils/schema-migration-plugins.js'; +import { absentTableReads } from '../../utils/absent-table-reads.js'; +import { describeDriverSqliteFile } from '../../utils/connection-display.js'; +import { OCCUPANCY_HINT, probeMigrationTarget } from '../../utils/migrate-occupancy-gate.js'; +import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js'; +import type { ListPreferenceExport, ListPreferencePlan } from '../../utils/list-preference-sweep.js'; + +/** + * `os migrate list-preferences` — delete the per-reader list preference rows + * an earlier Console stored in `sys_user_preference` under `ui.list.` + * (#35955). + * + * The Console no longer reads or writes that key family: a sort, filter or + * column change on a list is an unsaved draft, and the column widths, row + * height and view-tab order live in the reader's browser. The stored rows are + * not migrated anywhere — the maintainer ruled them cleared — so after an + * upgrade they are dead weight that no door reads. This command removes them. + * The family, and why the delete matches it byte for byte, is documented on + * `../../utils/list-preference-sweep.ts`. + * + * ## The shape is `os db orphans`', with the `os migrate` flags + * + * 1. An explicit operator command. ⛔ Nothing on any boot, upgrade, migrate + * or lifecycle path invokes it, and it must not grow such a caller + * (`list-preferences.no-auto-run.test.ts` holds it). + * 2. The default run is a dry-run report that writes no row or table: counts + * per key and the readers holding each, never a value. The report boots + * READ-ONLY, the boot `os migrate plan` takes. + * 3. `--apply` deletes, and only with `--export`: every row the run deletes, + * as stored, written owner-only (`0600`), created here or not at all + * (`wx`), and READ BACK before the first delete. Any failure there + * refuses the whole run with nothing deleted. + * 4. Each delete is the engine's by-id delete in the system context, on every + * organization's rows: the family is read from the driver, unscoped. + * 5. Judged by what is gone, never by what a delete returned: after the + * deletes the family is read again, and any row still there (one that + * failed, or one an older Console wrote since the export) exits 1. + * + * Re-runnable: a second run finds nothing, writes no export and deletes + * nothing. `ui.record.*` and every other preference key are untouched. + */ +export default class MigrateListPreferences extends Command { + static override description = + 'Delete the per-reader list preference rows an earlier Console stored in sys_user_preference under ' + + '"ui.list." (column widths, row height, tab order and, before that, sorts and filters), which the ' + + 'Console no longer reads. Dry run by default: counts per key, writes no row. --apply deletes them, only with ' + + '--export, after writing every row it deletes to an owner-only file and reading it back.'; + + static override examples = [ + '$ os migrate list-preferences', + '$ os migrate list-preferences --json', + '$ os migrate list-preferences --apply --export ./list-preferences-backup.json', + '$ os migrate list-preferences --apply --export ./list-preferences-backup.json --yes --json', + ]; + + static override flags = { + 'database-url': Flags.string({ + description: 'Database URL to migrate (defaults to $OS_DATABASE_URL / the project DB)', + env: 'OS_DATABASE_URL', + }), + apply: Flags.boolean({ + description: + 'Delete the listed rows (default is a read-only dry run that writes no row or table). Requires --export.', + default: false, + }), + export: Flags.string({ + description: + 'Path for the MANDATORY pre-delete export: every row the run deletes, as stored, written owner-only and ' + + 'read back before the first delete. Refuses to overwrite.', + }), + yes: Flags.boolean({ char: 'y', description: 'Skip the --apply confirmation prompt', default: false }), + force: Flags.boolean({ + description: 'Apply even when another process is using the database (SQLite occupancy check)', + default: false, + }), + json: Flags.boolean({ + description: 'Output as JSON (implies non-interactive; requires --yes to apply)', + default: false, + }), + }; + + async run(): Promise { + const { flags } = await this.parse(MigrateListPreferences); + const timer = createTimer(); + const json = flags.json; + const apply = flags.apply; + + if (!json) printHeader('Migrate · list-preferences'); + + if (apply && !flags.export) { + const message = + 'Refusing to delete without --export. The pre-delete export is mandatory: it is the only copy of the ' + + 'rows this run deletes. Name a path for it.'; + if (json) { await emitJson({ error: 'export_required', message }, 1, { compact: true }); return; } + printError(message); + this.exit(1); + return; + } + + const exportPath = flags.export ? resolvePath(flags.export) : undefined; + if (exportPath && existsSync(exportPath)) { + const message = `Refusing to overwrite an existing export at ${exportPath}. Name a new path.`; + if (json) { await emitJson({ error: 'export_exists', message, path: exportPath }, 1, { compact: true }); return; } + printError(message); + this.exit(1); + return; + } + + // A live server on the same SQLite file may write rows mid-run. + const occupancy = await probeMigrationTarget(flags['database-url']); + if (occupancy.status === 'busy' && apply && !flags.force) { + if (json) { + await emitJson( + { error: 'database_busy', database: occupancy.filename, signal: occupancy.signal, detail: occupancy.detail, hint: OCCUPANCY_HINT }, + 1, + { compact: true }, + ); + return; + } + printError(describeOccupancy(occupancy)); + printWarning(OCCUPANCY_HINT); + this.exit(1); + return; + } + if (occupancy.status === 'busy' && !json) { + printWarning(apply + ? `--force: ${describeOccupancy(occupancy)} Deleting anyway — the live process may write rows mid-run.` + : `${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}`); + } + if (occupancy.status === 'unknown' && !json) { + printWarning(`Could not check whether the database is in use — ${occupancy.detail}`); + } + + // The `os migrate` family's gate, before the boot: a run that did not give + // its confirmation reads nothing, deletes nothing and exits 1, naming `--yes`; + // an operator who declines at the prompt made a choice, and exits 0. + if (apply && !flags.yes) { + if (json) { await emitJson({ error: 'confirmation_required', hint: 'pass --yes' }, 1, { compact: true }); return; } + if (!process.stdin.isTTY) { + printWarning('Apply mode deletes rows. Re-run with --yes to confirm, or run without --apply to preview.'); + this.exit(1); + return; + } + const ok = await confirm(chalk.bold( + `\nDelete every sys_user_preference row keyed ui.list.* after writing the export to ${exportPath}? [y/N] `, + )); + if (!ok) { + printInfo('Aborted — nothing was read, written or deleted.'); + return; + } + } + + if (!json) printStep(apply ? 'Booting (APPLY mode)…' : 'Booting (dry run)…'); + + // Loaded at the point of use, never at module load: oclif `import()`s every + // command module on every invocation while building its table. + const { LIST_PREFERENCE_OBJECT, buildListPreferenceExport, exportedIds, planListPreferenceSweep, readListPreferenceRows } = + await import('../../utils/list-preference-sweep.js'); + const { createIdentityObjectsPlugin } = await import('@objectstack/plugin-auth'); + + let stack; + try { + stack = await bootSchemaStack({ + jsonOutput: json, + databaseUrl: flags['database-url'], + // `sys_user_preference` is an identity object: registered for its + // declaration only — no auth manager, no hook, nothing started. + extraPlugins: [composeProviderForDeclarations(createIdentityObjectsPlugin())], + // The dry run boots READ-ONLY, the boot `os migrate plan` takes. + // `--apply` keeps the plain boot: it deletes rows. + ...(apply ? {} : { deferSchemaDdl: true, readOnlyProbe: true }), + }); + } catch (error) { + const message = messageOf(error); + if (json) { await emitJson({ error: 'boot_failed', message, ...errorCodeFields(error) }, 1, { compact: true }); return; } + printError(message); + this.exit(1); + return; + } + + try { + // Either mode's connect may have switched a SQLite file's journal mode, + // which rewrites its header and no row, so no line below says nothing changed. + const journalNote = describeDriverSqliteFile(stack.driver?.config) !== undefined + ? ` ${JOURNAL_MODE_SWITCH_NOTE}` + : ''; + const engine = stack.kernel.getService('objectql') as ListPreferenceEngine | undefined; + const driver = engine?.getDriverForObject(LIST_PREFERENCE_OBJECT); + if (!engine || !driver) { + const message = `No ObjectQL engine or driver serves ${LIST_PREFERENCE_OBJECT} on this runtime, so no row can be read.`; + if (json) { await emitJson({ error: 'no_engine', message }, 1, { compact: true }); return; } + printError(message); + this.exit(1); + return; + } + + // A table the read-only boot measured absent stores nothing, so it is not read. + const reads = absentTableReads(stack, (object) => engine.getConfigs()[object]); + const readFamily = (): Promise[]> => + reads.rows(LIST_PREFERENCE_OBJECT, () => readListPreferenceRows(driver)); + const rows = await readFamily(); + const plan = planListPreferenceSweep(rows); + reads.notice(json); + + if (!apply) { + if (json) { await emitJson({ mode: 'report', database: stack.dbLabel, plan }, 0, { compact: true }); return; } + printInfo(`Database: ${chalk.white(stack.dbLabel)}`); + renderPlan(plan); + printInfo(`Dry run only — no row or table was written or deleted.${journalNote} (${timer.display()})`); + if (plan.counts.rows > 0) printInfo('Re-run with --apply --export to delete the listed rows.'); + return; + } + + if (rows.length === 0) { + if (json) { await emitJson({ mode: 'apply', database: stack.dbLabel, plan, deleted: 0, failed: [], remaining: 0 }, 0, { compact: true }); return; } + renderPlan(plan); + printSuccess('Nothing to delete — no export was written.'); + return; + } + + if (!json) { + renderPlan(plan); + printWarning( + `Deleting ${rows.length} ${LIST_PREFERENCE_OBJECT} row(s). The export below is the only copy that survives.`, + ); + } + + // ── The export, written and READ BACK before anything is deleted ────── + const ids = rows.map((row) => String(row.id)); + let verified: Set; + try { + const doc = buildListPreferenceExport({ rows, producedBy: `${this.config.bin} migrate list-preferences --apply` }); + // Owner-only, and CREATED here or not written at all: the existence check + // above runs before the boot and the prompt, so it is a pre-check, never + // the guarantee. `wx` makes the guarantee atomic. Then read back rather + // than trusting the write: a short or unreadable file would leave the + // delete with no copy at all, and look like a clean run. + writeFileSync(exportPath!, `${JSON.stringify(doc, null, 2)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' }); + verified = exportedIds(JSON.parse(readFileSync(exportPath!, 'utf8')) as ListPreferenceExport); + } catch (error) { + const message = + `Refusing to delete: the pre-delete export could not be written and read back at ${exportPath} — ${messageOf(error)}`; + if (json) { await emitJson({ error: 'export_failed', message }, 1, { compact: true }); return; } + printError(message); + this.exit(1); + return; + } + const missing = ids.filter((id) => !verified.has(id)); + if (missing.length > 0) { + const message = + `Refusing to delete: the export at ${exportPath} does not hold ${missing.length} of the ${ids.length} ` + + 'row(s) to be deleted.'; + if (json) { await emitJson({ error: 'export_incomplete', message, missing }, 1, { compact: true }); return; } + printError(message); + this.exit(1); + return; + } + if (!json) printSuccess(`Pre-delete export written (owner-only): ${exportPath}`); + + // ── Only the exported rows, each by id, as the system ───────────────── + const refusals = new Map(); + for (const id of ids) { + try { + await engine.delete(LIST_PREFERENCE_OBJECT, { where: { id }, context: { isSystem: true } }); + } catch (error) { + refusals.set(id, error); + } + } + + // Judged by what is gone, never by what a delete returned. + const left = await readFamily(); + const leftIds = new Set(left.map((row) => String(row.id))); + const failed = ids + .filter((id) => leftIds.has(id)) + .map((id) => { + const refusal = refusals.get(id); + return { + id, + message: refusal ? messageOf(refusal) : 'the delete returned, but the row is still stored', + ...(refusal ? errorCodeFields(refusal) : {}), + }; + }); + const deleted = ids.length - failed.length; + const unlisted = left.length - failed.length; + + if (json) { + await emitJson( + { mode: 'apply', database: stack.dbLabel, export: exportPath, plan, deleted, failed, remaining: left.length }, + left.length > 0 ? 1 : 0, + { compact: true }, + ); + return; + } + printSuccess(`Deleted ${deleted} ${LIST_PREFERENCE_OBJECT} row(s) in ${timer.display()}.`); + for (const f of failed) printError(` ${f.id}: ${f.message}`); + if (unlisted > 0) { + printError( + ` ${unlisted} row(s) of the family appeared after the export was written (a Console that still writes ` + + 'them is running?). They were not deleted; re-run with a new --export path.', + ); + } + printInfo(`Keep ${exportPath} until you are certain the sweep was correct — it is the only copy.`); + if (left.length > 0) this.exit(1); + } catch (error) { + // A read the run could not make is a refusal, and under `--json` a + // refusal is still one JSON document. + if (isExitSignal(error)) throw error; + const message = messageOf(error); + if (json) { await emitJson({ error: 'scan_failed', message, ...errorCodeFields(error) }, 1, { compact: true }); return; } + printError(message); + this.exit(1); + } finally { + await stack.shutdown(); + } + } +} + +/** The engine slice this command reads, and the one write verb it uses. */ +type ListPreferenceEngine = Pick; + +function messageOf(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +async function confirm(question: string): Promise { + if (!process.stdin.isTTY) return false; // non-interactive → require --yes + const rl = createInterface({ input: process.stdin, output: process.stdout }); + try { + const answer: string = await new Promise((resolve) => rl.question(question, resolve)); + return /^y(es)?$/i.test(answer.trim()); + } finally { + rl.close(); + } +} + +/** Render the plan for a human: counts only, never a value. */ +function renderPlan(plan: ListPreferencePlan): void { + console.log(chalk.bold(`\n ${plan.object} rows keyed ${plan.prefix}`)); + printInfo( + `${plan.counts.rows} row(s) · ${plan.counts.users} reader(s) · ${plan.counts.organizations} organization(s)`, + ); + for (const entry of plan.byKey) { + console.log(` ${chalk.white(entry.key)}: ${entry.rows} row(s), ${entry.users} reader(s)`); + } + console.log(''); +} diff --git a/packages/cli/src/utils/list-preference-sweep.ts b/packages/cli/src/utils/list-preference-sweep.ts new file mode 100644 index 00000000000..fccc0db431d --- /dev/null +++ b/packages/cli/src/utils/list-preference-sweep.ts @@ -0,0 +1,142 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The plan behind `os migrate list-preferences`: the `sys_user_preference` + * rows an earlier Console kept a reader's list state in, one per object, keyed + * `ui.list.` (#35955). + * + * The Console stopped reading and writing that key family when the column + * widths, the row height and the view-tab order moved into the reader's + * browser (the sorts, filters and columns it also held had become a list's + * unsaved draft before that). The maintainer ruled that the stored rows are + * not migrated anywhere: they are cleared («清掉»), by an upgrade command, and + * this module is that command's reading of them. + * + * ## The family, and nothing beside it + * + * A row belongs to the family when its key STARTS WITH `ui.list.`, the dot + * included ({@link isListPreferenceKey}), compared byte for byte. Measured on + * the Console that wrote the family (`ListPreferencesProvider`, removed by the + * change that retired it): every key it wrote was that prefix plus an object + * name, and no other preference key the platform writes starts with it — + * `ui.record.`, `ui.recent`, `ui.favorites`, `ui.app.last` and + * `ui.flow.palette.recents` are other families and are never touched. + * + * The read asks the driver for the prefix with `$startsWith`, whose contract + * is a case-sensitive, escaped prefix match on every driver (the SQL driver's + * `textMatchPredicate` without folding). So the driver's answer IS the family: + * `ui.listx.account`, the bare `ui.list` and `UI.LIST.account` are not in it + * (`commands/migrate/list-preferences.integration.test.ts` seeds all three + * and holds them stored after an `--apply`). No second filter restates it here. + * + * Read-only by construction: nothing here holds a write verb. + */ + +/** The key prefix of the retired family; an object's row was `ui.list.`. */ +export const LIST_PREFERENCE_PREFIX = 'ui.list.'; + +/** The object the family is stored in. */ +export const LIST_PREFERENCE_OBJECT = 'sys_user_preference'; + +/** Does this key belong to the retired family? Byte-exact, the trailing dot included: the export's read-back judges with it. */ +export function isListPreferenceKey(key: unknown): key is string { + return typeof key === 'string' && key.startsWith(LIST_PREFERENCE_PREFIX); +} + +/** The read port the plan needs: a driver's `find`. */ +export interface ListPreferenceReader { + find(object: string, query: Record): Promise[]>; +} + +/** + * Every stored row of the family, read from the driver and UNSCOPED: every + * organization and every user. A filter in front of this read subtracts rows, + * and a row missing from it is a row the report never mentions. + */ +export async function readListPreferenceRows(reader: ListPreferenceReader): Promise[]> { + return reader.find(LIST_PREFERENCE_OBJECT, { + where: { key: { $startsWith: LIST_PREFERENCE_PREFIX } }, + }); +} + +/** One key of the family and how many rows and readers hold it. */ +export interface ListPreferenceKeyCount { + key: string; + rows: number; + users: number; +} + +/** What the family holds on this database: counts only, never a value. */ +export interface ListPreferencePlan { + object: typeof LIST_PREFERENCE_OBJECT; + prefix: typeof LIST_PREFERENCE_PREFIX; + counts: { rows: number; users: number; organizations: number }; + /** Per key, sorted by key. */ + byKey: ListPreferenceKeyCount[]; +} + +/** Count what the rows hold, per key and in total. */ +export function planListPreferenceSweep(rows: readonly Record[]): ListPreferencePlan { + const users = new Set(); + const organizations = new Set(); + const perKey = new Map }>(); + for (const row of rows) { + const key = String(row.key); + const user = String(row.user_id ?? ''); + users.add(user); + organizations.add(String(row.organization_id ?? '')); + const entry = perKey.get(key) ?? { rows: 0, users: new Set() }; + entry.rows += 1; + entry.users.add(user); + perKey.set(key, entry); + } + return { + object: LIST_PREFERENCE_OBJECT, + prefix: LIST_PREFERENCE_PREFIX, + counts: { rows: rows.length, users: users.size, organizations: organizations.size }, + byKey: [...perKey.entries()] + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([key, entry]) => ({ key, rows: entry.rows, users: entry.users.size })), + }; +} + +/** The pre-delete export: every row the run deletes, as the driver stored it. */ +export interface ListPreferenceExport { + format: 'objectstack.list-preferences.pre-delete-export.v1'; + generatedAt: string; + producedBy: string; + object: typeof LIST_PREFERENCE_OBJECT; + prefix: typeof LIST_PREFERENCE_PREFIX; + warning: string; + rows: Record[]; +} + +export function buildListPreferenceExport(input: { + rows: readonly Record[]; + producedBy: string; + now?: () => Date; +}): ListPreferenceExport { + return { + format: 'objectstack.list-preferences.pre-delete-export.v1', + generatedAt: (input.now?.() ?? new Date()).toISOString(), + producedBy: input.producedBy, + object: LIST_PREFERENCE_OBJECT, + prefix: LIST_PREFERENCE_PREFIX, + warning: + 'This file holds every sys_user_preference row the run deleted, as stored: each reader\'s list state, which ' + + 'can include filter values. Nothing reads it back into the platform. Protect it as you protect a database ' + + 'backup, and delete it once you are certain the sweep was correct.', + rows: [...input.rows], + }; +} + +/** The ids a read-back export holds — the check made before the first delete. */ +export function exportedIds(doc: Partial | null | undefined): Set { + const ids = new Set(); + for (const row of doc?.rows ?? []) { + if (row && typeof row === 'object' && row.id !== undefined && row.id !== null && isListPreferenceKey(row.key)) { + ids.add(String(row.id)); + } + } + return ids; +} diff --git a/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts b/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts index d8538606d64..3906676160a 100644 --- a/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts +++ b/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts @@ -87,6 +87,7 @@ import MigrateTextScalars from '../commands/migrate/text-scalars.js'; import MigrateCommentReactions from '../commands/migrate/comment-reactions.js'; import MigrateDuplicates from '../commands/migrate/duplicates.js'; import MigrateFilesToReferences from '../commands/migrate/files-to-references.js'; +import MigrateListPreferences from '../commands/migrate/list-preferences.js'; import MigrateMeta from '../commands/migrate/meta.js'; import MigrateMultiValueColumns from '../commands/migrate/multi-value-columns.js'; import MigrateOrganizationOwnership from '../commands/migrate/organization-ownership.js'; @@ -288,6 +289,13 @@ const CALLERS: Record = { noWrite: [{ label: 'migrate files-to-references', argv: ['--database-url', '@DB@', '--json'] }], write: [{ label: 'migrate files-to-references --apply', argv: ['--apply', '--yes', '--database-url', '@DB@', '--json'] }], }, + 'commands/migrate/list-preferences.ts': { + run: invoke(MigrateListPreferences), + noWrite: [{ label: 'migrate list-preferences', argv: ['--database-url', '@DB@', '--json'] }], + // The fixture holds no `ui.list.*` row, so the run deletes nothing and writes + // no export: the plain boot a delete takes is what this case is about. + write: [{ label: 'migrate list-preferences --apply', argv: ['--apply', '--export', '@DIR@/list-preferences-export.json', '--yes', '--database-url', '@DB@', '--json'] }], + }, 'commands/migrate/meta.ts': { run: invoke(MigrateMeta), // Without `--stored` the command converts source files and boots nothing. diff --git a/packages/cli/test/migrate-confirmation-exit.pin.test.ts b/packages/cli/test/migrate-confirmation-exit.pin.test.ts index 88d0d1e36a1..7cac8487033 100644 --- a/packages/cli/test/migrate-confirmation-exit.pin.test.ts +++ b/packages/cli/test/migrate-confirmation-exit.pin.test.ts @@ -262,6 +262,8 @@ const ROSTER: Record = { 'comment-parent-pair': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, 'comment-reactions': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, 'files-to-references': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, + // `--apply` deletes only with its pre-delete export named; the gate sits before the boot. + 'list-preferences': { argv: ['--apply', '--export', join(SCRATCH, 'list-preferences-export.json')], confirm: '--yes', writes: BOOT }, // `--yes` belongs to the stored-row pass; without `--stored` the command converts source files. meta: { argv: ['--stored', '--apply'], confirm: '--yes', writes: BOOT }, 'multi-value-columns': { argv: ['--apply'], confirm: '--yes', writes: BOOT },