@principles/codex-adapter 0.13.1 → 0.15.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.
- package/dist/codec/input-decoder.d.ts +17 -0
- package/dist/codec/input-decoder.js +39 -0
- package/dist/ingestion/explicit-owner-statement.js +125 -1
- package/dist/ingestion/pain-receipt-fallback.d.ts +73 -0
- package/dist/ingestion/pain-receipt-fallback.js +229 -0
- package/dist/ingestion/turn-context.d.ts +10 -15
- package/dist/ingestion/turn-context.js +35 -9
- package/dist/pd-hook.js +57 -1
- package/dist/worker/workspace-worker.d.ts +15 -0
- package/dist/worker/workspace-worker.js +168 -69
- package/package.json +5 -5
|
@@ -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
|
|
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,73 @@
|
|
|
1
|
+
import type { TargetTurnEvidenceRead } from '@principles/core/runtime';
|
|
2
|
+
import { type PainReceiptRecoveryOutcome } from '@principles/core/runtime';
|
|
3
|
+
/** The MCP tool id this fallback processes (the server gate lives in the
|
|
4
|
+
* codec parser — exact match on both namespace segments, never a pattern). */
|
|
5
|
+
export declare const PAIN_SUBMIT_TOOL_NAME: 'pd_submit_pain';
|
|
6
|
+
export type PainReceiptFallbackResult = {
|
|
7
|
+
readonly status: 'not_applicable';
|
|
8
|
+
} | {
|
|
9
|
+
readonly status: 'attempted';
|
|
10
|
+
readonly outcome: PainReceiptRecoveryOutcome;
|
|
11
|
+
};
|
|
12
|
+
export interface PainReceiptFallbackInput {
|
|
13
|
+
readonly workspaceDir: string;
|
|
14
|
+
/** Raw host event `tool_name` — gated by the codec MCP namespace parser
|
|
15
|
+
* before anything else happens (P1-1). */
|
|
16
|
+
readonly toolName: string;
|
|
17
|
+
/** Raw `tool_response` from the PostToolUse payload. */
|
|
18
|
+
readonly toolResponse: unknown;
|
|
19
|
+
/** Host-authoritative identity from the event itself. */
|
|
20
|
+
readonly identity: {
|
|
21
|
+
readonly sessionId: string;
|
|
22
|
+
readonly turnId?: string;
|
|
23
|
+
readonly toolCallId: string;
|
|
24
|
+
};
|
|
25
|
+
/** Caller-resolved `host_identity_minimal_metadata` flag verdict. */
|
|
26
|
+
readonly minimalMetadataGranted: boolean;
|
|
27
|
+
readonly now?: () => Date;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* PRI-1273 (A2): the structured target-turn evidence read the worker's
|
|
31
|
+
* waiting-task reconcile consumes. This is the EXACT-turn authority for the
|
|
32
|
+
* Codex host boundary:
|
|
33
|
+
*
|
|
34
|
+
* 1. the source-material consent ledger is consulted FIRST (PRI-1283 R2
|
|
35
|
+
* parity with the submit path): a missing / revoked / not-granted /
|
|
36
|
+
* unreadable decision returns `blocked_by_consent` BEFORE any store
|
|
37
|
+
* query — a denial is never mixed into the waiting set;
|
|
38
|
+
* 2. the governance store is queried for the EXACT (rollout identity, host
|
|
39
|
+
* turn id) — never a session scan, never the submission turn, never a
|
|
40
|
+
* recent-turn fallback;
|
|
41
|
+
* 3. rows keep the same retention/excerpt contract the submit path's
|
|
42
|
+
* enrichment uses (user/assistant turns, operational|promoted retention,
|
|
43
|
+
* `governance_observation:<logicalKey>` sourceRef, bounded note) so the
|
|
44
|
+
* backfilled entries are indistinguishable from submit-time evidence.
|
|
45
|
+
*
|
|
46
|
+
* Expired/purged rows (retention outside operational|promoted, empty text)
|
|
47
|
+
* simply do not qualify — an honest not_found until retention re-promotes
|
|
48
|
+
* or the turn is re-collected.
|
|
49
|
+
*/
|
|
50
|
+
export declare function readCodexTargetTurnEvidence(workspaceDir: string, sessionId: string, turnId: string): TargetTurnEvidenceRead;
|
|
51
|
+
/**
|
|
52
|
+
* P1-3: does the authorized governance store already hold readable text for
|
|
53
|
+
* the EXACT (session, turn)? Shared by the receipt fallback (disposition
|
|
54
|
+
* choice) and the workspace worker's waiting-task reconcile (the flip) —
|
|
55
|
+
* the diagnosis itself re-reads the turn through the same store.
|
|
56
|
+
* Unreadable ⇒ missing. Since PRI-1273 this boolean is the `available`
|
|
57
|
+
* projection of the consent-gated structured read above: a consent denial
|
|
58
|
+
* reads as "not available", so the receipt fallback's waiting disposition
|
|
59
|
+
* is reclassified to `blocked_by_source_material_consent` by the worker
|
|
60
|
+
* reconcile on its next bounded pass.
|
|
61
|
+
*/
|
|
62
|
+
export declare function codexTargetTurnTextAvailable(workspaceDir: string, sessionId: string, turnId: string): boolean;
|
|
63
|
+
/**
|
|
64
|
+
* Attempt the receipt fallback for one PostToolUse event. Never throws —
|
|
65
|
+
* every failure is a structured result the hook surfaces as one bounded
|
|
66
|
+
* diagnostic (rc-9); the hook result itself is unaffected (fail-open belt).
|
|
67
|
+
*/
|
|
68
|
+
export declare function attemptPainReceiptFallback(input: PainReceiptFallbackInput): Promise<PainReceiptFallbackResult>;
|
|
69
|
+
/**
|
|
70
|
+
* One bounded stderr diagnostic line for the hook (ids and codes only —
|
|
71
|
+
* never receipt content, prompts or tool input/output).
|
|
72
|
+
*/
|
|
73
|
+
export declare function painReceiptFallbackDiagnostic(result: PainReceiptFallbackResult): string | null;
|
|
@@ -0,0 +1,229 @@
|
|
|
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 { listGovernanceConversationTextsForHostTurn, readSourceMaterialAuthorization } 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
|
+
* PRI-1273 (A2): the structured target-turn evidence read the worker's
|
|
84
|
+
* waiting-task reconcile consumes. This is the EXACT-turn authority for the
|
|
85
|
+
* Codex host boundary:
|
|
86
|
+
*
|
|
87
|
+
* 1. the source-material consent ledger is consulted FIRST (PRI-1283 R2
|
|
88
|
+
* parity with the submit path): a missing / revoked / not-granted /
|
|
89
|
+
* unreadable decision returns `blocked_by_consent` BEFORE any store
|
|
90
|
+
* query — a denial is never mixed into the waiting set;
|
|
91
|
+
* 2. the governance store is queried for the EXACT (rollout identity, host
|
|
92
|
+
* turn id) — never a session scan, never the submission turn, never a
|
|
93
|
+
* recent-turn fallback;
|
|
94
|
+
* 3. rows keep the same retention/excerpt contract the submit path's
|
|
95
|
+
* enrichment uses (user/assistant turns, operational|promoted retention,
|
|
96
|
+
* `governance_observation:<logicalKey>` sourceRef, bounded note) so the
|
|
97
|
+
* backfilled entries are indistinguishable from submit-time evidence.
|
|
98
|
+
*
|
|
99
|
+
* Expired/purged rows (retention outside operational|promoted, empty text)
|
|
100
|
+
* simply do not qualify — an honest not_found until retention re-promotes
|
|
101
|
+
* or the turn is re-collected.
|
|
102
|
+
*/
|
|
103
|
+
export function readCodexTargetTurnEvidence(workspaceDir, sessionId, turnId) {
|
|
104
|
+
const authorization = readSourceMaterialAuthorization({ workspaceDir, hostKind: 'codex' });
|
|
105
|
+
if (authorization.status === 'blocked') {
|
|
106
|
+
return { status: 'blocked_by_consent', reason: authorization.reason };
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
const result = listGovernanceConversationTextsForHostTurn({
|
|
110
|
+
workspaceDir,
|
|
111
|
+
hostKind: 'codex',
|
|
112
|
+
rolloutIdentity: sessionId,
|
|
113
|
+
hostTurnId: turnId,
|
|
114
|
+
limit: 12,
|
|
115
|
+
});
|
|
116
|
+
if (!result.ok) {
|
|
117
|
+
return { status: 'read_failed', reason: result.reason };
|
|
118
|
+
}
|
|
119
|
+
const entries = result.rows.map((row) => ({
|
|
120
|
+
sourceRef: 'governance_observation:' + row.logicalKey,
|
|
121
|
+
note: row.visibleText.slice(0, 2000),
|
|
122
|
+
}));
|
|
123
|
+
return entries.length > 0
|
|
124
|
+
? { status: 'available', entries }
|
|
125
|
+
: { status: 'not_found' };
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
return { status: 'read_failed', reason: error instanceof Error ? error.message.slice(0, 120) : 'store_exception' };
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* P1-3: does the authorized governance store already hold readable text for
|
|
133
|
+
* the EXACT (session, turn)? Shared by the receipt fallback (disposition
|
|
134
|
+
* choice) and the workspace worker's waiting-task reconcile (the flip) —
|
|
135
|
+
* the diagnosis itself re-reads the turn through the same store.
|
|
136
|
+
* Unreadable ⇒ missing. Since PRI-1273 this boolean is the `available`
|
|
137
|
+
* projection of the consent-gated structured read above: a consent denial
|
|
138
|
+
* reads as "not available", so the receipt fallback's waiting disposition
|
|
139
|
+
* is reclassified to `blocked_by_source_material_consent` by the worker
|
|
140
|
+
* reconcile on its next bounded pass.
|
|
141
|
+
*/
|
|
142
|
+
export function codexTargetTurnTextAvailable(workspaceDir, sessionId, turnId) {
|
|
143
|
+
return readCodexTargetTurnEvidence(workspaceDir, sessionId, turnId).status === 'available';
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Attempt the receipt fallback for one PostToolUse event. Never throws —
|
|
147
|
+
* every failure is a structured result the hook surfaces as one bounded
|
|
148
|
+
* diagnostic (rc-9); the hook result itself is unaffected (fail-open belt).
|
|
149
|
+
*/
|
|
150
|
+
export async function attemptPainReceiptFallback(input) {
|
|
151
|
+
// P1-1: exact namespace gate first — only the PD MCP server's
|
|
152
|
+
// `pd_submit_pain` completion may enter the recovery path.
|
|
153
|
+
if (!isPainSubmitPostToolUseToolName(input.toolName)) {
|
|
154
|
+
return { status: 'not_applicable' };
|
|
155
|
+
}
|
|
156
|
+
// P2: validate AND normalize at the host boundary. Validating a trimmed
|
|
157
|
+
// copy while forwarding the raw value would create a second identity
|
|
158
|
+
// spelling in Core/SQLite (and make exact target-turn joins miss).
|
|
159
|
+
const sessionId = normalizeEventId(input.identity.sessionId, { allowEmpty: false });
|
|
160
|
+
const toolCallId = normalizeEventId(input.identity.toolCallId, { allowEmpty: false });
|
|
161
|
+
const turnId = normalizeEventId(input.identity.turnId, { allowEmpty: true });
|
|
162
|
+
if (sessionId === null || toolCallId === null || turnId === null) {
|
|
163
|
+
return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'event_identity_invalid' } };
|
|
164
|
+
}
|
|
165
|
+
if (sessionId === undefined || toolCallId === undefined) {
|
|
166
|
+
return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'event_identity_missing' } };
|
|
167
|
+
}
|
|
168
|
+
const envelope = extractReceiptText(input.toolResponse);
|
|
169
|
+
if (!envelope.ok) {
|
|
170
|
+
return { status: 'attempted', outcome: { status: 'rejected', reasonCode: envelope.reasonCode } };
|
|
171
|
+
}
|
|
172
|
+
let parsed;
|
|
173
|
+
try {
|
|
174
|
+
parsed = JSON.parse(envelope.text);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
// Degraded transport forms (plain-text statement) and foreign payloads
|
|
178
|
+
// are not receipts — no recovery from free text.
|
|
179
|
+
return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'receipt_text_not_json' } };
|
|
180
|
+
}
|
|
181
|
+
// P2: normalize the workspace spellings BEFORE validation — the same
|
|
182
|
+
// directory written differently (`/w/p` vs `/w/p/.`) is the same
|
|
183
|
+
// workspace; a genuinely different directory is still rejected by the
|
|
184
|
+
// validated exact comparison. Platform path knowledge stays in the
|
|
185
|
+
// adapter (Core stays path-free).
|
|
186
|
+
const normalizedWorkspace = path.resolve(input.workspaceDir);
|
|
187
|
+
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
|
|
188
|
+
const parsedRecord = parsed;
|
|
189
|
+
const rawDir = Object.hasOwn(parsedRecord, 'workspaceDir') ? parsedRecord.workspaceDir : undefined;
|
|
190
|
+
if (typeof rawDir === 'string' && rawDir.length > 0) {
|
|
191
|
+
parsed = { ...parsedRecord, workspaceDir: path.resolve(rawDir) };
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const validated = validatePainSubmitReceipt(parsed, { workspaceDir: normalizedWorkspace });
|
|
195
|
+
if (!validated.ok) {
|
|
196
|
+
return { status: 'attempted', outcome: { status: 'rejected', reasonCode: validated.reasonCode } };
|
|
197
|
+
}
|
|
198
|
+
const outcome = await recoverTaskIdentityFromReceipt({
|
|
199
|
+
workspaceDir: normalizedWorkspace,
|
|
200
|
+
hostKind: 'codex',
|
|
201
|
+
receipt: validated.receipt,
|
|
202
|
+
identity: {
|
|
203
|
+
sessionId,
|
|
204
|
+
...(turnId === undefined ? {} : { submissionTurnId: turnId }),
|
|
205
|
+
toolCallId,
|
|
206
|
+
},
|
|
207
|
+
authorization: { minimalMetadataGranted: input.minimalMetadataGranted },
|
|
208
|
+
targetTurnTextAvailable: (hostSessionId, targetTurnId) => codexTargetTurnTextAvailable(normalizedWorkspace, hostSessionId, targetTurnId),
|
|
209
|
+
...(input.now !== undefined ? { now: input.now } : {}),
|
|
210
|
+
});
|
|
211
|
+
return { status: 'attempted', outcome };
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* One bounded stderr diagnostic line for the hook (ids and codes only —
|
|
215
|
+
* never receipt content, prompts or tool input/output).
|
|
216
|
+
*/
|
|
217
|
+
export function painReceiptFallbackDiagnostic(result) {
|
|
218
|
+
if (result.status === 'not_applicable')
|
|
219
|
+
return null;
|
|
220
|
+
const { outcome } = result;
|
|
221
|
+
switch (outcome.status) {
|
|
222
|
+
case 'recovered':
|
|
223
|
+
return `pain_receipt_recovered:taskId=${outcome.taskId}:state=${outcome.disposition.state}`;
|
|
224
|
+
case 'already_bound':
|
|
225
|
+
return `pain_receipt_idempotent:taskId=${outcome.taskId}`;
|
|
226
|
+
case 'rejected':
|
|
227
|
+
return `pain_receipt_rejected:${outcome.reasonCode}${outcome.detail !== undefined ? `:detail=${Array.from(outcome.detail).slice(0, 80).join('')}` : ''}${outcome.taskId !== undefined ? `:taskId=${outcome.taskId}` : ''}`;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -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 =
|
|
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
|
|
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
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
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
|
|
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
|
|
19
|
-
* never transcript content
|
|
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 =
|
|
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
|
|
232
|
-
*
|
|
233
|
-
*
|
|
234
|
-
*
|
|
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
|
-
|
|
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 { readCodexTargetTurnEvidence } 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:
|
|
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:
|
|
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,45 +294,74 @@ 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
|
+
// PRI-1273 (A2): the probe is the consent-gated EXACT-turn read —
|
|
303
|
+
// the flip CAS backfills the arrived evidence + evidenceClass onto
|
|
304
|
+
// the SAME task, and a source-material denial reclassifies the task
|
|
305
|
+
// to blocked_by_source_material_consent instead of waiting.
|
|
306
|
+
// SPEC TD §2.2 ruling 4: the SAME consent ledger is read once more
|
|
307
|
+
// right before the evidence write (the existing PRI-1283 R2 port), so
|
|
308
|
+
// a revocation landing between the read and the write persists nothing.
|
|
309
|
+
targetEvidenceReconcile = await reconcileWaitingTargetEvidenceTasks({
|
|
310
|
+
stateManager: handle.stateManager,
|
|
311
|
+
readTargetTurnEvidence: (sessionId, turnId) => readCodexTargetTurnEvidence(path.resolve(workspaceDir), sessionId, turnId),
|
|
312
|
+
sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(path.resolve(workspaceDir)),
|
|
313
|
+
nowIso: new Date().toISOString(),
|
|
314
|
+
});
|
|
315
|
+
if (targetEvidenceReconcile.flipped > 0 || targetEvidenceReconcile.blocked > 0 || targetEvidenceReconcile.errors.length > 0) {
|
|
316
|
+
emitEvent('CODEX_WORKER_TARGET_EVIDENCE_RECONCILE', JSON.stringify(targetEvidenceReconcile));
|
|
317
|
+
}
|
|
244
318
|
const candidate = await pickDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT, new Date().toISOString());
|
|
245
319
|
if (candidate !== null) {
|
|
246
320
|
const stateDir = path.join(workspaceDir, '.state');
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
.
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
321
|
+
let releaseBridge;
|
|
322
|
+
try {
|
|
323
|
+
const bridge = await createPainSignalBridge({
|
|
324
|
+
workspaceDir,
|
|
325
|
+
stateDir,
|
|
326
|
+
ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
|
|
327
|
+
owner: WORKER_OWNER,
|
|
328
|
+
effectiveConfig: config.effective,
|
|
329
|
+
getEnvVar: (name) => process.env[name],
|
|
330
|
+
// PRI-1233 / SPEC §9.2: this worker is where Stage A actually runs
|
|
331
|
+
// for governance-admitted Codex pains — the neutral host reader
|
|
332
|
+
// must ride along (flag-off = zero filesystem access inside it).
|
|
333
|
+
intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
|
|
334
|
+
// PRI-1265: the worker's Stage A gets the bound session's ORIGINAL
|
|
335
|
+
// turns from the workspace's own consent-tiered governance store.
|
|
336
|
+
trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
|
|
337
|
+
// PRI-1283 R2: latest-consent gate consulted per assembly / model call.
|
|
338
|
+
sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
|
|
339
|
+
// SPEC §9.6: lazy probe — a revoked flag stops persisted
|
|
340
|
+
// automatic_hook tasks at the bridge's execution boundary.
|
|
341
|
+
isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
|
|
342
|
+
}, (release) => { releaseBridge = release; });
|
|
343
|
+
const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
|
|
344
|
+
// PRI-917 v0.3.3 review fix (P2-2): forward the parked-candidate
|
|
345
|
+
// dispositions so the Owner sees the pending items instead of a bare
|
|
346
|
+
// degraded status with no subject.
|
|
347
|
+
const reuseReviewRequired = (executed.candidateOutcomes ?? [])
|
|
348
|
+
.filter((outcome) => outcome.reason === 'reuse_review_required')
|
|
349
|
+
.map((outcome) => outcome.candidateId);
|
|
350
|
+
diagnostician = {
|
|
351
|
+
taskId: candidate.taskId,
|
|
352
|
+
status: executed.status,
|
|
353
|
+
...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
|
|
354
|
+
...(executed.errorCategory !== undefined ? { errorCategory: executed.errorCategory } : {}),
|
|
355
|
+
...(reuseReviewRequired.length > 0 ? { reuseReviewRequiredCandidateIds: reuseReviewRequired } : {}),
|
|
356
|
+
};
|
|
357
|
+
// The bridge stays cached per workspace (bounded: one per workspace
|
|
358
|
+
// per worker process, exactly like the OpenClaw plugin host) — no
|
|
359
|
+
// per-cycle dispose, so a concurrent cycle can never hit a disposed
|
|
360
|
+
// bridge. The factory self-disposes losing concurrent constructions.
|
|
361
|
+
}
|
|
362
|
+
finally {
|
|
363
|
+
await releaseBridge?.();
|
|
364
|
+
}
|
|
283
365
|
}
|
|
284
366
|
else {
|
|
285
367
|
// No eligible candidate, but a retry_wait task may still be inside
|
|
@@ -298,10 +380,14 @@ export async function runCodexWorkspaceWorkerCycle(options) {
|
|
|
298
380
|
}
|
|
299
381
|
catch (error) {
|
|
300
382
|
const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
|
|
383
|
+
const reason = `diagnostician_execution_failed:${detail}`;
|
|
384
|
+
// F9: settle the liveness record — a degraded early return must not
|
|
385
|
+
// leave a stale mid-stage runningStage behind.
|
|
386
|
+
finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
|
|
301
387
|
return {
|
|
302
388
|
...base,
|
|
303
389
|
mode: 'degraded',
|
|
304
|
-
reason
|
|
390
|
+
reason,
|
|
305
391
|
nextAction: 'Inspect the Workspace runtime profile and provider configuration; the task keeps its pending/retry state and no evidence was mutated.',
|
|
306
392
|
report: { catchUp, reconcile, postProcessing: null, diagnostician: null, downstream: null },
|
|
307
393
|
};
|
|
@@ -333,30 +419,38 @@ export async function runCodexWorkspaceWorkerCycle(options) {
|
|
|
333
419
|
const resumedTaskIds = new Set();
|
|
334
420
|
if (backlog.length > 0) {
|
|
335
421
|
const stateDir = path.join(workspaceDir, '.state');
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
422
|
+
let releaseBridge;
|
|
423
|
+
try {
|
|
424
|
+
const bridge = await createPainSignalBridge({
|
|
425
|
+
workspaceDir,
|
|
426
|
+
stateDir,
|
|
427
|
+
ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
|
|
428
|
+
owner: WORKER_OWNER,
|
|
429
|
+
effectiveConfig: config.effective,
|
|
430
|
+
getEnvVar: (name) => process.env[name],
|
|
431
|
+
// PRI-1265: post-processing resumes see the same authorized
|
|
432
|
+
// trajectory context as the initial diagnosis run.
|
|
433
|
+
trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
|
|
434
|
+
// PRI-1283 R2: latest-consent gate consulted per assembly / model call.
|
|
435
|
+
sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
|
|
436
|
+
// SPEC §9.6: lazy probe — automatic_hook backlog resumes honor
|
|
437
|
+
// the Workspace authorization too.
|
|
438
|
+
isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
|
|
439
|
+
}, (release) => { releaseBridge = release; });
|
|
440
|
+
for (const item of backlog) {
|
|
441
|
+
const resumed = await bridge.resumeSucceededDiagnosisPostProcessing({ taskId: item.taskId });
|
|
442
|
+
if (resumed.status === 'resumed') {
|
|
443
|
+
resumedTaskIds.add(item.taskId);
|
|
444
|
+
}
|
|
445
|
+
else if (resumed.status === 'blocked') {
|
|
446
|
+
blocked.push({ candidateId: item.candidateId, reason: resumed.reason ?? 'blocked' });
|
|
447
|
+
}
|
|
448
|
+
for (const skip of resumed.skipped ?? [])
|
|
449
|
+
blocked.push(skip);
|
|
354
450
|
}
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
for (const skip of resumed.skipped ?? [])
|
|
359
|
-
blocked.push(skip);
|
|
451
|
+
}
|
|
452
|
+
finally {
|
|
453
|
+
await releaseBridge?.();
|
|
360
454
|
}
|
|
361
455
|
}
|
|
362
456
|
postProcessing = {
|
|
@@ -379,12 +473,14 @@ export async function runCodexWorkspaceWorkerCycle(options) {
|
|
|
379
473
|
}
|
|
380
474
|
catch (error) {
|
|
381
475
|
const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
|
|
476
|
+
const reason = `post_processing_continuation_failed:${detail}`;
|
|
477
|
+
finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
|
|
382
478
|
return {
|
|
383
479
|
...base,
|
|
384
480
|
mode: 'degraded',
|
|
385
|
-
reason
|
|
481
|
+
reason,
|
|
386
482
|
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 },
|
|
483
|
+
report: { catchUp, reconcile, postProcessing: null, diagnostician, downstream: null, ...(targetEvidenceReconcile !== null ? { targetEvidenceReconcile } : {}) },
|
|
388
484
|
};
|
|
389
485
|
}
|
|
390
486
|
}
|
|
@@ -406,10 +502,12 @@ export async function runCodexWorkspaceWorkerCycle(options) {
|
|
|
406
502
|
// liveness contract (host_tool_declaration_missing → OpenClaw default)
|
|
407
503
|
// and falsely pass host-liveness checks for a Codex activation. Degrade
|
|
408
504
|
// this cycle instead; the next cycle retries the declaration first.
|
|
505
|
+
const reason = `host_tool_declaration_persist_failed:${declared.reason}`;
|
|
506
|
+
finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
|
|
409
507
|
return {
|
|
410
508
|
...base,
|
|
411
509
|
mode: 'degraded',
|
|
412
|
-
reason
|
|
510
|
+
reason,
|
|
413
511
|
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
512
|
report: { catchUp, reconcile, postProcessing: null, diagnostician, downstream: null },
|
|
415
513
|
};
|
|
@@ -471,14 +569,15 @@ export async function runCodexWorkspaceWorkerCycle(options) {
|
|
|
471
569
|
lastCycleMode: degradedReason !== undefined ? 'degraded' : 'ready',
|
|
472
570
|
// PRI-1264: driver of the last COMPLETED cycle — the stall verdict reads
|
|
473
571
|
// this so a no_recent_cycle report names WHO stopped driving.
|
|
474
|
-
lastCycleDriver:
|
|
572
|
+
lastCycleDriver: codexWorkerCycleDriver(),
|
|
475
573
|
...(degradedReason !== undefined ? { lastDegradedReason: degradedReason } : {}),
|
|
574
|
+
...invocationIdLivenessPatch(),
|
|
476
575
|
});
|
|
477
576
|
return {
|
|
478
577
|
...base,
|
|
479
578
|
mode: degradedReason !== undefined ? 'degraded' : 'ready',
|
|
480
579
|
...(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 },
|
|
580
|
+
report: { catchUp, reconcile, postProcessing, diagnostician, downstream, ...(targetEvidenceReconcile !== null ? { targetEvidenceReconcile } : {}), stage2 },
|
|
482
581
|
};
|
|
483
582
|
}
|
|
484
583
|
// 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.
|
|
3
|
+
"version": "0.15.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
|
|
37
|
-
"@principles/host-runtime": "^4.
|
|
38
|
-
"@principles/install-layout": "^0.
|
|
36
|
+
"@principles/core": "^8.2.0",
|
|
37
|
+
"@principles/host-runtime": "^4.7.0",
|
|
38
|
+
"@principles/install-layout": "^0.11.0"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
41
|
"@types/node": "^26.6.6",
|
|
@@ -52,5 +52,5 @@
|
|
|
52
52
|
"publishConfig": {
|
|
53
53
|
"access": "public"
|
|
54
54
|
},
|
|
55
|
-
"gitHead": "
|
|
55
|
+
"gitHead": "06a20cb7842f41a6510937f92340343158164b9f"
|
|
56
56
|
}
|