@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,22 +1,53 @@
1
1
  /**
2
- * pd health --host codex command implementation.
2
+ * pd health --host codex command implementation — Codex Governance Closure
3
+ * Slice D (PRI-625; SPEC rev 2 §15 health surface).
3
4
  *
4
- * Reports Codex adapter/runtime versions, host.codex feature flag state,
5
- * hook trust status, and dual global/plugin hook registration detection.
5
+ * Reports the §15 Owner-experience surface for one workspace:
6
+ * - adapter/runtime versions + the G1 ingestion minimum Codex version;
7
+ * - workspace init (config resolution), hook trust, dual registration;
8
+ * - BOTH flag states (host.codex, codex_conversation_ingestion);
9
+ * - consent state (decision metadata only — no captured text, ever);
10
+ * - worker mode (no Companion ⇒ `manual_action_required`, never auto-closure);
11
+ * - per-rollout checkpoints with completeness (incomplete tail / degradation)
12
+ * and bounded byte lag against the live transcript file (stat only);
13
+ * - operational/promoted/quarantined counts + next expiry + last observation;
14
+ * - admission counts incl. admitted-pain-without-task + promotion tails;
15
+ * - Diagnostician task counts (pending/leased/retry_wait/needs_human_review);
16
+ * - §15 `ready` semantics — "unknown is not reported as healthy".
17
+ *
18
+ * Read-only throughout: this command never mutates workspace state and never
19
+ * opens a transcript (file SIZE stat only, never content).
6
20
  *
7
21
  * CLI gate compliance:
8
22
  * - cli-1: --json outputs exactly one parseable JSON object on stdout.
9
- * - cli-2: exit paths stop execution (return after process.exit).
23
+ * - cli-2: exit paths stop execution.
10
24
  * - cli-5: failure paths do not mutate state (read-only throughout).
11
- * - cli-6: every degraded/refused result includes reason + nextAction.
25
+ * - cli-6: every degraded/unknown section carries reason + nextAction.
12
26
  */
13
27
  import * as fs from 'fs';
14
28
  import * as path from 'path';
15
29
  import * as os from 'os';
16
30
  import { createRequire } from 'module';
17
31
  import { resolveWorkspaceDir } from '../resolve-workspace.js';
18
- import { loadPdConfigForPlugin, resolveNearestPdWorkspace } from '@principles/host-runtime';
19
- import { computeFeatureFlagsFromConfig, isFeatureEnabled } from '@principles/core/runtime-v2';
32
+ import {
33
+ loadPdConfigForPlugin,
34
+ resolveNearestPdWorkspace,
35
+ readCodexIngestionConsent,
36
+ deriveCodexIngestionConsentState,
37
+ listGovernanceCheckpoints,
38
+ readGovernanceObservationStats,
39
+ readGovernanceAdmissionCounts,
40
+ detectLegacyCodexHookRegistration,
41
+ CODEX_INGESTION_DISCLOSURE_VERSION,
42
+ } from '@principles/host-runtime';
43
+ import {
44
+ computeCodexWorkerStatusMode,
45
+ locateCodexTranscriptByRolloutIdentity,
46
+ CODEX_INGESTION_MIN_VERSION,
47
+ CODEX_INGESTION_VERIFIED_VERSION,
48
+ } from '@principles/codex-adapter';
49
+ import { getInstallLayoutPaths, parseInstallManifest } from '@principles/install-layout';
50
+ import { SqliteConnection, SqliteTaskStore, computeFeatureFlagsFromConfig, isFeatureEnabled } from '@principles/core/runtime-v2';
20
51
 
21
52
  const require = createRequire(import.meta.url);
22
53
 
@@ -25,12 +56,17 @@ interface CodexHealthOptions {
25
56
  json?: boolean;
26
57
  }
27
58
 
59
+ type Degradable<T> = T | { reason: string; nextAction: string };
60
+
28
61
  interface CodexHealthReport {
29
62
  generatedAt: string;
30
63
  host: 'codex';
31
64
  workspace: string;
32
65
  adapterVersion: string;
33
66
  runtimeVersion: string;
67
+ codexIngestionMinVersion: string;
68
+ /** G1-verified Codex version (the frozen contract fixtures come from this CLI). */
69
+ codexIngestionVerifiedVersion: string;
34
70
  featureFlag: {
35
71
  name: 'host.codex';
36
72
  enabled: boolean;
@@ -38,6 +74,19 @@ interface CodexHealthReport {
38
74
  reason?: string;
39
75
  nextAction?: string;
40
76
  };
77
+ ingestionFlag: Degradable<{
78
+ name: 'codex_conversation_ingestion';
79
+ enabled: boolean;
80
+ source: 'user_config' | 'defaults' | 'malformed';
81
+ }>;
82
+ consent: Degradable<{
83
+ state: 'granted' | 'revoked' | 'pending' | 'failed' | 'not_present' | 'flag_on_without_grant';
84
+ decidedAt?: string;
85
+ decidedVia?: string;
86
+ disclosureVersion?: string;
87
+ disclosureStale: boolean;
88
+ }>;
89
+ workspaceInit: Degradable<{ initialized: boolean }>;
41
90
  hooksTrust: {
42
91
  detectable: boolean;
43
92
  trusted?: boolean;
@@ -46,11 +95,56 @@ interface CodexHealthReport {
46
95
  };
47
96
  dualRegistration: {
48
97
  detected: boolean;
98
+ legacyAsyncPostToolUse?: boolean;
49
99
  globalHooksPath?: string;
50
100
  pluginHooksPath?: string;
51
101
  reason?: string;
52
102
  nextAction?: string;
53
103
  };
104
+ worker: {
105
+ mode: 'ready' | 'manual_action_required' | 'paused' | 'degraded';
106
+ registeredInInstallManifest: boolean;
107
+ reason?: string;
108
+ nextAction?: string;
109
+ };
110
+ rollouts: Degradable<{
111
+ checkpoints: {
112
+ rolloutIdentity: string;
113
+ byteOffset: number;
114
+ lastOrdinal: number;
115
+ incompleteTail: boolean;
116
+ lastDegradationReason: string | null;
117
+ updatedAt: string;
118
+ /** bytes past the checkpoint in the live transcript file; null = undetectable */
119
+ lagBytes: number | null;
120
+ }[];
121
+ lagUndetectable: boolean;
122
+ }>;
123
+ observations: Degradable<{
124
+ operational: number;
125
+ promoted: number;
126
+ quarantined: number;
127
+ terminalOther: number;
128
+ nextExpiryAt: string | null;
129
+ lastObservationAt: string | null;
130
+ }>;
131
+ admissions: Degradable<{
132
+ admitted: number;
133
+ admittedWithoutTask: number;
134
+ pendingTails: number;
135
+ staleTails: number;
136
+ completedTails: number;
137
+ lastAdmissionAt: string | null;
138
+ }>;
139
+ diagnosticianTasks: Degradable<{
140
+ pending: number;
141
+ leased: number;
142
+ retryWait: number;
143
+ needsHumanReview: number;
144
+ }>;
145
+ /** §15: ready is true only under the full §15 conjunction; unknown ⇒ not ready. */
146
+ ready: boolean;
147
+ readyBlockers: string[];
54
148
  warnings: string[];
55
149
  }
56
150
 
@@ -81,9 +175,9 @@ function detectHooksTrust(codexConfigDir: string | undefined): CodexHealthReport
81
175
  };
82
176
  }
83
177
  // Codex stores hook trust in config.toml under [features] hooks = true|false.
84
- // We do a best-effort text scan rather than a full TOML parse to avoid a new
85
- // dependency. If the file is missing or the hook line is absent, we report
86
- // undetectable with a clear next action.
178
+ // Best-effort text scan (no TOML parser dependency): find the 'hooks' key,
179
+ // then the next '=' and inspect the value token. Deliberately plain string
180
+ // operations no regex over assignment syntax.
87
181
  const configTomlPath = path.join(codexConfigDir, 'config.toml');
88
182
  if (!fs.existsSync(configTomlPath)) {
89
183
  return {
@@ -94,15 +188,30 @@ function detectHooksTrust(codexConfigDir: string | undefined): CodexHealthReport
94
188
  }
95
189
  try {
96
190
  const raw = fs.readFileSync(configTomlPath, 'utf8');
97
- const match = /hooks\s*=\s*(true|false)/i.exec(raw);
98
- if (!match || !match[1]) {
191
+ // Line-by-line scan: a `hooks = <bool>` assignment inside the file, with
192
+ // comment lines skipped — a commented-out `# hooks = false` legacy note
193
+ // must not flip the trust verdict (review round 3).
194
+ let trusted: boolean | undefined;
195
+ for (const rawLine of raw.split('\n')) {
196
+ const line = rawLine.trim();
197
+ if (line.startsWith('#')) continue;
198
+ const lowered = line.toLowerCase();
199
+ const hooksIndex = lowered.indexOf('hooks');
200
+ if (hooksIndex === -1) continue;
201
+ const eqIndex = lowered.indexOf('=', hooksIndex);
202
+ if (eqIndex === -1) continue;
203
+ const tail = lowered.slice(eqIndex + 1, eqIndex + 12).trim();
204
+ if (tail.startsWith('true')) { trusted = true; break; }
205
+ if (tail.startsWith('false')) { trusted = false; break; }
206
+ }
207
+ if (trusted === undefined) {
99
208
  return {
100
209
  detectable: false,
101
210
  reason: 'hooks_setting_not_found_in_config',
102
211
  nextAction: 'Open Codex and run /hooks to trust PD hooks. Codex config.toml exists but has no `hooks` setting under [features].',
103
212
  };
104
213
  }
105
- return { detectable: true, trusted: match[1].toLowerCase() === 'true' };
214
+ return { detectable: true, trusted };
106
215
  } catch (error) {
107
216
  const message = error instanceof Error ? error.message : String(error);
108
217
  return {
@@ -113,63 +222,245 @@ function detectHooksTrust(codexConfigDir: string | undefined): CodexHealthReport
113
222
  }
114
223
  }
115
224
 
225
+ /**
226
+ * Dual-registration detection for the §15/§17 health surface. The legacy
227
+ * predicate itself is the ONE authority in host-runtime
228
+ * (detectLegacyCodexHookRegistration) — shared with the retired installer.
229
+ */
116
230
  function detectDualRegistration(codexConfigDir: string | undefined): CodexHealthReport['dualRegistration'] {
117
231
  const globalHooksPath = codexConfigDir ? path.join(codexConfigDir, 'hooks.json') : undefined;
118
- // Plugin hooks are declared in a plugin manifest; we cannot reliably detect
119
- // them from outside Codex. We only flag the global-hooks path and let the
120
- // operator confirm plugin registration via /hooks in Codex.
121
232
  const globalHooksExists = globalHooksPath ? fs.existsSync(globalHooksPath) : false;
122
- if (globalHooksExists) {
233
+ if (globalHooksExists && globalHooksPath) {
234
+ const legacy = detectLegacyCodexHookRegistration(globalHooksPath);
123
235
  return {
124
236
  detected: true,
237
+ legacyAsyncPostToolUse: legacy.legacyAsyncPostToolUse,
125
238
  globalHooksPath,
126
239
  reason: 'global_hooks_json_present',
127
- nextAction: 'Global ~/.codex/hooks.json is installed. If the PD Codex plugin is also installed via marketplace, this may cause double-registration. Choose ONE: keep global hooks.json (fallback path) OR uninstall it and use the plugin (recommended). To remove global PD entries, run `create-principles-disciple uninstall --host codex`.',
240
+ nextAction: legacy.detected
241
+ ? 'A legacy PD global hook registration was detected. The Marketplace plugin is the only supported new install path (SPEC §17): remove the legacy registration with `create-principles-disciple uninstall --host codex`, then install the principles-disciple Codex plugin.'
242
+ : 'Global ~/.codex/hooks.json is installed. If the PD Codex plugin is also installed via marketplace, this may cause double-registration. Choose ONE: keep global hooks.json (fallback path) OR uninstall it and use the plugin (recommended).',
128
243
  };
129
244
  }
130
245
  return { detected: false };
131
246
  }
132
247
 
248
+ function readInstallManifestRegistration(workspace: string): { registered: boolean; error?: string } {
249
+ try {
250
+ const paths = getInstallLayoutPaths(os.homedir());
251
+ const raw: unknown = JSON.parse(fs.readFileSync(paths.manifest, 'utf8'));
252
+ const parsed = parseInstallManifest(raw);
253
+ if (parsed.manifest !== undefined) {
254
+ const registered = parsed.manifest.workspaces?.some((entry) => path.resolve(entry) === path.resolve(workspace)) ?? false;
255
+ return { registered };
256
+ }
257
+ return { registered: false, error: parsed.error ?? 'install_manifest_invalid' };
258
+ } catch {
259
+ return { registered: false, error: 'install_manifest_unreadable' };
260
+ }
261
+ }
262
+
263
+ /**
264
+ * §15 Diagnostician counts, read from the Runtime V2 task store
265
+ * (taskKind 'diagnostician'). Read-only; degradation is structured.
266
+ */
267
+ async function readDiagnosticianCounts(workspace: string): Promise<CodexHealthReport['diagnosticianTasks']> {
268
+ try {
269
+ const connection = new SqliteConnection(workspace);
270
+ const taskStore = new SqliteTaskStore(connection);
271
+ const count = async (status: 'pending' | 'leased' | 'retry_wait' | 'needs_human_review'): Promise<number> => {
272
+ // Bounded reporting: 1000 far exceeds any realistic per-workspace
273
+ // Diagnostician backlog; a saturated bucket still blocks readiness via
274
+ // needs_human_review/pending semantics rather than hiding.
275
+ const tasks = await taskStore.listTasks({ status, taskKind: 'diagnostician', limit: 1000 });
276
+ return tasks.length;
277
+ };
278
+ const [pending, leased, retryWait, needsHumanReview] = await Promise.all([
279
+ count('pending'), count('leased'), count('retry_wait'), count('needs_human_review'),
280
+ ]);
281
+ return { pending, leased, retryWait, needsHumanReview };
282
+ } catch (error) {
283
+ const message = error instanceof Error ? error.message.slice(0, 160) : String(error);
284
+ return {
285
+ reason: `diagnostician_counts_unavailable: ${message}`,
286
+ nextAction: 'Run `pd runtime init --confirm` if state.db is missing, or inspect the Runtime V2 task store.',
287
+ };
288
+ }
289
+ }
290
+
133
291
  export async function handleHealthCodex(opts: CodexHealthOptions = {}): Promise<void> {
134
292
  const generatedAt = new Date().toISOString();
135
- const workspaceDir = opts.workspace
136
- ? path.resolve(opts.workspace)
137
- : resolveWorkspaceDir();
293
+ const workspaceDir = opts.workspace ? path.resolve(opts.workspace) : resolveWorkspaceDir();
138
294
 
139
295
  const warnings: string[] = [];
296
+ const readyBlockers: string[] = [];
297
+ const noteReadyBlocker = (label: string, reason?: string): void => {
298
+ readyBlockers.push(reason !== undefined ? `${label}: ${reason}` : label);
299
+ };
140
300
 
141
- // Resolve workspace via the shared host-runtime resolver so pd-cli reports
142
- // the same workspace the Codex hook would resolve.
301
+ // ── Workspace config flags + workspace init ──────────────────────────────
143
302
  const resolution = resolveNearestPdWorkspace(workspaceDir);
144
- let resolvedWorkspace: string;
303
+ let resolvedWorkspace = workspaceDir;
145
304
  let featureFlagSource: 'user_config' | 'defaults' | 'malformed';
146
305
  let hostCodexEnabled = false;
306
+ let workspaceInit: CodexHealthReport['workspaceInit'] = { initialized: false, reason: 'workspace_not_resolved', nextAction: 'Run `pd runtime init --confirm` in the workspace.' };
307
+ // ONE config load feeds both flag states + workspace init.
308
+ const configLoad = loadPdConfigForPlugin(resolution.ok ? resolution.workspaceDir : workspaceDir);
147
309
 
148
310
  if (!resolution.ok) {
149
- resolvedWorkspace = workspaceDir;
150
311
  featureFlagSource = 'defaults';
151
312
  warnings.push(`workspace_not_resolved: ${resolution.reason} — ${resolution.nextAction}`);
313
+ noteReadyBlocker('workspace', resolution.reason);
152
314
  } else {
153
315
  resolvedWorkspace = resolution.workspaceDir;
154
- const configLoad = loadPdConfigForPlugin(resolvedWorkspace);
155
316
  featureFlagSource = configLoad.source;
156
317
  const flags = computeFeatureFlagsFromConfig(configLoad.effective);
157
318
  hostCodexEnabled = isFeatureEnabled(flags, 'host.codex');
158
319
  if (!configLoad.ok) {
159
- for (const error of configLoad.errors) {
160
- warnings.push(`config_error: ${error.reason} — ${error.nextAction}`);
320
+ workspaceInit = {
321
+ initialized: false,
322
+ reason: `config_malformed: ${configLoad.errors[0]?.reason ?? 'unknown'}`,
323
+ nextAction: configLoad.errors[0]?.nextAction ?? 'Repair .pd/config.yaml.',
324
+ };
325
+ for (const error of configLoad.errors) warnings.push(`config_error: ${error.reason} — ${error.nextAction}`);
326
+ noteReadyBlocker('workspace', 'config_malformed');
327
+ } else {
328
+ workspaceInit = { initialized: true };
329
+ }
330
+ }
331
+ const ingestionFlag: CodexHealthReport['ingestionFlag'] = configLoad.ok
332
+ ? {
333
+ name: 'codex_conversation_ingestion',
334
+ enabled: isFeatureEnabled(computeFeatureFlagsFromConfig(configLoad.effective), 'codex_conversation_ingestion'),
335
+ source: configLoad.source,
161
336
  }
337
+ : { reason: `config_unreadable: ${configLoad.errors[0]?.reason ?? 'unknown'}`, nextAction: 'Repair .pd/config.yaml so the flag state can be evaluated.' };
338
+ const ingestionEnabled = 'enabled' in ingestionFlag ? ingestionFlag.enabled : false;
339
+
340
+ // ── Consent state (decision metadata only — never captured text) ──────────
341
+ let consent: CodexHealthReport['consent'];
342
+ {
343
+ const read = readCodexIngestionConsent(resolvedWorkspace);
344
+ if (!read.ok) {
345
+ consent = { reason: read.reason, nextAction: read.nextAction };
346
+ noteReadyBlocker('consent', read.reason);
347
+ } else {
348
+ const state = deriveCodexIngestionConsentState(read.record, ingestionEnabled);
349
+ const disclosureStale = read.record !== null && read.record.disclosureVersion !== CODEX_INGESTION_DISCLOSURE_VERSION;
350
+ consent = {
351
+ state,
352
+ disclosureStale,
353
+ ...(read.record !== null
354
+ ? { decidedAt: read.record.decidedAt, decidedVia: read.record.decidedVia, disclosureVersion: read.record.disclosureVersion }
355
+ : {}),
356
+ ...(state === 'flag_on_without_grant'
357
+ ? {
358
+ reason: 'flag_enabled_without_consent_record',
359
+ nextAction: 'The ingestion flag was enabled outside the disclosed consent flow. Run `pd codex setup` to present the disclosure and record (or reverse) the decision.',
360
+ }
361
+ : {}),
362
+ ...(disclosureStale
363
+ ? { reason: 'consent_recorded_for_older_disclosure', nextAction: 'Run `pd codex setup` to review the current disclosure and re-record the decision.' }
364
+ : {}),
365
+ };
366
+ if (ingestionEnabled && state !== 'granted') noteReadyBlocker('consent', state);
162
367
  }
163
368
  }
164
369
 
165
- const adapterVersion = readPackageVersion('@principles/codex-adapter');
166
- const runtimeVersion = readPackageVersion('@principles/host-runtime');
370
+ // ── Worker mode ────────────────────────────────────────────────────────────
371
+ const manifest = readInstallManifestRegistration(resolvedWorkspace);
372
+ const workerEvaluation = computeCodexWorkerStatusMode({ workspaceDir: resolvedWorkspace, registeredInInstallManifest: manifest.registered });
373
+ const worker: CodexHealthReport['worker'] = {
374
+ mode: workerEvaluation.mode,
375
+ registeredInInstallManifest: manifest.registered,
376
+ ...(workerEvaluation.reason !== undefined ? { reason: workerEvaluation.reason } : {}),
377
+ ...(workerEvaluation.nextAction !== undefined ? { nextAction: workerEvaluation.nextAction } : {}),
378
+ };
379
+ if (workerEvaluation.mode === 'degraded') noteReadyBlocker('worker', workerEvaluation.reason);
380
+ if (workerEvaluation.mode === 'manual_action_required') noteReadyBlocker('worker', 'manual_action_required');
381
+ if (manifest.error !== undefined) warnings.push(`install_manifest: ${manifest.error}`);
382
+
383
+ // ── Hook trust + dual registration ─────────────────────────────────────────
167
384
  const codexConfigDir = detectCodexConfigDir();
168
385
  const hooksTrust = detectHooksTrust(codexConfigDir);
169
386
  const dualRegistration = detectDualRegistration(codexConfigDir);
170
-
171
387
  if (hooksTrust.reason) warnings.push(`hooks_trust: ${hooksTrust.reason}`);
172
388
  if (dualRegistration.reason) warnings.push(`dual_registration: ${dualRegistration.reason}`);
389
+ if (hooksTrust.trusted !== true) noteReadyBlocker('hooks_trust', hooksTrust.reason ?? 'untrusted');
390
+
391
+ // ── Per-rollout checkpoints + bounded lag (stat only, never content) ───────
392
+ let rollouts: CodexHealthReport['rollouts'];
393
+ {
394
+ const listed = listGovernanceCheckpoints({ workspaceDir: resolvedWorkspace, hostKind: 'codex' });
395
+ if (listed.ok) {
396
+ const codexHome = process.env.CODEX_HOME ?? path.join(os.homedir(), '.codex');
397
+ let lagUndetectable = false;
398
+ const checkpoints = listed.checkpoints.map((checkpoint) => {
399
+ let lagBytes: number | null = null;
400
+ const lookup = locateCodexTranscriptByRolloutIdentity(codexHome, checkpoint.rolloutIdentity);
401
+ if (lookup.ok) {
402
+ try {
403
+ lagBytes = Math.max(0, fs.statSync(lookup.transcriptPath).size - checkpoint.byteOffset);
404
+ } catch {
405
+ lagUndetectable = true;
406
+ }
407
+ } else {
408
+ lagUndetectable = true;
409
+ }
410
+ return {
411
+ rolloutIdentity: checkpoint.rolloutIdentity,
412
+ byteOffset: checkpoint.byteOffset,
413
+ lastOrdinal: checkpoint.lastOrdinal,
414
+ incompleteTail: checkpoint.incompleteTail,
415
+ lastDegradationReason: checkpoint.lastDegradationReason,
416
+ updatedAt: checkpoint.updatedAt,
417
+ lagBytes,
418
+ };
419
+ });
420
+ rollouts = { checkpoints, lagUndetectable };
421
+ for (const checkpoint of checkpoints) {
422
+ if (checkpoint.incompleteTail) noteReadyBlocker('rollout', `${checkpoint.rolloutIdentity} incomplete_tail`);
423
+ else if (checkpoint.lagBytes !== null && checkpoint.lagBytes > 0) noteReadyBlocker('rollout', `${checkpoint.rolloutIdentity} lag=${checkpoint.lagBytes}B`);
424
+ }
425
+ if (checkpoints.length > 0 && lagUndetectable) {
426
+ warnings.push('rollout_lag_undetectable: the transcript file for at least one checkpoint could not be located (deleted rollout or non-default CODEX_HOME).');
427
+ }
428
+ } else {
429
+ rollouts = { reason: listed.reason, nextAction: listed.nextAction };
430
+ noteReadyBlocker('rollouts', listed.reason);
431
+ }
432
+ }
433
+
434
+ // ── Observation / admission / diagnostician counts ─────────────────────────
435
+ let observations: CodexHealthReport['observations'];
436
+ {
437
+ const stats = readGovernanceObservationStats({ workspaceDir: resolvedWorkspace });
438
+ observations = stats.ok ? stats.stats : { reason: stats.reason, nextAction: stats.nextAction };
439
+ if (!stats.ok) noteReadyBlocker('observations', stats.reason);
440
+ }
441
+ let admissions: CodexHealthReport['admissions'];
442
+ {
443
+ const counts = readGovernanceAdmissionCounts({ workspaceDir: resolvedWorkspace });
444
+ admissions = counts.ok ? counts.counts : { reason: counts.reason, nextAction: counts.nextAction };
445
+ if (!counts.ok) noteReadyBlocker('admissions', counts.reason);
446
+ else if (counts.counts.admittedWithoutTask > 0) {
447
+ noteReadyBlocker('admissions', `${counts.counts.admittedWithoutTask} admitted pain(s) without a Diagnostician task; run pd codex reconcile`);
448
+ }
449
+ }
450
+ const diagnosticianTasks = await readDiagnosticianCounts(resolvedWorkspace);
451
+ if ('pending' in diagnosticianTasks) {
452
+ if (diagnosticianTasks.needsHumanReview > 0) noteReadyBlocker('diagnostician', `${diagnosticianTasks.needsHumanReview} task(s) need human review`);
453
+ } else {
454
+ noteReadyBlocker('diagnostician', diagnosticianTasks.reason);
455
+ }
456
+
457
+ // ── §15 ready conjunction ──────────────────────────────────────────────────
458
+ if (!hostCodexEnabled) noteReadyBlocker('host.codex', 'disabled');
459
+ if (workerEvaluation.mode === 'paused') noteReadyBlocker('worker', workerEvaluation.reason);
460
+ const adapterVersion = readPackageVersion('@principles/codex-adapter');
461
+ const runtimeVersion = readPackageVersion('@principles/host-runtime');
462
+ if (adapterVersion === 'unknown') noteReadyBlocker('adapter', 'version_unknown');
463
+ const ready = readyBlockers.length === 0;
173
464
 
174
465
  const report: CodexHealthReport = {
175
466
  generatedAt,
@@ -177,6 +468,8 @@ export async function handleHealthCodex(opts: CodexHealthOptions = {}): Promise<
177
468
  workspace: resolvedWorkspace,
178
469
  adapterVersion,
179
470
  runtimeVersion,
471
+ codexIngestionMinVersion: CODEX_INGESTION_MIN_VERSION,
472
+ codexIngestionVerifiedVersion: CODEX_INGESTION_VERIFIED_VERSION,
180
473
  featureFlag: {
181
474
  name: 'host.codex',
182
475
  enabled: hostCodexEnabled,
@@ -188,62 +481,96 @@ export async function handleHealthCodex(opts: CodexHealthOptions = {}): Promise<
188
481
  nextAction: `Enable the Codex host adapter by setting features.host.codex.enabled=true in ${resolvedWorkspace}/.pd/config.yaml, then re-run \`pd health --host codex\`.`,
189
482
  }),
190
483
  },
484
+ ingestionFlag,
485
+ consent,
486
+ workspaceInit,
191
487
  hooksTrust,
192
488
  dualRegistration,
489
+ worker,
490
+ rollouts,
491
+ observations,
492
+ admissions,
493
+ diagnosticianTasks,
494
+ ready,
495
+ readyBlockers: readyBlockers.slice(0, 12),
193
496
  warnings,
194
497
  };
195
498
 
196
499
  if (opts.json) {
197
500
  // cli-1: exactly one parseable JSON object on stdout.
198
501
  console.log(JSON.stringify(report, null, 2));
199
- // cli-2: exit-stops. Non-zero only when host.codex is disabled AND hooks
200
- // are not trusted — the operator must act before Codex activation works.
201
- if (!hostCodexEnabled && !hooksTrust.trusted) {
202
- process.exitCode = 1;
203
- }
502
+ // cli-2: exit paths stop execution. Not-ready is the actionable signal.
503
+ if (!ready) process.exitCode = 1;
204
504
  return;
205
505
  }
206
506
 
207
507
  // Text output — still includes explicit nextAction per cli-6.
208
- console.log(`generatedAt: ${report.generatedAt}`);
209
- console.log(`host: ${report.host}`);
210
- console.log(`workspace: ${report.workspace}`);
211
- console.log(`adapterVersion: ${report.adapterVersion}`);
212
- console.log(`runtimeVersion: ${report.runtimeVersion}`);
213
- console.log(`featureFlag.name: ${report.featureFlag.name}`);
214
- console.log(`featureFlag.enabled: ${report.featureFlag.enabled}`);
215
- console.log(`featureFlag.source: ${report.featureFlag.source}`);
216
- if (report.featureFlag.reason) {
217
- console.log(`featureFlag.reason: ${report.featureFlag.reason}`);
218
- console.log(`featureFlag.nextAction: ${report.featureFlag.nextAction ?? ''}`);
219
- }
220
- console.log(`hooksTrust.detectable: ${report.hooksTrust.detectable}`);
221
- if (report.hooksTrust.trusted !== undefined) {
222
- console.log(`hooksTrust.trusted: ${report.hooksTrust.trusted}`);
223
- }
224
- if (report.hooksTrust.reason) {
225
- console.log(`hooksTrust.reason: ${report.hooksTrust.reason}`);
226
- console.log(`hooksTrust.nextAction: ${report.hooksTrust.nextAction ?? ''}`);
227
- }
228
- console.log(`dualRegistration.detected: ${report.dualRegistration.detected}`);
229
- if (report.dualRegistration.globalHooksPath) {
230
- console.log(`dualRegistration.globalHooksPath: ${report.dualRegistration.globalHooksPath}`);
231
- }
232
- if (report.dualRegistration.reason) {
233
- console.log(`dualRegistration.reason: ${report.dualRegistration.reason}`);
234
- console.log(`dualRegistration.nextAction: ${report.dualRegistration.nextAction ?? ''}`);
508
+ const line = (label: string, value: string): void => console.log(`${label}: ${value}`);
509
+ line('generatedAt', report.generatedAt);
510
+ line('host', report.host);
511
+ line('workspace', report.workspace);
512
+ line('adapterVersion', report.adapterVersion);
513
+ line('runtimeVersion', report.runtimeVersion);
514
+ line('codexIngestionMinVersion', report.codexIngestionMinVersion);
515
+ line('codexIngestionVerifiedVersion', report.codexIngestionVerifiedVersion);
516
+ line('featureFlag.host.codex', `${String(report.featureFlag.enabled)} (${report.featureFlag.source})`);
517
+ if ('enabled' in report.ingestionFlag) {
518
+ line('ingestionFlag.codex_conversation_ingestion', `${String(report.ingestionFlag.enabled)} (${report.ingestionFlag.source})`);
519
+ } else {
520
+ line('ingestionFlag', `unknown (${report.ingestionFlag.reason})`);
521
+ line('ingestionFlag.nextAction', report.ingestionFlag.nextAction);
522
+ }
523
+ if ('state' in report.consent) line('consent.state', report.consent.state);
524
+ else {
525
+ line('consent', `unknown (${report.consent.reason})`);
526
+ line('consent.nextAction', report.consent.nextAction);
527
+ }
528
+ const init = report.workspaceInit as { initialized?: boolean; reason?: string };
529
+ line('workspaceInit', init.initialized === true ? 'ok' : `not-initialized (${init.reason ?? 'unknown'})`);
530
+ line('hooksTrust', report.hooksTrust.trusted === undefined ? `undetectable (${report.hooksTrust.reason ?? 'unknown'})` : String(report.hooksTrust.trusted));
531
+ line('dualRegistration', String(report.dualRegistration.detected));
532
+ if (report.dualRegistration.detected) line('dualRegistration.nextAction', report.dualRegistration.nextAction ?? '');
533
+ line('worker.mode', `${report.worker.mode}${report.worker.reason !== undefined ? ` (${report.worker.reason})` : ''}`);
534
+ if ('checkpoints' in report.rollouts) {
535
+ line('rollouts', String(report.rollouts.checkpoints.length));
536
+ for (const checkpoint of report.rollouts.checkpoints.slice(0, 10)) {
537
+ console.log(` - ${checkpoint.rolloutIdentity} lag=${checkpoint.lagBytes === null ? 'unknown' : `${checkpoint.lagBytes}B`} incompleteTail=${String(checkpoint.incompleteTail)} updatedAt=${checkpoint.updatedAt}`);
538
+ }
539
+ } else {
540
+ line('rollouts', `unknown (${report.rollouts.reason})`);
235
541
  }
542
+ if ('operational' in report.observations) {
543
+ line('observations', `operational=${String(report.observations.operational)} promoted=${String(report.observations.promoted)} quarantined=${String(report.observations.quarantined)} terminal=${String(report.observations.terminalOther)}`);
544
+ line('observations.nextExpiryAt', report.observations.nextExpiryAt ?? 'n/a');
545
+ line('observations.lastObservationAt', report.observations.lastObservationAt ?? 'n/a');
546
+ } else {
547
+ line('observations', `unknown (${report.observations.reason})`);
548
+ }
549
+ if ('admitted' in report.admissions) {
550
+ line('admissions', `admitted=${String(report.admissions.admitted)} withoutTask=${String(report.admissions.admittedWithoutTask)} tails pending=${String(report.admissions.pendingTails)}/stale=${String(report.admissions.staleTails)}/completed=${String(report.admissions.completedTails)}`);
551
+ line('admissions.lastAdmissionAt', report.admissions.lastAdmissionAt ?? 'n/a');
552
+ } else {
553
+ line('admissions', `unknown (${report.admissions.reason})`);
554
+ }
555
+ if ('pending' in report.diagnosticianTasks) {
556
+ line('diagnosticianTasks', `pending=${String(report.diagnosticianTasks.pending)} leased=${String(report.diagnosticianTasks.leased)} retryWait=${String(report.diagnosticianTasks.retryWait)} needsHumanReview=${String(report.diagnosticianTasks.needsHumanReview)}`);
557
+ } else {
558
+ line('diagnosticianTasks', `unknown (${report.diagnosticianTasks.reason})`);
559
+ }
560
+ line('ready', `${String(report.ready)}${report.readyBlockers.length > 0 ? ` (blockers: ${report.readyBlockers.join('; ')})` : ''}`);
236
561
  if (report.warnings.length > 0) {
237
- console.log(`warnings:`);
238
- for (const w of report.warnings) console.log(` - ${w}`);
562
+ console.log('warnings:');
563
+ for (const warning of report.warnings) console.log(` - ${warning}`);
239
564
  }
240
565
  console.log('');
241
566
 
567
+ // Product-claim boundary (PRI-625): automatic closure readiness is NOT
568
+ // cross-host signal parity (PRI-632 tracks that separately).
569
+ if (report.ready) {
570
+ console.log('rev2 automatic closure is ready for this workspace. This does NOT claim OpenClaw↔Codex signal-modality parity (see PRI-632).');
571
+ }
242
572
  if (!hostCodexEnabled) {
243
573
  console.warn(`⚠️ host.codex feature flag is disabled. Enable it in ${resolvedWorkspace}/.pd/config.yaml under features.host.codex.enabled to activate Codex hooks.`);
244
574
  }
245
- if (!hooksTrust.trusted && !hooksTrust.detectable) {
246
- console.warn(`⚠️ Hook trust state could not be detected. ${hooksTrust.nextAction ?? ''}`);
247
- process.exitCode = 1;
248
- }
575
+ if (!report.ready) process.exitCode = 1;
249
576
  }