@principles/codex-adapter 0.13.1 → 0.14.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.
@@ -11,3 +11,20 @@ export declare class CodexDecoderError extends Error {
11
11
  constructor(reason: string, nextAction: string);
12
12
  }
13
13
  export declare function decodeCodexInput(raw: unknown): HostEvent;
14
+ /** The MCP server ids whose `pd_submit_pain` the receipt fallback serves:
15
+ * the configured id (`pd-recall`) and its identifier-sanitized spelling. */
16
+ export declare const PAIN_SUBMIT_MCP_SERVER_IDS: ReadonlySet<string>;
17
+ export interface ParsedMcpToolName {
18
+ readonly serverId: string;
19
+ readonly toolId: string;
20
+ }
21
+ /** Decompose a Codex MCP tool name into (serverId, toolId); null when the
22
+ * name is not a namespaced MCP tool name. No substring semantics. */
23
+ export declare function parseCodexMcpToolName(toolName: string): ParsedMcpToolName | null;
24
+ /**
25
+ * Exact gate for the PostToolUse receipt fallback: the tool must be
26
+ * `pd_submit_pain` served by the PD MCP server (`pd-recall`). Every other
27
+ * tool — including an identically-named tool on a DIFFERENT MCP server —
28
+ * fails (equality on both parsed segments, never a substring match).
29
+ */
30
+ export declare function isPainSubmitPostToolUseToolName(toolName: string): boolean;
@@ -111,3 +111,42 @@ export function decodeCodexInput(raw) {
111
111
  const source = `codex:${eventName.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()}`;
112
112
  return { kind, context, rawPayload, source };
113
113
  }
114
+ // ── PRI-1274 (B1 / P1-1): MCP tool-name namespace on PostToolUse ─────────────
115
+ //
116
+ // Codex reports MCP tool calls under the server-namespaced form
117
+ // `mcp__<serverId>__<toolId>`. Evidence for the installed codex-cli 0.171.0:
118
+ // the binary's own format template `mcp__{}__{}`, its server-name charset
119
+ // check `^[a-zA-Z0-9_-]+$` with a reserved `mcp__` namespace, and its
120
+ // desktop-context string "MCP tools keep standard MCP identifiers such as
121
+ // `mcp__server__tool`". Runtime capture (Gate 2, 2026-10-31): the server
122
+ // configured as `pd-recall` (plugins/principles-disciple/.mcp.json) surfaced
123
+ // as `mcp__pd_recall__pd_recall_principle_pains` — non-identifier characters
124
+ // in the server id are sanitized to `_`, so BOTH spellings must be accepted.
125
+ //
126
+ // Parsing splits at the FIRST `__` after the `mcp__` prefix: a server id
127
+ // containing `__` would mis-parse, but such a name can never equal the
128
+ // accepted ids below, so foreign servers stay isolated regardless.
129
+ /** The MCP server ids whose `pd_submit_pain` the receipt fallback serves:
130
+ * the configured id (`pd-recall`) and its identifier-sanitized spelling. */
131
+ export const PAIN_SUBMIT_MCP_SERVER_IDS = new Set(['pd-recall', 'pd_recall']);
132
+ /** Decompose a Codex MCP tool name into (serverId, toolId); null when the
133
+ * name is not a namespaced MCP tool name. No substring semantics. */
134
+ export function parseCodexMcpToolName(toolName) {
135
+ if (!toolName.startsWith('mcp__'))
136
+ return null;
137
+ const rest = toolName.slice('mcp__'.length);
138
+ const separator = rest.indexOf('__');
139
+ if (separator <= 0 || separator + 2 >= rest.length)
140
+ return null;
141
+ return { serverId: rest.slice(0, separator), toolId: rest.slice(separator + 2) };
142
+ }
143
+ /**
144
+ * Exact gate for the PostToolUse receipt fallback: the tool must be
145
+ * `pd_submit_pain` served by the PD MCP server (`pd-recall`). Every other
146
+ * tool — including an identically-named tool on a DIFFERENT MCP server —
147
+ * fails (equality on both parsed segments, never a substring match).
148
+ */
149
+ export function isPainSubmitPostToolUseToolName(toolName) {
150
+ const parsed = parseCodexMcpToolName(toolName);
151
+ return parsed !== null && PAIN_SUBMIT_MCP_SERVER_IDS.has(parsed.serverId) && parsed.toolId === 'pd_submit_pain';
152
+ }
@@ -19,10 +19,119 @@
19
19
  * - No LLM runs here: admission + durable enqueue only, well inside the
20
20
  * 5s hook budget; the receipt carries painId/taskId.
21
21
  */
22
- import { admitGovernanceSignals, ensureGovernanceDiagnosticianTask, promoteAdmittedGovernanceEvidence, } from '@principles/host-runtime';
22
+ import fs from 'node:fs';
23
+ import { admitGovernanceSignals, ensureGovernanceDiagnosticianTask, promoteAdmittedGovernanceEvidence, readSourceMaterialAuthorization, } from '@principles/host-runtime';
23
24
  import { resolveCodexHome } from './codex-home.js';
24
25
  import { validateCodexTranscriptPath } from './transcript-path.js';
25
26
  import { extractFields } from './ingestion-fields.js';
27
+ function isRecord(value) {
28
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
29
+ }
30
+ function own(value, key) {
31
+ return Object.hasOwn(value, key) ? Object.getOwnPropertyDescriptor(value, key)?.value : undefined;
32
+ }
33
+ /** Bounded tail read: the current turn's user record sits at the end. */
34
+ const VERBATIM_VERIFY_MAX_BYTES = 4 * 1024 * 1024;
35
+ /**
36
+ * PRI-1283 round 3 (owner_manual ruling): the trusted Owner interaction
37
+ * record for the agent-assisted (`pd pain explicit`) channel. The submitted
38
+ * statement is confirmed ONLY when it appears VERBATIM inside the CURRENT
39
+ * turn's genuine user message in the host-validated transcript — i.e. the
40
+ * Owner typed exactly those words, so the final submitted content is what
41
+ * the Owner wrote, not an agent's paraphrase, summary or invention.
42
+ *
43
+ * Reads the same two user-turn record shapes the governance decoder
44
+ * projects (response_item user.text / event_msg UserMessage item_completed)
45
+ * so the confirmation is anchored on the SAME host-written substrate —
46
+ * never on anything the agent claimed. Transcript CONTENT is only read here
47
+ * under the conversation-ingestion consent (callers pass the flag); the
48
+ * check fails closed (no confirmation) on any read/parse problem.
49
+ */
50
+ function verifyOwnerVerbatimTurnMatch(args) {
51
+ const needle = args.statementText;
52
+ if (needle.length === 0)
53
+ return false;
54
+ let fd = null;
55
+ try {
56
+ fd = fs.openSync(args.validated.canonicalPath, 'r');
57
+ const stat = fs.fstatSync(fd);
58
+ // Post-open revalidation: same physical file the path validator proved.
59
+ if (stat.dev !== args.validated.identity.dev || stat.ino !== args.validated.identity.ino)
60
+ return false;
61
+ const start = Math.max(0, stat.size - VERBATIM_VERIFY_MAX_BYTES);
62
+ const length = Math.min(VERBATIM_VERIFY_MAX_BYTES, stat.size);
63
+ const buffer = Buffer.alloc(length);
64
+ const read = fs.readSync(fd, buffer, 0, length, start);
65
+ const text = buffer.subarray(0, read).toString('utf8');
66
+ const lines = text.split('\n');
67
+ for (const line of lines) {
68
+ const trimmed = line.trim();
69
+ if (trimmed.length === 0)
70
+ continue;
71
+ let record;
72
+ try {
73
+ record = JSON.parse(trimmed);
74
+ }
75
+ catch {
76
+ continue;
77
+ }
78
+ if (!isRecord(record))
79
+ continue;
80
+ const payload = own(record, 'payload');
81
+ if (!isRecord(payload))
82
+ continue;
83
+ const recordType = own(record, 'type');
84
+ if (recordType === 'response_item' && own(payload, 'type') === 'message' && own(payload, 'role') === 'user') {
85
+ const passthrough = own(payload, 'internal_chat_message_metadata_passthrough');
86
+ if (!isRecord(passthrough) || own(passthrough, 'turn_id') !== args.turnId)
87
+ continue;
88
+ const kinds = own(passthrough, 'content_item_kinds');
89
+ if (!Array.isArray(kinds) || kinds[0] !== 'user.text')
90
+ continue;
91
+ const content = own(payload, 'content');
92
+ if (!Array.isArray(content))
93
+ continue;
94
+ const parts = [];
95
+ for (const item of content) {
96
+ if (isRecord(item) && own(item, 'type') === 'input_text' && typeof own(item, 'text') === 'string')
97
+ parts.push(own(item, 'text'));
98
+ }
99
+ if (parts.join('').includes(needle))
100
+ return true;
101
+ continue;
102
+ }
103
+ if (recordType === 'event_msg' && own(payload, 'type') === 'item_completed' && own(payload, 'turn_id') === args.turnId) {
104
+ const item = own(payload, 'item');
105
+ if (!isRecord(item) || own(item, 'type') !== 'UserMessage')
106
+ continue;
107
+ const content = own(item, 'content');
108
+ if (!Array.isArray(content))
109
+ continue;
110
+ const parts = [];
111
+ for (const entry of content) {
112
+ if (isRecord(entry) && (own(entry, 'type') === 'text' || own(entry, 'type') === 'Text') && typeof own(entry, 'text') === 'string')
113
+ parts.push(own(entry, 'text'));
114
+ }
115
+ if (parts.join('').includes(needle))
116
+ return true;
117
+ }
118
+ }
119
+ return false;
120
+ }
121
+ catch {
122
+ return false;
123
+ }
124
+ finally {
125
+ if (fd !== null) {
126
+ try {
127
+ fs.closeSync(fd);
128
+ }
129
+ catch {
130
+ // best-effort close
131
+ }
132
+ }
133
+ }
134
+ }
26
135
  export { OWNER_STATEMENT_PREFIX as CODEX_OWNER_STATEMENT_PREFIX, MAX_OWNER_STATEMENT_CHARS, parseOwnerStatementPrefix } from '@principles/host-runtime';
27
136
  /**
28
137
  * Persist one explicit Owner statement. The consent-gated conversation
@@ -69,6 +178,21 @@ export async function recordExplicitOwnerStatement(args) {
69
178
  observedAt: new Date().toISOString(),
70
179
  explicitOwnerStatement: true,
71
180
  ...(args.explicitChannel !== undefined ? { explicitChannel: args.explicitChannel } : {}),
181
+ // PRI-1283 round 3 (owner_manual ruling): an agent-assisted statement is
182
+ // owner_manual ONLY when the submitted text matches the Owner's own words
183
+ // in the current turn's transcript record. The check reads transcript
184
+ // CONTENT, so it runs only under the conversation-ingestion consent;
185
+ // when consent is off (or the match fails) the statement persists as
186
+ // Agent-derived — classified down, never rejected outright.
187
+ ...(args.explicitChannel === 'codex_explicit_agent' && args.conversationIngestionEnabled
188
+ // Transcript content is consent-governed material: the feature flag
189
+ // alone is not the authority — the consent ledger must still grant
190
+ // codex ingestion before any confirmation reads transcript content
191
+ // (a revoked-but-still-flagged workspace must not mint exemptions).
192
+ && readSourceMaterialAuthorization({ workspaceDir: args.workspaceDir, hostKind: 'codex' }).status === 'authorized'
193
+ && verifyOwnerVerbatimTurnMatch({ validated, turnId: fields.turnId, statementText: args.statementText })
194
+ ? { ownerVerbatimConfirmed: true }
195
+ : {}),
72
196
  };
73
197
  const admitted = admitGovernanceSignals({ workspaceDir: args.workspaceDir, candidates: [candidate] });
74
198
  if (!admitted.ok) {
@@ -0,0 +1,46 @@
1
+ import { type PainReceiptRecoveryOutcome } from '@principles/core/runtime';
2
+ /** The MCP tool id this fallback processes (the server gate lives in the
3
+ * codec parser — exact match on both namespace segments, never a pattern). */
4
+ export declare const PAIN_SUBMIT_TOOL_NAME: 'pd_submit_pain';
5
+ export type PainReceiptFallbackResult = {
6
+ readonly status: 'not_applicable';
7
+ } | {
8
+ readonly status: 'attempted';
9
+ readonly outcome: PainReceiptRecoveryOutcome;
10
+ };
11
+ export interface PainReceiptFallbackInput {
12
+ readonly workspaceDir: string;
13
+ /** Raw host event `tool_name` — gated by the codec MCP namespace parser
14
+ * before anything else happens (P1-1). */
15
+ readonly toolName: string;
16
+ /** Raw `tool_response` from the PostToolUse payload. */
17
+ readonly toolResponse: unknown;
18
+ /** Host-authoritative identity from the event itself. */
19
+ readonly identity: {
20
+ readonly sessionId: string;
21
+ readonly turnId?: string;
22
+ readonly toolCallId: string;
23
+ };
24
+ /** Caller-resolved `host_identity_minimal_metadata` flag verdict. */
25
+ readonly minimalMetadataGranted: boolean;
26
+ readonly now?: () => Date;
27
+ }
28
+ /**
29
+ * P1-3: does the authorized governance store already hold readable text for
30
+ * the EXACT (session, turn)? Shared by the receipt fallback (disposition
31
+ * choice) and the workspace worker's waiting-task reconcile (the flip) —
32
+ * the diagnosis itself re-reads the turn through the same store.
33
+ * Unreadable ⇒ missing.
34
+ */
35
+ export declare function codexTargetTurnTextAvailable(workspaceDir: string, sessionId: string, turnId: string): boolean;
36
+ /**
37
+ * Attempt the receipt fallback for one PostToolUse event. Never throws —
38
+ * every failure is a structured result the hook surfaces as one bounded
39
+ * diagnostic (rc-9); the hook result itself is unaffected (fail-open belt).
40
+ */
41
+ export declare function attemptPainReceiptFallback(input: PainReceiptFallbackInput): Promise<PainReceiptFallbackResult>;
42
+ /**
43
+ * One bounded stderr diagnostic line for the hook (ids and codes only —
44
+ * never receipt content, prompts or tool input/output).
45
+ */
46
+ export declare function painReceiptFallbackDiagnostic(result: PainReceiptFallbackResult): string | null;
@@ -0,0 +1,193 @@
1
+ /**
2
+ * PRI-1274 (B1) — Codex PostToolUse structured-receipt fallback.
3
+ *
4
+ * When a `pd_submit_pain` MCP request carried no trusted host `_meta`, the
5
+ * original Pain/Task was legally persisted unbound. Codex's formal
6
+ * PostToolUse completion event then carries PD's own structured receipt in
7
+ * `tool_response` — the MCP envelope is a SINGLE text content block with the
8
+ * JSON in `content[0].text` (never `structuredContent`; the adapter owns
9
+ * this host envelope shape and must not extrapolate it to other hosts).
10
+ * Together with the event's own host-authoritative identity
11
+ * (`session_id` / `turn_id` / `tool_use_id` — never model parameters), this
12
+ * module restores the SAME original task's submission identity through the
13
+ * Core CAS recovery.
14
+ *
15
+ * P1-1 (review round 2): Codex reports MCP tools under the server
16
+ * namespace — the gate is an exact parse of `mcp__<server>__<tool>` against
17
+ * the PD server (`pd-recall`, sanitized `pd_recall`) + `pd_submit_pain`
18
+ * (see codec/input-decoder.ts for the format evidence). A bare
19
+ * `pd_submit_pain` or an identically-named tool on another MCP server never
20
+ * enters this path.
21
+ *
22
+ * Authorization: the Workspace-level `host_identity_minimal_metadata` quiet
23
+ * flag — deliberately INDEPENDENT of `codex_conversation_ingestion` (full
24
+ * conversation ingestion may stay off; this path reads no transcript and
25
+ * persists ids only).
26
+ *
27
+ * No recovery is EVER attempted from free text, ordinary EventLog
28
+ * `tool_call` rows, or look-alike strings (SPEC TD §1.3).
29
+ */
30
+ import * as path from 'node:path';
31
+ import { listGovernanceObservations } from '@principles/host-runtime';
32
+ import { isSentinelSessionId } from '@principles/core/runtime';
33
+ import { recoverTaskIdentityFromReceipt, validatePainSubmitReceipt, } from '@principles/core/runtime';
34
+ import { isPainSubmitPostToolUseToolName } from '../codec/input-decoder.js';
35
+ /** The MCP tool id this fallback processes (the server gate lives in the
36
+ * codec parser — exact match on both namespace segments, never a pattern). */
37
+ export const PAIN_SUBMIT_TOOL_NAME = 'pd_submit_pain';
38
+ /** MCP CallToolResult content block shape (single text block contract).
39
+ * P2 review round: more than one content block is AMBIGUOUS — two text
40
+ * blocks could each carry a different task's receipt, so the whole envelope
41
+ * is rejected instead of quietly trusting the first block. */
42
+ function extractReceiptText(toolResponse) {
43
+ if (typeof toolResponse !== 'object' || toolResponse === null || Array.isArray(toolResponse)) {
44
+ return { ok: false, reasonCode: 'receipt_envelope_not_an_object' };
45
+ }
46
+ if (!Object.hasOwn(toolResponse, 'content')) {
47
+ return { ok: false, reasonCode: 'receipt_envelope_content_missing' };
48
+ }
49
+ const { content } = toolResponse;
50
+ if (!Array.isArray(content) || content.length === 0) {
51
+ return { ok: false, reasonCode: 'receipt_envelope_content_missing' };
52
+ }
53
+ if (content.length > 1) {
54
+ return { ok: false, reasonCode: 'receipt_envelope_ambiguous_content' };
55
+ }
56
+ const [first] = content;
57
+ if (typeof first !== 'object' || first === null || Array.isArray(first)) {
58
+ return { ok: false, reasonCode: 'receipt_envelope_block_invalid' };
59
+ }
60
+ if (!Object.hasOwn(first, 'type') || !Object.hasOwn(first, 'text')) {
61
+ return { ok: false, reasonCode: 'receipt_envelope_not_text_block' };
62
+ }
63
+ const { type, text } = first;
64
+ if (type !== 'text' || typeof text !== 'string') {
65
+ return { ok: false, reasonCode: 'receipt_envelope_not_text_block' };
66
+ }
67
+ return { ok: true, text };
68
+ }
69
+ /** Normalize host ids at the adapter boundary, matching the trusted `_meta`
70
+ * reader. `null` means malformed; `undefined` means absent (or an empty
71
+ * optional id). Only the normalized value may cross into Core. */
72
+ function normalizeEventId(value, opts) {
73
+ if (value === undefined)
74
+ return undefined;
75
+ if (typeof value !== 'string')
76
+ return null;
77
+ const id = value.trim();
78
+ if (opts.allowEmpty && id.length === 0)
79
+ return undefined;
80
+ return id.length > 0 && id.length <= 200 && !isSentinelSessionId(id) ? id : null;
81
+ }
82
+ /**
83
+ * P1-3: does the authorized governance store already hold readable text for
84
+ * the EXACT (session, turn)? Shared by the receipt fallback (disposition
85
+ * choice) and the workspace worker's waiting-task reconcile (the flip) —
86
+ * the diagnosis itself re-reads the turn through the same store.
87
+ * Unreadable ⇒ missing.
88
+ */
89
+ export function codexTargetTurnTextAvailable(workspaceDir, sessionId, turnId) {
90
+ try {
91
+ const result = listGovernanceObservations({
92
+ workspaceDir,
93
+ hostKind: 'codex',
94
+ rolloutIdentity: sessionId,
95
+ hostTurnId: turnId,
96
+ limit: 8,
97
+ });
98
+ if (!result.ok)
99
+ return false;
100
+ return result.observations.some((row) => (row.kind === 'user_turn' || row.kind === 'assistant_turn')
101
+ && (row.retentionClass === 'operational' || row.retentionClass === 'promoted')
102
+ && typeof row.visibleText === 'string'
103
+ && row.visibleText.trim() !== '');
104
+ }
105
+ catch {
106
+ return false;
107
+ }
108
+ }
109
+ /**
110
+ * Attempt the receipt fallback for one PostToolUse event. Never throws —
111
+ * every failure is a structured result the hook surfaces as one bounded
112
+ * diagnostic (rc-9); the hook result itself is unaffected (fail-open belt).
113
+ */
114
+ export async function attemptPainReceiptFallback(input) {
115
+ // P1-1: exact namespace gate first — only the PD MCP server's
116
+ // `pd_submit_pain` completion may enter the recovery path.
117
+ if (!isPainSubmitPostToolUseToolName(input.toolName)) {
118
+ return { status: 'not_applicable' };
119
+ }
120
+ // P2: validate AND normalize at the host boundary. Validating a trimmed
121
+ // copy while forwarding the raw value would create a second identity
122
+ // spelling in Core/SQLite (and make exact target-turn joins miss).
123
+ const sessionId = normalizeEventId(input.identity.sessionId, { allowEmpty: false });
124
+ const toolCallId = normalizeEventId(input.identity.toolCallId, { allowEmpty: false });
125
+ const turnId = normalizeEventId(input.identity.turnId, { allowEmpty: true });
126
+ if (sessionId === null || toolCallId === null || turnId === null) {
127
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'event_identity_invalid' } };
128
+ }
129
+ if (sessionId === undefined || toolCallId === undefined) {
130
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'event_identity_missing' } };
131
+ }
132
+ const envelope = extractReceiptText(input.toolResponse);
133
+ if (!envelope.ok) {
134
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: envelope.reasonCode } };
135
+ }
136
+ let parsed;
137
+ try {
138
+ parsed = JSON.parse(envelope.text);
139
+ }
140
+ catch {
141
+ // Degraded transport forms (plain-text statement) and foreign payloads
142
+ // are not receipts — no recovery from free text.
143
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'receipt_text_not_json' } };
144
+ }
145
+ // P2: normalize the workspace spellings BEFORE validation — the same
146
+ // directory written differently (`/w/p` vs `/w/p/.`) is the same
147
+ // workspace; a genuinely different directory is still rejected by the
148
+ // validated exact comparison. Platform path knowledge stays in the
149
+ // adapter (Core stays path-free).
150
+ const normalizedWorkspace = path.resolve(input.workspaceDir);
151
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
152
+ const parsedRecord = parsed;
153
+ const rawDir = Object.hasOwn(parsedRecord, 'workspaceDir') ? parsedRecord.workspaceDir : undefined;
154
+ if (typeof rawDir === 'string' && rawDir.length > 0) {
155
+ parsed = { ...parsedRecord, workspaceDir: path.resolve(rawDir) };
156
+ }
157
+ }
158
+ const validated = validatePainSubmitReceipt(parsed, { workspaceDir: normalizedWorkspace });
159
+ if (!validated.ok) {
160
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: validated.reasonCode } };
161
+ }
162
+ const outcome = await recoverTaskIdentityFromReceipt({
163
+ workspaceDir: normalizedWorkspace,
164
+ hostKind: 'codex',
165
+ receipt: validated.receipt,
166
+ identity: {
167
+ sessionId,
168
+ ...(turnId === undefined ? {} : { submissionTurnId: turnId }),
169
+ toolCallId,
170
+ },
171
+ authorization: { minimalMetadataGranted: input.minimalMetadataGranted },
172
+ targetTurnTextAvailable: (hostSessionId, targetTurnId) => codexTargetTurnTextAvailable(normalizedWorkspace, hostSessionId, targetTurnId),
173
+ ...(input.now !== undefined ? { now: input.now } : {}),
174
+ });
175
+ return { status: 'attempted', outcome };
176
+ }
177
+ /**
178
+ * One bounded stderr diagnostic line for the hook (ids and codes only —
179
+ * never receipt content, prompts or tool input/output).
180
+ */
181
+ export function painReceiptFallbackDiagnostic(result) {
182
+ if (result.status === 'not_applicable')
183
+ return null;
184
+ const { outcome } = result;
185
+ switch (outcome.status) {
186
+ case 'recovered':
187
+ return `pain_receipt_recovered:taskId=${outcome.taskId}:state=${outcome.disposition.state}`;
188
+ case 'already_bound':
189
+ return `pain_receipt_idempotent:taskId=${outcome.taskId}`;
190
+ case 'rejected':
191
+ return `pain_receipt_rejected:${outcome.reasonCode}${outcome.detail !== undefined ? `:detail=${Array.from(outcome.detail).slice(0, 80).join('')}` : ''}${outcome.taskId !== undefined ? `:taskId=${outcome.taskId}` : ''}`;
192
+ }
193
+ }
@@ -1,6 +1,6 @@
1
1
  import { type RecordOwnerStatementResult } from './explicit-owner-statement.js';
2
2
  export declare const TURN_CONTEXT_FILENAME_PREFIX = "pd_current_turn_context_";
3
- export declare const TURN_CONTEXT_SCHEMA_VERSION = 1;
3
+ export declare const TURN_CONTEXT_SCHEMA_VERSION = 2;
4
4
  /**
5
5
  * Staleness bound for the turn context. Stop/SessionStart withdraw the file,
6
6
  * but any early exit on those paths (decode/config failure, host.codex flag
@@ -10,7 +10,7 @@ export declare const TURN_CONTEXT_SCHEMA_VERSION = 1;
10
10
  * legitimate in-turn registration latency.
11
11
  */
12
12
  export declare const TURN_CONTEXT_MAX_AGE_MS: number;
13
- /** Host-written identity of the CURRENT Codex turn. Ids and paths only. */
13
+ /** Host-written identity of the CURRENT Codex turn: ids, paths and one closed-set intent marker. */
14
14
  export interface CodexTurnContext {
15
15
  readonly schemaVersion: number;
16
16
  readonly writtenAt: string;
@@ -19,6 +19,8 @@ export interface CodexTurnContext {
19
19
  readonly transcriptPath: string;
20
20
  readonly codexHome: string;
21
21
  readonly workspaceDir: string;
22
+ /** Host-derived from a direct current-turn Owner request; never caller-supplied. */
23
+ readonly ownerIntent: 'explicit_pain_registration' | null;
22
24
  }
23
25
  interface CodexCallerEnvironment {
24
26
  CODEX_HOME?: string | undefined;
@@ -43,14 +45,6 @@ export declare function clearCurrentTurnContext(args: {
43
45
  sessionId: string;
44
46
  turnId?: string;
45
47
  }): TurnContextClearResult;
46
- /**
47
- * Publish (or withdraw) the current turn context. Called from the
48
- * UserPromptSubmit branch of the hook. A payload without complete lineage
49
- * (session/turn/transcript) clears any previous file instead of leaving a
50
- * stale turn bindable — the invariant is "file exists ⟺ the current turn
51
- * carries full lineage". Fail-open: a write failure degrades the
52
- * agent-assisted entry only (the prefix entry never needed this file).
53
- */
54
48
  export declare function writeCurrentTurnContext(args: {
55
49
  rawPayload: unknown;
56
50
  workspaceDir: string;
@@ -58,15 +52,16 @@ export declare function writeCurrentTurnContext(args: {
58
52
  }): TurnContextWriteResult;
59
53
  export type RegisterCurrentTurnResult = RecordOwnerStatementResult | {
60
54
  status: 'rejected';
61
- reason: 'turn_context_missing' | 'turn_context_invalid' | 'turn_context_stale' | 'turn_context_workspace_mismatch' | 'turn_context_session_mismatch' | 'caller_session_missing' | 'caller_session_conflict' | 'conversation_ingestion_config_invalid';
55
+ reason: 'turn_context_missing' | 'turn_context_invalid' | 'turn_context_stale' | 'turn_context_workspace_mismatch' | 'turn_context_session_mismatch' | 'caller_session_missing' | 'caller_session_conflict' | 'conversation_ingestion_config_invalid' | 'owner_intent_missing';
62
56
  nextAction: string;
63
57
  };
64
58
  /**
65
59
  * Register one explicit Owner statement through the LIVE turn context — the
66
- * agent-assisted counterpart of the prefix entry. The statement must be the
67
- * Owner's verbatim words from the CURRENT conversation turn (1–500 chars,
68
- * rejected when over the limit — never truncated); lineage comes exclusively
69
- * from the host-written context file, never from caller-supplied ids.
60
+ * agent-assisted counterpart of the prefix entry. The current Owner turn
61
+ * must explicitly request this registration. Supplied wording is Agent-derived
62
+ * unless a consent-authorized transcript match verifies it as Owner-verbatim.
63
+ * The intent marker authorizes this submission, not authorship. Lineage comes
64
+ * only from the host-written context file.
70
65
  */
71
66
  export declare function registerCurrentTurnOwnerStatement(args: {
72
67
  workspaceDir: string;
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Live-turn context bridge for agent-assisted explicit Owner pain
3
- * registration (no `PD记录痛苦:` prefix).
3
+ * registration gated by a host-derived current-turn Owner-intent marker.
4
4
  *
5
5
  * The hook writes the CURRENT turn's host-verified identity — session id,
6
6
  * turn id, transcript path, CODEX_HOME, workspace — to a file partitioned by
@@ -15,9 +15,9 @@
15
15
  * the transcript path (existence + CODEX_HOME containment + rollout identity)
16
16
  * at registration time. A cleared or stale context fails closed.
17
17
  *
18
- * Privacy: each file carries identifiers and paths only — never prompt text,
19
- * never transcript content. Session ids are hashed in filenames. The
20
- * conversation-ingestion flag does not gate context publication.
18
+ * Privacy: each file carries identifiers, paths and a closed-set intent marker only.
19
+ * It never persists prompt text or transcript content; session ids are hashed in filenames.
20
+ * The conversation-ingestion flag does not gate context publication.
21
21
  */
22
22
  import fs from 'node:fs';
23
23
  import { createHash, randomUUID } from 'node:crypto';
@@ -28,7 +28,7 @@ import { resolveCodexHome } from './codex-home.js';
28
28
  import { extractFields, isRecord } from './ingestion-fields.js';
29
29
  import { recordExplicitOwnerStatement, MAX_OWNER_STATEMENT_CHARS } from './explicit-owner-statement.js';
30
30
  export const TURN_CONTEXT_FILENAME_PREFIX = 'pd_current_turn_context_';
31
- export const TURN_CONTEXT_SCHEMA_VERSION = 1;
31
+ export const TURN_CONTEXT_SCHEMA_VERSION = 2;
32
32
  /**
33
33
  * Staleness bound for the turn context. Stop/SessionStart withdraw the file,
34
34
  * but any early exit on those paths (decode/config failure, host.codex flag
@@ -128,6 +128,13 @@ const CLEAR_FAILURE_NEXT_ACTION = 'The previous turn context could not be withdr
128
128
  * carries full lineage". Fail-open: a write failure degrades the
129
129
  * agent-assisted entry only (the prefix entry never needed this file).
130
130
  */
131
+ const OWNER_PAIN_REQUEST_PREFIXES = ['PD代录痛苦:', 'PD代录痛苦:', 'PD记录痛苦:', 'PD记录痛苦:'];
132
+ function resolveOwnerPainIntent(rawPayload) {
133
+ if (!isRecord(rawPayload) || typeof rawPayload.prompt !== 'string')
134
+ return null;
135
+ const prompt = rawPayload.prompt.trimStart();
136
+ return OWNER_PAIN_REQUEST_PREFIXES.some((prefix) => prompt.startsWith(prefix) && prompt.slice(prefix.length).trim().length > 0) ? 'explicit_pain_registration' : null;
137
+ }
131
138
  export function writeCurrentTurnContext(args) {
132
139
  const fields = extractFields(args.rawPayload);
133
140
  if (fields === null || fields.sessionId.length === 0) {
@@ -158,6 +165,7 @@ export function writeCurrentTurnContext(args) {
158
165
  transcriptPath: fields.transcriptPath,
159
166
  codexHome: home.home,
160
167
  workspaceDir: args.workspaceDir,
168
+ ownerIntent: resolveOwnerPainIntent(args.rawPayload),
161
169
  };
162
170
  const target = turnContextPath(args.workspaceDir, fields.sessionId);
163
171
  const temp = `${target}.tmp-${process.pid}`;
@@ -185,6 +193,11 @@ function requireStringField(record, key) {
185
193
  const value = Object.hasOwn(record, key) ? record[key] : undefined;
186
194
  return typeof value === 'string' && value.length > 0 ? value : null;
187
195
  }
196
+ /**
197
+ * A tool invocation is not proof that the Owner requested it. The UserPromptSubmit
198
+ * hook records only this closed-set marker from the current Owner message. It
199
+ * deliberately stores no prompt text and does not inspect historical turns.
200
+ */
188
201
  function readTurnContext(workspaceDir, sessionId) {
189
202
  let raw;
190
203
  try {
@@ -208,6 +221,10 @@ function readTurnContext(workspaceDir, sessionId) {
208
221
  const transcriptPath = requireStringField(parsed, 'transcriptPath');
209
222
  const codexHome = requireStringField(parsed, 'codexHome');
210
223
  const contextWorkspaceDir = requireStringField(parsed, 'workspaceDir');
224
+ const { ownerIntent } = parsed;
225
+ if (!Object.hasOwn(parsed, 'ownerIntent') || (ownerIntent !== null && ownerIntent !== 'explicit_pain_registration')) {
226
+ return { error: 'turn_context_invalid' };
227
+ }
211
228
  if (writtenAt === null || contextSessionId === null || turnId === null || transcriptPath === null || codexHome === null || contextWorkspaceDir === null) {
212
229
  return { error: 'turn_context_invalid' };
213
230
  }
@@ -224,14 +241,16 @@ function readTurnContext(workspaceDir, sessionId) {
224
241
  transcriptPath,
225
242
  codexHome,
226
243
  workspaceDir: contextWorkspaceDir,
244
+ ownerIntent,
227
245
  };
228
246
  }
229
247
  /**
230
248
  * Register one explicit Owner statement through the LIVE turn context — the
231
- * agent-assisted counterpart of the prefix entry. The statement must be the
232
- * Owner's verbatim words from the CURRENT conversation turn (1–500 chars,
233
- * rejected when over the limit — never truncated); lineage comes exclusively
234
- * from the host-written context file, never from caller-supplied ids.
249
+ * agent-assisted counterpart of the prefix entry. The current Owner turn
250
+ * must explicitly request this registration. Supplied wording is Agent-derived
251
+ * unless a consent-authorized transcript match verifies it as Owner-verbatim.
252
+ * The intent marker authorizes this submission, not authorship. Lineage comes
253
+ * only from the host-written context file.
235
254
  */
236
255
  export async function registerCurrentTurnOwnerStatement(args) {
237
256
  const caller = resolveCallerSessionId(process.env);
@@ -271,6 +290,13 @@ export async function registerCurrentTurnOwnerStatement(args) {
271
290
  nextAction: 'The turn context does not belong to this host-bound Codex session; nothing was recorded. Retry from the session that supplied the Owner statement.',
272
291
  };
273
292
  }
293
+ if (context.ownerIntent !== 'explicit_pain_registration') {
294
+ return {
295
+ status: 'rejected',
296
+ reason: 'owner_intent_missing',
297
+ nextAction: 'An agent/tool invocation is not Owner approval. The current Owner message must begin with PD代录痛苦:<request> (or PD记录痛苦:<Owner words> for direct submission). Start a new Owner turn with that explicit prefix; no history was read and nothing was recorded.',
298
+ };
299
+ }
274
300
  const statement = args.statementText.trim();
275
301
  if (statement.length === 0) {
276
302
  return { status: 'rejected', reason: 'statement_empty', nextAction: 'The Owner statement is empty; nothing was recorded. Pass the Owner verbatim words (1–500 characters).' };
package/dist/pd-hook.js CHANGED
@@ -13,6 +13,8 @@ import { CodexHooksHostAdapter } from './host-adapter.js';
13
13
  import { CodexDecoderError, CodexEncoderError } from './codec/index.js';
14
14
  import { ingestCodexConversation } from './ingestion/ingestion.js';
15
15
  import { runGovernanceAdmission } from './ingestion/admission.js';
16
+ import { attemptPainReceiptFallback, painReceiptFallbackDiagnostic } from './ingestion/pain-receipt-fallback.js';
17
+ import { isPainSubmitPostToolUseToolName } from './codec/input-decoder.js';
16
18
  import { parseOwnerStatementPrefix, recordExplicitOwnerStatement } from './ingestion/explicit-owner-statement.js';
17
19
  import { writeCurrentTurnContext, clearCurrentTurnContext } from './ingestion/turn-context.js';
18
20
  import { recordCodexPromptDeliveryEvidence, recordCodexDenyEvidence } from './codex-evidence-recorder.js';
@@ -912,7 +914,61 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
912
914
  evidenceDiagnostics.push(diagnostic(`codex_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
913
915
  }
914
916
  }
915
- 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];
917
+ // PRI-1274 (B1): PostToolUse structured-receipt fallback. When a
918
+ // pd_submit_pain MCP request carried no trusted host `_meta`, its
919
+ // original Pain/Task was legally persisted unbound; the host completion
920
+ // event's own structured receipt + host-authoritative identity now
921
+ // restores the SAME task via the Core CAS recovery. P1-1: the tool name
922
+ // arrives in Codex's MCP namespace (`mcp__pd_recall__pd_submit_pain`) and
923
+ // is gated by the exact codec parser — a bare or foreign-server name
924
+ // never enters. Independent of codex_conversation_ingestion (no
925
+ // transcript read; ids only), gated by the Workspace-level
926
+ // host_identity_minimal_metadata authorization. Fail-open: a fallback
927
+ // failure never changes the host decision.
928
+ const receiptDiagnostics = [];
929
+ if (event.kind === 'after_tool_call'
930
+ && event.context.toolName !== undefined
931
+ && isPainSubmitPostToolUseToolName(event.context.toolName)
932
+ && event.context.toolCallId !== undefined) {
933
+ try {
934
+ const fallback = await attemptPainReceiptFallback({
935
+ workspaceDir: resolution.workspaceDir,
936
+ toolName: event.context.toolName,
937
+ toolResponse: event.context.toolOutput,
938
+ identity: {
939
+ sessionId: event.context.sessionId,
940
+ ...(event.context.turnId !== undefined ? { turnId: event.context.turnId } : {}),
941
+ toolCallId: event.context.toolCallId,
942
+ },
943
+ minimalMetadataGranted: flags.host_identity_minimal_metadata?.enabled === true,
944
+ });
945
+ const line = painReceiptFallbackDiagnostic(fallback);
946
+ if (line !== null) {
947
+ // P1-5 (option B): the nextAction states EXACTLY what happened —
948
+ // only `recovered`/`already_bound` mean the task carries the
949
+ // identity; a refusal left the submission legally unbound and is
950
+ // NOT retried by any worker cycle.
951
+ const nextAction = fallback.status === 'not_applicable'
952
+ ? undefined
953
+ : fallback.outcome.status === 'recovered'
954
+ ? 'The submission identity was restored on the original task; no resubmission is needed.'
955
+ : fallback.outcome.status === 'already_bound'
956
+ ? 'The original task already carries this identity; nothing to do.'
957
+ : fallback.outcome.reasonCode === 'blocked_by_consent'
958
+ ? 'The Workspace has not granted minimal identity-metadata collection; enable host_identity_minimal_metadata in .pd/config.yaml if binding is wanted.'
959
+ : 'The recovery was refused and is not retried automatically; the submission stays legally unbound. Resubmit pd_submit_pain only if the binding is needed.';
960
+ receiptDiagnostics.push(nextAction === undefined
961
+ ? diagnostic(line, 'The receipt fallback outcome was recorded.')
962
+ : diagnostic(line, nextAction));
963
+ }
964
+ }
965
+ catch (error) {
966
+ // P1-5 (option B): no next-cycle retry exists for receipt recovery —
967
+ // the promise is removed rather than kept false.
968
+ receiptDiagnostics.push(diagnostic(`pain_receipt_fallback_failed:${errorMessage(error)}`, 'The hook decision is unaffected; identity recovery for this call did not complete and is not retried automatically — the submission stays legally unbound.'));
969
+ }
970
+ }
971
+ 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, ...receiptDiagnostics];
916
972
  return { stdout: encoded, exitCode: 0, stderr };
917
973
  }
918
974
  catch (error) {
@@ -1,3 +1,4 @@
1
+ import { type TargetEvidenceReconcileReport } from '@principles/core/runtime';
1
2
  import { type InternalizationConsumerCycleOutcome, type ConsumerCycleLogger, type ReconcileGovernanceContinuationResult, type SignalLlmClassifier, type Stage2CorrectionCycleReport } from '@principles/host-runtime';
2
3
  import { type CodexCatchUpResult } from '../ingestion/catch-up.js';
3
4
  import type { TranscriptPort } from '../ingestion/transcript-decoder.js';
@@ -34,6 +35,13 @@ export interface CodexWorkerCycleStepReport {
34
35
  readonly reuseReviewRequiredCandidateIds?: readonly string[];
35
36
  } | null;
36
37
  readonly downstream: InternalizationConsumerCycleOutcome | null;
38
+ /**
39
+ * PRI-1274 (B1 / P1-3): bounded waiting-task reconcile — flips
40
+ * `waiting_for_target_evidence` dispositions to `ready_for_diagnosis`
41
+ * once the authorized store holds the exact target turn's text. Present
42
+ * only on cycles that reached the diagnostician step.
43
+ */
44
+ readonly targetEvidenceReconcile?: TargetEvidenceReconcileReport;
37
45
  /**
38
46
  * Phase B Stage-2 review step. Always the LAST step so it can never starve
39
47
  * the Diagnostician (bounded to ≤2 candidates / ≤60s aggregate).
@@ -66,6 +74,13 @@ export interface CodexWorkerCycleOptions {
66
74
  readonly stage2Classifier?: SignalLlmClassifier | null;
67
75
  readonly stage2AggregateBudgetMs?: number;
68
76
  }
77
+ /**
78
+ * WHO drove this cycle (PRI-1264 attribution, Phase 2 extension). The
79
+ * Service Host sets `PD_INVOCATION_SOURCE=service_host` on its Worker
80
+ * children (shadow mode); without the third value the stall attribution
81
+ * would misreport service-driven cycles as manual (TD §5.2).
82
+ */
83
+ export declare function codexWorkerCycleDriver(): 'companion' | 'service_host' | 'manual';
69
84
  export declare function readCodexWorkerLiveness(workspaceDir: string): Record<string, unknown> | null;
70
85
  /**
71
86
  * SPEC §9.1 fair-share pick (review P1): pending and due-retry are both
@@ -27,9 +27,10 @@
27
27
  */
28
28
  import fs from 'node:fs';
29
29
  import path from 'node:path';
30
- import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
31
- import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createGovernanceTrajectoryTurnReader, createHostIntentDocReader, isAutomaticPainSubmissionAuthorized, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
30
+ import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, reconcileWaitingTargetEvidenceTasks, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
31
+ import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createGovernanceTrajectoryTurnReader, createConsentLedgerSourceMaterialAuthorization, createHostIntentDocReader, isAutomaticPainSubmissionAuthorized, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
32
32
  import { catchUpCodexIngestion } from '../ingestion/catch-up.js';
33
+ import { codexTargetTurnTextAvailable } from '../ingestion/pain-receipt-fallback.js';
33
34
  import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from '../tool-semantics.js';
34
35
  const WORKER_OWNER = 'companion-worker';
35
36
  const DEFAULT_DIAG_CANDIDATE_LIMIT = 5;
@@ -47,6 +48,34 @@ const LIVENESS_STAGE_DEADLINE_MS = {
47
48
  post_processing: 5 * 60_000,
48
49
  downstream_cycle: 10 * 60_000,
49
50
  };
51
+ /**
52
+ * WHO drove this cycle (PRI-1264 attribution, Phase 2 extension). The
53
+ * Service Host sets `PD_INVOCATION_SOURCE=service_host` on its Worker
54
+ * children (shadow mode); without the third value the stall attribution
55
+ * would misreport service-driven cycles as manual (TD §5.2).
56
+ */
57
+ export function codexWorkerCycleDriver() {
58
+ const source = process.env.PD_INVOCATION_SOURCE;
59
+ if (source === 'companion')
60
+ return 'companion';
61
+ if (source === 'service_host')
62
+ return 'service_host';
63
+ return 'manual';
64
+ }
65
+ /**
66
+ * F13 (TD §5.2): the coordinator passes a unique invocation id; when
67
+ * present it lands in the liveness record so the shared per-workspace file
68
+ * can be correlated back to the exact Service Host invocation.
69
+ * R5 review fix: a manual/companion cycle carries NO invocation id, so the
70
+ * patch must CLEAR the field — otherwise a completed manual run would keep
71
+ * masquerading under the previous shadow run's id.
72
+ */
73
+ function invocationIdLivenessPatch() {
74
+ const invocationId = process.env.PD_INVOCATION_ID;
75
+ return typeof invocationId === 'string' && invocationId.length > 0
76
+ ? { lastInvocationId: invocationId }
77
+ : { lastInvocationId: null };
78
+ }
50
79
  export function readCodexWorkerLiveness(workspaceDir) {
51
80
  try {
52
81
  const parsed = JSON.parse(fs.readFileSync(path.join(path.resolve(workspaceDir), '.state', LIVENESS_FILE), 'utf8'));
@@ -111,6 +140,25 @@ function writeLiveness(workspaceDir, patch) {
111
140
  // itself remains the observable degradation channel)
112
141
  }
113
142
  }
143
+ /**
144
+ * F9 review fix: finalize the liveness record for EARLY returns (consumer
145
+ * pause, structured degradations). Without this, a cycle that stopped after
146
+ * the `catch_up`/`post_processing` stage write leaves a stale
147
+ * `runningStage` + deadline behind and liveness readers report the
148
+ * finished cycle as still mid-stage.
149
+ */
150
+ function finalizeLiveness(workspaceDir, cycleStartedAt, settlement) {
151
+ writeLiveness(workspaceDir, {
152
+ runningStage: null,
153
+ stageDeadline: null,
154
+ lastCycleCompletedAt: new Date().toISOString(),
155
+ lastCycleDurationMs: Date.now() - cycleStartedAt.getTime(),
156
+ lastCycleMode: settlement.mode,
157
+ lastCycleDriver: codexWorkerCycleDriver(),
158
+ ...(settlement.reason !== undefined ? { lastDegradedReason: settlement.reason } : {}),
159
+ ...invocationIdLivenessPatch(),
160
+ });
161
+ }
114
162
  /**
115
163
  * SPEC §9.1 fair-share pick (review P1): pending and due-retry are both
116
164
  * continuously-eligible classes; neither may starve the other while new
@@ -161,7 +209,7 @@ export async function runCodexWorkspaceWorkerCycle(options) {
161
209
  // must not leave the PRE-pause cycle's deadline behind.
162
210
  stageDeadline: null,
163
211
  lastCycleStartedAt: cycleStartedAt.toISOString(),
164
- lastCycleDriver: process.env.PD_INVOCATION_SOURCE === 'companion' ? 'companion' : 'manual',
212
+ lastCycleDriver: codexWorkerCycleDriver(),
165
213
  });
166
214
  // PRI-1063 (review fix): single-line flow mapping — see catch-up.ts.
167
215
  return { ...base, mode: 'paused', reason: 'host.codex_disabled', nextAction: 'Enable Codex PD behavior in the Workspace .pd/config.yaml — in the existing "features:" block set host.codex: {enabled: true} (one flat key, not nested).' };
@@ -176,7 +224,7 @@ export async function runCodexWorkspaceWorkerCycle(options) {
176
224
  // the marker so the Owner can tell a companion-driven (resident, should
177
225
  // keep cycling) worker from a manual one-shot — "registered" alone said
178
226
  // nothing about whether a driver is actually alive.
179
- lastCycleDriver: process.env.PD_INVOCATION_SOURCE === 'companion' ? 'companion' : 'manual',
227
+ lastCycleDriver: codexWorkerCycleDriver(),
180
228
  });
181
229
  const consumerFlag = loadFeatureFlagFromConfig(workspaceDir, 'internalization_auto_consumer', { info: (m) => logger.info(m), warn: (m) => logger.warn(m) });
182
230
  // PRI-638 P1-C: the Diagnostician capability gate is resolved from the same
@@ -206,6 +254,8 @@ export async function runCodexWorkspaceWorkerCycle(options) {
206
254
  });
207
255
  // Steps 4–6 — execution authority: internalization_auto_consumer.
208
256
  let diagnostician = null;
257
+ // PRI-1274 (B1 / P1-3): filled by the waiting-task reconcile below.
258
+ let targetEvidenceReconcile = null;
209
259
  if (diagnosticianDisabled) {
210
260
  // PRI-638 P1-C: intentional governance pause. No candidate picking, no
211
261
  // provider call, no degraded mode. The rest of the cycle (downstream)
@@ -220,6 +270,9 @@ export async function runCodexWorkspaceWorkerCycle(options) {
220
270
  else if (!consumerFlag.enabled) {
221
271
  // paused: execution pause, NOT evidence freeze. Catch-up + reconcile
222
272
  // already ran above; manual CLI remains allowed (SPEC §13).
273
+ // F9: settle the liveness record — the cycle ENDED here (paused), so the
274
+ // in-flight `catch_up` stage and its deadline must not survive it.
275
+ finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'paused' });
223
276
  return {
224
277
  ...base,
225
278
  mode: 'paused',
@@ -241,6 +294,19 @@ export async function runCodexWorkspaceWorkerCycle(options) {
241
294
  if (sweep.recovered > 0 || sweep.errors.length > 0) {
242
295
  emitEvent('CODEX_WORKER_RECOVERY_SWEEP', JSON.stringify({ recovered: sweep.recovered, failed: sweep.errors.length }));
243
296
  }
297
+ // PRI-1274 (B1 / P1-3): bounded waiting-task reconcile BEFORE picking
298
+ // — catch-up (step 2) may have just delivered the target turn text,
299
+ // and the picker's SQL excludes anything still waiting. Bounded work
300
+ // over the existing task rows + the shared authorized-store probe;
301
+ // no new queue, no scheduler, no scanning of general history.
302
+ targetEvidenceReconcile = await reconcileWaitingTargetEvidenceTasks({
303
+ stateManager: handle.stateManager,
304
+ targetTurnTextAvailable: (sessionId, turnId) => codexTargetTurnTextAvailable(path.resolve(workspaceDir), sessionId, turnId),
305
+ nowIso: new Date().toISOString(),
306
+ });
307
+ if (targetEvidenceReconcile.flipped > 0 || targetEvidenceReconcile.errors.length > 0) {
308
+ emitEvent('CODEX_WORKER_TARGET_EVIDENCE_RECONCILE', JSON.stringify(targetEvidenceReconcile));
309
+ }
244
310
  const candidate = await pickDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT, new Date().toISOString());
245
311
  if (candidate !== null) {
246
312
  const stateDir = path.join(workspaceDir, '.state');
@@ -257,7 +323,9 @@ export async function runCodexWorkspaceWorkerCycle(options) {
257
323
  intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
258
324
  // PRI-1265: the worker's Stage A gets the bound session's ORIGINAL
259
325
  // turns from the workspace's own consent-tiered governance store.
260
- trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir }),
326
+ trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
327
+ // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
328
+ sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
261
329
  // SPEC §9.6: lazy probe — a revoked flag stops persisted
262
330
  // automatic_hook tasks at the bridge's execution boundary.
263
331
  isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
@@ -298,10 +366,14 @@ export async function runCodexWorkspaceWorkerCycle(options) {
298
366
  }
299
367
  catch (error) {
300
368
  const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
369
+ const reason = `diagnostician_execution_failed:${detail}`;
370
+ // F9: settle the liveness record — a degraded early return must not
371
+ // leave a stale mid-stage runningStage behind.
372
+ finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
301
373
  return {
302
374
  ...base,
303
375
  mode: 'degraded',
304
- reason: `diagnostician_execution_failed:${detail}`,
376
+ reason,
305
377
  nextAction: 'Inspect the Workspace runtime profile and provider configuration; the task keeps its pending/retry state and no evidence was mutated.',
306
378
  report: { catchUp, reconcile, postProcessing: null, diagnostician: null, downstream: null },
307
379
  };
@@ -342,7 +414,9 @@ export async function runCodexWorkspaceWorkerCycle(options) {
342
414
  getEnvVar: (name) => process.env[name],
343
415
  // PRI-1265: post-processing resumes see the same authorized
344
416
  // trajectory context as the initial diagnosis run.
345
- trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir }),
417
+ trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
418
+ // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
419
+ sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
346
420
  // SPEC §9.6: lazy probe — automatic_hook backlog resumes honor
347
421
  // the Workspace authorization too.
348
422
  isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
@@ -379,12 +453,14 @@ export async function runCodexWorkspaceWorkerCycle(options) {
379
453
  }
380
454
  catch (error) {
381
455
  const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
456
+ const reason = `post_processing_continuation_failed:${detail}`;
457
+ finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
382
458
  return {
383
459
  ...base,
384
460
  mode: 'degraded',
385
- reason: `post_processing_continuation_failed:${detail}`,
461
+ reason,
386
462
  nextAction: 'Inspect the workspace state.db principle_candidates/tasks; the worker retries automatically on the next cycle.',
387
- report: { catchUp, reconcile, postProcessing: null, diagnostician, downstream: null },
463
+ report: { catchUp, reconcile, postProcessing: null, diagnostician, downstream: null, ...(targetEvidenceReconcile !== null ? { targetEvidenceReconcile } : {}) },
388
464
  };
389
465
  }
390
466
  }
@@ -406,10 +482,12 @@ export async function runCodexWorkspaceWorkerCycle(options) {
406
482
  // liveness contract (host_tool_declaration_missing → OpenClaw default)
407
483
  // and falsely pass host-liveness checks for a Codex activation. Degrade
408
484
  // this cycle instead; the next cycle retries the declaration first.
485
+ const reason = `host_tool_declaration_persist_failed:${declared.reason}`;
486
+ finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
409
487
  return {
410
488
  ...base,
411
489
  mode: 'degraded',
412
- reason: `host_tool_declaration_persist_failed:${declared.reason}`,
490
+ reason,
413
491
  nextAction: 'Repair Codex host declaration persistence (.pd/host-tool-semantics/codex.json) before running the downstream internalization cycle; the worker retries automatically on the next cycle.',
414
492
  report: { catchUp, reconcile, postProcessing: null, diagnostician, downstream: null },
415
493
  };
@@ -471,14 +549,15 @@ export async function runCodexWorkspaceWorkerCycle(options) {
471
549
  lastCycleMode: degradedReason !== undefined ? 'degraded' : 'ready',
472
550
  // PRI-1264: driver of the last COMPLETED cycle — the stall verdict reads
473
551
  // this so a no_recent_cycle report names WHO stopped driving.
474
- lastCycleDriver: process.env.PD_INVOCATION_SOURCE === 'companion' ? 'companion' : 'manual',
552
+ lastCycleDriver: codexWorkerCycleDriver(),
475
553
  ...(degradedReason !== undefined ? { lastDegradedReason: degradedReason } : {}),
554
+ ...invocationIdLivenessPatch(),
476
555
  });
477
556
  return {
478
557
  ...base,
479
558
  mode: degradedReason !== undefined ? 'degraded' : 'ready',
480
559
  ...(degradedReason !== undefined ? { reason: degradedReason, nextAction: 'Inspect the Workspace .pd/config.yaml runtime profile and the per-step report above; the worker retries automatically on the next cycle.' } : {}),
481
- report: { catchUp, reconcile, postProcessing, diagnostician, downstream, stage2 },
560
+ report: { catchUp, reconcile, postProcessing, diagnostician, downstream, ...(targetEvidenceReconcile !== null ? { targetEvidenceReconcile } : {}), stage2 },
482
561
  };
483
562
  }
484
563
  // Slice D (PRI-625): the mode authority moved to host-runtime so the CLI and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.13.1",
3
+ "version": "0.14.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,9 +33,9 @@
33
33
  "lint": "eslint \"src/**/*.ts\""
34
34
  },
35
35
  "dependencies": {
36
- "@principles/core": "^8.0.1",
37
- "@principles/host-runtime": "^4.5.1",
38
- "@principles/install-layout": "^0.9.1"
36
+ "@principles/core": "^8.1.0",
37
+ "@principles/host-runtime": "^4.6.0",
38
+ "@principles/install-layout": "^0.10.0"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/node": "^26.6.6",
@@ -52,5 +52,5 @@
52
52
  "publishConfig": {
53
53
  "access": "public"
54
54
  },
55
- "gitHead": "44eb2260606776dc28939a45d5375c2fb29b4a0c"
55
+ "gitHead": "5e3b8d53d46dfb3884966a006be3996c1dd34428"
56
56
  }