@principles/codex-adapter 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ export type BackgroundSelectionJobResult = {
2
+ readonly status: 'selected';
3
+ readonly activationId: string;
4
+ } | {
5
+ readonly status: 'skipped' | 'unavailable' | 'invalid';
6
+ readonly reason: string;
7
+ };
8
+ /** Test seam: execute one job without the process boundary. */
9
+ export declare function runBackgroundSelectionJob(jobPath: string): Promise<BackgroundSelectionJobResult>;
@@ -0,0 +1,142 @@
1
+ /**
2
+ * PRI-1196 — detached background selector for the Codex host.
3
+ *
4
+ * argv[2] is a single-use job file written by the UserPromptSubmit hook after
5
+ * the Native body was already encoded. The job carries the current prompt ONLY
6
+ * so the SAME decision protocol can run; it is deleted before any network I/O.
7
+ * This process never writes to the host's stdout/stderr (`stdio: 'ignore'`).
8
+ */
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { runAdaptiveBackgroundSelection } from '@principles/host-runtime';
12
+ import { ADAPTIVE_APPEND_SCHEMA_VERSION, ADAPTIVE_APPEND_TTL_MS, adaptiveTurnEnded, appendAdaptiveAppendFact, discardAdaptiveAppendResult, takeAdaptiveAppendJob, writeAdaptiveAppendResultFor, } from './ingestion/adaptive-append-state.js';
13
+ function stateDirOf(workspaceDir) {
14
+ return path.join(workspaceDir, '.state');
15
+ }
16
+ function factCode(outcomeStatus, reason) {
17
+ if (outcomeStatus === 'needs_setup')
18
+ return `needs_setup:${reason}`.slice(0, 240);
19
+ return `skipped:background_${reason}`.slice(0, 240);
20
+ }
21
+ async function execute(job) {
22
+ const startedAt = Date.now();
23
+ const handoff = { workspaceDir: job.workspaceDir, sessionId: job.sessionId, turnId: job.turnId };
24
+ // Stop already ended this turn: a decision now cannot reach it.
25
+ if (adaptiveTurnEnded(handoff))
26
+ return { status: 'skipped', reason: 'turn_ended' };
27
+ const deadlineAt = job.createdAt + ADAPTIVE_APPEND_TTL_MS - 1000;
28
+ if (startedAt >= deadlineAt) {
29
+ appendAdaptiveAppendFact({
30
+ stateDir: stateDirOf(job.workspaceDir),
31
+ sessionId: job.sessionId,
32
+ turnId: job.turnId,
33
+ workspaceDir: job.workspaceDir,
34
+ resultCode: 'skipped:background_expired',
35
+ scored: false,
36
+ budget: job.budgetChars,
37
+ injectedCharCount: 0,
38
+ });
39
+ return { status: 'skipped', reason: 'expired' };
40
+ }
41
+ const outcome = await runAdaptiveBackgroundSelection({
42
+ workspaceDir: job.workspaceDir,
43
+ sessionId: job.sessionId,
44
+ turnId: job.turnId,
45
+ promptContent: job.promptContent,
46
+ nativeActivationIds: job.nativeActivationIds,
47
+ nativeChars: job.nativeChars,
48
+ budgetChars: job.budgetChars,
49
+ deadlineAt,
50
+ env: process.env,
51
+ });
52
+ const scored = outcome.diagnostic.sends > 0;
53
+ // Re-check after the decision: Stop or a new turn may have landed meanwhile.
54
+ if (adaptiveTurnEnded(handoff))
55
+ return { status: 'skipped', reason: 'turn_ended' };
56
+ if (outcome.status === 'selected') {
57
+ writeAdaptiveAppendResultFor(job.workspaceDir, {
58
+ schemaVersion: ADAPTIVE_APPEND_SCHEMA_VERSION,
59
+ createdAt: Date.now(),
60
+ startedAt: job.createdAt,
61
+ sessionId: job.sessionId,
62
+ turnId: job.turnId,
63
+ target: outcome.target,
64
+ directiveChars: outcome.directive.length,
65
+ nativeActivationIds: [...job.nativeActivationIds],
66
+ nativeChars: job.nativeChars,
67
+ budgetChars: job.budgetChars,
68
+ hookIdentity: job.hookIdentity,
69
+ });
70
+ // Close the Stop-vs-write race: if the turn ended while the result was
71
+ // being written, withdraw it so an ended turn never keeps a ready result.
72
+ if (adaptiveTurnEnded(handoff)) {
73
+ discardAdaptiveAppendResult(job.workspaceDir, job.sessionId, job.turnId);
74
+ return { status: 'skipped', reason: 'turn_ended' };
75
+ }
76
+ // "Background selected" is recorded separately from the eventual append:
77
+ // no activationIds here, so this line never claims an injection.
78
+ appendAdaptiveAppendFact({
79
+ stateDir: stateDirOf(job.workspaceDir),
80
+ sessionId: job.sessionId,
81
+ turnId: job.turnId,
82
+ workspaceDir: job.workspaceDir,
83
+ resultCode: 'selected:background_ready',
84
+ scored,
85
+ budget: job.budgetChars,
86
+ injectedCharCount: 0,
87
+ });
88
+ return { status: 'selected', activationId: outcome.target.activationId };
89
+ }
90
+ appendAdaptiveAppendFact({
91
+ stateDir: stateDirOf(job.workspaceDir),
92
+ sessionId: job.sessionId,
93
+ turnId: job.turnId,
94
+ workspaceDir: job.workspaceDir,
95
+ resultCode: factCode(outcome.diagnostic.status, outcome.reason),
96
+ scored,
97
+ budget: job.budgetChars,
98
+ injectedCharCount: 0,
99
+ });
100
+ return { status: outcome.status, reason: outcome.reason };
101
+ }
102
+ /** Test seam: execute one job without the process boundary. */
103
+ export async function runBackgroundSelectionJob(jobPath) {
104
+ const job = takeAdaptiveAppendJob(jobPath);
105
+ if (!job)
106
+ return { status: 'invalid', reason: 'job_unreadable' };
107
+ return execute(job);
108
+ }
109
+ const [, entryPath, jobPath] = process.argv;
110
+ const isMain = typeof entryPath === 'string'
111
+ && path.resolve(entryPath) === fileURLToPath(import.meta.url)
112
+ && jobPath !== undefined;
113
+ if (isMain && jobPath !== undefined) {
114
+ // The job is withdrawn ONCE. The failure fact below reuses this object: the
115
+ // old catch re-read the already-deleted file, so a thrown decision could
116
+ // never record `skipped:background_selection_failed` (it was dead code).
117
+ const job = takeAdaptiveAppendJob(jobPath);
118
+ if (job !== null) {
119
+ try {
120
+ await execute(job);
121
+ }
122
+ catch {
123
+ // A detached selector that throws must still leave the turn on Native.
124
+ // No raw error crosses into the host or the evidence log.
125
+ try {
126
+ appendAdaptiveAppendFact({
127
+ stateDir: stateDirOf(job.workspaceDir),
128
+ sessionId: job.sessionId,
129
+ turnId: job.turnId,
130
+ workspaceDir: job.workspaceDir,
131
+ resultCode: 'skipped:background_selection_failed',
132
+ scored: false,
133
+ budget: job.budgetChars,
134
+ injectedCharCount: 0,
135
+ });
136
+ }
137
+ catch {
138
+ // Nothing else can be done without risking the host; the turn is Native.
139
+ }
140
+ }
141
+ }
142
+ }
@@ -0,0 +1,209 @@
1
+ import type { AdaptiveAppendTargetRef } from '@principles/host-runtime';
2
+ export declare const ADAPTIVE_APPEND_SCHEMA_VERSION = 1;
3
+ /** Whole-turn window for a background decision to still be usable. */
4
+ export declare const ADAPTIVE_APPEND_TTL_MS = 20000;
5
+ /** Residue bound for files an abnormal exit left behind. */
6
+ export declare const ADAPTIVE_APPEND_MAX_AGE_MS: number;
7
+ /** Maximum complete turn history accepted at the append boundary. */
8
+ export declare const ADAPTIVE_APPEND_MAX_OBSERVATIONS = 64;
9
+ /**
10
+ * Turn-scoped "track this turn" marker. Written once at UserPromptSubmit,
11
+ * before the selector can withdraw the job, so the ordering gate keeps
12
+ * observing Pre/PostToolUse for the whole scoring window.
13
+ *
14
+ * The return value is also the "at most one scoring request per turn" gate:
15
+ * `exists` means a replayed prompt for the same turn must not spawn again.
16
+ */
17
+ export declare function markAdaptiveTurnStarted(input: {
18
+ workspaceDir: string;
19
+ sessionId: string;
20
+ turnId: string;
21
+ }): 'created' | 'exists' | 'failed';
22
+ /** True while this turn may still record observations or has a decision artifact. */
23
+ export declare function hasAdaptiveAppendTurn(input: {
24
+ workspaceDir: string;
25
+ sessionId: string;
26
+ turnId: string;
27
+ }): boolean;
28
+ /**
29
+ * Mark the turn as finished before the cleanup. A background selector that
30
+ * finishes after Stop checks this marker and discards its decision, so a
31
+ * late result can never surface as this turn's outcome.
32
+ */
33
+ export declare function markAdaptiveTurnEnded(input: {
34
+ workspaceDir: string;
35
+ sessionId: string;
36
+ turnId: string;
37
+ }): void;
38
+ export declare function adaptiveTurnEnded(input: {
39
+ workspaceDir: string;
40
+ sessionId: string;
41
+ turnId: string;
42
+ }): boolean;
43
+ export interface AdaptiveAppendHookIdentity {
44
+ readonly entryPath: string;
45
+ readonly mtimeMs: number;
46
+ }
47
+ /** The installed hook entry of the process that wrote the job. */
48
+ export declare function currentHookIdentity(): AdaptiveAppendHookIdentity | null;
49
+ export interface AdaptiveAppendJob {
50
+ readonly schemaVersion: number;
51
+ readonly createdAt: number;
52
+ readonly sessionId: string;
53
+ readonly turnId: string;
54
+ readonly workspaceDir: string;
55
+ readonly promptContent: string;
56
+ readonly nativeActivationIds: string[];
57
+ readonly nativeChars: number;
58
+ readonly budgetChars: number;
59
+ readonly hookIdentity: AdaptiveAppendHookIdentity | null;
60
+ }
61
+ /** rc-1/rc-3: strict job validation; an invalid job is unusable, never guessed. */
62
+ export declare function parseAdaptiveAppendJob(value: unknown): AdaptiveAppendJob | null;
63
+ export type { AdaptiveAppendTargetRef } from '@principles/host-runtime';
64
+ export interface AdaptiveAppendResult {
65
+ readonly schemaVersion: number;
66
+ readonly createdAt: number;
67
+ readonly startedAt: number;
68
+ readonly sessionId: string;
69
+ readonly turnId: string;
70
+ readonly target: AdaptiveAppendTargetRef;
71
+ readonly directiveChars: number;
72
+ readonly nativeActivationIds: string[];
73
+ readonly nativeChars: number;
74
+ readonly budgetChars: number;
75
+ readonly hookIdentity: AdaptiveAppendHookIdentity | null;
76
+ }
77
+ export declare function parseAdaptiveAppendResult(value: unknown): AdaptiveAppendResult | null;
78
+ export type AdaptiveAppendJobWrite = {
79
+ readonly ok: true;
80
+ readonly jobPath: string;
81
+ } | {
82
+ readonly ok: false;
83
+ readonly reason: 'already_started' | 'job_write_failed';
84
+ };
85
+ /**
86
+ * Parent side: create the job ONCE per turn, then hand it to a DETACHED
87
+ * process. `wx` is the gate behind "at most one scoring request per turn": a
88
+ * retried/replayed UserPromptSubmit for the same turn cannot replace the job
89
+ * and spawn a second selector. The job carries the Owner prompt for the
90
+ * decision request only, so the file is owner-only (0600) and is withdrawn by
91
+ * the selector as soon as it reads it; a write that never reaches the selector
92
+ * is removed here or aged out by the residue sweep.
93
+ */
94
+ export declare function writeAdaptiveAppendJob(job: AdaptiveAppendJob): AdaptiveAppendJobWrite;
95
+ /** A job that could not be handed off must not leave the prompt on disk. */
96
+ export declare function discardAdaptiveAppendJob(jobPath: string): void;
97
+ export type AdaptiveAppendSpawnResult = {
98
+ ok: true;
99
+ pid: number | undefined;
100
+ } | {
101
+ ok: false;
102
+ reason: string;
103
+ };
104
+ /**
105
+ * Spawn the background selector. `stdio: 'ignore'` is mandatory: a detached
106
+ * child that inherited the hook's stdout pipe would keep that pipe open and
107
+ * hold the host's first request until the decision finished.
108
+ */
109
+ export declare function spawnAdaptiveBackgroundSelection(jobPath: string): AdaptiveAppendSpawnResult;
110
+ /** Child side: read and immediately withdraw the job (the prompt is not kept). */
111
+ export declare function takeAdaptiveAppendJob(jobPath: string): AdaptiveAppendJob | null;
112
+ /** Persist the ONE ready decision for this turn. */
113
+ export declare function writeAdaptiveAppendResultFor(workspaceDir: string, result: AdaptiveAppendResult): void;
114
+ /** Withdraw a result whose turn ended while it was being written. */
115
+ export declare function discardAdaptiveAppendResult(workspaceDir: string, sessionId: string, turnId: string): void;
116
+ export type AdaptiveAppendReady = {
117
+ readonly status: 'ready';
118
+ readonly result: AdaptiveAppendResult;
119
+ readonly claimPath: string;
120
+ } | {
121
+ readonly status: 'absent' | 'invalid' | 'expired';
122
+ readonly reason?: string;
123
+ };
124
+ /**
125
+ * Atomically claim the ready result. `renameSync` is the mutex: exactly one
126
+ * concurrent consumer can move the file, so a replayed callback emits nothing.
127
+ */
128
+ export declare function claimAdaptiveAppendResult(input: {
129
+ workspaceDir: string;
130
+ sessionId: string;
131
+ turnId: string;
132
+ now: number;
133
+ }): AdaptiveAppendReady;
134
+ export declare function releaseAdaptiveAppendClaim(claimPath: string): void;
135
+ export type ToolObservationPhase = 'pre' | 'post';
136
+ export interface ToolObservation {
137
+ readonly phase: ToolObservationPhase;
138
+ readonly toolCallId: string;
139
+ readonly toolName: string;
140
+ readonly canonicalKind: string;
141
+ /** Only meaningful for execute kinds: classifyBashRisk(...) === 'safe'. */
142
+ readonly readOnly: boolean;
143
+ readonly at: number;
144
+ }
145
+ export declare function appendToolObservation(input: {
146
+ workspaceDir: string;
147
+ sessionId: string;
148
+ turnId: string;
149
+ observation: ToolObservation;
150
+ }): void;
151
+ export declare function readToolObservations(input: {
152
+ workspaceDir: string;
153
+ sessionId: string;
154
+ turnId: string;
155
+ }): ToolObservation[];
156
+ export type AppendOrdering = {
157
+ readonly ok: true;
158
+ } | {
159
+ readonly ok: false;
160
+ readonly reason: string;
161
+ };
162
+ /**
163
+ * The ordering gate:
164
+ * - the CURRENT call must have been observed at both boundaries — a lone
165
+ * post proves nothing about what happened before it;
166
+ * - a `write` call anywhere in this turn ends the opportunity;
167
+ * - an execute call that is not classified `safe`, or an unresolved kind,
168
+ * is "semantics unknown" and ends it too;
169
+ * - another call opened and not yet closed means the completion order of a
170
+ * parallel batch cannot be proven; a replayed post is a duplicate callback.
171
+ */
172
+ export declare function evaluateAppendOrdering(observations: readonly ToolObservation[], currentToolCallId: string): AppendOrdering;
173
+ /** Delete every short-lived file of one turn (Stop / terminal drop). */
174
+ export declare function clearAdaptiveAppendTurn(input: {
175
+ workspaceDir: string;
176
+ sessionId: string;
177
+ turnId: string;
178
+ }): void;
179
+ /** Opportunistic residue sweep; bounded and age-based, never touches fresh state. */
180
+ export declare function clearStaleAdaptiveAppendState(workspaceDir: string, now: number): void;
181
+ /**
182
+ * One-shot marker for a terminal fact of this turn. Returns true only to the
183
+ * caller that created it, so concurrent hooks emit the fact once.
184
+ */
185
+ export declare function claimAdaptiveReportMarker(input: {
186
+ workspaceDir: string;
187
+ sessionId: string;
188
+ turnId: string;
189
+ reason: string;
190
+ }): boolean;
191
+ export interface AdaptiveAppendFactInput {
192
+ readonly stateDir: string;
193
+ readonly sessionId: string;
194
+ readonly turnId: string;
195
+ readonly workspaceDir: string;
196
+ /** `<status>:<reason>` — the UI classifies on this prefix. */
197
+ readonly resultCode: string;
198
+ readonly scored: boolean;
199
+ readonly appended?: AdaptiveAppendTargetRef;
200
+ readonly budget: number;
201
+ readonly injectedCharCount: number;
202
+ }
203
+ /**
204
+ * The console reads `runtime_v2_prompt_activations_injected` with an
205
+ * `adaptive` fact. "Background selected" is emitted with empty arrays (no
206
+ * injection claim); "appended" carries exactly the one principle that was
207
+ * added to the later request.
208
+ */
209
+ export declare function appendAdaptiveAppendFact(input: AdaptiveAppendFactInput): void;
@@ -0,0 +1,544 @@
1
+ /**
2
+ * PRI-1196 — short-lived state for the background Adaptive append.
3
+ *
4
+ * One turn's state lives under `<workspace>/.state`:
5
+ * started_<session>_<turn>.json this turn is tracked (tool observations)
6
+ * job_<session>_<turn>.json what the background process must decide
7
+ * result_<session>_<turn>.json the ONE ready decision (ids only, no text)
8
+ * tools_<session>_<turn>.jsonl pre/post tool observations of this turn
9
+ * reported_<session>_<turn>.json one-shot marker for a terminal fact
10
+ * ended_<session>_<turn>.json Stop marker a late selector must observe
11
+ *
12
+ * The `started` marker is what keeps the ordering gate alive for the whole
13
+ * turn: the selector withdraws the job as soon as it starts, and the result
14
+ * does not exist until scoring ends, so "job or result exists" would leave the
15
+ * entire scoring window unobserved (P1-1). Stop removes the turn state.
16
+ * SessionStart cannot address one turn (its payload has no `turn_id`), so it
17
+ * only sweeps residue above the age bound.
18
+ *
19
+ * Nothing here is durable governance truth: the files are bound to one
20
+ * host-supplied `session_id` + `turn_id` and expire after a 20 s window.
21
+ * Delivery is claimed with `renameSync`, so a replayed or concurrent
22
+ * PostToolUse can emit at most one append.
23
+ */
24
+ import { randomUUID, createHash } from 'node:crypto';
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+ import { spawn } from 'node:child_process';
28
+ import { fileURLToPath } from 'node:url';
29
+ import { appendEventLogLine } from '@principles/core/runtime';
30
+ export const ADAPTIVE_APPEND_SCHEMA_VERSION = 1;
31
+ /** Whole-turn window for a background decision to still be usable. */
32
+ export const ADAPTIVE_APPEND_TTL_MS = 20_000;
33
+ /** Residue bound for files an abnormal exit left behind. */
34
+ export const ADAPTIVE_APPEND_MAX_AGE_MS = 10 * 60_000;
35
+ /** Maximum complete turn history accepted at the append boundary. */
36
+ export const ADAPTIVE_APPEND_MAX_OBSERVATIONS = 64;
37
+ const PREFIX = 'pd_adaptive_append_';
38
+ function stateDir(workspaceDir) {
39
+ return path.join(workspaceDir, '.state');
40
+ }
41
+ function keyOf(value) {
42
+ return createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 16);
43
+ }
44
+ function suffix(sessionId, turnId) {
45
+ return `${keyOf(sessionId)}_${keyOf(turnId)}`;
46
+ }
47
+ function jobPathFor(workspaceDir, sessionId, turnId) {
48
+ return path.join(stateDir(workspaceDir), `${PREFIX}job_${suffix(sessionId, turnId)}.json`);
49
+ }
50
+ function resultPathFor(workspaceDir, sessionId, turnId) {
51
+ return path.join(stateDir(workspaceDir), `${PREFIX}result_${suffix(sessionId, turnId)}.json`);
52
+ }
53
+ function toolsPathFor(workspaceDir, sessionId, turnId) {
54
+ return path.join(stateDir(workspaceDir), `${PREFIX}tools_${suffix(sessionId, turnId)}.jsonl`);
55
+ }
56
+ function reportedPathFor(workspaceDir, sessionId, turnId) {
57
+ return path.join(stateDir(workspaceDir), `${PREFIX}reported_${suffix(sessionId, turnId)}.json`);
58
+ }
59
+ function startedPathFor(workspaceDir, sessionId, turnId) {
60
+ return path.join(stateDir(workspaceDir), `${PREFIX}started_${suffix(sessionId, turnId)}.json`);
61
+ }
62
+ function endedPathFor(workspaceDir, sessionId, turnId) {
63
+ return path.join(stateDir(workspaceDir), `${PREFIX}ended_${suffix(sessionId, turnId)}.json`);
64
+ }
65
+ /**
66
+ * Turn-scoped "track this turn" marker. Written once at UserPromptSubmit,
67
+ * before the selector can withdraw the job, so the ordering gate keeps
68
+ * observing Pre/PostToolUse for the whole scoring window.
69
+ *
70
+ * The return value is also the "at most one scoring request per turn" gate:
71
+ * `exists` means a replayed prompt for the same turn must not spawn again.
72
+ */
73
+ export function markAdaptiveTurnStarted(input) {
74
+ try {
75
+ fs.mkdirSync(stateDir(input.workspaceDir), { recursive: true });
76
+ fs.writeFileSync(startedPathFor(input.workspaceDir, input.sessionId, input.turnId), JSON.stringify({ at: Date.now() }), { flag: 'wx' });
77
+ return 'created';
78
+ }
79
+ catch (error) {
80
+ if (error instanceof Error && Object.hasOwn(error, 'code') && Reflect.get(error, 'code') === 'EEXIST')
81
+ return 'exists';
82
+ return 'failed';
83
+ }
84
+ }
85
+ /** True while this turn may still record observations or has a decision artifact. */
86
+ export function hasAdaptiveAppendTurn(input) {
87
+ try {
88
+ return fs.existsSync(startedPathFor(input.workspaceDir, input.sessionId, input.turnId))
89
+ || fs.existsSync(jobPathFor(input.workspaceDir, input.sessionId, input.turnId))
90
+ || fs.existsSync(resultPathFor(input.workspaceDir, input.sessionId, input.turnId));
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ }
96
+ /**
97
+ * Mark the turn as finished before the cleanup. A background selector that
98
+ * finishes after Stop checks this marker and discards its decision, so a
99
+ * late result can never surface as this turn's outcome.
100
+ */
101
+ export function markAdaptiveTurnEnded(input) {
102
+ try {
103
+ fs.mkdirSync(stateDir(input.workspaceDir), { recursive: true });
104
+ fs.writeFileSync(endedPathFor(input.workspaceDir, input.sessionId, input.turnId), JSON.stringify({ at: Date.now() }), { flag: 'wx' });
105
+ }
106
+ catch {
107
+ // Already marked (or unwritable): the conservative branch is unchanged.
108
+ }
109
+ }
110
+ export function adaptiveTurnEnded(input) {
111
+ try {
112
+ return fs.existsSync(endedPathFor(input.workspaceDir, input.sessionId, input.turnId));
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ }
118
+ /** The installed hook entry of the process that wrote the job. */
119
+ export function currentHookIdentity() {
120
+ const [, entryPath] = process.argv;
121
+ if (typeof entryPath !== 'string' || entryPath.length === 0)
122
+ return null;
123
+ try {
124
+ return { entryPath, mtimeMs: fs.statSync(entryPath).mtimeMs };
125
+ }
126
+ catch {
127
+ return null;
128
+ }
129
+ }
130
+ function isRecord(value) {
131
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
132
+ }
133
+ function isFiniteNonNegative(value) {
134
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
135
+ }
136
+ /** rc-1/rc-3: strict job validation; an invalid job is unusable, never guessed. */
137
+ export function parseAdaptiveAppendJob(value) {
138
+ if (!isRecord(value))
139
+ return null;
140
+ if (value.schemaVersion !== ADAPTIVE_APPEND_SCHEMA_VERSION)
141
+ return null;
142
+ if (!isFiniteNonNegative(value.createdAt))
143
+ return null;
144
+ if (typeof value.sessionId !== 'string' || value.sessionId.length === 0)
145
+ return null;
146
+ if (typeof value.turnId !== 'string' || value.turnId.length === 0)
147
+ return null;
148
+ if (typeof value.workspaceDir !== 'string' || value.workspaceDir.length === 0)
149
+ return null;
150
+ if (typeof value.promptContent !== 'string')
151
+ return null;
152
+ if (!Array.isArray(value.nativeActivationIds) || !value.nativeActivationIds.every((id) => typeof id === 'string'))
153
+ return null;
154
+ if (!isFiniteNonNegative(value.nativeChars) || !isFiniteNonNegative(value.budgetChars))
155
+ return null;
156
+ let hookIdentity = null;
157
+ if (value.hookIdentity !== null && value.hookIdentity !== undefined) {
158
+ if (!isRecord(value.hookIdentity)
159
+ || typeof value.hookIdentity.entryPath !== 'string'
160
+ || typeof value.hookIdentity.mtimeMs !== 'number')
161
+ return null;
162
+ hookIdentity = { entryPath: value.hookIdentity.entryPath, mtimeMs: value.hookIdentity.mtimeMs };
163
+ }
164
+ return {
165
+ schemaVersion: ADAPTIVE_APPEND_SCHEMA_VERSION,
166
+ createdAt: value.createdAt,
167
+ sessionId: value.sessionId,
168
+ turnId: value.turnId,
169
+ workspaceDir: value.workspaceDir,
170
+ promptContent: value.promptContent,
171
+ nativeActivationIds: [...value.nativeActivationIds],
172
+ nativeChars: value.nativeChars,
173
+ budgetChars: value.budgetChars,
174
+ hookIdentity,
175
+ };
176
+ }
177
+ export function parseAdaptiveAppendResult(value) {
178
+ if (!isRecord(value))
179
+ return null;
180
+ if (value.schemaVersion !== ADAPTIVE_APPEND_SCHEMA_VERSION)
181
+ return null;
182
+ if (!isFiniteNonNegative(value.createdAt) || !isFiniteNonNegative(value.startedAt))
183
+ return null;
184
+ if (typeof value.sessionId !== 'string' || typeof value.turnId !== 'string')
185
+ return null;
186
+ if (!isRecord(value.target))
187
+ return null;
188
+ const { target } = value;
189
+ if (typeof target.revisionFingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(target.revisionFingerprint))
190
+ return null;
191
+ if (typeof target.principleId !== 'string' || typeof target.activationId !== 'string' || typeof target.artifactId !== 'string')
192
+ return null;
193
+ if (!isFiniteNonNegative(value.directiveChars) || !isFiniteNonNegative(value.budgetChars) || !isFiniteNonNegative(value.nativeChars))
194
+ return null;
195
+ if (!Array.isArray(value.nativeActivationIds) || !value.nativeActivationIds.every((id) => typeof id === 'string'))
196
+ return null;
197
+ let hookIdentity = null;
198
+ if (value.hookIdentity !== null && value.hookIdentity !== undefined) {
199
+ if (!isRecord(value.hookIdentity)
200
+ || typeof value.hookIdentity.entryPath !== 'string'
201
+ || typeof value.hookIdentity.mtimeMs !== 'number')
202
+ return null;
203
+ hookIdentity = { entryPath: value.hookIdentity.entryPath, mtimeMs: value.hookIdentity.mtimeMs };
204
+ }
205
+ return {
206
+ schemaVersion: ADAPTIVE_APPEND_SCHEMA_VERSION,
207
+ createdAt: value.createdAt,
208
+ startedAt: value.startedAt,
209
+ sessionId: value.sessionId,
210
+ turnId: value.turnId,
211
+ target: { principleId: target.principleId, activationId: target.activationId, artifactId: target.artifactId, revisionFingerprint: target.revisionFingerprint },
212
+ directiveChars: value.directiveChars,
213
+ nativeActivationIds: [...value.nativeActivationIds],
214
+ nativeChars: value.nativeChars,
215
+ budgetChars: value.budgetChars,
216
+ hookIdentity,
217
+ };
218
+ }
219
+ function writeAtomic(target, body, mode) {
220
+ fs.mkdirSync(path.dirname(target), { recursive: true });
221
+ const temp = `${target}.${process.pid}.${randomUUID()}.tmp`;
222
+ fs.writeFileSync(temp, JSON.stringify(body), mode === undefined ? undefined : { mode });
223
+ fs.renameSync(temp, target);
224
+ }
225
+ function unlinkQuietly(target) {
226
+ try {
227
+ fs.unlinkSync(target);
228
+ }
229
+ catch {
230
+ // ENOENT and an in-use file both mean "nothing to release".
231
+ }
232
+ }
233
+ /**
234
+ * Parent side: create the job ONCE per turn, then hand it to a DETACHED
235
+ * process. `wx` is the gate behind "at most one scoring request per turn": a
236
+ * retried/replayed UserPromptSubmit for the same turn cannot replace the job
237
+ * and spawn a second selector. The job carries the Owner prompt for the
238
+ * decision request only, so the file is owner-only (0600) and is withdrawn by
239
+ * the selector as soon as it reads it; a write that never reaches the selector
240
+ * is removed here or aged out by the residue sweep.
241
+ */
242
+ export function writeAdaptiveAppendJob(job) {
243
+ const jobPath = jobPathFor(job.workspaceDir, job.sessionId, job.turnId);
244
+ try {
245
+ fs.mkdirSync(path.dirname(jobPath), { recursive: true });
246
+ fs.writeFileSync(jobPath, JSON.stringify(job), { flag: 'wx', mode: 0o600 });
247
+ return { ok: true, jobPath };
248
+ }
249
+ catch (error) {
250
+ if (error instanceof Error && Object.hasOwn(error, 'code') && Reflect.get(error, 'code') === 'EEXIST') {
251
+ return { ok: false, reason: 'already_started' };
252
+ }
253
+ return { ok: false, reason: 'job_write_failed' };
254
+ }
255
+ }
256
+ /** A job that could not be handed off must not leave the prompt on disk. */
257
+ export function discardAdaptiveAppendJob(jobPath) {
258
+ unlinkQuietly(jobPath);
259
+ }
260
+ /**
261
+ * Spawn the background selector. `stdio: 'ignore'` is mandatory: a detached
262
+ * child that inherited the hook's stdout pipe would keep that pipe open and
263
+ * hold the host's first request until the decision finished.
264
+ */
265
+ export function spawnAdaptiveBackgroundSelection(jobPath) {
266
+ try {
267
+ const entry = fileURLToPath(new URL('../background-selection.js', import.meta.url));
268
+ const child = spawn(process.execPath, [entry, jobPath], {
269
+ detached: true,
270
+ stdio: 'ignore',
271
+ windowsHide: true,
272
+ env: process.env,
273
+ });
274
+ // Async spawn failures arrive as an 'error' event, not a throw. Without a
275
+ // listener that event is an uncaught exception in the hook process, which
276
+ // would break the fail-open contract; the failure is already represented by
277
+ // the job file the residue sweep will remove.
278
+ child.on('error', () => undefined);
279
+ child.unref();
280
+ if (child.pid === undefined)
281
+ return { ok: false, reason: 'spawn_no_pid' };
282
+ return { ok: true, pid: child.pid };
283
+ }
284
+ catch (error) {
285
+ return { ok: false, reason: error instanceof Error ? error.message.slice(0, 160) : 'spawn_failed' };
286
+ }
287
+ }
288
+ /** Child side: read and immediately withdraw the job (the prompt is not kept). */
289
+ export function takeAdaptiveAppendJob(jobPath) {
290
+ let raw;
291
+ try {
292
+ raw = fs.readFileSync(jobPath, 'utf8');
293
+ }
294
+ catch {
295
+ return null;
296
+ }
297
+ try {
298
+ fs.unlinkSync(jobPath);
299
+ }
300
+ catch {
301
+ // The job is single-use; a leftover file is aged out by the residue sweep.
302
+ }
303
+ try {
304
+ return parseAdaptiveAppendJob(JSON.parse(raw));
305
+ }
306
+ catch {
307
+ return null;
308
+ }
309
+ }
310
+ /** Persist the ONE ready decision for this turn. */
311
+ export function writeAdaptiveAppendResultFor(workspaceDir, result) {
312
+ writeAtomic(resultPathFor(workspaceDir, result.sessionId, result.turnId), result, 0o600);
313
+ }
314
+ /** Withdraw a result whose turn ended while it was being written. */
315
+ export function discardAdaptiveAppendResult(workspaceDir, sessionId, turnId) {
316
+ unlinkQuietly(resultPathFor(workspaceDir, sessionId, turnId));
317
+ }
318
+ /**
319
+ * Atomically claim the ready result. `renameSync` is the mutex: exactly one
320
+ * concurrent consumer can move the file, so a replayed callback emits nothing.
321
+ */
322
+ export function claimAdaptiveAppendResult(input) {
323
+ const resultPath = resultPathFor(input.workspaceDir, input.sessionId, input.turnId);
324
+ const claimPath = `${resultPath}.claimed_${process.pid}_${randomUUID()}`;
325
+ try {
326
+ fs.renameSync(resultPath, claimPath);
327
+ }
328
+ catch (error) {
329
+ if (error instanceof Error && Object.hasOwn(error, 'code') && Reflect.get(error, 'code') === 'ENOENT') {
330
+ return { status: 'absent' };
331
+ }
332
+ return { status: 'invalid', reason: 'claim_failed' };
333
+ }
334
+ let parsed;
335
+ try {
336
+ parsed = parseAdaptiveAppendResult(JSON.parse(fs.readFileSync(claimPath, 'utf8')));
337
+ }
338
+ catch {
339
+ parsed = null;
340
+ }
341
+ if (!parsed) {
342
+ unlinkQuietly(claimPath);
343
+ return { status: 'invalid', reason: 'result_unreadable' };
344
+ }
345
+ if (parsed.sessionId !== input.sessionId || parsed.turnId !== input.turnId) {
346
+ unlinkQuietly(claimPath);
347
+ return { status: 'invalid', reason: 'identity_mismatch' };
348
+ }
349
+ if (!Number.isFinite(parsed.startedAt) || input.now - parsed.startedAt > ADAPTIVE_APPEND_TTL_MS) {
350
+ unlinkQuietly(claimPath);
351
+ return { status: 'expired', reason: 'ttl_expired' };
352
+ }
353
+ return { status: 'ready', result: parsed, claimPath };
354
+ }
355
+ export function releaseAdaptiveAppendClaim(claimPath) {
356
+ unlinkQuietly(claimPath);
357
+ }
358
+ export function appendToolObservation(input) {
359
+ const target = toolsPathFor(input.workspaceDir, input.sessionId, input.turnId);
360
+ try {
361
+ fs.mkdirSync(path.dirname(target), { recursive: true });
362
+ fs.appendFileSync(target, `${JSON.stringify(input.observation)}\n`);
363
+ }
364
+ catch {
365
+ // Observation loss downgrades to the conservative branch: no proof of
366
+ // ordering means no append. Never fail the tool call.
367
+ }
368
+ }
369
+ export function readToolObservations(input) {
370
+ let raw;
371
+ try {
372
+ raw = fs.readFileSync(toolsPathFor(input.workspaceDir, input.sessionId, input.turnId), 'utf8');
373
+ }
374
+ catch {
375
+ return [];
376
+ }
377
+ const lines = raw.split('\n').filter((line) => line.trim().length > 0);
378
+ // A partial history cannot establish that the current tool preceded the first write.
379
+ if (lines.length > ADAPTIVE_APPEND_MAX_OBSERVATIONS)
380
+ return [];
381
+ const observations = [];
382
+ for (const line of lines) {
383
+ try {
384
+ const value = JSON.parse(line);
385
+ if (!isRecord(value))
386
+ return [];
387
+ if (value.phase !== 'pre' && value.phase !== 'post')
388
+ return [];
389
+ if (typeof value.toolCallId !== 'string' || typeof value.toolName !== 'string')
390
+ return [];
391
+ if (typeof value.canonicalKind !== 'string' || typeof value.readOnly !== 'boolean' || !isFiniteNonNegative(value.at))
392
+ return [];
393
+ observations.push({
394
+ phase: value.phase,
395
+ toolCallId: value.toolCallId,
396
+ toolName: value.toolName,
397
+ canonicalKind: value.canonicalKind,
398
+ readOnly: value.readOnly,
399
+ at: value.at,
400
+ });
401
+ }
402
+ catch {
403
+ return [];
404
+ }
405
+ }
406
+ return observations;
407
+ }
408
+ /**
409
+ * The ordering gate:
410
+ * - the CURRENT call must have been observed at both boundaries — a lone
411
+ * post proves nothing about what happened before it;
412
+ * - a `write` call anywhere in this turn ends the opportunity;
413
+ * - an execute call that is not classified `safe`, or an unresolved kind,
414
+ * is "semantics unknown" and ends it too;
415
+ * - another call opened and not yet closed means the completion order of a
416
+ * parallel batch cannot be proven; a replayed post is a duplicate callback.
417
+ */
418
+ export function evaluateAppendOrdering(observations, currentToolCallId) {
419
+ if (observations.length === 0)
420
+ return { ok: false, reason: 'ordering_unprovable' };
421
+ const opened = new Set(observations.filter((entry) => entry.phase === 'pre').map((entry) => entry.toolCallId));
422
+ const closed = new Set(observations.filter((entry) => entry.phase === 'post').map((entry) => entry.toolCallId));
423
+ let sawCurrentPost = false;
424
+ for (const entry of observations) {
425
+ if (entry.toolCallId === currentToolCallId && entry.phase === 'post') {
426
+ if (sawCurrentPost)
427
+ return { ok: false, reason: 'duplicate_callback' };
428
+ sawCurrentPost = true;
429
+ continue;
430
+ }
431
+ if (entry.canonicalKind === 'write')
432
+ return { ok: false, reason: 'mutating_tool_observed' };
433
+ if (entry.canonicalKind === 'other')
434
+ return { ok: false, reason: 'unknown_tool_observed' };
435
+ if (entry.canonicalKind === 'execute' && entry.readOnly !== true) {
436
+ return { ok: false, reason: 'unknown_tool_observed' };
437
+ }
438
+ }
439
+ if (!sawCurrentPost || !opened.has(currentToolCallId) || !closed.has(currentToolCallId)) {
440
+ return { ok: false, reason: 'ordering_unprovable' };
441
+ }
442
+ for (const entry of observations) {
443
+ if (entry.phase !== 'pre')
444
+ continue;
445
+ if (entry.toolCallId === currentToolCallId)
446
+ continue;
447
+ if (!closed.has(entry.toolCallId))
448
+ return { ok: false, reason: 'parallel_order_unprovable' };
449
+ }
450
+ return { ok: true };
451
+ }
452
+ /** Delete every short-lived file of one turn (Stop / terminal drop). */
453
+ export function clearAdaptiveAppendTurn(input) {
454
+ const dir = stateDir(input.workspaceDir);
455
+ const keys = suffix(input.sessionId, input.turnId);
456
+ let entries;
457
+ try {
458
+ entries = fs.readdirSync(dir);
459
+ }
460
+ catch {
461
+ return;
462
+ }
463
+ for (const name of entries) {
464
+ if (!name.startsWith(PREFIX) || !name.includes(keys))
465
+ continue;
466
+ // The ended marker outlives the turn's state: a late selector reads it.
467
+ if (name.startsWith(`${PREFIX}ended_`))
468
+ continue;
469
+ unlinkQuietly(path.join(dir, name));
470
+ }
471
+ }
472
+ /** Opportunistic residue sweep; bounded and age-based, never touches fresh state. */
473
+ export function clearStaleAdaptiveAppendState(workspaceDir, now) {
474
+ const dir = stateDir(workspaceDir);
475
+ let entries;
476
+ try {
477
+ entries = fs.readdirSync(dir).slice(0, 200);
478
+ }
479
+ catch {
480
+ return;
481
+ }
482
+ for (const name of entries) {
483
+ if (!name.startsWith(PREFIX))
484
+ continue;
485
+ const target = path.join(dir, name);
486
+ try {
487
+ if (now - fs.statSync(target).mtimeMs > ADAPTIVE_APPEND_MAX_AGE_MS)
488
+ unlinkQuietly(target);
489
+ }
490
+ catch {
491
+ continue;
492
+ }
493
+ }
494
+ }
495
+ /**
496
+ * One-shot marker for a terminal fact of this turn. Returns true only to the
497
+ * caller that created it, so concurrent hooks emit the fact once.
498
+ */
499
+ export function claimAdaptiveReportMarker(input) {
500
+ const target = reportedPathFor(input.workspaceDir, input.sessionId, input.turnId);
501
+ try {
502
+ fs.mkdirSync(path.dirname(target), { recursive: true });
503
+ fs.writeFileSync(target, JSON.stringify({ reason: input.reason, at: Date.now() }), { flag: 'wx' });
504
+ return true;
505
+ }
506
+ catch {
507
+ return false;
508
+ }
509
+ }
510
+ /**
511
+ * The console reads `runtime_v2_prompt_activations_injected` with an
512
+ * `adaptive` fact. "Background selected" is emitted with empty arrays (no
513
+ * injection claim); "appended" carries exactly the one principle that was
514
+ * added to the later request.
515
+ */
516
+ export function appendAdaptiveAppendFact(input) {
517
+ const { appended } = input;
518
+ const data = {
519
+ eventId: randomUUID(),
520
+ sessionId: input.sessionId,
521
+ runId: input.turnId,
522
+ workspaceDir: input.workspaceDir,
523
+ principleIds: appended ? [appended.principleId] : [],
524
+ activationIds: appended ? [appended.activationId] : [],
525
+ artifactIds: appended ? [appended.artifactId] : [],
526
+ injectedCount: appended ? 1 : 0,
527
+ skippedWarnings: [],
528
+ injectedCharCount: input.injectedCharCount,
529
+ budget: input.budget,
530
+ hostKind: 'codex',
531
+ adaptive: {
532
+ resultCode: input.resultCode.slice(0, 240),
533
+ scored: input.scored,
534
+ ...(appended ? { appendedActivationId: appended.activationId } : {}),
535
+ },
536
+ };
537
+ appendEventLogLine(input.stateDir, {
538
+ ts: new Date().toISOString(),
539
+ type: 'runtime_v2_prompt_activations_injected',
540
+ category: 'injected',
541
+ sessionId: input.sessionId,
542
+ data,
543
+ });
544
+ }
package/dist/pd-hook.js CHANGED
@@ -5,7 +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 { ADAPTIVE_SELECTION_LIMITS, createAdaptivePriorityProviderForConfig, createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveHostToolSemanticsForHook, resolveNearestPdWorkspace } from '@principles/host-runtime';
8
+ import { ADAPTIVE_SELECTION_LIMITS, createAdaptivePriorityProviderForConfig, createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, renderAcceptedAdaptiveAppend, resolveHostToolSemanticsForHook, resolveNearestPdWorkspace } from '@principles/host-runtime';
9
+ import { classifyBashRisk } from '@principles/core/runtime/internalization/bash-risk';
9
10
  import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from './tool-semantics.js';
10
11
  import { computeFeatureFlagsFromConfig } from '@principles/core/runtime';
11
12
  import { CodexHooksHostAdapter } from './host-adapter.js';
@@ -15,6 +16,7 @@ import { runGovernanceAdmission } from './ingestion/admission.js';
15
16
  import { parseOwnerStatementPrefix, recordExplicitOwnerStatement } from './ingestion/explicit-owner-statement.js';
16
17
  import { writeCurrentTurnContext, clearCurrentTurnContext } from './ingestion/turn-context.js';
17
18
  import { recordCodexPromptDeliveryEvidence, recordCodexDenyEvidence } from './codex-evidence-recorder.js';
19
+ import { ADAPTIVE_APPEND_SCHEMA_VERSION, appendAdaptiveAppendFact, appendToolObservation, claimAdaptiveAppendResult, claimAdaptiveReportMarker, clearAdaptiveAppendTurn, clearStaleAdaptiveAppendState, currentHookIdentity, discardAdaptiveAppendJob, evaluateAppendOrdering, hasAdaptiveAppendTurn, markAdaptiveTurnEnded, markAdaptiveTurnStarted, readToolObservations, releaseAdaptiveAppendClaim, spawnAdaptiveBackgroundSelection, writeAdaptiveAppendJob, } from './ingestion/adaptive-append-state.js';
18
20
  const MAX_DIAGNOSTIC = 500;
19
21
  function diagnostic(reason, nextAction) {
20
22
  const boundedReason = reason.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
@@ -126,6 +128,108 @@ function codexEventEmitter(stateDir, evidence, readAdaptiveFact) {
126
128
  },
127
129
  };
128
130
  }
131
+ /** One bounded Adaptive fact line; evidence is best-effort and never blocks the hook. */
132
+ function emitBackgroundFact(key, fact) {
133
+ try {
134
+ appendAdaptiveAppendFact({
135
+ stateDir: key.stateDir,
136
+ sessionId: key.sessionId,
137
+ turnId: key.turnId,
138
+ workspaceDir: key.workspaceDir,
139
+ resultCode: fact.resultCode,
140
+ scored: fact.scored,
141
+ budget: fact.budget,
142
+ injectedCharCount: fact.injectedCharCount,
143
+ ...(fact.appended ? { appended: fact.appended } : {}),
144
+ });
145
+ }
146
+ catch {
147
+ // A failed evidence write must not change the host decision.
148
+ }
149
+ }
150
+ /** Emit at most ONE terminal drop fact for this turn. */
151
+ function reportBackgroundDrop(key, drop) {
152
+ if (!claimAdaptiveReportMarker({ ...key, reason: drop.reason }))
153
+ return;
154
+ emitBackgroundFact(key, {
155
+ resultCode: `skipped:background_${drop.reason}`,
156
+ scored: drop.scored,
157
+ budget: drop.budget,
158
+ injectedCharCount: 0,
159
+ });
160
+ }
161
+ /**
162
+ * Turn end: claim any ready result, record one honest terminal fact, mark the
163
+ * turn ended (a late selector must discard its decision) and clear the state.
164
+ *
165
+ * Unconditional mark/clear: Stop can land while the selector is still scoring,
166
+ * when neither a job nor a result exists. Returning early there used to skip
167
+ * the marker, so the late result landed in an ended turn with no terminal fact
168
+ * and the console stayed on "waiting for the next request" (P1-2).
169
+ */
170
+ function finalizeBackgroundTurn(key) {
171
+ const claimed = claimAdaptiveAppendResult({ ...key, now: Date.now() });
172
+ if (claimed.status === 'ready') {
173
+ releaseAdaptiveAppendClaim(claimed.claimPath);
174
+ reportBackgroundDrop(key, { reason: 'turn_ended', scored: true, budget: claimed.result.budgetChars });
175
+ }
176
+ else if (claimed.status === 'expired') {
177
+ reportBackgroundDrop(key, { reason: 'expired', scored: true, budget: 0 });
178
+ }
179
+ else {
180
+ reportBackgroundDrop(key, { reason: 'turn_ended', scored: false, budget: 0 });
181
+ }
182
+ markAdaptiveTurnEnded(key);
183
+ clearAdaptiveAppendTurn(key);
184
+ }
185
+ /**
186
+ * "Qualified read-only" is the existing semantic declaration plus the existing
187
+ * shell-risk classifier: a `write` kind, an unresolved kind, or an execute
188
+ * command that cannot be proven `safe` never qualifies.
189
+ */
190
+ function resolveAppendToolFacts(kind, toolInput) {
191
+ if (kind === 'execute')
192
+ return { readOnly: classifyBashRisk(true, toolInput) === 'safe' };
193
+ return { readOnly: kind === 'read' || kind === 'search' };
194
+ }
195
+ /**
196
+ * Consume-time proof. The decision may be seconds old, so the target's
197
+ * authorization/body is re-read through the shared revalidator, the installed
198
+ * hook identity must be unchanged, and the directive must still fit the
199
+ * Native budget reported for THIS turn.
200
+ */
201
+ async function consumeBackgroundAppend(input) {
202
+ const currentIdentity = currentHookIdentity();
203
+ const storedIdentity = input.result.hookIdentity;
204
+ if (!currentIdentity || !storedIdentity)
205
+ return { ok: false, reason: 'version_unverified' };
206
+ if (currentIdentity.entryPath !== storedIdentity.entryPath || currentIdentity.mtimeMs !== storedIdentity.mtimeMs) {
207
+ return { ok: false, reason: 'version_changed' };
208
+ }
209
+ if (input.result.nativeActivationIds.includes(input.result.target.activationId)) {
210
+ return { ok: false, reason: 'already_native' };
211
+ }
212
+ const rendered = await renderAcceptedAdaptiveAppend({
213
+ workspaceDir: input.workspaceDir,
214
+ target: input.result.target,
215
+ signal: AbortSignal.timeout(1500),
216
+ });
217
+ if (!rendered.ok)
218
+ return { ok: false, reason: rendered.reason };
219
+ if (input.result.nativeChars + rendered.directive.length > input.result.budgetChars) {
220
+ return { ok: false, reason: 'budget_exhausted' };
221
+ }
222
+ return {
223
+ ok: true,
224
+ directive: rendered.directive,
225
+ target: {
226
+ principleId: rendered.principle.principleId,
227
+ activationId: rendered.principle.activationId,
228
+ artifactId: rendered.principle.artifactId,
229
+ revisionFingerprint: input.result.target.revisionFingerprint,
230
+ },
231
+ };
232
+ }
129
233
  /**
130
234
  * PRI-813: admissible evaluation entry = the CANONICAL core schema guard
131
235
  * (rc-1/rc-2, P4: no hand-rolled field copy that could drift from the
@@ -310,6 +414,11 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
310
414
  return { stdout: {}, exitCode: 0, stderr: [diagnostic('host.codex_disabled', 'Enable PD in the selected Workspace .pd/config.yaml — in the existing "features:" block set host.codex: {enabled: true} (one flat key, not nested).')] };
311
415
  }
312
416
  const ingestionEnabled = flags.codex_conversation_ingestion?.enabled === true;
417
+ // PRI-1196: selection timing. Absent = 'sync' — every existing workspace
418
+ // keeps the historical behavior. Background mode never builds the sync
419
+ // provider, so this turn cannot be scored twice.
420
+ const adaptiveTiming = config.effective.config.adaptiveActivation?.timing === 'background' ? 'background' : 'sync';
421
+ const backgroundSelectionEnabled = flags['host.codex.adaptive_activation']?.enabled === true && adaptiveTiming === 'background';
313
422
  if (event.kind === 'turn_complete') {
314
423
  // Withdraw the live turn context: once the turn completes, the
315
424
  // agent-assisted explicit entry must fail closed (turn_context_missing)
@@ -333,6 +442,19 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
333
442
  const stderr = ingestionEnabled
334
443
  ? [...clearDiagnostics, ...await runConversationIngestion({ rawPayload: parsed, kind: event.kind, workspaceDir: resolution.workspaceDir, env: _env })]
335
444
  : [...clearDiagnostics, diagnostic('feature_disabled', 'Enable bounded conversation ingestion in the selected Workspace .pd/config.yaml — in the existing "features:" block set codex_conversation_ingestion: {enabled: true} (one flat key, not nested).')];
445
+ // Clean up the background turn whenever THIS turn was tracked, even if the
446
+ // timing was switched back to `sync` mid-turn: the started marker outlives
447
+ // the setting, and leaving it behind would strand a late result (P1-2).
448
+ if (event.context.turnId !== undefined) {
449
+ const backgroundKey = {
450
+ workspaceDir: resolution.workspaceDir,
451
+ stateDir: path.join(resolution.workspaceDir, '.state'),
452
+ sessionId: event.context.sessionId,
453
+ turnId: event.context.turnId,
454
+ };
455
+ if (hasAdaptiveAppendTurn(backgroundKey))
456
+ finalizeBackgroundTurn(backgroundKey);
457
+ }
336
458
  return { stdout: {}, exitCode: 0, stderr };
337
459
  }
338
460
  try {
@@ -343,6 +465,9 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
343
465
  const clearDiagnostics = cleared.ok
344
466
  ? []
345
467
  : [diagnostic(`turn_context_${cleared.reason}`, 'The turn context could not be withdrawn; the agent-assisted explicit entry stays fail-closed only via its staleness bound. Inspect the workspace .state directory.')];
468
+ // A SessionStart payload carries no turn_id, so per-turn cleanup is not
469
+ // addressable; sweep only residue above the age bound (P2-3).
470
+ clearStaleAdaptiveAppendState(resolution.workspaceDir, Date.now());
346
471
  const health = await createProductionHostRuntime({ hostKind: 'codex' }).health(resolution.workspaceDir);
347
472
  if (!health.ok)
348
473
  return { stdout: {}, exitCode: 0, stderr: [...clearDiagnostics, diagnostic(health.reason ?? 'runtime_unhealthy', health.nextAction ?? 'Inspect the Workspace runtime.')] };
@@ -450,7 +575,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
450
575
  const adaptiveDiagnostics = [];
451
576
  let adaptivePriorityProvider;
452
577
  let adaptiveTurnFact = null;
453
- if (event.kind === 'before_prompt_build' && flags['host.codex.adaptive_activation']?.enabled === true) {
578
+ if (event.kind === 'before_prompt_build' && flags['host.codex.adaptive_activation']?.enabled === true && adaptiveTiming === 'sync') {
454
579
  const adaptive = createAdaptivePriorityProviderForConfig(config.effective.config, resolution.workspaceDir, {
455
580
  env: _env,
456
581
  ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
@@ -501,6 +626,63 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
501
626
  // defaults) and must be visible on stderr (rc-9).
502
627
  ? toolSemanticsResolution.warnings.map((warning) => diagnostic(warning, 're-run this host so it refreshes its persisted tool declaration'))
503
628
  : [diagnostic(toolSemanticsResolution.reason, toolSemanticsResolution.nextAction)];
629
+ // PRI-1196: the background decision is bound to THIS host turn. The
630
+ // `started` marker (written below) keeps ordering observation alive for the
631
+ // whole turn, including the scoring window in which neither a job nor a
632
+ // result exists (P1-1).
633
+ const backgroundTurnKey = backgroundSelectionEnabled && event.context.turnId !== undefined
634
+ ? {
635
+ workspaceDir: resolution.workspaceDir,
636
+ stateDir: path.join(resolution.workspaceDir, '.state'),
637
+ sessionId: event.context.sessionId,
638
+ turnId: event.context.turnId,
639
+ }
640
+ : null;
641
+ // Residue sweep runs on EVERY prompt build, including after the timing was
642
+ // switched back to `sync` or the switch was turned off — the job carries the
643
+ // Owner prompt and must not wait for the feature to be re-enabled (P2-1).
644
+ let turnStartedNow = 'failed';
645
+ if (event.kind === 'before_prompt_build') {
646
+ clearStaleAdaptiveAppendState(resolution.workspaceDir, Date.now());
647
+ if (backgroundTurnKey)
648
+ turnStartedNow = markAdaptiveTurnStarted(backgroundTurnKey);
649
+ }
650
+ const toolKind = toolSemantics.resolve(event.context.toolName ?? '');
651
+ const appendToolFacts = resolveAppendToolFacts(toolKind, event.context.toolInput);
652
+ if (backgroundTurnKey
653
+ && event.context.toolCallId !== undefined
654
+ && (event.kind === 'before_tool_call' || event.kind === 'after_tool_call')
655
+ && hasAdaptiveAppendTurn(backgroundTurnKey)) {
656
+ appendToolObservation({
657
+ ...backgroundTurnKey,
658
+ observation: {
659
+ phase: event.kind === 'before_tool_call' ? 'pre' : 'post',
660
+ toolCallId: event.context.toolCallId,
661
+ toolName: event.context.toolName ?? '',
662
+ canonicalKind: toolKind,
663
+ readOnly: appendToolFacts.readOnly,
664
+ at: Date.now(),
665
+ },
666
+ });
667
+ }
668
+ // Capture the Native assembly facts the background job must match. The
669
+ // emitter receives them from the runtime; no second prompt build is needed.
670
+ const nativeCapture = { value: null };
671
+ const baseEmitter = codexEventEmitter(path.join(resolution.workspaceDir, '.state'), evidenceContext, () => adaptiveTurnFact);
672
+ const events = {
673
+ ...baseEmitter,
674
+ recordRuntimeActivationsInjected(data) {
675
+ nativeCapture.value = {
676
+ activationIds: [...data.activationIds],
677
+ injectedCharCount: data.injectedCharCount,
678
+ budget: data.budget,
679
+ capacitySource: data.budgetCapacitySource,
680
+ capacityStatus: data.budgetCapacityStatus,
681
+ contextWindowTokens: data.budgetContextWindowTokens,
682
+ };
683
+ baseEmitter.recordRuntimeActivationsInjected(data);
684
+ },
685
+ };
504
686
  const result = await createProductionHostRuntime({
505
687
  projectDir: requestedCwd,
506
688
  hostKind: 'codex',
@@ -514,7 +696,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
514
696
  currentToolUseId: event.context.toolCallId ?? '',
515
697
  toolSemantics,
516
698
  }),
517
- events: codexEventEmitter(path.join(resolution.workspaceDir, '.state'), evidenceContext, () => adaptiveTurnFact),
699
+ events,
518
700
  }).dispatch(event);
519
701
  // PRI-813: the shared gate's evaluation facts leave through metadata —
520
702
  // persist them here (telemetry persistence is host-side business; the
@@ -526,7 +708,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
526
708
  // claims only what reached stdout (codex_permission_decision_encoded).
527
709
  // V2 rules remain suspended by the shared gate when this provider reports
528
710
  // unavailable history; that degraded state is preserved in stderr.
529
- const encoded = adapter.encodeOutput(result, event.kind);
711
+ let encoded = adapter.encodeOutput(result, event.kind);
530
712
  // CR-07 (A16): the explicit-statement receipt rides as additional context
531
713
  // so the model can answer truthfully about what happened (received +
532
714
  // queued), instead of guessing or claiming it is still waiting for input.
@@ -538,6 +720,148 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
538
720
  : explicitReceiptContext;
539
721
  }
540
722
  }
723
+ const backgroundDiagnostics = [];
724
+ // PRI-1196 — background start. The Native body is ALREADY encoded above;
725
+ // this only writes a single-use job and hands it to a detached process.
726
+ // It never awaits the decision, and the child has no inherited stdio.
727
+ if (backgroundTurnKey && event.kind === 'before_prompt_build') {
728
+ const injection = nativeCapture.value;
729
+ if (injection === null) {
730
+ emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: 0, injectedCharCount: 0 });
731
+ backgroundDiagnostics.push(diagnostic('adaptive_background_spawn_failed:native_assembly_missing', 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
732
+ }
733
+ else {
734
+ const output = encoded;
735
+ const nativeText = output.hookSpecificOutput?.additionalContext;
736
+ const nativeChars = typeof nativeText === 'string' ? nativeText.length : injection.injectedCharCount;
737
+ try {
738
+ if (turnStartedNow === 'exists') {
739
+ // A retried/replayed UserPromptSubmit for the same turn must not
740
+ // start a second scoring request (P2-5). The `started` marker is the
741
+ // gate that survives the selector withdrawing its job.
742
+ emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:already_started', scored: false, budget: injection.budget, injectedCharCount: 0 });
743
+ }
744
+ else {
745
+ const written = writeAdaptiveAppendJob({
746
+ schemaVersion: ADAPTIVE_APPEND_SCHEMA_VERSION,
747
+ createdAt: Date.now(),
748
+ sessionId: event.context.sessionId,
749
+ turnId: backgroundTurnKey.turnId,
750
+ workspaceDir: resolution.workspaceDir,
751
+ promptContent: event.context.promptContent ?? '',
752
+ nativeActivationIds: injection.activationIds,
753
+ nativeChars,
754
+ budgetChars: injection.budget,
755
+ hookIdentity: currentHookIdentity(),
756
+ });
757
+ if (!written.ok) {
758
+ if (written.reason === 'already_started') {
759
+ emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:already_started', scored: false, budget: injection.budget, injectedCharCount: 0 });
760
+ }
761
+ else {
762
+ emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: injection.budget, injectedCharCount: 0 });
763
+ backgroundDiagnostics.push(diagnostic('adaptive_background_job_failed', 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
764
+ }
765
+ }
766
+ else {
767
+ const spawned = spawnAdaptiveBackgroundSelection(written.jobPath);
768
+ if (!spawned.ok) {
769
+ discardAdaptiveAppendJob(written.jobPath);
770
+ emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: injection.budget, injectedCharCount: 0 });
771
+ backgroundDiagnostics.push(diagnostic(`adaptive_background_spawn_failed:${spawned.reason}`, 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
772
+ }
773
+ else {
774
+ emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawned', scored: false, budget: injection.budget, injectedCharCount: 0 });
775
+ }
776
+ }
777
+ }
778
+ }
779
+ catch (error) {
780
+ emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: injection.budget, injectedCharCount: 0 });
781
+ backgroundDiagnostics.push(diagnostic(`adaptive_background_job_failed:${errorMessage(error)}`, 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
782
+ }
783
+ }
784
+ }
785
+ // PRI-1196 — consume at a qualified read-only tool boundary of the SAME
786
+ // turn. The claim rename makes replay/concurrency emit at most once.
787
+ if (backgroundTurnKey && event.kind === 'after_tool_call' && event.context.toolCallId !== undefined) {
788
+ const claimed = claimAdaptiveAppendResult({ ...backgroundTurnKey, now: Date.now() });
789
+ if (claimed.status === 'invalid') {
790
+ // The claim already withdrew the unreadable result; without a fact the
791
+ // console would keep showing "waiting for the next request" (rc-9, P2-2).
792
+ reportBackgroundDrop(backgroundTurnKey, { reason: claimed.reason ?? 'result_invalid', scored: true, budget: 0 });
793
+ }
794
+ else if (!appendToolFacts.readOnly) {
795
+ if (claimed.status === 'ready') {
796
+ releaseAdaptiveAppendClaim(claimed.claimPath);
797
+ reportBackgroundDrop(backgroundTurnKey, {
798
+ reason: toolKind === 'write' ? 'mutating_tool' : 'unknown_tool',
799
+ scored: true,
800
+ budget: claimed.result.budgetChars,
801
+ });
802
+ }
803
+ }
804
+ else {
805
+ const ordering = evaluateAppendOrdering(readToolObservations(backgroundTurnKey), event.context.toolCallId);
806
+ if (!ordering.ok) {
807
+ if (claimed.status === 'ready') {
808
+ releaseAdaptiveAppendClaim(claimed.claimPath);
809
+ reportBackgroundDrop(backgroundTurnKey, { reason: ordering.reason, scored: true, budget: claimed.result.budgetChars });
810
+ }
811
+ }
812
+ else if (claimed.status === 'expired') {
813
+ reportBackgroundDrop(backgroundTurnKey, { reason: 'expired', scored: true, budget: 0 });
814
+ }
815
+ else if (claimed.status === 'ready') {
816
+ const consumed = await consumeBackgroundAppend({
817
+ workspaceDir: resolution.workspaceDir,
818
+ result: claimed.result,
819
+ });
820
+ if (consumed.ok) {
821
+ // The appended directive is additional context for the NEXT model
822
+ // request; Native items and their order are untouched.
823
+ //
824
+ // This calls the Codex encoder DIRECTLY instead of routing the
825
+ // result through the shared dispatch: `hasValidResultSemantics`
826
+ // (host-runtime) deliberately forbids `after_tool_call` results
827
+ // carrying `additionalContext`, while the Codex host contract
828
+ // accepts exactly that shape (codex-adapter spec §5.3.2). The
829
+ // shared rule encodes the host-neutral default; the Codex adapter
830
+ // is the host authority for its own output shape. If upstream later
831
+ // generalises that rule, this direct call stays correct only as
832
+ // long as `encodeOutput` remains the Codex output authority.
833
+ encoded = adapter.encodeOutput({ decision: 'observe', source: event.source, additionalContext: consumed.directive }, 'after_tool_call');
834
+ emitBackgroundFact(backgroundTurnKey, {
835
+ resultCode: 'selected:background_appended',
836
+ scored: true,
837
+ budget: claimed.result.budgetChars,
838
+ injectedCharCount: consumed.directive.length,
839
+ appended: consumed.target,
840
+ });
841
+ // Terminal fact for this turn: a later Stop must not overwrite it
842
+ // with "turn ended" in "上一次结果".
843
+ claimAdaptiveReportMarker({ ...backgroundTurnKey, reason: 'appended' });
844
+ try {
845
+ recordCodexPromptDeliveryEvidence({
846
+ workspaceDir: resolution.workspaceDir,
847
+ sessionId: event.context.sessionId,
848
+ turnId: backgroundTurnKey.turnId,
849
+ injected: [consumed.target],
850
+ evidenceEnabled: evidenceContext.evidenceEnabled,
851
+ warn: evidenceContext.warn,
852
+ });
853
+ }
854
+ catch (error) {
855
+ evidenceDiagnostics.push(diagnostic(`codex_evidence_append_failed:${errorMessage(error)}`, 'The append was already encoded; evidence replay from the durable source is safe.'));
856
+ }
857
+ }
858
+ else {
859
+ reportBackgroundDrop(backgroundTurnKey, { reason: consumed.reason, scored: true, budget: claimed.result.budgetChars });
860
+ }
861
+ releaseAdaptiveAppendClaim(claimed.claimPath);
862
+ }
863
+ }
864
+ }
541
865
  if (result.decision === 'deny') {
542
866
  try {
543
867
  let liveActivationId;
@@ -580,7 +904,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
580
904
  evidenceDiagnostics.push(diagnostic(`codex_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
581
905
  }
582
906
  }
583
- 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];
907
+ 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, ...backgroundDiagnostics];
584
908
  return { stdout: encoded, exitCode: 0, stderr };
585
909
  }
586
910
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Codex CLI host adapter for Principles Disciple — implements HostAdapter interface for OpenAI Codex CLI's stdin/stdout JSON hook model (ADR-0020).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -33,8 +33,8 @@
33
33
  "lint": "eslint \"src/**/*.ts\""
34
34
  },
35
35
  "dependencies": {
36
- "@principles/core": "^7.7.0",
37
- "@principles/host-runtime": "^4.2.0",
36
+ "@principles/core": "^7.9.0",
37
+ "@principles/host-runtime": "^4.3.0",
38
38
  "@principles/install-layout": "^0.8.0"
39
39
  },
40
40
  "devDependencies": {
@@ -52,5 +52,5 @@
52
52
  "publishConfig": {
53
53
  "access": "public"
54
54
  },
55
- "gitHead": "7feb0044cae3768b8bf278dad1cb58e77410b6f9"
55
+ "gitHead": "97cac4b30eb64ad4b369d2f86f5c57a8053897eb"
56
56
  }