@principles/workbuddy-adapter 0.8.0 → 0.9.1

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.
@@ -41,3 +41,24 @@ export declare function normalizeWorkbuddyToolResponse(toolResponse: unknown, ev
41
41
  * contract violation. Absent optional identity is never fabricated (rc-6).
42
42
  */
43
43
  export declare function decodeWorkbuddyInput(raw: unknown): HostEvent;
44
+ /** The MCP server ids whose `pd_submit_pain` the receipt fallback serves.
45
+ * WorkBuddy keeps the hyphen — the real installed engine (probe 2026-11-24)
46
+ * registers `mcp__pd-recall__pd_submit_pain` verbatim, with NO identifier
47
+ * sanitization (unlike Codex, whose CLI sanitizes `-`→`_`). A literal
48
+ * `pd_recall` server on this host is a DIFFERENT third-party server and must
49
+ * never reach the recovery path (Devin review, receipt-forgery surface). */
50
+ export declare const PAIN_SUBMIT_MCP_SERVER_IDS: ReadonlySet<string>;
51
+ export interface ParsedWorkbuddyMcpToolName {
52
+ readonly serverId: string;
53
+ readonly toolId: string;
54
+ }
55
+ /** Decompose a WorkBuddy MCP tool name into (serverId, toolId); null when
56
+ * the name is not a namespaced MCP tool name. No substring semantics. */
57
+ export declare function parseWorkbuddyMcpToolName(toolName: string): ParsedWorkbuddyMcpToolName | null;
58
+ /**
59
+ * Exact gate: the tool must be `pd_submit_pain` served by the PD MCP server
60
+ * (`pd-recall`). Every other tool — including an identically-named tool on a
61
+ * DIFFERENT MCP server — fails (equality on both parsed segments, never a
62
+ * substring match).
63
+ */
64
+ export declare function isPainSubmitWorkbuddyToolName(toolName: string): boolean;
@@ -185,8 +185,24 @@ export function normalizeWorkbuddyToolResponse(toolResponse, eventForDiagnostics
185
185
  ? { toolResponse }
186
186
  : toolResponse;
187
187
  }
188
+ if (Array.isArray(toolResponse)) {
189
+ // PRI-1275: MCP tool completions arrive as the CallToolResult CONTENT
190
+ // BLOCK ARRAY (`[{type:'text',text:…}, …]`) — probe-verified on the real
191
+ // installed engine (CodeBuddy Code 2.165.0, 2026-11-24): the engine puts
192
+ // `result.content` directly into the PostToolUse `tool_response`. The
193
+ // channel contract still holds (PostToolUseFailure is the separate
194
+ // failure registration), and the shared classifier already classifies an
195
+ // array envelope as success (normalizeOutcome). rc-4: validating "is
196
+ // array" is not enough — every content block must be a record; anything
197
+ // else is a malformed completion and fails loud. The array passes through
198
+ // UNCHANGED: the structured-receipt fallback reads the exact blocks.
199
+ if (toolResponse.length === 0 || !toolResponse.every((block) => typeof block === 'object' && block !== null)) {
200
+ throw new WorkBuddyDecoderError(`malformed required field "tool_response"`, `${eventForDiagnostics} MCP tool_response must be a non-empty array of content-block objects from ${HOST_CONTRACT_BASELINE}.`);
201
+ }
202
+ return toolResponse;
203
+ }
188
204
  if (!isRecord(toolResponse)) {
189
- throw new WorkBuddyDecoderError(`malformed required field "tool_response"`, `${eventForDiagnostics} tool_response must be the rendered string or the engine result object from ${HOST_CONTRACT_BASELINE}.`);
205
+ throw new WorkBuddyDecoderError(`malformed required field "tool_response"`, `${eventForDiagnostics} tool_response must be the rendered string, the engine result object, or the MCP content-block array from ${HOST_CONTRACT_BASELINE}.`);
190
206
  }
191
207
  const isError = field(toolResponse, 'is_error') === true;
192
208
  const exitCodeValue = field(toolResponse, 'exitCode');
@@ -315,3 +331,36 @@ export function decodeWorkbuddyInput(raw) {
315
331
  const source = `workbuddy:${eventName.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()}`;
316
332
  return { kind, context, rawPayload, source };
317
333
  }
334
+ // ─── PRI-1275 (B2): the MCP namespace gate for the receipt fallback ─────────
335
+ // The real installed engine (CodeBuddy Code 2.165.0, probe 2026-11-24) names
336
+ // MCP tools `mcp__<server>__<tool>` — the same convention the Codex adapter
337
+ // froze in P1-1. Identical semantics here: exact parse of BOTH segments,
338
+ // never a substring match.
339
+ /** The MCP server ids whose `pd_submit_pain` the receipt fallback serves.
340
+ * WorkBuddy keeps the hyphen — the real installed engine (probe 2026-11-24)
341
+ * registers `mcp__pd-recall__pd_submit_pain` verbatim, with NO identifier
342
+ * sanitization (unlike Codex, whose CLI sanitizes `-`→`_`). A literal
343
+ * `pd_recall` server on this host is a DIFFERENT third-party server and must
344
+ * never reach the recovery path (Devin review, receipt-forgery surface). */
345
+ export const PAIN_SUBMIT_MCP_SERVER_IDS = new Set(['pd-recall']);
346
+ /** Decompose a WorkBuddy MCP tool name into (serverId, toolId); null when
347
+ * the name is not a namespaced MCP tool name. No substring semantics. */
348
+ export function parseWorkbuddyMcpToolName(toolName) {
349
+ if (!toolName.startsWith('mcp__'))
350
+ return null;
351
+ const rest = toolName.slice('mcp__'.length);
352
+ const separator = rest.indexOf('__');
353
+ if (separator <= 0 || separator + 2 >= rest.length)
354
+ return null;
355
+ return { serverId: rest.slice(0, separator), toolId: rest.slice(separator + 2) };
356
+ }
357
+ /**
358
+ * Exact gate: the tool must be `pd_submit_pain` served by the PD MCP server
359
+ * (`pd-recall`). Every other tool — including an identically-named tool on a
360
+ * DIFFERENT MCP server — fails (equality on both parsed segments, never a
361
+ * substring match).
362
+ */
363
+ export function isPainSubmitWorkbuddyToolName(toolName) {
364
+ const parsed = parseWorkbuddyMcpToolName(toolName);
365
+ return parsed !== null && PAIN_SUBMIT_MCP_SERVER_IDS.has(parsed.serverId) && parsed.toolId === 'pd_submit_pain';
366
+ }
@@ -0,0 +1,68 @@
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
+ /**
13
+ * WorkBuddy MCP envelope: the tool_response is the CallToolResult content
14
+ * block ARRAY. More than one text block is AMBIGUOUS — two text blocks
15
+ * could each carry a different task's receipt, so the whole envelope is
16
+ * rejected instead of quietly trusting the first block (P2 rule, mirrored
17
+ * from the Codex adapter).
18
+ */
19
+ export declare function extractReceiptText(toolResponse: unknown): {
20
+ ok: true;
21
+ text: string;
22
+ } | {
23
+ ok: false;
24
+ reasonCode: string;
25
+ };
26
+ /**
27
+ * The structured target-turn evidence read for the WorkBuddy host boundary —
28
+ * the exact contract the Codex adapter froze (PRI-1273): the consent ledger
29
+ * FIRST (a denial returns blocked_by_consent BEFORE any store query), then
30
+ * the EXACT (rollout identity, host turn id) — never a session scan, never
31
+ * the submission turn, never a recent-turn fallback.
32
+ */
33
+ export declare function readWorkbuddyTargetTurnEvidence(workspaceDir: string, sessionId: string, turnId: string): TargetTurnEvidenceRead;
34
+ /**
35
+ * Does the authorized governance store already hold readable text for the
36
+ * EXACT (session, turn)? Shared by the receipt fallback (disposition choice)
37
+ * and the workspace worker's waiting-task reconcile (the flip).
38
+ */
39
+ export declare function workbuddyTargetTurnTextAvailable(workspaceDir: string, sessionId: string, turnId: string): boolean;
40
+ export interface PainReceiptFallbackInput {
41
+ readonly workspaceDir: string;
42
+ /** Raw host event `tool_name` — gated by the codec MCP namespace parser
43
+ * before anything else happens (P1-1). */
44
+ readonly toolName: string;
45
+ /** Raw `tool_response` from the PostToolUse payload. */
46
+ readonly toolResponse: unknown;
47
+ /** Host-authoritative identity from the event itself. NO submission turn:
48
+ * the WorkBuddy event's `generation_id` is not a proven turn id (SPEC TD
49
+ * §1.3 field rules), so the type physically omits it (review round). */
50
+ readonly identity: {
51
+ readonly sessionId: string;
52
+ readonly toolCallId: string;
53
+ };
54
+ /** Caller-resolved `host_identity_minimal_metadata` flag verdict. */
55
+ readonly minimalMetadataGranted: boolean;
56
+ readonly now?: () => Date;
57
+ }
58
+ /**
59
+ * Attempt the receipt fallback for one PostToolUse event. Never throws —
60
+ * every failure is a structured result the hook surfaces as one bounded
61
+ * diagnostic (rc-9); the hook result itself is unaffected (fail-open belt).
62
+ */
63
+ export declare function attemptPainReceiptFallback(input: PainReceiptFallbackInput): Promise<PainReceiptFallbackResult>;
64
+ /**
65
+ * One bounded stderr diagnostic line for the hook (ids and codes only —
66
+ * never receipt content, prompts or tool input/output).
67
+ */
68
+ export declare function painReceiptFallbackDiagnostic(result: PainReceiptFallbackResult): string | null;
@@ -0,0 +1,226 @@
1
+ /**
2
+ * PRI-1275 (B2) — WorkBuddy 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 (`host_session_claim_empty`
6
+ * — the WorkBuddy designated fallback territory, PRI-1275 extension of the
7
+ * PRI-1274 P1-2 whitelist). WorkBuddy's formal PostToolUse completion event
8
+ * then carries PD's own structured receipt (`pd.pain-submit-receipt.v1`) in
9
+ * the CallToolResult CONTENT BLOCK ARRAY (`[{type:'text',text:...}, ...]`),
10
+ * probe-verified on the REAL installed engine (CodeBuddy Code 2.165.0,
11
+ * 2026-11-24) — never assumed from Codex's single object envelope. Together
12
+ * with the event's own host-authoritative identity (`session_id` /
13
+ * `generation_id` / `call_id` — never model parameters), this module
14
+ * restores the SAME original task's submission identity through the Core
15
+ * CAS recovery.
16
+ *
17
+ * P1-1 (mirrored from PRI-1274): the gate is an exact parse of
18
+ * `mcp__<server>__<tool>` against the PD server id `pd-recall` + the tool id
19
+ * `pd_submit_pain`. The real WorkBuddy engine keeps the hyphen (probe
20
+ * 2026-11-24) — the sanitized `pd_recall` spelling is NOT admitted, because a
21
+ * locally registered server literally named `pd_recall` is a DIFFERENT
22
+ * third-party server. A bare `pd_submit_pain` or an identically-named tool on
23
+ * another MCP server never enters this path.
24
+ *
25
+ * Authorization: the Workspace-level `host_identity_minimal_metadata` quiet
26
+ * flag — deliberately INDEPENDENT of `workbuddy_conversation_ingestion`
27
+ * (full conversation ingestion may stay off; this path reads no transcript
28
+ * and persists ids only).
29
+ *
30
+ * No recovery is EVER attempted from free text, ordinary tool_call rows, or
31
+ * look-alike strings (SPEC TD §1.3).
32
+ */
33
+ import * as path from 'node:path';
34
+ import { createConsentLedgerSourceMaterialAuthorization, readSourceMaterialAuthorization } from '@principles/host-runtime';
35
+ import { isSentinelSessionId } from '@principles/core/runtime';
36
+ import { listGovernanceConversationTextsForHostTurn } from '@principles/host-runtime';
37
+ import { recoverTaskIdentityFromReceipt, validatePainSubmitReceipt, } from '@principles/core/runtime';
38
+ import { isPainSubmitWorkbuddyToolName } from '../codec/input-decoder.js';
39
+ /** The MCP tool id this fallback processes (the server gate lives in the
40
+ * codec parser — exact match on both namespace segments, never a pattern). */
41
+ export const PAIN_SUBMIT_TOOL_NAME = 'pd_submit_pain';
42
+ /**
43
+ * WorkBuddy MCP envelope: the tool_response is the CallToolResult content
44
+ * block ARRAY. More than one text block is AMBIGUOUS — two text blocks
45
+ * could each carry a different task's receipt, so the whole envelope is
46
+ * rejected instead of quietly trusting the first block (P2 rule, mirrored
47
+ * from the Codex adapter).
48
+ */
49
+ export function extractReceiptText(toolResponse) {
50
+ if (!Array.isArray(toolResponse)) {
51
+ return { ok: false, reasonCode: 'receipt_envelope_not_content_array' };
52
+ }
53
+ const textBlocks = [];
54
+ for (const block of toolResponse) {
55
+ if (typeof block !== 'object' || block === null || Array.isArray(block)) {
56
+ return { ok: false, reasonCode: 'receipt_envelope_block_invalid' };
57
+ }
58
+ const record = block;
59
+ const type = Object.hasOwn(record, 'type') ? record.type : undefined;
60
+ const text = Object.hasOwn(record, 'text') ? record.text : undefined;
61
+ if (type === 'text' && typeof text === 'string')
62
+ textBlocks.push(text);
63
+ }
64
+ if (textBlocks.length === 0)
65
+ return { ok: false, reasonCode: 'receipt_envelope_content_missing' };
66
+ const [firstText] = textBlocks;
67
+ if (firstText === undefined)
68
+ return { ok: false, reasonCode: 'receipt_envelope_content_missing' };
69
+ if (textBlocks.length > 1)
70
+ return { ok: false, reasonCode: 'receipt_envelope_ambiguous_content' };
71
+ return { ok: true, text: firstText };
72
+ }
73
+ /**
74
+ * Normalize host ids at the adapter boundary, matching the trusted `_meta`
75
+ * reader. `null` means malformed; `undefined` means absent (or an empty
76
+ * optional id). Only the normalized value may cross into Core.
77
+ */
78
+ function normalizeEventId(value, opts) {
79
+ if (value === undefined)
80
+ return undefined;
81
+ if (typeof value !== 'string')
82
+ return null;
83
+ const id = value.trim();
84
+ if (opts.allowEmpty && id.length === 0)
85
+ return undefined;
86
+ return id.length > 0 && id.length <= 200 && !isSentinelSessionId(id) ? id : null;
87
+ }
88
+ /**
89
+ * The structured target-turn evidence read for the WorkBuddy host boundary —
90
+ * the exact contract the Codex adapter froze (PRI-1273): the consent ledger
91
+ * FIRST (a denial returns blocked_by_consent BEFORE any store query), then
92
+ * the EXACT (rollout identity, host turn id) — never a session scan, never
93
+ * the submission turn, never a recent-turn fallback.
94
+ */
95
+ export function readWorkbuddyTargetTurnEvidence(workspaceDir, sessionId, turnId) {
96
+ const authorization = readSourceMaterialAuthorization({ workspaceDir, hostKind: 'workbuddy' });
97
+ if (authorization.status === 'blocked') {
98
+ return { status: 'blocked_by_consent', reason: authorization.reason };
99
+ }
100
+ try {
101
+ const result = listGovernanceConversationTextsForHostTurn({
102
+ workspaceDir,
103
+ hostKind: 'workbuddy',
104
+ rolloutIdentity: sessionId,
105
+ hostTurnId: turnId,
106
+ limit: 12,
107
+ });
108
+ if (!result.ok) {
109
+ return { status: 'read_failed', reason: result.reason };
110
+ }
111
+ const entries = result.rows.map((row) => ({
112
+ sourceRef: 'governance_observation:' + row.logicalKey,
113
+ note: row.visibleText.slice(0, 2000),
114
+ }));
115
+ return entries.length > 0
116
+ ? { status: 'available', entries }
117
+ : { status: 'not_found' };
118
+ }
119
+ catch (error) {
120
+ return { status: 'read_failed', reason: error instanceof Error ? error.message.slice(0, 120) : 'store_exception' };
121
+ }
122
+ }
123
+ /**
124
+ * Does the authorized governance store already hold readable text for the
125
+ * EXACT (session, turn)? Shared by the receipt fallback (disposition choice)
126
+ * and the workspace worker's waiting-task reconcile (the flip).
127
+ */
128
+ export function workbuddyTargetTurnTextAvailable(workspaceDir, sessionId, turnId) {
129
+ return readWorkbuddyTargetTurnEvidence(workspaceDir, sessionId, turnId).status === 'available';
130
+ }
131
+ /**
132
+ * Attempt the receipt fallback for one PostToolUse event. Never throws —
133
+ * every failure is a structured result the hook surfaces as one bounded
134
+ * diagnostic (rc-9); the hook result itself is unaffected (fail-open belt).
135
+ */
136
+ export async function attemptPainReceiptFallback(input) {
137
+ // P1-1: exact namespace gate first — only the PD MCP server's
138
+ // `pd_submit_pain` completion may enter the recovery path.
139
+ if (!isPainSubmitWorkbuddyToolName(input.toolName)) {
140
+ return { status: 'not_applicable' };
141
+ }
142
+ // P2: validate AND normalize at the host boundary. Validating a trimmed
143
+ // copy while forwarding the raw value would create a second identity
144
+ // spelling in Core/SQLite (and make exact target-turn joins miss).
145
+ const sessionId = normalizeEventId(input.identity.sessionId, { allowEmpty: false });
146
+ const toolCallId = normalizeEventId(input.identity.toolCallId, { allowEmpty: false });
147
+ if (sessionId === null || toolCallId === null) {
148
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'event_identity_invalid' } };
149
+ }
150
+ if (sessionId === undefined || toolCallId === undefined) {
151
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'event_identity_missing' } };
152
+ }
153
+ const envelope = extractReceiptText(input.toolResponse);
154
+ if (!envelope.ok) {
155
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: envelope.reasonCode } };
156
+ }
157
+ let parsed;
158
+ try {
159
+ parsed = JSON.parse(envelope.text);
160
+ }
161
+ catch {
162
+ // Degraded transport forms (plain-text statement) and foreign payloads
163
+ // are not receipts — no recovery from free text.
164
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'receipt_text_not_json' } };
165
+ }
166
+ // P2: normalize the workspace spellings BEFORE validation — the same
167
+ // directory written differently (`/w/p` vs `/w/p/.`) is the same
168
+ // workspace; a genuinely different directory is still rejected by the
169
+ // validated exact comparison. Platform path knowledge stays in the
170
+ // adapter (Core stays path-free).
171
+ const normalizedWorkspace = path.resolve(input.workspaceDir);
172
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
173
+ const parsedRecord = parsed;
174
+ const rawDir = Object.hasOwn(parsedRecord, 'workspaceDir') ? parsedRecord.workspaceDir : undefined;
175
+ if (typeof rawDir === 'string' && rawDir.length > 0) {
176
+ parsed = { ...parsedRecord, workspaceDir: path.resolve(rawDir) };
177
+ }
178
+ }
179
+ const validated = validatePainSubmitReceipt(parsed, { workspaceDir: normalizedWorkspace });
180
+ if (!validated.ok) {
181
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: validated.reasonCode } };
182
+ }
183
+ // Nothing to repair: a `submitted` receipt whose association is already
184
+ // `verified` means the trusted `_meta` path bound the identity at the
185
+ // INITIAL write. Running the recovery anyway could only answer
186
+ // `already_bound`, which the hook renders as a routine `status=degraded`
187
+ // line on EVERY successful submission — drowning the genuinely actionable
188
+ // degraded signals (and the `blocked_by_consent` nextAction). This is the
189
+ // normal WorkBuddy happy path, not a fallback case at all.
190
+ // `submit_unconfirmed` is deliberately NOT skipped: its write outcome is
191
+ // unknown, so the read-back-confirmed recovery still applies.
192
+ if (validated.receipt.status === 'submitted' && validated.receipt.sessionAssociation.status === 'verified') {
193
+ return { status: 'not_applicable' };
194
+ }
195
+ const outcome = await recoverTaskIdentityFromReceipt({
196
+ workspaceDir: normalizedWorkspace,
197
+ hostKind: 'workbuddy',
198
+ receipt: validated.receipt,
199
+ // No submissionTurnId: the WorkBuddy host provides no proven turn id.
200
+ // An absent turn never negates the session binding (SPEC §G2); a target
201
+ // turn pinned to an unproven id would wedge the task's evidence wait.
202
+ identity: { sessionId, toolCallId },
203
+ authorization: { minimalMetadataGranted: input.minimalMetadataGranted },
204
+ readTargetTurnEvidence: (hostSessionId, targetTurnId) => readWorkbuddyTargetTurnEvidence(normalizedWorkspace, hostSessionId, targetTurnId),
205
+ sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(normalizedWorkspace),
206
+ ...(input.now !== undefined ? { now: input.now } : {}),
207
+ });
208
+ return { status: 'attempted', outcome };
209
+ }
210
+ /**
211
+ * One bounded stderr diagnostic line for the hook (ids and codes only —
212
+ * never receipt content, prompts or tool input/output).
213
+ */
214
+ export function painReceiptFallbackDiagnostic(result) {
215
+ if (result.status === 'not_applicable')
216
+ return null;
217
+ const { outcome } = result;
218
+ switch (outcome.status) {
219
+ case 'recovered':
220
+ return `pain_receipt_recovered:taskId=${outcome.taskId}:state=${outcome.disposition.state}`;
221
+ case 'already_bound':
222
+ return `pain_receipt_idempotent:taskId=${outcome.taskId}`;
223
+ case 'rejected':
224
+ return `pain_receipt_rejected:${outcome.reasonCode}${outcome.detail !== undefined ? `:detail=${Array.from(outcome.detail).slice(0, 80).join('')}` : ''}${outcome.taskId !== undefined ? `:taskId=${outcome.taskId}` : ''}`;
225
+ }
226
+ }
package/dist/pd-hook.js CHANGED
@@ -45,6 +45,8 @@ import { WorkBuddyDecoderError, WorkBuddyEncoderError, isWorkBuddyHookOutput, WO
45
45
  import { recordWorkbuddyOwnerStatement } from './explicit-owner-statement.js';
46
46
  import { recordWorkbuddyPromptDeliveryEvidence, recordWorkbuddyDenyEvidence } from './workbuddy-evidence-recorder.js';
47
47
  import { ingestWorkbuddyConversation } from './ingestion/ingestion.js';
48
+ import { attemptPainReceiptFallback, painReceiptFallbackDiagnostic } from './ingestion/pain-receipt-fallback.js';
49
+ import { isPainSubmitWorkbuddyToolName } from './codec/input-decoder.js';
48
50
  const MAX_DIAGNOSTIC = 500;
49
51
  function bound(text) {
50
52
  return text.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
@@ -563,12 +565,70 @@ export async function processWorkbuddyHookInvocation(rawStdin, channelEventName,
563
565
  evidenceDiagnostics.push(diagnostic('degraded', `workbuddy_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
564
566
  }
565
567
  }
568
+ // PRI-1275 (B2): PostToolUse structured-receipt fallback. When a
569
+ // pd_submit_pain MCP request carried no trusted host `_meta`, its
570
+ // original Pain/Task was legally persisted unbound; the host completion
571
+ // event's own structured receipt + host-authoritative identity now
572
+ // restores the SAME task via the Core CAS recovery. P1-1: the tool name
573
+ // arrives in WorkBuddy's MCP namespace (`mcp__pd-recall__pd_submit_pain`,
574
+ // hyphen preserved — the engine does NOT sanitize) and is gated by the
575
+ // exact codec parser — a bare or foreign-server name never enters.
576
+ // Independent of workbuddy_conversation_ingestion (no
577
+ // transcript read; ids only), gated by the Workspace-level
578
+ // host_identity_minimal_metadata authorization. Fail-open: a fallback
579
+ // failure never changes the host decision.
580
+ const receiptDiagnostics = [];
581
+ // Each hook invocation resolves the flags from the CURRENT config, so a
582
+ // revoked minimal identity authorization stops binding on the next event.
583
+ const minimalMetadataGranted = flags.host_identity_minimal_metadata?.enabled === true;
584
+ if (event.kind === 'after_tool_call'
585
+ && event.context.toolName !== undefined
586
+ && isPainSubmitWorkbuddyToolName(event.context.toolName)
587
+ && event.context.toolCallId !== undefined) {
588
+ try {
589
+ const fallback = await attemptPainReceiptFallback({
590
+ workspaceDir: resolution.workspaceDir,
591
+ toolName: event.context.toolName,
592
+ toolResponse: event.context.toolOutput,
593
+ // Identity comes from the EVENT's own session/call ids. The event's
594
+ // `generation_id` (decoder `context.turnId`) is deliberately NOT
595
+ // passed: its equivalence to a PD submission turn is unproven
596
+ // (SPEC TD §1.3 field rules; Devin/CodeRabbit round — mapping it
597
+ // would pin the recovery to a target the trajectory store cannot
598
+ // resolve, wedging the task in waiting_for_target_evidence).
599
+ identity: {
600
+ sessionId: event.context.sessionId,
601
+ toolCallId: event.context.toolCallId,
602
+ },
603
+ minimalMetadataGranted,
604
+ });
605
+ const line = painReceiptFallbackDiagnostic(fallback);
606
+ if (line !== null) {
607
+ const nextAction = fallback.status === 'not_applicable'
608
+ ? undefined
609
+ : fallback.outcome.status === 'recovered'
610
+ ? 'The submission identity was restored on the original task; no resubmission is needed.'
611
+ : fallback.outcome.status === 'already_bound'
612
+ ? 'The original task already carries this identity; nothing to do.'
613
+ : fallback.outcome.reasonCode === 'blocked_by_consent'
614
+ ? 'The Workspace has not granted minimal identity-metadata collection; enable host_identity_minimal_metadata in .pd/config.yaml if binding is wanted.'
615
+ : 'The recovery was refused and is not retried automatically; the submission stays legally unbound. Resubmit pd_submit_pain only if the binding is needed.';
616
+ receiptDiagnostics.push(nextAction === undefined
617
+ ? diagnostic('degraded', line, 'The receipt fallback outcome was recorded.')
618
+ : diagnostic('degraded', line, nextAction));
619
+ }
620
+ }
621
+ catch (error) {
622
+ receiptDiagnostics.push(diagnostic('degraded', `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.'));
623
+ }
624
+ }
566
625
  const stderr = [
567
626
  ...annotateContextWarnings(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic('degraded', warning, 'Inspect the PD governance workspace state and retry; the hook stayed permissive (allow+warnings is degraded health, not fail-closed).')),
568
627
  ...evaluationDiagnostics,
569
628
  ...evidenceDiagnostics,
570
629
  ...autoDiagnostics,
571
630
  ...toolSemanticsDiagnostics,
631
+ ...receiptDiagnostics,
572
632
  ];
573
633
  return { stdout: receiptOutput(encoded), exitCode: 0, stderr: [...stderr, ...(ownerReceipt === undefined ? [] : [ownerReceipt])] };
574
634
  }
@@ -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 WorkbuddyCatchUpResult } from '../ingestion/catch-up.js';
3
4
  export type WorkbuddyWorkerMode = 'ready' | 'manual_action_required' | 'paused' | 'degraded';
@@ -14,6 +15,8 @@ export interface WorkbuddyWorkerCycleStepReport {
14
15
  readonly nextAction?: string;
15
16
  } | null;
16
17
  readonly downstream: InternalizationConsumerCycleOutcome | null;
18
+ /** PRI-1296: bounded exact-target evidence reconcile, before candidate picking. */
19
+ readonly targetEvidenceReconcile?: TargetEvidenceReconcileReport;
17
20
  /** Phase B Stage-2 review step (always last, ≤2 candidates / ≤60s aggregate). */
18
21
  readonly stage2?: Stage2CorrectionCycleReport;
19
22
  }
@@ -31,10 +31,11 @@
31
31
  */
32
32
  import fs from 'node:fs';
33
33
  import path from 'node:path';
34
- import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
35
- import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createGovernanceTrajectoryTurnReader, createConsentLedgerSourceMaterialAuthorization, createHostIntentDocReader, isAutomaticPainSubmissionAuthorized, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
34
+ import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, reconcileWaitingTargetEvidenceTasks, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
35
+ import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, resolveWorkspacePipelineHostDeps, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
36
36
  import { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS } from '../tool-semantics.js';
37
37
  import { catchUpWorkbuddyIngestion } from '../ingestion/catch-up.js';
38
+ import { readWorkbuddyTargetTurnEvidence } from '../ingestion/pain-receipt-fallback.js';
38
39
  const WORKER_OWNER = 'companion-worker';
39
40
  const DEFAULT_DIAG_CANDIDATE_LIMIT = 5;
40
41
  // ── Cycle liveness (Phase 2, SPEC §11 / TD §2.3: WorkBuddy had NO liveness
@@ -157,22 +158,18 @@ function finalizeLiveness(workspaceDir, cycleStartedAt, settlement) {
157
158
  });
158
159
  }
159
160
  /**
160
- * Oldest pending diagnostician first; retry_wait candidates are filtered to
161
- * those whose backoff window has ELAPSED (same discipline as the Codex
162
- * worker — an old-but-waiting task cannot starve a younger eligible one).
161
+ * PRI-1275 review round (CR-2): the candidate pick delegates to the SHARED
162
+ * Core `pickDiagnosticianCandidate` — the same authority the Codex worker
163
+ * uses. Its store queries exclude `waiting_for_target_evidence` /
164
+ * `blocked_by_source_material_consent` tasks INSIDE the SQL (before ORDER BY
165
+ * + LIMIT), so a task left waiting by the receipt recovery can never block
166
+ * the head of this host's diagnostician queue (SPEC §4 A3), and the
167
+ * pending/retry_wait fair-share cursor stays one implementation for both
168
+ * hosts. The local oldest-first variant this replaces had none of those
169
+ * exclusions.
163
170
  */
164
- async function pickDiagnosticianCandidate(stateManager, limit) {
165
- const pending = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'pending', orderBy: 'updated_at_asc', limit });
166
- const [first] = pending;
167
- if (first !== undefined)
168
- return first;
169
- const retrying = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'retry_wait', orderBy: 'updated_at_asc', limit });
170
- for (const candidate of retrying) {
171
- if (isRetryWaitBackoffElapsed(candidate.status, candidate.leaseExpiresAt)) {
172
- return candidate;
173
- }
174
- }
175
- return null;
171
+ async function pickNextDiagnosticianCandidate(stateManager, limit) {
172
+ return pickDiagnosticianCandidate(stateManager, limit, new Date().toISOString());
176
173
  }
177
174
  /**
178
175
  * Run ONE bounded worker cycle for a canonical governance workspace. Never
@@ -245,6 +242,8 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
245
242
  });
246
243
  // Steps 3–5 — execution authority: internalization_auto_consumer.
247
244
  let diagnostician = null;
245
+ // PRI-1296: filled by the exact-target evidence reconcile below.
246
+ let targetEvidenceReconcile = null;
248
247
  if (diagnosticianDisabled) {
249
248
  diagnostician = {
250
249
  taskId: '',
@@ -301,40 +300,76 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
301
300
  try {
302
301
  const handle = await createRuntimeStateHandle({ workspaceDir, readonly: false });
303
302
  try {
303
+ // SPEC-PD-PIPELINE-SPINE-001 §4.2 (PRI-1292 Phase 2A): ONE assembly
304
+ // point for the five host collaborators. The target-evidence reconcile
305
+ // and any diagnostician bridge in this cycle share the SAME consent
306
+ // authorization instance.
307
+ const hostDeps = resolveWorkspacePipelineHostDeps({
308
+ workspaceDir,
309
+ effectiveConfig: config.effective,
310
+ telemetryPersistenceFailureHandler: (detail) => {
311
+ try {
312
+ emitEvent('WORKBUDDY_WORKER_CRITICAL_TELEMETRY_PERSIST_FAILED', detail);
313
+ }
314
+ catch {
315
+ // Telemetry persistence warnings must never fail the worker cycle.
316
+ }
317
+ },
318
+ });
304
319
  const sweep = await handle.stateManager.runRecoverySweep();
305
320
  if (sweep.recovered > 0 || sweep.errors.length > 0) {
306
321
  emitEvent('WORKBUDDY_WORKER_RECOVERY_SWEEP', JSON.stringify({ recovered: sweep.recovered, failed: sweep.errors.length }));
307
322
  }
308
- const candidate = await pickDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT);
323
+ // PRI-1296: reconcile waiting target evidence BEFORE the candidate
324
+ // picker. Catch-up may have just delivered the exact target turn, and
325
+ // the picker SQL excludes waiting tasks; doing this after picking
326
+ // would let diagnosis consume a task before its evidence exists.
327
+ targetEvidenceReconcile = await reconcileWaitingTargetEvidenceTasks({
328
+ stateManager: handle.stateManager,
329
+ readTargetTurnEvidence: (sessionId, turnId) => readWorkbuddyTargetTurnEvidence(workspaceDir, sessionId, turnId),
330
+ sourceMaterialAuthorization: hostDeps.sourceMaterialAuthorization,
331
+ hostKind: 'workbuddy',
332
+ nowIso: new Date().toISOString(),
333
+ });
334
+ if (targetEvidenceReconcile.flipped > 0 || targetEvidenceReconcile.blocked > 0 || targetEvidenceReconcile.errors.length > 0) {
335
+ emitEvent('WORKBUDDY_WORKER_TARGET_EVIDENCE_RECONCILE', JSON.stringify(targetEvidenceReconcile));
336
+ }
337
+ const candidate = await pickNextDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT);
309
338
  if (candidate !== null) {
310
339
  const stateDir = path.join(workspaceDir, '.state');
311
- const bridge = await createPainSignalBridge({
312
- workspaceDir,
313
- stateDir,
314
- ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
315
- owner: WORKER_OWNER,
316
- effectiveConfig: config.effective,
317
- getEnvVar: (name) => process.env[name],
340
+ let releaseBridge;
341
+ try {
318
342
  // PRI-1233 / SPEC §9.2: this worker is where Stage A actually runs
319
- // for governance-admitted WorkBuddy pains — the neutral host reader
320
- // must ride along (flag-off = zero filesystem access inside it).
321
- intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
322
- // PRI-1265: the worker's Stage A gets the bound session's ORIGINAL
323
- // turns from the workspace's own consent-tiered governance store.
324
- trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
325
- // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
326
- sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
327
- // SPEC §9.6: lazy probe — a revoked flag stops persisted
328
- // automatic_hook tasks at the bridge's execution boundary.
329
- isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
330
- });
331
- const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
332
- diagnostician = {
333
- taskId: candidate.taskId,
334
- status: executed.status,
335
- ...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
336
- ...(executed.errorCategory !== undefined ? { errorCategory: executed.errorCategory } : {}),
337
- };
343
+ // for governance-admitted WorkBuddy pains; PRI-1265: the Stage A gets
344
+ // the bound session's ORIGINAL turns through the shared host deps.
345
+ const bridge = await createPainSignalBridge({
346
+ workspaceDir,
347
+ stateDir,
348
+ ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
349
+ owner: WORKER_OWNER,
350
+ effectiveConfig: config.effective,
351
+ getEnvVar: (name) => process.env[name],
352
+ intentDocReader: hostDeps.intentDocReader,
353
+ trajectoryTurnReader: hostDeps.trajectoryTurnReader,
354
+ sourceMaterialAuthorization: hostDeps.sourceMaterialAuthorization,
355
+ // PRI-939 Option A: allowlisted runner/bridge events persist to
356
+ // the workspace sink instead of the unsubscribed singleton.
357
+ telemetrySink: hostDeps.telemetrySink,
358
+ // SPEC §9.6: lazy probe — a revoked flag stops persisted
359
+ // automatic_hook tasks at the bridge's execution boundary.
360
+ isAutoPainSubmissionAuthorized: hostDeps.isAutoPainSubmissionAuthorized,
361
+ }, (release) => { releaseBridge = release; });
362
+ const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
363
+ diagnostician = {
364
+ taskId: candidate.taskId,
365
+ status: executed.status,
366
+ ...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
367
+ ...(executed.errorCategory !== undefined ? { errorCategory: executed.errorCategory } : {}),
368
+ };
369
+ }
370
+ finally {
371
+ await releaseBridge?.();
372
+ }
338
373
  }
339
374
  else {
340
375
  const waiting = await handle.stateManager.listTasks({ taskKind: 'diagnostician', status: 'retry_wait', orderBy: 'updated_at_asc', limit: 1 });
@@ -358,7 +393,7 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
358
393
  mode: 'degraded',
359
394
  reason,
360
395
  nextAction: 'Inspect the governance workspace runtime profile and provider configuration; the task keeps its pending/retry state and no evidence was mutated.',
361
- report: { catchUp, reconcile, diagnostician: null, downstream: null },
396
+ report: { catchUp, reconcile, diagnostician: null, downstream: null, ...(targetEvidenceReconcile !== null ? { targetEvidenceReconcile } : {}) },
362
397
  };
363
398
  }
364
399
  }
@@ -381,7 +416,7 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
381
416
  mode: 'degraded',
382
417
  reason,
383
418
  nextAction: 'Repair WorkBuddy host declaration persistence (.pd/host-tool-semantics/workbuddy.json) before running the downstream internalization cycle; the worker retries automatically on the next cycle.',
384
- report: { catchUp, reconcile, diagnostician, downstream: null },
419
+ report: { catchUp, reconcile, diagnostician, downstream: null, ...(targetEvidenceReconcile !== null ? { targetEvidenceReconcile } : {}) },
385
420
  };
386
421
  }
387
422
  writeLiveness(workspaceDir, { runningStage: 'downstream_cycle', stageDeadline: new Date(Date.now() + LIVENESS_STAGE_DEADLINE_MS.downstream_cycle).toISOString() });
@@ -434,6 +469,6 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
434
469
  ...base,
435
470
  mode: degradedReason !== undefined ? 'degraded' : 'ready',
436
471
  ...(degradedReason !== undefined ? { reason: degradedReason, nextAction: 'Inspect the governance workspace .pd/config.yaml runtime profile and the per-step report above; the worker retries automatically on the next cycle.' } : {}),
437
- report: { catchUp, reconcile, diagnostician, downstream, stage2 },
472
+ report: { catchUp, reconcile, diagnostician, downstream, ...(targetEvidenceReconcile !== null ? { targetEvidenceReconcile } : {}), stage2 },
438
473
  };
439
474
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/workbuddy-adapter",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "description": "WorkBuddy host adapter for Principles Disciple — implements the HostAdapter interface for WorkBuddy's Git Bash command-hook model (ADR-0020 third host, SPEC workbuddy-host-adapter v0.3.0).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -42,9 +42,9 @@
42
42
  "lint": "eslint \"src/**/*.ts\""
43
43
  },
44
44
  "dependencies": {
45
- "@principles/core": "^8.1.0",
46
- "@principles/host-runtime": "^4.6.0",
47
- "@principles/install-layout": "^0.10.0"
45
+ "@principles/core": "^8.3.0",
46
+ "@principles/host-runtime": "^4.7.1",
47
+ "@principles/install-layout": "^0.11.1"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@types/node": "^26.6.6",
@@ -61,5 +61,5 @@
61
61
  "publishConfig": {
62
62
  "access": "public"
63
63
  },
64
- "gitHead": "5e3b8d53d46dfb3884966a006be3996c1dd34428"
64
+ "gitHead": "16f7e15c5832284db3836b8babed2b7980bca8c9"
65
65
  }