@principles/workbuddy-adapter 0.7.1 → 0.9.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 +21 -0
- package/dist/codec/input-decoder.js +50 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/ingestion/pain-receipt-fallback.d.ts +68 -0
- package/dist/ingestion/pain-receipt-fallback.js +225 -0
- package/dist/pd-hook.js +60 -0
- package/dist/worker/workspace-worker.d.ts +7 -0
- package/dist/worker/workspace-worker.js +222 -51
- package/package.json +5 -5
- package/plugin/.codebuddy-plugin/plugin.json +2 -2
|
@@ -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
|
|
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
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -13,5 +13,5 @@ export { resolveWorkbuddyWorkspace, type WorkbuddyWorkspaceResolution, } from '.
|
|
|
13
13
|
export { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS, } from './tool-semantics.js';
|
|
14
14
|
export { recordWorkbuddyPromptDeliveryEvidence, recordWorkbuddyDenyEvidence, workbuddyCapabilityDeclarations, WORKBUDDY_EVIDENCE_ADAPTER_VERSION, } from './workbuddy-evidence-recorder.js';
|
|
15
15
|
export { processWorkbuddyHookInvocation, annotateContextWarnings, type WorkBuddyPdHookResult, } from './pd-hook.js';
|
|
16
|
-
export { runWorkbuddyWorkspaceWorkerCycle, type WorkbuddyWorkerCycleResult, type WorkbuddyWorkerCycleOptions, type WorkbuddyWorkerCycleStepReport, type WorkbuddyWorkerMode, } from './worker/workspace-worker.js';
|
|
16
|
+
export { runWorkbuddyWorkspaceWorkerCycle, readWorkbuddyWorkerLiveness, workbuddyWorkerCycleDriver, type WorkbuddyWorkerCycleResult, type WorkbuddyWorkerCycleOptions, type WorkbuddyWorkerCycleStepReport, type WorkbuddyWorkerMode, } from './worker/workspace-worker.js';
|
|
17
17
|
export { encodeWorkbuddyCwd, deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, resolveWorkbuddyProjectsRoot, decodeWorkbuddyTranscriptWindow, createWorkbuddyTranscriptSource, WORKBUDDY_SINGLE_SESSION_ALERT_BYTES, type WorkbuddyTranscriptFileIdentity, type WorkbuddyTranscriptPathValidation, type DecodedWorkbuddyDelta, type DecodeWorkbuddyWindowInput, type WorkbuddyTranscriptSourceContext, ingestWorkbuddyConversation, workbuddyIngestionHints, catchUpWorkbuddyIngestion, locateWorkbuddyTranscriptBySessionIdentity, type WorkbuddyIngestionOptions, type WorkbuddyIngestionOutcome, type WorkbuddyCatchUpOptions, type WorkbuddyCatchUpResult, } from './ingestion/index.js';
|
package/dist/index.js
CHANGED
|
@@ -13,5 +13,5 @@ export { resolveWorkbuddyWorkspace, } from './workspace-resolution.js';
|
|
|
13
13
|
export { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS, } from './tool-semantics.js';
|
|
14
14
|
export { recordWorkbuddyPromptDeliveryEvidence, recordWorkbuddyDenyEvidence, workbuddyCapabilityDeclarations, WORKBUDDY_EVIDENCE_ADAPTER_VERSION, } from './workbuddy-evidence-recorder.js';
|
|
15
15
|
export { processWorkbuddyHookInvocation, annotateContextWarnings, } from './pd-hook.js';
|
|
16
|
-
export { runWorkbuddyWorkspaceWorkerCycle, } from './worker/workspace-worker.js';
|
|
16
|
+
export { runWorkbuddyWorkspaceWorkerCycle, readWorkbuddyWorkerLiveness, workbuddyWorkerCycleDriver, } from './worker/workspace-worker.js';
|
|
17
17
|
export { encodeWorkbuddyCwd, deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, resolveWorkbuddyProjectsRoot, decodeWorkbuddyTranscriptWindow, createWorkbuddyTranscriptSource, WORKBUDDY_SINGLE_SESSION_ALERT_BYTES, ingestWorkbuddyConversation, workbuddyIngestionHints, catchUpWorkbuddyIngestion, locateWorkbuddyTranscriptBySessionIdentity, } from './ingestion/index.js';
|
|
@@ -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,225 @@
|
|
|
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 { 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
|
+
targetTurnTextAvailable: (hostSessionId, targetTurnId) => workbuddyTargetTurnTextAvailable(normalizedWorkspace, hostSessionId, targetTurnId),
|
|
205
|
+
...(input.now !== undefined ? { now: input.now } : {}),
|
|
206
|
+
});
|
|
207
|
+
return { status: 'attempted', outcome };
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* One bounded stderr diagnostic line for the hook (ids and codes only —
|
|
211
|
+
* never receipt content, prompts or tool input/output).
|
|
212
|
+
*/
|
|
213
|
+
export function painReceiptFallbackDiagnostic(result) {
|
|
214
|
+
if (result.status === 'not_applicable')
|
|
215
|
+
return null;
|
|
216
|
+
const { outcome } = result;
|
|
217
|
+
switch (outcome.status) {
|
|
218
|
+
case 'recovered':
|
|
219
|
+
return `pain_receipt_recovered:taskId=${outcome.taskId}:state=${outcome.disposition.state}`;
|
|
220
|
+
case 'already_bound':
|
|
221
|
+
return `pain_receipt_idempotent:taskId=${outcome.taskId}`;
|
|
222
|
+
case 'rejected':
|
|
223
|
+
return `pain_receipt_rejected:${outcome.reasonCode}${outcome.detail !== undefined ? `:detail=${Array.from(outcome.detail).slice(0, 80).join('')}` : ''}${outcome.taskId !== undefined ? `:taskId=${outcome.taskId}` : ''}`;
|
|
224
|
+
}
|
|
225
|
+
}
|
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
|
}
|
|
@@ -41,6 +41,13 @@ export interface WorkbuddyWorkerCycleOptions {
|
|
|
41
41
|
readonly stage2Classifier?: SignalLlmClassifier | null;
|
|
42
42
|
readonly stage2AggregateBudgetMs?: number;
|
|
43
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* WHO drove this cycle — same attribution contract as the Codex worker
|
|
46
|
+
* (PRI-1264 + Phase 2 `service_host` driver identity, TD §5.2).
|
|
47
|
+
*/
|
|
48
|
+
export declare function workbuddyWorkerCycleDriver(): 'companion' | 'service_host' | 'manual';
|
|
49
|
+
/** Read the persisted liveness record, or null when absent/unreadable. */
|
|
50
|
+
export declare function readWorkbuddyWorkerLiveness(workspaceDir: string): Record<string, unknown> | null;
|
|
44
51
|
/**
|
|
45
52
|
* Run ONE bounded worker cycle for a canonical governance workspace. Never
|
|
46
53
|
* throws: every failure becomes a structured degraded result with a
|
|
@@ -31,12 +31,63 @@
|
|
|
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, createHostIntentDocReader, isAutomaticPainSubmissionAuthorized, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
|
|
34
|
+
import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, 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';
|
|
36
36
|
import { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS } from '../tool-semantics.js';
|
|
37
37
|
import { catchUpWorkbuddyIngestion } from '../ingestion/catch-up.js';
|
|
38
38
|
const WORKER_OWNER = 'companion-worker';
|
|
39
39
|
const DEFAULT_DIAG_CANDIDATE_LIMIT = 5;
|
|
40
|
+
// ── Cycle liveness (Phase 2, SPEC §11 / TD §2.3: WorkBuddy had NO liveness
|
|
41
|
+
// record — FR-10 health was undecidable). Same shape and atomic-write
|
|
42
|
+
// discipline as the Codex worker's `.state/codex-worker-liveness.json`
|
|
43
|
+
// (CR-08 §9.3: liveness facts are worker-owned runtime state, never
|
|
44
|
+
// governance truth). ────────────────────────────────────────────────────
|
|
45
|
+
const LIVENESS_FILE = 'workbuddy-worker-liveness.json';
|
|
46
|
+
const LIVENESS_STAGE_DEADLINE_MS = {
|
|
47
|
+
catch_up: 5 * 60_000,
|
|
48
|
+
reconcile: 5 * 60_000,
|
|
49
|
+
diagnosis_execution: 15 * 60_000,
|
|
50
|
+
downstream_cycle: 10 * 60_000,
|
|
51
|
+
};
|
|
52
|
+
function isPlainRecord(value) {
|
|
53
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* WHO drove this cycle — same attribution contract as the Codex worker
|
|
57
|
+
* (PRI-1264 + Phase 2 `service_host` driver identity, TD §5.2).
|
|
58
|
+
*/
|
|
59
|
+
export function workbuddyWorkerCycleDriver() {
|
|
60
|
+
const source = process.env.PD_INVOCATION_SOURCE;
|
|
61
|
+
if (source === 'companion')
|
|
62
|
+
return 'companion';
|
|
63
|
+
if (source === 'service_host')
|
|
64
|
+
return 'service_host';
|
|
65
|
+
return 'manual';
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* F13 (TD §5.2): the coordinator passes a unique invocation id; when
|
|
69
|
+
* present it lands in the liveness record so the shared per-workspace file
|
|
70
|
+
* can be correlated back to the exact Service Host invocation.
|
|
71
|
+
* R5 review fix: a manual/companion cycle carries NO invocation id, so the
|
|
72
|
+
* patch must CLEAR the field — otherwise a completed manual run would keep
|
|
73
|
+
* masquerading under the previous shadow run's id.
|
|
74
|
+
*/
|
|
75
|
+
function invocationIdLivenessPatch() {
|
|
76
|
+
const invocationId = process.env.PD_INVOCATION_ID;
|
|
77
|
+
return typeof invocationId === 'string' && invocationId.length > 0
|
|
78
|
+
? { lastInvocationId: invocationId }
|
|
79
|
+
: { lastInvocationId: null };
|
|
80
|
+
}
|
|
81
|
+
/** Read the persisted liveness record, or null when absent/unreadable. */
|
|
82
|
+
export function readWorkbuddyWorkerLiveness(workspaceDir) {
|
|
83
|
+
try {
|
|
84
|
+
const parsed = JSON.parse(fs.readFileSync(path.join(path.resolve(workspaceDir), '.state', LIVENESS_FILE), 'utf8'));
|
|
85
|
+
return isPlainRecord(parsed) ? parsed : null;
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
40
91
|
function workerLogger(logger) {
|
|
41
92
|
return logger ?? {
|
|
42
93
|
info: () => undefined,
|
|
@@ -52,23 +103,72 @@ function directoryExists(dir) {
|
|
|
52
103
|
return false;
|
|
53
104
|
}
|
|
54
105
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
106
|
+
function writeLiveness(workspaceDir, patch) {
|
|
107
|
+
try {
|
|
108
|
+
const root = path.resolve(workspaceDir);
|
|
109
|
+
const stateDir = path.join(root, '.state');
|
|
110
|
+
const file = path.join(stateDir, LIVENESS_FILE);
|
|
111
|
+
if (!file.startsWith(root + path.sep))
|
|
112
|
+
return;
|
|
113
|
+
if (!directoryExists(stateDir))
|
|
114
|
+
fs.mkdirSync(stateDir, { recursive: true });
|
|
115
|
+
let current = {};
|
|
116
|
+
try {
|
|
117
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
118
|
+
if (isPlainRecord(parsed))
|
|
119
|
+
current = parsed;
|
|
69
120
|
}
|
|
121
|
+
catch {
|
|
122
|
+
current = {};
|
|
123
|
+
}
|
|
124
|
+
const merged = { ...current, ...patch, updatedAt: new Date().toISOString() };
|
|
125
|
+
// Exclusive random temp + rename (same CodeQL-safe pattern as Codex).
|
|
126
|
+
const tmp = path.join(stateDir, `${LIVENESS_FILE}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 10)}.tmp`);
|
|
127
|
+
const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
128
|
+
try {
|
|
129
|
+
fs.writeFileSync(fd, JSON.stringify(merged));
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
fs.closeSync(fd);
|
|
133
|
+
}
|
|
134
|
+
fs.renameSync(tmp, file);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
// Liveness bookkeeping must never break the cycle (rc-9: the cycle
|
|
138
|
+
// report remains the observable degradation channel).
|
|
70
139
|
}
|
|
71
|
-
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* F9 review fix: settle the liveness record for EARLY returns (consumer
|
|
143
|
+
* pause, structured degradations). A cycle that stops after the `catch_up`
|
|
144
|
+
* stage write must not leave a stale runningStage + deadline behind —
|
|
145
|
+
* liveness readers would report the finished cycle as still mid-stage.
|
|
146
|
+
*/
|
|
147
|
+
function finalizeLiveness(workspaceDir, cycleStartedAt, settlement) {
|
|
148
|
+
writeLiveness(workspaceDir, {
|
|
149
|
+
runningStage: null,
|
|
150
|
+
stageDeadline: null,
|
|
151
|
+
lastCycleCompletedAt: new Date().toISOString(),
|
|
152
|
+
lastCycleDurationMs: Date.now() - cycleStartedAt.getTime(),
|
|
153
|
+
lastCycleMode: settlement.mode,
|
|
154
|
+
lastCycleDriver: workbuddyWorkerCycleDriver(),
|
|
155
|
+
...(settlement.reason !== undefined ? { lastDegradedReason: settlement.reason } : {}),
|
|
156
|
+
...invocationIdLivenessPatch(),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* PRI-1275 review round (CR-2): the candidate pick delegates to the SHARED
|
|
161
|
+
* Core `pickDiagnosticianCandidate` — the same authority the Codex worker
|
|
162
|
+
* uses. Its store queries exclude `waiting_for_target_evidence` /
|
|
163
|
+
* `blocked_by_source_material_consent` tasks INSIDE the SQL (before ORDER BY
|
|
164
|
+
* + LIMIT), so a task left waiting by the receipt recovery can never block
|
|
165
|
+
* the head of this host's diagnostician queue (SPEC §4 A3), and the
|
|
166
|
+
* pending/retry_wait fair-share cursor stays one implementation for both
|
|
167
|
+
* hosts. The local oldest-first variant this replaces had none of those
|
|
168
|
+
* exclusions.
|
|
169
|
+
*/
|
|
170
|
+
async function pickNextDiagnosticianCandidate(stateManager, limit) {
|
|
171
|
+
return pickDiagnosticianCandidate(stateManager, limit, new Date().toISOString());
|
|
72
172
|
}
|
|
73
173
|
/**
|
|
74
174
|
* Run ONE bounded worker cycle for a canonical governance workspace. Never
|
|
@@ -80,6 +180,7 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
80
180
|
const logger = workerLogger(options.logger);
|
|
81
181
|
const emitEvent = options.emitEvent ?? ((_event, _payload) => undefined);
|
|
82
182
|
const base = { workspaceDir };
|
|
183
|
+
const cycleStartedAt = new Date();
|
|
83
184
|
// Step 1 — Workspace eligibility.
|
|
84
185
|
if (!directoryExists(workspaceDir)) {
|
|
85
186
|
return { ...base, mode: 'degraded', reason: 'workspace_missing', nextAction: 'The governance workspace directory no longer exists; run the WorkBuddy setup flow to re-initialize it. No PD state was mutated.' };
|
|
@@ -91,9 +192,25 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
91
192
|
}
|
|
92
193
|
const { flags } = computeFeatureFlagsFromConfig(config.effective);
|
|
93
194
|
if (flags['host.workbuddy']?.enabled !== true) {
|
|
195
|
+
// Same PRI-1264 discipline as Codex: an intentional CONFIG pause keeps
|
|
196
|
+
// the heartbeat alive — the worker IS cycling, deliberately idle.
|
|
197
|
+
writeLiveness(workspaceDir, {
|
|
198
|
+
runningStage: 'paused',
|
|
199
|
+
stageDeadline: null,
|
|
200
|
+
lastCycleStartedAt: cycleStartedAt.toISOString(),
|
|
201
|
+
lastCycleDriver: workbuddyWorkerCycleDriver(),
|
|
202
|
+
});
|
|
94
203
|
// PRI-1063 (review fix): single-line flow mapping — see pd-hook.ts.
|
|
95
204
|
return { ...base, mode: 'paused', reason: 'host.workbuddy_disabled', nextAction: 'Enable WorkBuddy PD behavior in the governance workspace .pd/config.yaml — in the existing "features:" block set host.workbuddy: {enabled: true} (one flat key, not nested).' };
|
|
96
205
|
}
|
|
206
|
+
// Liveness bookkeeping starts only after eligibility (CR-08 ordering —
|
|
207
|
+
// writing into a missing workspace directory would fabricate it).
|
|
208
|
+
writeLiveness(workspaceDir, {
|
|
209
|
+
lastCycleStartedAt: cycleStartedAt.toISOString(),
|
|
210
|
+
runningStage: 'catch_up',
|
|
211
|
+
stageDeadline: new Date(cycleStartedAt.getTime() + LIVENESS_STAGE_DEADLINE_MS.catch_up).toISOString(),
|
|
212
|
+
lastCycleDriver: workbuddyWorkerCycleDriver(),
|
|
213
|
+
});
|
|
97
214
|
const consumerFlag = loadFeatureFlagFromConfig(workspaceDir, 'internalization_auto_consumer', { info: (m) => logger.info(m), warn: (m) => logger.warn(m) });
|
|
98
215
|
// The Diagnostician capability gate resolves from the same canonical
|
|
99
216
|
// authority as the runtime factory. An Owner-disabled agent is an
|
|
@@ -133,17 +250,46 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
133
250
|
};
|
|
134
251
|
}
|
|
135
252
|
else if (!consumerFlag.enabled) {
|
|
253
|
+
// F9: the cycle ENDED here (paused) — settle the liveness record so the
|
|
254
|
+
// in-flight `catch_up` stage and its deadline do not survive it.
|
|
255
|
+
// P2-01 (final-remediation review): EVERY earlier stage's failure must
|
|
256
|
+
// reach the result — not catch-up only. A reconcile failure under a
|
|
257
|
+
// consumer pause is a degraded cycle, never a clean paused + exit 0.
|
|
258
|
+
const prePauseDegradations = [];
|
|
259
|
+
if (catchUp.status === 'degraded') {
|
|
260
|
+
prePauseDegradations.push(`catch_up:${catchUp.reason ?? 'degraded'}`);
|
|
261
|
+
}
|
|
262
|
+
if (!reconcile.ok) {
|
|
263
|
+
prePauseDegradations.push(`reconcile:${reconcile.reason ?? 'failed'}`);
|
|
264
|
+
}
|
|
265
|
+
for (const d of reconcile.degradations) {
|
|
266
|
+
const tagged = `reconcile:${d}`;
|
|
267
|
+
if (!prePauseDegradations.includes(tagged))
|
|
268
|
+
prePauseDegradations.push(tagged);
|
|
269
|
+
}
|
|
270
|
+
if (prePauseDegradations.length > 0) {
|
|
271
|
+
const reason = `paused_stage_failures:${prePauseDegradations.join('|').slice(0, 160)}`;
|
|
272
|
+
finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
|
|
273
|
+
return {
|
|
274
|
+
...base,
|
|
275
|
+
mode: 'degraded',
|
|
276
|
+
reason,
|
|
277
|
+
// Keep the REAL failing stage's recovery guidance ahead of the
|
|
278
|
+
// generic pause hint (P2-01 §C: catchUp.nextAction must not be
|
|
279
|
+
// overwritten by a generic paused suggestion).
|
|
280
|
+
nextAction: catchUp.status === 'degraded' && catchUp.nextAction !== undefined
|
|
281
|
+
? catchUp.nextAction
|
|
282
|
+
: (reconcile.nextAction ?? 'Inspect the governance workspace trajectory store and transcript consent; the worker retries automatically on the next cycle.'),
|
|
283
|
+
degradations: prePauseDegradations,
|
|
284
|
+
report: { catchUp, reconcile, diagnostician: null, downstream: null },
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'paused' });
|
|
136
288
|
return {
|
|
137
289
|
...base,
|
|
138
290
|
mode: 'paused',
|
|
139
291
|
reason: 'internalization_auto_consumer_disabled',
|
|
140
292
|
nextAction: 'Automatic internalization execution is paused for this governance workspace; manual commands remain available: pd diagnose, pd runtime internalization run-once.',
|
|
141
|
-
// Catch-up ran BEFORE this early return. Keeping its degradation on the
|
|
142
|
-
// paused result means `pd workbuddy worker --once` can still report a
|
|
143
|
-
// broken transcript catch-up instead of exiting as a clean pause.
|
|
144
|
-
...(catchUp.status === 'degraded'
|
|
145
|
-
? { degradations: [`catch_up:${catchUp.reason ?? 'degraded'}`] }
|
|
146
|
-
: {}),
|
|
147
293
|
report: { catchUp, reconcile, diagnostician: null, downstream: null },
|
|
148
294
|
};
|
|
149
295
|
}
|
|
@@ -155,34 +301,42 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
155
301
|
if (sweep.recovered > 0 || sweep.errors.length > 0) {
|
|
156
302
|
emitEvent('WORKBUDDY_WORKER_RECOVERY_SWEEP', JSON.stringify({ recovered: sweep.recovered, failed: sweep.errors.length }));
|
|
157
303
|
}
|
|
158
|
-
const candidate = await
|
|
304
|
+
const candidate = await pickNextDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT);
|
|
159
305
|
if (candidate !== null) {
|
|
160
306
|
const stateDir = path.join(workspaceDir, '.state');
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
307
|
+
let releaseBridge;
|
|
308
|
+
try {
|
|
309
|
+
const bridge = await createPainSignalBridge({
|
|
310
|
+
workspaceDir,
|
|
311
|
+
stateDir,
|
|
312
|
+
ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
|
|
313
|
+
owner: WORKER_OWNER,
|
|
314
|
+
effectiveConfig: config.effective,
|
|
315
|
+
getEnvVar: (name) => process.env[name],
|
|
316
|
+
// PRI-1233 / SPEC §9.2: this worker is where Stage A actually runs
|
|
317
|
+
// for governance-admitted WorkBuddy pains — the neutral host reader
|
|
318
|
+
// must ride along (flag-off = zero filesystem access inside it).
|
|
319
|
+
intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
|
|
320
|
+
// PRI-1265: the worker's Stage A gets the bound session's ORIGINAL
|
|
321
|
+
// turns from the workspace's own consent-tiered governance store.
|
|
322
|
+
trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
|
|
323
|
+
// PRI-1283 R2: latest-consent gate consulted per assembly / model call.
|
|
324
|
+
sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
|
|
325
|
+
// SPEC §9.6: lazy probe — a revoked flag stops persisted
|
|
326
|
+
// automatic_hook tasks at the bridge's execution boundary.
|
|
327
|
+
isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
|
|
328
|
+
}, (release) => { releaseBridge = release; });
|
|
329
|
+
const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
|
|
330
|
+
diagnostician = {
|
|
331
|
+
taskId: candidate.taskId,
|
|
332
|
+
status: executed.status,
|
|
333
|
+
...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
|
|
334
|
+
...(executed.errorCategory !== undefined ? { errorCategory: executed.errorCategory } : {}),
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
finally {
|
|
338
|
+
await releaseBridge?.();
|
|
339
|
+
}
|
|
186
340
|
}
|
|
187
341
|
else {
|
|
188
342
|
const waiting = await handle.stateManager.listTasks({ taskKind: 'diagnostician', status: 'retry_wait', orderBy: 'updated_at_asc', limit: 1 });
|
|
@@ -198,10 +352,13 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
198
352
|
}
|
|
199
353
|
catch (error) {
|
|
200
354
|
const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
|
|
355
|
+
const reason = `diagnostician_execution_failed:${detail}`;
|
|
356
|
+
// F9: settle the liveness record on the degraded early return.
|
|
357
|
+
finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
|
|
201
358
|
return {
|
|
202
359
|
...base,
|
|
203
360
|
mode: 'degraded',
|
|
204
|
-
reason
|
|
361
|
+
reason,
|
|
205
362
|
nextAction: 'Inspect the governance workspace runtime profile and provider configuration; the task keeps its pending/retry state and no evidence was mutated.',
|
|
206
363
|
report: { catchUp, reconcile, diagnostician: null, downstream: null },
|
|
207
364
|
};
|
|
@@ -218,14 +375,18 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
218
375
|
});
|
|
219
376
|
if (!declared.ok) {
|
|
220
377
|
logger.warn?.(`[PD:WorkbuddyWorker] Failed to persist WorkBuddy tool declaration: ${declared.reason} — host-neutral consumers will not find it (rc-9)`);
|
|
378
|
+
const reason = `host_tool_declaration_persist_failed:${declared.reason}`;
|
|
379
|
+
// F9: settle the liveness record on the degraded early return.
|
|
380
|
+
finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
|
|
221
381
|
return {
|
|
222
382
|
...base,
|
|
223
383
|
mode: 'degraded',
|
|
224
|
-
reason
|
|
384
|
+
reason,
|
|
225
385
|
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.',
|
|
226
386
|
report: { catchUp, reconcile, diagnostician, downstream: null },
|
|
227
387
|
};
|
|
228
388
|
}
|
|
389
|
+
writeLiveness(workspaceDir, { runningStage: 'downstream_cycle', stageDeadline: new Date(Date.now() + LIVENESS_STAGE_DEADLINE_MS.downstream_cycle).toISOString() });
|
|
229
390
|
const downstream = await runInternalizationConsumerCycle(workspaceDir, {
|
|
230
391
|
owner: WORKER_OWNER,
|
|
231
392
|
logLabel: 'WorkbuddyWorker',
|
|
@@ -261,6 +422,16 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
261
422
|
: downstream.skipReason === 'runtime_config_error' || downstream.skipReason === 'cycle_error' || downstream.skipReason === 'config_malformed' ? `downstream:${downstream.skipReason}`
|
|
262
423
|
: !stage2.ok ? `stage2:${stage2.reason ?? 'failed'}`
|
|
263
424
|
: undefined;
|
|
425
|
+
writeLiveness(workspaceDir, {
|
|
426
|
+
runningStage: null,
|
|
427
|
+
stageDeadline: null,
|
|
428
|
+
lastCycleCompletedAt: new Date().toISOString(),
|
|
429
|
+
lastCycleDurationMs: Date.now() - cycleStartedAt.getTime(),
|
|
430
|
+
lastCycleMode: degradedReason !== undefined ? 'degraded' : 'ready',
|
|
431
|
+
lastCycleDriver: workbuddyWorkerCycleDriver(),
|
|
432
|
+
...(degradedReason !== undefined ? { lastDegradedReason: degradedReason } : {}),
|
|
433
|
+
...invocationIdLivenessPatch(),
|
|
434
|
+
});
|
|
264
435
|
return {
|
|
265
436
|
...base,
|
|
266
437
|
mode: degradedReason !== undefined ? 'degraded' : 'ready',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/workbuddy-adapter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
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.0
|
|
46
|
-
"@principles/host-runtime": "^4.
|
|
47
|
-
"@principles/install-layout": "^0.
|
|
45
|
+
"@principles/core": "^8.2.0",
|
|
46
|
+
"@principles/host-runtime": "^4.7.0",
|
|
47
|
+
"@principles/install-layout": "^0.11.0"
|
|
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": "
|
|
64
|
+
"gitHead": "06a20cb7842f41a6510937f92340343158164b9f"
|
|
65
65
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "principles-disciple",
|
|
3
3
|
"version": "0.2.2",
|
|
4
|
-
"description": "Principles Disciple — Owner-governed behavior internalization for AI agents (WorkBuddy host adapter, ADR-0020 third host). Three independent states: (1) the PD installer registers this plugin and records enablement in settings.json (enabledPlugins[key]) — an existing Owner true/false choice
|
|
5
|
-
"defaultEnabled":
|
|
4
|
+
"description": "Principles Disciple — Owner-governed behavior internalization for AI agents (WorkBuddy host adapter, ADR-0020 third host). Three independent states: (1) the PD installer registers this plugin and records enablement in settings.json (enabledPlugins[key]) — an existing Owner true/false choice always wins, otherwise the manifest defaultEnabled=true applies, so a fresh install is ENABLED out of the box and both its hooks and the bundled pd-recall MCP server load on the next session (the Owner can still disable it at any time); (2) governance is ON by default at install (features.host.workbuddy.enabled=true) and an explicit false opt-out is preserved; (3) automatic pain detection/correction is NOT available in WorkBuddy — record pain only with the explicit \"PD记录痛苦:\" prefix. Ships the read-only pd-recall MCP server (Gate 4).",
|
|
5
|
+
"defaultEnabled": true
|
|
6
6
|
}
|