@principles/pd-cli 1.147.5 → 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.
Files changed (32) hide show
  1. package/dist/commands/codex-ingest-quarantine.d.ts +12 -0
  2. package/dist/commands/codex-ingest-quarantine.d.ts.map +1 -0
  3. package/dist/commands/codex-ingest-quarantine.js +116 -0
  4. package/dist/commands/codex-ingest-quarantine.js.map +1 -0
  5. package/dist/commands/codex-setup.d.ts +46 -0
  6. package/dist/commands/codex-setup.d.ts.map +1 -0
  7. package/dist/commands/codex-setup.js +423 -0
  8. package/dist/commands/codex-setup.js.map +1 -0
  9. package/dist/commands/console.d.ts.map +1 -1
  10. package/dist/commands/console.js +12 -2
  11. package/dist/commands/console.js.map +1 -1
  12. package/dist/commands/health-codex.d.ts.map +1 -1
  13. package/dist/commands/health-codex.js +350 -67
  14. package/dist/commands/health-codex.js.map +1 -1
  15. package/dist/index.js +51 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/services/console-launcher.d.ts.map +1 -1
  18. package/dist/services/console-launcher.js +8 -1
  19. package/dist/services/console-launcher.js.map +1 -1
  20. package/package.json +1 -1
  21. package/src/commands/codex-ingest-quarantine.ts +127 -0
  22. package/src/commands/codex-setup.ts +476 -0
  23. package/src/commands/console.ts +13 -2
  24. package/src/commands/health-codex.ts +396 -69
  25. package/src/index.ts +53 -0
  26. package/src/services/console-launcher.ts +9 -1
  27. package/tests/commands/codex-consent-reversibility.steps.test.ts +299 -0
  28. package/tests/commands/codex-ingest-quarantine.test.ts +136 -0
  29. package/tests/commands/codex-setup.test.ts +297 -0
  30. package/tests/commands/codex-worker-registration.test.ts +29 -0
  31. package/tests/commands/console-open.test.ts +31 -0
  32. package/tests/commands/health-codex.test.ts +278 -172
@@ -1,50 +1,123 @@
1
1
  /**
2
- * pd health --host codex command unit tests.
2
+ * pd health --host codex command tests — §15 health surface (Slice D).
3
+ *
4
+ * Module-boundary mock style (the handler is a read-model aggregator): every
5
+ * collaborator is mocked, the handler logic (§15 ready conjunction, consent
6
+ * states, blockers, exit codes) is exercised for real.
3
7
  *
4
8
  * Covers:
5
- * - cli-1: JSON mode outputs exactly one parseable JSON object.
6
- * - cli-2: exit paths stop execution (process.exitCode set, no later side effects).
7
- * - cli-5: failure paths do not mutate state (read-only).
8
- * - cli-6: every degraded result includes reason + nextAction.
9
- * - flag-off path (host.codex disabled warning + exitCode).
10
- * - hooks trust undetectable (no ~/.codex) reason + nextAction.
11
- * - dual registration detection (global hooks.json present → reason + nextAction).
12
- * - happy path (flag on, hooks trusted) → clean JSON, no warnings.
9
+ * - cli-1: --json outputs exactly one parseable JSON object.
10
+ * - §15 ready conjunction: full green ready + exit 0.
11
+ * - "unknown is not healthy": a degraded section not ready + blocker.
12
+ * - consent: flag_on_without_consent blocker; stale disclosure; decline.
13
+ * - admissions without task blocker with `pd codex reconcile` nextAction.
14
+ * - hooks trust untrusted blocker + exit 1.
15
+ * - legacy dual registration migration nextAction (§17 retirement).
16
+ * - worker mode manual_action_required/degraded not ready.
17
+ * - per-rollout lag detection from checkpoint + transcript stat.
13
18
  */
14
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
19
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
15
20
 
16
21
  const {
17
22
  mockResolveNearestPdWorkspace,
18
23
  mockLoadPdConfigForPlugin,
19
24
  mockComputeFeatureFlagsFromConfig,
20
25
  mockIsFeatureEnabled,
26
+ mockReadCodexIngestionConsent,
27
+ mockDeriveConsentState,
28
+ mockListGovernanceCheckpoints,
29
+ mockReadObservationStats,
30
+ mockReadAdmissionCounts,
31
+ mockComputeWorkerMode,
32
+ mockLocateTranscript,
33
+ mockGetInstallLayoutPaths,
34
+ mockParseInstallManifest,
21
35
  mockExistsSync,
22
36
  mockReadFileSync,
37
+ mockStatSync,
23
38
  mockHomedir,
24
39
  mockRequireResolve,
25
40
  mockConsoleLog,
26
41
  mockConsoleWarn,
27
- } = vi.hoisted(() => {
28
- return {
29
- mockResolveNearestPdWorkspace: vi.fn(),
30
- mockLoadPdConfigForPlugin: vi.fn(),
31
- mockComputeFeatureFlagsFromConfig: vi.fn(),
32
- mockIsFeatureEnabled: vi.fn(),
33
- mockExistsSync: vi.fn(),
34
- mockReadFileSync: vi.fn(),
35
- mockHomedir: vi.fn(),
36
- mockRequireResolve: vi.fn(),
37
- mockConsoleLog: vi.fn(),
38
- mockConsoleWarn: vi.fn(),
39
- };
40
- });
42
+ } = vi.hoisted(() => ({
43
+ mockResolveNearestPdWorkspace: vi.fn(),
44
+ mockLoadPdConfigForPlugin: vi.fn(),
45
+ mockComputeFeatureFlagsFromConfig: vi.fn(),
46
+ mockIsFeatureEnabled: vi.fn(),
47
+ mockReadCodexIngestionConsent: vi.fn(),
48
+ mockDeriveConsentState: vi.fn(),
49
+ mockListGovernanceCheckpoints: vi.fn(),
50
+ mockReadObservationStats: vi.fn(),
51
+ mockReadAdmissionCounts: vi.fn(),
52
+ mockComputeWorkerMode: vi.fn(),
53
+ mockLocateTranscript: vi.fn(),
54
+ mockGetInstallLayoutPaths: vi.fn(),
55
+ mockParseInstallManifest: vi.fn(),
56
+ mockExistsSync: vi.fn(),
57
+ mockReadFileSync: vi.fn(),
58
+ mockStatSync: vi.fn(),
59
+ mockHomedir: vi.fn(),
60
+ mockRequireResolve: vi.fn(),
61
+ mockConsoleLog: vi.fn(),
62
+ mockConsoleWarn: vi.fn(),
63
+ }));
41
64
 
42
65
  vi.mock('@principles/host-runtime', () => ({
43
- resolveNearestPdWorkspace: mockResolveNearestPdWorkspace,
44
66
  loadPdConfigForPlugin: mockLoadPdConfigForPlugin,
67
+ resolveNearestPdWorkspace: mockResolveNearestPdWorkspace,
68
+ readCodexIngestionConsent: mockReadCodexIngestionConsent,
69
+ deriveCodexIngestionConsentState: mockDeriveConsentState,
70
+ listGovernanceCheckpoints: mockListGovernanceCheckpoints,
71
+ readGovernanceObservationStats: mockReadObservationStats,
72
+ readGovernanceAdmissionCounts: mockReadAdmissionCounts,
73
+ detectLegacyCodexHookRegistration: (hooksJsonPath?: string) => {
74
+ // Mirrors the host-runtime FS edge: read via the mocked fs, delegate the
75
+ // parse semantics (marker + legacy async PostToolUse) exactly as
76
+ // codex-legacy-registration.ts does over @principles/core/host.
77
+ try {
78
+ const parsed = JSON.parse(mockReadFileSync(hooksJsonPath ?? '/fake/home/.codex/hooks.json', 'utf8')) as Record<string, unknown>;
79
+ const result = { detected: false, legacyAsyncPostToolUse: false };
80
+ for (const eventName of ['PreToolUse', 'PostToolUse', 'UserPromptSubmit', 'SessionStart']) {
81
+ const groups = parsed[eventName];
82
+ if (!Array.isArray(groups)) continue;
83
+ for (const group of groups) {
84
+ if (typeof group !== 'object' || group === null || !Object.hasOwn(group, '__pd_marker') || (group as Record<string, unknown>).__pd_marker !== 'pd-owned') continue;
85
+ result.detected = true;
86
+ const entries = (group as Record<string, unknown>).hooks;
87
+ if (Array.isArray(entries)) {
88
+ for (const entry of entries) {
89
+ if (typeof entry === 'object' && entry !== null && eventName === 'PostToolUse' && Object.hasOwn(entry, 'async') && (entry as Record<string, unknown>).async === true) {
90
+ result.legacyAsyncPostToolUse = true;
91
+ }
92
+ }
93
+ }
94
+ }
95
+ }
96
+ return result;
97
+ } catch {
98
+ return { detected: false, legacyAsyncPostToolUse: false };
99
+ }
100
+ },
101
+ CODEX_INGESTION_DISCLOSURE_VERSION: 'g2a-2026-08-28',
102
+ }));
103
+
104
+ vi.mock('@principles/codex-adapter', () => ({
105
+ computeCodexWorkerStatusMode: mockComputeWorkerMode,
106
+ locateCodexTranscriptByRolloutIdentity: mockLocateTranscript,
107
+ CODEX_INGESTION_MIN_VERSION: '0.148.0',
108
+ CODEX_INGESTION_VERIFIED_VERSION: '0.150.1',
109
+ }));
110
+
111
+ vi.mock('@principles/install-layout', () => ({
112
+ getInstallLayoutPaths: mockGetInstallLayoutPaths,
113
+ parseInstallManifest: mockParseInstallManifest,
45
114
  }));
46
115
 
47
116
  vi.mock('@principles/core/runtime-v2', () => ({
117
+ SqliteConnection: class {},
118
+ SqliteTaskStore: class {
119
+ listTasks = vi.fn().mockResolvedValue([]);
120
+ },
48
121
  computeFeatureFlagsFromConfig: mockComputeFeatureFlagsFromConfig,
49
122
  isFeatureEnabled: mockIsFeatureEnabled,
50
123
  }));
@@ -56,188 +129,221 @@ vi.mock('../../src/resolve-workspace.js', () => ({
56
129
  vi.mock('fs', () => ({
57
130
  existsSync: mockExistsSync,
58
131
  readFileSync: mockReadFileSync,
132
+ statSync: mockStatSync,
59
133
  }));
60
134
 
61
135
  vi.mock('os', () => ({
136
+ default: { homedir: mockHomedir, userInfo: vi.fn().mockReturnValue({ username: 'tester' }) },
62
137
  homedir: mockHomedir,
138
+ userInfo: vi.fn().mockReturnValue({ username: 'tester' }),
63
139
  }));
64
140
 
65
141
  vi.mock('module', () => ({
66
- createRequire: () => ({
67
- resolve: mockRequireResolve,
68
- }),
142
+ createRequire: () => ({ resolve: mockRequireResolve }),
69
143
  }));
70
144
 
71
145
  import { handleHealthCodex } from '../../src/commands/health-codex.js';
72
146
 
73
- describe('pd health --host codex', () => {
74
- beforeEach(() => {
75
- vi.clearAllMocks();
76
- process.exitCode = undefined;
77
- mockHomedir.mockReturnValue('/fake/home');
78
- mockRequireResolve.mockImplementation((name: string) => `/fake/node_modules/${name}/package.json`);
79
- mockReadFileSync.mockImplementation((p: string) => {
80
- if (typeof p === 'string' && p.includes('package.json')) {
81
- return JSON.stringify({ version: '0.1.0' });
82
- }
83
- return '';
84
- });
85
- mockResolveNearestPdWorkspace.mockReturnValue({
86
- ok: true,
87
- workspaceDir: '/fake/workspace',
88
- configPath: '/fake/workspace/.pd/config.yaml',
89
- source: 'nearest',
90
- });
91
- mockLoadPdConfigForPlugin.mockReturnValue({
92
- ok: true,
93
- effective: {},
94
- source: 'user_config',
95
- configPath: '/fake/workspace/.pd/config.yaml',
96
- warnings: [],
97
- errors: [],
98
- });
99
- mockComputeFeatureFlagsFromConfig.mockReturnValue({ flags: {} });
100
- mockIsFeatureEnabled.mockReturnValue(true);
101
- // No ~/.codex by default → hooks trust undetectable
102
- mockExistsSync.mockImplementation((p: string) => !p.includes('.codex'));
103
- mockConsoleLog.mockImplementation(() => {});
104
- mockConsoleWarn.mockImplementation(() => {});
105
- vi.spyOn(console, 'log').mockImplementation(mockConsoleLog);
106
- vi.spyOn(console, 'warn').mockImplementation(mockConsoleWarn);
107
- });
108
-
109
- afterEach(() => {
110
- process.exitCode = undefined;
111
- vi.restoreAllMocks();
147
+ function flagMap(): Record<string, { enabled: boolean }> {
148
+ return {
149
+ 'host.codex': { enabled: true },
150
+ codex_conversation_ingestion: { enabled: true },
151
+ };
152
+ }
153
+
154
+ function grantedConsentRecord(): Record<string, unknown> {
155
+ return { decision: 'granted', disclosureVersion: 'g2a-2026-08-28', decidedAt: '2026-09-06T00:00:00.000Z', decidedVia: 'pd_codex_setup', schemaVersion: '1' };
156
+ }
157
+
158
+ function greenSetup(): void {
159
+ mockResolveNearestPdWorkspace.mockReturnValue({ ok: true, workspaceDir: '/fake/workspace', configPath: '/fake/workspace/.pd/config.yaml', source: 'nearest' });
160
+ mockLoadPdConfigForPlugin.mockReturnValue({ ok: true, source: 'user_config', effective: {}, configPath: '/fake/workspace/.pd/config.yaml', warnings: [], errors: [] });
161
+ mockComputeFeatureFlagsFromConfig.mockReturnValue({ flags: flagMap() });
162
+ mockIsFeatureEnabled.mockImplementation((_flags: unknown, id: string) => (flagMap())[id]?.enabled ?? false);
163
+ mockReadCodexIngestionConsent.mockReturnValue({ ok: true, existed: true, record: grantedConsentRecord() });
164
+ mockDeriveConsentState.mockReturnValue('granted');
165
+ mockListGovernanceCheckpoints.mockReturnValue({ ok: true, checkpoints: [] });
166
+ mockReadObservationStats.mockReturnValue({ ok: true, stats: { operational: 3, promoted: 1, quarantined: 0, terminalOther: 0, nextExpiryAt: '2026-09-07T00:00:00.000Z', lastObservationAt: '2026-09-06T00:00:00.000Z' } });
167
+ mockReadAdmissionCounts.mockReturnValue({ ok: true, counts: { admitted: 1, admittedWithoutTask: 0, pendingTails: 0, staleTails: 0, completedTails: 1, lastAdmissionAt: '2026-09-06T00:00:00.000Z' } });
168
+ mockComputeWorkerMode.mockReturnValue({ mode: 'ready' });
169
+ mockLocateTranscript.mockReturnValue({ ok: false, reason: 'not_found' });
170
+ mockGetInstallLayoutPaths.mockReturnValue({ manifest: '/fake/manifest.json' });
171
+ mockParseInstallManifest.mockReturnValue({ manifest: { workspaces: ['/fake/workspace'] } });
172
+ // Green hooks environment: ~/.codex exists with config.toml hooks = true.
173
+ // NOTE: the handler joins paths with the REAL path module, so on Windows
174
+ // the separators are backslashes — match by suffix, never full equality.
175
+ mockHomedir.mockReturnValue('/fake/home');
176
+ mockExistsSync.mockImplementation((candidate: string | Buffer) => {
177
+ const value = String(candidate);
178
+ return value.endsWith('.codex') || value.endsWith('config.toml');
112
179
  });
113
-
114
- it('cli-1: --json outputs exactly one parseable JSON object on stdout', async () => {
115
- // ~/.codex exists with trusted hooks for happy path
116
- mockExistsSync.mockImplementation((p: string) => true);
117
- mockReadFileSync.mockImplementation((p: string) => {
118
- if (typeof p === 'string' && p.includes('package.json')) return JSON.stringify({ version: '0.1.0' });
119
- if (typeof p === 'string' && p.includes('config.toml')) return '[features]\nhooks = true\n';
120
- return '';
121
- });
122
-
123
- await handleHealthCodex({ json: true });
124
-
125
- expect(mockConsoleLog).toHaveBeenCalledTimes(1);
126
- const output = mockConsoleLog.mock.calls[0][0] as string;
127
- const parsed = JSON.parse(output);
128
- expect(parsed.host).toBe('codex');
129
- expect(parsed.adapterVersion).toBe('0.1.0');
130
- expect(parsed.runtimeVersion).toBe('0.1.0');
131
- expect(parsed.featureFlag.enabled).toBe(true);
132
- expect(parsed.hooksTrust.detectable).toBe(true);
133
- expect(parsed.hooksTrust.trusted).toBe(true);
134
- expect(process.exitCode).toBeUndefined();
180
+ mockRequireResolve.mockImplementation((name: string) => `/fake/node_modules/${name}/package.json`);
181
+ mockReadFileSync.mockImplementation((candidate: string | Buffer) => {
182
+ const value = String(candidate);
183
+ if (value.endsWith('config.toml')) return '[features]\nhooks = true\n';
184
+ if (value.includes('package.json')) return JSON.stringify({ version: '0.1.0' });
185
+ return '';
135
186
  });
187
+ mockStatSync.mockReturnValue({ size: 0 });
188
+ }
189
+
190
+ async function runJson(): Promise<Record<string, unknown>> {
191
+ await handleHealthCodex({ json: true });
192
+ expect(mockConsoleLog).toHaveBeenCalledTimes(1);
193
+ return JSON.parse(mockConsoleLog.mock.calls[0]?.[0] as string) as Record<string, unknown>;
194
+ }
195
+
196
+ beforeEach(() => {
197
+ vi.clearAllMocks();
198
+ greenSetup();
199
+ vi.spyOn(console, 'log').mockImplementation(mockConsoleLog);
200
+ vi.spyOn(console, 'warn').mockImplementation(mockConsoleWarn);
201
+ });
136
202
 
137
- it('cli-6: when ~/.codex is missing, reports reason + nextAction', async () => {
138
- mockExistsSync.mockImplementation((p: string) => !p.includes('.codex'));
139
-
140
- await handleHealthCodex({ json: true });
203
+ afterEach(() => {
204
+ process.exitCode = undefined;
205
+ vi.restoreAllMocks();
206
+ });
141
207
 
142
- const output = mockConsoleLog.mock.calls[0][0] as string;
143
- const parsed = JSON.parse(output);
144
- expect(parsed.hooksTrust.detectable).toBe(false);
145
- expect(parsed.hooksTrust.reason).toBe('codex_config_dir_not_found');
146
- expect(parsed.hooksTrust.nextAction).toContain('Install Codex CLI');
147
- expect(parsed.warnings).toContainEqual(expect.stringContaining('hooks_trust'));
208
+ describe('pd health --host codex §15 ready semantics', () => {
209
+ it('cli-1 + full green ⇒ ready true, exit 0, one JSON object with §15 fields', async () => {
210
+ const report = await runJson();
211
+ expect(report.ready, JSON.stringify(report.readyBlockers)).toBe(true);
212
+ expect(report.readyBlockers).toHaveLength(0);
213
+ expect(report.host).toBe('codex');
214
+ expect(report.codexIngestionMinVersion).toBe('0.148.0');
215
+ expect((report.consent as { state: string }).state).toBe('granted');
216
+ expect((report.workspaceInit as { initialized: boolean }).initialized).toBe(true);
217
+ expect((report.observations as { operational: number }).operational).toBe(3);
218
+ expect((report.diagnosticianTasks as { pending: number }).pending).toBe(0);
219
+ expect(process.exitCode ?? 0).toBe(0);
148
220
  });
149
221
 
150
- it('flag-off + hooks untrusted exitCode 1', async () => {
151
- mockIsFeatureEnabled.mockReturnValue(false);
152
- mockExistsSync.mockImplementation((p: string) => !p.includes('.codex'));
153
-
154
- await handleHealthCodex({ json: true });
155
-
222
+ it('untrusted hooks not ready with blocker and exit 1', async () => {
223
+ mockExistsSync.mockImplementation((candidate: string | Buffer) => String(candidate).endsWith('config.toml'));
224
+ mockReadFileSync.mockImplementation((candidate: string | Buffer) => (String(candidate).endsWith('config.toml') ? '[features]\nhooks = false\n' : ''));
225
+ const report = await runJson();
226
+ expect(report.ready).toBe(false);
227
+ expect((report.readyBlockers as string[]).some((blocker) => blocker.startsWith('hooks_trust'))).toBe(true);
156
228
  expect(process.exitCode).toBe(1);
157
- const output = mockConsoleLog.mock.calls[0][0] as string;
158
- const parsed = JSON.parse(output);
159
- expect(parsed.featureFlag.enabled).toBe(false);
160
229
  });
161
230
 
162
- it('cli-6: config.toml exists but hooks setting missing reason + nextAction', async () => {
163
- mockExistsSync.mockImplementation((p: string) => true);
164
- mockReadFileSync.mockImplementation((p: string) => {
165
- if (typeof p === 'string' && p.includes('package.json')) return JSON.stringify({ version: '0.1.0' });
166
- if (typeof p === 'string' && p.includes('config.toml')) return '[features]\nmodel = "gpt-4"\n';
167
- return '';
168
- });
169
-
170
- await handleHealthCodex({ json: true });
171
-
172
- const output = mockConsoleLog.mock.calls[0][0] as string;
173
- const parsed = JSON.parse(output);
174
- expect(parsed.hooksTrust.detectable).toBe(false);
175
- expect(parsed.hooksTrust.reason).toBe('hooks_setting_not_found_in_config');
176
- expect(parsed.hooksTrust.nextAction).toContain('/hooks');
231
+ it('degraded admission counts unknown is not healthy (§15)', async () => {
232
+ mockReadAdmissionCounts.mockReturnValue({ ok: false, reason: 'governance_admission_counts_unavailable', nextAction: 'inspect trajectory.db' });
233
+ const report = await runJson();
234
+ expect(report.ready).toBe(false);
235
+ expect((report.readyBlockers as string[]).some((blocker) => blocker.startsWith('admissions'))).toBe(true);
236
+ expect((report.admissions as { reason: string }).reason).toBe('governance_admission_counts_unavailable');
177
237
  });
178
238
 
179
- it('dual registration: global hooks.json present detected + reason + nextAction', async () => {
180
- mockExistsSync.mockImplementation((p: string) => true);
181
- mockReadFileSync.mockImplementation((p: string) => {
182
- if (typeof p === 'string' && p.includes('package.json')) return JSON.stringify({ version: '0.1.0' });
183
- if (typeof p === 'string' && p.includes('config.toml')) return '[features]\nhooks = true\n';
184
- return '';
185
- });
186
-
187
- await handleHealthCodex({ json: true });
188
-
189
- const output = mockConsoleLog.mock.calls[0][0] as string;
190
- const parsed = JSON.parse(output);
191
- expect(parsed.dualRegistration.detected).toBe(true);
192
- expect(parsed.dualRegistration.globalHooksPath).toContain('hooks.json');
193
- expect(parsed.dualRegistration.reason).toBe('global_hooks_json_present');
194
- expect(parsed.dualRegistration.nextAction).toContain('double-registration');
239
+ it('admitted pains without task blocker recommending reconcile', async () => {
240
+ mockReadAdmissionCounts.mockReturnValue({ ok: true, counts: { admitted: 2, admittedWithoutTask: 1, pendingTails: 0, staleTails: 0, completedTails: 0, lastAdmissionAt: null } });
241
+ const report = await runJson();
242
+ expect(report.ready).toBe(false);
243
+ const blocker = (report.readyBlockers as string[]).find((entry) => entry.startsWith('admissions'));
244
+ expect(blocker).toContain('reconcile');
195
245
  });
196
246
 
197
- it('cli-5: workspace not resolved does not mutate state, reports warning', async () => {
198
- mockResolveNearestPdWorkspace.mockReturnValue({
199
- ok: false,
200
- cwd: '/fake/workspace',
201
- reason: 'config_not_found',
202
- nextAction: 'Create .pd/config.yaml',
203
- });
247
+ it('worker degraded not ready', async () => {
248
+ mockComputeWorkerMode.mockReturnValue({ mode: 'degraded', reason: 'workspace_missing', nextAction: 'restore the workspace' });
249
+ const report = await runJson();
250
+ expect(report.ready).toBe(false);
251
+ expect((report.worker as { mode: string }).mode).toBe('degraded');
252
+ });
204
253
 
205
- await handleHealthCodex({ json: true });
254
+ it('no Companion worker ⇒ manual_action_required, never ready (no automatic closure)', async () => {
255
+ mockParseInstallManifest.mockReturnValue({ manifest: { workspaces: [] } });
256
+ mockComputeWorkerMode.mockReturnValue({ mode: 'manual_action_required', reason: 'workspace_not_in_install_manifest' });
257
+ const report = await runJson();
258
+ expect((report.worker as { mode: string }).mode).toBe('manual_action_required');
259
+ expect(report.ready).toBe(false);
260
+ });
206
261
 
207
- const output = mockConsoleLog.mock.calls[0][0] as string;
208
- const parsed = JSON.parse(output);
209
- expect(parsed.workspace).toBe('/fake/workspace');
210
- expect(parsed.featureFlag.enabled).toBe(false);
211
- expect(parsed.featureFlag.source).toBe('defaults');
212
- expect(parsed.warnings).toContainEqual(expect.stringContaining('workspace_not_resolved'));
262
+ it('diagnostician needs_human_review tasks not ready with review blocker', async () => {
263
+ // Override the task store default via the mocked class instance.
264
+ const coreModule = (await vi.importMock('@principles/core/runtime-v2')) as { SqliteTaskStore: new () => { listTasks: (filter: { status: string }) => Promise<unknown[]> } };
265
+ const original = coreModule.SqliteTaskStore;
266
+ class FakeStore {
267
+ listTasks(filter: { status: string }): Promise<unknown[]> {
268
+ return Promise.resolve(filter.status === 'needs_human_review' ? [{ id: 't1' }] : []);
269
+ }
270
+ }
271
+ vi.doMock('@principles/core/runtime-v2', () => ({ SqliteConnection: class {}, SqliteTaskStore: FakeStore, computeFeatureFlagsFromConfig: mockComputeFeatureFlagsFromConfig, isFeatureEnabled: mockIsFeatureEnabled }));
272
+ void original;
273
+ vi.resetModules();
274
+ const { handleHealthCodex: freshHandler } = await import('../../src/commands/health-codex.js');
275
+ await freshHandler({ json: true });
276
+ const output = mockConsoleLog.mock.calls[mockConsoleLog.mock.calls.length - 1]?.[0] as string;
277
+ const report = JSON.parse(output) as { ready: boolean; readyBlockers: string[] };
278
+ expect(report.ready).toBe(false);
279
+ expect(report.readyBlockers.some((blocker) => blocker.includes('human review'))).toBe(true);
280
+ process.exitCode = undefined;
213
281
  });
282
+ });
214
283
 
215
- it('text output includes nextAction for degraded hooks trust', async () => {
216
- mockExistsSync.mockImplementation((p: string) => !p.includes('.codex'));
284
+ describe('pd health --host codex consent surface (no captured text)', () => {
285
+ it('flag on without consent record ⇒ governance blocker with setup nextAction', async () => {
286
+ mockReadCodexIngestionConsent.mockReturnValue({ ok: true, existed: false, record: null });
287
+ mockDeriveConsentState.mockReturnValue('flag_on_without_grant');
288
+ const report = await runJson();
289
+ const consent = report.consent as { state: string; nextAction?: string };
290
+ expect(consent.state).toBe('flag_on_without_grant');
291
+ expect(consent.nextAction).toContain('pd codex setup');
292
+ expect(report.ready).toBe(false);
293
+ });
217
294
 
218
- await handleHealthCodex({ json: false });
295
+ it('declined consent with flag off does not block readiness on consent', async () => {
296
+ mockIsFeatureEnabled.mockImplementation((_flags: unknown, id: string) => id === 'host.codex');
297
+ mockReadCodexIngestionConsent.mockReturnValue({ ok: true, existed: true, record: { ...grantedConsentRecord(), decision: 'revoked' } });
298
+ mockDeriveConsentState.mockReturnValue('revoked');
299
+ const report = await runJson();
300
+ expect((report.consent as { state: string }).state).toBe('revoked');
301
+ expect((report.readyBlockers as string[]).some((blocker) => blocker.startsWith('consent'))).toBe(false);
302
+ });
219
303
 
220
- const calls = mockConsoleLog.mock.calls.map((c) => c[0] as string);
221
- expect(calls.some((s) => s.includes('hooksTrust.nextAction:'))).toBe(true);
222
- expect(calls.some((s) => s.includes('host: codex'))).toBe(true);
223
- expect(mockConsoleWarn).toHaveBeenCalled();
304
+ it('stale disclosure version is surfaced as re-consent nextAction', async () => {
305
+ mockReadCodexIngestionConsent.mockReturnValue({ ok: true, existed: true, record: { ...grantedConsentRecord(), disclosureVersion: 'g2a-2020-01-01' } });
306
+ const report = await runJson();
307
+ expect((report.consent as { disclosureStale: boolean }).disclosureStale).toBe(true);
224
308
  });
309
+ });
225
310
 
226
- it('adapter/runtime version unknown when package.json unreadable', async () => {
227
- mockRequireResolve.mockImplementation(() => {
228
- throw new Error('not found');
311
+ describe('pd health --host codex legacy registration (§17 retirement)', () => {
312
+ it('legacy async PostToolUse registration ⇒ migration nextAction', async () => {
313
+ mockHomedir.mockReturnValue('/fake/home');
314
+ mockExistsSync.mockImplementation((candidate: string | Buffer) => {
315
+ const value = String(candidate);
316
+ return value.endsWith('.codex') || value.endsWith('hooks.json') || value.endsWith('config.toml');
229
317
  });
230
- mockExistsSync.mockImplementation((p: string) => true);
231
- mockReadFileSync.mockImplementation((p: string) => {
232
- if (typeof p === 'string' && p.includes('config.toml')) return '[features]\nhooks = true\n';
318
+ mockReadFileSync.mockImplementation((candidate: string | Buffer) => {
319
+ const value = String(candidate);
320
+ if (value.endsWith('hooks.json')) {
321
+ return JSON.stringify({
322
+ PreToolUse: [{ matcher: 'Bash|apply_patch', hooks: [{ type: 'command', command: 'node pd-hook.cjs' }], __pd_marker: 'pd-owned' }],
323
+ PostToolUse: [{ matcher: '.*', hooks: [{ type: 'command', command: 'node pd-hook.cjs', timeout: 5, async: true }], __pd_marker: 'pd-owned' }],
324
+ });
325
+ }
326
+ if (value.endsWith('config.toml')) return '[features]\nhooks = true\n';
327
+ if (value.includes('package.json')) return JSON.stringify({ version: '0.1.0' });
233
328
  return '';
234
329
  });
330
+ const report = await runJson();
331
+ expect((report.dualRegistration as { detected: boolean; legacyAsyncPostToolUse: boolean }).legacyAsyncPostToolUse, JSON.stringify(report.dualRegistration)).toBe(true);
332
+ expect((report.dualRegistration as { nextAction?: string }).nextAction).toContain('Marketplace');
333
+ });
334
+ });
235
335
 
236
- await handleHealthCodex({ json: true });
237
-
238
- const output = mockConsoleLog.mock.calls[0][0] as string;
239
- const parsed = JSON.parse(output);
240
- expect(parsed.adapterVersion).toBe('unknown');
241
- expect(parsed.runtimeVersion).toBe('unknown');
336
+ describe('pd health --host codex — per-rollout lag', () => {
337
+ it('checkpoint lag over zero ⇒ rollout blocker with byte lag', async () => {
338
+ mockListGovernanceCheckpoints.mockReturnValue({
339
+ ok: true,
340
+ checkpoints: [{ hostKind: 'codex', rolloutIdentity: 'r-1', byteOffset: 10, lastOrdinal: 1, cliVersion: null, rootSessionId: 'root', incompleteTail: false, lastDegradationReason: null, lastDegradationOrdinal: null, updatedAt: '2026-09-06T00:00:00.000Z' }],
341
+ });
342
+ mockLocateTranscript.mockReturnValue({ ok: true, transcriptPath: '/fake/home/.codex/sessions/r-1.jsonl' });
343
+ mockStatSync.mockReturnValue({ size: 512 });
344
+ const report = await runJson();
345
+ expect(report.ready).toBe(false);
346
+ expect(((report.rollouts as { checkpoints: { lagBytes: number | null }[] }).checkpoints[0]?.lagBytes) ?? -1).toBe(502);
347
+ expect((report.readyBlockers as string[]).some((blocker) => blocker.includes('r-1'))).toBe(true);
242
348
  });
243
349
  });