@principles/codex-adapter 0.5.7 → 0.5.9

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.
@@ -59,10 +59,15 @@ function validateCommon(raw, needsTurn) {
59
59
  const sessionId = requiredString(raw, 'session_id');
60
60
  requiredNullableString(raw, 'transcript_path');
61
61
  const workspaceDir = requiredString(raw, 'cwd');
62
- requiredString(raw, 'model');
62
+ // SPEC-PD-MODEL-AWARE-PROMPT-BUDGET-001: keep the VALIDATED model identity
63
+ // (was: checked then discarded). It is an identity string only — never a
64
+ // capacity; the budget resolver turns it into a budget via the installed
65
+ // catalog, falling back to the fixed budget on unknown/ambiguous ids. It
66
+ // must not block the hook or leak into tool allow/deny decisions.
67
+ const modelId = requiredString(raw, 'model');
63
68
  requiredString(raw, 'permission_mode');
64
69
  const turnId = needsTurn ? requiredString(raw, 'turn_id') : undefined;
65
- return { workspaceDir, sessionId, ...(turnId ? { turnId } : {}) };
70
+ return { base: { workspaceDir, sessionId, ...(turnId ? { turnId } : {}) }, modelId };
66
71
  }
67
72
  export function decodeCodexInput(raw) {
68
73
  if (!isRecord(raw))
@@ -71,7 +76,10 @@ export function decodeCodexInput(raw) {
71
76
  const kind = EVENT_KINDS.get(eventName);
72
77
  if (!kind)
73
78
  throw new CodexDecoderError(`unknown hook_event_name "${eventName}"`, 'Configure only PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, or Stop.');
74
- const common = validateCommon(raw, kind !== 'session_start');
79
+ const { base, modelId } = validateCommon(raw, kind !== 'session_start');
80
+ // Model identity rides every event context under modelContext (budget
81
+ // resolution happens on the prompt path; other paths carry it harmlessly).
82
+ const common = { ...base, modelContext: { modelId } };
75
83
  let context;
76
84
  let rawPayload = raw;
77
85
  if (kind === 'before_tool_call' || kind === 'after_tool_call') {
@@ -33,6 +33,7 @@ export declare function buildLiveCorrectionCandidate(args: {
33
33
  export declare function buildLiveToolCandidate(args: {
34
34
  fields: PayloadFields;
35
35
  rolloutIdentity: string;
36
+ projectDir?: string;
36
37
  }): GovernanceSignalCandidate | null;
37
38
  /**
38
39
  * Decoded transcript observations → candidates. User turns carry visibleText;
@@ -56,6 +56,7 @@ export function buildLiveToolCandidate(args) {
56
56
  // CR-01 — `toolUseId` is recorded into tool_calls.tool_use_id and used for
57
57
  // the admission dedup join against the live PostToolUse row.
58
58
  toolUseId: fields.toolUseId,
59
+ ...(args.projectDir !== undefined ? { projectDir: args.projectDir } : {}),
59
60
  ...(fields.toolInput !== undefined ? { toolInput: fields.toolInput } : {}),
60
61
  ...(fields.toolResponse !== undefined ? { toolOutput: fields.toolResponse } : {}),
61
62
  observedAt: new Date().toISOString(),
@@ -23,6 +23,8 @@ import { type GovernanceSignalCandidate } from '@principles/host-runtime';
23
23
  import { type TranscriptPort } from './transcript-decoder.js';
24
24
  export interface CodexIngestionOptions {
25
25
  readonly workspaceDir: string;
26
+ /** Native live-hook cwd; intentionally omitted for transcript catch-up. */
27
+ readonly projectDir?: string;
26
28
  readonly env?: {
27
29
  CODEX_HOME?: string | undefined;
28
30
  };
@@ -13,7 +13,7 @@ export function setCodexTranscriptPortForTest(port) {
13
13
  function activeTranscriptPort(options) {
14
14
  return options.port ?? activePort ?? createNodeTranscriptPort();
15
15
  }
16
- function ingestLiveObservation({ fields, rolloutIdentity, workspaceDir, now }) {
16
+ function ingestLiveObservation({ fields, rolloutIdentity, workspaceDir, projectDir, now }) {
17
17
  const nowIso = now.toISOString();
18
18
  let observation = null;
19
19
  if (fields.turnId !== null && fields.prompt !== null) {
@@ -63,7 +63,7 @@ function ingestLiveObservation({ fields, rolloutIdentity, workspaceDir, now }) {
63
63
  // candidate (SPEC §12) — the caller (pd-hook) runs detection/admission.
64
64
  const candidate = observation.kind === 'user_turn'
65
65
  ? buildLiveCorrectionCandidate({ fields, rolloutIdentity })
66
- : buildLiveToolCandidate({ fields, rolloutIdentity });
66
+ : buildLiveToolCandidate({ fields, rolloutIdentity, ...(projectDir !== undefined ? { projectDir } : {}) });
67
67
  return {
68
68
  status: 'ok', inserted: result.inserted, enriched: result.enriched, duplicates: result.duplicates, warnings: result.warnings, lagBytes: 0,
69
69
  admissionCandidates: candidate !== null ? [candidate] : [],
@@ -256,7 +256,7 @@ export function ingestCodexConversation(rawPayload, kind, options) {
256
256
  return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction, warnings: [] };
257
257
  const now = options.now ?? new Date();
258
258
  if (kind === 'before_prompt_build' || kind === 'after_tool_call') {
259
- return ingestLiveObservation({ fields, rolloutIdentity: validated.rolloutIdentity, workspaceDir: options.workspaceDir, now });
259
+ return ingestLiveObservation({ fields, rolloutIdentity: validated.rolloutIdentity, workspaceDir: options.workspaceDir, ...(options.projectDir !== undefined ? { projectDir: options.projectDir } : {}), now });
260
260
  }
261
261
  return ingestTranscriptDelta({
262
262
  fallbackRootSessionId: fields.sessionId,
package/dist/pd-hook.d.ts CHANGED
@@ -11,6 +11,5 @@ export interface CodexEvidenceContext {
11
11
  evidenceEnabled: boolean;
12
12
  warn: (diagnosticLine: string) => void;
13
13
  }
14
- export declare function annotateContextWarnings(warnings: readonly string[]): string[];
15
14
  export declare function processHookInvocation(rawStdin: string, _env?: EnvMap, cwd?: string): Promise<PdHookResult>;
16
15
  export {};
package/dist/pd-hook.js CHANGED
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import process from 'node:process';
6
6
  import { pathToFileURL, fileURLToPath } from 'node:url';
7
7
  import { appendEventLogLine, redactTelemetryString, isRuleHostEvaluatedEventData } from '@principles/core/runtime-v2';
8
- import { createProductionHostRuntime, loadPdConfigForPlugin, resolveNearestPdWorkspace } from '@principles/host-runtime';
8
+ import { createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveNearestPdWorkspace } from '@principles/host-runtime';
9
9
  import { CODEX_TOOL_SEMANTICS } from './tool-semantics.js';
10
10
  import { computeFeatureFlagsFromConfig } from '@principles/core/runtime-v2';
11
11
  import { CodexHooksHostAdapter } from './host-adapter.js';
@@ -144,26 +144,6 @@ function recordRuleHostEvaluations(stateDir, sessionId, evaluations) {
144
144
  }
145
145
  return diagnostics;
146
146
  }
147
- /**
148
- * PRI-780 Codex capability declaration (structured UNSUPPORTED — suspension
149
- * semantics, revised after Codex review round 2 P1): the Codex host has no
150
- * runtime context provider, and the "unavailable → allow" contract is
151
- * generation-time prompt discipline, NOT a runtime-enforced invariant. Handing
152
- * v2 rules a truthy unavailable-posture context would let a persisted rule
153
- * evaluate context-blind and DENY tool calls that were previously suspended —
154
- * a silent governance behavior change. Codex therefore passes NO context
155
- * provider: the shared gate skips v2 rules with its structured
156
- * `rule_context_v2_unavailable` warning, and this hook annotates that warning
157
- * with the explicit host-unsupported reason before it reaches Codex stderr
158
- * (see annotateContextWarnings — ticket option B: 明确 unsupported + 结构化
159
- * warning, never a silent skip).
160
- */
161
- const CODEX_CONTEXT_UNSUPPORTED_NOTE = 'codex_runtime_context_unsupported: the Codex host provides no runtime context provider; v2 rules stay suspended on this host';
162
- export function annotateContextWarnings(warnings) {
163
- return warnings.map((warning) => warning.startsWith('rule_context_v2_unavailable')
164
- ? `${warning}; ${CODEX_CONTEXT_UNSUPPORTED_NOTE}`
165
- : warning);
166
- }
167
147
  // Bounded governance-observation ingestion (Codex Governance Closure Slice
168
148
  // A) followed by the Slice B signal-admission pass (SPEC §12/§13): detection
169
149
  // → canonical pain → evidence promotion → one pending Diagnostician task.
@@ -175,12 +155,12 @@ export function annotateContextWarnings(warnings) {
175
155
  // canonical derivation first and the production handler's duplicate probe
176
156
  // then converges to a no-op (exactly one pain per real tool call).
177
157
  async function runConversationIngestion(args) {
178
- const { rawPayload, kind, workspaceDir, env } = args;
158
+ const { rawPayload, kind, workspaceDir, projectDir, env } = args;
179
159
  if (kind !== 'turn_complete' && kind !== 'before_prompt_build' && kind !== 'after_tool_call')
180
160
  return [];
181
161
  const diagnostics = [];
182
162
  try {
183
- const outcome = ingestCodexConversation(rawPayload, kind, { workspaceDir, env });
163
+ const outcome = ingestCodexConversation(rawPayload, kind, { workspaceDir, ...(projectDir !== undefined ? { projectDir } : {}), env });
184
164
  if (outcome.status === 'degraded') {
185
165
  diagnostics.push(diagnostic(outcome.reason, outcome.nextAction));
186
166
  }
@@ -229,6 +209,9 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
229
209
  const nextAction = error instanceof CodexDecoderError ? error.nextAction : 'Inspect the Codex 0.147 hook payload.';
230
210
  return { stdout: {}, exitCode: 0, stderr: [diagnostic(reason, nextAction)] };
231
211
  }
212
+ // Capture the PreToolUse boundary before ingestion, governance or runtime
213
+ // work can consume time; history must never include rows written afterwards.
214
+ const hookEpoch = new Date();
232
215
  // Initializing the user workspace explicitly opts Codex into shared
233
216
  // governance. Otherwise preserve the existing per-project resolution.
234
217
  const requestedCwd = event.context.workspaceDir || cwd;
@@ -324,6 +307,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
324
307
  rawPayload: parsed,
325
308
  kind: event.kind,
326
309
  workspaceDir: resolution.workspaceDir,
310
+ projectDir: requestedCwd,
327
311
  env: _env,
328
312
  // CR-07: the explicit path already handled this turn's user prompt —
329
313
  // suppress the generic correction candidate so exactly one writer
@@ -349,10 +333,15 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
349
333
  projectDir: requestedCwd,
350
334
  hostKind: 'codex',
351
335
  toolSemantics: CODEX_TOOL_SEMANTICS,
336
+ ruleContextProvider: createCodexRuleContextProvider({
337
+ workspaceDir: resolution.workspaceDir,
338
+ projectDir: requestedCwd,
339
+ enabled: flags.rulecode_context_v2?.enabled === true && ingestionEnabled,
340
+ cutoffAt: hookEpoch,
341
+ currentToolUseId: event.context.toolCallId ?? '',
342
+ toolSemantics: CODEX_TOOL_SEMANTICS,
343
+ }),
352
344
  events: codexEventEmitter(path.join(resolution.workspaceDir, '.state'), evidenceContext),
353
- // PRI-780 (revised after Codex review round 2 P1): NO context provider —
354
- // v2 rules stay SUSPENDED on Codex (never loaded context-blind). See
355
- // annotateContextWarnings for the structured unsupported declaration.
356
345
  }).dispatch(event);
357
346
  // PRI-813: the shared gate's evaluation facts leave through metadata —
358
347
  // persist them here (telemetry persistence is host-side business; the
@@ -360,11 +349,10 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
360
349
  // rulehost_evaluated rows, so shadow evidence never reached the
361
350
  // promotion pipeline.
362
351
  const evaluationDiagnostics = recordRuleHostEvaluations(path.join(resolution.workspaceDir, '.state'), event.context.sessionId, result.metadata?.evaluations);
363
- // PD v2 Phase 1: encode BEFORE recording an attributed deny — a
364
- // runtime_verified application claims only what reached the stdout
365
- // channel (codex_permission_decision_encoded boundary). Dormant while
366
- // v2 enforcement is suspended (PRI-780); wired honestly for the day it
367
- // is not.
352
+ // Encode before recording an attributed deny: runtime_verified evidence
353
+ // claims only what reached stdout (codex_permission_decision_encoded).
354
+ // V2 rules remain suspended by the shared gate when this provider reports
355
+ // unavailable history; that degraded state is preserved in stderr.
368
356
  const encoded = adapter.encodeOutput(result, event.kind);
369
357
  // CR-07 (A16): the explicit-statement receipt rides as additional context
370
358
  // so the model can answer truthfully about what happened (received +
@@ -419,7 +407,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
419
407
  evidenceDiagnostics.push(diagnostic(`codex_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
420
408
  }
421
409
  }
422
- const stderr = [...annotateContextWarnings(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...explicitDiagnostics, ...ingestionDiagnostics];
410
+ const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...explicitDiagnostics, ...ingestionDiagnostics];
423
411
  return { stdout: encoded, exitCode: 0, stderr };
424
412
  }
425
413
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.5.7",
3
+ "version": "0.5.9",
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",
@@ -33,8 +33,8 @@
33
33
  "lint": "eslint \"src/**/*.ts\""
34
34
  },
35
35
  "dependencies": {
36
- "@principles/core": "^1.293.4",
37
- "@principles/host-runtime": "^0.10.2",
36
+ "@principles/core": "^1.295.0",
37
+ "@principles/host-runtime": "^0.11.0",
38
38
  "@principles/install-layout": "^0.4.0"
39
39
  },
40
40
  "devDependencies": {