@principles/workbuddy-adapter 0.0.0-stage → 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ Principles Disciple
2
+ Copyright 2026 Principles Disciple Contributors
@@ -0,0 +1,2 @@
1
+ export { decodeWorkbuddyInput, normalizeWorkbuddyToolResponse, WorkBuddyDecoderError, WORKBUDDY_EVENT_PRE_TOOL_USE, WORKBUDDY_EVENT_POST_TOOL_USE, WORKBUDDY_EVENT_POST_TOOL_USE_FAILURE, WORKBUDDY_EVENT_USER_PROMPT_SUBMIT, WORKBUDDY_EVENT_SESSION_START, } from './input-decoder.js';
2
+ export { encodeWorkbuddyOutput, workbuddyOutputFieldsAreWhitelisted, isWorkBuddyHookOutput, WorkBuddyEncoderError, type WorkBuddyHookOutput, } from './output-encoder.js';
@@ -0,0 +1,2 @@
1
+ export { decodeWorkbuddyInput, normalizeWorkbuddyToolResponse, WorkBuddyDecoderError, WORKBUDDY_EVENT_PRE_TOOL_USE, WORKBUDDY_EVENT_POST_TOOL_USE, WORKBUDDY_EVENT_POST_TOOL_USE_FAILURE, WORKBUDDY_EVENT_USER_PROMPT_SUBMIT, WORKBUDDY_EVENT_SESSION_START, } from './input-decoder.js';
2
+ export { encodeWorkbuddyOutput, workbuddyOutputFieldsAreWhitelisted, isWorkBuddyHookOutput, WorkBuddyEncoderError, } from './output-encoder.js';
@@ -0,0 +1,30 @@
1
+ import type { HostEvent } from '@principles/core/host';
2
+ export declare const WORKBUDDY_EVENT_PRE_TOOL_USE = "PreToolUse";
3
+ export declare const WORKBUDDY_EVENT_POST_TOOL_USE = "PostToolUse";
4
+ export declare const WORKBUDDY_EVENT_POST_TOOL_USE_FAILURE = "PostToolUseFailure";
5
+ export declare const WORKBUDDY_EVENT_USER_PROMPT_SUBMIT = "UserPromptSubmit";
6
+ export declare const WORKBUDDY_EVENT_SESSION_START = "SessionStart";
7
+ export declare class WorkBuddyDecoderError extends Error {
8
+ readonly reason: string;
9
+ readonly nextAction: string;
10
+ constructor(reason: string, nextAction: string);
11
+ }
12
+ /**
13
+ * SPEC §4.2 failure normalization: WorkBuddy marks tool failure through
14
+ * explicit shapes — `{is_error:true,...}` (Read failures), Bash
15
+ * `{exitCode>0, error}` — while SUCCESS may be a bare STRING (rendered Read
16
+ * output). A string carries no failure marker and is passed through
17
+ * faithfully (the frozen fixtures show string === Read success; asserting
18
+ * success-or-failure from string-ness alone would be fabrication).
19
+ *
20
+ * The shared production pain path (production-pain-evidence normalizeOutcome)
21
+ * detects failure from an `error` field or a non-zero `exitCode` on the
22
+ * envelope/result. `{is_error:true}` WITHOUT either (the read-iserror fixture
23
+ * shape) would silently classify as success there — so this decoder wraps
24
+ * every DETECTED failure in an explicit envelope
25
+ * `{result: <original>, error: <explicit>}`, preserving the raw response
26
+ * inside `result` while guaranteeing the failure is never missed. Missing
27
+ * exitCode on a detected failure NEVER defaults to success.
28
+ */
29
+ export declare function normalizeWorkbuddyToolResponse(toolResponse: unknown, eventForDiagnostics: string): unknown;
30
+ export declare function decodeWorkbuddyInput(raw: unknown): HostEvent;
@@ -0,0 +1,232 @@
1
+ /**
2
+ * WorkBuddy input decoder — stdin JSON → unified HostEvent.
3
+ *
4
+ * CONTRACT SOURCE (frozen): tests/fixtures/host-contract/hook-runtime-contract.json,
5
+ * captured by Phase 0 real-host probes P01–P06 on WorkBuddy Desktop 5.8.1 /
6
+ * engine 2.161.0 (2026-10-12). Every required-field set below mirrors that
7
+ * contract's per-event `payloadFields.required` exactly; the 10 real payload
8
+ * fixtures under tests/fixtures/host-contract/events/ are the decode tests'
9
+ * primary inputs.
10
+ *
11
+ * Runtime Contract rules applied (AGENTS.md §9):
12
+ * - rc-1/rc-2: the payload is `unknown`; every consumed field is guarded, never
13
+ * `as`-cast;
14
+ * - rc-3: missing/malformed required fields fail loud via WorkBuddyDecoderError;
15
+ * - rc-6: sessionId/turnId/toolCallId all come from the SAME raw payload — a
16
+ * missing id is left undefined, never fabricated from timestamps/hashes;
17
+ * - rc-5: Object.hasOwn-based own-field reads.
18
+ *
19
+ * SPEC workbuddy-host-adapter §4.2 decisions frozen here:
20
+ * - SessionStart has NO cwd (probe P00) — workspaceDir is left empty for the
21
+ * process entry to replace with the resolved governance workspace;
22
+ * - generation_id → context.turnId (present on all observed events, stable
23
+ * within one turn); call_id (= tool_use_id) → context.toolCallId; both
24
+ * OPTIONAL per the frozen contract — undefined stays undefined;
25
+ * - transcript_path is validated for TYPE only and never opened (MVP privacy
26
+ * boundary: PD does not read the transcript);
27
+ * - permission_mode is type-validated and retained WITHOUT granting any extra
28
+ * authority — bypassPermissions never bypasses the governance gate;
29
+ * - PostToolUseFailure (thrown tool errors) maps onto the SAME after_tool_call
30
+ * pain path as PostToolUse: a thrown tool error is a real tool failure.
31
+ * Registration history (OD-02, evidence-driven): v1 did NOT register it —
32
+ * P03 was then read as "ordinary failures already reach PostToolUse". The
33
+ * independent re-verification (2026-10-13, engine 2.161.0 sha256 1b1a01bc…,
34
+ * scripts/dev/workbuddy-probe/probe-post-tool-use-failure.mjs) FALSIFIED
35
+ * that reading: a Write to an existing-but-not-read file emits ONLY
36
+ * PostToolUseFailure (tool_error_code=2009, thrown `error`, NO
37
+ * tool_response) — PostToolUse never fires for that failure class. hooks.json
38
+ * therefore registers the event (matcher '*'), still without adding a core
39
+ * event kind: the payload normalizes to the shared failure envelope below.
40
+ */
41
+ import path from 'node:path';
42
+ const HOST_CONTRACT_BASELINE = 'WorkBuddy Desktop 5.8.1 / engine 2.161.0 (Phase 0 probe contract, 2026-10-12)';
43
+ export const WORKBUDDY_EVENT_PRE_TOOL_USE = 'PreToolUse';
44
+ export const WORKBUDDY_EVENT_POST_TOOL_USE = 'PostToolUse';
45
+ export const WORKBUDDY_EVENT_POST_TOOL_USE_FAILURE = 'PostToolUseFailure';
46
+ export const WORKBUDDY_EVENT_USER_PROMPT_SUBMIT = 'UserPromptSubmit';
47
+ export const WORKBUDDY_EVENT_SESSION_START = 'SessionStart';
48
+ const EVENT_KINDS = new Map([
49
+ [WORKBUDDY_EVENT_PRE_TOOL_USE, 'before_tool_call'],
50
+ [WORKBUDDY_EVENT_POST_TOOL_USE, 'after_tool_call'],
51
+ [WORKBUDDY_EVENT_POST_TOOL_USE_FAILURE, 'after_tool_call'],
52
+ [WORKBUDDY_EVENT_USER_PROMPT_SUBMIT, 'before_prompt_build'],
53
+ [WORKBUDDY_EVENT_SESSION_START, 'session_start'],
54
+ ]);
55
+ export class WorkBuddyDecoderError extends Error {
56
+ reason;
57
+ nextAction;
58
+ constructor(reason, nextAction) {
59
+ super(`WorkBuddy input decode failed: ${reason}`);
60
+ this.reason = reason;
61
+ this.nextAction = nextAction;
62
+ this.name = 'WorkBuddyDecoderError';
63
+ }
64
+ }
65
+ function isRecord(value) {
66
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
67
+ }
68
+ function own(value, key) {
69
+ return Object.hasOwn(value, key) ? Object.getOwnPropertyDescriptor(value, key)?.value : undefined;
70
+ }
71
+ function requiredString(value, key) {
72
+ const candidate = own(value, key);
73
+ if (typeof candidate !== 'string' || candidate.trim().length === 0) {
74
+ throw new WorkBuddyDecoderError(`missing or malformed required field "${key}"`, `Use the exact ${HOST_CONTRACT_BASELINE} ${key} field.`);
75
+ }
76
+ return candidate;
77
+ }
78
+ /** Required-presence field whose value may legitimately be null (transcript_path). */
79
+ function requiredNullableString(value, key) {
80
+ if (!Object.hasOwn(value, key))
81
+ throw new WorkBuddyDecoderError(`missing required field "${key}"`, `Use the exact ${HOST_CONTRACT_BASELINE} ${key} field.`);
82
+ const candidate = own(value, key);
83
+ if (candidate !== null && typeof candidate !== 'string') {
84
+ throw new WorkBuddyDecoderError(`malformed required field "${key}"`, `${key} must be a string or null.`);
85
+ }
86
+ return candidate;
87
+ }
88
+ function requiredRecord(value, key) {
89
+ if (!Object.hasOwn(value, key))
90
+ throw new WorkBuddyDecoderError(`missing required field "${key}"`, `Use the exact ${HOST_CONTRACT_BASELINE} ${key} field.`);
91
+ const candidate = own(value, key);
92
+ if (!isRecord(candidate)) {
93
+ throw new WorkBuddyDecoderError(`malformed required field "${key}"`, `${key} must be a JSON object.`);
94
+ }
95
+ return candidate;
96
+ }
97
+ /** Optional field CONSUMED for lineage: absent → undefined; present-but-invalid → fail loud (rc-3/rc-6). */
98
+ function consumedOptionalString(value, key) {
99
+ if (!Object.hasOwn(value, key))
100
+ return undefined;
101
+ const candidate = own(value, key);
102
+ if (typeof candidate !== 'string' || candidate.trim().length === 0) {
103
+ throw new WorkBuddyDecoderError(`malformed optional field "${key}"`, `${key} must be a non-empty string when present.`);
104
+ }
105
+ return candidate;
106
+ }
107
+ /** Optional field NOT consumed for logic: type-check only when present, value retained nowhere. */
108
+ function validateOptionalStringType(value, key) {
109
+ if (!Object.hasOwn(value, key))
110
+ return;
111
+ const candidate = own(value, key);
112
+ if (typeof candidate !== 'string') {
113
+ throw new WorkBuddyDecoderError(`malformed optional field "${key}"`, `${key} must be a string when present.`);
114
+ }
115
+ }
116
+ function requiredAbsoluteCwd(value) {
117
+ const cwd = requiredString(value, 'cwd');
118
+ if (!path.isAbsolute(cwd)) {
119
+ throw new WorkBuddyDecoderError('cwd is not an absolute path', 'WorkBuddy hook payloads carry the absolute project cwd.');
120
+ }
121
+ return cwd;
122
+ }
123
+ function field(value, key) {
124
+ return Object.hasOwn(value, key) ? Object.getOwnPropertyDescriptor(value, key)?.value : undefined;
125
+ }
126
+ /**
127
+ * SPEC §4.2 failure normalization: WorkBuddy marks tool failure through
128
+ * explicit shapes — `{is_error:true,...}` (Read failures), Bash
129
+ * `{exitCode>0, error}` — while SUCCESS may be a bare STRING (rendered Read
130
+ * output). A string carries no failure marker and is passed through
131
+ * faithfully (the frozen fixtures show string === Read success; asserting
132
+ * success-or-failure from string-ness alone would be fabrication).
133
+ *
134
+ * The shared production pain path (production-pain-evidence normalizeOutcome)
135
+ * detects failure from an `error` field or a non-zero `exitCode` on the
136
+ * envelope/result. `{is_error:true}` WITHOUT either (the read-iserror fixture
137
+ * shape) would silently classify as success there — so this decoder wraps
138
+ * every DETECTED failure in an explicit envelope
139
+ * `{result: <original>, error: <explicit>}`, preserving the raw response
140
+ * inside `result` while guaranteeing the failure is never missed. Missing
141
+ * exitCode on a detected failure NEVER defaults to success.
142
+ */
143
+ export function normalizeWorkbuddyToolResponse(toolResponse, eventForDiagnostics) {
144
+ if (typeof toolResponse === 'string')
145
+ return toolResponse;
146
+ if (!isRecord(toolResponse)) {
147
+ 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}.`);
148
+ }
149
+ const isError = field(toolResponse, 'is_error') === true;
150
+ const exitCodeValue = field(toolResponse, 'exitCode');
151
+ const exitCode = typeof exitCodeValue === 'number' ? exitCodeValue : undefined;
152
+ const errorValue = field(toolResponse, 'error');
153
+ const errorText = typeof errorValue === 'string' && errorValue.trim().length > 0 ? errorValue : undefined;
154
+ const failed = isError || (exitCode !== undefined && exitCode > 0) || errorText !== undefined;
155
+ if (!failed)
156
+ return toolResponse;
157
+ const toolErrorCode = field(toolResponse, 'tool_error_code');
158
+ let explicitError;
159
+ if (errorText !== undefined) {
160
+ explicitError = errorText;
161
+ }
162
+ else {
163
+ const codeSuffix = typeof toolErrorCode === 'string' && toolErrorCode.length > 0 ? ` tool_error_code=${toolErrorCode}` : '';
164
+ explicitError = `workbuddy tool failure: is_error=true${codeSuffix}`;
165
+ }
166
+ return { result: toolResponse, error: explicitError };
167
+ }
168
+ export function decodeWorkbuddyInput(raw) {
169
+ if (!isRecord(raw))
170
+ throw new WorkBuddyDecoderError('stdin payload is not a JSON object', 'Run this executable only as a WorkBuddy command hook.');
171
+ const eventName = requiredString(raw, 'hook_event_name');
172
+ const kind = EVENT_KINDS.get(eventName);
173
+ if (!kind) {
174
+ throw new WorkBuddyDecoderError(`unknown hook_event_name "${eventName}"`, 'Configure only PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, or SessionStart.');
175
+ }
176
+ const sessionId = requiredString(raw, 'session_id');
177
+ requiredNullableString(raw, 'transcript_path');
178
+ // ID mapping (frozen contract §ids): generation_id → turnId on every event
179
+ // where the host provides it; call_id (= tool_use_id) → toolCallId. Neither
180
+ // is ever fabricated when missing (rc-6).
181
+ const turnId = consumedOptionalString(raw, 'generation_id');
182
+ const base = { sessionId, ...(turnId !== undefined ? { turnId } : {}) };
183
+ let context;
184
+ let rawPayload = raw;
185
+ if (kind === 'session_start') {
186
+ // SessionStart has NO cwd (probe P00): source/permission_mode/client/version
187
+ // are the frozen required set. workspaceDir stays empty here — the process
188
+ // entry replaces it with the resolved governance workspace before dispatch.
189
+ const source = requiredString(raw, 'source');
190
+ requiredString(raw, 'permission_mode');
191
+ requiredString(raw, 'client');
192
+ requiredString(raw, 'version');
193
+ context = { ...base, workspaceDir: '', source };
194
+ }
195
+ else if (kind === 'before_prompt_build') {
196
+ const cwd = requiredAbsoluteCwd(raw);
197
+ validateOptionalStringType(raw, 'permission_mode');
198
+ context = { ...base, workspaceDir: cwd, promptContent: requiredString(raw, 'prompt') };
199
+ }
200
+ else {
201
+ const cwd = requiredAbsoluteCwd(raw);
202
+ validateOptionalStringType(raw, 'permission_mode');
203
+ const toolName = requiredString(raw, 'tool_name');
204
+ const toolInput = requiredRecord(raw, 'tool_input');
205
+ const callId = consumedOptionalString(raw, 'call_id') ?? consumedOptionalString(raw, 'tool_use_id');
206
+ if (kind === 'after_tool_call') {
207
+ let toolOutput;
208
+ if (eventName === WORKBUDDY_EVENT_POST_TOOL_USE) {
209
+ if (!Object.hasOwn(raw, 'tool_response')) {
210
+ throw new WorkBuddyDecoderError('missing required field "tool_response"', `Use the exact ${HOST_CONTRACT_BASELINE} tool_response field.`);
211
+ }
212
+ toolOutput = normalizeWorkbuddyToolResponse(own(raw, 'tool_response'), eventName);
213
+ }
214
+ else {
215
+ // PostToolUseFailure: the engine result is the thrown `error` (+ codes).
216
+ // Normalize to the same explicit failure envelope so the shared pain
217
+ // path sees it identically to an is_error PostToolUse result.
218
+ const thrownError = requiredString(raw, 'error');
219
+ toolOutput = { result: raw, error: thrownError };
220
+ }
221
+ context = { ...base, workspaceDir: cwd, toolName, ...(callId !== undefined ? { toolCallId: callId } : {}), toolInput, toolOutput };
222
+ }
223
+ else {
224
+ context = { ...base, workspaceDir: cwd, toolName, ...(callId !== undefined ? { toolCallId: callId } : {}), toolInput };
225
+ }
226
+ // The shared production gate reads its tool tuple from rawPayload.toolInput
227
+ // (production-rulehost-gate readToolInput contract).
228
+ rawPayload = { toolInput: { toolName, params: toolInput } };
229
+ }
230
+ const source = `workbuddy:${eventName.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()}`;
231
+ return { kind, context, rawPayload, source };
232
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * WorkBuddy output encoder — unified HostEventResult → host stdout JSON.
3
+ *
4
+ * CONTRACT SOURCE (frozen, probe P02/P04): the WorkBuddy engine wraps ANY
5
+ * raw stdout text (even invalid JSON, even with exit codes 1/2/3) into a
6
+ * model-visible <system-reminder data-role="hook"> on SessionStart and
7
+ * UserPromptSubmit. Therefore:
8
+ *
9
+ * NEUTRAL RESULT = EMPTY STDOUT. The encoder returns `null` and the entry
10
+ * writes NOTHING. `{}` or a JSON document without additionalContext is NOT
11
+ * a safe neutral on this host — it would be injected verbatim.
12
+ *
13
+ * Whitelist (SPEC §4.3, first version): hookSpecificOutput.{hookEventName,
14
+ * permissionDecision (deny ONLY), permissionDecisionReason, additionalContext}.
15
+ * - permissionDecision "allow" is NEVER emitted: the probe proved allow
16
+ * bypasses the host permission ask (P02), so silence is the only neutral;
17
+ * - deny is PreToolUse-only and requires a non-empty reason (verified to
18
+ * block the tool and reach the model as `Error: <reason>`);
19
+ * - additionalContext is the verified clean injection channel
20
+ * (UserPromptSubmit, probe P04) — v1 enables it for before_prompt_build;
21
+ * - modifiedInput/updatedToolOutput/ask/continue:false are REJECTED (OD-06 +
22
+ * probe side effects: continue:false re-submits the user prompt).
23
+ */
24
+ import type { HostEventResult } from '@principles/core/host';
25
+ type HookName = 'PreToolUse' | 'PostToolUse' | 'UserPromptSubmit' | 'SessionStart';
26
+ interface HookSpecificOutput {
27
+ hookEventName: HookName;
28
+ permissionDecision?: 'deny';
29
+ permissionDecisionReason?: string;
30
+ additionalContext?: string;
31
+ }
32
+ export interface WorkBuddyHookOutput {
33
+ hookSpecificOutput: HookSpecificOutput;
34
+ }
35
+ export declare class WorkBuddyEncoderError extends Error {
36
+ readonly reason: string;
37
+ readonly nextAction: string;
38
+ constructor(reason: string, nextAction: string);
39
+ }
40
+ /**
41
+ * @returns the stdout JSON document, or `null` when the correct output is an
42
+ * EMPTY stdout (neutral — see the file header for why silence is the only
43
+ * safe neutral on this host).
44
+ */
45
+ export declare function encodeWorkbuddyOutput(result: HostEventResult, kind: string): WorkBuddyHookOutput | null;
46
+ /**
47
+ * Whitelist guard for the encoded output (test surface + runtime belt): the
48
+ * document may carry ONLY the four frozen keys under hookSpecificOutput, and
49
+ * permissionDecision may ONLY be the string "deny" (never "allow"/"ask" —
50
+ * P02 proved allow bypasses the host permission ask).
51
+ */
52
+ export declare function workbuddyOutputFieldsAreWhitelisted(output: unknown): {
53
+ ok: boolean;
54
+ violators: string[];
55
+ };
56
+ /**
57
+ * Type guard for values returned by HostAdapter.encodeOutput (interface
58
+ * return type is `unknown` — rc-2: narrow with a guard, never an `as` cast).
59
+ * A document that violates the whitelist is NOT a WorkBuddy hook output.
60
+ */
61
+ export declare function isWorkBuddyHookOutput(value: unknown): value is WorkBuddyHookOutput;
62
+ export {};
@@ -0,0 +1,75 @@
1
+ export class WorkBuddyEncoderError extends Error {
2
+ reason;
3
+ nextAction;
4
+ constructor(reason, nextAction) {
5
+ super(`WorkBuddy output encode failed: ${reason}`);
6
+ this.reason = reason;
7
+ this.nextAction = nextAction;
8
+ this.name = 'WorkBuddyEncoderError';
9
+ }
10
+ }
11
+ function nonEmpty(value) { return typeof value === 'string' && value.trim().length > 0; }
12
+ /**
13
+ * @returns the stdout JSON document, or `null` when the correct output is an
14
+ * EMPTY stdout (neutral — see the file header for why silence is the only
15
+ * safe neutral on this host).
16
+ */
17
+ export function encodeWorkbuddyOutput(result, kind) {
18
+ if (result.modifiedInput !== undefined)
19
+ throw new WorkBuddyEncoderError('modifiedInput is rejected by the PD WorkBuddy adapter (OD-06)', 'Deny or stay silent on the original input.');
20
+ const names = new Map([['before_tool_call', 'PreToolUse'], ['after_tool_call', 'PostToolUse'], ['before_prompt_build', 'UserPromptSubmit'], ['session_start', 'SessionStart']]);
21
+ const hookEventName = names.get(kind);
22
+ if (!hookEventName)
23
+ throw new WorkBuddyEncoderError(`unknown event kind "${kind}"`, 'Encode only a supported WorkBuddy hook event.');
24
+ if (result.decision === 'deny') {
25
+ if (kind !== 'before_tool_call')
26
+ throw new WorkBuddyEncoderError(`deny is unsupported for ${kind}`, 'Return the route-compatible host result.');
27
+ if (!nonEmpty(result.reason))
28
+ throw new WorkBuddyEncoderError('deny requires a non-empty reason', 'Supply an operator-readable reason.');
29
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: result.reason.trim() } };
30
+ }
31
+ if (result.reason !== undefined) {
32
+ throw new WorkBuddyEncoderError('reason without deny is unsupported', 'Drop reason for a non-deny decision.');
33
+ }
34
+ if (result.additionalContext !== undefined) {
35
+ if (kind !== 'before_prompt_build')
36
+ throw new WorkBuddyEncoderError(`additionalContext is unsupported for ${kind} in v1`, 'Only the verified UserPromptSubmit injection channel is enabled (SPEC §4.3).');
37
+ if (!nonEmpty(result.additionalContext))
38
+ throw new WorkBuddyEncoderError('additionalContext must be non-empty', 'Drop or populate additionalContext.');
39
+ return { hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: result.additionalContext } };
40
+ }
41
+ return null;
42
+ }
43
+ const TOP_LEVEL = new Set(['hookSpecificOutput']);
44
+ const NESTED = new Set(['hookEventName', 'permissionDecision', 'permissionDecisionReason', 'additionalContext']);
45
+ const HOOK_NAMES = new Set(['PreToolUse', 'PostToolUse', 'UserPromptSubmit', 'SessionStart']);
46
+ /**
47
+ * Whitelist guard for the encoded output (test surface + runtime belt): the
48
+ * document may carry ONLY the four frozen keys under hookSpecificOutput, and
49
+ * permissionDecision may ONLY be the string "deny" (never "allow"/"ask" —
50
+ * P02 proved allow bypasses the host permission ask).
51
+ */
52
+ export function workbuddyOutputFieldsAreWhitelisted(output) {
53
+ if (typeof output !== 'object' || output === null || Array.isArray(output))
54
+ return { ok: false, violators: ['<not-an-object>'] };
55
+ const top = Object.keys(output).filter((key) => !TOP_LEVEL.has(key));
56
+ const descriptor = Object.getOwnPropertyDescriptor(output, 'hookSpecificOutput')?.value;
57
+ if (typeof descriptor !== 'object' || descriptor === null || Array.isArray(descriptor))
58
+ return { ok: false, violators: [...top, 'hookSpecificOutput'] };
59
+ const nested = Object.keys(descriptor).filter((key) => !NESTED.has(key)).map((key) => `hookSpecificOutput.${key}`);
60
+ const name = Object.getOwnPropertyDescriptor(descriptor, 'hookEventName')?.value;
61
+ if (typeof name !== 'string' || !HOOK_NAMES.has(name))
62
+ nested.push('hookSpecificOutput.hookEventName');
63
+ const decision = Object.getOwnPropertyDescriptor(descriptor, 'permissionDecision')?.value;
64
+ if (decision !== undefined && decision !== 'deny')
65
+ nested.push('hookSpecificOutput.permissionDecision');
66
+ return { ok: top.length + nested.length === 0, violators: [...top, ...nested] };
67
+ }
68
+ /**
69
+ * Type guard for values returned by HostAdapter.encodeOutput (interface
70
+ * return type is `unknown` — rc-2: narrow with a guard, never an `as` cast).
71
+ * A document that violates the whitelist is NOT a WorkBuddy hook output.
72
+ */
73
+ export function isWorkBuddyHookOutput(value) {
74
+ return value !== null && typeof value === 'object' && workbuddyOutputFieldsAreWhitelisted(value).ok;
75
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * WorkBuddyHooksHostAdapter — implements HostAdapter for WorkBuddy
3
+ * (ADR-0020 third host, SPEC workbuddy-host-adapter §4.2).
4
+ *
5
+ * WorkBuddy executes plugin hooks as command subprocesses through Git Bash
6
+ * (probe P05), writing the event payload as JSON on stdin and consuming a
7
+ * JSON hookSpecificOutput document on stdout. This adapter owns:
8
+ * 1. Decoding the raw stdin JSON into a unified HostEvent (codec/input-decoder).
9
+ * 2. Encoding a unified HostEventResult into the whitelisted stdout JSON —
10
+ * or into EMPTY stdout for neutral results, because the host injects any
11
+ * raw stdout text into model-visible context (codec/output-encoder).
12
+ *
13
+ * The adapter does NOT own hook business logic (injection, gate enforcement,
14
+ * pain evidence). Those run in the shared host-runtime production path and
15
+ * are invoked by pd-hook.ts between decodeEvent() and encodeOutput().
16
+ *
17
+ * MVP scope (SPEC §0 four-event baseline): PreToolUse, PostToolUse,
18
+ * UserPromptSubmit, SessionStart. PostToolUseFailure decodes onto the same
19
+ * after_tool_call path but is NOT registered in the shipped hooks.json
20
+ * (OD-02/P03: ordinary tool failures already reach PostToolUse).
21
+ *
22
+ * Feature flag: when host.workbuddy is disabled (quiet, default OFF), the
23
+ * process entry short-circuits to EMPTY stdout + exit 0 with an observable
24
+ * skip record BEFORE this adapter dispatches anything (rc-9).
25
+ */
26
+ import type { HostAdapter, HostEvent, HostEventKind, HostEventResult } from '@principles/core/host';
27
+ export declare class WorkBuddyHooksHostAdapter implements HostAdapter {
28
+ readonly hostId = "workbuddy";
29
+ readonly hostKind: 'subprocess';
30
+ subscribedEvents(): readonly HostEventKind[];
31
+ decodeEvent(raw: unknown): HostEvent;
32
+ encodeOutput(result: HostEventResult, kind: HostEventKind): unknown;
33
+ }
@@ -0,0 +1,23 @@
1
+ import { decodeWorkbuddyInput, encodeWorkbuddyOutput } from './codec/index.js';
2
+ const SUBSCRIBED_EVENTS = [
3
+ 'before_tool_call',
4
+ 'after_tool_call',
5
+ 'before_prompt_build',
6
+ 'session_start',
7
+ ];
8
+ export class WorkBuddyHooksHostAdapter {
9
+ hostId = 'workbuddy';
10
+ hostKind = 'subprocess';
11
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
12
+ subscribedEvents() {
13
+ return SUBSCRIBED_EVENTS;
14
+ }
15
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
16
+ decodeEvent(raw) {
17
+ return decodeWorkbuddyInput(raw);
18
+ }
19
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
20
+ encodeOutput(result, kind) {
21
+ return encodeWorkbuddyOutput(result, kind);
22
+ }
23
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @principles/workbuddy-adapter — the WorkBuddy host adapter for Principles
3
+ * Disciple (ADR-0020 third host, SPEC workbuddy-host-adapter v0.3.0).
4
+ *
5
+ * Public surface mirrors the codex-adapter layout: the HostAdapter
6
+ * implementation, the codec, the governance-workspace resolution, the tool
7
+ * semantic declaration, and the evidence recorder. The process entry lives
8
+ * at ./pd-hook (spawned per hook event by plugin/scripts/wrapper.cjs).
9
+ */
10
+ export { WorkBuddyHooksHostAdapter } from './host-adapter.js';
11
+ export { decodeWorkbuddyInput, normalizeWorkbuddyToolResponse, encodeWorkbuddyOutput, workbuddyOutputFieldsAreWhitelisted, WorkBuddyDecoderError, WorkBuddyEncoderError, WORKBUDDY_EVENT_PRE_TOOL_USE, WORKBUDDY_EVENT_POST_TOOL_USE, WORKBUDDY_EVENT_POST_TOOL_USE_FAILURE, WORKBUDDY_EVENT_USER_PROMPT_SUBMIT, WORKBUDDY_EVENT_SESSION_START, type WorkBuddyHookOutput, } from './codec/index.js';
12
+ export { resolveWorkbuddyWorkspace, type WorkbuddyWorkspaceResolution, } from './workspace-resolution.js';
13
+ export { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS, } from './tool-semantics.js';
14
+ export { recordWorkbuddyPromptDeliveryEvidence, recordWorkbuddyDenyEvidence, workbuddyCapabilityDeclarations, WORKBUDDY_EVIDENCE_ADAPTER_VERSION, } from './workbuddy-evidence-recorder.js';
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';
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @principles/workbuddy-adapter — the WorkBuddy host adapter for Principles
3
+ * Disciple (ADR-0020 third host, SPEC workbuddy-host-adapter v0.3.0).
4
+ *
5
+ * Public surface mirrors the codex-adapter layout: the HostAdapter
6
+ * implementation, the codec, the governance-workspace resolution, the tool
7
+ * semantic declaration, and the evidence recorder. The process entry lives
8
+ * at ./pd-hook (spawned per hook event by plugin/scripts/wrapper.cjs).
9
+ */
10
+ export { WorkBuddyHooksHostAdapter } from './host-adapter.js';
11
+ export { decodeWorkbuddyInput, normalizeWorkbuddyToolResponse, encodeWorkbuddyOutput, workbuddyOutputFieldsAreWhitelisted, WorkBuddyDecoderError, WorkBuddyEncoderError, WORKBUDDY_EVENT_PRE_TOOL_USE, WORKBUDDY_EVENT_POST_TOOL_USE, WORKBUDDY_EVENT_POST_TOOL_USE_FAILURE, WORKBUDDY_EVENT_USER_PROMPT_SUBMIT, WORKBUDDY_EVENT_SESSION_START, } from './codec/index.js';
12
+ export { resolveWorkbuddyWorkspace, } from './workspace-resolution.js';
13
+ export { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS, } from './tool-semantics.js';
14
+ export { recordWorkbuddyPromptDeliveryEvidence, recordWorkbuddyDenyEvidence, workbuddyCapabilityDeclarations, WORKBUDDY_EVIDENCE_ADAPTER_VERSION, } from './workbuddy-evidence-recorder.js';
15
+ export { processWorkbuddyHookInvocation, annotateContextWarnings, } from './pd-hook.js';
16
+ export { runWorkbuddyWorkspaceWorkerCycle, } from './worker/workspace-worker.js';
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import { type WorkBuddyHookOutput } from './codec/index.js';
3
+ type EnvMap = Record<string, string | undefined>;
4
+ export interface WorkBuddyPdHookResult {
5
+ stdout: WorkBuddyHookOutput | null;
6
+ exitCode: number;
7
+ stderr: string[];
8
+ }
9
+ /** Evidence context the emitters need (subprocess-local, best-effort). */
10
+ export interface WorkbuddyEvidenceContext {
11
+ workspaceDir: string;
12
+ evidenceEnabled: boolean;
13
+ warn: (diagnosticLine: string) => void;
14
+ }
15
+ export declare function annotateContextWarnings(warnings: readonly string[]): string[];
16
+ export declare function processWorkbuddyHookInvocation(rawStdin: string, channelEventName: string | undefined, _env?: EnvMap): Promise<WorkBuddyPdHookResult>;
17
+ export {};