@principles/codex-adapter 0.5.6 → 0.5.8
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.
- package/dist/ingestion/admission.d.ts +1 -0
- package/dist/ingestion/admission.js +1 -0
- package/dist/ingestion/explicit-owner-statement.d.ts +1 -17
- package/dist/ingestion/explicit-owner-statement.js +1 -21
- package/dist/ingestion/ingestion.d.ts +2 -0
- package/dist/ingestion/ingestion.js +3 -3
- package/dist/pd-hook.d.ts +0 -1
- package/dist/pd-hook.js +20 -32
- package/package.json +3 -3
|
@@ -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(),
|
|
@@ -1,20 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
export declare const CODEX_OWNER_STATEMENT_PREFIX = "PD\u8BB0\u5F55\u75DB\u82E6\uFF1A";
|
|
3
|
-
/** SPEC §6.1: reject instead of truncating the Owner's intent. */
|
|
4
|
-
export declare const MAX_OWNER_STATEMENT_CHARS = 500;
|
|
5
|
-
export type OwnerStatementPrefixParse = {
|
|
6
|
-
matched: false;
|
|
7
|
-
} | {
|
|
8
|
-
matched: true;
|
|
9
|
-
text: string | null;
|
|
10
|
-
reason?: 'statement_empty' | 'statement_too_long';
|
|
11
|
-
};
|
|
12
|
-
/**
|
|
13
|
-
* Deterministic prefix parse of the CURRENT user prompt. `text === null` means
|
|
14
|
-
* the prefix matched but the remainder was empty/blank — an explicit request
|
|
15
|
-
* with no content is a bounded rejection, never a fabricated statement.
|
|
16
|
-
*/
|
|
17
|
-
export declare function parseOwnerStatementPrefix(prompt: unknown): OwnerStatementPrefixParse;
|
|
1
|
+
export { OWNER_STATEMENT_PREFIX as CODEX_OWNER_STATEMENT_PREFIX, MAX_OWNER_STATEMENT_CHARS, parseOwnerStatementPrefix, type OwnerStatementPrefixParse } from '@principles/host-runtime';
|
|
18
2
|
export type RecordOwnerStatementResult = {
|
|
19
3
|
status: 'received';
|
|
20
4
|
painId: string;
|
|
@@ -23,27 +23,7 @@ import { admitGovernanceSignals, ensureGovernanceDiagnosticianTask, promoteAdmit
|
|
|
23
23
|
import { resolveCodexHome } from './codex-home.js';
|
|
24
24
|
import { validateCodexTranscriptPath } from './transcript-path.js';
|
|
25
25
|
import { extractFields } from './ingestion-fields.js';
|
|
26
|
-
|
|
27
|
-
export const CODEX_OWNER_STATEMENT_PREFIX = 'PD记录痛苦:';
|
|
28
|
-
/** SPEC §6.1: reject instead of truncating the Owner's intent. */
|
|
29
|
-
export const MAX_OWNER_STATEMENT_CHARS = 500;
|
|
30
|
-
/**
|
|
31
|
-
* Deterministic prefix parse of the CURRENT user prompt. `text === null` means
|
|
32
|
-
* the prefix matched but the remainder was empty/blank — an explicit request
|
|
33
|
-
* with no content is a bounded rejection, never a fabricated statement.
|
|
34
|
-
*/
|
|
35
|
-
export function parseOwnerStatementPrefix(prompt) {
|
|
36
|
-
if (typeof prompt !== 'string')
|
|
37
|
-
return { matched: false };
|
|
38
|
-
if (!prompt.startsWith(CODEX_OWNER_STATEMENT_PREFIX))
|
|
39
|
-
return { matched: false };
|
|
40
|
-
const remainder = prompt.slice(CODEX_OWNER_STATEMENT_PREFIX.length).trim();
|
|
41
|
-
if (remainder.length === 0)
|
|
42
|
-
return { matched: true, text: null, reason: 'statement_empty' };
|
|
43
|
-
if (remainder.length > MAX_OWNER_STATEMENT_CHARS)
|
|
44
|
-
return { matched: true, text: null, reason: 'statement_too_long' };
|
|
45
|
-
return { matched: true, text: remainder };
|
|
46
|
-
}
|
|
26
|
+
export { OWNER_STATEMENT_PREFIX as CODEX_OWNER_STATEMENT_PREFIX, MAX_OWNER_STATEMENT_CHARS, parseOwnerStatementPrefix } from '@principles/host-runtime';
|
|
47
27
|
/**
|
|
48
28
|
* Persist one explicit Owner statement. The consent-gated conversation
|
|
49
29
|
* ingestion flag does NOT gate this path (no conversation tables or transcript
|
|
@@ -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
|
-
//
|
|
364
|
-
//
|
|
365
|
-
//
|
|
366
|
-
//
|
|
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 = [...
|
|
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.
|
|
3
|
+
"version": "0.5.8",
|
|
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.
|
|
37
|
-
"@principles/host-runtime": "^0.10.
|
|
36
|
+
"@principles/core": "^1.293.5",
|
|
37
|
+
"@principles/host-runtime": "^0.10.3",
|
|
38
38
|
"@principles/install-layout": "^0.4.0"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|