@principles/codex-adapter 0.8.10 → 0.8.12
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.js +2 -0
- package/dist/ingestion/ingestion.d.ts +9 -7
- package/dist/ingestion/ingestion.js +68 -144
- package/dist/ingestion/transcript-decoder.d.ts +35 -44
- package/dist/ingestion/transcript-decoder.js +23 -84
- package/dist/ingestion/transcript-source.d.ts +29 -0
- package/dist/ingestion/transcript-source.js +65 -0
- package/dist/pd-hook.d.ts +9 -2
- package/dist/pd-hook.js +25 -7
- package/dist/tool-semantics.js +5 -1
- package/dist/worker/workspace-worker.js +4 -2
- package/package.json +5 -5
|
@@ -87,6 +87,8 @@ export async function runGovernanceAdmission(args) {
|
|
|
87
87
|
workspaceDir,
|
|
88
88
|
logicalObservationKey: outcome.logicalObservationKey,
|
|
89
89
|
canonicalPainId: outcome.canonicalPainId,
|
|
90
|
+
codexConversationIngestionEnabled: true,
|
|
91
|
+
// Legacy alias: an older installed host-runtime reads only this name.
|
|
90
92
|
conversationIngestionEnabled: true,
|
|
91
93
|
});
|
|
92
94
|
if (!cont.ok) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Codex conversation ingestion orchestrator (Codex Governance Closure
|
|
3
|
-
* Slice A; SPEC rev 2 §7/§9/§17).
|
|
3
|
+
* Slice A; SPEC rev 2 §7/§9/§17; PRI-1171 P1 seam migration).
|
|
4
4
|
*
|
|
5
5
|
* Called by pd-hook ONLY after both `host.codex` and
|
|
6
6
|
* `codex_conversation_ingestion` are enabled — the flag check happens
|
|
@@ -9,18 +9,20 @@
|
|
|
9
9
|
* hard privacy invariant, proven by a port spy test).
|
|
10
10
|
*
|
|
11
11
|
* Responsibilities: extract validated ingestion fields from the raw hook
|
|
12
|
-
* payload (Codex protocol facts live in the adapter, not host-runtime),
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
12
|
+
* payload (Codex protocol facts live in the adapter, not host-runtime), and
|
|
13
|
+
* run the transcript delta through the host-neutral
|
|
14
|
+
* `runConversationIngestion` pipeline with the Codex source adapter
|
|
15
|
+
* (locate/decode/version guard live in transcript-source.ts; the pipeline
|
|
16
|
+
* owns checkpoint, TOCTOU mapping, stop classification, and the store
|
|
17
|
+
* commit). Verified tool outcomes ride the pipeline's pre-ingest hook so a
|
|
18
|
+
* write failure still holds the checkpoint (CR-01 ordering).
|
|
16
19
|
*
|
|
17
20
|
* Stop (`turn_complete`) is the turn-complete ingestion trigger (G1 §2);
|
|
18
21
|
* live `UserPromptSubmit`/`PostToolUse` contribute live observations that
|
|
19
22
|
* the transcript replay later converges with (SPEC §10 source precedence).
|
|
20
23
|
*/
|
|
21
24
|
import type { HostEventKind } from '@principles/core/host';
|
|
22
|
-
import { type GovernanceSignalCandidate } from '@principles/host-runtime';
|
|
23
|
-
import { type TranscriptPort } from './transcript-decoder.js';
|
|
25
|
+
import { type GovernanceSignalCandidate, type TranscriptPort } from '@principles/host-runtime';
|
|
24
26
|
export interface CodexIngestionOptions {
|
|
25
27
|
readonly workspaceDir: string;
|
|
26
28
|
readonly env?: {
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { ingestGovernanceObservations,
|
|
1
|
+
import { ingestGovernanceObservations, recordVerifiedToolOutcomes, runConversationIngestion, } from '@principles/host-runtime';
|
|
2
|
+
import { createNodeTranscriptPort } from './transcript-decoder.js';
|
|
3
|
+
import { createCodexTranscriptSource } from './transcript-source.js';
|
|
2
4
|
import { resolveCodexHome } from './codex-home.js';
|
|
3
5
|
import { validateCodexTranscriptPath } from './transcript-path.js';
|
|
4
|
-
import { classifyCodexVersion, CODEX_VERSION_NEXT_ACTION } from './codex-version.js';
|
|
5
|
-
import { decodeTranscriptWindow, createNodeTranscriptPort, CODEX_INGESTION_MAX_BATCH_BYTES, TranscriptReplacedError } from './transcript-decoder.js';
|
|
6
6
|
import { extractFields } from './ingestion-fields.js';
|
|
7
7
|
import { buildLiveCorrectionCandidate, buildTranscriptCandidates } from './admission.js';
|
|
8
8
|
let activePort = null;
|
|
@@ -72,6 +72,13 @@ function ingestLiveObservation({ fields, rolloutIdentity, workspaceDir, now }) {
|
|
|
72
72
|
rolloutIdentity,
|
|
73
73
|
};
|
|
74
74
|
}
|
|
75
|
+
/** Exact Operator-facing degradation texts the Codex CLI vocabulary owns (quarantine commands etc.). */
|
|
76
|
+
const CODEX_PIPELINE_DEGRADE_TEXTS = {
|
|
77
|
+
readFailedNextAction: 'verify the transcript file still exists and is a regular file inside the Codex sessions root.',
|
|
78
|
+
checkpointInconsistentNextAction: 'the transcript is shorter than the committed checkpoint; quarantine the stale rollout records via `pd codex ingest quarantine` or re-ingest from a fresh rollout.',
|
|
79
|
+
malformedNextAction: 'the record is stable-invalid; quarantine this record via `pd codex ingest quarantine` (dry-run default). Later records remain as lag.',
|
|
80
|
+
oversizedNextAction: 'a single transcript record exceeds the bounded-read window; inspect the rollout file.',
|
|
81
|
+
};
|
|
75
82
|
/**
|
|
76
83
|
* SPEC-CODEX-PAIN-CLOSURE-001 CR-01: project decoded CommandExecution facts
|
|
77
84
|
* onto the shared verified-outcome upgrade. The transcript's model-level call
|
|
@@ -109,138 +116,62 @@ function collectVerifiedToolOutcomes(observations) {
|
|
|
109
116
|
}
|
|
110
117
|
return outcomes;
|
|
111
118
|
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
return { status: 'degraded', reason: 'checkpoint_inconsistent', nextAction: 'the transcript is shorter than the committed checkpoint; quarantine the stale rollout records via `pd codex ingest quarantine` or re-ingest from a fresh rollout.', warnings: [] };
|
|
136
|
-
}
|
|
137
|
-
const byteBoundReached = offset + window.bytes.length < window.fileSize;
|
|
138
|
-
const decoded = decodeTranscriptWindow({
|
|
139
|
-
bytes: window.bytes,
|
|
140
|
-
fileOffset: offset,
|
|
141
|
-
byteBoundReached,
|
|
142
|
-
rolloutIdentity,
|
|
143
|
-
fallbackRootSessionId: existing !== null ? existing.rootSessionId : fallbackRootSessionId,
|
|
144
|
-
nowIso: now.toISOString(),
|
|
145
|
-
});
|
|
146
|
-
// Supported-version guard (SPEC §9): the version signal lives in the
|
|
147
|
-
// transcript session_meta (or the committed checkpoint after the first
|
|
148
|
-
// batch). Anything below the verified floor or above the verified ceiling
|
|
149
|
-
// degrades explicitly — never guess record fields of an unknown contract.
|
|
150
|
-
const cliVersion = decoded.rolloutMeta.cliVersion ?? existing?.cliVersion ?? null;
|
|
151
|
-
const version = classifyCodexVersion(cliVersion);
|
|
152
|
-
if (version.status !== 'supported') {
|
|
153
|
-
return {
|
|
154
|
-
status: 'degraded',
|
|
155
|
-
reason: `${version.reason}:${cliVersion ?? 'unknown'}`,
|
|
156
|
-
nextAction: CODEX_VERSION_NEXT_ACTION,
|
|
157
|
-
warnings: decoded.warnings,
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
const degradations = [];
|
|
161
|
-
if (decoded.stop.kind === 'malformed') {
|
|
162
|
-
degradations.push({ reason: 'transcript_record_malformed', ...(decoded.stop.ordinal !== null ? { ordinal: decoded.stop.ordinal } : {}), nextAction: 'the record is stable-invalid; quarantine this record via `pd codex ingest quarantine` (dry-run default). Later records remain as lag.' });
|
|
163
|
-
}
|
|
164
|
-
else if (decoded.stop.kind === 'oversized_record') {
|
|
165
|
-
degradations.push({ reason: 'transcript_record_too_large', nextAction: 'a single transcript record exceeds the bounded-read window; inspect the rollout file.' });
|
|
166
|
-
}
|
|
167
|
-
const rootSessionId = decoded.rolloutMeta.rootSessionId ?? existing?.rootSessionId ?? fallbackRootSessionId;
|
|
168
|
-
// CR-01: upgrade text-only live observations with the host-verified exit
|
|
169
|
-
// codes BEFORE the checkpoint advances, so a write failure holds the delta
|
|
170
|
-
// and the next Stop retries instead of silently losing the verified facts.
|
|
171
|
-
const verifiedOutcomes = collectVerifiedToolOutcomes(decoded.observations);
|
|
172
|
-
if (verifiedOutcomes.length > 0) {
|
|
173
|
-
// SPEC-RULECODE-HOST-PROMOTION-001 R2: stamp the producing host on the
|
|
174
|
-
// inserted rows so attribution-aware readers can prove provenance.
|
|
175
|
-
const verified = recordVerifiedToolOutcomes({ workspaceDir, sessionId: rootSessionId, outcomes: verifiedOutcomes, hostKind: 'codex' });
|
|
176
|
-
const failed = verified.find((result) => result.status === 'unavailable');
|
|
177
|
-
if (failed !== undefined) {
|
|
178
|
-
const reason = failed.reason === 'trajectory_db_not_found' ? 'verified_outcome_db_unavailable' : `verified_outcome_write_failed:${failed.reason.split(':', 2)[1] ?? ''}`;
|
|
179
|
-
return { status: 'degraded', reason, nextAction: 'inspect the workspace trajectory database; the transcript checkpoint was NOT advanced, the next Stop retries this delta.', warnings: decoded.warnings };
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
const result = ingestGovernanceObservations({
|
|
119
|
+
/**
|
|
120
|
+
* CR-01 rides the pipeline's pre-ingest hook: upgrade text-only live
|
|
121
|
+
* observations with the host-verified exit codes BEFORE the checkpoint
|
|
122
|
+
* advances, so a write failure holds the delta and the next Stop retries
|
|
123
|
+
* instead of silently losing the verified facts.
|
|
124
|
+
*/
|
|
125
|
+
function codexVerifiedOutcomesPreIngest({ workspaceDir, delta, now: _now }) {
|
|
126
|
+
const verifiedOutcomes = collectVerifiedToolOutcomes(delta.observations);
|
|
127
|
+
if (verifiedOutcomes.length === 0)
|
|
128
|
+
return { ok: true };
|
|
129
|
+
// SPEC-RULECODE-HOST-PROMOTION-001 R2: stamp the producing host on the
|
|
130
|
+
// inserted rows so attribution-aware readers can prove provenance.
|
|
131
|
+
const rootSessionId = delta.rollout.rootSessionId ?? '';
|
|
132
|
+
const verified = recordVerifiedToolOutcomes({ workspaceDir, sessionId: rootSessionId, outcomes: verifiedOutcomes, hostKind: 'codex' });
|
|
133
|
+
const failed = verified.find((result) => result.status === 'unavailable');
|
|
134
|
+
if (failed !== undefined) {
|
|
135
|
+
const reason = failed.reason === 'trajectory_db_not_found' ? 'verified_outcome_db_unavailable' : `verified_outcome_write_failed:${failed.reason.split(':', 2)[1] ?? ''}`;
|
|
136
|
+
return { ok: false, reason, nextAction: 'inspect the workspace trajectory database; the transcript checkpoint was NOT advanced, the next Stop retries this delta.' };
|
|
137
|
+
}
|
|
138
|
+
return { ok: true };
|
|
139
|
+
}
|
|
140
|
+
function ingestTranscriptDelta({ fallbackRootSessionId, transcriptPath, workspaceDir, env, now, port }) {
|
|
141
|
+
const outcome = runConversationIngestion({
|
|
183
142
|
workspaceDir,
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
byteOffset: decoded.nextByteOffset,
|
|
197
|
-
lastOrdinal: decoded.lastOrdinal >= 0 ? decoded.lastOrdinal : existing?.lastOrdinal ?? 0,
|
|
198
|
-
cliVersion: cliVersion ?? undefined,
|
|
199
|
-
rootSessionId,
|
|
200
|
-
incompleteTail: decoded.stop.kind === 'incomplete_tail',
|
|
201
|
-
},
|
|
202
|
-
...(degradations.length > 0 ? { degradations } : {}),
|
|
203
|
-
...(decoded.compactionTimestamp !== null ? { compactionTimestamp: decoded.compactionTimestamp } : {}),
|
|
204
|
-
...(decoded.rollbackTurns.length > 0 ? { rollbackTurns: decoded.rollbackTurns } : {}),
|
|
143
|
+
source: createCodexTranscriptSource({ env, fallbackRootSessionId, now }),
|
|
144
|
+
session: { sessionId: fallbackRootSessionId },
|
|
145
|
+
hints: { transcriptPath },
|
|
146
|
+
// PRI-1171 P1 phasing: the double FLAG gate (host.codex ∧
|
|
147
|
+
// codex_conversation_ingestion) is checked by pd-hook / catch-up BEFORE
|
|
148
|
+
// this module is entered, and the consent LEDGER remains the governance
|
|
149
|
+
// record the setup flow enforces (v2 authority model — the runtime gate
|
|
150
|
+
// reads only the flags). The pipeline's consent gate therefore receives
|
|
151
|
+
// the setup-flow invariant 'granted' until the P3 full-text batch wires
|
|
152
|
+
// the real v3 record + disclosureVersion tier.
|
|
153
|
+
flags: { ingestionEnabled: true },
|
|
154
|
+
consent: { decision: 'granted' },
|
|
205
155
|
now,
|
|
156
|
+
port,
|
|
157
|
+
degradeTexts: CODEX_PIPELINE_DEGRADE_TEXTS,
|
|
158
|
+
preIngest: codexVerifiedOutcomesPreIngest,
|
|
206
159
|
});
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
return { status: 'degraded', reason: result.reason ?? 'governance_write_failed', nextAction: result.nextAction ?? 'inspect the workspace trajectory database.', warnings };
|
|
210
|
-
}
|
|
211
|
-
if (decoded.stop.kind === 'incomplete_tail') {
|
|
212
|
-
warnings.push('transcript_incomplete_tail');
|
|
213
|
-
}
|
|
214
|
-
if (decoded.stop.kind === 'malformed') {
|
|
215
|
-
// The store already committed the records before the malformed line and
|
|
216
|
-
// held the checkpoint at it; surface the stable failure loudly (SPEC §14.2).
|
|
217
|
-
return {
|
|
218
|
-
status: 'degraded',
|
|
219
|
-
reason: 'transcript_record_malformed',
|
|
220
|
-
nextAction: 'the record is stable-invalid; quarantine this record via `pd codex ingest quarantine` (dry-run default). Later records remain as lag.',
|
|
221
|
-
warnings,
|
|
222
|
-
};
|
|
223
|
-
}
|
|
224
|
-
if (decoded.stop.kind === 'oversized_record') {
|
|
225
|
-
return {
|
|
226
|
-
status: 'degraded',
|
|
227
|
-
reason: 'transcript_record_too_large',
|
|
228
|
-
nextAction: 'a single transcript record exceeds the bounded-read window; inspect the rollout file.',
|
|
229
|
-
warnings,
|
|
230
|
-
};
|
|
160
|
+
if (outcome.status === 'degraded') {
|
|
161
|
+
return outcome;
|
|
231
162
|
}
|
|
232
163
|
return {
|
|
233
164
|
status: 'ok',
|
|
234
|
-
inserted:
|
|
235
|
-
enriched:
|
|
236
|
-
duplicates:
|
|
237
|
-
warnings,
|
|
238
|
-
lagBytes:
|
|
165
|
+
inserted: outcome.inserted,
|
|
166
|
+
enriched: outcome.enriched,
|
|
167
|
+
duplicates: outcome.duplicates,
|
|
168
|
+
warnings: outcome.warnings,
|
|
169
|
+
lagBytes: outcome.lagBytes,
|
|
239
170
|
// Slice B: transcript-only user turns / tool calls that were never seen
|
|
240
171
|
// live get their admission evaluation here (SPEC §10/§12) — already
|
|
241
172
|
// admitted logical keys no-op on the marker.
|
|
242
|
-
admissionCandidates: buildTranscriptCandidates(
|
|
243
|
-
rolloutIdentity,
|
|
173
|
+
admissionCandidates: buildTranscriptCandidates(outcome.observations),
|
|
174
|
+
rolloutIdentity: outcome.sessionIdentity,
|
|
244
175
|
};
|
|
245
176
|
}
|
|
246
177
|
export function ingestCodexConversation(rawPayload, kind, options) {
|
|
@@ -252,21 +183,22 @@ export function ingestCodexConversation(rawPayload, kind, options) {
|
|
|
252
183
|
// SPEC §9: never scan for another file; keep a neutral degraded result.
|
|
253
184
|
return { status: 'degraded', reason: 'transcript_unavailable', nextAction: 'Codex supplied no transcript for this event; nothing is read or fabricated.', warnings: [] };
|
|
254
185
|
}
|
|
255
|
-
const home = resolveCodexHome(options.env);
|
|
256
|
-
if (!home.ok)
|
|
257
|
-
return { status: 'degraded', reason: home.reason, nextAction: home.nextAction, warnings: [] };
|
|
258
|
-
const validated = validateCodexTranscriptPath(fields.transcriptPath, home.home);
|
|
259
|
-
if (!validated.ok)
|
|
260
|
-
return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction, warnings: [] };
|
|
261
186
|
const now = options.now ?? new Date();
|
|
262
187
|
if (kind === 'before_prompt_build' || kind === 'after_tool_call') {
|
|
188
|
+
// Live observations key on the rollout identity derived from the SAME
|
|
189
|
+
// validated transcript reference the Stop replay later converges with
|
|
190
|
+
// (SPEC §10) — validate here exactly as before the seam migration.
|
|
191
|
+
const home = resolveCodexHome(options.env);
|
|
192
|
+
if (!home.ok)
|
|
193
|
+
return { status: 'degraded', reason: home.reason, nextAction: home.nextAction, warnings: [] };
|
|
194
|
+
const validated = validateCodexTranscriptPath(fields.transcriptPath, home.home);
|
|
195
|
+
if (!validated.ok)
|
|
196
|
+
return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction, warnings: [] };
|
|
263
197
|
return ingestLiveObservation({ fields, rolloutIdentity: validated.rolloutIdentity, workspaceDir: options.workspaceDir, now });
|
|
264
198
|
}
|
|
265
199
|
return ingestTranscriptDelta({
|
|
266
200
|
fallbackRootSessionId: fields.sessionId,
|
|
267
|
-
|
|
268
|
-
identity: validated.identity,
|
|
269
|
-
rolloutIdentity: validated.rolloutIdentity,
|
|
201
|
+
transcriptPath: fields.transcriptPath,
|
|
270
202
|
workspaceDir: options.workspaceDir,
|
|
271
203
|
env: options.env ?? {},
|
|
272
204
|
now,
|
|
@@ -282,17 +214,9 @@ export function ingestCodexConversation(rawPayload, kind, options) {
|
|
|
282
214
|
* previously-authenticated rollouts (checkpoints), never discovered sessions.
|
|
283
215
|
*/
|
|
284
216
|
export function ingestCodexTranscriptFromPath(args) {
|
|
285
|
-
const home = resolveCodexHome(args.env);
|
|
286
|
-
if (!home.ok)
|
|
287
|
-
return { status: 'degraded', reason: home.reason, nextAction: home.nextAction, warnings: [] };
|
|
288
|
-
const validated = validateCodexTranscriptPath(args.transcriptPath, home.home);
|
|
289
|
-
if (!validated.ok)
|
|
290
|
-
return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction, warnings: [] };
|
|
291
217
|
return ingestTranscriptDelta({
|
|
292
218
|
fallbackRootSessionId: args.fallbackRootSessionId,
|
|
293
|
-
|
|
294
|
-
identity: validated.identity,
|
|
295
|
-
rolloutIdentity: validated.rolloutIdentity,
|
|
219
|
+
transcriptPath: args.transcriptPath,
|
|
296
220
|
workspaceDir: args.workspaceDir,
|
|
297
221
|
env: args.env ?? {},
|
|
298
222
|
now: args.now ?? new Date(),
|
|
@@ -1,47 +1,38 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
}
|
|
36
|
-
kind: 'incomplete_tail';
|
|
37
|
-
} | {
|
|
38
|
-
kind: 'malformed';
|
|
39
|
-
ordinal: number | null;
|
|
40
|
-
} | {
|
|
41
|
-
kind: 'byte_bound';
|
|
42
|
-
} | {
|
|
43
|
-
kind: 'oversized_record';
|
|
44
|
-
};
|
|
1
|
+
/**
|
|
2
|
+
* Codex rollout transcript incremental decoder (Codex Governance Closure
|
|
3
|
+
* Slice A; SPEC rev 2 §9, G1 probe report §6).
|
|
4
|
+
*
|
|
5
|
+
* Decodes a bounded byte window from the durable checkpoint offset and
|
|
6
|
+
* projects ONLY governance-relevant visible facts (SPEC §12 privacy
|
|
7
|
+
* boundary): genuine visible user messages (`content_item_kinds[0] ===
|
|
8
|
+
* "user.text"` — host-injected context arrives as user-role records with
|
|
9
|
+
* other kinds), visible assistant commentary/final messages, and tool
|
|
10
|
+
* execution facts anchored on the `event_msg item_completed
|
|
11
|
+
* CommandExecution` record whose `item.id` IS the hook `tool_use_id` id
|
|
12
|
+
* space (the G1-verified bridge; the model-level `call_id` is a different
|
|
13
|
+
* space). Hidden reasoning, system/developer prompts, world_state,
|
|
14
|
+
* host-injected context, and unknown record bodies are identified by shape
|
|
15
|
+
* and dropped before persistence — never projected, logged, or emitted.
|
|
16
|
+
*
|
|
17
|
+
* Failure classes are distinct (SPEC §14): an incomplete final line (no
|
|
18
|
+
* trailing newline at EOF) is a transient append/flush boundary — the
|
|
19
|
+
* checkpoint does not advance past it and the next ingestion retries; a
|
|
20
|
+
* complete line that fails JSON parsing or envelope validation is a stable
|
|
21
|
+
* malformed record — decoding stops at it without advancing, with a
|
|
22
|
+
* structured reason. Unknown-but-well-formed record types are skipped with
|
|
23
|
+
* a bounded warning and DO advance.
|
|
24
|
+
*
|
|
25
|
+
* PRI-1171 P1: the host-neutral skeleton (TranscriptPort with post-open
|
|
26
|
+
* identity revalidation, batch bounds, stop taxonomy, and the
|
|
27
|
+
* newline-window/incomplete-tail plan) moved to
|
|
28
|
+
* host-runtime/conversation-ingestion/source.ts; this module keeps ONLY the
|
|
29
|
+
* Codex-specific record projection and re-exports the moved names for one
|
|
30
|
+
* version cycle. Behavior is byte-identical (locked by the existing
|
|
31
|
+
* ingestion fixtures).
|
|
32
|
+
*/
|
|
33
|
+
import { type GovernanceObservationInput, type TranscriptDecodeStop } from '@principles/host-runtime';
|
|
34
|
+
export { CONVERSATION_INGESTION_MAX_BATCH_BYTES as CODEX_INGESTION_MAX_BATCH_BYTES, CONVERSATION_INGESTION_MAX_BATCH_RECORDS as CODEX_INGESTION_MAX_BATCH_RECORDS, TranscriptReplacedError, createNodeTranscriptPort, } from '@principles/host-runtime';
|
|
35
|
+
export type { TranscriptReadResult, TranscriptExpectedIdentity, TranscriptReadRequest, TranscriptPort, TranscriptDecodeStop, } from '@principles/host-runtime';
|
|
45
36
|
export interface DecodedDelta {
|
|
46
37
|
readonly observations: readonly GovernanceObservationInput[];
|
|
47
38
|
readonly rolloutMeta: {
|
|
@@ -21,69 +21,18 @@
|
|
|
21
21
|
* malformed record — decoding stops at it without advancing, with a
|
|
22
22
|
* structured reason. Unknown-but-well-formed record types are skipped with
|
|
23
23
|
* a bounded warning and DO advance.
|
|
24
|
+
*
|
|
25
|
+
* PRI-1171 P1: the host-neutral skeleton (TranscriptPort with post-open
|
|
26
|
+
* identity revalidation, batch bounds, stop taxonomy, and the
|
|
27
|
+
* newline-window/incomplete-tail plan) moved to
|
|
28
|
+
* host-runtime/conversation-ingestion/source.ts; this module keeps ONLY the
|
|
29
|
+
* Codex-specific record projection and re-exports the moved names for one
|
|
30
|
+
* version cycle. Behavior is byte-identical (locked by the existing
|
|
31
|
+
* ingestion fixtures).
|
|
24
32
|
*/
|
|
25
|
-
import
|
|
26
|
-
|
|
27
|
-
export
|
|
28
|
-
/** Thrown by the port when the opened object is not the validated one (replacement/TOCTOU). */
|
|
29
|
-
export class TranscriptReplacedError extends Error {
|
|
30
|
-
constructor() {
|
|
31
|
-
super('transcript_replaced_after_validation');
|
|
32
|
-
this.name = 'TranscriptReplacedError';
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
function identityMatches(opened, expected) {
|
|
36
|
-
// Size+mtime fingerprint must ALWAYS hold. When the platform reports a
|
|
37
|
-
// Number-safe inode on both sides, the inode must match too (it is what
|
|
38
|
-
// catches delete+recreate replacements whose inode got reused on Linux CI
|
|
39
|
-
// with a same-ms write; a same-size same-ms recreate remains outside the
|
|
40
|
-
// threat model for an append-only host-owned file). On platforms whose
|
|
41
|
-
// ino exceeds Number.MAX_SAFE_INTEGER (Windows file IDs), the inode is not
|
|
42
|
-
// reliably comparable and the fingerprint alone decides. A false refusal
|
|
43
|
-
// is the safe direction: the hook degrades observably and the next Stop
|
|
44
|
-
// revalidates and retries.
|
|
45
|
-
if (opened.size !== expected.size || opened.mtimeMs !== expected.mtimeMs)
|
|
46
|
-
return false;
|
|
47
|
-
const comparableIno = expected.ino !== 0 && expected.dev !== 0
|
|
48
|
-
&& opened.ino !== 0 && Number.isSafeInteger(expected.ino) && Number.isSafeInteger(opened.ino);
|
|
49
|
-
if (comparableIno)
|
|
50
|
-
return opened.ino === expected.ino && opened.dev === expected.dev;
|
|
51
|
-
return true;
|
|
52
|
-
}
|
|
53
|
-
export function createNodeTranscriptPort() {
|
|
54
|
-
return {
|
|
55
|
-
read({ canonicalPath, offset, maxBytes, expectedIdentity }) {
|
|
56
|
-
const fd = fs.openSync(canonicalPath, 'r');
|
|
57
|
-
try {
|
|
58
|
-
// Post-open revalidation (G1 §7 / SPEC §9): fstat the OPEN OBJECT —
|
|
59
|
-
// not the path — and re-prove it is the regular file the validator
|
|
60
|
-
// approved, still at the expected identity. A path swapped between
|
|
61
|
-
// validation and open (replacement/symlink TOCTOU) is refused before
|
|
62
|
-
// a single byte is read.
|
|
63
|
-
const stats = fs.fstatSync(fd);
|
|
64
|
-
if (!stats.isFile())
|
|
65
|
-
throw new Error('transcript_is_not_regular_file');
|
|
66
|
-
if (expectedIdentity !== undefined && !identityMatches(stats, expectedIdentity)) {
|
|
67
|
-
throw new TranscriptReplacedError();
|
|
68
|
-
}
|
|
69
|
-
const length = Math.max(0, Math.min(maxBytes, stats.size - offset));
|
|
70
|
-
if (length === 0)
|
|
71
|
-
return { bytes: Buffer.alloc(0), fileSize: stats.size };
|
|
72
|
-
const buffer = Buffer.alloc(length);
|
|
73
|
-
const bytesRead = fs.readSync(fd, buffer, 0, length, offset);
|
|
74
|
-
// Post-read byte bound re-verification (EP-08): never trust the
|
|
75
|
-
// pre-read stat for the enforced cap.
|
|
76
|
-
const actual = bytesRead < 0 ? 0 : bytesRead;
|
|
77
|
-
if (actual > maxBytes)
|
|
78
|
-
throw new Error('transcript_read_exceeded_bound');
|
|
79
|
-
return { bytes: buffer.subarray(0, actual), fileSize: stats.size };
|
|
80
|
-
}
|
|
81
|
-
finally {
|
|
82
|
-
fs.closeSync(fd);
|
|
83
|
-
}
|
|
84
|
-
},
|
|
85
|
-
};
|
|
86
|
-
}
|
|
33
|
+
import { CONVERSATION_INGESTION_MAX_BATCH_RECORDS, planJsonlWindow, } from '@principles/host-runtime';
|
|
34
|
+
// Compat re-exports (one version cycle): the seam owns the skeleton now.
|
|
35
|
+
export { CONVERSATION_INGESTION_MAX_BATCH_BYTES as CODEX_INGESTION_MAX_BATCH_BYTES, CONVERSATION_INGESTION_MAX_BATCH_RECORDS as CODEX_INGESTION_MAX_BATCH_RECORDS, TranscriptReplacedError, createNodeTranscriptPort, } from '@principles/host-runtime';
|
|
87
36
|
function isRecord(value) {
|
|
88
37
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
89
38
|
}
|
|
@@ -426,26 +375,16 @@ export function decodeTranscriptWindow(input) {
|
|
|
426
375
|
if (bytes.length === 0) {
|
|
427
376
|
return { ...finish(context, input.fileOffset, -1), stop: { kind: 'eof' } };
|
|
428
377
|
}
|
|
429
|
-
//
|
|
430
|
-
//
|
|
431
|
-
|
|
432
|
-
const
|
|
433
|
-
const tailBytes = bytes.subarray(completeEnd); // bytes after the final newline (no terminator)
|
|
434
|
-
let cursor = input.fileOffset;
|
|
378
|
+
// PRI-1171: the newline-window split (complete lines + unterminated tail)
|
|
379
|
+
// comes from the seam's planJsonlWindow — the same byte-exact
|
|
380
|
+
// incomplete-tail semantics every host inherits.
|
|
381
|
+
const plan = planJsonlWindow(bytes, input.fileOffset);
|
|
435
382
|
let lastOrdinal = -1;
|
|
436
383
|
let recordsConsumed = 0;
|
|
437
|
-
|
|
438
|
-
while (lineStart < completeEnd) {
|
|
439
|
-
const lineEnd = bytes.indexOf(0x0a, lineStart);
|
|
440
|
-
if (lineEnd === -1 || lineEnd >= completeEnd)
|
|
441
|
-
break;
|
|
442
|
-
const lineBytes = bytes.subarray(lineStart, lineEnd);
|
|
443
|
-
const recordByteStart = cursor;
|
|
444
|
-
cursor = input.fileOffset + lineEnd + 1;
|
|
445
|
-
lineStart = lineEnd + 1;
|
|
384
|
+
for (const { bytes: lineBytes, recordByteStart } of plan.lines) {
|
|
446
385
|
if (lineBytes.length === 0 || lineBytes.toString('utf8').trim().length === 0)
|
|
447
386
|
continue;
|
|
448
|
-
if (recordsConsumed >=
|
|
387
|
+
if (recordsConsumed >= CONVERSATION_INGESTION_MAX_BATCH_RECORDS) {
|
|
449
388
|
return { ...finish(context, recordByteStart, lastOrdinal), stop: { kind: 'byte_bound' } };
|
|
450
389
|
}
|
|
451
390
|
const line = decodeLine(lineBytes);
|
|
@@ -459,27 +398,27 @@ export function decodeTranscriptWindow(input) {
|
|
|
459
398
|
lastOrdinal = line.ordinal;
|
|
460
399
|
projectRecord(context, { type: line.type, payload: line.payload ?? {}, ordinal: line.ordinal, recordByteStart, timestamp: line.timestamp });
|
|
461
400
|
}
|
|
462
|
-
if (
|
|
463
|
-
const tailStart =
|
|
401
|
+
if (plan.tail !== null) {
|
|
402
|
+
const tailStart = plan.tail.startOffset; // byte offset where the unterminated tail begins
|
|
464
403
|
if (input.byteBoundReached) {
|
|
465
404
|
// The window ended mid-line because of the byte bound — the line is not
|
|
466
405
|
// known-incomplete; leave it wholly unread and report bounded lag.
|
|
467
|
-
if (
|
|
406
|
+
if (plan.lines.length === 0) {
|
|
468
407
|
return { ...finish(context, input.fileOffset, lastOrdinal), stop: { kind: 'oversized_record' } };
|
|
469
408
|
}
|
|
470
409
|
return { ...finish(context, tailStart, lastOrdinal), stop: { kind: 'byte_bound' } };
|
|
471
410
|
}
|
|
472
|
-
const line = decodeLine(
|
|
411
|
+
const line = decodeLine(plan.tail.bytes);
|
|
473
412
|
if (line.record !== null && line.type !== null) {
|
|
474
413
|
// A parseable final line without a trailing newline is a complete
|
|
475
414
|
// record; consume it and advance the checkpoint to EOF.
|
|
476
415
|
lastOrdinal = line.ordinal;
|
|
477
416
|
projectRecord(context, { type: line.type, payload: line.payload ?? {}, ordinal: line.ordinal, recordByteStart: tailStart, timestamp: line.timestamp });
|
|
478
|
-
return { ...finish(context, tailStart +
|
|
417
|
+
return { ...finish(context, tailStart + plan.tail.bytes.length, lastOrdinal), stop: { kind: 'eof' } };
|
|
479
418
|
}
|
|
480
419
|
// Incomplete final line: transient append/flush boundary — do not
|
|
481
420
|
// advance past the previous record; the next ingestion retries (SPEC §14.1).
|
|
482
421
|
return { ...finish(context, tailStart, lastOrdinal), stop: { kind: 'incomplete_tail' } };
|
|
483
422
|
}
|
|
484
|
-
return { ...finish(context,
|
|
423
|
+
return { ...finish(context, plan.completeEndOffset, lastOrdinal), stop: input.byteBoundReached ? { kind: 'byte_bound' } : { kind: 'eof' } };
|
|
485
424
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codex transcript source adapter for the host-neutral conversation-ingestion
|
|
3
|
+
* seam (PRI-1171 P1; SPEC v0.2 §4.1/§4.4).
|
|
4
|
+
*
|
|
5
|
+
* Everything Codex-specific about LOCATING and DECODING a rollout lives here:
|
|
6
|
+
* - locate: Codex home resolution + `validateCodexTranscriptPath`
|
|
7
|
+
* containment and pre-open identity capture (SPEC §9 — never scan for
|
|
8
|
+
* another file);
|
|
9
|
+
* - decodeWindow: the rollout record projection (transcript-decoder.ts)
|
|
10
|
+
* plus the supported-version guard, expressed as the seam's data-shaped
|
|
11
|
+
* `guard` verdict so the pipeline can refuse a delta without ingesting
|
|
12
|
+
* or advancing the checkpoint;
|
|
13
|
+
* - rollout lineage (root session / parent / agent / depth / cliVersion)
|
|
14
|
+
* resolved with the committed checkpoint as fallback, exactly as the
|
|
15
|
+
* pre-seam orchestrator did (behavior lock).
|
|
16
|
+
*
|
|
17
|
+
* The seam (host-runtime/conversation-ingestion) stays format-agnostic; this
|
|
18
|
+
* is the per-host thin half of "one decoder per host".
|
|
19
|
+
*/
|
|
20
|
+
import type { TranscriptSourceAdapter } from '@principles/host-runtime';
|
|
21
|
+
export interface CodexTranscriptSourceContext {
|
|
22
|
+
readonly env: {
|
|
23
|
+
CODEX_HOME?: string | undefined;
|
|
24
|
+
};
|
|
25
|
+
/** Hook-payload session id — the last-ditch root-session fallback (G1 §4). */
|
|
26
|
+
readonly fallbackRootSessionId: string;
|
|
27
|
+
readonly now: Date;
|
|
28
|
+
}
|
|
29
|
+
export declare function createCodexTranscriptSource(context: CodexTranscriptSourceContext): TranscriptSourceAdapter;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { resolveCodexHome } from './codex-home.js';
|
|
2
|
+
import { validateCodexTranscriptPath } from './transcript-path.js';
|
|
3
|
+
import { classifyCodexVersion, CODEX_VERSION_NEXT_ACTION } from './codex-version.js';
|
|
4
|
+
import { decodeTranscriptWindow } from './transcript-decoder.js';
|
|
5
|
+
export function createCodexTranscriptSource(context) {
|
|
6
|
+
return {
|
|
7
|
+
hostKind: 'codex',
|
|
8
|
+
locate(_session, hints) {
|
|
9
|
+
const home = resolveCodexHome(context.env);
|
|
10
|
+
if (!home.ok)
|
|
11
|
+
return { status: 'degraded', reason: home.reason, nextAction: home.nextAction };
|
|
12
|
+
if (typeof hints.transcriptPath !== 'string' || hints.transcriptPath.length === 0) {
|
|
13
|
+
// SPEC §9: never scan for another file; keep a neutral degraded result.
|
|
14
|
+
return { status: 'degraded', reason: 'transcript_unavailable', nextAction: 'Codex supplied no transcript for this event; nothing is read or fabricated.' };
|
|
15
|
+
}
|
|
16
|
+
const validated = validateCodexTranscriptPath(hints.transcriptPath, home.home);
|
|
17
|
+
if (!validated.ok)
|
|
18
|
+
return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction };
|
|
19
|
+
return {
|
|
20
|
+
status: 'ok',
|
|
21
|
+
filePath: validated.canonicalPath,
|
|
22
|
+
expectedIdentity: validated.identity,
|
|
23
|
+
sessionIdentity: validated.rolloutIdentity,
|
|
24
|
+
};
|
|
25
|
+
},
|
|
26
|
+
decodeWindow(locator, window, checkpoint) {
|
|
27
|
+
const decoded = decodeTranscriptWindow({
|
|
28
|
+
bytes: window.bytes,
|
|
29
|
+
fileOffset: window.fileOffset,
|
|
30
|
+
byteBoundReached: window.byteBoundReached,
|
|
31
|
+
rolloutIdentity: locator.sessionIdentity,
|
|
32
|
+
fallbackRootSessionId: checkpoint !== null ? checkpoint.rootSessionId : context.fallbackRootSessionId,
|
|
33
|
+
nowIso: context.now.toISOString(),
|
|
34
|
+
});
|
|
35
|
+
// Supported-version guard (SPEC §9): the version signal lives in the
|
|
36
|
+
// transcript session_meta (or the committed checkpoint after the first
|
|
37
|
+
// batch). Anything below the verified floor or above the verified
|
|
38
|
+
// ceiling refuses the delta — never guess record fields of an unknown
|
|
39
|
+
// contract.
|
|
40
|
+
const cliVersion = decoded.rolloutMeta.cliVersion ?? checkpoint?.cliVersion ?? null;
|
|
41
|
+
const version = classifyCodexVersion(cliVersion);
|
|
42
|
+
const guard = version.status === 'supported'
|
|
43
|
+
? null
|
|
44
|
+
: { reason: `${version.reason}:${cliVersion ?? 'unknown'}`, nextAction: CODEX_VERSION_NEXT_ACTION };
|
|
45
|
+
return {
|
|
46
|
+
observations: decoded.observations,
|
|
47
|
+
rollout: {
|
|
48
|
+
rootSessionId: decoded.rolloutMeta.rootSessionId ?? checkpoint?.rootSessionId ?? context.fallbackRootSessionId,
|
|
49
|
+
...(cliVersion !== null ? { cliVersion } : {}),
|
|
50
|
+
...(decoded.rolloutMeta.parentRolloutIdentity !== null ? { parentRolloutIdentity: decoded.rolloutMeta.parentRolloutIdentity } : {}),
|
|
51
|
+
...(decoded.rolloutMeta.agentIdentity !== null ? { agentIdentity: decoded.rolloutMeta.agentIdentity } : {}),
|
|
52
|
+
...(decoded.rolloutMeta.agentDepth !== null ? { agentDepth: decoded.rolloutMeta.agentDepth } : {}),
|
|
53
|
+
},
|
|
54
|
+
guard,
|
|
55
|
+
compactionTimestamp: decoded.compactionTimestamp,
|
|
56
|
+
rollbackTurns: decoded.rollbackTurns,
|
|
57
|
+
stop: decoded.stop,
|
|
58
|
+
nextByteOffset: decoded.nextByteOffset,
|
|
59
|
+
lastOrdinal: decoded.lastOrdinal,
|
|
60
|
+
warnings: decoded.warnings,
|
|
61
|
+
fileSize: window.fileSize,
|
|
62
|
+
};
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
package/dist/pd-hook.d.ts
CHANGED
|
@@ -23,14 +23,21 @@ export declare const CODEX_HOOK_TIMEOUT_MS = 5000;
|
|
|
23
23
|
/** Reserved for Native packing, encoding and stdout after Adaptive is cut off. */
|
|
24
24
|
export declare const CODEX_NATIVE_RESERVE_MS = 800;
|
|
25
25
|
export declare const CODEX_ADAPTIVE_BUDGET_MS: number;
|
|
26
|
+
/** Maximum from sending a scoring request to validating its full response. */
|
|
27
|
+
export declare const CODEX_ADAPTIVE_DECISION_MS: 2000;
|
|
26
28
|
export interface PdHookDeps {
|
|
27
29
|
/** Test seam: replace the outbound transport without bypassing the hook entry. */
|
|
28
30
|
readonly fetchImpl?: typeof fetch;
|
|
29
31
|
readonly now?: () => number;
|
|
30
|
-
readonly
|
|
31
|
-
readonly generationTimeoutMs?: number;
|
|
32
|
+
readonly requestTimeoutMs?: number;
|
|
32
33
|
/** Test seam: effective adaptive budget inside the host hook window. */
|
|
33
34
|
readonly hookBudgetMs?: number;
|
|
35
|
+
/**
|
|
36
|
+
* PRI-1182: remaining-budget floor for the pre-selection skip gate. Defaults
|
|
37
|
+
* to the request's minimum executable envelope; 0 keeps a cancellation
|
|
38
|
+
* scenario sending.
|
|
39
|
+
*/
|
|
40
|
+
readonly minExecutableBudgetMs?: number;
|
|
34
41
|
}
|
|
35
42
|
export declare function processHookInvocation(rawStdin: string, _env?: EnvMap, cwd?: string, deps?: PdHookDeps): Promise<PdHookResult>;
|
|
36
43
|
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';
|
|
8
|
-
import { createAdaptivePriorityProviderForConfig, createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveHostToolSemanticsForHook, resolveNearestPdWorkspace } from '@principles/host-runtime';
|
|
8
|
+
import { ADAPTIVE_SELECTION_LIMITS, createAdaptivePriorityProviderForConfig, createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveHostToolSemanticsForHook, resolveNearestPdWorkspace } from '@principles/host-runtime';
|
|
9
9
|
import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from './tool-semantics.js';
|
|
10
10
|
import { computeFeatureFlagsFromConfig } from '@principles/core/runtime';
|
|
11
11
|
import { CodexHooksHostAdapter } from './host-adapter.js';
|
|
@@ -30,9 +30,23 @@ function errorMessage(error) {
|
|
|
30
30
|
* rejection apart — never the prompt, the raw response, or credentials.
|
|
31
31
|
*/
|
|
32
32
|
function adaptiveSelectionDiagnostic(line) {
|
|
33
|
-
|
|
33
|
+
// PRI-1181: a deterministic pre-selection skip is normal behaviour (zero
|
|
34
|
+
// reads, zero sends) — it must not be reported as a degraded selection.
|
|
35
|
+
const status = line.status === 'selected'
|
|
36
|
+
? 'adaptive'
|
|
37
|
+
: line.status === 'skipped'
|
|
38
|
+
? 'skipped'
|
|
39
|
+
: 'degraded';
|
|
34
40
|
const failures = line.failures.length > 0 ? line.failures.join('|') : 'none';
|
|
35
|
-
|
|
41
|
+
// rc-8: bounded score projection — ids are `c1..cN` / `insufficient_context`,
|
|
42
|
+
// never prompt text, and at most 16 entries reach the line.
|
|
43
|
+
const scores = line.decision === null
|
|
44
|
+
? 'none'
|
|
45
|
+
: Object.entries(line.decision.scores).slice(0, 16).map(([id, value]) => `${id}=${value}`).join(',');
|
|
46
|
+
const decision = line.decision === null
|
|
47
|
+
? 'unknown'
|
|
48
|
+
: `${line.decision.status}:${line.decision.reason}:${line.decision.ref ?? 'none'}`;
|
|
49
|
+
return `[PD] status=${status} reason=adaptive_selection_${line.status}:${line.reason} stage=${line.stage} sends=${line.sends} requestSentAt=${line.requestSentAt ?? 'unknown'} firstByteAt=${line.firstByteAt ?? 'unknown'} generationEndedAt=${line.generationEndedAt ?? 'unknown'} validatedAt=${line.validatedAt ?? 'unknown'} cancelledAt=${line.cancelledAt ?? 'unknown'} httpStatus=${line.httpStatus ?? 'unknown'} finishReason=${line.finishReason} modelObserved=${line.modelObserved ?? 'unknown'} providerObserved=${line.providerObserved ?? 'absent'} decision=${decision} scores=${scores} failures=${failures}`
|
|
36
50
|
.replace(/\s+/g, ' ')
|
|
37
51
|
.trim()
|
|
38
52
|
.slice(0, MAX_DIAGNOSTIC * 2);
|
|
@@ -216,6 +230,8 @@ export const CODEX_HOOK_TIMEOUT_MS = 5_000;
|
|
|
216
230
|
/** Reserved for Native packing, encoding and stdout after Adaptive is cut off. */
|
|
217
231
|
export const CODEX_NATIVE_RESERVE_MS = 800;
|
|
218
232
|
export const CODEX_ADAPTIVE_BUDGET_MS = CODEX_HOOK_TIMEOUT_MS - CODEX_NATIVE_RESERVE_MS;
|
|
233
|
+
/** Maximum from sending a scoring request to validating its full response. */
|
|
234
|
+
export const CODEX_ADAPTIVE_DECISION_MS = ADAPTIVE_SELECTION_LIMITS.requestTimeoutMs;
|
|
219
235
|
// stdin, env and cwd are the host CLI contract; `deps` is the optional transport
|
|
220
236
|
// seam that lets integration tests drive the real entry point without a network.
|
|
221
237
|
// eslint-disable-next-line @typescript-eslint/max-params
|
|
@@ -425,8 +441,8 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
425
441
|
env: _env,
|
|
426
442
|
...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
|
|
427
443
|
...(deps.now ? { now: deps.now } : {}),
|
|
428
|
-
|
|
429
|
-
...(deps.
|
|
444
|
+
requestTimeoutMs: deps.requestTimeoutMs ?? CODEX_ADAPTIVE_DECISION_MS,
|
|
445
|
+
...(deps.minExecutableBudgetMs !== undefined ? { minExecutableBudgetMs: deps.minExecutableBudgetMs } : {}),
|
|
430
446
|
outerDeadlineAt: adaptiveDeadlineAt,
|
|
431
447
|
onDiagnostic: (line) => { adaptiveDiagnostics.push(adaptiveSelectionDiagnostic(line)); },
|
|
432
448
|
});
|
|
@@ -451,13 +467,15 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
451
467
|
? toolSemanticsResolution.registry
|
|
452
468
|
: CODEX_TOOL_SEMANTICS;
|
|
453
469
|
const toolSemanticsDiagnostics = toolSemanticsResolution.ok
|
|
454
|
-
|
|
470
|
+
// ADR-0030: a legacy persisted declaration still loads (degraded to
|
|
471
|
+
// defaults) and must be visible on stderr (rc-9).
|
|
472
|
+
? toolSemanticsResolution.warnings.map((warning) => diagnostic(warning, 're-run this host so it refreshes its persisted tool declaration'))
|
|
455
473
|
: [diagnostic(toolSemanticsResolution.reason, toolSemanticsResolution.nextAction)];
|
|
456
474
|
const result = await createProductionHostRuntime({
|
|
457
475
|
projectDir: requestedCwd,
|
|
458
476
|
hostKind: 'codex',
|
|
459
477
|
toolSemantics,
|
|
460
|
-
...(adaptivePriorityProvider ? { adaptivePriorityProvider } : {}),
|
|
478
|
+
...(adaptivePriorityProvider ? { adaptiveGapProvider: adaptivePriorityProvider } : {}),
|
|
461
479
|
ruleContextProvider: createCodexRuleContextProvider({
|
|
462
480
|
workspaceDir: resolution.workspaceDir,
|
|
463
481
|
projectDir: requestedCwd,
|
package/dist/tool-semantics.js
CHANGED
|
@@ -21,7 +21,11 @@
|
|
|
21
21
|
import { buildToolSemanticRegistry } from '@principles/core/runtime';
|
|
22
22
|
export const CODEX_TOOL_SEMANTIC_MAPPINGS = Object.freeze([
|
|
23
23
|
{ rawToolName: 'Bash', canonicalKind: 'execute' },
|
|
24
|
-
|
|
24
|
+
// ADR-0030: apply_patch writes a `*** Begin Patch` envelope. The design gate
|
|
25
|
+
// must parse those file headers to know the target paths, and that encoding
|
|
26
|
+
// is not expressible via canonicalKind — declare it instead of matching the
|
|
27
|
+
// raw name downstream.
|
|
28
|
+
{ rawToolName: 'apply_patch', canonicalKind: 'write', writePayloadFormat: 'file-header-patch' },
|
|
25
29
|
]);
|
|
26
30
|
const built = buildToolSemanticRegistry(CODEX_TOOL_SEMANTIC_MAPPINGS);
|
|
27
31
|
if (!built.ok) {
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
import fs from 'node:fs';
|
|
29
29
|
import path from 'node:path';
|
|
30
30
|
import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
|
|
31
|
-
import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, saveHostToolDeclaration, } from '@principles/host-runtime';
|
|
31
|
+
import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
|
|
32
32
|
import { catchUpCodexIngestion } from '../ingestion/catch-up.js';
|
|
33
33
|
import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from '../tool-semantics.js';
|
|
34
34
|
const WORKER_OWNER = 'companion-worker';
|
|
@@ -179,6 +179,8 @@ export async function runCodexWorkspaceWorkerCycle(options) {
|
|
|
179
179
|
// Step 3 — Slice B idempotent reconciliation (always runs; creates no LLM work).
|
|
180
180
|
const reconcile = await reconcileGovernanceContinuation({
|
|
181
181
|
workspaceDir,
|
|
182
|
+
codexConversationIngestionEnabled: flags.codex_conversation_ingestion?.enabled === true,
|
|
183
|
+
// Legacy alias for an older installed host-runtime (P2 review).
|
|
182
184
|
conversationIngestionEnabled: flags.codex_conversation_ingestion?.enabled === true,
|
|
183
185
|
});
|
|
184
186
|
// Steps 4–6 — execution authority: internalization_auto_consumer.
|
|
@@ -355,7 +357,7 @@ export async function runCodexWorkspaceWorkerCycle(options) {
|
|
|
355
357
|
// for host-neutral consumers) and thread the registry into the cycle so
|
|
356
358
|
// activation-gate replay resolves Codex tool semantics (Bash, not bash).
|
|
357
359
|
const declared = saveHostToolDeclaration(workspaceDir, {
|
|
358
|
-
version:
|
|
360
|
+
version: HOST_TOOL_DECLARATION_VERSION,
|
|
359
361
|
hostKind: 'codex',
|
|
360
362
|
mappings: CODEX_TOOL_SEMANTIC_MAPPINGS,
|
|
361
363
|
declaredAt: new Date().toISOString(),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/codex-adapter",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.12",
|
|
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,9 +33,9 @@
|
|
|
33
33
|
"lint": "eslint \"src/**/*.ts\""
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@principles/core": "^7.
|
|
37
|
-
"@principles/host-runtime": "^3.
|
|
38
|
-
"@principles/install-layout": "^0.
|
|
36
|
+
"@principles/core": "^7.4.0",
|
|
37
|
+
"@principles/host-runtime": "^3.5.0",
|
|
38
|
+
"@principles/install-layout": "^0.8.0"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
41
|
"@types/node": "^26.6.6",
|
|
@@ -52,5 +52,5 @@
|
|
|
52
52
|
"publishConfig": {
|
|
53
53
|
"access": "public"
|
|
54
54
|
},
|
|
55
|
-
"gitHead": "
|
|
55
|
+
"gitHead": "5c7389e72a6409efb00891327a63dfc01a2009cb"
|
|
56
56
|
}
|