@unson/brainbase-mcp 0.50.24 → 0.50.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,9 +2,10 @@
2
2
  import { createPortableGraph, portableGraphDigest } from './portable-graph.js';
3
3
  import { createOrganizationGraphConfig, createOrganizationGraphClient } from './organization-graph.js';
4
4
  import { listLocalMemories, memoryListJson, registerSelectedMemories, registrationPreviewJson, renderMemoryList, renderRegistrationPreview, renderRegistrationResult, selectLocalMemories } from './personal-memory-handover.js';
5
+ import { randomBytes } from 'node:crypto';
5
6
  import { constants, realpathSync } from 'node:fs';
6
- import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
7
- import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
7
+ import { access, chmod, link, lstat, mkdir, open, readdir, readFile, readlink, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
8
+ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path';
8
9
  import { fileURLToPath } from 'node:url';
9
10
  import { initializePersonalOs, loadPersonalOs, migrateCanonicalGraph, mutatePersonalOs } from './ssot.js';
10
11
  import { diagnoseGraph } from './graph-diagnosis.js';
@@ -23,6 +24,8 @@ import { applyCanonicalWrites, buildCanonicalEdge } from './canonical-edge-build
23
24
  import { defaultJudgmentJournalRoot } from './judgment-value-proof-review.js';
24
25
  import { createWorldExtension, readWorldVocabulary } from './world-extension.js';
25
26
  import { createLocalWebHost, LOCAL_WEB_DEFAULT_PORT } from './local-web-host.js';
27
+ import { assertCredentialsFilePath, BrainbaseLoginError, CREDENTIALS_SCHEMA_VERSION, defaultCredentialsPath, loginWithDeviceCode, normalizeServerUrl, readCredentials, removeCredentials, withCredentialsLock } from './brainbase-login.js';
28
+ import { CLAUDE_CODE_HOOK_CONFIG_SCHEMA, canonicalFilePath, claudeCodeHookCommand, claudeCodeJudgmentHookGroups, defaultClaudeCodeHookConfigPath, handleClaudeCodeJudgmentHook, hasInstalledClaudeCodeHooks, isClaudeCodeHookConfigText, parseClaudeCodeHookConfig, normalizeRepositoryEntry, registerClaudeCodeJudgmentHooks } from './claude-code-judgment-hook.js';
26
29
  export async function runCli(argv = process.argv.slice(2), io = process) {
27
30
  const parsed = parseArgs(argv);
28
31
  try {
@@ -109,6 +112,14 @@ export async function runCli(argv = process.argv.slice(2), io = process) {
109
112
  return await judgmentHook(parsed, io);
110
113
  case 'judgment:install':
111
114
  return await judgmentInstall(parsed, io);
115
+ case 'judgment:claude-code-hook':
116
+ return await judgmentClaudeCodeHook(parsed, io);
117
+ case 'login':
118
+ return await login(parsed, io);
119
+ case 'login:status':
120
+ return await loginStatus(parsed, io);
121
+ case 'logout':
122
+ return await logout(parsed, io);
112
123
  case 'doctor':
113
124
  return await doctor(parsed, io);
114
125
  case 'web:serve':
@@ -161,8 +172,10 @@ async function judgmentHook(parsed, io) {
161
172
  }
162
173
  async function judgmentInstall(parsed, io) {
163
174
  const target = first(parsed, 'target');
175
+ if (target === 'claude-code')
176
+ return await judgmentInstallClaudeCode(parsed, io);
164
177
  if (target !== 'codex')
165
- throw new Error('judgment:install currently requires --target codex');
178
+ throw new Error('judgment:install requires --target codex|claude-code');
166
179
  const cliPath = fileURLToPath(new URL('./cli.js', import.meta.url));
167
180
  const autonomy = judgmentAutonomyOptions(parsed);
168
181
  const hookArguments = [
@@ -198,11 +211,694 @@ async function judgmentInstall(parsed, io) {
198
211
  write(io, `Wrote Codex Judgment Host config snippet to ${outputPath}\n`);
199
212
  return 0;
200
213
  }
201
- async function readHookStdin(input) {
202
- let text = '';
203
- for await (const chunk of input)
204
- text += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8');
205
- return text;
214
+ const CLAUDE_CODE_HOOK_MAX_INPUT_BYTES = 16 * 1024 * 1024;
215
+ async function judgmentClaudeCodeHook(parsed, io) {
216
+ // Fail-open: whatever happens, Claude Code gets a valid hook answer and exit 0.
217
+ let output;
218
+ try {
219
+ const input = await readHookStdin(io.stdin ?? process.stdin, CLAUDE_CODE_HOOK_MAX_INPUT_BYTES);
220
+ const payload = JSON.parse(input || '{}');
221
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
222
+ throw new Error('judgment_hook_payload_invalid');
223
+ const configPath = first(parsed, 'config');
224
+ const registrationId = first(parsed, 'registration');
225
+ output = await handleClaudeCodeJudgmentHook(payload, {
226
+ ...(configPath ? { configPath } : {}),
227
+ ...(registrationId ? { registrationId } : {}),
228
+ });
229
+ }
230
+ catch (error) {
231
+ const message = error instanceof Error && /^judgment_[a-z0-9_]{1,120}$/u.test(error.message)
232
+ ? error.message : 'judgment_hook_failed';
233
+ output = { systemMessage: `⚠️ Brainbase判断フック: 判断フックの処理に失敗しました(${message})。判断監査なしで続行します。` };
234
+ }
235
+ write(io, `${JSON.stringify(output)}\n`);
236
+ return 0;
237
+ }
238
+ const HOOK_PROJECT_CODE_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
239
+ // Every option judgment:install --target claude-code reads. Anything else
240
+ // (a typo, or `--opt=value`, which parseArgs keeps whole as the key
241
+ // `opt=value`) would be ignored silently and widen what gets audited or write
242
+ // where a preview was meant, so it is refused before any file is touched.
243
+ const CLAUDE_CODE_INSTALL_VALUE_OPTIONS = new Set(['target', 'settings', 'config', 'origin', 'server', 'project', 'repositories']);
244
+ const CLAUDE_CODE_INSTALL_SWITCHES = new Set(['remove', 'dry-run']);
245
+ function assertClaudeCodeInstallOptions(parsed) {
246
+ for (const name of [...parsed.flags, ...parsed.values.keys()]) {
247
+ if (CLAUDE_CODE_INSTALL_VALUE_OPTIONS.has(name) || CLAUDE_CODE_INSTALL_SWITCHES.has(name))
248
+ continue;
249
+ const base = name.split('=')[0] ?? name;
250
+ if (base !== name && (CLAUDE_CODE_INSTALL_VALUE_OPTIONS.has(base) || CLAUDE_CODE_INSTALL_SWITCHES.has(base))) {
251
+ const hint = CLAUDE_CODE_INSTALL_SWITCHES.has(base) ? `--${base}` : `--${base} <値>`;
252
+ throw new Error(`--${base}=… の形は使えません。${hint} のように書いてください。何も変えずに止めました。`);
253
+ }
254
+ throw new Error(`judgment:install --target claude-code は --${name} を知りません。何も変えずに止めました。`);
255
+ }
256
+ for (const name of CLAUDE_CODE_INSTALL_SWITCHES) {
257
+ // `--dry-run true` would leave dry-run unset and write for real.
258
+ if (parsed.values.has(name))
259
+ throw new Error(`--${name} は値をとりません(--${name} だけを書きます)。何も変えずに止めました。`);
260
+ }
261
+ for (const name of CLAUDE_CODE_INSTALL_VALUE_OPTIONS) {
262
+ if (name !== 'repositories' && (parsed.values.get(name)?.length ?? 0) > 1) {
263
+ throw new Error(`--${name} は1回だけ書けます。何も変えずに止めました。`);
264
+ }
265
+ }
266
+ }
267
+ // The file the system opens for `path`. resolve() drops `link/..` as text, but
268
+ // the system follows `link` first, so `alias/link/../settings.json` is a file
269
+ // next to the link's target, not in `alias`. The parent directory is resolved
270
+ // by the system and the last name added back. realpathSync.native, because
271
+ // the JavaScript realpathSync also normalizes the text before following links.
272
+ // When the parent does not exist yet, the text form opens the same file only
273
+ // if the path has no `..`; with one, a link before it could lead elsewhere,
274
+ // so the install stops instead of guessing.
275
+ function settingsPathAsOpened(path) {
276
+ // `file.json/` names a directory; dropping the slash would edit file.json.
277
+ // Only the system's separators count: on POSIX `settings.json\` is a file name.
278
+ if (process.platform === 'win32' ? /[\\/]$/u.test(path) : path.endsWith('/')) {
279
+ throw new Error(`--settings ${path} は末尾が / で、ファイルを指していないため止めました。settings.json のパスを指定してください。何も変えていません。`);
280
+ }
281
+ const absolute = isAbsolute(path) ? path : `${process.cwd()}${sep}${path}`;
282
+ const name = basename(absolute);
283
+ if (name === '' || name === '.' || name === '..')
284
+ return resolve(absolute);
285
+ try {
286
+ return join(realpathSync.native(dirname(absolute)), name);
287
+ }
288
+ catch (error) {
289
+ if (error.code !== 'ENOENT')
290
+ throw error;
291
+ if (absolute.split(/[\\/]/u).includes('..')) {
292
+ throw new Error(`--settings ${path} の途中に、まだ無いディレクトリと .. があり、どのファイルを開くかを決められないため止めました。.. を含まないパスか、ディレクトリがそろったパスを指定してください。何も変えていません。`);
293
+ }
294
+ return resolve(absolute);
295
+ }
296
+ }
297
+ async function judgmentInstallClaudeCode(parsed, io) {
298
+ assertClaudeCodeInstallOptions(parsed);
299
+ // `--opt=value` or a bare `--opt` would otherwise fall back to the default
300
+ // settings or config, and --remove would edit a file the user did not name.
301
+ const settingsPath = settingsPathAsOpened(explicitValue(parsed, 'settings', '--settings <path>')
302
+ ?? join(process.env.CLAUDE_CONFIG_DIR || join(process.env.HOME || '', '.claude'), 'settings.json'));
303
+ // Absolute, because the registered command carries it to every hook run.
304
+ const configPath = resolve(explicitValue(parsed, 'config', '--config <path>') ?? defaultClaudeCodeHookConfigPath());
305
+ const settingsReal = await installSettingsTarget(settingsPath);
306
+ const configReal = canonicalFilePath(configPath);
307
+ if (settingsReal === configReal) {
308
+ throw new Error('judgment:install --settings and --config must be different files');
309
+ }
310
+ if (configReal === settingsReal + INSTALL_SETTINGS_BACKUP_SUFFIX) {
311
+ throw new Error('judgment:install --config must not be the settings backup file');
312
+ }
313
+ if (configReal === canonicalFilePath(resolve(defaultCredentialsPath()))) {
314
+ throw new Error('judgment:install --config must not be the brainbase login file');
315
+ }
316
+ const remove = parsed.flags.has('remove');
317
+ const dryRun = parsed.flags.has('dry-run');
318
+ const registrationId = randomBytes(16).toString('hex');
319
+ let config;
320
+ if (!remove) {
321
+ const origin = explicitValue(parsed, 'origin', '--origin <hosted MCP URL>');
322
+ if (!origin)
323
+ throw new Error('judgment:install --target claude-code requires --origin <hosted MCP URL>');
324
+ // A bare, empty or blank --project would drop the project and let the Host
325
+ // pick one; leave the option out for that instead.
326
+ const projectValue = explicitValue(parsed, 'project', '--project <code>');
327
+ const projectCode = projectValue?.trim();
328
+ if (projectValue !== undefined && !HOOK_PROJECT_CODE_PATTERN.test(projectCode ?? ''))
329
+ throw new Error('judgment:install --project must match [a-z0-9][a-z0-9._-]{0,63}');
330
+ explicitValue(parsed, 'repositories', '--repositories <host/owner/name,...>');
331
+ const repositoryValues = parsed.values.get('repositories');
332
+ const repositories = (repositoryValues ?? [])
333
+ .flatMap((value) => value.split(',')).map((name) => name.trim()).filter(Boolean)
334
+ .map((name) => {
335
+ const normalized = normalizeRepositoryEntry(name);
336
+ if (!normalized) {
337
+ throw new Error(`judgment:install --repositories needs host/owner/name, e.g. github.com/example-org/app (got ${name})`);
338
+ }
339
+ return normalized;
340
+ });
341
+ // An empty list would read as "no limit". Leaving the option out audits
342
+ // every repository; an empty value is refused instead of widening to that.
343
+ // `--repositories ''` arrives as a bare flag.
344
+ if ((repositoryValues !== undefined || parsed.flags.has('repositories')) && repositories.length === 0) {
345
+ throw new Error('judgment:install --repositories needs at least one host/owner/name; leave the option out to audit every repository');
346
+ }
347
+ // The hook sends only the login made to this API, so a later login to
348
+ // another environment never reaches this Host.
349
+ const loginServer = explicitValue(parsed, 'server', '--server <API URL>')
350
+ ?? (await readCredentials(defaultCredentialsPath()).catch(() => null))?.server_url;
351
+ if (!loginServer) {
352
+ throw new Error('judgment:install --target claude-code requires --server <API URL> (the server you log in to with brainbase login), or a saved login');
353
+ }
354
+ config = {
355
+ schema_version: CLAUDE_CODE_HOOK_CONFIG_SCHEMA,
356
+ origin: normalizeServerUrl(origin),
357
+ login_server: normalizeServerUrl(loginServer),
358
+ ...(projectCode ? { project_code: projectCode } : {}),
359
+ ...(repositories.length > 0 ? { repositories: [...new Set(repositories)] } : {}),
360
+ registration: { id: registrationId, settings: settingsReal }
361
+ };
362
+ }
363
+ const cliPath = fileURLToPath(new URL('./cli.js', import.meta.url));
364
+ const command = claudeCodeHookCommand(process.execPath, cliPath, configPath, registrationId);
365
+ const plan = { settingsPath, settingsReal, configPath, configReal, config, command, remove, dryRun };
366
+ // Claude Code saves its settings without taking the install lock. When it
367
+ // saved between our read and our write, start again from what it saved, so
368
+ // its change is kept; give up after a few tries without changing anything.
369
+ const run = async () => {
370
+ for (let attempt = 1;; attempt += 1) {
371
+ try {
372
+ return await applyClaudeCodeRegistration(plan, io);
373
+ }
374
+ catch (error) {
375
+ if (!(error instanceof SettingsChangedError))
376
+ throw error;
377
+ if (attempt >= SETTINGS_CHANGED_ATTEMPTS) {
378
+ throw new Error(`${settingsPath} は登録の途中で何度も別の保存が入ったため、何も変えずに止めました。Claude Code の設定の保存が落ち着いてから、もう一度実行してください。`);
379
+ }
380
+ }
381
+ }
382
+ };
383
+ // A preview writes nothing, so it takes no lock.
384
+ return dryRun ? await run() : await withInstallLocks([settingsReal, configReal], async () => {
385
+ await recoverInstallSettings(settingsReal);
386
+ return await run();
387
+ });
388
+ }
389
+ /**
390
+ * Runs `task` holding one lock per file, so that two installs touching the
391
+ * same Claude Code settings or the same hook config run one after the other:
392
+ * each reads, checks ownership and writes both files under the locks. The
393
+ * locks are taken in one order (sorted real paths), so two installs never wait
394
+ * on each other. Each lock sits next to the real file
395
+ * (`<real path>.brainbase-install.lock`),
396
+ * so installs run with different homes still share it. They follow the rules
397
+ * of the saved-login lock: a lock is only taken over when its holder no
398
+ * longer runs.
399
+ */
400
+ // Install locks sit next to settings files that other tools also keep files
401
+ // beside. They get a name of their own, and a file there that is not a lock
402
+ // record this code wrote is never removed: the install waits and says which
403
+ // file to check instead.
404
+ // The settings are no saved login, so taking this lock never runs the
405
+ // recovery of a login save or logout that stopped half way (recover: false).
406
+ const INSTALL_LOCK = { suffix: '.brainbase-install.lock', recover: false };
407
+ async function withInstallLocks(files, task) {
408
+ const keys = [...new Set(files)].sort();
409
+ const hold = async (index) => {
410
+ if (index === keys.length)
411
+ return await task();
412
+ try {
413
+ return await withCredentialsLock(keys[index], () => hold(index + 1), INSTALL_LOCK);
414
+ }
415
+ catch (error) {
416
+ if (error instanceof BrainbaseLoginError && error.code === 'login_busy') {
417
+ throw new Error(`Another judgment:install is changing ${files.join(' or ')}. Try again. If no judgment:install runs, remove ${keys[index]}${INSTALL_LOCK.suffix}.`);
418
+ }
419
+ throw error;
420
+ }
421
+ };
422
+ return await hold(0);
423
+ }
424
+ const SETTINGS_CHANGED_ATTEMPTS = 3;
425
+ const INSTALL_SETTINGS_BACKUP_SUFFIX = '.brainbase-install-previous';
426
+ // A settings symlink can be dangling precisely because its target was moved aside.
427
+ // Each link is followed the way the system does (settingsPathAsOpened), since a
428
+ // link's text such as `sub/../settings.json` names a file next to sub's target.
429
+ async function installSettingsTarget(path) {
430
+ try {
431
+ return realpathSync.native(path);
432
+ }
433
+ catch (error) {
434
+ if (error.code !== 'ENOENT')
435
+ throw error;
436
+ }
437
+ const seen = new Set();
438
+ let target = path;
439
+ while (!seen.has(target)) {
440
+ seen.add(target);
441
+ const destination = await readlink(target).catch((error) => {
442
+ if (error.code === 'ENOENT' || error.code === 'EINVAL')
443
+ return null;
444
+ throw error;
445
+ });
446
+ if (destination === null)
447
+ return target;
448
+ target = settingsPathAsOpened(isAbsolute(destination) ? destination : `${dirname(target)}${sep}${destination}`);
449
+ }
450
+ throw new Error(`${path} has a symbolic link loop`);
451
+ }
452
+ async function recoverInstallSettings(target) {
453
+ const current = await lstat(target).catch((error) => {
454
+ if (error.code === 'ENOENT')
455
+ return null;
456
+ throw error;
457
+ });
458
+ if (current)
459
+ return;
460
+ const directory = dirname(target);
461
+ const name = basename(target);
462
+ const entries = await readdir(directory).catch((error) => {
463
+ if (error.code === 'ENOENT')
464
+ return [];
465
+ throw error;
466
+ });
467
+ // Older installers added a PID and eight hex digits before the suffix.
468
+ const backups = entries.filter((entry) => entry === name + INSTALL_SETTINGS_BACKUP_SUFFIX
469
+ || (entry.startsWith(name) && /^\.\d+\.[0-9a-f]{8}\.brainbase-install-previous$/u.test(entry.slice(name.length))));
470
+ if (backups.length === 0)
471
+ return;
472
+ if (backups.length !== 1) {
473
+ throw new Error(`${target} has multiple judgment:install backups. Restore the correct settings file before retrying.`);
474
+ }
475
+ const backup = join(directory, backups[0]);
476
+ if (!(await lstat(backup)).isFile()) {
477
+ throw new Error(`${backup} is not a regular settings backup. Check the file before retrying.`);
478
+ }
479
+ try {
480
+ // A save by Claude Code made during recovery takes precedence.
481
+ await link(backup, target);
482
+ }
483
+ catch (error) {
484
+ if (error.code === 'EEXIST')
485
+ return;
486
+ throw error;
487
+ }
488
+ await rm(backup, { force: true });
489
+ }
490
+ /**
491
+ * Reads `path` (following links) only when it is a regular file; null when
492
+ * it does not exist. It is opened without waiting (a named pipe with no
493
+ * writer would otherwise hold the install, and its lock, forever) and its
494
+ * type is taken from the opened file, so a swap after the check is caught too.
495
+ */
496
+ async function readRegularFile(path, option) {
497
+ let handle;
498
+ try {
499
+ handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
500
+ }
501
+ catch (error) {
502
+ if (error?.code === 'ENOENT')
503
+ return null;
504
+ throw error;
505
+ }
506
+ try {
507
+ if (!(await handle.stat()).isFile()) {
508
+ throw new Error(`judgment:install ${option} ${path} は通常のファイルではありません(名前付きパイプ、デバイス、ディレクトリなど)。何も変えずに止めました。`);
509
+ }
510
+ return await handle.readFile('utf8');
511
+ }
512
+ finally {
513
+ await handle.close();
514
+ }
515
+ }
516
+ /** The file was saved by someone else after it was read; nothing was written over it. */
517
+ class SettingsChangedError extends Error {
518
+ }
519
+ /**
520
+ * A file brainbase writes for another use (a hook config, a saved login)
521
+ * carries brainbase's schema_version. Taking it as Claude Code settings would
522
+ * add hooks to it, and the registration that owns it would later replace it
523
+ * whole and drop them.
524
+ */
525
+ function brainbaseFileUse(value) {
526
+ const schema = value.schema_version;
527
+ if (schema === CLAUDE_CODE_HOOK_CONFIG_SCHEMA)
528
+ return '判断フックの設定';
529
+ if (schema === CREDENTIALS_SCHEMA_VERSION)
530
+ return 'brainbase login の保存ファイル';
531
+ if (typeof schema === 'string' && schema.startsWith('brainbase'))
532
+ return `brainbase のファイル(${schema})`;
533
+ return null;
534
+ }
535
+ async function applyClaudeCodeRegistration(plan, io) {
536
+ const { settingsPath, settingsReal, configPath, configReal, config, command, remove, dryRun } = plan;
537
+ let settings = {};
538
+ // The text as read, so the write can tell whether someone saved since.
539
+ const settingsText = await readRegularFile(settingsPath, '--settings');
540
+ if (settingsText !== null) {
541
+ const parsedSettings = JSON.parse(settingsText);
542
+ if (!parsedSettings || typeof parsedSettings !== 'object' || Array.isArray(parsedSettings)) {
543
+ throw new Error(`Claude Code settings is not a JSON object: ${settingsPath}`);
544
+ }
545
+ settings = parsedSettings;
546
+ }
547
+ const otherUse = brainbaseFileUse(settings);
548
+ if (otherUse) {
549
+ throw new Error(`judgment:install --settings ${settingsPath} は${otherUse}で、Claude Code の設定ではありません。何も変えずに止めました。Claude Code の settings.json を指定してください。`);
550
+ }
551
+ // The installer only overwrites or removes a config file it wrote itself.
552
+ // Read once, as a regular file; the checks below use this text and do not
553
+ // open the path again.
554
+ const previousConfig = await readRegularFile(configPath, '--config');
555
+ const configExists = previousConfig !== null;
556
+ const configOwned = configExists && isClaudeCodeHookConfigText(previousConfig);
557
+ if (!remove && configExists && !configOwned) {
558
+ throw new Error(`judgment:install --config ${configPath} exists and is not a brainbase hook config; choose another path`);
559
+ }
560
+ // A hook config belongs to the one settings file that registered it. Another
561
+ // settings file reusing it would redirect or, on removal, stop that
562
+ // registration's hooks.
563
+ const existingConfig = configOwned ? parseClaudeCodeHookConfig(previousConfig) : null;
564
+ const registeredElsewhere = configOwned && (existingConfig
565
+ ? canonicalFilePath(existingConfig.registration.settings) !== settingsReal
566
+ : !hasInstalledClaudeCodeHooks(settings, configPath));
567
+ if (!remove && registeredElsewhere) {
568
+ throw new Error(`judgment:install --config ${configPath} is used by ${existingConfig?.registration.settings ?? 'another registration'}; choose another --config for ${settingsPath}`);
569
+ }
570
+ if (remove && !hasInstalledClaudeCodeHooks(settings, configPath)) {
571
+ throw new Error(`judgment:install --remove found no registration for ${configPath} in ${settingsPath}; nothing was changed`);
572
+ }
573
+ const removedIds = new Set();
574
+ const next = registerClaudeCodeJudgmentHooks(settings, { command, configPath, remove, removedIds });
575
+ if (dryRun) {
576
+ // Only the change: the settings around it may hold secrets.
577
+ write(io, `${JSON.stringify({
578
+ settingsPath,
579
+ configPath,
580
+ config: config ?? null,
581
+ hooks: { add: remove ? [] : claudeCodeJudgmentHookGroups(command), remove_registration_ids: [...removedIds] },
582
+ }, null, 2)}\n`);
583
+ return 0;
584
+ }
585
+ if (remove) {
586
+ await replaceFileFollowingLinks(settingsPath, `${JSON.stringify(next, null, 2)}\n`, 0o600, settingsText);
587
+ // The config is deleted only when the registration it now carries was one
588
+ // of the commands just taken out; otherwise a command elsewhere still uses it.
589
+ const currentElsewhere = !!existingConfig && !removedIds.has(existingConfig.registration.id);
590
+ // The real file goes, not a link to it: a command that names the real
591
+ // path would otherwise still find its registration. The link is left.
592
+ if (configOwned && !registeredElsewhere && !currentElsewhere)
593
+ await rm(configReal, { force: true });
594
+ write(io, [
595
+ `Claude Codeの判断フックを外しました(${settingsPath})。`,
596
+ ...(configExists && !configOwned ? [`${configPath} は判断フックの設定ではないため、残しました。`] : []),
597
+ ...(registeredElsewhere ? [`${configPath} は ${existingConfig?.registration.settings ?? '別の登録'} の登録が使っているため、残しました。`] : []),
598
+ ...(!registeredElsewhere && currentElsewhere ? [`${configPath} は外した登録とは別の、いまの登録が使っているため、残しました。`] : []),
599
+ ''
600
+ ].join('\n'));
601
+ return 0;
602
+ }
603
+ // The config goes first: while the settings are not yet written, the new
604
+ // registration is not active, and an earlier one (whose command carries the
605
+ // old registration id) sends nothing rather than to the new destination.
606
+ // When writing the settings fails, the earlier config is put back, so the
607
+ // earlier registration keeps auditing where it did.
608
+ await mkdir(dirname(configPath), { recursive: true, mode: 0o700 });
609
+ await replaceFileFollowingLinks(configPath, `${JSON.stringify(config, null, 2)}\n`, 0o600);
610
+ try {
611
+ await replaceFileFollowingLinks(settingsPath, `${JSON.stringify(next, null, 2)}\n`, 0o600, settingsText);
612
+ }
613
+ catch (error) {
614
+ try {
615
+ if (previousConfig === null)
616
+ await rm(configPath, { force: true });
617
+ else
618
+ await replaceFileFollowingLinks(configPath, previousConfig, 0o600);
619
+ }
620
+ catch {
621
+ throw new Error(`${error instanceof Error ? error.message : String(error)}; ${configPath} could not be put back, run judgment:install again`);
622
+ }
623
+ throw error;
624
+ }
625
+ write(io, [
626
+ `Claude Codeの判断フックを登録しました(${settingsPath})。`,
627
+ `送り先: ${config.origin}`,
628
+ `project: ${config.project_code ?? 'Hostが決める'}`,
629
+ `対象のリポジトリ: ${config.repositories?.join(', ') ?? 'すべて'}`,
630
+ ...(await readCredentials(defaultCredentialsPath()).catch(() => null)
631
+ ? []
632
+ : ['まだログインしていません。brainbase login --server <API のURL> を実行してください。']),
633
+ 'Claude Codeを起動し直すと有効になります。',
634
+ ''
635
+ ].join('\n'));
636
+ return 0;
637
+ }
638
+ /**
639
+ * An option the user typed must carry a value. parseArgs turns `--opt` with no
640
+ * value (or `--opt ''`) into a bare flag; falling back to the default there would
641
+ * act on a path or server the user did not choose (logout would delete the
642
+ * default login). Stop before touching any file or the network.
643
+ */
644
+ function explicitValue(parsed, key, hint) {
645
+ if (parsed.flags.has(key))
646
+ throw new Error(`--${key} には値が要ります(${hint})。何も変えずに止めました。`);
647
+ // parseArgs keeps `--opt=value` whole as the key `opt=value`, so the option
648
+ // would look absent and the default would be used. Refuse that spelling.
649
+ const prefix = `${key}=`;
650
+ if ([...parsed.flags, ...parsed.values.keys()].some((name) => name.startsWith(prefix))) {
651
+ throw new Error(`--${key}=… の形は使えません。${hint} のように空白で区切ってください。何も変えずに止めました。`);
652
+ }
653
+ return first(parsed, key);
654
+ }
655
+ /**
656
+ * The login commands act on a saved login, so an argument they do not know must
657
+ * stop them. Ignoring a mistyped `--credntials other.json` would make logout fall
658
+ * back to the default path and delete the default login. Checked before the save
659
+ * path is decided, so nothing is read, removed or sent.
660
+ */
661
+ function assertOnlyLoginOptions(parsed, command, allowed) {
662
+ const usageHint = `brainbase ${command} ${allowed.map((key) => `[--${key} <${key === 'server' ? 'url' : 'path'}>]`).join(' ')}`;
663
+ const stop = (what) => new Error(`${what}。${usageHint} の形で指定してください。何も変えずに止めました。`);
664
+ // A known option without a value (or as --opt=value) gets its own, more precise message first.
665
+ for (const key of allowed)
666
+ explicitValue(parsed, key, `--${key} <${key === 'server' ? 'url' : 'path'}>`);
667
+ for (const name of [...parsed.flags, ...parsed.values.keys()]) {
668
+ // `--known=value` is refused by explicitValue with its own message.
669
+ const base = name.includes('=') ? name.slice(0, name.indexOf('=')) : name;
670
+ if (!allowed.includes(base))
671
+ throw stop(`${command} は --${base} というオプションを知りません`);
672
+ }
673
+ for (const [key, list] of parsed.values) {
674
+ if (list.length > 1)
675
+ throw stop(`--${key} が${list.length}回指定されています。1回だけにしてください`);
676
+ }
677
+ if (parsed.positionals.length > 0) {
678
+ throw stop(`${command} は「${parsed.positionals[0]}」のような引数を取りません`);
679
+ }
680
+ }
681
+ function credentialsPathOf(parsed) {
682
+ const path = explicitValue(parsed, 'credentials', '--credentials <path>') ?? defaultCredentialsPath();
683
+ assertCredentialsFilePath(path);
684
+ return path;
685
+ }
686
+ async function login(parsed, io) {
687
+ assertOnlyLoginOptions(parsed, 'login', ['credentials', 'server']);
688
+ const credentialsPath = credentialsPathOf(parsed);
689
+ const serverUrl = explicitValue(parsed, 'server', '--server <url>') ?? (await readCredentials(credentialsPath).catch(() => null))?.server_url;
690
+ if (!serverUrl)
691
+ throw new Error('login requires --server <url> (your Brainbase API URL)');
692
+ const credentials = await loginWithDeviceCode({
693
+ serverUrl,
694
+ credentialsPath,
695
+ onPrompt: (prompt) => {
696
+ write(io, [
697
+ 'ブラウザで次の URL を開き、ログインして承認してください。',
698
+ ` URL: ${prompt.verificationUriComplete ?? prompt.verificationUri}`,
699
+ ...(prompt.userCode ? [` コード: ${prompt.userCode}`] : []),
700
+ ` 期限: ${Math.round(prompt.expiresInSeconds / 60)} 分`,
701
+ '承認を待っています...',
702
+ ''
703
+ ].join('\n'));
704
+ }
705
+ });
706
+ write(io, `ログインしました(${credentials.server_url})。保存先: ${credentialsPath}\n`);
707
+ return 0;
708
+ }
709
+ async function loginStatus(parsed, io) {
710
+ assertOnlyLoginOptions(parsed, 'login:status', ['credentials']);
711
+ const credentialsPath = credentialsPathOf(parsed);
712
+ const credentials = await readCredentials(credentialsPath);
713
+ if (!credentials) {
714
+ write(io, 'ログインしていません。brainbase login --server <url> を実行してください。\n');
715
+ return 1;
716
+ }
717
+ const expired = Date.parse(credentials.expires_at) <= Date.now();
718
+ write(io, [
719
+ `サーバー: ${credentials.server_url}`,
720
+ `token の期限: ${credentials.expires_at}${expired ? '(切れています)' : ''}`,
721
+ `自動の更新: ${credentials.refresh_token ? 'できる' : 'できない(期限が来たら brainbase login をやり直す)'}`,
722
+ `保存先: ${credentialsPath}`,
723
+ ''
724
+ ].join('\n'));
725
+ return 0;
726
+ }
727
+ async function logout(parsed, io) {
728
+ assertOnlyLoginOptions(parsed, 'logout', ['credentials']);
729
+ const credentialsPath = credentialsPathOf(parsed);
730
+ let removed;
731
+ try {
732
+ removed = await removeCredentials(credentialsPath);
733
+ }
734
+ catch (error) {
735
+ if (error instanceof BrainbaseLoginError)
736
+ throw error; // login_busy and the like say what to do.
737
+ // The file may be gone in memory but not on disk: do not report a logout.
738
+ const code = error?.code ?? 'error';
739
+ writeError(io, `ログインを消したことを、ディスクに書き切れませんでした(${code})。brainbase logout をやり直してください。\n`);
740
+ return 1;
741
+ }
742
+ write(io, removed.existed ? `この端末のログインを消しました(${credentialsPath})。\n` : 'ログインはありませんでした。\n');
743
+ if (!removed.durable) {
744
+ writeError(io, 'この環境ではディレクトリをディスクに書き切れないため、電源が落ちると消したログインが戻ることがあります。\n');
745
+ }
746
+ return 0;
747
+ }
748
+ // Bytes are joined before decoding, so a character split across chunks stays intact.
749
+ export async function readHookStdin(input, maxBytes = Number.POSITIVE_INFINITY) {
750
+ const chunks = [];
751
+ let bytes = 0;
752
+ for await (const chunk of input) {
753
+ const buffer = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk);
754
+ bytes += buffer.length;
755
+ if (bytes > maxBytes)
756
+ throw new Error('judgment_hook_payload_too_large');
757
+ chunks.push(buffer);
758
+ }
759
+ return Buffer.concat(chunks).toString('utf8');
760
+ }
761
+ // The real path of a file, or of its nearest existing parent joined with the
762
+ // rest, so two spellings of one file (symlinks, `..`) compare equal.
763
+ /**
764
+ * Replaces the file at `path` atomically. When `path` is a symbolic link, the
765
+ * file it points to is replaced and the link stays; a link to nothing is
766
+ * refused. A file that exists keeps its mode; a new one gets `mode`.
767
+ *
768
+ * With `expected` (the text read earlier, or null for "did not exist"), the
769
+ * file is only replaced while it still holds that text (swapInIfUnchanged);
770
+ * otherwise a save made since stays and SettingsChangedError is thrown.
771
+ */
772
+ async function replaceFileFollowingLinks(path, content, mode, expected) {
773
+ let target = resolve(path);
774
+ let targetMode = mode;
775
+ try {
776
+ target = await realpath(target);
777
+ targetMode = (await stat(target)).mode & 0o777;
778
+ }
779
+ catch (error) {
780
+ if (error?.code !== 'ENOENT')
781
+ throw error;
782
+ const link = await lstat(target).catch(() => null);
783
+ if (link?.isSymbolicLink())
784
+ throw new Error(`${path} is a symbolic link to a missing file; nothing was changed`);
785
+ await mkdir(dirname(target), { recursive: true });
786
+ }
787
+ const temporary = `${target}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
788
+ try {
789
+ await writeFile(temporary, content, { mode: targetMode, flag: 'wx' });
790
+ await chmod(temporary, targetMode);
791
+ if (expected === undefined)
792
+ await rename(temporary, target);
793
+ else {
794
+ await swapInIfUnchanged(path, target, temporary, content, expected);
795
+ await rm(temporary, { force: true });
796
+ }
797
+ }
798
+ catch (error) {
799
+ await rm(temporary, { force: true });
800
+ throw error;
801
+ }
802
+ }
803
+ /**
804
+ * Puts `temporary` at `target` only when `target` still holds `expected`.
805
+ * Claude Code saves its settings without our lock, and rename() replaces
806
+ * whatever is there, so a check followed by rename() would overwrite a save
807
+ * made in between. Instead the file there is first moved aside (rename is
808
+ * atomic, so exactly the file present at that moment is taken), ours is
809
+ * placed with link(), which never replaces a file, and only then is the
810
+ * file taken out compared. The rule is that a save someone else made always
811
+ * stays: when what was taken out is not what was read, it goes back; when a
812
+ * file appeared at `target` meanwhile, that file stays and ours is dropped.
813
+ * Either way SettingsChangedError is thrown and the caller starts again from
814
+ * the saved file. Nothing here replaces a file that is not ours.
815
+ */
816
+ async function swapInIfUnchanged(path, target, temporary, content, expected) {
817
+ const changed = () => new SettingsChangedError(`${path} was saved by someone else while it was being changed; nothing was written over it`);
818
+ const tag = `${process.pid}.${randomBytes(4).toString('hex')}`;
819
+ // A file system without hard links fails here, before the settings are touched.
820
+ const probe = `${temporary}.link`;
821
+ await link(temporary, probe);
822
+ await rm(probe, { force: true });
823
+ const placeOurs = async () => {
824
+ try {
825
+ await link(temporary, target);
826
+ return true;
827
+ }
828
+ catch (error) {
829
+ if (error?.code === 'EEXIST')
830
+ return false;
831
+ throw error;
832
+ }
833
+ };
834
+ if (expected === null) {
835
+ if (!(await placeOurs()))
836
+ throw changed();
837
+ }
838
+ else {
839
+ const aside = target + INSTALL_SETTINGS_BACKUP_SUFFIX;
840
+ // rename() replaces whatever is at `aside`. A file already there is a
841
+ // backup from an earlier run that someone may still need; keep it.
842
+ if (await lstat(aside).then(() => true, (error) => {
843
+ if (error?.code === 'ENOENT')
844
+ return false;
845
+ throw error;
846
+ })) {
847
+ throw new Error(`${aside} が残っているため、上書きせずに止めました。中身を確かめて、要らなければ消してから、もう一度実行してください。${path} は変えていません。`);
848
+ }
849
+ try {
850
+ await rename(target, aside);
851
+ }
852
+ catch (error) {
853
+ if (error?.code === 'ENOENT')
854
+ throw changed();
855
+ throw error;
856
+ }
857
+ let placed;
858
+ try {
859
+ placed = await placeOurs();
860
+ }
861
+ catch (error) {
862
+ await putBackIfFree(aside, target).catch(() => rename(aside, target));
863
+ throw error;
864
+ }
865
+ if (!placed) {
866
+ // Saved while the file was aside: that save is the newest and stays.
867
+ await rm(aside, { force: true });
868
+ throw changed();
869
+ }
870
+ const taken = await readFile(aside, 'utf8');
871
+ if (taken !== expected) {
872
+ // What was taken out is a save made after our read. Take ours out again
873
+ // and give that save back, unless an even newer one has replaced ours.
874
+ const ours = `${target}.${tag}.brainbase-install-ours`;
875
+ await rename(target, ours).catch(() => undefined);
876
+ const back = await readFile(ours, 'utf8').catch(() => null);
877
+ if (back === null || back === content)
878
+ await putBackIfFree(aside, target);
879
+ else
880
+ await putBackIfFree(ours, target);
881
+ await rm(ours, { force: true });
882
+ await rm(aside, { force: true });
883
+ throw changed();
884
+ }
885
+ await rm(aside, { force: true });
886
+ }
887
+ // A writer that replaces the file in place right after ours was placed
888
+ // leaves its own text; start again from it so the hooks are not missing.
889
+ if ((await readFile(target, 'utf8').catch(() => null)) !== content)
890
+ throw changed();
891
+ }
892
+ /** Puts `from` back at `target` unless a file has appeared there; `from` is then left to the caller. */
893
+ async function putBackIfFree(from, target) {
894
+ try {
895
+ await link(from, target);
896
+ }
897
+ catch (error) {
898
+ if (error?.code !== 'EEXIST')
899
+ throw error;
900
+ }
901
+ await rm(from, { force: true });
206
902
  }
207
903
  function textOrJsonFormat(parsed, command) {
208
904
  const format = first(parsed, 'format') ?? 'text';
@@ -1103,9 +1799,12 @@ function parseArgs(argv) {
1103
1799
  const rest = command ? remaining : argv;
1104
1800
  const values = new Map();
1105
1801
  const flags = new Set();
1802
+ const positionals = [];
1106
1803
  for (let index = 0; index < rest.length; index += 1) {
1107
1804
  const token = rest[index];
1108
1805
  if (!token?.startsWith('--')) {
1806
+ if (token !== undefined)
1807
+ positionals.push(token);
1109
1808
  continue;
1110
1809
  }
1111
1810
  const key = token.slice(2);
@@ -1120,7 +1819,8 @@ function parseArgs(argv) {
1120
1819
  return {
1121
1820
  command,
1122
1821
  values,
1123
- flags
1822
+ flags,
1823
+ positionals
1124
1824
  };
1125
1825
  }
1126
1826
  function first(parsed, key) {
@@ -1230,7 +1930,12 @@ function usage() {
1230
1930
  brainbase memory:register --id id [--id id...] [--dir path] [--write] [--format text|json]
1231
1931
  brainbase ontology:migrate [--dir path] [--write --expected-input-digest digest]
1232
1932
  brainbase judgment:install --target codex [--autonomy-mode off|canary|on] [--autonomy-project code] [--dry-run] [--output path]
1933
+ brainbase judgment:install --target claude-code --origin url [--server url] [--project code] [--repositories name,name] [--settings path] [--config path] [--dry-run] [--remove]
1934
+ brainbase judgment:claude-code-hook [--config path]
1233
1935
  brainbase judgment:hook [--autonomy-mode off|canary|on] [--autonomy-project code]
1936
+ brainbase login --server url [--credentials path]
1937
+ brainbase login:status [--credentials path]
1938
+ brainbase logout [--credentials path]
1234
1939
  brainbase doctor [--dir path] [--judgment-hooks path]
1235
1940
  brainbase web:serve [--dir path] [--journal path] [--port n] [--world [--world-vocabulary file]]
1236
1941
  brainbase review:serve [--dir path] [--journal path] [--port n] (web:serveの別名)