|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * The ADR-0131 D10 `--apply` on `sys_activity`'s organization-less rows |
| 5 | + * (ruling record 6257510973 item 3, Q3 A): activity is written only when an |
| 6 | + * organization is derivable, never as a NULL row, and the ceremony deletes the |
| 7 | + * existing NULL rows no anchor attributes — 14-day telemetry, whose change the |
| 8 | + * deployment ledger (`sys_audit_log`, D7) keeps. |
| 9 | + * |
| 10 | + * The fixture is a sign-up's measured shape: activity about a `sys_user` (an |
| 11 | + * object with no organization column) written NULL, beside a NULL activity |
| 12 | + * row about an organization's record and an activity row already stamped. |
| 13 | + * |
| 14 | + * - Walled (`isolated`): the row about the organization's record takes its |
| 15 | + * organization from the subject anchor; the two about the user, which no |
| 16 | + * anchor attributes, are deleted by the mirror-deletion step; the stamped |
| 17 | + * row is untouched. The plan says so before the first write, and the |
| 18 | + * verdict certifies with nothing remaining. |
| 19 | + * - `single`: the Default Organization takes the user's rows, as a |
| 20 | + * single-posture boot gives it every row it writes; nothing is deleted. |
| 21 | + */ |
| 22 | + |
| 23 | +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; |
| 24 | +import Database from 'better-sqlite3'; |
| 25 | +import { mkdtempSync, rmSync } from 'node:fs'; |
| 26 | +import { tmpdir } from 'node:os'; |
| 27 | +import { join } from 'node:path'; |
| 28 | +import { buildOrganizationOwnershipPlan, inventoryDigest, type OrganizationOwnershipPlan } from './organization-ownership-plan.js'; |
| 29 | +import { |
| 30 | + applyOrganizationOwnership, |
| 31 | + reviewedConflictsOf, |
| 32 | + type ApplyExecutor, |
| 33 | + type CeremonyCheckpoint, |
| 34 | + type CeremonyLedgerPort, |
| 35 | + type ColumnDropPort, |
| 36 | + type OrganizationOwnershipApplyReport, |
| 37 | +} from './organization-ownership-apply.js'; |
| 38 | + |
| 39 | +let dir: string; |
| 40 | +let db: Database.Database; |
| 41 | +/** Every write statement the ceremony issued, in order. */ |
| 42 | +let writes: string[]; |
| 43 | + |
| 44 | +function executor(): ApplyExecutor { |
| 45 | + return { |
| 46 | + dialect: 'sqlite', |
| 47 | + client: 'better-sqlite3', |
| 48 | + async query(sql, params = []) { |
| 49 | + return db.prepare(sql).all(...(params as unknown[])) as Record<string, unknown>[]; |
| 50 | + }, |
| 51 | + async execute(sql, params = []) { |
| 52 | + writes.push(sql); |
| 53 | + db.prepare(sql).run(...(params as unknown[])); |
| 54 | + }, |
| 55 | + }; |
| 56 | +} |
| 57 | + |
| 58 | +const columnDrops: ColumnDropPort = { |
| 59 | + async drop(columns) { |
| 60 | + return columns.map(({ table, column }) => { |
| 61 | + db.exec(`ALTER TABLE "${table}" DROP COLUMN "${column}"`); |
| 62 | + return { table, column, outcome: 'dropped' as const }; |
| 63 | + }); |
| 64 | + }, |
| 65 | +}; |
| 66 | + |
| 67 | +function ledger(): CeremonyLedgerPort { |
| 68 | + let stored: CeremonyCheckpoint | null = null; |
| 69 | + return { |
| 70 | + async read() { |
| 71 | + return stored ? (JSON.parse(JSON.stringify(stored)) as CeremonyCheckpoint) : null; |
| 72 | + }, |
| 73 | + async write(checkpoint) { |
| 74 | + stored = JSON.parse(JSON.stringify(checkpoint)) as CeremonyCheckpoint; |
| 75 | + }, |
| 76 | + }; |
| 77 | +} |
| 78 | + |
| 79 | +const database = (): string => join(dir, 'fixture.db'); |
| 80 | + |
| 81 | +const plan = (posture: string): Promise<OrganizationOwnershipPlan> => |
| 82 | + buildOrganizationOwnershipPlan({ reader: executor(), posture, database: database() }); |
| 83 | + |
| 84 | +/** Plan, then apply that reviewed plan, as the command does. */ |
| 85 | +async function apply(posture: string, l = ledger()): Promise<OrganizationOwnershipApplyReport> { |
| 86 | + const reviewed = await plan(posture); |
| 87 | + return applyOrganizationOwnership({ |
| 88 | + executor: executor(), |
| 89 | + posture, |
| 90 | + database: database(), |
| 91 | + reviewedPlan: { |
| 92 | + file: 'plan.json', |
| 93 | + generatedAt: reviewed.generatedAt, |
| 94 | + database: database(), |
| 95 | + inventoryDigest: inventoryDigest(), |
| 96 | + posture, |
| 97 | + conflicts: reviewedConflictsOf(reviewed), |
| 98 | + }, |
| 99 | + catalog: { async resolve() { return undefined; } }, |
| 100 | + door: { |
| 101 | + async save(type, name) { |
| 102 | + throw new Error(`no environment save is expected here (${type} ${name})`); |
| 103 | + }, |
| 104 | + }, |
| 105 | + templates: { async find() { return undefined; } }, |
| 106 | + views: { async list() { return []; } }, |
| 107 | + lock: { async verdict() { return { editable: true }; } }, |
| 108 | + columnDrops, |
| 109 | + ledger: l, |
| 110 | + now: () => new Date('2026-10-19T00:00:00Z'), |
| 111 | + }); |
| 112 | +} |
| 113 | + |
| 114 | +const activity = (): Record<string, unknown>[] => |
| 115 | + db.prepare(`SELECT id, organization_id FROM sys_activity ORDER BY id`).all() as Record<string, unknown>[]; |
| 116 | + |
| 117 | +beforeEach(() => { |
| 118 | + dir = mkdtempSync(join(tmpdir(), 'os-d10-underivable-activity-')); |
| 119 | + db = new Database(database()); |
| 120 | + writes = []; |
| 121 | + db.exec(` |
| 122 | + CREATE TABLE sys_organization (id TEXT PRIMARY KEY, slug TEXT); |
| 123 | + INSERT INTO sys_organization VALUES ('org_default', 'default'), ('org_a', 'acme'); |
| 124 | + CREATE TABLE sys_user (id TEXT PRIMARY KEY, name TEXT, email TEXT); |
| 125 | + INSERT INTO sys_user VALUES ('usr_1', 'Ada', 'ada@example.com'); |
| 126 | + CREATE TABLE crm_deal (id TEXT PRIMARY KEY, organization_id TEXT, name TEXT); |
| 127 | + INSERT INTO crm_deal VALUES ('deal_1', 'org_a', 'Acme renewal'); |
| 128 | + CREATE TABLE sys_activity (id TEXT PRIMARY KEY, organization_id TEXT, type TEXT, object_name TEXT, record_id TEXT); |
| 129 | + INSERT INTO sys_activity VALUES |
| 130 | + ('act_deal_null', NULL, 'created', 'crm_deal', 'deal_1'), |
| 131 | + ('act_deal_stamped', 'org_a', 'updated', 'crm_deal', 'deal_1'), |
| 132 | + ('act_user_created', NULL, 'created', 'sys_user', 'usr_1'), |
| 133 | + ('act_user_updated', NULL, 'updated', 'sys_user', 'usr_1'); |
| 134 | + `); |
| 135 | +}); |
| 136 | + |
| 137 | +afterEach(() => { |
| 138 | + db.close(); |
| 139 | + rmSync(dir, { recursive: true, force: true }); |
| 140 | +}); |
| 141 | + |
| 142 | +describe('sys_activity rows no organization is derivable for (ruling record 6257510973 item 3)', () => { |
| 143 | + it('walled: the plan counts the two underivable rows as departing, says so before the first write, and reports none', async () => { |
| 144 | + const reviewed = await plan('isolated'); |
| 145 | + const table = reviewed.tables.find((t) => t.object === 'sys_activity')!; |
| 146 | + expect(table.fateCounts).toMatchObject({ rowsToAttribute: 1, departingRows: 2, unattributableRows: 0 }); |
| 147 | + expect(table.departures).toEqual([expect.objectContaining({ id: 'underivable-activity', as: 'mirror-deletion', rows: 2 })]); |
| 148 | + expect(table.unattributable).toEqual([]); |
| 149 | + expect(table.notNull.willReceive).toBe(true); |
| 150 | + expect(reviewed.warnings).toEqual([expect.stringMatching(/^sys_activity holds 2 organization-less row\(s\) no anchor attributes: .*--apply deletes them/)]); |
| 151 | + }); |
| 152 | + |
| 153 | + it('walled: the anchored row takes its organization, the two about the user are deleted, the stamped row stays; nothing remains', async () => { |
| 154 | + const report = await apply('isolated'); |
| 155 | + |
| 156 | + expect([report.complete, report.blocking]).toEqual([true, 0]); |
| 157 | + const table = report.tables.find((t) => t.object === 'sys_activity')!; |
| 158 | + expect(table).toMatchObject({ attributed: 1, deleted: 2, remaining: 0, unattributable: [], departures: [] }); |
| 159 | + expect(table.after).toEqual({ total: 2, organizationNull: 0 }); |
| 160 | + expect(activity()).toEqual([ |
| 161 | + { id: 'act_deal_null', organization_id: 'org_a' }, |
| 162 | + { id: 'act_deal_stamped', organization_id: 'org_a' }, |
| 163 | + ]); |
| 164 | + // Deleted after attribution, by the mirror-deletion step, NULL rows only. |
| 165 | + const deletes = writes.filter((w) => /^DELETE FROM "sys_activity"/i.test(w)); |
| 166 | + expect(deletes).toEqual(['DELETE FROM "sys_activity" WHERE "organization_id" IS NULL']); |
| 167 | + expect(writes.findIndex((w) => /^UPDATE "sys_activity"/i.test(w))).toBeLessThan(writes.indexOf(deletes[0]!)); |
| 168 | + expect(report.steps.find((s) => s.step === 'mirror-deletion')).toMatchObject({ status: 'done', summary: { deleted: 2 } }); |
| 169 | + }); |
| 170 | + |
| 171 | + it('walled: a second run finds nothing to delete and writes nothing to the table', async () => { |
| 172 | + const l = ledger(); |
| 173 | + await apply('isolated', l); |
| 174 | + writes = []; |
| 175 | + const again = await apply('isolated', l); |
| 176 | + expect([again.complete, again.blocking]).toEqual([true, 0]); |
| 177 | + expect(writes.filter((w) => /sys_activity/.test(w))).toEqual([]); |
| 178 | + }); |
| 179 | + |
| 180 | + it('single: the Default Organization takes the user\'s rows, and nothing is deleted', async () => { |
| 181 | + const reviewed = await plan('single'); |
| 182 | + const table = reviewed.tables.find((t) => t.object === 'sys_activity')!; |
| 183 | + expect(table.departures).toEqual([]); |
| 184 | + expect(table.attribution).toMatchObject({ 'default-organization': 2 }); |
| 185 | + expect(reviewed.warnings).toEqual([]); |
| 186 | + |
| 187 | + const report = await apply('single'); |
| 188 | + expect([report.complete, report.blocking]).toEqual([true, 0]); |
| 189 | + expect(report.tables.find((t) => t.object === 'sys_activity')).toMatchObject({ attributed: 3, deleted: 0, remaining: 0 }); |
| 190 | + expect(activity()).toEqual([ |
| 191 | + { id: 'act_deal_null', organization_id: 'org_a' }, |
| 192 | + { id: 'act_deal_stamped', organization_id: 'org_a' }, |
| 193 | + { id: 'act_user_created', organization_id: 'org_default' }, |
| 194 | + { id: 'act_user_updated', organization_id: 'org_default' }, |
| 195 | + ]); |
| 196 | + expect(writes.filter((w) => /^DELETE FROM "sys_activity"/i.test(w))).toEqual([]); |
| 197 | + }); |
| 198 | +}); |
0 commit comments