@unson/brainbase-mcp 0.50.18 → 0.50.19

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.
@@ -0,0 +1,20 @@
1
+ export interface JudgmentJournalTurnInput {
2
+ sessionId: string;
3
+ turnId: string;
4
+ projectCode: string;
5
+ trustedToken: string;
6
+ /** Identity verified by the Host JWT boundary, never client body fields. */
7
+ trustedPrincipal: {
8
+ personId: string;
9
+ tenantId: string;
10
+ };
11
+ }
12
+ export interface JudgmentJournalTurnPublisherOptions {
13
+ apiBaseUrl?: string;
14
+ journalRoot: string;
15
+ fetch?: typeof globalThis.fetch;
16
+ /** Receives only a fixed reason code, never exception details or journal data. */
17
+ onError?: (reason: string) => void;
18
+ }
19
+ /** HTTP-only, best-effort publication of the host's finished canonical journal. */
20
+ export declare function createJudgmentJournalTurnPublisher(options: JudgmentJournalTurnPublisherOptions): (input: JudgmentJournalTurnInput) => Promise<void>;
@@ -0,0 +1,112 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, readdir } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
5
+ const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
6
+ /** HTTP-only, best-effort publication of the host's finished canonical journal. */
7
+ export function createJudgmentJournalTurnPublisher(options) {
8
+ const report = (reason) => {
9
+ try {
10
+ (options.onError ?? console.warn)(reason);
11
+ }
12
+ catch { /* Diagnostics must fail open too. */ }
13
+ };
14
+ return async (input) => {
15
+ if (!options.apiBaseUrl || !options.journalRoot) {
16
+ report('judgment_journal_not_configured');
17
+ return;
18
+ }
19
+ if (!input.trustedToken) {
20
+ report('judgment_journal_token_missing');
21
+ return;
22
+ }
23
+ let body;
24
+ try {
25
+ const sessionRef = hash(input.sessionId);
26
+ const prefix = join(options.journalRoot, sessionRef, hash(input.turnId));
27
+ const read = async (path, optional = false) => {
28
+ let text;
29
+ try {
30
+ text = await readFile(path, 'utf8');
31
+ }
32
+ catch (error) {
33
+ if (optional && error.code === 'ENOENT')
34
+ return undefined;
35
+ throw error;
36
+ }
37
+ const value = JSON.parse(text);
38
+ if (!object(value))
39
+ throw new Error('invalid');
40
+ return value;
41
+ };
42
+ const episode = (await read(`${prefix}.episode.json`));
43
+ // Check ownership when supplied; current hosts rely on the receiving API receipt-owner binding.
44
+ if (!input.trustedPrincipal?.personId?.trim() || !input.trustedPrincipal.tenantId?.trim()
45
+ || ('owner_person_id' in episode && episode.owner_person_id !== input.trustedPrincipal.personId)
46
+ || ('tenant_id' in episode && episode.tenant_id !== input.trustedPrincipal.tenantId))
47
+ throw new Error('invalid');
48
+ const final = (await read(`${prefix}.final.json`));
49
+ const receipt = episode.initial_route_receipt;
50
+ if (!object(receipt) || typeof receipt.resolution_id !== 'string' || !receipt.resolution_id
51
+ || receipt.project_code !== input.projectCode
52
+ || (receipt.turn_id !== undefined && receipt.turn_id !== input.turnId)
53
+ || (episode.turn_id !== undefined && episode.turn_id !== input.turnId)
54
+ || (episode.session_ref !== undefined && episode.session_ref !== sessionRef)
55
+ || (final.turn_id !== undefined && final.turn_id !== input.turnId)
56
+ || (final.session_ref !== undefined && final.session_ref !== sessionRef)
57
+ || typeof final.finalized_at !== 'string'
58
+ || !Number.isFinite(Date.parse(final.finalized_at)))
59
+ throw new Error('invalid');
60
+ let names;
61
+ try {
62
+ names = await readdir(`${prefix}.events`);
63
+ }
64
+ catch (error) {
65
+ if (error.code !== 'ENOENT')
66
+ throw error;
67
+ names = []; // Hosts need not create a directory for a zero-tool turn.
68
+ }
69
+ const rawEvents = await Promise.all(names.filter(name => name.endsWith('.json'))
70
+ .map(async (name) => (await read(join(`${prefix}.events`, name)))));
71
+ const sequence = (event) => typeof event.event_sequence === 'number' ? event.event_sequence : Number(event.sequence) - 1;
72
+ rawEvents.sort((a, b) => sequence(a) - sequence(b));
73
+ const events = rawEvents.map((event, index) => {
74
+ if (sequence(event) !== index || index >= 4096
75
+ || typeof event.event_fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(event.event_fingerprint)
76
+ || typeof event.tool_use_id !== 'string' || !event.tool_use_id.trim())
77
+ throw new Error('invalid');
78
+ return { event_sequence: index, event_fingerprint: event.event_fingerprint,
79
+ tool_use_id: event.tool_use_id, event };
80
+ });
81
+ if (final.event_count !== events.length)
82
+ throw new Error('invalid');
83
+ const turnInput = await read(`${prefix}.turn-input.json`, true);
84
+ const valueProof = await read(`${prefix}.value-proof.json`, true);
85
+ body = {
86
+ resolution_id: receipt.resolution_id, turn_id: input.turnId, project_code: input.projectCode,
87
+ turn_ref: `${sessionRef}/${hash(input.turnId)}`, entrypoint: 'claude_code',
88
+ receipt, episode, final, events,
89
+ ...(turnInput ? { turn_input: turnInput } : {}),
90
+ ...(valueProof ? { value_proof: valueProof } : {}), recorded_at: final.finalized_at,
91
+ };
92
+ }
93
+ catch (error) {
94
+ report(error.code === 'ENOENT'
95
+ ? 'judgment_journal_files_missing' : 'judgment_journal_files_invalid');
96
+ return;
97
+ }
98
+ try {
99
+ const response = await (options.fetch ?? globalThis.fetch)(`${options.apiBaseUrl.replace(/\/$/, '')}/api/organization/judgment-journal/turns`, {
100
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(1000),
101
+ headers: { Authorization: `Bearer ${input.trustedToken}`, 'Content-Type': 'application/json' },
102
+ body: JSON.stringify(body),
103
+ });
104
+ if (response.status !== 200 && response.status !== 201) {
105
+ report(response.status === 409 ? 'judgment_journal_conflict' : 'judgment_journal_http_failed');
106
+ }
107
+ }
108
+ catch {
109
+ report('judgment_journal_network_failed');
110
+ }
111
+ };
112
+ }
@@ -0,0 +1,82 @@
1
+ import type { JudgmentJournalTurnInput } from './judgment-journal-turn-publisher.js';
2
+ /** Minimal identity verified by the consuming host's authentication boundary. */
3
+ export interface RemoteJudgmentHookPrincipal {
4
+ personId: string;
5
+ organizationId: string;
6
+ tenantId?: string;
7
+ projectCodes: string[];
8
+ }
9
+ export declare const REMOTE_JUDGMENT_HOOK_PATH = "/host/judgment/hook";
10
+ export declare const REMOTE_JUDGMENT_HOOK_MAX_BODY_BYTES: number;
11
+ export interface RemoteJudgmentHookDispatchResult {
12
+ output: Record<string, unknown>;
13
+ receiptId?: string;
14
+ routeResolutionSha256?: string;
15
+ }
16
+ /**
17
+ * `remote`: a remote runtime. `claude-code`: Claude Code on
18
+ * the owner's loopback bridge or authenticated with a person's hosted JWT.
19
+ */
20
+ export type RemoteJudgmentHookHost = 'remote' | 'claude-code';
21
+ /**
22
+ * Authentication context verified by the Host before it reaches the hook
23
+ * dispatcher. A shared bearer intentionally has no trusted principal or
24
+ * auth kind and therefore is not represented here.
25
+ */
26
+ export type RemoteJudgmentHookAuthKind = 'brainbase-jwt' | 'company-authority';
27
+ /** Derive flags from verified authentication and the host's owner-loopback check. */
28
+ export declare function remoteJudgmentHookHostFlags(authKind: RemoteJudgmentHookAuthKind | 'shared-bearer', isOwnerLocalBridge: boolean): {
29
+ personHostedClaudeCodeAllowed: boolean;
30
+ localClaudeCodeAllowed: boolean;
31
+ };
32
+ export interface RemoteJudgmentHookDispatchOptions {
33
+ host: RemoteJudgmentHookHost;
34
+ /** Principal verified by the Host authentication boundary, when available. */
35
+ trustedPrincipal?: RemoteJudgmentHookPrincipal;
36
+ /** The verified caller token, kept inside the dispatch boundary for canonical readback. */
37
+ trustedToken?: string;
38
+ /** Authentication kind verified by the Host authentication boundary. */
39
+ trustedAuthKind?: RemoteJudgmentHookAuthKind;
40
+ /** Raw encoded Company Authority response verified by the canonical API. */
41
+ companyAuthorityResponse?: string;
42
+ }
43
+ export type RemoteJudgmentHookDispatch = (payload: Record<string, unknown>, projectCode: string | undefined, options: RemoteJudgmentHookDispatchOptions) => Promise<RemoteJudgmentHookDispatchResult>;
44
+ export interface RemoteJudgmentHookRequest {
45
+ method?: string;
46
+ url?: string;
47
+ authorization?: string;
48
+ body: Buffer;
49
+ bearerToken: string;
50
+ projectCode?: string;
51
+ /** Principal verified by the Host authentication boundary, never by request body fields. */
52
+ trustedPrincipal?: RemoteJudgmentHookPrincipal;
53
+ /** Verified caller token; never included in the response or diagnostic payload. */
54
+ trustedToken?: string;
55
+ /** Authentication kind verified by the Host authentication boundary. */
56
+ trustedAuthKind?: RemoteJudgmentHookAuthKind;
57
+ /** Raw encoded Company Authority response verified by the canonical API. */
58
+ companyAuthorityResponse?: string;
59
+ /** The x-brainbase-judgment-host header, when the caller declared one. */
60
+ declaredHost?: string;
61
+ /** True only on the owner's loopback bridge for a shared-bearer request. */
62
+ localClaudeCodeAllowed?: boolean;
63
+ /** True only for a person authenticated by the hosted MCP's JWT boundary. */
64
+ personHostedClaudeCodeAllowed?: boolean;
65
+ isAuthorized: (authorization: string | undefined, expectedToken: string) => boolean;
66
+ dispatch: RemoteJudgmentHookDispatch;
67
+ /** Optional HTTP publisher for person-authenticated hosted Claude Code Stop events. */
68
+ journalTurnPublisher?: (input: JudgmentJournalTurnInput) => Promise<void>;
69
+ onDispatchError?: (details: {
70
+ eventName: string;
71
+ reason: string;
72
+ errorName: string;
73
+ errorCode?: string;
74
+ causeReasonCode?: string;
75
+ }) => void;
76
+ }
77
+ export interface RemoteJudgmentHookResponse {
78
+ status: number;
79
+ headers?: Record<string, string>;
80
+ body: Record<string, unknown>;
81
+ }
82
+ export declare function handleRemoteJudgmentHookRequest(request: RemoteJudgmentHookRequest): Promise<RemoteJudgmentHookResponse | null>;
@@ -0,0 +1,207 @@
1
+ export const REMOTE_JUDGMENT_HOOK_PATH = '/host/judgment/hook';
2
+ export const REMOTE_JUDGMENT_HOOK_MAX_BODY_BYTES = 1024 * 1024;
3
+ /** Derive flags from verified authentication and the host's owner-loopback check. */
4
+ export function remoteJudgmentHookHostFlags(authKind, isOwnerLocalBridge) {
5
+ return {
6
+ personHostedClaudeCodeAllowed: authKind === 'brainbase-jwt',
7
+ localClaudeCodeAllowed: authKind === 'shared-bearer' && isOwnerLocalBridge === true,
8
+ };
9
+ }
10
+ const PROJECT_CODE_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
11
+ const SUPPORTED_HOOK_EVENTS = new Set(['UserPromptSubmit', 'PostToolUse', 'PostToolUseFailure', 'Stop']);
12
+ // The owner's Claude Code also sends a knowledge lookup's PreToolUse, so the
13
+ // Host can reserve the attempt it later records. A remote runtime keeps the
14
+ // events above.
15
+ const CLAUDE_CODE_HOOK_EVENTS = new Set([...SUPPORTED_HOOK_EVENTS, 'PreToolUse']);
16
+ const SAFE_REASON_CODE = /^[a-z][a-z0-9_]{1,80}$/;
17
+ const FORBIDDEN_SCOPE_REASON_CODES = new Set([
18
+ 'judgment_history_scope_mismatch',
19
+ 'judgment_history_project_denied',
20
+ 'judgment_history_shared_bearer_denied',
21
+ // Current scope binder wording; retain the explicit deny classification if
22
+ // the binder has not yet adopted the shorter reason code above.
23
+ 'judgment_history_scope_shared_bearer_rejected',
24
+ ]);
25
+ function isInternalJudgmentControlTool(payload) {
26
+ const toolName = payload.tool_name ?? payload.toolName;
27
+ return typeof toolName === 'string'
28
+ && ['mcp__brainbase__brainbase_judgment_state_record',
29
+ 'mcp__brainbase__brainbase_judgment_audit_read',
30
+ 'mcp__brainbase__brainbase_judgment_repair_read'].includes(toolName);
31
+ }
32
+ function safeCauseReasonCode(error) {
33
+ let current = typeof error === 'object' && error && 'cause' in error ? error.cause : undefined;
34
+ const visited = new Set();
35
+ for (let depth = 0; depth < 6 && current && !visited.has(current); depth += 1) {
36
+ visited.add(current);
37
+ if (current instanceof Error && SAFE_REASON_CODE.test(current.message))
38
+ return current.message;
39
+ current = typeof current === 'object' && 'cause' in current ? current.cause : undefined;
40
+ }
41
+ return undefined;
42
+ }
43
+ export async function handleRemoteJudgmentHookRequest(request) {
44
+ if (request.method !== 'POST' || request.url !== REMOTE_JUDGMENT_HOOK_PATH)
45
+ return null;
46
+ if (!request.isAuthorized(request.authorization, request.bearerToken)) {
47
+ return {
48
+ status: 401,
49
+ headers: { 'WWW-Authenticate': 'Bearer' },
50
+ body: { error: 'unauthorized' },
51
+ };
52
+ }
53
+ if (request.body.length > REMOTE_JUDGMENT_HOOK_MAX_BODY_BYTES) {
54
+ return { status: 413, body: { error: 'judgment_hook_payload_too_large' } };
55
+ }
56
+ let payload;
57
+ try {
58
+ payload = JSON.parse(request.body.toString('utf8'));
59
+ }
60
+ catch {
61
+ return { status: 400, body: { error: 'invalid_json' } };
62
+ }
63
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
64
+ return { status: 400, body: { error: 'invalid_hook_payload' } };
65
+ }
66
+ const hookPayload = payload;
67
+ const eventName = hookPayload.hook_event_name ?? hookPayload.hookEventName;
68
+ if (typeof eventName !== 'string' || !CLAUDE_CODE_HOOK_EVENTS.has(eventName)) {
69
+ return { status: 400, body: { error: 'unsupported_hook_event' } };
70
+ }
71
+ const personHostedClaudeCode = request.personHostedClaudeCodeAllowed === true
72
+ && request.trustedAuthKind === 'brainbase-jwt';
73
+ const host = request.declaredHost === undefined || request.declaredHost === ''
74
+ ? 'remote' : 'claude-code';
75
+ if (host === 'claude-code'
76
+ && (request.declaredHost !== 'claude-code' || (request.localClaudeCodeAllowed !== true && !personHostedClaudeCode))) {
77
+ return { status: 400, body: { error: 'judgment_hook_host_unsupported' } };
78
+ }
79
+ if (host === 'remote' && !SUPPORTED_HOOK_EVENTS.has(eventName)) {
80
+ return { status: 400, body: { error: 'unsupported_hook_event' } };
81
+ }
82
+ // A local Claude Code turn may leave the project to the Host, which derives
83
+ // it from the turn's cwd exactly as for Codex.
84
+ const requiresProjectScope = host === 'remote' || (host === 'claude-code' && personHostedClaudeCode);
85
+ if (host === 'claude-code' && personHostedClaudeCode
86
+ && !request.trustedPrincipal?.tenantId?.trim()) {
87
+ return { status: 403, body: { error: 'authenticated_history_principal_unavailable' } };
88
+ }
89
+ if ((requiresProjectScope || request.projectCode !== undefined)
90
+ && (!request.projectCode || !PROJECT_CODE_PATTERN.test(request.projectCode))) {
91
+ return { status: 400, body: { error: 'invalid_project_code' } };
92
+ }
93
+ if (requiresProjectScope && request.trustedPrincipal
94
+ && (!request.projectCode || !request.trustedPrincipal.projectCodes.includes(request.projectCode))) {
95
+ return { status: 403, body: { error: 'project_not_authorized' } };
96
+ }
97
+ if (request.trustedPrincipal && !request.trustedPrincipal.tenantId?.trim()) {
98
+ return { status: 403, body: { error: 'authenticated_history_principal_unavailable' } };
99
+ }
100
+ const sessionId = hookPayload.session_id;
101
+ const turnId = hookPayload.turn_id;
102
+ if (typeof sessionId !== 'string' || !sessionId || typeof turnId !== 'string' || !turnId) {
103
+ return { status: 400, body: { error: 'invalid_hook_identity' } };
104
+ }
105
+ try {
106
+ const dispatchOptions = request.trustedPrincipal
107
+ ? {
108
+ host,
109
+ trustedPrincipal: request.trustedPrincipal,
110
+ ...(request.trustedToken ? { trustedToken: request.trustedToken } : {}),
111
+ ...(request.trustedAuthKind ? { trustedAuthKind: request.trustedAuthKind } : {}),
112
+ ...(request.companyAuthorityResponse
113
+ ? { companyAuthorityResponse: request.companyAuthorityResponse }
114
+ : {}),
115
+ }
116
+ : { host };
117
+ const dispatchResult = await request.dispatch(hookPayload, request.projectCode, dispatchOptions);
118
+ const { output } = dispatchResult;
119
+ if (!output || typeof output !== 'object' || Array.isArray(output)) {
120
+ return { status: 503, body: { error: 'judgment_hook_output_invalid' } };
121
+ }
122
+ // The remote runtime's stream validator needs an audit line per tool. A
123
+ // local Claude Code turn has no such validator; the Host decides alone.
124
+ if (host === 'remote' && (eventName === 'PostToolUse' || eventName === 'PostToolUseFailure')
125
+ && !isInternalJudgmentControlTool(hookPayload)
126
+ && (typeof output.systemMessage !== 'string' || !output.systemMessage.trim())) {
127
+ return { status: 503, body: { error: 'judgment_hook_audit_not_recorded' } };
128
+ }
129
+ if (eventName === 'UserPromptSubmit'
130
+ && (typeof dispatchResult.receiptId !== 'string' || !dispatchResult.receiptId.trim()
131
+ || typeof dispatchResult.routeResolutionSha256 !== 'string'
132
+ || !/^[a-f0-9]{64}$/.test(dispatchResult.routeResolutionSha256))) {
133
+ return { status: 503, body: { error: 'judgment_hook_route_receipt_missing' } };
134
+ }
135
+ if (eventName === 'Stop' && host === 'claude-code' && personHostedClaudeCode
136
+ && request.localClaudeCodeAllowed !== true) {
137
+ const report = (reason) => {
138
+ try {
139
+ console.warn(reason);
140
+ }
141
+ catch { /* Logging cannot affect the hook response. */ }
142
+ };
143
+ if (!request.journalTurnPublisher)
144
+ report('judgment_journal_not_configured');
145
+ else if (!request.trustedToken)
146
+ report('judgment_journal_token_missing');
147
+ else {
148
+ let timer;
149
+ try {
150
+ await Promise.race([
151
+ Promise.resolve().then(() => request.journalTurnPublisher({
152
+ sessionId, turnId, projectCode: request.projectCode, trustedToken: request.trustedToken,
153
+ trustedPrincipal: { personId: request.trustedPrincipal.personId, tenantId: request.trustedPrincipal.tenantId },
154
+ })),
155
+ new Promise((_resolve, reject) => {
156
+ timer = setTimeout(() => reject(new Error()), 1500);
157
+ }),
158
+ ]);
159
+ }
160
+ catch {
161
+ report('judgment_journal_publish_failed');
162
+ }
163
+ finally {
164
+ if (timer)
165
+ clearTimeout(timer);
166
+ }
167
+ }
168
+ }
169
+ const hasRouteReceipt = typeof dispatchResult.receiptId === 'string'
170
+ && dispatchResult.receiptId.trim().length > 0
171
+ && typeof dispatchResult.routeResolutionSha256 === 'string'
172
+ && /^[a-f0-9]{64}$/.test(dispatchResult.routeResolutionSha256);
173
+ return {
174
+ status: 200,
175
+ body: {
176
+ schema_version: '1', accepted: true,
177
+ hook_event_name: eventName, session_id: sessionId, turn_id: turnId,
178
+ ...((eventName === 'UserPromptSubmit' || eventName === 'Stop') && hasRouteReceipt ? {
179
+ receipt_id: dispatchResult.receiptId,
180
+ route_resolution_sha256: dispatchResult.routeResolutionSha256,
181
+ } : {}),
182
+ output,
183
+ },
184
+ };
185
+ }
186
+ catch (error) {
187
+ const reason = error instanceof Error
188
+ && /^judgment_[a-z0-9_]{1,80}$/.test(error.message)
189
+ ? error.message
190
+ : 'judgment_hook_unavailable';
191
+ const errorCode = error && typeof error === 'object'
192
+ && 'code' in error && typeof error.code === 'string'
193
+ && /^[A-Z0-9_]{1,80}$/.test(error.code)
194
+ ? error.code
195
+ : undefined;
196
+ const causeReasonCode = safeCauseReasonCode(error);
197
+ request.onDispatchError?.({
198
+ eventName,
199
+ reason,
200
+ errorName: error instanceof Error ? error.name : 'UnknownError',
201
+ ...(errorCode ? { errorCode } : {}),
202
+ ...(causeReasonCode && causeReasonCode !== reason ? { causeReasonCode } : {}),
203
+ });
204
+ const status = FORBIDDEN_SCOPE_REASON_CODES.has(reason) ? 403 : 503;
205
+ return { status, body: { error: reason } };
206
+ }
207
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unson/brainbase-mcp",
3
- "version": "0.50.18",
3
+ "version": "0.50.19",
4
4
  "description": "Local-first Brainbase judgment OS that lets supported AI agents reuse a user's approved goals, priorities, decisions, and judgment criteria.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,6 +43,14 @@
43
43
  "types": "./dist/judgment-history.d.ts",
44
44
  "import": "./dist/judgment-history.js"
45
45
  },
46
+ "./judgment-journal-turn-publisher": {
47
+ "types": "./dist/judgment-journal-turn-publisher.d.ts",
48
+ "import": "./dist/judgment-journal-turn-publisher.js"
49
+ },
50
+ "./remote-judgment-hook-http": {
51
+ "types": "./dist/remote-judgment-hook-http.d.ts",
52
+ "import": "./dist/remote-judgment-hook-http.js"
53
+ },
46
54
  "./judgment-history-http": {
47
55
  "types": "./dist/judgment-history-http.d.ts",
48
56
  "import": "./dist/judgment-history-http.js"
@@ -649,5 +657,5 @@
649
657
  "url": "https://github.com/Unson-LLC/brainbase/issues"
650
658
  },
651
659
  "homepage": "https://github.com/Unson-LLC/brainbase#readme",
652
- "gitHead": "c7217bea64aaf3562280a8ec55ce6e6ca590b4a9"
660
+ "gitHead": "bf9c68fa85fbb56c74133fab383bd39248fdae92"
653
661
  }