@principles/codex-adapter 0.4.8 → 0.5.1

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.
@@ -0,0 +1,56 @@
1
+ import type { InterventionCapabilityDeclaration } from '@principles/core/runtime-v2';
2
+ /** Evidence adapter surface version (major-series label; exact package version lives in package.json). */
3
+ export declare const CODEX_EVIDENCE_ADAPTER_VERSION = "codex-adapter@2";
4
+ export type EvidenceWarn = (diagnosticLine: string) => void;
5
+ /**
6
+ * Codex capability matrix (SPEC §13.6) — declared, never inferred from
7
+ * record absence. 'supported' requires a proof note; Unknown is an honest
8
+ * state, not a failure (ADR-0027 §2.4).
9
+ */
10
+ export declare function codexCapabilityDeclarations(): InterventionCapabilityDeclaration[];
11
+ export interface CodexPromptDeliveryEvidenceInput {
12
+ workspaceDir: string;
13
+ sessionId: string;
14
+ /** Codex turn_id as carried by the injected-event runId (optional). */
15
+ turnId?: string;
16
+ /** Index-aligned per-principle injection facts from the injected event. */
17
+ injected: readonly {
18
+ principleId: string;
19
+ activationId: string;
20
+ artifactId?: string;
21
+ }[];
22
+ evidenceEnabled: boolean;
23
+ warn: EvidenceWarn;
24
+ }
25
+ /**
26
+ * Record one agent-context delivery attempt per injected principle after the
27
+ * raw injected-event line has been appended to the durable Codex event log —
28
+ * confirmation 'submitted', outcome 'attempted'.
29
+ */
30
+ export declare function recordCodexPromptDeliveryEvidence(input: CodexPromptDeliveryEvidenceInput): void;
31
+ export interface CodexDenyEvidenceInput {
32
+ workspaceDir: string;
33
+ sessionId?: string;
34
+ toolUseId?: string;
35
+ toolName: string;
36
+ activationId?: string;
37
+ principleId?: string;
38
+ ruleId?: string;
39
+ reason?: string;
40
+ evidenceEnabled: boolean;
41
+ warn: EvidenceWarn;
42
+ }
43
+ /**
44
+ * Record the enforcement chain for an ATTRIBUTED deny that was successfully
45
+ * encoded to the Codex stdout channel. The proof boundary is the encoded
46
+ * permissionDecision — PD does not claim the host executed anything broader.
47
+ * Currently dormant while v2 rule enforcement is suspended (PRI-780), but
48
+ * wired so an attributed deny is recorded honestly if one ever occurs.
49
+ *
50
+ * Episode identity requires the per-call toolUseId. Without it the chain is
51
+ * skipped: a hash fallback would mint an episode with NO native event key,
52
+ * which the normalizer rejects (episode_requires_native_event_key) and drops
53
+ * the WHOLE batch. (Codex deny episodes only ever carry toolCallId — unlike
54
+ * OpenClaw they never see a runId — so there is no legitimate fallback here.)
55
+ */
56
+ export declare function recordCodexDenyEvidence(input: CodexDenyEvidenceInput): void;
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Codex Evidence Recorder — the Codex source adapter for the PD v2 Phase 1
3
+ * evidence ledger (ADR-0027). Mirrors the OpenClaw recorder but keeps the
4
+ * Codex honesty boundaries: the subprocess stdout channel proves
5
+ * 'submitted', never host consumption; v2 rule enforcement stays suspended
6
+ * (PRI-780 — no context provider), so enforcement delivery and
7
+ * runtime_verified application are declared Unknown, not Supported; there
8
+ * is no self-report capture channel on Codex — Unsupported, not faked.
9
+ *
10
+ * All writes flow through the shared host-runtime ingress (SPEC §13.7 单一
11
+ * 入口). Best-effort: degradation produces a bounded stderr diagnostic and
12
+ * never changes the hook result.
13
+ */
14
+ import { getInterventionEvidenceIngress } from '@principles/host-runtime';
15
+ /** Evidence adapter surface version (major-series label; exact package version lives in package.json). */
16
+ export const CODEX_EVIDENCE_ADAPTER_VERSION = 'codex-adapter@2';
17
+ /**
18
+ * Codex capability matrix (SPEC §13.6) — declared, never inferred from
19
+ * record absence. 'supported' requires a proof note; Unknown is an honest
20
+ * state, not a failure (ADR-0027 §2.4).
21
+ */
22
+ export function codexCapabilityDeclarations() {
23
+ return [
24
+ {
25
+ hostKind: 'codex', capability: 'agent_context_delivery', status: 'supported',
26
+ adapterVersion: CODEX_EVIDENCE_ADAPTER_VERSION, channel: 'pd-hook:UserPromptSubmit',
27
+ maxConfirmation: 'submitted',
28
+ note: 'additionalContext encoded into the hook stdout hookSpecificOutput; host consumption is not confirmable',
29
+ },
30
+ {
31
+ hostKind: 'codex', capability: 'enforcement_delivery', status: 'unknown',
32
+ adapterVersion: CODEX_EVIDENCE_ADAPTER_VERSION, channel: 'pd-hook:PreToolUse',
33
+ note: 'v2 rule context provider not injected (PRI-780); live rule enforcement stays suspended — no runtime_loaded claims',
34
+ },
35
+ {
36
+ hostKind: 'codex', capability: 'application_runtime_verified', status: 'unknown',
37
+ adapterVersion: CODEX_EVIDENCE_ADAPTER_VERSION, channel: 'pd-hook:PreToolUse',
38
+ note: 'an attributed deny would be recorded after successful stdout encoding; enforcement currently suspended (PRI-780)',
39
+ },
40
+ {
41
+ hostKind: 'codex', capability: 'application_self_report', status: 'unsupported',
42
+ adapterVersion: CODEX_EVIDENCE_ADAPTER_VERSION, channel: 'pd-hook',
43
+ note: 'no self-report capture channel exists on the Codex host; nothing is claimed',
44
+ },
45
+ {
46
+ hostKind: 'codex', capability: 'behavior_observation', status: 'unknown',
47
+ adapterVersion: CODEX_EVIDENCE_ADAPTER_VERSION, channel: 'pd-hook:PreToolUse',
48
+ note: 'tool episodes are recorded only on attributed gate interventions, which are currently suspended (PRI-780)',
49
+ },
50
+ {
51
+ hostKind: 'codex', capability: 'outcome_observation', status: 'unknown',
52
+ adapterVersion: CODEX_EVIDENCE_ADAPTER_VERSION, channel: 'console',
53
+ note: 'no automated outcome source; Phase 1 outcomes enter via Owner console input only',
54
+ },
55
+ ];
56
+ }
57
+ function appendCodexBatch(workspaceDir, observations, warn) {
58
+ if (observations.length === 0)
59
+ return;
60
+ const ingress = getInterventionEvidenceIngress();
61
+ const batch = {
62
+ evidenceScopeId: ingress.evidenceScopeIdFor(workspaceDir),
63
+ sourceKind: 'codex_pd_hook_event_log',
64
+ adapterVersion: CODEX_EVIDENCE_ADAPTER_VERSION,
65
+ recordedAt: new Date().toISOString(),
66
+ observations,
67
+ capabilityDeclarations: codexCapabilityDeclarations(),
68
+ };
69
+ const result = ingress.appendObservationBatch({ workspaceDir, batch });
70
+ if (!result.ok) {
71
+ warn(`[PD:Evidence] codex append degraded: ${result.reason ?? 'unknown'}; next: ${result.nextAction ?? 'replay from durable source'}`);
72
+ }
73
+ }
74
+ /**
75
+ * Record one agent-context delivery attempt per injected principle after the
76
+ * raw injected-event line has been appended to the durable Codex event log —
77
+ * confirmation 'submitted', outcome 'attempted'.
78
+ */
79
+ export function recordCodexPromptDeliveryEvidence(input) {
80
+ if (!input.evidenceEnabled || input.injected.length === 0)
81
+ return;
82
+ const ingress = getInterventionEvidenceIngress();
83
+ const observations = [];
84
+ for (const entry of input.injected) {
85
+ const observationKey = `codex|delivery|agent_context|${input.sessionId}|${input.turnId ?? '-'}|${entry.activationId}`;
86
+ const sourceLocator = `codex-pd-hook-event-log:${input.sessionId}`;
87
+ const existing = ingress.existingObservationRefs(input.workspaceDir, {
88
+ sourceKind: 'codex_pd_hook_event_log', sourceLocator, observationKey,
89
+ principleId: entry.principleId, activationId: entry.activationId, ...(entry.artifactId ? { artifactId: entry.artifactId } : {}),
90
+ });
91
+ const activationRef = existing?.activationRef ?? ingress.resolveActivationOccurrenceRef(input.workspaceDir, entry.activationId);
92
+ if (!activationRef) {
93
+ input.warn(`[PD:Evidence] codex prompt delivery skipped for activation ${entry.activationId}: occurrence snapshot unresolvable`);
94
+ continue;
95
+ }
96
+ if (entry.artifactId !== undefined && activationRef.artifactId !== entry.artifactId) {
97
+ input.warn(`[PD:Evidence] codex prompt delivery skipped for activation ${entry.activationId}: source artifact does not match occurrence`);
98
+ continue;
99
+ }
100
+ const contentRef = existing?.contentRef ?? ingress.resolveInterventionContentRef(input.workspaceDir, activationRef, entry.principleId);
101
+ observations.push({
102
+ observationKey,
103
+ sourceLocator,
104
+ kind: 'delivery',
105
+ nativeRefs: {
106
+ hostKind: 'codex',
107
+ sessionId: input.sessionId,
108
+ ...(input.turnId ? { turnId: input.turnId } : {}),
109
+ },
110
+ principleId: entry.principleId,
111
+ contentRef: {
112
+ principleId: entry.principleId,
113
+ ...(activationRef.artifactId ? { artifactId: activationRef.artifactId } : {}),
114
+ ...(contentRef ? { payloadDigest: contentRef.payloadDigest } : {}),
115
+ resolution: contentRef ? 'resolved' : 'revision_reference_unresolved',
116
+ },
117
+ activationRef,
118
+ payload: { targetKind: 'agent_context', confirmation: 'submitted', outcome: 'attempted' },
119
+ });
120
+ }
121
+ appendCodexBatch(input.workspaceDir, observations, input.warn);
122
+ }
123
+ /**
124
+ * Record the enforcement chain for an ATTRIBUTED deny that was successfully
125
+ * encoded to the Codex stdout channel. The proof boundary is the encoded
126
+ * permissionDecision — PD does not claim the host executed anything broader.
127
+ * Currently dormant while v2 rule enforcement is suspended (PRI-780), but
128
+ * wired so an attributed deny is recorded honestly if one ever occurs.
129
+ *
130
+ * Episode identity requires the per-call toolUseId. Without it the chain is
131
+ * skipped: a hash fallback would mint an episode with NO native event key,
132
+ * which the normalizer rejects (episode_requires_native_event_key) and drops
133
+ * the WHOLE batch. (Codex deny episodes only ever carry toolCallId — unlike
134
+ * OpenClaw they never see a runId — so there is no legitimate fallback here.)
135
+ */
136
+ export function recordCodexDenyEvidence(input) {
137
+ if (!input.activationId || !input.principleId)
138
+ return;
139
+ if (!input.toolUseId) {
140
+ input.warn('[PD:Evidence] codex deny chain skipped: no toolUseId — episode identity would lack a native event key');
141
+ return;
142
+ }
143
+ if (!input.evidenceEnabled)
144
+ return;
145
+ const ingress = getInterventionEvidenceIngress();
146
+ const toolKey = input.toolUseId;
147
+ const sessionPart = input.sessionId ?? '-';
148
+ const deliveryKey = `codex|delivery|enforcement|${sessionPart}|${toolKey}|${input.activationId}`;
149
+ const sourceLocator = `codex-pd-hook-event-log:${sessionPart}`;
150
+ const existing = ingress.existingObservationRefs(input.workspaceDir, {
151
+ sourceKind: 'codex_pd_hook_event_log', sourceLocator, observationKey: deliveryKey,
152
+ principleId: input.principleId, activationId: input.activationId,
153
+ });
154
+ const activationRef = existing?.activationRef ?? ingress.resolveActivationOccurrenceRef(input.workspaceDir, input.activationId);
155
+ if (!activationRef) {
156
+ input.warn(`[PD:Evidence] codex deny chain skipped for activation ${input.activationId}: occurrence snapshot unresolvable`);
157
+ return;
158
+ }
159
+ const episodeKey = `codex|episode|${sessionPart}|${toolKey}`;
160
+ const content = existing?.contentRef ?? ingress.resolveInterventionContentRef(input.workspaceDir, activationRef, input.principleId);
161
+ const contentRef = {
162
+ principleId: input.principleId,
163
+ ...(activationRef.artifactId ? { artifactId: activationRef.artifactId } : {}),
164
+ ...(content ? { payloadDigest: content.payloadDigest } : {}),
165
+ resolution: content ? 'resolved' : 'revision_reference_unresolved',
166
+ };
167
+ const observations = [
168
+ {
169
+ observationKey: deliveryKey,
170
+ sourceLocator,
171
+ kind: 'delivery',
172
+ nativeRefs: {
173
+ hostKind: 'codex',
174
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
175
+ ...(input.toolUseId ? { toolCallId: input.toolUseId } : {}),
176
+ toolName: input.toolName,
177
+ },
178
+ principleId: input.principleId,
179
+ contentRef,
180
+ activationRef,
181
+ payload: { targetKind: 'runtime_enforcement', confirmation: 'runtime_loaded', outcome: 'delivered' },
182
+ },
183
+ {
184
+ observationKey: `codex|application|runtime_verified|${sessionPart}|${toolKey}|${input.activationId}`,
185
+ sourceLocator: `codex-pd-hook-event-log:${sessionPart}`,
186
+ kind: 'application',
187
+ nativeRefs: {
188
+ hostKind: 'codex',
189
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
190
+ ...(input.toolUseId ? { toolCallId: input.toolUseId } : {}),
191
+ toolName: input.toolName,
192
+ },
193
+ principleId: input.principleId,
194
+ activationRef,
195
+ episodeKey,
196
+ payload: { proofMethod: 'runtime_verified', action: 'tool_blocked', enforcementBoundary: 'codex_permission_decision_encoded' },
197
+ },
198
+ {
199
+ observationKey: episodeKey,
200
+ sourceLocator: `codex-pd-hook-event-log:${sessionPart}`,
201
+ kind: 'behavior_episode',
202
+ nativeRefs: {
203
+ hostKind: 'codex',
204
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
205
+ ...(input.toolUseId ? { toolCallId: input.toolUseId } : {}),
206
+ toolName: input.toolName,
207
+ },
208
+ payload: {
209
+ status: 'closed',
210
+ actionSummary: `${input.toolName} denied by rule ${input.ruleId ?? 'unknown'}`,
211
+ resultSummary: 'deny encoded to Codex permission decision',
212
+ },
213
+ },
214
+ {
215
+ observationKey: `codex|effect|${sessionPart}|${toolKey}|${input.activationId}`,
216
+ sourceLocator: `codex-pd-hook-event-log:${sessionPart}`,
217
+ kind: 'effect',
218
+ nativeRefs: {
219
+ hostKind: 'codex',
220
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
221
+ ...(input.toolUseId ? { toolCallId: input.toolUseId } : {}),
222
+ toolName: input.toolName,
223
+ },
224
+ principleId: input.principleId,
225
+ episodeKey,
226
+ contentRef,
227
+ activationRef,
228
+ payload: {
229
+ status: 'observed',
230
+ observationSummary: `rule ${input.ruleId ?? 'unknown'} denied ${input.toolName}`,
231
+ },
232
+ },
233
+ ];
234
+ appendCodexBatch(input.workspaceDir, observations, input.warn);
235
+ }
package/dist/pd-hook.d.ts CHANGED
@@ -5,6 +5,12 @@ export interface PdHookResult {
5
5
  exitCode: number;
6
6
  stderr: string[];
7
7
  }
8
+ /** PD v2 Phase 1: evidence context the emitter needs (subprocess-local). */
9
+ export interface CodexEvidenceContext {
10
+ workspaceDir: string;
11
+ evidenceEnabled: boolean;
12
+ warn: (diagnosticLine: string) => void;
13
+ }
8
14
  export declare function annotateContextWarnings(warnings: readonly string[]): string[];
9
15
  export declare function processHookInvocation(rawStdin: string, _env?: EnvMap, cwd?: string): Promise<PdHookResult>;
10
16
  export {};
package/dist/pd-hook.js CHANGED
@@ -12,6 +12,16 @@ import { CodexHooksHostAdapter } from './host-adapter.js';
12
12
  import { CodexDecoderError, CodexEncoderError } from './codec/index.js';
13
13
  import { ingestCodexConversation } from './ingestion/ingestion.js';
14
14
  import { runGovernanceAdmission } from './ingestion/admission.js';
15
+ import { recordCodexPromptDeliveryEvidence, recordCodexDenyEvidence } from './codex-evidence-recorder.js';
16
+ const MAX_DIAGNOSTIC = 500;
17
+ function diagnostic(reason, nextAction) {
18
+ const boundedReason = reason.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
19
+ const boundedNextAction = nextAction.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
20
+ return `[PD] status=degraded reason=${boundedReason} nextAction=${boundedNextAction}`;
21
+ }
22
+ function errorMessage(error) {
23
+ return error instanceof Error ? error.message.slice(0, MAX_DIAGNOSTIC) : 'unknown_error';
24
+ }
15
25
  function redactStringFields(data) {
16
26
  // rc-8: telemetry is redacted string-field by string field (same policy as
17
27
  // the OpenClaw EventLog redactEventData) — shared by every emitter here.
@@ -27,7 +37,7 @@ function redactStringFields(data) {
27
37
  * writer, so the Codex host path stays independent of the OpenClaw plugin
28
38
  * (codex-adapter must not depend on principles-disciple — bundle guard).
29
39
  */
30
- function codexEventEmitter(stateDir) {
40
+ function codexEventEmitter(stateDir, evidence) {
31
41
  return {
32
42
  recordRuntimeV2ActivationsInjected(data) {
33
43
  appendEventLogLine(stateDir, {
@@ -37,6 +47,31 @@ function codexEventEmitter(stateDir) {
37
47
  sessionId: data.sessionId,
38
48
  data,
39
49
  });
50
+ // PD v2 Phase 1: the durable source line is appended — now record the
51
+ // normalized agent-context delivery attempts (submitted, not delivered).
52
+ // Degrades to a bounded diagnostic; never affects the hook result.
53
+ if (evidence) {
54
+ try {
55
+ const injected = data.principleIds
56
+ .map((principleId, index) => ({
57
+ principleId,
58
+ activationId: data.activationIds[index] ?? '',
59
+ artifactId: data.artifactIds[index],
60
+ }))
61
+ .filter((entry) => entry.activationId.length > 0);
62
+ recordCodexPromptDeliveryEvidence({
63
+ workspaceDir: evidence.workspaceDir,
64
+ sessionId: data.sessionId,
65
+ ...(data.runId ? { turnId: data.runId } : {}),
66
+ injected,
67
+ evidenceEnabled: evidence.evidenceEnabled,
68
+ warn: evidence.warn,
69
+ });
70
+ }
71
+ catch (error) {
72
+ evidence.warn(diagnostic(`codex_evidence_delivery_failed:${errorMessage(error)}`, 'The raw injected event is durable; replay is safe. The hook result is unaffected.'));
73
+ }
74
+ }
40
75
  },
41
76
  recordToolCall(sessionId, data) {
42
77
  appendEventLogLine(stateDir, {
@@ -49,15 +84,6 @@ function codexEventEmitter(stateDir) {
49
84
  },
50
85
  };
51
86
  }
52
- const MAX_DIAGNOSTIC = 500;
53
- function diagnostic(reason, nextAction) {
54
- const boundedReason = reason.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
55
- const boundedNextAction = nextAction.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
56
- return `[PD] status=degraded reason=${boundedReason} nextAction=${boundedNextAction}`;
57
- }
58
- function errorMessage(error) {
59
- return error instanceof Error ? error.message.slice(0, MAX_DIAGNOSTIC) : 'unknown_error';
60
- }
61
87
  /**
62
88
  * PRI-813: admissible evaluation entry = the CANONICAL core schema guard
63
89
  * (rc-1/rc-2, P4: no hand-rolled field copy that could drift from the
@@ -253,6 +279,15 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
253
279
  const ingestionDiagnostics = ingestionEnabled
254
280
  ? await runConversationIngestion({ rawPayload: parsed, kind: event.kind, workspaceDir: resolution.workspaceDir, env: _env })
255
281
  : [];
282
+ // PD v2 Phase 1: evidence context for this subprocess invocation. The
283
+ // ledger flag follows the OpenClaw convention (principle_receipt_ledger
284
+ // gates normalized evidence writes).
285
+ const evidenceDiagnostics = [];
286
+ const evidenceContext = {
287
+ workspaceDir: resolution.workspaceDir,
288
+ evidenceEnabled: flags.principle_receipt_ledger?.enabled === true,
289
+ warn: (line) => evidenceDiagnostics.push(diagnostic(line.replace(/^\[PD:Evidence\] /, 'codex_evidence:'), 'Inspect workspace state.db evidence ledger; the durable raw source allows safe replay.')),
290
+ };
256
291
  // PRI-750: emit shared-path injection/tool events with the host's natural
257
292
  // turn/tool ids (turn_id → runId, tool_use_id → toolCallId) through the core
258
293
  // event-JSONL writer (same events_*.jsonl format as the OpenClaw EventLog;
@@ -262,7 +297,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
262
297
  projectDir: requestedCwd,
263
298
  hostKind: 'codex',
264
299
  toolSemantics: CODEX_TOOL_SEMANTICS,
265
- events: codexEventEmitter(path.join(resolution.workspaceDir, '.state')),
300
+ events: codexEventEmitter(path.join(resolution.workspaceDir, '.state'), evidenceContext),
266
301
  // PRI-780 (revised after Codex review round 2 P1): NO context provider —
267
302
  // v2 rules stay SUSPENDED on Codex (never loaded context-blind). See
268
303
  // annotateContextWarnings for the structured unsupported declaration.
@@ -273,8 +308,56 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
273
308
  // rulehost_evaluated rows, so shadow evidence never reached the
274
309
  // promotion pipeline.
275
310
  const evaluationDiagnostics = recordRuleHostEvaluations(path.join(resolution.workspaceDir, '.state'), event.context.sessionId, result.metadata?.evaluations);
276
- const stderr = [...annotateContextWarnings(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...ingestionDiagnostics];
277
- return { stdout: adapter.encodeOutput(result, event.kind), exitCode: 0, stderr };
311
+ // PD v2 Phase 1: encode BEFORE recording an attributed deny — a
312
+ // runtime_verified application claims only what reached the stdout
313
+ // channel (codex_permission_decision_encoded boundary). Dormant while
314
+ // v2 enforcement is suspended (PRI-780); wired honestly for the day it
315
+ // is not.
316
+ const encoded = adapter.encodeOutput(result, event.kind);
317
+ if (result.decision === 'deny') {
318
+ try {
319
+ let liveActivationId;
320
+ const evaluations = result.metadata?.evaluations;
321
+ if (Array.isArray(evaluations)) {
322
+ for (const entry of evaluations) {
323
+ if (typeof entry !== 'object' || entry === null)
324
+ continue;
325
+ const record = entry;
326
+ if (record.activationMode === 'live' && typeof record.activationId === 'string' && record.activationId.length > 0) {
327
+ ({ activationId: liveActivationId } = record);
328
+ break;
329
+ }
330
+ }
331
+ }
332
+ const { metadata } = result;
333
+ const principleId = typeof metadata?.principleId === 'string' ? metadata.principleId : undefined;
334
+ const ruleId = typeof metadata?.ruleId === 'string' ? metadata.ruleId : undefined;
335
+ const rawPayload = parsed;
336
+ const toolName = typeof rawPayload?.tool_name === 'string'
337
+ ? String(rawPayload.tool_name)
338
+ : 'unknown-tool';
339
+ const toolUseId = typeof rawPayload?.tool_use_id === 'string'
340
+ ? String(rawPayload.tool_use_id)
341
+ : undefined;
342
+ recordCodexDenyEvidence({
343
+ workspaceDir: resolution.workspaceDir,
344
+ sessionId: event.context.sessionId,
345
+ ...(toolUseId ? { toolUseId } : {}),
346
+ toolName,
347
+ activationId: liveActivationId,
348
+ principleId,
349
+ ruleId,
350
+ reason: result.reason,
351
+ evidenceEnabled: evidenceContext.evidenceEnabled,
352
+ warn: evidenceContext.warn,
353
+ });
354
+ }
355
+ catch (error) {
356
+ evidenceDiagnostics.push(diagnostic(`codex_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
357
+ }
358
+ }
359
+ const stderr = [...annotateContextWarnings(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics];
360
+ return { stdout: encoded, exitCode: 0, stderr };
278
361
  }
279
362
  catch (error) {
280
363
  const reason = error instanceof CodexEncoderError ? error.reason : `runtime_failed:${errorMessage(error)}`;
@@ -282,14 +365,75 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
282
365
  return { stdout: {}, exitCode: 0, stderr: [diagnostic(reason, nextAction)] };
283
366
  }
284
367
  }
368
+ // PRI-943: process-boundary fail-open belt. Every resolved path sets exitCode 0,
369
+ // so nothing may let an unwritable stream, an unserializable result, or an
370
+ // escaping rejection reach node's default handling, which terminates the hook
371
+ // with exit 1. Three distinct failure modes, each reproduced from a spawned
372
+ // process in tests/pd-hook-entry-belt.test.ts:
373
+ // * a write that THROWS synchronously — caught per write below;
374
+ // * a host closing the pipe, which raises an ASYNC 'error' event on the
375
+ // Socket. try/catch cannot reach that one, so a listener is required
376
+ // (armStreamBelts) or node aborts with "Unhandled 'error' event".
377
+ // * the stdout JSON object failing to SERIALIZE — guarded separately because
378
+ // the object is the contract (serializeStdout).
379
+ // stdout must stay exactly one JSON object, so a belt diagnostic goes to stderr
380
+ // only; when stderr itself is the dead stream nothing is reported rather than
381
+ // written into the machine channel.
382
+ let beltReported = false;
383
+ let stdoutJsonDelivered = false;
384
+ function writeBeltDiagnostic(reason, nextAction) {
385
+ if (beltReported)
386
+ return;
387
+ beltReported = true;
388
+ try {
389
+ process.stderr.write(`${diagnostic(reason, nextAction)}\n`);
390
+ }
391
+ catch {
392
+ // Both streams are gone: there is no channel left inside the fail-open
393
+ // contract, and adding I/O here would widen the belt itself.
394
+ }
395
+ }
396
+ function reportStreamFailure(error) {
397
+ writeBeltDiagnostic(`hook_stream_failed:${errorMessage(error)}`, 'The host closed the pipe; retry the tool call — the hook failed open.');
398
+ }
399
+ function writeStream(stream, line) {
400
+ try {
401
+ process[stream].write(`${line}\n`);
402
+ // Tracked here rather than at each call site so no future stdout write can
403
+ // make the entry belt believe nothing was delivered yet.
404
+ if (stream === 'stdout')
405
+ stdoutJsonDelivered = true;
406
+ return true;
407
+ }
408
+ catch (error) {
409
+ reportStreamFailure(error);
410
+ return false;
411
+ }
412
+ }
413
+ function armStreamBelts() {
414
+ process.stdout.on('error', reportStreamFailure);
415
+ process.stderr.on('error', reportStreamFailure);
416
+ }
417
+ /** rc-8: the stdout JSON object is the contract itself, so serializing it is a
418
+ * failure path of the belt rather than of the encoder — degrade to `{}` and
419
+ * report, never let the throw escape into the entry belt's last-resort branch. */
420
+ function serializeStdout(value) {
421
+ try {
422
+ return JSON.stringify(value) ?? '{}';
423
+ }
424
+ catch (error) {
425
+ writeBeltDiagnostic(`hook_stdout_serialize_failed:${errorMessage(error)}`, 'Retry the tool call; the hook failed open with an empty JSON object.');
426
+ return '{}';
427
+ }
428
+ }
285
429
  async function main() {
286
430
  let raw;
287
431
  try {
288
432
  raw = readFileSync(0, 'utf8');
289
433
  }
290
434
  catch (error) {
291
- process.stderr.write(`${diagnostic(`stdin_read_failed:${errorMessage(error)}`, 'Run the hook from Codex with JSON stdin.')}\n`);
292
- process.stdout.write('{}\n');
435
+ writeStream('stderr', diagnostic(`stdin_read_failed:${errorMessage(error)}`, 'Run the hook from Codex with JSON stdin.'));
436
+ writeStream('stdout', '{}');
293
437
  return;
294
438
  }
295
439
  let result;
@@ -300,12 +444,16 @@ async function main() {
300
444
  // Fail-open belt for an unexpected pre-dispatch throw (e.g. a workspace
301
445
  // resolution race): Codex must still receive exactly one JSON object on
302
446
  // stdout and a bounded diagnostic on stderr — never a bare crash.
303
- process.stderr.write(`${diagnostic(`hook_pipeline_unexpected:${errorMessage(error)}`, 'Retry the tool call; if it repeats, inspect PD stderr and the Workspace .pd/config.yaml state.')}\n`);
447
+ writeStream('stderr', diagnostic(`hook_pipeline_unexpected:${errorMessage(error)}`, 'Retry the tool call; if it repeats, inspect PD stderr and the Workspace .pd/config.yaml state.'));
304
448
  result = { stdout: {}, exitCode: 0, stderr: [] };
305
449
  }
306
- for (const line of result.stderr)
307
- process.stderr.write(`${line}\n`);
308
- process.stdout.write(`${JSON.stringify(result.stdout)}\n`);
450
+ // Each write is guarded on its own: with stderr dead the stdout JSON object
451
+ // is still what Codex needs to fail open, so one stream must not abort the other.
452
+ for (const line of result.stderr) {
453
+ if (!writeStream('stderr', line))
454
+ break;
455
+ }
456
+ writeStream('stdout', serializeStdout(result.stdout));
309
457
  process.exitCode = result.exitCode;
310
458
  }
311
459
  // PRI-892: Node resolves the main module through symlinks/junctions while
@@ -331,9 +479,19 @@ function isMainModuleEntry() {
331
479
  // satisfies it, because its argv[1] is the runner, not pd-hook.
332
480
  if (path.basename(entry) !== path.basename(fileURLToPath(import.meta.url)))
333
481
  return false;
334
- process.stderr.write(`${diagnostic(`entry_identity_unverified:${errorMessage(error)}`, 'Reinstall the Codex adapter; if it repeats, report this line together with the command that invoked the hook.')}\n`);
482
+ writeStream('stderr', diagnostic(`entry_identity_unverified:${errorMessage(error)}`, 'Reinstall the Codex adapter; if it repeats, report this line together with the command that invoked the hook.'));
335
483
  return true;
336
484
  }
337
485
  }
338
- if (isMainModuleEntry())
339
- void main();
486
+ if (isMainModuleEntry()) {
487
+ armStreamBelts();
488
+ void main().catch((error) => {
489
+ // Last-resort belt: a rejection escaping main's own guards must still leave
490
+ // Codex with exit 0 and, when nothing reached stdout yet, an empty JSON
491
+ // object instead of a bare crash.
492
+ writeBeltDiagnostic(`hook_fatal:${errorMessage(error)}`, 'Retry the tool call; if it repeats, report this line together with the command that invoked the hook.');
493
+ if (!stdoutJsonDelivered)
494
+ writeStream('stdout', '{}');
495
+ process.exitCode = 0;
496
+ });
497
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.4.8",
3
+ "version": "0.5.1",
4
4
  "description": "Codex CLI host adapter for Principles Disciple — implements HostAdapter interface for OpenAI Codex CLI's stdin/stdout JSON hook model (ADR-0020).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -31,8 +31,8 @@
31
31
  "lint": "eslint \"src/**/*.ts\""
32
32
  },
33
33
  "dependencies": {
34
- "@principles/core": "^1.289.0",
35
- "@principles/host-runtime": "^0.7.13",
34
+ "@principles/core": "^1.290.0",
35
+ "@principles/host-runtime": "^0.8.0",
36
36
  "@principles/install-layout": "^0.2.7"
37
37
  },
38
38
  "devDependencies": {