|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [ADR-0131 D10 item 5] What `os migrate apply --allow-destructive` tells the |
| 5 | + * operator when it holds back an `organization_id` drop the organization-ownership |
| 6 | + * ceremony owns, in 18.0. |
| 7 | + * |
| 8 | + * 18.0 supports fresh installs only, and its registered |
| 9 | + * `os migrate organization-ownership` refuses on every database, plan and apply |
| 10 | + * alike (`organization-ownership.release-refusal.test.ts`). So the drop gate's |
| 11 | + * refusal, the human face and the `--json` `detail` both, names no step of that |
| 12 | + * command: it says what 18.0 supports for a v17 database, the 17.x release to |
| 13 | + * keep it on and the 18.x release that carries the upgrade path, as the boot |
| 14 | + * refusal does (`organizationOwnershipRefusalMessage`, `@objectstack/runtime`). |
| 15 | + * |
| 16 | + * ## What is real here |
| 17 | + * |
| 18 | + * The command's own parse, its drift handling and the gate run for real. The |
| 19 | + * boot, the occupancy probe, the process exit and the ceremony's marker read |
| 20 | + * are replaced: the subject is the text the gate hands the operator, for each |
| 21 | + * marker state it can read, and a control proves the harness reaches the |
| 22 | + * writes once the marker is verified. The real command on a v17-shape SQLite |
| 23 | + * table is `apply-organization-ownership-gate.integration.test.ts`. |
| 24 | + */ |
| 25 | + |
| 26 | +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; |
| 27 | +import { dirname, resolve } from 'node:path'; |
| 28 | +import { fileURLToPath } from 'node:url'; |
| 29 | +import MigrateApply from './apply.js'; |
| 30 | +import { isExitSignal } from '../../utils/format.js'; |
| 31 | + |
| 32 | +// ⛔ `vi.hoisted`, never a value import of `bootSchemaStack`: this suite boots |
| 33 | +// nothing, and a value import of that symbol files a test in the integration |
| 34 | +// tier (`vitest-tiers.ts`). |
| 35 | +const mocks = vi.hoisted(() => ({ |
| 36 | + bootSchemaStack: vi.fn(), |
| 37 | + exitOneShotCommand: vi.fn(async (_code: number) => {}), |
| 38 | + readOrganizationOwnershipMarker: vi.fn(), |
| 39 | +})); |
| 40 | + |
| 41 | +vi.mock('../../utils/schema-migrate.js', async (importOriginal) => ({ |
| 42 | + ...(await importOriginal<Record<string, unknown>>()), |
| 43 | + bootSchemaStack: mocks.bootSchemaStack, |
| 44 | +})); |
| 45 | +vi.mock('../../utils/migrate-occupancy-gate.js', () => ({ |
| 46 | + OCCUPANCY_HINT: 'occupancy hint', |
| 47 | + probeMigrationTarget: vi.fn(async () => ({ status: 'free' })), |
| 48 | +})); |
| 49 | +vi.mock('../../utils/one-shot-exit.js', () => ({ exitOneShotCommand: mocks.exitOneShotCommand })); |
| 50 | +vi.mock('../../utils/organization-ownership-drop-gate.js', async (importOriginal) => ({ |
| 51 | + ...(await importOriginal<Record<string, unknown>>()), |
| 52 | + readOrganizationOwnershipMarker: mocks.readOrganizationOwnershipMarker, |
| 53 | +})); |
| 54 | + |
| 55 | +const HERE = dirname(fileURLToPath(import.meta.url)); |
| 56 | +const CLI_ROOT = resolve(HERE, '..', '..', '..'); |
| 57 | +/** oclif builds its whole command table on the first `run()` in a process. */ |
| 58 | +const RUN_TIMEOUT = 60_000; |
| 59 | + |
| 60 | +/** |
| 61 | + * The drift a v17-shape table offers: a physical `organization_id` on a table |
| 62 | + * whose v18 object declares none. |
| 63 | + */ |
| 64 | +const ORGANIZATION_DROP = { |
| 65 | + category: 'destructive', |
| 66 | + table: 'sys_platform_setting', |
| 67 | + column: 'organization_id', |
| 68 | + op: { type: 'drop_column', column: 'organization_id' }, |
| 69 | + description: 'sys_platform_setting.organization_id: column exists in the database but not in metadata (orphaned)', |
| 70 | +}; |
| 71 | + |
| 72 | +/** A step of `os migrate organization-ownership`, which 18.0 refuses on every database. */ |
| 73 | +const WITHDRAWN_COMMAND = /os migrate organization-ownership|--plan-file|organization-ownership --out/; |
| 74 | + |
| 75 | +const UNVERIFIED = { id: 'adr-0131-organization-ownership', last_run_at: '2026-10-01T00:00:00.000Z', verified_at: null, blocking: 2 }; |
| 76 | +const VERIFIED = { ...UNVERIFIED, verified_at: '2026-10-01T00:00:00.000Z', blocking: 0 }; |
| 77 | + |
| 78 | +let flushSchemaDdl: ReturnType<typeof vi.fn>; |
| 79 | +let applyMigrationEntries: ReturnType<typeof vi.fn>; |
| 80 | + |
| 81 | +function bootWithOrganizationDrop(): void { |
| 82 | + flushSchemaDdl = vi.fn(async () => []); |
| 83 | + applyMigrationEntries = vi.fn(async () => ({ applied: [ORGANIZATION_DROP], skipped: [] })); |
| 84 | + mocks.bootSchemaStack.mockResolvedValue({ |
| 85 | + driver: {}, |
| 86 | + drivers: [], |
| 87 | + dbLabel: 'file:v17.db', |
| 88 | + dbSource: { kind: 'flag' }, |
| 89 | + telemetryDatabase: null, |
| 90 | + composition: { plugins: [], hostConfigPath: null, hostConfigLoaded: false, hostConfigError: null, notes: [] }, |
| 91 | + detectManagedDrift: async () => [ORGANIZATION_DROP], |
| 92 | + driftApplyLimit: () => null, |
| 93 | + pendingSchemaWork: [], |
| 94 | + kernel: { getService: () => ({}) }, |
| 95 | + flushSchemaDdl, |
| 96 | + applyMigrationEntries, |
| 97 | + shutdown: vi.fn(async () => {}), |
| 98 | + }); |
| 99 | +} |
| 100 | + |
| 101 | +let stdout: ReturnType<typeof vi.spyOn>; |
| 102 | +let log: ReturnType<typeof vi.spyOn>; |
| 103 | +let stderr: ReturnType<typeof vi.spyOn>; |
| 104 | +let savedExitCode: typeof process.exitCode; |
| 105 | +beforeEach(() => { |
| 106 | + savedExitCode = process.exitCode; |
| 107 | + process.exitCode = undefined; |
| 108 | + mocks.bootSchemaStack.mockReset(); |
| 109 | + mocks.exitOneShotCommand.mockClear(); |
| 110 | + mocks.readOrganizationOwnershipMarker.mockReset(); |
| 111 | + // `emitJson` awaits the write's DRAIN callback, so the double must invoke it. |
| 112 | + stdout = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown, enc?: unknown, cb?: unknown) => { |
| 113 | + const done = typeof enc === 'function' ? enc : cb; |
| 114 | + if (typeof done === 'function') done(); |
| 115 | + return true; |
| 116 | + }) as typeof process.stdout.write); |
| 117 | + log = vi.spyOn(console, 'log').mockImplementation(() => {}); |
| 118 | + stderr = vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 119 | +}); |
| 120 | +afterEach(() => { |
| 121 | + stdout.mockRestore(); |
| 122 | + log.mockRestore(); |
| 123 | + stderr.mockRestore(); |
| 124 | + process.exitCode = savedExitCode; |
| 125 | +}); |
| 126 | + |
| 127 | +/** |
| 128 | + * Run the command; answer the status it ends the process with, the JSON |
| 129 | + * document it emitted, and the refusal line the human face printed. |
| 130 | + */ |
| 131 | +async function runApply(argv: string[]) { |
| 132 | + const err = await MigrateApply.run(argv, { root: CLI_ROOT }).then(() => null, (e: unknown) => e); |
| 133 | + if (err !== null && !isExitSignal(err)) throw err; |
| 134 | + const exit = err !== null |
| 135 | + ? (err as { oclif?: { exit?: number } }).oclif?.exit |
| 136 | + : mocks.exitOneShotCommand.mock.calls.at(-1)?.[0]; |
| 137 | + const out = stdout.mock.calls.map((c: unknown[]) => String(c[0])).join('').trim(); |
| 138 | + const refusal = log.mock.calls.map((c: unknown[]) => c.map(String).join(' ')).find((line: string) => line.includes('Refusing this --allow-destructive run')); |
| 139 | + return { exit, payload: out ? JSON.parse(out) : null, refusal }; |
| 140 | +} |
| 141 | + |
| 142 | +const ARGV = ['--database-url', 'file:v17.db', '--allow-destructive', '--yes']; |
| 143 | + |
| 144 | +describe('os migrate apply --allow-destructive: the organization-ownership refusal names no command 18.0 refuses', () => { |
| 145 | + for (const [state, flag] of [['no ceremony run recorded', null], ['an unverified run recorded', UNVERIFIED]] as const) { |
| 146 | + it(`${state}: the human face refuses, exit 1, saying what 18.0 supports, and nothing is written`, async () => { |
| 147 | + bootWithOrganizationDrop(); |
| 148 | + mocks.readOrganizationOwnershipMarker.mockResolvedValue({ verified: false, flag }); |
| 149 | + |
| 150 | + const { exit, refusal } = await runApply(ARGV); |
| 151 | + |
| 152 | + expect(exit).toBe(1); |
| 153 | + expect(refusal, 'the gate printed its refusal').toBeDefined(); |
| 154 | + expect(refusal).toContain('sys_platform_setting'); |
| 155 | + expect(refusal).not.toMatch(WITHDRAWN_COMMAND); |
| 156 | + expect(refusal).toContain('17.x release'); |
| 157 | + expect(refusal).toContain('18.x release'); |
| 158 | + if (flag) expect(refusal).toContain('2 blocking'); |
| 159 | + expect(flushSchemaDdl).not.toHaveBeenCalled(); |
| 160 | + expect(applyMigrationEntries).not.toHaveBeenCalled(); |
| 161 | + }, RUN_TIMEOUT); |
| 162 | + |
| 163 | + it(`${state}: under --json the refusal's detail names no command 18.0 refuses either`, async () => { |
| 164 | + bootWithOrganizationDrop(); |
| 165 | + mocks.readOrganizationOwnershipMarker.mockResolvedValue({ verified: false, flag }); |
| 166 | + |
| 167 | + const { exit, payload } = await runApply([...ARGV, '--json']); |
| 168 | + |
| 169 | + expect(exit).toBe(1); |
| 170 | + expect(payload).toMatchObject({ |
| 171 | + message: 'refused_organization_ownership_unmigrated', |
| 172 | + tables: ['sys_platform_setting'], |
| 173 | + applied: [], |
| 174 | + created: [], |
| 175 | + marker: flag, |
| 176 | + }); |
| 177 | + expect(payload.detail).not.toMatch(WITHDRAWN_COMMAND); |
| 178 | + expect(applyMigrationEntries).not.toHaveBeenCalled(); |
| 179 | + }, RUN_TIMEOUT); |
| 180 | + } |
| 181 | +}); |
| 182 | + |
| 183 | +describe('control', () => { |
| 184 | + it('a verified marker lets the drop through and exits 0, so the harness can tell a refusal from a run', async () => { |
| 185 | + bootWithOrganizationDrop(); |
| 186 | + mocks.readOrganizationOwnershipMarker.mockResolvedValue({ verified: true, flag: VERIFIED }); |
| 187 | + |
| 188 | + const { exit, payload } = await runApply([...ARGV, '--json']); |
| 189 | + |
| 190 | + expect(exit).toBe(0); |
| 191 | + expect(applyMigrationEntries).toHaveBeenCalledTimes(1); |
| 192 | + expect(payload.applied).toEqual([ORGANIZATION_DROP]); |
| 193 | + }, RUN_TIMEOUT); |
| 194 | +}); |
0 commit comments