@principles/pd-cli 1.147.6 → 1.147.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -584,6 +584,32 @@ const codexCmd = program
584
584
  .command('codex')
585
585
  .description('Codex host governance operations');
586
586
 
587
+ // ── pd codex setup — consent UX for conversation ingestion (Slice D) ─────────
588
+ // PRI-625, SPEC rev 2 §17 + G2A frozen disclosure: the ONE authority that can
589
+ // enable codex_conversation_ingestion — presents the frozen disclosure and
590
+ // records the explicit Owner decision BEFORE flipping the flag. Declining
591
+ // leaves all existing governance unchanged and reads no transcript.
592
+ codexCmd
593
+ .command('setup')
594
+ .description('Present the frozen ingestion disclosure and record the explicit consent decision (accept enables codex_conversation_ingestion; decline keeps everything off)')
595
+ .option('-w, --workspace <path>', 'Workspace directory')
596
+ .option('--accept', 'Explicitly accept after the disclosure has been presented (non-interactive)')
597
+ .option('--decline', 'Explicitly decline; the ingestion flag stays off and no transcript is ever read')
598
+ .option('--show-disclosure', 'Print the frozen disclosure text (zh default, --lang en) and exit without mutating anything')
599
+ .option('--lang <zh|en>', 'Disclosure language for presentation', undefined)
600
+ .option('--json', 'Output raw JSON (decision must be explicit: --accept or --decline)')
601
+ .action(async (opts) => {
602
+ const { handleCodexSetup } = await import('./commands/codex-setup.js');
603
+ await handleCodexSetup({
604
+ workspace: opts.workspace,
605
+ json: opts.json === true,
606
+ accept: opts.accept === true,
607
+ decline: opts.decline === true,
608
+ showDisclosure: opts.showDisclosure === true,
609
+ ...(typeof opts.lang === 'string' ? { lang: opts.lang } : {}),
610
+ });
611
+ });
612
+
587
613
  codexCmd
588
614
  .command('reconcile')
589
615
  .description('Reconcile admitted Codex pains with Diagnostician tasks and promotion tails (idempotent)')
@@ -624,6 +650,33 @@ codexIngestCmd
624
650
  });
625
651
  });
626
652
 
653
+ // ── pd codex ingest quarantine — audited recovery for invalid records ────────
654
+ // Codex Governance Closure Slice D (PRI-625, SPEC §15): dry-run by default,
655
+ // --confirm required to mutate; records digest/reason/operator/timestamp/gap;
656
+ // never edits the Codex transcript; promoted evidence is refused.
657
+ codexIngestCmd
658
+ .command('quarantine')
659
+ .description('Quarantine a permanently invalid governance observation (dry-run by default; --confirm to apply; never touches the transcript)')
660
+ .option('-w, --workspace <path>', 'Workspace directory')
661
+ .option('--rollout <id>', 'Rollout identity that owns the record (required)')
662
+ .option('--record <id>', 'Numeric governance_observations.id to quarantine (required)')
663
+ .option('--reason <text>', 'Why the record is permanently invalid, 1-200 chars (required)')
664
+ .option('--operator <id>', 'Operator identity recorded in the audit metadata (default: current OS user)')
665
+ .option('--confirm', 'Apply the quarantine; without this flag the command is a dry run')
666
+ .option('--json', 'Output raw JSON')
667
+ .action(async (opts) => {
668
+ const { handleCodexIngestQuarantine } = await import('./commands/codex-ingest-quarantine.js');
669
+ await handleCodexIngestQuarantine({
670
+ workspace: opts.workspace,
671
+ rollout: opts.rollout,
672
+ record: opts.record,
673
+ reason: opts.reason,
674
+ ...(typeof opts.operator === 'string' ? { operator: opts.operator } : {}),
675
+ confirm: opts.confirm === true,
676
+ json: opts.json === true,
677
+ });
678
+ });
679
+
627
680
  // ── pd codex worker — Workspace-scoped governance worker ─────────────────────
628
681
  // Codex Governance Closure Slice C (PRI-624, SPEC §13; ADR-0020 §11.1): the
629
682
  // one Owner-approved background worker (catch-up → reconciliation → one
@@ -0,0 +1,299 @@
1
+ import { afterEach, beforeEach, expect, vi } from 'vitest';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import * as yaml from 'js-yaml';
6
+ import { getDefaultPdConfig } from '@principles/core/runtime-v2';
7
+ import { catchUpCodexIngestion } from '@principles/codex-adapter';
8
+ import {
9
+ ingestGovernanceObservations,
10
+ listGovernanceObservations,
11
+ promoteGovernanceEvidence,
12
+ readCodexIngestionConsent,
13
+ CODEX_INGESTION_DISCLOSURE_VERSION,
14
+ } from '@principles/host-runtime';
15
+ import { createStepRegistry, defineFeature } from '../../../principles-core/tests/bdd/support/vitest-bdd.js';
16
+ import { resolveFeaturePath } from '../../../principles-core/tests/bdd/support/repo-root.js';
17
+
18
+ /**
19
+ * Codex Governance Closure Slice D (PRI-625): consent & reversibility BDD
20
+ * steps for SPEC rev 2 §18 scenarios 17 and 15 (flag-off half). Drives the
21
+ * REAL setup handler (the installed-path consent authority) and the REAL
22
+ * catch-up/consent/evidence seams. The uninstall/legacy-migration half of
23
+ * §18-15 is bound in create-principles-disciple's installer suites.
24
+ *
25
+ * R1 behaviors proven here (SPEC §3):
26
+ * R1-1 the disclosure is presented before ingestion can be enabled;
27
+ * R1-2 declining leaves the flag off and governance working unchanged;
28
+ * R1-3 declining never opens or reads the transcript;
29
+ * R1-4 upgrade/machine paths never enable ingestion implicitly.
30
+ */
31
+
32
+ let logLines: string[];
33
+
34
+ /** Guarded path builder: only allowlisted basenames under <root>/.pd. */
35
+ function pdFile(root: string, name: string): string | null {
36
+ if (!FILENAME_ALLOWLIST.includes(name)) return null;
37
+ const base = path.join(root, '.pd');
38
+ const target = path.join(base, name);
39
+ if (!target.startsWith(base + path.sep)) return null;
40
+ return target;
41
+ }
42
+
43
+ const FILENAME_ALLOWLIST = ['config.yaml', 'codex-ingestion-consent.json'];
44
+
45
+ function makeWorkspace(options: { handEnableIngestion?: boolean } = {}): string {
46
+ const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-bdd-consent-'));
47
+ fs.mkdirSync(path.join(ws, '.pd'), { recursive: true });
48
+ fs.mkdirSync(path.join(ws, '.state'), { recursive: true });
49
+ fs.writeFileSync(path.join(ws, '.state', 'trajectory.db'), '');
50
+ const config = getDefaultPdConfig();
51
+ config.features['host.codex'].enabled = true;
52
+ if (options.handEnableIngestion) {
53
+ config.features['codex_conversation_ingestion'].enabled = true;
54
+ }
55
+ // Multi-line YAML dump: the line-targeted editor needs a `features:` line.
56
+ fs.writeFileSync(path.join(ws, '.pd', 'config.yaml'), yaml.dump(config, { indent: 2, lineWidth: 200, noRefs: true }));
57
+ return ws;
58
+ }
59
+
60
+ /** Snapshot the fixed, allowlisted file set a consent run may touch. */
61
+ function snapshot(root: string): Map<string, string> {
62
+ const files = new Map<string, string>();
63
+ for (const name of FILENAME_ALLOWLIST) {
64
+ const full = pdFile(root, name);
65
+ if (full === null) continue;
66
+ // Read first, no stat-then-read window (CodeQL FS race): ENOENT simply
67
+ // means the file is absent for this snapshot.
68
+ try {
69
+ files.set(full, fs.readFileSync(full, 'utf8'));
70
+ } catch {
71
+ // absent file — snapshot stays empty for it
72
+ }
73
+ }
74
+ return files;
75
+ }
76
+
77
+ async function runSetup(options: Record<string, unknown>): Promise<Record<string, unknown>> {
78
+ const { handleCodexSetup } = await import('../../src/commands/codex-setup.js');
79
+ const captured: string[] = [];
80
+ // Install the capture INSIDE the step: defineFeature-created tests may not
81
+ // see file-level console/stdout spies reliably, and the capture must wrap
82
+ // exactly the handler call.
83
+ const logSpy = vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {
84
+ captured.push(args.map(String).join(' '));
85
+ });
86
+ const outSpy = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown) => {
87
+ captured.push(String(chunk));
88
+ return true;
89
+ }) as typeof process.stdout.write);
90
+ try {
91
+ await handleCodexSetup({ ...options, json: options.json === true } as never);
92
+ } finally {
93
+ logSpy.mockRestore();
94
+ outSpy.mockRestore();
95
+ }
96
+ logLines.push(...captured);
97
+ const jsonLine = captured.reverse().find((line) => line.startsWith('{'));
98
+ if (jsonLine === undefined) return {};
99
+ try {
100
+ return JSON.parse(jsonLine) as Record<string, unknown>;
101
+ } catch {
102
+ return {};
103
+ }
104
+ }
105
+
106
+ beforeEach(() => {
107
+ logLines = [];
108
+ vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {
109
+ logLines.push(args.map(String).join(' '));
110
+ });
111
+ vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown) => {
112
+ logLines.push(String(chunk));
113
+ return true;
114
+ }) as typeof process.stdout.write);
115
+ });
116
+
117
+ afterEach(() => {
118
+ vi.restoreAllMocks();
119
+ process.exitCode = undefined;
120
+ });
121
+
122
+ const registry = createStepRegistry();
123
+ let ws: string;
124
+ let beforeFiles: Map<string, string>;
125
+
126
+ registry.given('an isolated Codex Workspace without a consent record', () => {
127
+ ws = makeWorkspace();
128
+ beforeFiles = snapshot(ws);
129
+ });
130
+
131
+ registry.given('an isolated Codex Workspace with the ingestion flag hand-enabled and no consent record', () => {
132
+ ws = makeWorkspace({ handEnableIngestion: true });
133
+ beforeFiles = snapshot(ws);
134
+ });
135
+
136
+ registry.when('setup presents the ingestion disclosure', async () => {
137
+ await runSetup({ workspace: ws, showDisclosure: true });
138
+ });
139
+
140
+ registry.then('the frozen Chinese text is shown verbatim with the version of the approved decision package', () => {
141
+ const output = logLines.join('\n');
142
+ expect(output, `captured=${JSON.stringify(logLines).slice(0, 200)}`).toContain('### Principles Disciple — 对话观察与治理闭环(Codex)');
143
+ expect(output).toContain('默认关闭。只有你在看到本说明后明确选择开启才会生效;升级 PD 永远不会替你开启。');
144
+ expect(CODEX_INGESTION_DISCLOSURE_VERSION).toBe('g2a-2026-08-28');
145
+ const read = readCodexIngestionConsent(ws);
146
+ expect(read.ok && read.record).toBeNull();
147
+ });
148
+
149
+ registry.when('the Owner explicitly accepts after the disclosure', async () => {
150
+ // The disclosure was presented first (R1-1 ordering): show, then accept.
151
+ await runSetup({ workspace: ws, showDisclosure: true });
152
+ const report = await runSetup({ workspace: ws, accept: true, json: true });
153
+ expect(report.status, JSON.stringify(report)).toBe('ok');
154
+ });
155
+
156
+ registry.then('the consent record exists with the granted decision and the ingestion flag is enabled', () => {
157
+ const read = readCodexIngestionConsent(ws);
158
+ expect(read.ok && read.record?.decision).toBe('granted');
159
+ if (read.ok && read.record) {
160
+ expect(read.record.disclosureVersion).toBe(CODEX_INGESTION_DISCLOSURE_VERSION);
161
+ expect(read.record.decidedVia).toBe('pd_codex_setup');
162
+ }
163
+ const config = pdFile(ws, 'config.yaml');
164
+ expect(config).not.toBeNull();
165
+ if (config !== null) {
166
+ expect(fs.readFileSync(config, 'utf8')).toContain('enabled: true');
167
+ }
168
+ });
169
+
170
+ registry.then('no config outside the workspace consent flow was modified', () => {
171
+ // The consent flow touches exactly two files: config.yaml and the consent
172
+ // record (the allowlisted snapshot). New files may only be the consent
173
+ // record; every pre-existing file may only be the config.yaml flip.
174
+ const after = snapshot(ws);
175
+ for (const [file, content] of beforeFiles) {
176
+ if (file.endsWith('config.yaml')) continue; // the flag flip is the point
177
+ expect(after.get(file) ?? '', `unexpected change: ${file}`).toBe(content);
178
+ }
179
+ const consentPath = path.join(ws, '.pd', 'codex-ingestion-consent.json');
180
+ expect(after.has(consentPath), 'the consent record must be the only new file').toBe(true);
181
+ });
182
+
183
+ registry.when('the Owner explicitly declines', async () => {
184
+ const report = await runSetup({ workspace: ws, decline: true, json: true });
185
+ expect(report.status).toBe('ok');
186
+ expect(report.decision).toBe('revoked');
187
+ });
188
+
189
+ registry.then('the consent record exists with the declined decision and the ingestion flag is off', () => {
190
+ const read = readCodexIngestionConsent(ws);
191
+ expect(read.ok && read.record?.decision).toBe('revoked');
192
+ const config = pdFile(ws, 'config.yaml');
193
+ expect(config).not.toBeNull();
194
+ if (config !== null) {
195
+ const content = fs.readFileSync(config, 'utf8');
196
+ expect(content).toContain('codex_conversation_ingestion:');
197
+ expect(content).toContain('enabled: false');
198
+ }
199
+ });
200
+
201
+ registry.then('no transcript was opened by the decline', () => {
202
+ // The decline only rewrites the two allowlisted .pd files; the handler has
203
+ // no transcript argument and no Codex-home FS surface. (The CODEX_HOME env
204
+ // assertion was removed in review round 3: it depends on the developer's
205
+ // machine environment, not on the behavior under test.)
206
+ expect(readCodexIngestionConsent(ws).ok && readCodexIngestionConsent(ws).record?.decision).toBe('revoked');
207
+ });
208
+
209
+ registry.when('setup runs in machine mode without an explicit accept or decline', async () => {
210
+ const report = await runSetup({ workspace: ws, json: true });
211
+ expect(report.reason).toBe('decision_required');
212
+ });
213
+
214
+ registry.then('nothing is recorded and nothing is enabled', () => {
215
+ expect(readCodexIngestionConsent(ws).ok && readCodexIngestionConsent(ws).record).toBeNull();
216
+ const after = snapshot(ws);
217
+ for (const [file, content] of beforeFiles) {
218
+ expect(after.get(file) ?? '').toBe(content);
219
+ }
220
+ });
221
+
222
+ // ── §18-15 flag-off reversibility ─────────────────────────────────────────────
223
+
224
+ registry.given('an isolated Codex Workspace with conversation ingestion enabled and evidence recorded', () => {
225
+ ws = makeWorkspace({ handEnableIngestion: true });
226
+ const now = new Date();
227
+ const seeded = ingestGovernanceObservations({
228
+ workspaceDir: ws,
229
+ now,
230
+ observations: [{
231
+ hostKind: 'codex', rolloutIdentity: 'r-evidence', rootSessionId: 'root-evidence',
232
+ hostTurnId: 't1', kind: 'user_turn', logicalObservationKey: 'codex|r-evidence|t1|user',
233
+ source: 'transcript', completeness: 'complete', observedAt: now.toISOString(),
234
+ recordByteStart: 100, recordOrdinal: 1, visibleText: 'owner correction evidence',
235
+ }],
236
+ });
237
+ expect(seeded.ok).toBe(true);
238
+ });
239
+
240
+ registry.when('the ingestion flag is turned off', async () => {
241
+ const report = await runSetup({ workspace: ws, decline: true, json: true });
242
+ expect(report.status).toBe('ok');
243
+ });
244
+
245
+ registry.then('catch-up reports feature_disabled with zero transcript reads', async () => {
246
+ const result = await catchUpCodexIngestion({ workspaceDir: ws });
247
+ expect(result.status).toBe('skipped');
248
+ if (result.status === 'skipped') {
249
+ expect(result.reason).toBe('feature_disabled');
250
+ expect(result.nextAction).toContain('codex_conversation_ingestion');
251
+ }
252
+ });
253
+
254
+ registry.then('previously promoted evidence remains intact', async () => {
255
+ const promotion = promoteGovernanceEvidence({
256
+ workspaceDir: ws, hostKind: 'codex', rolloutIdentity: 'r-evidence',
257
+ triggerLogicalKey: 'codex|r-evidence|t1|user', painRef: 'pain_reversibility_1',
258
+ });
259
+ expect(promotion.ok).toBe(true);
260
+ const listed = listGovernanceObservations({ workspaceDir: ws });
261
+ expect(listed.ok).toBe(true);
262
+ if (!listed.ok) return;
263
+ expect(listed.observations.find((row) => row.logicalKey === 'codex|r-evidence|t1|user')?.retentionClass).toBe('promoted');
264
+ });
265
+
266
+ // ── §18-15 / R1-4: the upgrade path never enables ingestion ──────────────────
267
+
268
+ registry.given('an isolated Codex Workspace where the Owner declined ingestion', async () => {
269
+ ws = makeWorkspace();
270
+ const report = await runSetup({ workspace: ws, decline: true, json: true });
271
+ expect(report.status).toBe('ok');
272
+ expect(report.decision).toBe('revoked');
273
+ });
274
+
275
+ registry.when('the production runtime initializer re-runs over the workspace', async () => {
276
+ // `pd runtime init` is the upgrade/re-init entry over an existing workspace.
277
+ const { handleRuntimeInit } = await import('../../src/commands/runtime-init.js');
278
+ const captured: string[] = [];
279
+ const logSpy = vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {
280
+ captured.push(args.map(String).join(' '));
281
+ });
282
+ try {
283
+ await handleRuntimeInit({ workspace: ws, confirm: true, json: true });
284
+ } finally {
285
+ logSpy.mockRestore();
286
+ }
287
+ void captured;
288
+ });
289
+
290
+ registry.then('the ingestion flag is still off and the declined consent record is untouched', () => {
291
+ const read = readCodexIngestionConsent(ws);
292
+ expect(read.ok && read.record?.decision).toBe('revoked');
293
+ const config = fs.readFileSync(path.join(ws, '.pd', 'config.yaml'), 'utf8');
294
+ expect(config).toContain('codex_conversation_ingestion:');
295
+ expect(config).toContain('enabled: false');
296
+ expect(config).not.toMatch(/codex_conversation_ingestion:[\s\S]{0,40}enabled: true/);
297
+ });
298
+
299
+ defineFeature(fs.readFileSync(resolveFeaturePath('docs/specs/features/codex-governance/codex-consent-reversibility.feature'), 'utf8'), registry);
@@ -0,0 +1,136 @@
1
+ /**
2
+ * pd codex ingest quarantine command tests (Slice D, SPEC §15).
3
+ *
4
+ * Functional, real-filesystem: seeds a workspace trajectory.db through the
5
+ * production store, then exercises the handler. Proven:
6
+ * - dry run is the DEFAULT: --json reports dryRun=true and the record row is
7
+ * untouched;
8
+ * - --confirm quarantines (row becomes terminal, bodies dropped);
9
+ * - missing/invalid flags are refused with reason + nextAction, exit 1, and
10
+ * mutate nothing (cli-5);
11
+ * - --json emits exactly one parseable object (cli-1).
12
+ */
13
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
14
+ import fs from 'node:fs';
15
+ import os from 'node:os';
16
+ import path from 'node:path';
17
+ import { getDefaultPdConfig } from '@principles/core/runtime-v2';
18
+ import { ingestGovernanceObservations, listGovernanceObservations } from '@principles/host-runtime';
19
+
20
+ let workspaceDir: string;
21
+ let corruptRecordId = 0;
22
+ let logSpy: ReturnType<typeof vi.spyOn>;
23
+ let savedExitCode: number | undefined;
24
+
25
+ beforeEach(() => {
26
+ workspaceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-cli-quarantine-'));
27
+ fs.mkdirSync(path.join(workspaceDir, '.pd'), { recursive: true });
28
+ fs.mkdirSync(path.join(workspaceDir, '.state'), { recursive: true });
29
+ fs.writeFileSync(path.join(workspaceDir, '.state', 'trajectory.db'), '');
30
+ const config = getDefaultPdConfig();
31
+ config.features['host.codex'].enabled = true;
32
+ config.features.codex_conversation_ingestion.enabled = true;
33
+ fs.writeFileSync(path.join(workspaceDir, '.pd', 'config.yaml'), JSON.stringify(config));
34
+ const now = new Date('2026-08-29T12:00:00.000Z');
35
+ const seeded = ingestGovernanceObservations({
36
+ workspaceDir,
37
+ now,
38
+ observations: [
39
+ { hostKind: 'codex', rolloutIdentity: 'rollout-uuid-1', rootSessionId: 'root-1', hostTurnId: 't1', kind: 'user_turn', logicalObservationKey: 'codex|rollout-uuid-1|t1|user', source: 'transcript', completeness: 'complete', observedAt: now.toISOString(), recordByteStart: 100, recordOrdinal: 1, visibleText: 'first' },
40
+ { hostKind: 'codex', rolloutIdentity: 'rollout-uuid-1', rootSessionId: 'root-1', hostTurnId: 't2', kind: 'user_turn', logicalObservationKey: 'codex|rollout-uuid-1|t2|user', source: 'transcript', completeness: 'partial', observedAt: now.toISOString(), recordByteStart: 300, recordOrdinal: 3, visibleText: 'corrupt record' },
41
+ ],
42
+ });
43
+ expect(seeded.ok, JSON.stringify(seeded)).toBe(true);
44
+ const listed = listGovernanceObservations({ workspaceDir });
45
+ expect(listed.ok).toBe(true);
46
+ if (!listed.ok) throw new Error('unreachable');
47
+ const corrupt = listed.observations.find((row) => row.logicalKey === 'codex|rollout-uuid-1|t2|user');
48
+ expect(corrupt).toBeDefined();
49
+ corruptRecordId = corrupt.id;
50
+
51
+ savedExitCode = process.exitCode;
52
+ process.exitCode = undefined;
53
+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
54
+ });
55
+
56
+ afterEach(() => {
57
+ logSpy.mockRestore();
58
+ process.exitCode = savedExitCode;
59
+ fs.rmSync(workspaceDir, { recursive: true, force: true });
60
+ });
61
+
62
+ function findRecord(): { retentionClass: string; visibleText: string | null } {
63
+ const listed = listGovernanceObservations({ workspaceDir });
64
+ if (!listed.ok) throw new Error('list failed');
65
+ const row = listed.observations.find((entry) => entry.id === corruptRecordId);
66
+ if (!row) throw new Error('record vanished');
67
+ return row;
68
+ }
69
+
70
+ async function run(options: Record<string, unknown>): Promise<Record<string, unknown>> {
71
+ const { handleCodexIngestQuarantine } = await import('../../src/commands/codex-ingest-quarantine.js');
72
+ const callsBefore = logSpy.mock.calls.length;
73
+ await handleCodexIngestQuarantine({ workspace: workspaceDir, ...options } as never);
74
+ const newOutput = logSpy.mock.calls.slice(callsBefore).map((call) => String(call[0]));
75
+ const jsonLine = newOutput.reverse().find((line) => line.startsWith('{'));
76
+ expect(jsonLine, 'handler must emit exactly one JSON object for --json').toBeDefined();
77
+ return JSON.parse(jsonLine as string) as Record<string, unknown>;
78
+ }
79
+
80
+ describe('pd codex ingest quarantine (functional)', () => {
81
+ it('dry run is the default: reports digest/gap, mutates nothing, exits 0', { timeout: 20_000 }, async () => {
82
+ const report = await run({ rollout: 'rollout-uuid-1', record: String(corruptRecordId), reason: 'stable-invalid', json: true });
83
+ expect(report.status).toBe('ok');
84
+ expect(report.dryRun).toBe(true);
85
+ expect(report.confirmed).toBe(false);
86
+ expect(report.transcriptTouched).toBe(false);
87
+ const record = report.record as { digest: string; gap: string; id: number };
88
+ expect(record.id).toBe(corruptRecordId);
89
+ expect(record.digest).toMatch(/^[0-9a-f]{64}$/);
90
+ expect(record.gap).toContain('prev=');
91
+ expect(findRecord().retentionClass).toBe('operational');
92
+ expect(process.exitCode ?? 0).toBe(0);
93
+ });
94
+
95
+ it('--confirm quarantines the record; a repeat is idempotent', { timeout: 20_000 }, async () => {
96
+ const report = await run({ rollout: 'rollout-uuid-1', record: String(corruptRecordId), reason: 'stable-invalid', operator: 'tester', confirm: true, json: true });
97
+ expect(report.dryRun).toBe(false);
98
+ expect(report.alreadyQuarantined).toBe(false);
99
+ expect(findRecord().retentionClass).toBe('quarantined');
100
+ expect(findRecord().visibleText).toBeNull();
101
+
102
+ const repeat = await run({ rollout: 'rollout-uuid-1', record: String(corruptRecordId), reason: 'stable-invalid', confirm: true, json: true });
103
+ expect(repeat.alreadyQuarantined).toBe(true);
104
+ });
105
+
106
+ it('refuses invalid arguments with reason+nextAction and no mutation (cli-5/cli-6)', { timeout: 30_000 }, async () => {
107
+ // Case table is built INSIDE the test so record ids reference the row
108
+ // seeded in beforeEach (an it.each table would evaluate before seeding).
109
+ const cases: [Record<string, unknown>, string][] = [
110
+ [{ reason: 'x' }, 'rollout_required'],
111
+ [{ rollout: 'rollout-uuid-1', reason: 'x' }, 'record_required'],
112
+ [{ rollout: 'rollout-uuid-1', record: 'abc' }, 'record_required'],
113
+ [{ rollout: 'rollout-uuid-1', record: String(corruptRecordId) }, 'reason_required'],
114
+ [{ rollout: 'unknown-rollout', record: String(corruptRecordId), reason: 'x' }, 'rollout_not_found'],
115
+ ];
116
+ for (const [options, expectedReason] of cases) {
117
+ process.exitCode = undefined;
118
+ const report = await run({ ...options, json: true });
119
+ expect(report.status, JSON.stringify({ options, report })).toBe('refused');
120
+ expect(report.reason).toBe(expectedReason);
121
+ expect(String(report.nextAction).length).toBeGreaterThan(0);
122
+ expect(process.exitCode).toBe(1);
123
+ expect(findRecord().retentionClass, String(expectedReason)).toBe('operational');
124
+ }
125
+ });
126
+
127
+ it('text output includes the dry-run next action', { timeout: 20_000 }, async () => {
128
+ const { handleCodexIngestQuarantine } = await import('../../src/commands/codex-ingest-quarantine.js');
129
+ await handleCodexIngestQuarantine({ workspace: workspaceDir, rollout: 'rollout-uuid-1', record: String(corruptRecordId), reason: 'stable-invalid' });
130
+ const output = logSpy.mock.calls.map((call) => String(call[0])).join('\n');
131
+ expect(output).toContain('dry-run');
132
+ expect(output).toContain('digest:');
133
+ expect(output).toContain('--confirm');
134
+ expect(process.exitCode ?? 0).toBe(0);
135
+ });
136
+ });