From 0c23193abcb918dbef3bfd9039f29e95b14fbd74 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 01:50:25 +0000 Subject: [PATCH 1/2] test(cli, plugin-audit): pin the os migrate audit-side-copies door and the rewrite's amendment name before the code The archive integration suite drives the command over the hot tables and an archive datasource (dry run, --object, apply, re-run, refusal); the family rosters gain the new member; the live redaction suite pins the name a sealed row's amendment records. Docs and the changeset say how to run it. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .changeset/33155-audit-side-copies-door.md | 23 ++ content/docs/deployment/cli.mdx | 44 +- content/docs/upgrading.mdx | 2 + .../audit-redaction-seal.contract.test.ts | 3 +- ...it-side-copies.archive.integration.test.ts | 381 ++++++++++++++++++ ...mmands.absent-database.integration.test.ts | 31 ++ ...igrate.one-shot-family.integration.test.ts | 6 + .../cli/test/json-stdout-purity.e2e.test.ts | 3 + .../migrate-confirmation-exit.pin.test.ts | 1 + ...it-seal-redaction-live.integration.test.ts | 16 +- 10 files changed, 502 insertions(+), 8 deletions(-) create mode 100644 .changeset/33155-audit-side-copies-door.md create mode 100644 packages/cli/src/commands/migrate/audit-side-copies.archive.integration.test.ts diff --git a/.changeset/33155-audit-side-copies-door.md b/.changeset/33155-audit-side-copies-door.md new file mode 100644 index 00000000000..ddd4dc99946 --- /dev/null +++ b/.changeset/33155-audit-side-copies-door.md @@ -0,0 +1,23 @@ +--- +'@objectstack/cli': patch +'@objectstack/plugin-audit': patch +--- + +feat(cli): `os migrate audit-side-copies` runs the at-rest side-copy rewrite on the live audit tables and the archive + +Clause-②: yes (widening) +Metadata-protocol: none + +**Run `os migrate audit-side-copies` once after upgrading from 18.4.0 or earlier, a dry run first:** + +```bash +os migrate audit-side-copies # dry run: counts per table and store, writes no row +os migrate audit-side-copies --object sys_audit_log # only one copy table (repeatable) +os migrate audit-side-copies --apply # remove the columns (prompts; --yes skips the prompt) +os migrate audit-side-copies --apply --yes --json # CI / scripts +``` + +The audit writer no longer copies a side-copy column (another record's field values, today an approval request's `payload_json`) into `sys_audit_log` (`new_value`, `old_value`) or `sys_activity` (both halves of `metadata`). Copies written before that still carry it. Until they are rewritten, the read-time redaction drops the column and the query guard treats a query naming it as reaching every object, so the command is cleanup, not a gate. + +- **The command.** It drives `@objectstack/plugin-audit`'s `migrateSideCopies` (the live `sys_audit_log` and `sys_activity` rows) and `migrateArchivedSideCopies` (the archive datasource `sys_audit_log` archives to). It is a dry run by default and writes only with `--apply`. Its flags are `os migrate audit-key-material`'s (`--database-url`, `--apply`, `--yes`, `--force`, `--json`) plus `--object`, which takes `sys_audit_log` or `sys_activity` and narrows the run, hot and archive, to the tables it names. Any other name is refused with `OBJECT_NOT_FOUND`, exit 1, before anything is read. The report gives, per copy table, the copies read and the copies rewritten (or to rewrite), for the hot tables and for the archive each, and never prints a value. It is idempotent: a second `--apply` rewrites nothing. A failed read or write, a sealed row it had to refuse, or an archive it could not reach exits 1, as for its twins. +- **The rewrite's name (`@objectstack/plugin-audit`).** A sealed row the rewrite amends (ADR-0154 D7) now records `rewritten_by: 'os migrate audit-side-copies'`, the command that rewrote it, as `audit-mail-bodies`, `audit-key-material` and `audit-metadata-bodies` record theirs. It recorded `side-copy-migration` before; a row amended under that name keeps it. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index a1cbb3b6c42..83f4b42836b 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1482,6 +1482,7 @@ where the data lives. | `os migrate activity-changed-fields` | Stamp the two read-rule columns (`changed_fields`, `milestone_key`) on the `sys_activity` rows written before they existed. Until it runs, those rows are withheld from every reader but the system, so run it at once after upgrading. No flag; idempotent | | `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 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 | @@ -1502,7 +1503,7 @@ holds nothing, and answers with empty work and exit 0. `os migrate value-shapes` clean over zero records and names the objects it did not read. `os migrate recorded-by` has nothing to convert and `os migrate resume` no interrupted runs. `os migrate meta --stored` has no stored metadata to examine, `os migrate -audit-metadata-bodies`, `os migrate audit-mail-bodies` and `os migrate audit-key-material` no audit copy to rewrite, and +audit-metadata-bodies`, `os migrate audit-mail-bodies`, `os migrate audit-key-material` and `os migrate audit-side-copies` no audit copy to rewrite, and `os migrate account-issuer` no account to collide. `os secret orphans`, `os secret rewrap` and `os storage orphans` report no secret and no file. A read the command cannot avoid and that fails for any other reason still refuses and exits 1. Point `--database-url` at the deployment's @@ -2114,10 +2115,47 @@ carries the same `archive` entries with the same `status` values and exit codes. A declared archive this boot does not connect, or an active runtime datasource row of that name, reads `not-connected` and exits `1`. +#### `os migrate audit-side-copies` + +Some columns hold another record's field values, which that record's own row +serves only through its owner's per-reader narrowing: today the approval +request's `payload_json`, its snapshot of the record under approval. An audit +copy (`sys_audit_log.new_value` / `old_value`, both halves of +`sys_activity.metadata`) cannot be narrowed that way, so new copies omit those +columns. This command removes them from the copies written before that. + +```bash +os migrate audit-side-copies # Dry run: counts, writes no rows +os migrate audit-side-copies --object sys_audit_log # Only one copy table (repeatable) +os migrate audit-side-copies --apply # Remove the columns (prompts) +os migrate audit-side-copies --apply --yes --json # CI / scripts +``` + +The report gives, per copy table, the copies it read and the copies it +rewrote (or, in a dry run, would rewrite), for the hot tables and for the +archive datasource each. Only the listed keys of a copy are removed: every +other key, and every other column of the row (its `updated_at` included), +stays as it was. A column of the same name in a copy of any other object is +left alone. The report holds counts only and never prints a value. + +The flags are `os migrate audit-key-material`'s, one for one, plus +`--object`, which takes `sys_audit_log` or `sys_activity` and narrows the run, +hot and archive, to the tables it names. Any other name is refused with +`OBJECT_NOT_FOUND`, exit `1`, before anything is read. + +**Idempotent**: a copy without the columns has nothing to remove, so a second +run rewrites nothing, and re-running is how an interrupted run is finished. A +failed read or write exits `1`. Run it once after upgrading, with the server +stopped. Until it has run, the served copies are still safe: the read-time +redaction drops the columns and the query guard treats a query naming one as +reaching every object. **The archive datasource** is covered exactly as for +[`os migrate audit-mail-bodies`](#os-migrate-audit-mail-bodies), with the same +`archive` entries, `status` values and exit codes. + #### Sealed audit rows (`os migrate audit-*`) -`os migrate audit-metadata-bodies`, `os migrate audit-mail-bodies` and -`os migrate audit-key-material` rewrite value columns of ledger rows, which an +`os migrate audit-metadata-bodies`, `os migrate audit-mail-bodies`, +`os migrate audit-key-material` and `os migrate audit-side-copies` rewrite value columns of ledger rows, which an object can seal (`lifecycle.seal`, ADR-0154). Before a row that a checkpoint seals is rewritten, the command writes a signed **redaction amendment** (`sys_audit_amendment`): the checkpoint, the row and column, the commitment the diff --git a/content/docs/upgrading.mdx b/content/docs/upgrading.mdx index c169ace1403..5f2330af4ac 100644 --- a/content/docs/upgrading.mdx +++ b/content/docs/upgrading.mdx @@ -487,6 +487,8 @@ the protocol-18 step, which `os migrate meta --from 17` lists for your sources **Upgrading from 18.2.0 or earlier:** run [`os migrate audit-key-material`](/docs/deployment/cli#os-migrate-audit-key-material) once, a dry run first and then `--apply`; it removes the encrypted key-material columns from the audit-ledger copies those releases wrote. +**Upgrading from 18.4.0 or earlier:** run [`os migrate audit-side-copies`](/docs/deployment/cli#os-migrate-audit-side-copies) once, a dry run first and then `--apply`; it removes the side-copy columns (an approval request's `payload_json`) from the audit-ledger copies those releases wrote. Served copies are redacted at read time until it runs, 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/audit-redaction-seal.contract.test.ts b/packages/cli/src/commands/migrate/audit-redaction-seal.contract.test.ts index c5c0c6e9642..52f33f6bb9b 100644 --- a/packages/cli/src/commands/migrate/audit-redaction-seal.contract.test.ts +++ b/packages/cli/src/commands/migrate/audit-redaction-seal.contract.test.ts @@ -1,6 +1,6 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // -// [ADR-0154 D7] The three `os migrate audit-*` ledger-copy rewrites compose the +// [ADR-0154 D7] The four `os migrate audit-*` ledger-copy rewrites compose the // crypto `os serve` seals with (`composeRedactionSeal`) and hand its `seal` to // every run, hot and archive, so a sealed row is amended before it is rewritten // or refused; and a run that refused one exits non-zero. What the `seal` does is @@ -22,6 +22,7 @@ const HERE = path.dirname(fileURLToPath(import.meta.url)); const COMMANDS: Record = { 'audit-mail-bodies.ts': ['migrateMailLogBodyCopies', 'migrateArchivedMailLogBodyCopies'], 'audit-key-material.ts': ['migrateKeyMaterialCopies', 'migrateArchivedKeyMaterialCopies'], + 'audit-side-copies.ts': ['migrateSideCopies', 'migrateArchivedSideCopies'], 'audit-metadata-bodies.ts': ['migrateStoredMetadataBodyCopies'], }; diff --git a/packages/cli/src/commands/migrate/audit-side-copies.archive.integration.test.ts b/packages/cli/src/commands/migrate/audit-side-copies.archive.integration.test.ts new file mode 100644 index 00000000000..9d1a434b283 --- /dev/null +++ b/packages/cli/src/commands/migrate/audit-side-copies.archive.integration.test.ts @@ -0,0 +1,381 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// test-budget: 90 — spawns the real producer once per single-cause fixture: two served-shape boots that run the real Archiver, and six spawns of the source CLI (a misspelled --object refused before the boot; the human dry run; the JSON dry run; an --apply narrowed to sys_activity; --apply; a re-run), the budget of its twin audit-key-material.archive, re-measure on CI + +/** + * [#33155] `os migrate audit-side-copies` is the operator door for + * `@objectstack/plugin-audit`'s at-rest side-copy rewrite (#32442): it removes + * the columns `side-copy-columns.ts` lists (today `sys_approval_request`'s + * `payload_json`) from the ledger copies written before the writer omitted + * them, on the hot tables (`migrateSideCopies`) and in the archive datasource + * `sys_audit_log` archives to (`migrateArchivedSideCopies`). The fixture and + * the cases are `audit-key-material.archive.integration.test.ts`'s, over this + * rewrite's list, plus the `--object` scope. The archive classification the + * twins share (`../../utils/ledger-copy-archive.ts`: none, not-connected, + * unknown) is pinned there and not repeated here. + * + * ## The fixture + * + * A project declaring an `archive` SQLite datasource with `autoConnect: true`, + * and a served-shape boot that seeds older-writer copies still carrying the + * column (two approval-request copies past the hot window, one inside it, and + * a row of an object the list does not name that happens to carry a column of + * the same name, past it), then runs the REAL Archiver (`lifecycle.sweep()`). + * + * ## What is pinned + * + * 0. The Archiver moved the old copies to the archive still carrying the + * column (a vacuous fixture is no pin), and left the young one hot. + * 1. The dry run reports, per copy table, the copies read and the copies to + * rewrite for the hot tables and for the archive, and writes nothing to + * either store; the human face prints the same counts per table and store. + * 2. `--object sys_activity --apply` reads and writes only that table: no + * `sys_audit_log` copy is read or rewritten in either store. + * 3. `--apply` leaves 0 copies carrying the column in either store and + * reports the counts it wrote; every other key of a rewritten copy, every + * other column, and the unlisted object's row are untouched. + * 4. A second `--apply` rewrites nothing and changes no archived row. + * 5. The copy that was hot when the command ran, aged past the window and + * archived by a second sweep, lands in the archive without the column. + * 6. An `--object` that is not a copy table is refused before anything is + * read, exit 1, `OBJECT_NOT_FOUND`. + * 7. No run prints a sentinel. + * + * ⛔ The column values are sentinels, and every comparison is reported as a + * count or a boolean. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { spawn, spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { isDeepStrictEqual } from 'node:util'; +import Database from 'better-sqlite3'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI_ROOT = resolve(HERE, '..', '..', '..'); +/** The source entry, as `test/helpers/serve-process.ts` spawns it; `src/` cannot import that helper. */ +const CLI = resolve(HERE, '../../../bin/run-dev.js'); + +const HOOK_TIMEOUT_MS = 480_000; +const RUN_BUDGET_MS = 120_000; +const SENTINEL = 'side-copy-sentinel-33155'; +/** The same-named column on an object the list does not name: recorded as before. */ +const OTHER = 'other-object-column-33155'; + +/** Env that would point a boot somewhere other than the fixture. */ +const OVERRIDING_ENV = ['OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME'] as const; + +/** + * This process's environment for a child, minus the families + * `test/helpers/serve-process.ts` `childEnv()` strips (its header says why). + */ +function childEnv(overrides: Record): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(process.env)) { + if (key === 'TEST' || key === 'VITEST' || key.startsWith('VITEST_') || key === 'NODE_PATH') continue; + env[key] = value; + } + const unset: Record = {}; + for (const key of OVERRIDING_ENV) unset[key] = undefined; + return { + ...env, + ...unset, + // The fixed key `serve-process.ts` hands its children, so no boot mints and + // persists a crypto key into this runner's home directory. + OS_SECRET_KEY: '0e2e'.repeat(16), + // [#22579] One database for the hot objects: the fixture declares its own topology. + OS_TELEMETRY_DB: '0', + NO_COLOR: '1', + ...overrides, + }; +} + +/** + * A served-shape boot of the data stack plus the audit plugin, with the + * fixture's `archive` datasource. `MODE=seed` plants the older-writer copies; + * `MODE=age` moves every hot copy's `created_at` past the window. Either way + * the boot then runs the real Archiver once. + */ +const SWEEP_CHILD = ` +const rt = await import('@objectstack/runtime'); +const { PlatformObjectsPlugin } = await import('@objectstack/platform-objects/plugin'); +const { AuditPlugin } = await import('@objectstack/plugin-audit'); +const { SqlDriver } = await import('@objectstack/driver-sql'); +const stack = await rt.createStandaloneStack({ + projectRoot: process.env.FIXTURE_PROJECT, + databaseUrl: 'file:' + process.env.FIXTURE_DB, + skipSeedData: true, + // Armed, so the service is enabled: the sweep below is the one this child + // runs itself, long before the schedule's first (unref'ed) tick. +}); +const runtime = new rt.Runtime({ cluster: false }); +const kernel = runtime.getKernel(); +for (const plugin of stack.plugins) await kernel.use(plugin); +await kernel.use(new PlatformObjectsPlugin()); +await kernel.use(new AuditPlugin()); +await runtime.start(); +const ql = kernel.getService('objectql'); +let source = 'declared'; +if (!ql.getDriverByName('archive')) { + // The host registers the archive driver under the datasource's name, as + // the datasource-connection service does for a connected declaration. + const cold = new SqlDriver({ client: 'better-sqlite3', connection: { filename: process.env.FIXTURE_ARCHIVE }, useNullAsDefault: true }); + Object.defineProperty(cold, 'name', { value: 'archive' }); + await cold.connect(); + ql.registerDriver(cold); + source = 'host-registered'; +} +const k = ql.getDriverForObject('sys_audit_log').knex; +const old = new Date(Date.now() - 200 * 86400000).toISOString(); +if (process.env.MODE === 'seed') { + const v = process.env.SENTINEL; + await k('sys_audit_log').insert([ + { id: 'aud_old_1', object_name: 'sys_approval_request', record_id: 'ar_1', action: 'create', created_at: old, updated_at: old, new_value: JSON.stringify({ id: 'ar_1', status: 'kept', process_name: 'kept', payload_json: v }) }, + { id: 'aud_old_2', object_name: 'sys_approval_request', record_id: 'ar_2', action: 'delete', created_at: old, updated_at: old, old_value: JSON.stringify({ id: 'ar_2', status: 'kept', payload_json: v }) }, + { id: 'aud_old_3', object_name: 'crm_note', record_id: 'n_1', action: 'create', created_at: old, updated_at: old, new_value: JSON.stringify({ id: 'n_1', title: 'kept', payload_json: process.env.OTHER }) }, + { id: 'aud_young', object_name: 'sys_approval_request', record_id: 'ar_3', action: 'update', created_at: new Date().toISOString(), new_value: JSON.stringify({ id: 'ar_3', status: 'kept', payload_json: v }) }, + ]); +} else { + await k('sys_audit_log').update({ created_at: old }); +} +const report = await kernel.getService('lifecycle').sweep(); +const entry = report.swept.find((s) => s.object === 'sys_audit_log'); +await kernel.shutdown(); +process.stderr.write('[fixture] swept ' + JSON.stringify({ source, archived: entry ? entry.archived : null }) + '\\n'); +process.exit(0); +`; + +interface Run { + code: number | null; + stdout: string; + stderr: string; +} + +let dir: string; +let mainDb: string; +let archiveDb: string; +let seedDetail: { source: string; archived: number | null }; +let ageDetail: { source: string; archived: number | null }; +const runs: Record<'refused' | 'human' | 'dry' | 'scoped' | 'apply' | 'again', Run> = {} as never; +let archivedBefore: Record[]; +let hotBefore: Record[]; +let archivedAfterDry: Record[]; +let hotAfterDry: Record[]; +let archivedAfterScoped: Record[]; +let hotAfterScoped: Record[]; +let archivedAfterApply: Record[]; +let hotAfterApply: Record[]; +let archivedAfterAgain: Record[]; +let archivedAfterAging: Record[]; + +function sweep(mode: 'seed' | 'age'): { source: string; archived: number | null } { + const r = spawnSync(process.execPath, ['--input-type=module', '-e', SWEEP_CHILD], { + cwd: CLI_ROOT, + env: childEnv({ + OS_ARTIFACT_PATH: join(dir, 'dist', 'objectstack.json'), + FIXTURE_PROJECT: dir, + FIXTURE_DB: mainDb, + FIXTURE_ARCHIVE: archiveDb, + SENTINEL, + OTHER, + MODE: mode, + }), + encoding: 'utf8', + timeout: RUN_BUDGET_MS, + }); + const line = String(r.stderr).split('\n').find((l) => l.startsWith('[fixture] swept ')); + if (r.status !== 0 || !line) throw new Error(`the ${mode} sweep did not run (status ${r.status})\n${String(r.stderr).slice(-3000)}`); + return JSON.parse(line.slice('[fixture] swept '.length)); +} + +/** One `os migrate audit-side-copies --database-url file:` run, in `project`. */ +function runCommand(project: string, db: string, extra: string[]): Promise { + return new Promise((resolveRun, rejectRun) => { + const child = spawn( + process.execPath, + [CLI, 'migrate', 'audit-side-copies', ...extra, '--database-url', `file:${db}`], + { cwd: project, env: childEnv({ OS_ARTIFACT_PATH: join(project, 'dist', 'objectstack.json') }), stdio: ['ignore', 'pipe', 'pipe'] }, + ); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (c) => { stdout += String(c); }); + child.stderr.on('data', (c) => { stderr += String(c); }); + const timer = setTimeout(() => { + child.kill('SIGKILL'); + rejectRun(new Error(`os migrate audit-side-copies did not finish within ${RUN_BUDGET_MS}ms`)); + }, RUN_BUDGET_MS); + child.on('error', (err) => { clearTimeout(timer); rejectRun(err); }); + child.on('close', (code) => { clearTimeout(timer); resolveRun({ code, stdout, stderr }); }); + }); +} + +/** Every `sys_audit_log` row of one database file, read with a connection of our own. */ +function auditRows(file: string): Record[] { + const db = new Database(file, { readonly: true }); + try { + return db.prepare('SELECT * FROM sys_audit_log ORDER BY id').all() as Record[]; + } finally { + db.close(); + } +} + +/** Rows that still carry a listed column. */ +const clear = (rows: Record[]): number => rows.filter((r) => JSON.stringify(r).includes(SENTINEL)).length; + +function writeArtifact(project: string, datasources: unknown[]): void { + mkdirSync(join(project, 'dist'), { recursive: true }); + writeFileSync( + join(project, 'dist', 'objectstack.json'), + JSON.stringify({ + manifest: { id: 'com.example.os33155', name: 'Archived side copies', version: '0.0.0', type: 'app' }, + datasources, + objects: [{ name: 'os33155_thing', fields: { name: { type: 'text' } } }], + }), + ); +} + +beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), 'os-33155-')); + mkdirSync(join(dir, 'data'), { recursive: true }); + mainDb = join(dir, 'data', 'main.db'); + archiveDb = join(dir, 'data', 'archive.db'); + writeArtifact(dir, [{ name: 'archive', driver: 'sqlite', config: { filename: archiveDb }, autoConnect: true }]); + + seedDetail = sweep('seed'); + archivedBefore = auditRows(archiveDb); + hotBefore = auditRows(mainDb); + + runs.refused = await runCommand(dir, mainDb, ['--object', 'sys_approval_request', '--apply', '--yes', '--json']); + runs.human = await runCommand(dir, mainDb, []); + runs.dry = await runCommand(dir, mainDb, ['--json']); + archivedAfterDry = auditRows(archiveDb); + hotAfterDry = auditRows(mainDb); + runs.scoped = await runCommand(dir, mainDb, ['--object', 'sys_activity', '--apply', '--yes', '--json']); + archivedAfterScoped = auditRows(archiveDb); + hotAfterScoped = auditRows(mainDb); + runs.apply = await runCommand(dir, mainDb, ['--apply', '--yes', '--json']); + archivedAfterApply = auditRows(archiveDb); + hotAfterApply = auditRows(mainDb); + runs.again = await runCommand(dir, mainDb, ['--apply', '--yes', '--json']); + archivedAfterAgain = auditRows(archiveDb); + + ageDetail = sweep('age'); + archivedAfterAging = auditRows(archiveDb); +}, HOOK_TIMEOUT_MS); + +afterAll(() => { + if (dir) rmSync(dir, { recursive: true, force: true }); +}); + +const doc = (run: Run): any => JSON.parse(run.stdout); +/** Two row sets hold the same rows, column for column — a boolean, so a failure prints no row. */ +const sameRows = (a: Record[], b: Record[]): boolean => + a.length === b.length && a.every((row, i) => isDeepStrictEqual(row, b[i])); +const archiveOf = (run: Run): any => doc(run).archive.find((a: { datasource: string }) => a.datasource === 'archive'); + +describe('os migrate audit-side-copies over the hot tables and an archive datasource', () => { + it('0. the fixture: the real Archiver moved the old copies to the archive still carrying the column', () => { + expect(seedDetail.archived).toBe(3); + expect(archivedBefore.length).toBe(3); + expect(clear(archivedBefore)).toBe(2); + expect(clear(hotBefore)).toBe(1); + }); + + it('1. the dry run reports the copies read and to rewrite per table, hot and archived, and writes nothing', () => { + const run = runs.dry; + expect(run.code, run.stderr.slice(-2000)).toBe(0); + expect(doc(run)).toMatchObject({ apply: false }); + expect(doc(run).report).toMatchObject({ + apply: false, + failures: 0, + byObject: { sys_audit_log: { scanned: 1, rewritten: 1, refused: 0 }, sys_activity: { rewritten: 0 } }, + }); + expect(archiveOf(run)).toMatchObject({ + status: 'examined', + objects: ['sys_audit_log'], + report: { apply: false, failures: 0, byObject: { sys_audit_log: { scanned: 2, rewritten: 2 } } }, + }); + // Both stores, read after the dry run: neither moved. + expect(sameRows(archivedAfterDry, archivedBefore)).toBe(true); + expect(sameRows(hotAfterDry, hotBefore)).toBe(true); + expect(clear(archivedAfterDry)).toBe(2); + }); + + it('1b. the human dry run prints the same counts per table, hot and archived, and says nothing was written', () => { + const run = runs.human; + expect(run.code, run.stderr.slice(-2000)).toBe(0); + expect(run.stdout).toMatch(/sys_audit_log: 1 ledger cop\(ies\) scanned, 1 to rewrite/); + expect(run.stdout).toMatch(/sys_audit_log \(archive datasource 'archive'\): 2 ledger cop\(ies\) scanned, 2 to rewrite/); + expect(run.stdout).toMatch(/Dry run only/); + }); + + it('2. --object sys_activity --apply reads and writes only that table, in neither store sys_audit_log', () => { + const run = runs.scoped; + expect(run.code, run.stderr.slice(-2000)).toBe(0); + expect(Object.keys(doc(run).report.byObject)).toEqual(['sys_activity']); + expect(doc(run).report).toMatchObject({ apply: true, rewritten: 0, failures: 0 }); + expect(doc(run).archive).toEqual([]); + expect(sameRows(archivedAfterScoped, archivedBefore)).toBe(true); + expect(sameRows(hotAfterScoped, hotBefore)).toBe(true); + }); + + it('3. --apply leaves 0 copies carrying the column in either store, reports what it wrote, and nothing else moves', () => { + const run = runs.apply; + expect(run.code, run.stderr.slice(-2000)).toBe(0); + expect(doc(run).report).toMatchObject({ apply: true, failures: 0, byObject: { sys_audit_log: { scanned: 1, rewritten: 1 } } }); + expect(archiveOf(run).report).toMatchObject({ apply: true, rewritten: 2, failures: 0, byObject: { sys_audit_log: { scanned: 2, rewritten: 2 } } }); + expect(clear(archivedAfterApply)).toBe(0); + expect(clear(hotAfterApply)).toBe(0); + const before = new Map(archivedBefore.map((r) => [r.id, r])); + const movedColumns = archivedAfterApply.flatMap((row) => + Object.keys(before.get(row.id)!) + .filter((key) => key !== 'new_value' && key !== 'old_value') + .filter((key) => !isDeepStrictEqual(row[key], before.get(row.id)![key])) + .map((key) => `${String(row.id)}.${key}`), + ); + // Names only: an id and a column, never a value. + expect(movedColumns).toEqual([]); + // The unlisted object's row keeps its same-named column. + expect(isDeepStrictEqual(archivedAfterApply.find((r) => r.id === 'aud_old_3'), before.get('aud_old_3'))).toBe(true); + expect(JSON.stringify(archivedAfterApply.find((r) => r.id === 'aud_old_3')).includes(OTHER)).toBe(true); + // A rewritten copy loses exactly the column: every other key is kept. + const created = JSON.parse(String(archivedAfterApply.find((r) => r.id === 'aud_old_1')!.new_value)); + const deleted = JSON.parse(String(archivedAfterApply.find((r) => r.id === 'aud_old_2')!.old_value)); + const young = JSON.parse(String(hotAfterApply.find((r) => r.id === 'aud_young')!.new_value)); + expect(Object.keys(created).sort()).toEqual(['id', 'process_name', 'status']); + expect(Object.keys(deleted).sort()).toEqual(['id', 'status']); + expect(Object.keys(young).sort()).toEqual(['id', 'status']); + }); + + it('4. a second --apply rewrites nothing and changes no archived row', () => { + const run = runs.again; + expect(run.code, run.stderr.slice(-2000)).toBe(0); + expect(doc(run).report.rewritten).toBe(0); + expect(archiveOf(run).report).toMatchObject({ scanned: 2, rewritten: 0, failures: 0 }); + expect(sameRows(archivedAfterAgain, archivedAfterApply)).toBe(true); + }); + + it('5. the copy that was hot when the command ran is archived without the column', () => { + expect(ageDetail.archived).toBe(1); + expect(archivedAfterAging.length).toBe(4); + expect(archivedAfterAging.some((r) => r.id === 'aud_young')).toBe(true); + expect(clear(archivedAfterAging)).toBe(0); + }); + + it('6. an --object that is not a copy table is refused before anything is read, and nothing is written', () => { + const run = runs.refused; + expect(run.code).toBe(1); + expect(doc(run)).toMatchObject({ code: 'OBJECT_NOT_FOUND' }); + expect(doc(run).error).toMatch(/sys_activity, sys_audit_log/); + // It ran first: the dry run read both stores as the seed left them. + expect(sameRows(hotAfterDry, hotBefore)).toBe(true); + }); + + it('7. no run prints a sentinel', () => { + for (const run of Object.values(runs)) { + expect(`${run.stdout}\n${run.stderr}`.includes(SENTINEL)).toBe(false); + } + }); +}); diff --git a/packages/cli/src/commands/migrate/data-commands.absent-database.integration.test.ts b/packages/cli/src/commands/migrate/data-commands.absent-database.integration.test.ts index 0a17f64adb8..8175027f90f 100644 --- a/packages/cli/src/commands/migrate/data-commands.absent-database.integration.test.ts +++ b/packages/cli/src/commands/migrate/data-commands.absent-database.integration.test.ts @@ -82,6 +82,10 @@ * born with the answer too. Its control rows are an older writer's copies of a * secret-store row and a settings row, each carrying its key-material column, * planted below the writer. + * + * [#33155] `os migrate audit-side-copies`, the third twin, joined it born with + * the answer too. Its control rows are an older writer's copies of an approval + * request, each carrying its side-copy column, planted below the writer. */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -474,6 +478,18 @@ await k(shard.name).insert({ changed_fields: '[]', metadata: JSON.stringify({ old: null, new: { id: 'set_26687', namespace: 'os26687', key: 'k', encrypted: true, value_enc: 'key-material-sentinel-26687' } }), }); +// [#33155] An older writer's copies of an approval request, each still carrying +// its side-copy column (a sentinel). The activity row carries its read-rule +// stamp, so it is no row of work for \`activity-changed-fields\`. +await k('sys_audit_log').insert({ + id: 'aud_33155', object_name: 'sys_approval_request', record_id: 'ar_33155', action: 'create', + new_value: JSON.stringify({ id: 'ar_33155', status: 'pending', payload_json: 'side-copy-sentinel-33155' }), +}); +await k(shard.name).insert({ + organization_id: 'org_fixture', id: 'act_33155', timestamp: new Date().toISOString(), type: 'create', summary: 'created', object_name: 'sys_approval_request', record_id: 'ar_33155', + changed_fields: '[]', + metadata: JSON.stringify({ old: null, new: { id: 'ar_33155', status: 'pending', payload_json: 'side-copy-sentinel-33155' } }), +}); await k('sys_comment').insert({ organization_id: 'org_fixture', id: 'cmt_23857', thread_id: 'sys_metadata:m_21552', body: 'planted below the writer', author_id: 'u1', created_at: new Date().toISOString(), @@ -566,6 +582,21 @@ const DOORS: readonly Door[] = [ expect(doc.report).toMatchObject({ failures: 0, byObject: { sys_audit_log: { rewritten: 1 }, sys_activity: { rewritten: 1 } } }); }, }, + { + name: 'migrate audit-side-copies', + argv: ['migrate', 'audit-side-copies'], + empty: (doc) => { + expect(doc).toMatchObject({ apply: false, report: { scanned: 0, rewritten: 0, failures: 0 } }); + expect(Object.keys(doc.report.byObject).sort()).toEqual(['sys_activity', 'sys_audit_log']); + }, + humanEmpty: /Nothing to remove/, + tables: ['sys_audit_log', 'sys_activity'], + work: (doc) => { + // The seeded approval-request copy is the one row to rewrite on each table, + // the live sys_activity row included; the rotation-managed table's rows are READ. + expect(doc.report).toMatchObject({ failures: 0, byObject: { sys_audit_log: { scanned: 1, rewritten: 1 }, sys_activity: { scanned: 1, rewritten: 1 } } }); + }, + }, { name: 'migrate activity-changed-fields', argv: ['migrate', 'activity-changed-fields'], 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 cfaafc63e63..f5569d71590 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 @@ -77,6 +77,7 @@ import MigrateActivityChangedFields from '../commands/migrate/activity-changed-f import MigrateCommentParentPair from '../commands/migrate/comment-parent-pair.js'; import MigrateApply from '../commands/migrate/apply.js'; import MigrateAuditKeyMaterial from '../commands/migrate/audit-key-material.js'; +import MigrateAuditSideCopies from '../commands/migrate/audit-side-copies.js'; import MigrateAuditMailBodies from '../commands/migrate/audit-mail-bodies.js'; import MigrateAuditMetadataBodies from '../commands/migrate/audit-metadata-bodies.js'; import MigrateBlankMultiValues from '../commands/migrate/blank-multi-values.js'; @@ -253,6 +254,11 @@ const CALLERS: Record = { noWrite: [{ label: 'migrate audit-key-material', argv: ['--database-url', '@DB@', '--json'] }], write: [{ label: 'migrate audit-key-material --apply', argv: ['--apply', '--yes', '--database-url', '@DB@', '--json'] }], }, + 'commands/migrate/audit-side-copies.ts': { + run: invoke(MigrateAuditSideCopies), + noWrite: [{ label: 'migrate audit-side-copies', argv: ['--database-url', '@DB@', '--json'] }], + write: [{ label: 'migrate audit-side-copies --apply', argv: ['--apply', '--yes', '--database-url', '@DB@', '--json'] }], + }, 'commands/migrate/audit-mail-bodies.ts': { run: invoke(MigrateAuditMailBodies), noWrite: [{ label: 'migrate audit-mail-bodies', argv: ['--database-url', '@DB@', '--json'] }], diff --git a/packages/cli/test/json-stdout-purity.e2e.test.ts b/packages/cli/test/json-stdout-purity.e2e.test.ts index 3d40b148661..74f2e466133 100644 --- a/packages/cli/test/json-stdout-purity.e2e.test.ts +++ b/packages/cli/test/json-stdout-purity.e2e.test.ts @@ -133,6 +133,9 @@ const FAMILY: Record = { // that writes nothing, its rewrite runner logging through a sink `--json` // points at stderr. 'migrate audit-key-material': [], + // [#33155] The third twin over the same two tables: a dry run by default that + // writes nothing, its rewrite runner logging through a sink `--json` points at stderr. + 'migrate audit-side-copies': [], // A dry run is its DEFAULT and the only form driven here: without `--apply` // it boots read-only (plugin-audit's objects registered), reads // `sys_comment` below the data door and writes nothing. diff --git a/packages/cli/test/migrate-confirmation-exit.pin.test.ts b/packages/cli/test/migrate-confirmation-exit.pin.test.ts index 9cb7271c8c3..cacc87e4ce3 100644 --- a/packages/cli/test/migrate-confirmation-exit.pin.test.ts +++ b/packages/cli/test/migrate-confirmation-exit.pin.test.ts @@ -254,6 +254,7 @@ const ROSTER: Record = { 'audit-key-material': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, 'audit-mail-bodies': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, 'audit-metadata-bodies': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, + 'audit-side-copies': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, 'blank-multi-values': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, 'blank-single-values': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, 'option-codes': { argv: ['--apply'], confirm: '--yes', writes: BOOT }, diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-redaction-live.integration.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-redaction-live.integration.test.ts index c7c6eb4be65..0375fcae039 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-redaction-live.integration.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-redaction-live.integration.test.ts @@ -10,6 +10,7 @@ import { installDefaultOrganization } from '../default-organization.testkit.js'; import { migrateKeyMaterialCopies } from '../key-material-copy-migration.js'; import { migrateArchivedMailLogBodyCopies, migrateMailLogBodyCopies, planMailLogBodyAuditRowPatch } from '../mail-log-body-migration.js'; import { SysAuditLog } from '../objects/sys-audit-log.object.js'; +import { migrateSideCopies } from '../side-copy-migration.js'; import { migrateStoredMetadataBodyCopies } from '../stored-metadata-body-migration.js'; import { RedactionAmender, type AuditRedactionSeal } from './amendment-writer.js'; import { canonicalValue, commitValue } from './canonical.js'; @@ -22,7 +23,7 @@ import { SigningKeyTrust } from './verifier.js'; /** * ADR-0154 D7 on a live engine over SQLite, with an `archive` datasource: - * `sys_audit_log` sealed, the plugin's own sealer seals it, and the three real + * `sys_audit_log` sealed, the plugin's own sealer seals it, and the four real * rewrite migrations rewrite its copies through the one amendment writer. The * live check then reads each rewritten sealed row `redacted`, with the * amendment the writer signed. A run with no crypto provider refuses the @@ -36,6 +37,7 @@ const SYS = { isSystem: true } as const; const LOG = 'sys_audit_log'; const MAIL_BODY = 'mail-body-sentinel'; const KEY_MATERIAL = 'key-material-sentinel'; +const SIDE_COPY = 'side-copy-sentinel'; type Row = Record; interface Driver { @@ -98,6 +100,7 @@ describe('the redaction amendment writer on a live engine (ADR-0154 D7)', () => // Copies at rest in a settled window, one copy per migration, and one row nothing rewrites. await hot().create(LOG, copy('mail', past + 60_000, 'sys_email', { id: 'em_1', subject: 'kept', body_text: MAIL_BODY })); await hot().create(LOG, copy('key', past + 120_000, 'sys_secret', { id: 'sec_1', namespace: 'n', ciphertext: KEY_MATERIAL })); + await hot().create(LOG, copy('side', past + 130_000, 'sys_approval_request', { id: 'ar_1', status: 'kept', payload_json: SIDE_COPY })); await hot().create(LOG, copy('meta', past + 150_000, 'sys_metadata', { id: 'md_1', name: 'kept', checksum: `sha256:${'a'.repeat(64)}` })); await hot().create(LOG, copy('tampered', past + 160_000, 'sys_email', { id: 'em_2', body_text: MAIL_BODY })); await hot().create(LOG, copy('moved', past + 170_000, 'sys_email', { id: 'em_3', body_text: MAIL_BODY })); @@ -173,18 +176,23 @@ describe('the redaction amendment writer on a live engine (ADR-0154 D7)', () => expect(result.dangling).toEqual([]); }); - it('the key-material and the metadata-body rewrites amend their sealed copies the same way', async () => { + it('the key-material, the side-copy and the metadata-body rewrites amend their sealed copies the same way', async () => { const keys = await migrateKeyMaterialCopies(engine as never, recordingLogger(), { apply: true, seal: seal(), objects: ['sys_audit_log'] }); expect(keys).toMatchObject({ rewritten: 1, refused: 0 }); + const side = await migrateSideCopies(engine as never, recordingLogger(), { apply: true, seal: seal(), objects: ['sys_audit_log'] }); + expect(side).toMatchObject({ rewritten: 1, refused: 0 }); const meta = await migrateStoredMetadataBodyCopies(engine as never, recordingLogger(), { apply: true, seal: seal() }); expect(meta.byObject.sys_audit_log).toEqual({ scanned: 1, rewritten: 1, refused: 0 }); expect(String((await stored('key'))!.new_value)).not.toContain(KEY_MATERIAL); expect(String((await stored('meta'))!.new_value)).not.toContain('sha256:'); - expect((await amendments()).filter((a) => a.row_id === 'key' || a.row_id === 'meta').map((a) => a.rewritten_by).sort()).toEqual([ + expect(String((await stored('side'))!.new_value)).not.toContain(SIDE_COPY); + // Each amendment names the command that rewrote the row (#33155: the side-copy rewrite's name). + expect((await amendments()).filter((a) => ['key', 'side', 'meta'].includes(String(a.row_id))).map((a) => a.rewritten_by).sort()).toEqual([ 'os migrate audit-key-material', 'os migrate audit-metadata-bodies', + 'os migrate audit-side-copies', ]); - expect(verdicts(await verify())).toEqual({ mail: 'redacted', key: 'redacted', meta: 'redacted', tampered: 'modified' }); + expect(verdicts(await verify())).toEqual({ mail: 'redacted', key: 'redacted', side: 'redacted', meta: 'redacted', tampered: 'modified' }); }); it('amends a sealed copy in the archive datasource through the archive run', async () => { From 34582583df4b86a5250a4adefee4d4f7a3ae3521 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 01:53:43 +0000 Subject: [PATCH 2/2] feat(cli): os migrate audit-side-copies runs the at-rest side-copy rewrite, hot and archive The command drives plugin-audit's migrateSideCopies and migrateArchivedSideCopies with audit-key-material's shape (read-only dry run by default, --apply/--yes/--force/--json, the redaction seal, the archive classification and exit codes) plus a repeatable --object over the two copy tables; any other name is refused OBJECT_NOT_FOUND before the boot. The rewrite's redaction amendments now name it 'os migrate audit-side-copies', as the twins name theirs. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .changeset/33155-audit-side-copies-door.md | 2 +- .../src/commands/migrate/audit-side-copies.ts | 351 ++++++++++++++++++ .../plugin-audit/src/side-copy-migration.ts | 11 +- 3 files changed, 360 insertions(+), 4 deletions(-) create mode 100644 packages/cli/src/commands/migrate/audit-side-copies.ts diff --git a/.changeset/33155-audit-side-copies-door.md b/.changeset/33155-audit-side-copies-door.md index ddd4dc99946..7d77e378ab9 100644 --- a/.changeset/33155-audit-side-copies-door.md +++ b/.changeset/33155-audit-side-copies-door.md @@ -20,4 +20,4 @@ os migrate audit-side-copies --apply --yes --json # CI / scripts The audit writer no longer copies a side-copy column (another record's field values, today an approval request's `payload_json`) into `sys_audit_log` (`new_value`, `old_value`) or `sys_activity` (both halves of `metadata`). Copies written before that still carry it. Until they are rewritten, the read-time redaction drops the column and the query guard treats a query naming it as reaching every object, so the command is cleanup, not a gate. - **The command.** It drives `@objectstack/plugin-audit`'s `migrateSideCopies` (the live `sys_audit_log` and `sys_activity` rows) and `migrateArchivedSideCopies` (the archive datasource `sys_audit_log` archives to). It is a dry run by default and writes only with `--apply`. Its flags are `os migrate audit-key-material`'s (`--database-url`, `--apply`, `--yes`, `--force`, `--json`) plus `--object`, which takes `sys_audit_log` or `sys_activity` and narrows the run, hot and archive, to the tables it names. Any other name is refused with `OBJECT_NOT_FOUND`, exit 1, before anything is read. The report gives, per copy table, the copies read and the copies rewritten (or to rewrite), for the hot tables and for the archive each, and never prints a value. It is idempotent: a second `--apply` rewrites nothing. A failed read or write, a sealed row it had to refuse, or an archive it could not reach exits 1, as for its twins. -- **The rewrite's name (`@objectstack/plugin-audit`).** A sealed row the rewrite amends (ADR-0154 D7) now records `rewritten_by: 'os migrate audit-side-copies'`, the command that rewrote it, as `audit-mail-bodies`, `audit-key-material` and `audit-metadata-bodies` record theirs. It recorded `side-copy-migration` before; a row amended under that name keeps it. +- **The rewrite's name (`@objectstack/plugin-audit`).** A sealed row the rewrite amends (ADR-0154 D7) now records `rewritten_by: 'os migrate audit-side-copies'`, the command that rewrote it, as `audit-mail-bodies`, `audit-key-material` and `audit-metadata-bodies` record theirs. It recorded `side-copy-migration` before, a name no release shipped; a row amended under it on a pre-release build keeps it. diff --git a/packages/cli/src/commands/migrate/audit-side-copies.ts b/packages/cli/src/commands/migrate/audit-side-copies.ts new file mode 100644 index 00000000000..9b5c5468855 --- /dev/null +++ b/packages/cli/src/commands/migrate/audit-side-copies.ts @@ -0,0 +1,351 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { Command, Flags } from '@oclif/core'; +import chalk from 'chalk'; +import { createInterface } from 'node:readline'; +import type { IObjectQLEngine } from '@objectstack/spec/contracts'; +import { + printHeader, + printSuccess, + printWarning, + printError, + printInfo, + printStep, + createTimer, + emitJson, + isExitSignal, + errorCodeFields, +} from '../../utils/format.js'; +import { bootSchemaStack } from '../../utils/schema-migrate.js'; +import { OCCUPANCY_HINT, probeMigrationTarget } from '../../utils/migrate-occupancy-gate.js'; +import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-occupancy.js'; +import { buildDataMigrationPlugins } from '../../utils/data-migration-plugins.js'; +import { absentTableReads } from '../../utils/absent-table-reads.js'; +import { exitOneShotCommand } from '../../utils/one-shot-exit.js'; +import { archiveFailureCount, examineArchiveTargets } from '../../utils/ledger-copy-archive.js'; +import { composeRedactionSeal } from '../../utils/audit-redaction-seal.js'; +import { objectNotFoundError } from '@objectstack/core'; + +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(); + } +} + +/** + * `os migrate audit-side-copies` — the one-off removal of the side-copy + * columns from the ledger copies the audit writer stored in `sys_audit_log` / + * `sys_activity` before it omitted them (#32442, #33155). + * + * A side-copy column holds ANOTHER record's field values, served on its own + * row only through its owner's per-reader narrowing (`side-copy-columns.ts` in + * `@objectstack/plugin-audit`; today `sys_approval_request.payload_json`). A + * ledger copy cannot be narrowed that way, so the writer omits those columns + * from every new copy; copies written before keep them. This command removes + * them with the writer's own list (`migrateSideCopies` on the hot tables, + * `migrateArchivedSideCopies` on the archive). Operators run it once after + * upgrading, dry run first. Until it has run, the serve-time redactions drop + * the columns and the query guards treat a query naming one as reaching every + * object, so it is completeness, not a gate. + * + * It is `os migrate audit-key-material`'s twin: the same runner and stores in + * plugin-audit, driven with a different list and planners, and the same + * command shape here (flags, read-only dry-run boot, absent-table read view, + * redaction seal, archive run and exit semantics), plus `--object`, which + * narrows the run to the named copy tables. A name that is not one of them is + * refused before the boot (`OBJECT_NOT_FOUND`), never narrowed to nothing. + * Its redaction amendments name it `os migrate audit-side-copies` + * (`rewritten_by`), as the twins name theirs. + * + * Dry run by default (writes no row), `--apply` to remove. Idempotent: a copy + * without the columns has nothing to remove, so a second run rewrites nothing — + * re-running and reading a clean report is the verification. The report is + * counts only, per copy table and per store, and no line names a value. No + * `sys_migration` flag is recorded: nothing gates irreversible behaviour on it. + * + * ## The archive datasource too + * + * After the hot run this command reads each selected copy table's declared + * archive target (`lifecycle.archive.to`) and, when this boot connected a + * datasource of that name, runs the same rewrite through its driver, in the + * same dry-run / `--apply` mode. Absence is loud, exactly as for the twins: + * an archive this boot did not reach but the stack config declares, or that an + * active runtime datasource row names, is NOT examined, and the command exits + * non-zero (`../../utils/ledger-copy-archive.ts` holds the one classification). + */ +export default class MigrateAuditSideCopies extends Command { + static override description = + 'Remove the side-copy columns (another record\'s field values, such as an approval request\'s payload_json) from ' + + 'the sys_audit_log / sys_activity copies the audit writer stored before it omitted them, on this database and in ' + + 'the archive datasource sys_audit_log archives to. Dry run by default; --apply writes. Reports counts only.'; + + static override examples = [ + '$ os migrate audit-side-copies', + '$ os migrate audit-side-copies --object sys_audit_log', + '$ os migrate audit-side-copies --apply', + '$ os migrate audit-side-copies --apply --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: 'Remove the side-copy columns from the copies that hold them (default is a read-only dry run)', + default: false, + }), + 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, + }), + object: Flags.string({ + description: 'Rewrite only this copy table (sys_audit_log or sys_activity), on this database and its archive. Repeatable; default both', + multiple: true, + }), + json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to apply)' }), + }; + + /** + * The process must end when the run does, as `os migrate audit-key-material` + * does: the boot connects the declared datasources + * (`composeDeclaredDatasources`), and a pool it opened can leave the event + * loop alive after the kernel reports a clean shutdown. The failure paths + * exit through oclif's own signal and do not come back here. + */ + async run(): Promise { + await this.rewrite(); + await exitOneShotCommand(typeof process.exitCode === 'number' ? process.exitCode : 0); + } + + private async rewrite(): Promise { + const { flags } = await this.parse(MigrateAuditSideCopies); + const timer = createTimer(); + const apply = flags.apply; + + if (!flags.json) printHeader('Migrate · audit-side-copies'); + + // `--object` names copy tables; anything else is refused before the boot, + // with the family's envelope (`OBJECT_NOT_FOUND`), never narrowed to nothing. + const { migrateSideCopies, migrateArchivedSideCopies, SIDE_COPY_TABLES } = await import('@objectstack/plugin-audit'); + const unknown = [...new Set((flags.object ?? []).filter((name) => !(SIDE_COPY_TABLES as readonly string[]).includes(name)))]; + if (unknown.length > 0) { + const error = objectNotFoundError(unknown[0]); + error.message = + `${unknown.length === 1 ? 'Object' : 'Objects'} ${unknown.map((name) => `'${name}'`).join(', ')} not a ledger copy ` + + `table: --object takes one of ${[...SIDE_COPY_TABLES].sort().join(', ')}, and nothing was read.`; + if (flags.json) { + await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); + this.exit(1); + return; + } + printError(error.message); + this.exit(1); + return; + } + const objects = flags.object + ? SIDE_COPY_TABLES.filter((table) => flags.object!.includes(table)) + : [...SIDE_COPY_TABLES]; + const occupancy = await probeMigrationTarget(flags['database-url']); + if (occupancy.status === 'busy' && apply && !flags.force) { + if (flags.json) { + await emitJson( + { error: 'database_busy', database: occupancy.filename, signal: occupancy.signal, detail: occupancy.detail, hint: OCCUPANCY_HINT }, + 0, + { compact: true }, + ); + this.exit(1); + return; + } + printError(describeOccupancy(occupancy)); + printWarning(OCCUPANCY_HINT); + this.exit(1); + return; + } + if (occupancy.status === 'busy' && !flags.json) { + printWarning(apply + ? `--force: ${describeOccupancy(occupancy)} Rewriting anyway — the live process may write rows mid-walk.` + : `${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' && !flags.json) { + printWarning(`Could not check whether the database is in use — ${occupancy.detail}`); + } + + if (apply && !flags.yes) { + if (flags.json || !process.stdin.isTTY) { + if (flags.json) { + await emitJson({ error: 'confirmation_required', hint: 'pass --yes' }, 0, { compact: true }); + this.exit(1); + return; + } + printWarning('Apply mode rewrites audit/activity rows (and archived audit rows). Re-run with --yes to confirm, or run without --apply to preview.'); + this.exit(1); + return; + } + const ok = await confirm( + chalk.bold(`\nRemove the side-copy columns from every ${objects.join(' / ')} ledger copy on this database and its archive? [y/N] `), + ); + if (!ok) { + printInfo('Aborted — no changes made.'); + return; + } + } + + if (!flags.json) { + printStep(apply ? 'Booting data stack (APPLY mode)…' : 'Booting data stack (dry run)…'); + } + + // [ADR-0154 D7] The crypto `os serve` seals with, so a sealed copy is amended before it is rewritten. + const redaction = await composeRedactionSeal(); + let stack; + try { + // The dry run boots READ-ONLY — the boot `os migrate plan` takes: + // `deferSchemaDdl` holds schema DDL back and suppresses the artifact's + // inline seed loader, and `readOnlyProbe` keeps a missing sqlite file + // from being created. `--apply` keeps the plain boot. + stack = await bootSchemaStack({ + jsonOutput: flags.json, + databaseUrl: flags['database-url'], + extraPlugins: [...(await buildDataMigrationPlugins({ audit: true })), ...redaction.plugins], + // Connect the declared datasources as `os serve` does, so a declared + // archive datasource is registered under its name and the archive run + // below reaches it. + composeDeclaredDatasources: true, + ...(apply ? {} : { deferSchemaDdl: true, readOnlyProbe: true }), + }); + } catch (error: any) { + if (flags.json) { await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); this.exit(1); } + printError(error.message || String(error)); + this.exit(1); + return; + } + + try { + // `SchemaStack.kernel` is untyped, so the slot's contract is stated on the + // RESULT — the `objectql` slot serves `IObjectQLEngine`, whose `find` / + // `update` are exactly what the rewrite calls. + const engine = stack.kernel.getService('objectql') as IObjectQLEngine | undefined; + if (typeof engine?.find !== 'function' || typeof engine?.update !== 'function') { + throw new Error('No ObjectQL engine on this stack — cannot rewrite audit rows.'); + } + + const logger = flags.json + ? { info: (m: string) => console.error(m), warn: (m: string) => console.error(m) } + : { info: (m: string) => printInfo(m), warn: (m: string) => printWarning(m) }; + + // The read view `os migrate audit-key-material` reads the same two tables + // through: a table the read-only boot MEASURED absent holds no copy and + // answers no rows without the read; `sys_activity`, rotation-managed and a + // view over time-sharded tables, is always read, and only the refusal of a + // table that is not there reads as no rows. ⛔ Any other refused read is + // still counted in `failures` and still exits non-zero. `--apply` booted + // plain; its writes go to the engine itself. + const reads = absentTableReads(stack, (object) => engine.getObject(object)); + const readView: Pick = { + find: (object, query, options) => reads.rows(object, () => engine.find(object, query, options)), + update: (object, data, options) => engine.update(object, data, options), + }; + + const seal = redaction.seal(stack.kernel, engine); + const report = await migrateSideCopies(readView, logger, { apply, objects, seal }); + + // Each copy table's declared archive target, then the same rewrite + // through that datasource's driver. + const archive = await examineArchiveTargets({ + engine, + kernel: stack.kernel, + reads: readView, + tables: objects, + run: (driver, archived) => migrateArchivedSideCopies(driver, logger, { apply, objects: archived, seal }), + }); + const failures = report.failures + archiveFailureCount(archive); + const refused = report.refused + archive.reduce((n, a) => n + (a.report?.refused ?? 0), 0); + + if (flags.json) { + reads.notice(true); + await emitJson({ database: stack.dbLabel, apply, objects, report, archive, duration: timer.elapsed() }); + if (failures > 0 || refused > 0) this.exit(1); + return; + } + + printInfo(`Database: ${chalk.white(stack.dbLabel)}`); + reads.notice(false); + console.log(''); + for (const [object, stats] of Object.entries(report.byObject)) { + console.log( + ` ${chalk.white(object)}: ${stats.scanned} ledger cop(ies) scanned, ${stats.rewritten} ${apply ? 'rewritten' : 'to rewrite'}` + + (stats.refused > 0 ? `, ${stats.refused} sealed and refused` : ''), + ); + } + for (const a of archive) { + if (a.report) { + for (const [object, stats] of Object.entries(a.report.byObject)) { + console.log( + ` ${chalk.white(object)} (archive datasource '${a.datasource}'): ${stats.scanned} ledger cop(ies) scanned, ` + + `${stats.rewritten} ${apply ? 'rewritten' : 'to rewrite'}` + (stats.refused > 0 ? `, ${stats.refused} sealed and refused` : ''), + ); + } + } else if (a.status === 'none') { + console.log(chalk.dim( + ` archive datasource '${a.datasource}': none declared and connected on this boot, and no active runtime ` + + `datasource row names one — nothing examined. An archive a host registers in code outside the stack ` + + `config is not reached: declare it in the config's \`datasources\` with \`autoConnect: true\`.`, + )); + } + } + console.log(''); + for (const a of archive) { + if (a.status === 'not-connected' && a.connection) { + printError( + `Archive datasource '${a.datasource}' (${a.objects.join(', ')}) was NOT examined: the stack config declares ` + + `it, and this boot did not connect it (${a.connection.status}` + + `${a.connection.reason ? `: ${a.connection.reason}` : ''}), so its archived copies may still hold ` + + `side-copy columns. Make it reachable from where this command runs, and re-run.`, + ); + } else if (a.status === 'not-connected') { + printError( + `Archive datasource '${a.datasource}' (${a.objects.join(', ')}) was NOT examined: the database holds an active ` + + `runtime datasource of that name, which \`os serve\` connects and this command does not, so its archived ` + + `copies may still hold side-copy columns. Declare it in the stack config's \`datasources\` ` + + `(with \`autoConnect: true\`) and re-run.`, + ); + } else if (a.status === 'unknown') { + printError( + `Archive datasource '${a.datasource}' (${a.objects.join(', ')}) was NOT examined: it is not connected on this ` + + `boot, and whether the database holds a runtime datasource of that name could not be read.`, + ); + } + } + + const rewritten = report.rewritten + archive.reduce((n, a) => n + (a.report?.rewritten ?? 0), 0); + if (refused > 0) printError(redaction.refusedLine(refused)); + if (failures > 0) { + printError(`${failures} read(s), row(s) or archive datasource(s) failed — re-run to finish them.`); + } else if (apply && rewritten > 0) { + printSuccess( + `Removed the side-copy columns from ${rewritten} audit/activity row(s). Re-run any time — it only revisits copies still holding them.`, + ); + } else if (!apply && rewritten > 0) { + printInfo(`Dry run only — ${rewritten} row(s) would be rewritten. Re-run with --apply.`); + } else if (refused === 0) { + printSuccess('Nothing to remove — no audit/activity copy holds a side-copy column.'); + } + console.log(chalk.dim(` ${timer.display()}`)); + console.log(''); + if (failures > 0 || refused > 0) this.exit(1); + } catch (error: any) { + if (isExitSignal(error)) throw error; + if (flags.json) { await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); this.exit(1); } + printError(error.message || String(error)); + this.exit(1); + } finally { + await stack.shutdown(); + } + } +} diff --git a/packages/plugins/plugin-audit/src/side-copy-migration.ts b/packages/plugins/plugin-audit/src/side-copy-migration.ts index 9e332a4074d..423412c80d4 100644 --- a/packages/plugins/plugin-audit/src/side-copy-migration.ts +++ b/packages/plugins/plugin-audit/src/side-copy-migration.ts @@ -10,7 +10,7 @@ * (`mail-log-body-migration.ts`, {@link runLedgerCopyRewrite}), so the * rewrites never disagree about paging, the write's context, a sealed row * (amended first, or refused) or what is a failure. Dry-run by default, - * idempotent, counts only. + * idempotent, counts only. Its operator door is `os migrate audit-side-copies`. * * Until it has run, the serve-time redactions drop the columns and the query * guards judge a query naming a carrying column against every object (`side-copy-columns.ts`). @@ -133,12 +133,17 @@ export interface SideCopyMigrationReport { failures: number; } -/** The side-copy rewrite's list, planners and words. Its command-line door is owed; until then a host drives the runners. */ +/** + * The side-copy rewrite's list, planners and words. Its door is `os migrate + * audit-side-copies`, and a redaction amendment names the rewrite by that + * command (`rewritten_by`), as the twins name theirs. A row amended before the + * door existed keeps `side-copy-migration`. + */ const SIDE_COPY_REWRITE: LedgerCopyRewriteSpec = { objectNames: SIDE_COPY_OBJECTS, planAudit: planSideCopyAuditRowPatch, planActivity: planSideCopyActivityRowPatch, - migration: 'side-copy-migration', + migration: 'os migrate audit-side-copies', tag: '[side-copy-migration]', summary: (report, label) => `[side-copy-migration] ${report.apply ? 'removed' : 'would remove'} listed columns from ${report.rewritten} of ` +