@unson/brainbase-mcp 0.50.23 → 0.50.25

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,1003 @@
1
+ // Claude Code adapter for a hosted Brainbase judgment Host.
2
+ //
3
+ // Claude Code runs this as a command hook (`brainbase judgment:claude-code-hook`)
4
+ // for UserPromptSubmit, PreToolUse, PostToolUse, PostToolUseFailure and Stop.
5
+ // Claude Code's hook input has no turn_id, so the adapter keeps one per prompt.
6
+ // It forwards each event to the hosted MCP's `/host/judgment/hook` with the
7
+ // person token from `brainbase login`, and returns only a notice for the person
8
+ // and context for the model (and, for a knowledge lookup, the Host's denial).
9
+ //
10
+ // The hook is fail-open: the judgment plane audits, it does not authorize.
11
+ // Nothing here exits 2 or blocks a Stop, on its own error or on the Host's
12
+ // request. A failure becomes a warning for the person and the turn goes on.
13
+ //
14
+ // The person does not export variables. `judgment:install --target claude-code`
15
+ // writes the origin, and optionally the project and audited repositories, to
16
+ // the hook config file. When no project is configured, the Host chooses it
17
+ // from the repository this adapter sends (host/owner/name of the origin
18
+ // remote), or from the person's only project.
19
+ import { spawnSync } from 'node:child_process';
20
+ import { createHash, randomUUID } from 'node:crypto';
21
+ import { mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
22
+ import { homedir } from 'node:os';
23
+ import { dirname, join, resolve } from 'node:path';
24
+ import { getAccessTokenOfLogin } from './brainbase-login.js';
25
+ export const CLAUDE_CODE_HOOK_CONFIG_SCHEMA = 'brainbase-claude-code-judgment-hook-v1';
26
+ const HOOK_PATH = '/host/judgment/hook';
27
+ const RECENT_PROMPTS = 16;
28
+ const TIMEOUT_MS = {
29
+ UserPromptSubmit: 40_000, Stop: 40_000, PreToolUse: 15_000, PostToolUse: 15_000, PostToolUseFailure: 15_000,
30
+ };
31
+ // The Host reserves and checks a knowledge lookup attempt before it runs and
32
+ // records it only against that reservation. No other tool waits on the Host.
33
+ export const PRE_TOOL_USE_TOOLS = new Set(['mcp__brainbase__brainbase_knowledge_lookup']);
34
+ const WARNING_PREFIX = '⚠️ Brainbase判断フック:';
35
+ const TURN_SCHEMA = 'brainbase-claude-judgment-turn-v1';
36
+ function warning(text) {
37
+ return { systemMessage: `${WARNING_PREFIX} ${text}` };
38
+ }
39
+ function brainbaseHome(env) {
40
+ return join(env.HOME || homedir(), '.brainbase');
41
+ }
42
+ export function defaultClaudeCodeHookConfigPath(env = process.env) {
43
+ return env.BRAINBASE_CLAUDE_JUDGMENT_HOOK_CONFIG?.trim() || join(brainbaseHome(env), 'claude-code-judgment-hook.json');
44
+ }
45
+ export function readClaudeCodeHookConfig(path) {
46
+ let text;
47
+ try {
48
+ text = readFileSync(path, 'utf8');
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ return parseClaudeCodeHookConfig(text);
54
+ }
55
+ /** The hook config held in `text` (a file already read), or null when it is not a usable one. */
56
+ export function parseClaudeCodeHookConfig(text) {
57
+ let parsed;
58
+ try {
59
+ parsed = JSON.parse(text);
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ const value = parsed;
65
+ if (!value || value.schema_version !== CLAUDE_CODE_HOOK_CONFIG_SCHEMA || typeof value.origin !== 'string')
66
+ return null;
67
+ // Without the login it belongs to, no saved token may be sent.
68
+ if (typeof value.login_server !== 'string' || !value.login_server)
69
+ return null;
70
+ let repositories;
71
+ if (value.repositories !== undefined) {
72
+ // A list that cannot be read must not widen into "audit everything".
73
+ if (!Array.isArray(value.repositories))
74
+ return null;
75
+ repositories = [];
76
+ for (const entry of value.repositories) {
77
+ // Already an identifier: read as is, so a name ending in `.git` stays whole.
78
+ const normalized = typeof entry === 'string' ? canonicalRepositoryIdentifier(entry) : null;
79
+ if (!normalized)
80
+ return null;
81
+ repositories.push(normalized);
82
+ }
83
+ }
84
+ const registration = value.registration;
85
+ if (!registration || typeof registration.id !== 'string' || !REGISTRATION_ID.test(registration.id)
86
+ || typeof registration.settings !== 'string' || !registration.settings)
87
+ return null;
88
+ return {
89
+ schema_version: CLAUDE_CODE_HOOK_CONFIG_SCHEMA,
90
+ origin: value.origin,
91
+ login_server: value.login_server,
92
+ registration: { id: registration.id, settings: registration.settings },
93
+ ...(typeof value.project_code === 'string' && value.project_code ? { project_code: value.project_code } : {}),
94
+ // An empty list stays empty: it audits no repository, it never means all.
95
+ ...(repositories ? { repositories } : {}),
96
+ };
97
+ }
98
+ /** True when the file holds JSON with this hook config's schema (it was written by the installer). */
99
+ export function isClaudeCodeHookConfigFile(path) {
100
+ try {
101
+ return isClaudeCodeHookConfigText(readFileSync(path, 'utf8'));
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ }
107
+ /** True when `text` (a file already read) is JSON with this hook config's schema. */
108
+ export function isClaudeCodeHookConfigText(text) {
109
+ try {
110
+ const parsed = JSON.parse(text);
111
+ return !!parsed && typeof parsed === 'object' && !Array.isArray(parsed)
112
+ && parsed.schema_version === CLAUDE_CODE_HOOK_CONFIG_SCHEMA;
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ }
118
+ export const REGISTRATION_ID = /^[a-f0-9]{32}$/u;
119
+ const REPOSITORY_HOST = /^[a-z0-9][a-z0-9.-]*(?::[0-9]+)?$/u;
120
+ const REPOSITORY_PATH = /^[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)+$/u;
121
+ /**
122
+ * Hosts whose repository paths ignore case: there, `Owner/App` and `owner/app`
123
+ * are one repository. Elsewhere (a self-hosted server may tell them apart),
124
+ * the path is compared exactly.
125
+ */
126
+ const CASE_INSENSITIVE_PATH_HOSTS = new Set(['github.com']);
127
+ /**
128
+ * A repository named in the config: `host/owner/name`. The host is
129
+ * lowercased (host names ignore case). The path keeps its case, except on a
130
+ * host whose paths ignore case. A bare name or `owner/name` is refused,
131
+ * because it would also match a repository of the same name under another
132
+ * owner or host.
133
+ */
134
+ export function normalizeRepositoryEntry(entry) {
135
+ // As in a remote URL, one trailing `.git` is the URL's, not the name's.
136
+ return canonicalRepositoryIdentifier(entry.trim().replace(/\/+$/u, '').replace(/\.git$/iu, ''));
137
+ }
138
+ /**
139
+ * A `host/owner/name` identifier in its one spelling: the host lowercased,
140
+ * the path lowercased only on a host whose paths ignore case. Nothing is
141
+ * stripped, so an identifier read back from the config stays the same.
142
+ */
143
+ export function canonicalRepositoryIdentifier(entry) {
144
+ const value = entry.trim().replace(/\/+$/u, '');
145
+ const slash = value.indexOf('/');
146
+ if (slash <= 0)
147
+ return null;
148
+ const host = value.slice(0, slash).toLowerCase();
149
+ const rawPath = value.slice(slash + 1);
150
+ if (!REPOSITORY_HOST.test(host) || !REPOSITORY_PATH.test(rawPath))
151
+ return null;
152
+ const path = CASE_INSENSITIVE_PATH_HOSTS.has(host) ? rawPath.toLowerCase() : rawPath;
153
+ return `${host}/${path}`;
154
+ }
155
+ // ---- Repository identity, read from git files without starting git ----
156
+ function isGitMetadata(dotGit) {
157
+ try {
158
+ if (statSync(dotGit).isDirectory())
159
+ return statSync(join(dotGit, 'HEAD')).isFile();
160
+ return /^gitdir:\s*\S/u.test(readFileSync(dotGit, 'utf8'));
161
+ }
162
+ catch {
163
+ return false;
164
+ }
165
+ }
166
+ /**
167
+ * The nearest directory at or above `start` with valid git metadata. The walk
168
+ * starts from the real path: a link inside one checkout that points into
169
+ * another checkout belongs to the checkout it points into, not to the one
170
+ * whose directory holds the link. A start that cannot be resolved gives null,
171
+ * so nothing is sent for it.
172
+ */
173
+ export function findGitRoot(start) {
174
+ let current;
175
+ try {
176
+ current = realpathSync(resolve(start));
177
+ }
178
+ catch {
179
+ return null;
180
+ }
181
+ for (;;) {
182
+ if (isGitMetadata(join(current, '.git')))
183
+ return current;
184
+ const parent = dirname(current);
185
+ if (parent === current)
186
+ return null;
187
+ current = parent;
188
+ }
189
+ }
190
+ /** The git directory a linked worktree shares with its main checkout. */
191
+ export function gitCommonDir(repoRoot) {
192
+ const dotGit = join(repoRoot, '.git');
193
+ try {
194
+ if (statSync(dotGit).isDirectory())
195
+ return dotGit;
196
+ const match = /^gitdir:\s*(.+?)\s*$/mu.exec(readFileSync(dotGit, 'utf8'));
197
+ if (!match)
198
+ return null;
199
+ const gitDir = resolve(repoRoot, match[1]);
200
+ try {
201
+ return resolve(gitDir, readFileSync(join(gitDir, 'commondir'), 'utf8').trim());
202
+ }
203
+ catch {
204
+ return gitDir;
205
+ }
206
+ }
207
+ catch {
208
+ return null;
209
+ }
210
+ }
211
+ // Variables that would point git at another repository than the checkout.
212
+ const GIT_LOCATION_VARIABLES = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE'];
213
+ /**
214
+ * The URL git itself uses for the `origin` remote, asked from git: includes,
215
+ * `insteadOf` rewrites and the global and system config apply as for a fetch.
216
+ * `none` when the checkout has no origin remote; `unresolved` when git could
217
+ * not answer (not installed, refused the checkout, timed out), so nothing can
218
+ * be said about the repository.
219
+ */
220
+ function originLookup(repoRoot, env) {
221
+ const childEnv = { ...env, PATH: env.PATH ?? process.env.PATH, GIT_TERMINAL_PROMPT: '0' };
222
+ for (const name of GIT_LOCATION_VARIABLES)
223
+ delete childEnv[name];
224
+ const result = spawnSync('git', ['-C', repoRoot, 'remote', 'get-url', 'origin'], {
225
+ env: childEnv, encoding: 'utf8', timeout: 5_000, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
226
+ });
227
+ if (result.error || result.status === null)
228
+ return { status: 'unresolved' };
229
+ const url = result.stdout.trim();
230
+ if (result.status === 0 && url && !url.includes('\n'))
231
+ return { status: 'found', url };
232
+ // `git remote get-url` exits with 2 for a remote that does not exist.
233
+ if (result.status === 2 && /No such remote/iu.test(result.stderr))
234
+ return { status: 'none' };
235
+ return { status: 'unresolved' };
236
+ }
237
+ /**
238
+ * `host/owner/name` of a git remote URL (normalized as in the config), or null when the URL has
239
+ * no host or no owner. Accepts https/ssh/git URLs and scp-like `user@host:path`.
240
+ */
241
+ export function repositoryIdentityFromUrl(remote) {
242
+ const value = remote.trim();
243
+ let host;
244
+ let path;
245
+ const scp = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/\/)(.+)$/u.exec(value);
246
+ if (scp && !/^[a-z][a-z0-9+.-]*:\/\//iu.test(value)) {
247
+ [, host, path] = scp;
248
+ // `host:/srv/a/b` names a path from the server's root, `host:a/b` one
249
+ // below the login's home: on a self-hosted SSH server they can be two
250
+ // repositories. Without the leading slash they would read as the same
251
+ // `host/a/b`, so an absolute scp-like path names no repository; without
252
+ // --project nothing is sent for it (see isAuditedRepository).
253
+ if (path.startsWith('/'))
254
+ return null;
255
+ }
256
+ else {
257
+ let url;
258
+ try {
259
+ url = new URL(value);
260
+ }
261
+ catch {
262
+ return null;
263
+ }
264
+ if (!url.hostname)
265
+ return null;
266
+ host = url.port ? `${url.hostname}:${url.port}` : url.hostname;
267
+ path = decodeURIComponent(url.pathname);
268
+ }
269
+ return normalizeRepositoryEntry(`${host}/${path.replace(/^\/+/u, '')}`);
270
+ }
271
+ /**
272
+ * The repository a checkout works for: `host/owner/name` of its origin
273
+ * remote, the same for every worktree of one repository. Null without an
274
+ * origin remote whose URL names a host and an owner.
275
+ */
276
+ export function repositoryIdentity(repoRoot, env = process.env) {
277
+ const origin = originLookup(repoRoot, env);
278
+ return origin.status === 'found' ? repositoryIdentityFromUrl(origin.url) : null;
279
+ }
280
+ function eventRepository(payload, env) {
281
+ const cwd = typeof payload.cwd === 'string' && payload.cwd ? payload.cwd : process.cwd();
282
+ const root = findGitRoot(cwd);
283
+ if (!root)
284
+ return { inGit: false, repository: null, checkout: null };
285
+ const commonDir = gitCommonDir(root);
286
+ let checkout = null;
287
+ try {
288
+ checkout = commonDir ? realpathSync(commonDir) : null;
289
+ }
290
+ catch {
291
+ checkout = null;
292
+ }
293
+ const origin = originLookup(root, env);
294
+ if (origin.status === 'unresolved')
295
+ return { inGit: true, repository: null, checkout, unresolved: true };
296
+ if (origin.status === 'none')
297
+ return { inGit: true, repository: null, checkout };
298
+ const repository = repositoryIdentityFromUrl(origin.url);
299
+ return repository === null
300
+ ? { inGit: true, repository: null, checkout, unidentified: true }
301
+ : { inGit: true, repository, checkout };
302
+ }
303
+ function isAuditedRepository(scope, config) {
304
+ if (!scope.inGit || scope.unresolved)
305
+ return false;
306
+ // Sent without a repository, the Host would put the records in the
307
+ // person's only project, which need not be the one this origin works for.
308
+ if (scope.unidentified && !config.project_code)
309
+ return false;
310
+ if (!config.repositories)
311
+ return true;
312
+ return scope.repository !== null && config.repositories.includes(scope.repository);
313
+ }
314
+ // A later event belongs to the turn only when it runs in the repository the
315
+ // turn was opened in: the same host/owner/name, or, for a repository without
316
+ // one, the same checkout. Outside git nothing belongs to a turn. The turn's
317
+ // repository, not the event's, is sent.
318
+ function sameScope(state, scope) {
319
+ if (!scope.inGit)
320
+ return false;
321
+ if (typeof state.repository === 'string')
322
+ return state.repository === scope.repository;
323
+ return scope.repository === null && typeof state.checkout === 'string' && state.checkout === scope.checkout;
324
+ }
325
+ // Where events go: the config file, the Host origin and the project. A turn
326
+ // keeps the destination it was opened with.
327
+ function destinationOf(context) {
328
+ return JSON.stringify([context.configPath, context.config.origin, context.config.project_code ?? null]);
329
+ }
330
+ function sameDestination(state, context) {
331
+ return state.destination === destinationOf(context);
332
+ }
333
+ // ---- Turn state ----
334
+ function turnDirectory(env) {
335
+ return env.BRAINBASE_CLAUDE_JUDGMENT_TURN_DIR || join(brainbaseHome(env), 'var', 'claude-judgment-turns');
336
+ }
337
+ function sha256(text) {
338
+ return createHash('sha256').update(text).digest('hex');
339
+ }
340
+ // Turns are kept per session and per hook config, so two registered configs
341
+ // (two Hosts) never share a turn.
342
+ function stateKey(sessionId, configPath) {
343
+ return sha256(`${sessionId}\n${configPath}`);
344
+ }
345
+ function turnKey(payload, context) {
346
+ return stateKey(String(payload.session_id), context.configPath);
347
+ }
348
+ function statePath(env, key) {
349
+ return join(turnDirectory(env), `${key}.json`);
350
+ }
351
+ // Present while an input Claude Code screened during this prompt's turn may
352
+ // still run as a turn of its own (see unannouncedTurn).
353
+ function screeningPath(env, sessionId, promptId) {
354
+ return join(turnDirectory(env), `${sessionId}.screened-${sha256(promptId).slice(0, 32)}`);
355
+ }
356
+ function noteScreening(env, sessionId, promptId) {
357
+ try {
358
+ mkdirSync(turnDirectory(env), { recursive: true, mode: 0o700 });
359
+ writeFileSync(screeningPath(env, sessionId, promptId), '', { mode: 0o600 });
360
+ }
361
+ catch { }
362
+ }
363
+ function forgetScreening(env, sessionId, promptId) {
364
+ try {
365
+ unlinkSync(screeningPath(env, sessionId, promptId));
366
+ }
367
+ catch { }
368
+ }
369
+ function recentPrompts(previous) {
370
+ const earlier = Array.isArray(previous?.recent_prompt_ids)
371
+ ? previous.recent_prompt_ids.filter((id) => typeof id === 'string' && id !== previous.prompt_id) : [];
372
+ return (typeof previous?.prompt_id === 'string' ? [...earlier, previous.prompt_id] : earlier).slice(-RECENT_PROMPTS);
373
+ }
374
+ function readState(env, sessionId) {
375
+ try {
376
+ const state = JSON.parse(readFileSync(statePath(env, sessionId), 'utf8'));
377
+ return state && typeof state.turn_id === 'string' && state.turn_id ? state : null;
378
+ }
379
+ catch {
380
+ return null;
381
+ }
382
+ }
383
+ function writeState(env, sessionId, state) {
384
+ mkdirSync(turnDirectory(env), { recursive: true, mode: 0o700 });
385
+ const path = statePath(env, sessionId);
386
+ const temporary = `${path}.${process.pid}.tmp`;
387
+ writeFileSync(temporary, JSON.stringify(state), { mode: 0o600 });
388
+ renameSync(temporary, path);
389
+ }
390
+ function promptIdOf(payload) {
391
+ return typeof payload.prompt_id === 'string' && payload.prompt_id ? payload.prompt_id : null;
392
+ }
393
+ // ---- Transport ----
394
+ function bearerTransportSafe(url) {
395
+ return url.protocol === 'https:'
396
+ || (url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname));
397
+ }
398
+ /** `id` as this registration sends it to the Host. */
399
+ export function namespacedId(id, config) {
400
+ return `${id}.bb-${sha256(`brainbase-claude-code-registration\n${config.registration.id}`).slice(0, 16)}`;
401
+ }
402
+ // The Host looks a repository up in its project mapping only in this form
403
+ // (REPOSITORY_PATTERN of the Host's remote-judgment-hook-http). Any other
404
+ // identifier is passed over there, and the Host falls back to the person's
405
+ // only project.
406
+ const HOST_MAPPABLE_REPOSITORY = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
407
+ /**
408
+ * Whether the Host can choose the project for this repository from its
409
+ * mapping. Without --project, a repository it cannot look up (a host with a
410
+ * port, a `~` in the path, a very long name) is not sent at all.
411
+ */
412
+ export function hostCanMapRepository(repository, config) {
413
+ if (config.project_code || repository === null)
414
+ return true;
415
+ return HOST_MAPPABLE_REPOSITORY.test(repository);
416
+ }
417
+ async function forward(payload, context, repository, login = {}) {
418
+ if (!hostCanMapRepository(repository, context.config))
419
+ throw new Error('judgment_repository_unmappable');
420
+ let endpoint;
421
+ try {
422
+ endpoint = new URL(HOOK_PATH, context.config.origin);
423
+ }
424
+ catch {
425
+ throw new Error('judgment_hook_endpoint_invalid');
426
+ }
427
+ if (!bearerTransportSafe(endpoint))
428
+ throw new Error('judgment_hook_transport_unsafe');
429
+ let token;
430
+ let loginId;
431
+ try {
432
+ const obtained = await context.accessToken();
433
+ token = typeof obtained === 'string' ? obtained : obtained.token;
434
+ loginId = typeof obtained === 'string' ? null : obtained.loginId;
435
+ }
436
+ catch (error) {
437
+ const code = error?.code;
438
+ throw new Error(typeof code === 'string' && /^login_[a-z_]{1,60}$/u.test(code)
439
+ ? `judgment_hook_${code}` : 'judgment_hook_login_unavailable');
440
+ }
441
+ // Logged in again (as someone else, or the same person anew) since the turn
442
+ // began: the turn's events are not sent with the new login.
443
+ if (login.expected !== undefined && login.expected !== loginId)
444
+ throw new Error('judgment_turn_login_changed');
445
+ login.used = loginId;
446
+ const eventName = String(payload.hook_event_name);
447
+ // Claude Code's session and turn ids are the same for every registration
448
+ // that sees the event. The Host keys a turn by them, so each registration
449
+ // sends its own: the id with a tag of the registration appended.
450
+ const sent = {
451
+ ...payload,
452
+ session_id: namespacedId(String(payload.session_id), context.config),
453
+ turn_id: namespacedId(String(payload.turn_id), context.config),
454
+ };
455
+ let response;
456
+ try {
457
+ response = await context.fetch(endpoint, {
458
+ method: 'POST',
459
+ headers: {
460
+ 'content-type': 'application/json',
461
+ authorization: `Bearer ${token}`,
462
+ 'x-brainbase-judgment-host': 'claude-code',
463
+ ...(context.config.project_code ? { 'x-brainbase-project-code': context.config.project_code } : {}),
464
+ ...(repository ? { 'x-brainbase-repository': repository } : {}),
465
+ },
466
+ body: JSON.stringify(sent),
467
+ redirect: 'error',
468
+ signal: AbortSignal.timeout(TIMEOUT_MS[eventName] ?? 15_000),
469
+ });
470
+ }
471
+ catch (error) {
472
+ throw new Error(error?.name === 'TimeoutError' ? 'judgment_hook_timeout' : 'judgment_hook_unreachable');
473
+ }
474
+ const text = await response.text();
475
+ let envelope;
476
+ try {
477
+ envelope = JSON.parse(text);
478
+ }
479
+ catch {
480
+ envelope = null;
481
+ }
482
+ if (!response.ok) {
483
+ const upstream = typeof envelope?.error === 'string' && /^[a-z0-9_]{1,80}$/u.test(envelope.error)
484
+ ? `_${envelope.error}` : '';
485
+ throw new Error(`judgment_hook_http_${response.status}${upstream}`);
486
+ }
487
+ const output = envelope?.output;
488
+ if (!envelope || envelope.schema_version !== '1' || envelope.accepted !== true
489
+ || envelope.hook_event_name !== payload.hook_event_name
490
+ || envelope.session_id !== sent.session_id || envelope.turn_id !== sent.turn_id
491
+ || !output || typeof output !== 'object' || Array.isArray(output)) {
492
+ throw new Error('judgment_hook_response_invalid');
493
+ }
494
+ return output;
495
+ }
496
+ // The judgment plane audits; it never stops, blocks or rewrites. So only a
497
+ // notice for the person and, where Claude Code takes it, context for the model
498
+ // leave this adapter: never `continue`, `stopReason`, `decision`, `reason`,
499
+ // `suppressOutput` or a permission or input change, whatever the Host answers.
500
+ // Stop takes no context. The Host's PostToolUse branch names its context
501
+ // PostToolUse even for a failure event, so the event name is set here.
502
+ function documentedOutput(output, eventName) {
503
+ const result = typeof output.systemMessage === 'string' && output.systemMessage
504
+ ? { systemMessage: output.systemMessage } : {};
505
+ const specific = output.hookSpecificOutput;
506
+ if (eventName !== 'Stop' && specific && typeof specific === 'object' && !Array.isArray(specific)
507
+ && typeof specific.additionalContext === 'string') {
508
+ result.hookSpecificOutput = { hookEventName: eventName, additionalContext: specific.additionalContext };
509
+ }
510
+ return result;
511
+ }
512
+ function isBrainbaseTool(payload) {
513
+ return typeof payload.tool_name === 'string' && payload.tool_name.startsWith('mcp__brainbase__');
514
+ }
515
+ function digestSummary(value) {
516
+ const text = JSON.stringify(value) ?? 'null';
517
+ return { digest: `sha256:${sha256(text)}`, bytes: Buffer.byteLength(text) };
518
+ }
519
+ /**
520
+ * The Host keeps only digests of a non-Brainbase tool's input, output and
521
+ * error. Sending digests keeps file bodies and command output on this machine.
522
+ * The success fact is kept beside the digest, because a non-empty digest
523
+ * object alone would read as a success.
524
+ */
525
+ /**
526
+ * Fields of a Stop input the Host reads. Claude Code also puts the session's
527
+ * background work in a Stop input (`background_tasks[].command`,
528
+ * `session_crons[].prompt`, ...), whose commands and prompts can hold
529
+ * secrets, so a Stop is rebuilt from this list and nothing else is sent.
530
+ */
531
+ export const STOP_FORWARDED_FIELDS = [
532
+ 'hook_event_name', 'session_id', 'turn_id', 'prompt_id', 'transcript_path', 'cwd',
533
+ 'permission_mode', 'model', 'last_assistant_message', 'stop_hook_active',
534
+ ];
535
+ export function forwardedStopPayload(payload) {
536
+ const kept = {};
537
+ for (const field of STOP_FORWARDED_FIELDS) {
538
+ if (payload[field] !== undefined)
539
+ kept[field] = payload[field];
540
+ }
541
+ return kept;
542
+ }
543
+ export function forwardedToolPayload(payload) {
544
+ if (isBrainbaseTool(payload))
545
+ return payload;
546
+ const summarized = { ...payload };
547
+ for (const field of ['tool_input', 'tool_response', 'error']) {
548
+ if (payload[field] !== undefined)
549
+ summarized[field] = digestSummary(payload[field]);
550
+ }
551
+ const response = payload.tool_response;
552
+ summarized.tool_response = {
553
+ ...digestSummary(response),
554
+ success: response !== undefined && response !== null
555
+ && payload.hook_event_name !== 'PostToolUseFailure'
556
+ && payload.is_interrupt !== true && response?.interrupted !== true
557
+ && response?.is_error !== true && response?.isError !== true
558
+ && response?.success !== false
559
+ && response?.status !== 'error' && response?.status !== 'failed'
560
+ && !(Number.isInteger(response?.exit_code) && response?.exit_code !== 0)
561
+ && !(Number.isInteger(response?.exitCode) && response?.exitCode !== 0),
562
+ };
563
+ return summarized;
564
+ }
565
+ function safeReason(error) {
566
+ const message = error instanceof Error ? error.message : '';
567
+ return /^judgment_[a-z0-9_]{1,120}$/u.test(message) ? message : 'judgment_hook_failed';
568
+ }
569
+ // ---- Event handlers ----
570
+ function currentTurn(payload, context) {
571
+ const state = readState(context.env, turnKey(payload, context));
572
+ if (!state)
573
+ return null;
574
+ const promptId = promptIdOf(payload);
575
+ if (promptId && typeof state.prompt_id === 'string' && state.prompt_id !== promptId)
576
+ return null;
577
+ return state;
578
+ }
579
+ // An event of a prompt that no UserPromptSubmit opened. Claude Code screens an
580
+ // input that arrives mid-turn and keeps the result; when that input later runs
581
+ // as its own turn, no UserPromptSubmit arrives for it. The Host cannot open a
582
+ // turn without that request, so the turn is recorded as unannounced and the
583
+ // person is told once.
584
+ function unannouncedTurn(payload, context) {
585
+ const { env } = context;
586
+ const sessionId = turnKey(payload, context);
587
+ const promptId = promptIdOf(payload);
588
+ const previous = readState(env, sessionId);
589
+ if (!promptId || typeof previous?.prompt_id !== 'string' || previous.prompt_id === promptId)
590
+ return {};
591
+ if (recentPrompts(previous).includes(promptId))
592
+ return {};
593
+ const audited = isAuditedRepository(context.scope, context.config);
594
+ // Only one event takes the note: several processes can each unlink the same
595
+ // file, but only one rename of it succeeds.
596
+ const note = screeningPath(env, sessionId, previous.prompt_id);
597
+ try {
598
+ renameSync(note, `${note}.${process.pid}`);
599
+ }
600
+ catch {
601
+ return {};
602
+ }
603
+ try {
604
+ unlinkSync(`${note}.${process.pid}`);
605
+ }
606
+ catch { }
607
+ if (readState(env, sessionId)?.prompt_id !== previous.prompt_id)
608
+ return {};
609
+ const told = audited
610
+ ? warning('このターンはClaude CodeからUserPromptSubmitが届かなかったため、判断監査なしで続行します(judgment_turn_unannounced)。作業中に届いた入力が次のターンとして実行されたときなどに起こります。')
611
+ : {};
612
+ try {
613
+ writeState(env, sessionId, {
614
+ schema_version: TURN_SCHEMA,
615
+ turn_id: promptId,
616
+ prompt_id: promptId,
617
+ started_at: new Date().toISOString(),
618
+ start_status: audited ? 'unannounced' : 'out_of_scope',
619
+ stop_blocks: 0,
620
+ recent_prompt_ids: recentPrompts(previous),
621
+ repository: context.scope.repository,
622
+ checkout: context.scope.checkout,
623
+ destination: destinationOf(context),
624
+ });
625
+ }
626
+ catch {
627
+ return told;
628
+ }
629
+ noteScreening(env, sessionId, promptId);
630
+ return told;
631
+ }
632
+ async function handleUserPromptSubmit(payload, context) {
633
+ const { env } = context;
634
+ const sessionId = turnKey(payload, context);
635
+ const promptId = promptIdOf(payload);
636
+ const previous = readState(env, sessionId);
637
+ // Claude Code fires UserPromptSubmit again with the running turn's prompt_id
638
+ // when it screens an input that arrives mid-turn. The first submission
639
+ // decided the turn, so a screening is not sent; it is only noted.
640
+ if (promptId && previous?.prompt_id === promptId) {
641
+ noteScreening(env, sessionId, promptId);
642
+ return {};
643
+ }
644
+ if (typeof previous?.prompt_id === 'string')
645
+ forgetScreening(env, sessionId, previous.prompt_id);
646
+ const state = {
647
+ schema_version: TURN_SCHEMA,
648
+ turn_id: promptId ?? randomUUID(),
649
+ prompt_id: promptId,
650
+ started_at: new Date().toISOString(),
651
+ start_status: 'failed',
652
+ stop_blocks: 0,
653
+ recent_prompt_ids: recentPrompts(previous),
654
+ repository: context.scope.repository,
655
+ checkout: context.scope.checkout,
656
+ destination: destinationOf(context),
657
+ };
658
+ if (!isAuditedRepository(context.scope, context.config)) {
659
+ writeState(env, sessionId, { ...state, start_status: 'out_of_scope' });
660
+ if (context.scope.unresolved) {
661
+ return warning('git からこのリポジトリの origin を確かめられなかったため、判断監査なしで続行します(judgment_repository_unresolved)。git が入っているか、このフォルダーを git が扱えるかを確かめてください。');
662
+ }
663
+ if (context.scope.unidentified) {
664
+ return warning('このリポジトリの origin の URL からホスト・所有者・名前を読み取れず、送り先のプロジェクトを決められないため、判断監査なしで続行します(judgment_repository_unidentified)。judgment:install に --project を付けて登録し直してください。');
665
+ }
666
+ return {};
667
+ }
668
+ if (!hostCanMapRepository(context.scope.repository, context.config)) {
669
+ writeState(env, sessionId, { ...state, start_status: 'out_of_scope' });
670
+ return warning(`このリポジトリ(${context.scope.repository})は判断ハーネスがプロジェクトを選べない形式のため、判断監査なしで続行します(judgment_repository_unmappable)。judgment:install に --project を付けて登録し直してください。`);
671
+ }
672
+ writeState(env, sessionId, state);
673
+ try {
674
+ const login = {};
675
+ const output = await forward({ ...payload, turn_id: state.turn_id }, context, state.repository ?? null, login);
676
+ writeState(env, sessionId, { ...state, start_status: 'started', login: login.used ?? null });
677
+ return documentedOutput(output, 'UserPromptSubmit');
678
+ }
679
+ catch (error) {
680
+ return warning(`判断ハーネスに接続できないため、このターンは判断監査なしで続行します(${safeReason(error)})。`);
681
+ }
682
+ }
683
+ // A started turn always has its login recorded; a state without one (written
684
+ // before logins were pinned) matches no login, so nothing more is sent.
685
+ function turnLogin(state) {
686
+ return { expected: typeof state.login === 'string' || state.login === null ? state.login : '\u0000unrecorded' };
687
+ }
688
+ async function handlePostToolUse(payload, context, eventName) {
689
+ const state = currentTurn(payload, context);
690
+ if (!state)
691
+ return unannouncedTurn(payload, context);
692
+ if (state.start_status !== 'started' || !sameScope(state, context.scope) || !sameDestination(state, context)
693
+ || !isAuditedRepository(context.scope, context.config))
694
+ return {};
695
+ try {
696
+ return documentedOutput(await forward({ ...forwardedToolPayload(payload), turn_id: state.turn_id }, context, state.repository ?? null, turnLogin(state)), eventName);
697
+ }
698
+ catch (error) {
699
+ return warning(`監査記録に失敗しました(${safeReason(error)})。作業は続行します。`);
700
+ }
701
+ }
702
+ // Only a denial with its reason, or context for the model, leaves a
703
+ // PreToolUse: the judgment plane never allows, rewrites or stops a call.
704
+ function preToolUseOutput(output) {
705
+ const result = typeof output.systemMessage === 'string' ? { systemMessage: output.systemMessage } : {};
706
+ const specific = output.hookSpecificOutput;
707
+ if (!specific || typeof specific !== 'object' || Array.isArray(specific))
708
+ return result;
709
+ if (specific.permissionDecision === 'deny') {
710
+ result.hookSpecificOutput = {
711
+ hookEventName: 'PreToolUse', permissionDecision: 'deny',
712
+ ...(typeof specific.permissionDecisionReason === 'string'
713
+ ? { permissionDecisionReason: specific.permissionDecisionReason } : {}),
714
+ };
715
+ }
716
+ else if (typeof specific.additionalContext === 'string') {
717
+ result.hookSpecificOutput = { hookEventName: 'PreToolUse', additionalContext: specific.additionalContext };
718
+ }
719
+ return result;
720
+ }
721
+ async function handlePreToolUse(payload, context) {
722
+ if (typeof payload.tool_name !== 'string' || !PRE_TOOL_USE_TOOLS.has(payload.tool_name))
723
+ return {};
724
+ const state = currentTurn(payload, context);
725
+ if (!state)
726
+ return unannouncedTurn(payload, context);
727
+ if (state.start_status !== 'started' || !sameScope(state, context.scope) || !sameDestination(state, context)
728
+ || !isAuditedRepository(context.scope, context.config))
729
+ return {};
730
+ try {
731
+ return preToolUseOutput(await forward({ ...payload, turn_id: state.turn_id }, context, state.repository ?? null, turnLogin(state)));
732
+ }
733
+ catch (error) {
734
+ return warning(`知識取得の試行を判断ハーネスへ予約できませんでした(${safeReason(error)})。この試行は記録されません。`);
735
+ }
736
+ }
737
+ async function handleStop(payload, context) {
738
+ const state = currentTurn(payload, context);
739
+ if (!state)
740
+ return unannouncedTurn(payload, context);
741
+ if (state.start_status !== 'started')
742
+ return {};
743
+ if (!sameScope(state, context.scope)) {
744
+ return warning('ターンの途中で別のリポジトリに移ったため、回答を送らずに監査未完了のまま終了します(judgment_turn_repository_changed)。');
745
+ }
746
+ if (!sameDestination(state, context)) {
747
+ return warning('ターンの途中で判断フックの送り先が変わったため、回答を送らずに監査未完了のまま終了します(judgment_turn_destination_changed)。');
748
+ }
749
+ // The config is read again for every event: a repository taken off the list
750
+ // mid-turn sends nothing more, though the destination stays the same.
751
+ if (!isAuditedRepository(context.scope, context.config)) {
752
+ return warning('ターンの途中でこのリポジトリが監査の対象から外れたため、回答を送らずに終了します(judgment_turn_repository_unaudited)。');
753
+ }
754
+ const blocks = Number.isSafeInteger(state.stop_blocks) ? state.stop_blocks : 0;
755
+ let raw;
756
+ try {
757
+ raw = await forward({ ...forwardedStopPayload(payload), turn_id: state.turn_id, stop_hook_active: blocks > 0 }, context, state.repository ?? null, turnLogin(state));
758
+ }
759
+ catch (error) {
760
+ return warning(`回答の照合に失敗したため、監査未完了のまま終了します(${safeReason(error)})。`);
761
+ }
762
+ const output = documentedOutput(raw, 'Stop');
763
+ if (raw.decision !== 'block')
764
+ return output;
765
+ // The person has already read the answer when Stop runs. Sending the repair
766
+ // request back would print the same answer twice, so it is shown as a notice.
767
+ writeState(context.env, turnKey(payload, context), { ...state, stop_blocks: blocks + 1 });
768
+ const repairId = /r-[a-f0-9]{16}/u.exec(typeof raw.reason === 'string' ? raw.reason : '')?.[0];
769
+ const notice = warning(`回答は差し戻しません。監査は未完了のまま終了します${repairId ? `(${repairId})` : ''}。`).systemMessage;
770
+ return { systemMessage: [output.systemMessage, notice].filter(Boolean).join('\n') };
771
+ }
772
+ /** Handles one Claude Code hook event. Never throws. */
773
+ export async function handleClaudeCodeJudgmentHook(payload, options = {}) {
774
+ const env = options.env ?? process.env;
775
+ try {
776
+ if (env.BRAINBASE_CLAUDE_JUDGMENT_HOOK === 'disabled')
777
+ return {};
778
+ const configPath = resolve(options.configPath ?? defaultClaudeCodeHookConfigPath(env));
779
+ const config = readClaudeCodeHookConfig(configPath);
780
+ // Not installed for this person, or removed: forward nothing.
781
+ if (!config)
782
+ return {};
783
+ const eventName = payload.hook_event_name;
784
+ // The config now belongs to another registration (installed again from
785
+ // another settings file): this one sends nothing, and says so once a turn.
786
+ if (options.registrationId !== config.registration.id) {
787
+ return eventName === 'UserPromptSubmit'
788
+ ? warning(`この登録の設定(${configPath})は、別のClaude Codeの設定(${config.registration.settings})の登録に使われています。判断監査なしで続行します。judgment:install をやり直してください。`)
789
+ : {};
790
+ }
791
+ if (typeof payload.session_id !== 'string' || !payload.session_id)
792
+ return {};
793
+ // A subagent's events are not the parent turn's.
794
+ if (typeof payload.agent_id === 'string' && payload.agent_id)
795
+ return {};
796
+ const context = {
797
+ env,
798
+ config,
799
+ fetch: options.fetch ?? fetch,
800
+ accessToken: options.accessToken ?? (async () => {
801
+ const login = await getAccessTokenOfLogin({ fetch: options.fetch, ...options.credentials });
802
+ // A login to another environment (production instead of staging, say)
803
+ // must not reach this Host.
804
+ if (login.serverUrl !== config.login_server) {
805
+ throw Object.assign(new Error('login_origin_mismatch'), { code: 'login_origin_mismatch' });
806
+ }
807
+ return { token: login.token, loginId: login.loginId };
808
+ }),
809
+ scope: eventRepository(payload, env),
810
+ configPath,
811
+ };
812
+ if (eventName === 'UserPromptSubmit')
813
+ return await handleUserPromptSubmit(payload, context);
814
+ if (eventName === 'PreToolUse')
815
+ return await handlePreToolUse(payload, context);
816
+ if (eventName === 'PostToolUse' || eventName === 'PostToolUseFailure') {
817
+ return await handlePostToolUse(payload, context, eventName);
818
+ }
819
+ if (eventName === 'Stop')
820
+ return await handleStop(payload, context);
821
+ return {};
822
+ }
823
+ catch (error) {
824
+ return warning(`判断フックの処理に失敗しました(${safeReason(error)})。判断監査なしで続行します。`);
825
+ }
826
+ }
827
+ // ---- Registration in the person's Claude Code settings ----
828
+ export const CLAUDE_CODE_HOOK_COMMAND = 'judgment:claude-code-hook';
829
+ /** One argument quoted for a POSIX shell (Claude Code runs hook commands with sh). */
830
+ export function shellQuote(argument) {
831
+ return `'${argument.replace(/'/gu, `'\\''`)}'`;
832
+ }
833
+ /**
834
+ * The command the installer registers: node, the CLI, the hook command, the
835
+ * config file and the registration id, each quoted for the shell.
836
+ */
837
+ export function claudeCodeHookCommand(nodePath, cliPath, configPath, registrationId) {
838
+ return [nodePath, cliPath, CLAUDE_CODE_HOOK_COMMAND, '--config', configPath, '--registration', registrationId]
839
+ .map(shellQuote).join(' ');
840
+ }
841
+ /** The arguments of a command made only of single-quoted words, or null. */
842
+ function singleQuotedWords(command) {
843
+ const words = [];
844
+ let index = 0;
845
+ while (index < command.length) {
846
+ if (command[index] !== "'")
847
+ return null;
848
+ let word = '';
849
+ for (;;) {
850
+ const close = command.indexOf("'", index + 1);
851
+ if (close < 0)
852
+ return null;
853
+ word += command.slice(index + 1, close);
854
+ index = close + 1;
855
+ if (command.startsWith("\\''", index)) {
856
+ word += "'";
857
+ index += 2; // continue with the reopening quote
858
+ continue;
859
+ }
860
+ break;
861
+ }
862
+ words.push(word);
863
+ if (index === command.length)
864
+ break;
865
+ if (command[index] !== ' ')
866
+ return null;
867
+ index += 1;
868
+ }
869
+ return words;
870
+ }
871
+ /**
872
+ * The config path and registration id of a registration this installer
873
+ * wrote, or null for any other hook (a wrapper, or another hook that only
874
+ * mentions the command).
875
+ */
876
+ export function installedHookRegistration(hook) {
877
+ const value = hook;
878
+ if (!value || value.type !== 'command' || typeof value.command !== 'string')
879
+ return null;
880
+ const words = singleQuotedWords(value.command);
881
+ if (!words || words.length !== 7 || words[2] !== CLAUDE_CODE_HOOK_COMMAND || words[3] !== '--config'
882
+ || words[5] !== '--registration' || !REGISTRATION_ID.test(words[6]) || !words[4])
883
+ return null;
884
+ return { configPath: words[4], registrationId: words[6] };
885
+ }
886
+ /** The config path of a registration this installer wrote, or null. */
887
+ export function installedHookConfigPath(hook) {
888
+ return installedHookRegistration(hook)?.configPath ?? null;
889
+ }
890
+ /**
891
+ * One name for a file however it is reached: the real path, with links in
892
+ * every existing directory followed. For a file that does not exist yet, its
893
+ * nearest existing directory is resolved and the rest appended.
894
+ */
895
+ export function canonicalFilePath(path) {
896
+ const absolute = resolve(path);
897
+ try {
898
+ return realpathSync(absolute);
899
+ }
900
+ catch {
901
+ const parent = dirname(absolute);
902
+ if (parent === absolute)
903
+ return absolute;
904
+ return join(canonicalFilePath(parent), absolute.slice(parent.length).replace(/^[/\\]+/u, ''));
905
+ }
906
+ }
907
+ // A registered command names the config by the path it was installed with.
908
+ // Two paths to one file (a linked directory) are one registration.
909
+ function sameConfigFile(registered, configPath) {
910
+ return registered === configPath || canonicalFilePath(registered) === canonicalFilePath(configPath);
911
+ }
912
+ // Timeouts (seconds) outlast the adapter's own HTTP deadlines.
913
+ const REGISTRATIONS = [
914
+ { event: 'UserPromptSubmit', timeout: 60, statusMessage: 'brainbase judgment' },
915
+ {
916
+ event: 'PreToolUse',
917
+ matcher: 'mcp__brainbase__brainbase_knowledge_lookup',
918
+ timeout: 30,
919
+ statusMessage: 'brainbase judgment lookup check',
920
+ },
921
+ { event: 'PostToolUse', timeout: 30, statusMessage: 'brainbase judgment audit' },
922
+ { event: 'PostToolUseFailure', timeout: 30, statusMessage: 'brainbase judgment audit' },
923
+ { event: 'Stop', timeout: 60, statusMessage: 'brainbase judgment answer check' },
924
+ ];
925
+ function withoutInstalledHooks(hooks, configPath, removedIds) {
926
+ const result = {};
927
+ for (const [event, groups] of Object.entries((hooks ?? {}))) {
928
+ if (!Array.isArray(groups)) {
929
+ result[event] = groups;
930
+ continue;
931
+ }
932
+ const kept = [];
933
+ for (const group of groups) {
934
+ const inner = group?.hooks;
935
+ if (!Array.isArray(inner)) {
936
+ kept.push(group);
937
+ continue;
938
+ }
939
+ const remaining = inner.filter((hook) => {
940
+ const registration = installedHookRegistration(hook);
941
+ if (!registration || !sameConfigFile(registration.configPath, configPath))
942
+ return true;
943
+ removedIds?.add(registration.registrationId);
944
+ return false;
945
+ });
946
+ if (remaining.length === inner.length)
947
+ kept.push(group);
948
+ else if (remaining.length > 0)
949
+ kept.push({ ...group, hooks: remaining });
950
+ }
951
+ if (kept.length > 0)
952
+ result[event] = kept;
953
+ }
954
+ return result;
955
+ }
956
+ /** True when the settings hold a registration this installer wrote for `configPath`. */
957
+ export function hasInstalledClaudeCodeHooks(settings, configPath) {
958
+ for (const groups of Object.values((settings.hooks ?? {}))) {
959
+ if (!Array.isArray(groups))
960
+ continue;
961
+ for (const group of groups) {
962
+ const inner = group?.hooks;
963
+ if (Array.isArray(inner) && inner.some((hook) => {
964
+ const registered = installedHookConfigPath(hook);
965
+ return registered !== null && sameConfigFile(registered, configPath);
966
+ }))
967
+ return true;
968
+ }
969
+ }
970
+ return false;
971
+ }
972
+ /**
973
+ * The hook groups one registration adds to Claude Code settings, one per
974
+ * event. A preview shows these, not the settings they go into, which may hold
975
+ * secrets (`env`, `apiKeyHelper`, other hooks' commands).
976
+ */
977
+ export function claudeCodeJudgmentHookGroups(command) {
978
+ return REGISTRATIONS.map(({ event, matcher, timeout, statusMessage }) => ({
979
+ event,
980
+ group: { ...(matcher ? { matcher } : {}), hooks: [{ type: 'command', command, timeout, statusMessage }] },
981
+ }));
982
+ }
983
+ /**
984
+ * Claude Code settings with exactly one registration per event for
985
+ * `configPath`, or none with `remove`. Only registrations this installer wrote
986
+ * for the same config file (by any path to it) are replaced; every other hook
987
+ * and setting is kept. The registration ids of the replaced commands are added
988
+ * to `removedIds`.
989
+ */
990
+ export function registerClaudeCodeJudgmentHooks(settings, { command, configPath, remove = false, removedIds }) {
991
+ const hooks = withoutInstalledHooks(settings.hooks, configPath, removedIds);
992
+ if (!remove) {
993
+ for (const { event, group } of claudeCodeJudgmentHookGroups(command)) {
994
+ hooks[event] = [...(hooks[event] ?? []), group];
995
+ }
996
+ }
997
+ const next = { ...settings };
998
+ if (Object.keys(hooks).length > 0)
999
+ next.hooks = hooks;
1000
+ else
1001
+ delete next.hooks;
1002
+ return next;
1003
+ }