@principles/codex-adapter 0.8.8 → 0.8.11

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.
@@ -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
- * authorize the transcript path, run bounded incremental decoding from the
14
- * durable checkpoint, apply the supported-version guard, and hand the
15
- * projected observations to the host-neutral host-runtime seam.
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, readGovernanceCheckpoint, recordVerifiedToolOutcomes, } from '@principles/host-runtime';
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
- function ingestTranscriptDelta({ fallbackRootSessionId, canonicalPath, identity, rolloutIdentity, workspaceDir, now, port }) {
113
- const checkpoint = readGovernanceCheckpoint({ workspaceDir, hostKind: 'codex', rolloutIdentity });
114
- if (checkpoint !== null && !('byteOffset' in checkpoint) && 'ok' in checkpoint && checkpoint.ok === false) {
115
- return { status: 'degraded', reason: checkpoint.reason, nextAction: checkpoint.nextAction, warnings: [] };
116
- }
117
- const existing = checkpoint !== null && 'byteOffset' in checkpoint ? checkpoint : null;
118
- const offset = existing !== null ? existing.byteOffset : 0;
119
- let window;
120
- try {
121
- // Post-open revalidation (SPEC §9): the port must prove the opened
122
- // object still carries the identity the validator approved.
123
- window = port.read({ canonicalPath, offset, maxBytes: CODEX_INGESTION_MAX_BATCH_BYTES, expectedIdentity: identity });
124
- }
125
- catch (error) {
126
- if (error instanceof TranscriptReplacedError) {
127
- return { status: 'degraded', reason: 'transcript_replaced', nextAction: 'the transcript changed identity after validation (replacement or symlink swap); refusing to read — the next Stop revalidates the current file.', warnings: [] };
128
- }
129
- const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
130
- return { status: 'degraded', reason: `transcript_read_failed:${detail}`, nextAction: 'verify the transcript file still exists and is a regular file inside the Codex sessions root.', warnings: [] };
131
- }
132
- if (offset > window.fileSize) {
133
- // The file shrank below the committed cursor: replaced or truncated —
134
- // never guess; hold the checkpoint and degrade explicitly.
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
- rollout: {
185
- hostKind: 'codex',
186
- rolloutIdentity,
187
- rootSessionId,
188
- ...(decoded.rolloutMeta.parentRolloutIdentity !== null ? { parentRolloutIdentity: decoded.rolloutMeta.parentRolloutIdentity } : {}),
189
- ...(decoded.rolloutMeta.agentIdentity !== null ? { agentIdentity: decoded.rolloutMeta.agentIdentity } : {}),
190
- ...(decoded.rolloutMeta.agentDepth !== null ? { agentDepth: decoded.rolloutMeta.agentDepth } : {}),
191
- },
192
- observations: decoded.observations,
193
- checkpoint: {
194
- hostKind: 'codex',
195
- rolloutIdentity,
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
- const warnings = [...decoded.warnings, ...result.warnings];
208
- if (!result.ok) {
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: result.inserted,
235
- enriched: result.enriched,
236
- duplicates: result.duplicates,
237
- warnings,
238
- lagBytes: Math.max(0, window.fileSize - decoded.nextByteOffset),
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(decoded.observations),
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
- canonicalPath: validated.canonicalPath,
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
- canonicalPath: validated.canonicalPath,
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
- import type { GovernanceObservationInput } from '@principles/host-runtime';
2
- export declare const CODEX_INGESTION_MAX_BATCH_BYTES: number;
3
- export declare const CODEX_INGESTION_MAX_BATCH_RECORDS = 256;
4
- export interface TranscriptReadResult {
5
- /** Raw bytes read from [offset, offset+maxBytes) — never a decoded string, so multi-byte UTF-8 never corrupts offset math. */
6
- readonly bytes: Buffer;
7
- readonly fileSize: number;
8
- }
9
- /** Identity the validator captured pre-open; the port must re-prove it post-open (SPEC §9 TOCTOU). */
10
- export interface TranscriptExpectedIdentity {
11
- readonly dev: number;
12
- readonly ino: number;
13
- readonly size: number;
14
- readonly mtimeMs: number;
15
- }
16
- /** Arguments for one bounded transcript window read. */
17
- export interface TranscriptReadRequest {
18
- readonly canonicalPath: string;
19
- readonly offset: number;
20
- readonly maxBytes: number;
21
- /** Pre-open identity from the validator; the port re-proves it post-open. */
22
- readonly expectedIdentity?: TranscriptExpectedIdentity;
23
- }
24
- /** Filesystem boundary for the transcript read — injectable so tests can spy. */
25
- export interface TranscriptPort {
26
- read(request: TranscriptReadRequest): TranscriptReadResult;
27
- }
28
- /** Thrown by the port when the opened object is not the validated one (replacement/TOCTOU). */
29
- export declare class TranscriptReplacedError extends Error {
30
- constructor();
31
- }
32
- export declare function createNodeTranscriptPort(): TranscriptPort;
33
- export type TranscriptDecodeStop = {
34
- kind: 'eof';
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 fs from 'node:fs';
26
- export const CODEX_INGESTION_MAX_BATCH_BYTES = 1024 * 1024;
27
- export const CODEX_INGESTION_MAX_BATCH_RECORDS = 256;
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
- // UTF-8 multi-byte sequences never contain 0x0A, so splitting the byte
430
- // window at newline bytes is safe and keeps the checkpoint byte-exact.
431
- const lastNewline = bytes.lastIndexOf(0x0a);
432
- const completeEnd = lastNewline + 1; // exclusive byte end of the newline-terminated region
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
- let lineStart = 0;
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 >= CODEX_INGESTION_MAX_BATCH_RECORDS) {
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 (tailBytes.length > 0) {
463
- const tailStart = cursor; // byte offset where the unterminated tail begins
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 (lastNewline === -1) {
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(tailBytes);
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 + tailBytes.length, lastOrdinal), stop: { kind: 'eof' } };
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, cursor, lastOrdinal), stop: input.byteBoundReached ? { kind: 'byte_bound' } : { kind: 'eof' } };
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
@@ -11,5 +11,31 @@ export interface CodexEvidenceContext {
11
11
  evidenceEnabled: boolean;
12
12
  warn: (diagnosticLine: string) => void;
13
13
  }
14
- export declare function processHookInvocation(rawStdin: string, _env?: EnvMap, cwd?: string): Promise<PdHookResult>;
14
+ /**
15
+ * The host hook window is declared by the plugin manifest
16
+ * (`plugins/principles-disciple/hooks/hooks.json`, `UserPromptSubmit.timeout`,
17
+ * in seconds). Codex owns that timer and terminates the hook process when it
18
+ * fires; PD gets no in-band notification, so Adaptive must end BEFORE the
19
+ * window and leave the remainder to emit the Native body.
20
+ * `pd-hook-adaptive.test.ts` guards this constant against the manifest.
21
+ */
22
+ export declare const CODEX_HOOK_TIMEOUT_MS = 5000;
23
+ /** Reserved for Native packing, encoding and stdout after Adaptive is cut off. */
24
+ export declare const CODEX_NATIVE_RESERVE_MS = 800;
25
+ export declare const CODEX_ADAPTIVE_BUDGET_MS: number;
26
+ export interface PdHookDeps {
27
+ /** Test seam: replace the outbound transport without bypassing the hook entry. */
28
+ readonly fetchImpl?: typeof fetch;
29
+ readonly now?: () => number;
30
+ readonly firstByteTimeoutMs?: number;
31
+ readonly generationTimeoutMs?: number;
32
+ /** Test seam: effective adaptive budget inside the host hook window. */
33
+ readonly hookBudgetMs?: number;
34
+ /**
35
+ * PRI-1181: remaining-budget floor for the pre-selection skip gate. Defaults
36
+ * to the measured minimum; 0 keeps a cancellation scenario sending.
37
+ */
38
+ readonly minRemainingBudgetMs?: number;
39
+ }
40
+ export declare function processHookInvocation(rawStdin: string, _env?: EnvMap, cwd?: string, deps?: PdHookDeps): Promise<PdHookResult>;
15
41
  export {};
package/dist/pd-hook.js CHANGED
@@ -5,8 +5,8 @@ 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 { createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveNearestPdWorkspace } from '@principles/host-runtime';
9
- import { CODEX_TOOL_SEMANTICS } from './tool-semantics.js';
8
+ import { createAdaptivePriorityProviderForConfig, createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveHostToolSemanticsForHook, resolveNearestPdWorkspace } from '@principles/host-runtime';
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';
12
12
  import { CodexDecoderError, CodexEncoderError } from './codec/index.js';
@@ -24,6 +24,25 @@ function diagnostic(reason, nextAction) {
24
24
  function errorMessage(error) {
25
25
  return error instanceof Error ? error.message.slice(0, MAX_DIAGNOSTIC) : 'unknown_error';
26
26
  }
27
+ /**
28
+ * PRI-1170: one bounded line per Adaptive turn. Records the facts needed to
29
+ * tell first-byte expiry, generation expiry, transport failure and ref/digest
30
+ * rejection apart — never the prompt, the raw response, or credentials.
31
+ */
32
+ function adaptiveSelectionDiagnostic(line) {
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';
40
+ const failures = line.failures.length > 0 ? line.failures.join('|') : 'none';
41
+ return `[PD] status=${status} reason=adaptive_selection_${line.status}:${line.reason} stage=${line.stage} sends=${line.sends} firstByteAt=${line.firstByteAt ?? 'unknown'} generationEndedAt=${line.generationEndedAt ?? 'unknown'} cancelledAt=${line.cancelledAt ?? 'unknown'} httpStatus=${line.httpStatus ?? 'unknown'} finishReason=${line.finishReason} failures=${failures}`
42
+ .replace(/\s+/g, ' ')
43
+ .trim()
44
+ .slice(0, MAX_DIAGNOSTIC * 2);
45
+ }
27
46
  function redactStringFields(data) {
28
47
  // rc-8: telemetry is redacted string-field by string field (same policy as
29
48
  // the OpenClaw EventLog redactEventData) — shared by every emitter here.
@@ -191,7 +210,25 @@ async function runConversationIngestion(args) {
191
210
  }
192
211
  return diagnostics;
193
212
  }
194
- export async function processHookInvocation(rawStdin, _env = process.env, cwd = process.cwd()) {
213
+ /**
214
+ * The host hook window is declared by the plugin manifest
215
+ * (`plugins/principles-disciple/hooks/hooks.json`, `UserPromptSubmit.timeout`,
216
+ * in seconds). Codex owns that timer and terminates the hook process when it
217
+ * fires; PD gets no in-band notification, so Adaptive must end BEFORE the
218
+ * window and leave the remainder to emit the Native body.
219
+ * `pd-hook-adaptive.test.ts` guards this constant against the manifest.
220
+ */
221
+ export const CODEX_HOOK_TIMEOUT_MS = 5_000;
222
+ /** Reserved for Native packing, encoding and stdout after Adaptive is cut off. */
223
+ export const CODEX_NATIVE_RESERVE_MS = 800;
224
+ export const CODEX_ADAPTIVE_BUDGET_MS = CODEX_HOOK_TIMEOUT_MS - CODEX_NATIVE_RESERVE_MS;
225
+ // stdin, env and cwd are the host CLI contract; `deps` is the optional transport
226
+ // seam that lets integration tests drive the real entry point without a network.
227
+ // eslint-disable-next-line @typescript-eslint/max-params
228
+ export async function processHookInvocation(rawStdin, _env = process.env, cwd = process.cwd(), deps = {}) {
229
+ // The host owns this window and kills the process when it expires; anchor at
230
+ // entry so decode/ingestion time counts against the same budget.
231
+ const adaptiveDeadlineAt = Date.now() + (deps.hookBudgetMs ?? CODEX_ADAPTIVE_BUDGET_MS);
195
232
  let parsed;
196
233
  try {
197
234
  parsed = JSON.parse(rawStdin);
@@ -385,17 +422,56 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
385
422
  // event-JSONL writer (same events_*.jsonl format as the OpenClaw EventLog;
386
423
  // the Codex adapter stays independent of the OpenClaw plugin). The line
387
424
  // writer appends synchronously — no flush/dispose needed for the subprocess.
425
+ // PRI-1170: Adaptive Activation is an INDEPENDENT, default-off switch on
426
+ // top of the PD hook. `host.codex.enabled` remains the whole-hook gate.
427
+ const adaptiveDiagnostics = [];
428
+ let adaptivePriorityProvider;
429
+ if (event.kind === 'before_prompt_build' && flags['host.codex.adaptive_activation']?.enabled === true) {
430
+ const adaptive = createAdaptivePriorityProviderForConfig(config.effective.config, resolution.workspaceDir, {
431
+ env: _env,
432
+ ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
433
+ ...(deps.now ? { now: deps.now } : {}),
434
+ ...(deps.firstByteTimeoutMs !== undefined ? { firstByteTimeoutMs: deps.firstByteTimeoutMs } : {}),
435
+ ...(deps.generationTimeoutMs !== undefined ? { generationTimeoutMs: deps.generationTimeoutMs } : {}),
436
+ ...(deps.minRemainingBudgetMs !== undefined ? { minRemainingBudgetMs: deps.minRemainingBudgetMs } : {}),
437
+ outerDeadlineAt: adaptiveDeadlineAt,
438
+ onDiagnostic: (line) => { adaptiveDiagnostics.push(adaptiveSelectionDiagnostic(line)); },
439
+ });
440
+ if (adaptive.ok) {
441
+ adaptivePriorityProvider = adaptive.provider;
442
+ }
443
+ else {
444
+ // rc-9: an enabled-but-unusable switch is observable, never silent.
445
+ adaptiveDiagnostics.push(diagnostic(`adaptive_activation_${adaptive.readiness}:${adaptive.reason}`, adaptive.nextAction));
446
+ }
447
+ }
448
+ // B3: resolve tool semantics from the workspace declarations — the SAME
449
+ // source replay / evidence / Console read — with the compiled-in Codex
450
+ // declaration as the fallback. A malformed declaration degrades
451
+ // observably on stderr instead of blocking the tool call (rc-9).
452
+ const toolSemanticsResolution = resolveHostToolSemanticsForHook({
453
+ workspaceDir: resolution.workspaceDir,
454
+ hostKind: 'codex',
455
+ staticMappings: CODEX_TOOL_SEMANTIC_MAPPINGS,
456
+ });
457
+ const toolSemantics = toolSemanticsResolution.ok
458
+ ? toolSemanticsResolution.registry
459
+ : CODEX_TOOL_SEMANTICS;
460
+ const toolSemanticsDiagnostics = toolSemanticsResolution.ok
461
+ ? []
462
+ : [diagnostic(toolSemanticsResolution.reason, toolSemanticsResolution.nextAction)];
388
463
  const result = await createProductionHostRuntime({
389
464
  projectDir: requestedCwd,
390
465
  hostKind: 'codex',
391
- toolSemantics: CODEX_TOOL_SEMANTICS,
466
+ toolSemantics,
467
+ ...(adaptivePriorityProvider ? { adaptivePriorityProvider } : {}),
392
468
  ruleContextProvider: createCodexRuleContextProvider({
393
469
  workspaceDir: resolution.workspaceDir,
394
470
  projectDir: requestedCwd,
395
471
  enabled: flags.rulecode_context_v2?.enabled === true && ingestionEnabled,
396
472
  cutoffAt: hookEpoch,
397
473
  currentToolUseId: event.context.toolCallId ?? '',
398
- toolSemantics: CODEX_TOOL_SEMANTICS,
474
+ toolSemantics,
399
475
  }),
400
476
  events: codexEventEmitter(path.join(resolution.workspaceDir, '.state'), evidenceContext),
401
477
  }).dispatch(event);
@@ -463,7 +539,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
463
539
  evidenceDiagnostics.push(diagnostic(`codex_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
464
540
  }
465
541
  }
466
- const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics, ...explicitDiagnostics];
542
+ const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics, ...explicitDiagnostics, ...adaptiveDiagnostics, ...toolSemanticsDiagnostics];
467
543
  return { stdout: encoded, exitCode: 0, stderr };
468
544
  }
469
545
  catch (error) {
@@ -545,7 +621,12 @@ async function main() {
545
621
  }
546
622
  let result;
547
623
  try {
548
- result = await processHookInvocation(raw);
624
+ // The host's 5 s window starts at process spawn, not at this call: node
625
+ // boot and module loading already consumed part of it. Anchor the deadline
626
+ // at process start so the measured reserve really reaches Native.
627
+ const elapsedSinceProcessStartMs = Math.round(process.uptime() * 1000);
628
+ const remainingBudgetMs = Math.max(1, CODEX_ADAPTIVE_BUDGET_MS - elapsedSinceProcessStartMs);
629
+ result = await processHookInvocation(raw, process.env, process.cwd(), { hookBudgetMs: remainingBudgetMs });
549
630
  }
550
631
  catch (error) {
551
632
  // Fail-open belt for an unexpected pre-dispatch throw (e.g. a workspace
@@ -67,6 +67,21 @@ export interface CodexWorkerCycleOptions {
67
67
  readonly stage2AggregateBudgetMs?: number;
68
68
  }
69
69
  export declare function readCodexWorkerLiveness(workspaceDir: string): Record<string, unknown> | null;
70
+ /**
71
+ * SPEC §9.1 fair-share pick (review P1): pending and due-retry are both
72
+ * continuously-eligible classes; neither may starve the other while new
73
+ * pending signals keep arriving. A persistent round-robin cursor (stored in
74
+ * the existing reconciliation_cursor authority, so a worker restart does NOT
75
+ * reset it to pending-priority) alternates service between the two classes —
76
+ * each eligible class is served at least every other cycle, well inside the
77
+ * 3-full-cycle bound. Single-eligible work is always served.
78
+ *
79
+ * The implementation is shared with OpenClaw's L3 automatic run
80
+ * (`@principles/core/runtime` `pickDiagnosticianCandidate`); this file keeps no
81
+ * second copy. Oldest pending diagnostician first; retry_wait candidates are
82
+ * filtered to those whose backoff window has ELAPSED, so an old-but-still-
83
+ * waiting task cannot starve a younger eligible one (review P1).
84
+ */
70
85
  /**
71
86
  * Run ONE bounded worker cycle for a canonical workspace. Never throws:
72
87
  * every failure becomes a structured degraded result with a nextAction.
@@ -27,7 +27,7 @@
27
27
  */
28
28
  import fs from 'node:fs';
29
29
  import path from 'node:path';
30
- import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
30
+ import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
31
31
  import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, saveHostToolDeclaration, } 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';
@@ -111,14 +111,6 @@ function writeLiveness(workspaceDir, patch) {
111
111
  // itself remains the observable degradation channel)
112
112
  }
113
113
  }
114
- /**
115
- * Oldest pending diagnostician first; retry_wait candidates are filtered to
116
- * those whose backoff window has ELAPSED, so an old-but-still-waiting task
117
- * cannot starve a younger eligible one (review P1). The candidate set stays
118
- * bounded (`limit`), and executePendingDiagnosis re-enforces the backoff
119
- * window on the chosen task — no double bookkeeping.
120
- */
121
- const DIAGNOSTICIAN_FAIR_SHARE_SCOPE = 'codex-worker-diagnostician-fair-share';
122
114
  /**
123
115
  * SPEC §9.1 fair-share pick (review P1): pending and due-retry are both
124
116
  * continuously-eligible classes; neither may starve the other while new
@@ -127,34 +119,13 @@ const DIAGNOSTICIAN_FAIR_SHARE_SCOPE = 'codex-worker-diagnostician-fair-share';
127
119
  * reset it to pending-priority) alternates service between the two classes —
128
120
  * each eligible class is served at least every other cycle, well inside the
129
121
  * 3-full-cycle bound. Single-eligible work is always served.
122
+ *
123
+ * The implementation is shared with OpenClaw's L3 automatic run
124
+ * (`@principles/core/runtime` `pickDiagnosticianCandidate`); this file keeps no
125
+ * second copy. Oldest pending diagnostician first; retry_wait candidates are
126
+ * filtered to those whose backoff window has ELAPSED, so an old-but-still-
127
+ * waiting task cannot starve a younger eligible one (review P1).
130
128
  */
131
- async function pickDiagnosticianCandidate(stateManager, limit, nowIso) {
132
- const pending = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'pending', orderBy: 'updated_at_asc', limit });
133
- const [pendingTask] = pending;
134
- let retryTask = null;
135
- const retrying = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'retry_wait', orderBy: 'updated_at_asc', limit });
136
- for (const candidate of retrying) {
137
- if (isRetryWaitBackoffElapsed(candidate.status, candidate.leaseExpiresAt)) {
138
- retryTask = candidate;
139
- break;
140
- }
141
- }
142
- if (pendingTask === undefined && retryTask === null)
143
- return null;
144
- if (retryTask === null) {
145
- await stateManager.setDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE, { lastUpdatedAt: nowIso, lastTaskId: 'pending' });
146
- return pendingTask ?? null;
147
- }
148
- if (pendingTask === undefined) {
149
- await stateManager.setDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE, { lastUpdatedAt: nowIso, lastTaskId: 'retry_wait' });
150
- return retryTask;
151
- }
152
- const cursor = await stateManager.getDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE);
153
- const serveRetryFirst = cursor?.lastTaskId !== 'retry_wait';
154
- const servedClass = serveRetryFirst ? 'retry_wait' : 'pending';
155
- await stateManager.setDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE, { lastUpdatedAt: nowIso, lastTaskId: servedClass });
156
- return serveRetryFirst ? retryTask : pendingTask;
157
- }
158
129
  /**
159
130
  * Run ONE bounded worker cycle for a canonical workspace. Never throws:
160
131
  * every failure becomes a structured degraded result with a nextAction.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.8.8",
3
+ "version": "0.8.11",
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": "^7.2.0",
37
- "@principles/host-runtime": "^3.2.2",
36
+ "@principles/core": "^7.3.2",
37
+ "@principles/host-runtime": "^3.4.0",
38
38
  "@principles/install-layout": "^0.7.0"
39
39
  },
40
40
  "devDependencies": {
@@ -52,5 +52,5 @@
52
52
  "publishConfig": {
53
53
  "access": "public"
54
54
  },
55
- "gitHead": "7ad401c6ecb8a3f50d53783c0091fcf65dccadd9"
55
+ "gitHead": "3d6e2af3cf55ad63b7bb388c005adf4b923eb383"
56
56
  }