@principles/codex-adapter 0.4.7 → 0.5.0
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
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { readFileSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { readFileSync, realpathSync, statSync } from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
import process from 'node:process';
|
|
5
6
|
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
@@ -11,6 +12,16 @@ import { CodexHooksHostAdapter } from './host-adapter.js';
|
|
|
11
12
|
import { CodexDecoderError, CodexEncoderError } from './codec/index.js';
|
|
12
13
|
import { ingestCodexConversation } from './ingestion/ingestion.js';
|
|
13
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
|
+
}
|
|
14
25
|
function redactStringFields(data) {
|
|
15
26
|
// rc-8: telemetry is redacted string-field by string field (same policy as
|
|
16
27
|
// the OpenClaw EventLog redactEventData) — shared by every emitter here.
|
|
@@ -26,7 +37,7 @@ function redactStringFields(data) {
|
|
|
26
37
|
* writer, so the Codex host path stays independent of the OpenClaw plugin
|
|
27
38
|
* (codex-adapter must not depend on principles-disciple — bundle guard).
|
|
28
39
|
*/
|
|
29
|
-
function codexEventEmitter(stateDir) {
|
|
40
|
+
function codexEventEmitter(stateDir, evidence) {
|
|
30
41
|
return {
|
|
31
42
|
recordRuntimeV2ActivationsInjected(data) {
|
|
32
43
|
appendEventLogLine(stateDir, {
|
|
@@ -36,6 +47,31 @@ function codexEventEmitter(stateDir) {
|
|
|
36
47
|
sessionId: data.sessionId,
|
|
37
48
|
data,
|
|
38
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
|
+
}
|
|
39
75
|
},
|
|
40
76
|
recordToolCall(sessionId, data) {
|
|
41
77
|
appendEventLogLine(stateDir, {
|
|
@@ -48,15 +84,6 @@ function codexEventEmitter(stateDir) {
|
|
|
48
84
|
},
|
|
49
85
|
};
|
|
50
86
|
}
|
|
51
|
-
const MAX_DIAGNOSTIC = 500;
|
|
52
|
-
function diagnostic(reason, nextAction) {
|
|
53
|
-
const boundedReason = reason.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
|
|
54
|
-
const boundedNextAction = nextAction.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
|
|
55
|
-
return `[PD] status=degraded reason=${boundedReason} nextAction=${boundedNextAction}`;
|
|
56
|
-
}
|
|
57
|
-
function errorMessage(error) {
|
|
58
|
-
return error instanceof Error ? error.message.slice(0, MAX_DIAGNOSTIC) : 'unknown_error';
|
|
59
|
-
}
|
|
60
87
|
/**
|
|
61
88
|
* PRI-813: admissible evaluation entry = the CANONICAL core schema guard
|
|
62
89
|
* (rc-1/rc-2, P4: no hand-rolled field copy that could drift from the
|
|
@@ -195,11 +222,27 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
195
222
|
const nextAction = error instanceof CodexDecoderError ? error.nextAction : 'Inspect the Codex 0.147 hook payload.';
|
|
196
223
|
return { stdout: {}, exitCode: 0, stderr: [diagnostic(reason, nextAction)] };
|
|
197
224
|
}
|
|
198
|
-
//
|
|
199
|
-
//
|
|
200
|
-
// Workspace's hook into another Workspace's business state.
|
|
225
|
+
// Initializing the user workspace explicitly opts Codex into shared
|
|
226
|
+
// governance. Otherwise preserve the existing per-project resolution.
|
|
201
227
|
const requestedCwd = event.context.workspaceDir || cwd;
|
|
202
|
-
|
|
228
|
+
if (!path.isAbsolute(requestedCwd))
|
|
229
|
+
return { stdout: {}, exitCode: 0, stderr: [diagnostic('cwd_not_absolute', 'Provide the absolute Codex project directory.')] };
|
|
230
|
+
// Resolve like pd-locate.cjs does: a relative CODEX_HOME must yield the same
|
|
231
|
+
// absolute workspace for hooks and owner scripts, or resolveNearestPdWorkspace
|
|
232
|
+
// rejects it after the config check already accepted it.
|
|
233
|
+
const userWorkspace = path.join(path.resolve(_env.CODEX_HOME || path.join(os.homedir(), '.codex')), 'pd-workspace');
|
|
234
|
+
let userWorkspaceInitialized = false;
|
|
235
|
+
try {
|
|
236
|
+
userWorkspaceInitialized = statSync(path.join(userWorkspace, '.pd', 'config.yaml')).isFile();
|
|
237
|
+
if (!userWorkspaceInitialized)
|
|
238
|
+
return { stdout: {}, exitCode: 0, stderr: [diagnostic('user_workspace_config_invalid', 'Repair the user workspace .pd/config.yaml; project configuration was not used.')] };
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
if (!(error instanceof Error && Object.hasOwn(error, 'code') && Reflect.get(error, 'code') === 'ENOENT')) {
|
|
242
|
+
return { stdout: {}, exitCode: 0, stderr: [diagnostic('user_workspace_config_unreadable', 'Restore access to the user workspace .pd/config.yaml; project configuration was not used.')] };
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const resolution = resolveNearestPdWorkspace(userWorkspaceInitialized ? userWorkspace : requestedCwd);
|
|
203
246
|
if (!resolution.ok)
|
|
204
247
|
return { stdout: {}, exitCode: 0, stderr: [diagnostic(resolution.reason, resolution.nextAction)] };
|
|
205
248
|
event = { ...event, context: { ...event.context, workspaceDir: resolution.workspaceDir } };
|
|
@@ -236,15 +279,25 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
236
279
|
const ingestionDiagnostics = ingestionEnabled
|
|
237
280
|
? await runConversationIngestion({ rawPayload: parsed, kind: event.kind, workspaceDir: resolution.workspaceDir, env: _env })
|
|
238
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
|
+
};
|
|
239
291
|
// PRI-750: emit shared-path injection/tool events with the host's natural
|
|
240
292
|
// turn/tool ids (turn_id → runId, tool_use_id → toolCallId) through the core
|
|
241
293
|
// event-JSONL writer (same events_*.jsonl format as the OpenClaw EventLog;
|
|
242
294
|
// the Codex adapter stays independent of the OpenClaw plugin). The line
|
|
243
295
|
// writer appends synchronously — no flush/dispose needed for the subprocess.
|
|
244
296
|
const result = await createProductionHostRuntime({
|
|
297
|
+
projectDir: requestedCwd,
|
|
245
298
|
hostKind: 'codex',
|
|
246
299
|
toolSemantics: CODEX_TOOL_SEMANTICS,
|
|
247
|
-
events: codexEventEmitter(path.join(resolution.workspaceDir, '.state')),
|
|
300
|
+
events: codexEventEmitter(path.join(resolution.workspaceDir, '.state'), evidenceContext),
|
|
248
301
|
// PRI-780 (revised after Codex review round 2 P1): NO context provider —
|
|
249
302
|
// v2 rules stay SUSPENDED on Codex (never loaded context-blind). See
|
|
250
303
|
// annotateContextWarnings for the structured unsupported declaration.
|
|
@@ -255,8 +308,56 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
255
308
|
// rulehost_evaluated rows, so shadow evidence never reached the
|
|
256
309
|
// promotion pipeline.
|
|
257
310
|
const evaluationDiagnostics = recordRuleHostEvaluations(path.join(resolution.workspaceDir, '.state'), event.context.sessionId, result.metadata?.evaluations);
|
|
258
|
-
|
|
259
|
-
|
|
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 };
|
|
260
361
|
}
|
|
261
362
|
catch (error) {
|
|
262
363
|
const reason = error instanceof CodexEncoderError ? error.reason : `runtime_failed:${errorMessage(error)}`;
|
|
@@ -13,6 +13,12 @@ export interface CodexWorkerCycleStepReport {
|
|
|
13
13
|
readonly errorCategory?: string;
|
|
14
14
|
/** PRI-638 P1-C: recovery action for capability-disabled pauses. */
|
|
15
15
|
readonly nextAction?: string;
|
|
16
|
+
/**
|
|
17
|
+
* PRI-917 v0.3.3 review fix (P2-2): candidates parked by the Reuse Review
|
|
18
|
+
* Gate (suspected duplicates awaiting the Owner). Forwarded per-candidate
|
|
19
|
+
* so the report shows WHAT awaits the Owner, not just a degraded status.
|
|
20
|
+
*/
|
|
21
|
+
readonly reuseReviewRequiredCandidateIds?: readonly string[];
|
|
16
22
|
} | null;
|
|
17
23
|
readonly downstream: InternalizationConsumerCycleOutcome | null;
|
|
18
24
|
}
|
|
@@ -156,11 +156,18 @@ export async function runCodexWorkspaceWorkerCycle(options) {
|
|
|
156
156
|
getEnvVar: (name) => process.env[name],
|
|
157
157
|
});
|
|
158
158
|
const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
|
|
159
|
+
// PRI-917 v0.3.3 review fix (P2-2): forward the parked-candidate
|
|
160
|
+
// dispositions so the Owner sees the pending items instead of a bare
|
|
161
|
+
// degraded status with no subject.
|
|
162
|
+
const reuseReviewRequired = (executed.candidateOutcomes ?? [])
|
|
163
|
+
.filter((outcome) => outcome.reason === 'reuse_review_required')
|
|
164
|
+
.map((outcome) => outcome.candidateId);
|
|
159
165
|
diagnostician = {
|
|
160
166
|
taskId: candidate.taskId,
|
|
161
167
|
status: executed.status,
|
|
162
168
|
...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
|
|
163
169
|
...(executed.errorCategory !== undefined ? { errorCategory: executed.errorCategory } : {}),
|
|
170
|
+
...(reuseReviewRequired.length > 0 ? { reuseReviewRequiredCandidateIds: reuseReviewRequired } : {}),
|
|
164
171
|
};
|
|
165
172
|
// The bridge stays cached per workspace (bounded: one per workspace
|
|
166
173
|
// per worker process, exactly like the OpenClaw plugin host) — no
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/codex-adapter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
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.
|
|
35
|
-
"@principles/host-runtime": "^0.
|
|
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": {
|