@unson/brainbase-mcp 0.51.2 → 0.51.4

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.
@@ -291,7 +291,8 @@
291
291
  "ontology:audit",
292
292
  "ontology:migrate",
293
293
  "ontology:show",
294
- "web:serve"
294
+ "web:serve",
295
+ "world-model:revalidation-queue"
295
296
  ],
296
297
  "aliases": {
297
298
  "review:serve": "web:serve"
@@ -105,6 +105,7 @@ export declare function isAntigravityHookConfigText(text: string): boolean;
105
105
  * - `call_mcp_tool` with `ServerName` matching `^brainbase(?:-.+)?$` -> `mcp__brainbase__<ToolName>`
106
106
  */
107
107
  export declare function normalizeAntigravityToolName(name: string, args?: unknown): string;
108
+ declare function normalizedToolInput(rawName: string, normalizedName: string, args: unknown): unknown;
108
109
  interface TranscriptEntry {
109
110
  step_index?: unknown;
110
111
  tool_use_id?: unknown;
@@ -178,6 +179,12 @@ export interface TurnStateLockOptions {
178
179
  declare function withTurnStateLock<T>(env: NodeJS.ProcessEnv, key: string, fn: () => T | Promise<T>, options?: TurnStateLockOptions): Promise<T>;
179
180
  /** Namespaces session and turn IDs per registration, matching Claude Code isolation. */
180
181
  export declare function antigravityNamespacedId(id: string, config: Pick<AntigravityHookConfig, 'registration'>): string;
182
+ /**
183
+ * Formats a Brainbase judgment context as an Antigravity `injectSteps` entry.
184
+ * Because `systemMessage` persists in Antigravity's conversation trajectory across turns,
185
+ * the header binds it to the current `turn_id` and explicitly supersedes earlier turns.
186
+ */
187
+ declare function buildSystemMessageStep(turnId: string, additionalContext?: string, userMarkdown?: string): Record<string, unknown> | null;
181
188
  /** Handles one Antigravity lifecycle hook event. Never throws. */
182
189
  export declare function handleAntigravityJudgmentHook(payload: AntigravityHookPayload, options?: AntigravityHookOptions): Promise<AntigravityHookOutput>;
183
190
  /** Builds the POSIX-quoted command registered in Antigravity `hooks.json`. */
@@ -203,6 +210,8 @@ export declare function registerAntigravityJudgmentHooks(hooksJson: Record<strin
203
210
  }): Record<string, unknown>;
204
211
  /** @internal Exposed strictly for deterministic concurrency and TOCTOU regression tests. */
205
212
  export declare const __antigravityHookTestInternals: {
213
+ buildSystemMessageStep: typeof buildSystemMessageStep;
214
+ normalizedToolInput: typeof normalizedToolInput;
206
215
  withTurnStateLock: typeof withTurnStateLock;
207
216
  readTranscriptTailEntries: typeof readTranscriptTailEntries;
208
217
  resolveOpenatHelperBinary: typeof resolveOpenatHelperBinary;
@@ -18,7 +18,7 @@
18
18
  // 5. Base URLs with path prefixes (e.g. `https://bb.unson.jp/runtime-mcp`) preserve their
19
19
  // path when resolving `host/judgment/hook`.
20
20
  // 6. Strict fail-open outputs with short HTTP timeouts:
21
- // - PreInvocation: `{}` (or `{ injectSteps: [{ systemMessage: { systemMessage, metadata? } }], terminationBehavior: '' }`)
21
+ // - PreInvocation: `{}` (or `{ injectSteps: [{ systemMessage: { systemMessage } }], terminationBehavior: '' }`)
22
22
  // - PreToolUse: `{ decision: 'allow' }` (or `{ decision: 'deny', reason }`)
23
23
  // - PostToolUse: ALWAYS `{}` (any follow-up context is queued with `turn_id` for next PreInvocation)
24
24
  // - Stop: ALWAYS `{ decision: '' }` (never `"continue"`)
@@ -26,7 +26,7 @@ import { spawn, spawnSync } from 'node:child_process';
26
26
  import { createHash, randomUUID } from 'node:crypto';
27
27
  import { accessSync, closeSync, constants as fsConstants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
28
28
  import { homedir } from 'node:os';
29
- import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
29
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
30
30
  import { fileURLToPath } from 'node:url';
31
31
  import { BrainbaseLoginError, getAccessTokenOfLogin } from './brainbase-login.js';
32
32
  import { PRE_TOOL_USE_TOOLS, REGISTRATION_ID, bearerTransportSafe, canonicalFilePath, canonicalRepositoryIdentifier, digestSummary, forwardedStopPayload, hostCanMapRepository, resolveRepositoryScope, shellQuote, singleQuotedWords, } from './claude-code-judgment-hook.js';
@@ -275,16 +275,35 @@ export function normalizeAntigravityToolName(name, args) {
275
275
  }
276
276
  return trimmed;
277
277
  }
278
+ function isPlainToolRecord(value) {
279
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
280
+ }
281
+ /**
282
+ * Strips Antigravity's synthetic UI metadata key (`toolSummary`) from
283
+ * Brainbase MCP tool inputs while leaving all other keys intact so
284
+ * Host-side strict validation continues to enforce exact tool schemas.
285
+ */
286
+ function stripAntigravitySyntheticToolKeys(value) {
287
+ if (!isPlainToolRecord(value))
288
+ return value;
289
+ if (!Object.hasOwn(value, 'toolSummary'))
290
+ return value;
291
+ const copy = { ...value };
292
+ delete copy.toolSummary;
293
+ return copy;
294
+ }
278
295
  function normalizedToolInput(rawName, normalizedName, args) {
279
- if (rawName === 'call_mcp_tool' && normalizedName.startsWith('mcp__brainbase__')
280
- && args && typeof args === 'object' && !Array.isArray(args)) {
281
- const record = args;
282
- if ('Arguments' in record)
283
- return record.Arguments;
284
- if ('arguments' in record)
285
- return record.arguments;
296
+ let unwrapped = args ?? {};
297
+ if (rawName === 'call_mcp_tool' && normalizedName.startsWith('mcp__brainbase__') && isPlainToolRecord(args)) {
298
+ if ('Arguments' in args)
299
+ unwrapped = args.Arguments;
300
+ else if ('arguments' in args)
301
+ unwrapped = args.arguments;
286
302
  }
287
- return args ?? {};
303
+ if (normalizedName.startsWith('mcp__brainbase__')) {
304
+ return stripAntigravitySyntheticToolKeys(unwrapped);
305
+ }
306
+ return unwrapped;
288
307
  }
289
308
  // ---- Scope resolution (git + non-git + cwd_prefixes) ----
290
309
  function stripTrailingSeparator(pathValue) {
@@ -679,6 +698,121 @@ function resolveAuthorizedTranscriptTarget(transcriptPath, options) {
679
698
  function resolveAuthorizedTranscriptPath(transcriptPath, options) {
680
699
  return resolveAuthorizedTranscriptTarget(transcriptPath, options)?.canonicalPath ?? null;
681
700
  }
701
+ function isEnoentError(error) {
702
+ return !!error && typeof error === 'object' && error.code === 'ENOENT';
703
+ }
704
+ /**
705
+ * Resolves an authorized transcript location ONLY when the transcript file itself
706
+ * does not exist yet (`ENOENT`), e.g. on the first tool call before Antigravity
707
+ * flushes `logs/transcript.jsonl` while `steps/<n>/output.txt` already exists.
708
+ *
709
+ * Strictly enforces the same canonical root, conversation structure, and
710
+ * no-symlink ancestor invariants; fails closed if the file exists (and was
711
+ * already rejected by `resolveAuthorizedTranscriptTarget`), contains `.`/`..`,
712
+ * or traverses any symlink inside the authorized root.
713
+ */
714
+ function resolveAuthorizedMissingTranscriptTarget(transcriptPath, options) {
715
+ if (typeof transcriptPath !== 'string' || !transcriptPath.trim() || transcriptPath.includes('\0')) {
716
+ return null;
717
+ }
718
+ const conversationId = options?.conversationId?.trim() ?? '';
719
+ if (!isSafeConversationIdSegment(conversationId))
720
+ return null;
721
+ const rawPath = transcriptPath.trim();
722
+ if (!isAbsolute(rawPath))
723
+ return null;
724
+ const rawSegments = rawPath.split(/[/\\]/u);
725
+ if (rawSegments.includes('..') || rawSegments.includes('.')) {
726
+ return null;
727
+ }
728
+ try {
729
+ lstatSync(rawPath);
730
+ return null;
731
+ }
732
+ catch (error) {
733
+ if (!isEnoentError(error))
734
+ return null;
735
+ }
736
+ const fileName = basename(rawPath);
737
+ if (!ALLOWED_TRANSCRIPT_FILENAMES.has(fileName) || !isSafePathSegment(fileName)) {
738
+ return null;
739
+ }
740
+ let candidateCanonical = null;
741
+ const parentDir = dirname(rawPath);
742
+ try {
743
+ const parentStat = lstatSync(parentDir);
744
+ if (parentStat.isSymbolicLink() || !parentStat.isDirectory())
745
+ return null;
746
+ candidateCanonical = join(realpathSync(parentDir), fileName);
747
+ }
748
+ catch (error) {
749
+ if (!isEnoentError(error))
750
+ return null;
751
+ const parentName = basename(parentDir);
752
+ if (parentName !== 'logs' || !isSafePathSegment(parentName))
753
+ return null;
754
+ const grandParentDir = dirname(parentDir);
755
+ try {
756
+ const grandStat = lstatSync(grandParentDir);
757
+ if (grandStat.isSymbolicLink() || !grandStat.isDirectory())
758
+ return null;
759
+ candidateCanonical = join(realpathSync(grandParentDir), parentName, fileName);
760
+ }
761
+ catch {
762
+ return null;
763
+ }
764
+ }
765
+ if (!candidateCanonical)
766
+ return null;
767
+ const roots = canonicalTranscriptRoots(options);
768
+ if (roots.length === 0)
769
+ return null;
770
+ const matchedRoot = roots.find((root) => (root !== sep
771
+ && root !== '/'
772
+ && matchesConversationTranscriptStructure(root, candidateCanonical, conversationId)));
773
+ if (!matchedRoot)
774
+ return null;
775
+ try {
776
+ const rootStat = lstatSync(matchedRoot);
777
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory())
778
+ return null;
779
+ if (realpathSync(matchedRoot) !== matchedRoot)
780
+ return null;
781
+ }
782
+ catch {
783
+ return null;
784
+ }
785
+ const segments = relative(matchedRoot, candidateCanonical).split(sep);
786
+ if (segments.length === 0 || !segments.every(isSafePathSegment))
787
+ return null;
788
+ let current = matchedRoot;
789
+ let sawMissingDir = false;
790
+ for (let i = 0; i < segments.length - 1; i += 1) {
791
+ current = join(current, segments[i]);
792
+ if (sawMissingDir)
793
+ return null;
794
+ try {
795
+ const dirStat = lstatSync(current);
796
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory())
797
+ return null;
798
+ }
799
+ catch (error) {
800
+ if (!isEnoentError(error) || i !== segments.length - 2 || segments[i] !== 'logs') {
801
+ return null;
802
+ }
803
+ sawMissingDir = true;
804
+ }
805
+ }
806
+ try {
807
+ lstatSync(candidateCanonical);
808
+ return null;
809
+ }
810
+ catch (error) {
811
+ if (!isEnoentError(error))
812
+ return null;
813
+ }
814
+ return { canonicalRoot: matchedRoot, canonicalPath: candidateCanonical, segments };
815
+ }
682
816
  function buildPythonOpenatReader(faults, mode = 'tail') {
683
817
  const forceOpenat2Errno = faults?.forceOpenat2Errno;
684
818
  const renameAfterRead = faults?.renameAfterTailRead;
@@ -1222,82 +1356,120 @@ function resolveSiblingFullTranscriptTarget(baseTarget, options) {
1222
1356
  }
1223
1357
  function resolveAuthorizedStepOutputTarget(baseTarget, conversationId, candidatePath) {
1224
1358
  if (!candidatePath || !isAbsolute(candidatePath) || candidatePath.includes('\0')) {
1225
- return null;
1359
+ return { kind: 'rejected' };
1226
1360
  }
1227
1361
  const sysGenSegments = systemGeneratedPrefixSegments(baseTarget, conversationId);
1228
1362
  if (!sysGenSegments)
1229
- return null;
1363
+ return { kind: 'rejected' };
1230
1364
  const stepsDirRaw = join(baseTarget.canonicalRoot, ...sysGenSegments, 'steps');
1231
1365
  try {
1232
- const stepsDirStat = lstatSync(stepsDirRaw);
1366
+ let stepsDirStat;
1367
+ try {
1368
+ stepsDirStat = lstatSync(stepsDirRaw);
1369
+ }
1370
+ catch (error) {
1371
+ return isEnoentError(error) ? { kind: 'missing' } : { kind: 'rejected' };
1372
+ }
1233
1373
  if (stepsDirStat.isSymbolicLink() || !stepsDirStat.isDirectory())
1234
- return null;
1374
+ return { kind: 'rejected' };
1235
1375
  const stepsDir = realpathSync(stepsDirRaw);
1236
1376
  if (stepsDir !== stepsDirRaw || !isStrictDescendantPath(baseTarget.canonicalRoot, stepsDir)) {
1237
- return null;
1377
+ return { kind: 'rejected' };
1378
+ }
1379
+ let candidateParentStat;
1380
+ try {
1381
+ candidateParentStat = lstatSync(dirname(candidatePath));
1382
+ }
1383
+ catch (error) {
1384
+ return isEnoentError(error) ? { kind: 'missing' } : { kind: 'rejected' };
1238
1385
  }
1239
- const candidateParentStat = lstatSync(dirname(candidatePath));
1240
1386
  if (candidateParentStat.isSymbolicLink() || !candidateParentStat.isDirectory())
1241
- return null;
1242
- const candidateStat = lstatSync(candidatePath);
1387
+ return { kind: 'rejected' };
1388
+ let candidateStat;
1389
+ try {
1390
+ candidateStat = lstatSync(candidatePath);
1391
+ }
1392
+ catch (error) {
1393
+ return isEnoentError(error) ? { kind: 'missing' } : { kind: 'rejected' };
1394
+ }
1243
1395
  if (candidateStat.isSymbolicLink() || !candidateStat.isFile())
1244
- return null;
1396
+ return { kind: 'rejected' };
1245
1397
  const canonicalFile = realpathSync(candidatePath);
1246
1398
  if (!isStrictDescendantPath(stepsDir, canonicalFile))
1247
- return null;
1399
+ return { kind: 'rejected' };
1248
1400
  const relFromSteps = relative(stepsDir, canonicalFile).split(sep);
1249
1401
  if (relFromSteps.length !== 2 || !/^\d+$/u.test(relFromSteps[0]) || relFromSteps[1] !== 'output.txt') {
1250
- return null;
1402
+ return { kind: 'rejected' };
1251
1403
  }
1252
1404
  if (!verifyNoSymlinkPathUnderRoot(baseTarget.canonicalRoot, canonicalFile).ok) {
1253
- return null;
1405
+ return { kind: 'rejected' };
1254
1406
  }
1255
1407
  return {
1256
- canonicalRoot: baseTarget.canonicalRoot,
1257
- canonicalPath: canonicalFile,
1258
- segments: [...sysGenSegments, 'steps', relFromSteps[0], 'output.txt'],
1408
+ kind: 'ok',
1409
+ target: {
1410
+ canonicalRoot: baseTarget.canonicalRoot,
1411
+ canonicalPath: canonicalFile,
1412
+ segments: [...sysGenSegments, 'steps', relFromSteps[0], 'output.txt'],
1413
+ },
1259
1414
  };
1260
1415
  }
1261
1416
  catch {
1262
- return null;
1417
+ return { kind: 'rejected' };
1263
1418
  }
1264
1419
  }
1420
+ function isToolResultEntry(entry) {
1421
+ if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
1422
+ return false;
1423
+ return typeof entry.content === 'string' && entry.content.trim().length > 0;
1424
+ }
1425
+ function hasStepIndexInTranscript(entries, stepIdx) {
1426
+ return entries.some((entry) => entry.step_index === stepIdx);
1427
+ }
1428
+ function hasConflictingToolUseIdAtStep(entries, stepIdx, toolUseId) {
1429
+ return entries.some((entry) => {
1430
+ if (entry.step_index !== stepIdx)
1431
+ return false;
1432
+ const entryId = entryToolUseId(entry);
1433
+ return entryId !== null && entryId !== toolUseId;
1434
+ });
1435
+ }
1265
1436
  function findToolEntryInTranscript(entries, stepCandidates, toolUseId) {
1266
1437
  const normalizedToolUseId = typeof toolUseId === 'string' && toolUseId.trim() ? toolUseId.trim() : null;
1267
- for (const targetStep of stepCandidates) {
1268
- if (normalizedToolUseId !== null) {
1438
+ // 1. Prefer exact tool_use_id / tool_call_id match on step candidates first.
1439
+ if (normalizedToolUseId !== null) {
1440
+ for (const targetStep of stepCandidates) {
1269
1441
  for (let index = entries.length - 1; index >= 0; index -= 1) {
1270
1442
  const entry = entries[index];
1271
- if (entry.step_index !== targetStep)
1272
- continue;
1273
- if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
1274
- continue;
1275
- if (typeof entry.content !== 'string' || !entry.content.trim())
1443
+ if (entry.step_index !== targetStep || !isToolResultEntry(entry))
1276
1444
  continue;
1277
1445
  if (entryToolUseId(entry) === normalizedToolUseId)
1278
1446
  return entry;
1279
1447
  }
1280
1448
  }
1449
+ // 2. Fall back to exact tool_use_id / tool_call_id match anywhere in the transcript tail
1450
+ // (handles step_index shifts between transcript.jsonl and transcript_full.jsonl).
1281
1451
  for (let index = entries.length - 1; index >= 0; index -= 1) {
1282
1452
  const entry = entries[index];
1283
- if (entry.step_index !== targetStep)
1284
- continue;
1285
- if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
1286
- continue;
1287
- if (typeof entry.content !== 'string' || !entry.content.trim())
1453
+ if (!isToolResultEntry(entry))
1288
1454
  continue;
1289
- return entry;
1455
+ if (entryToolUseId(entry) === normalizedToolUseId)
1456
+ return entry;
1290
1457
  }
1291
1458
  }
1292
- if (normalizedToolUseId !== null) {
1459
+ // 3. Untagged step_index match is strictly restricted to the exact primary step (`stepCandidates[0]`).
1460
+ // Never match a neighboring step (`stepIdx + 1`) without an explicit tool_use_id match, and
1461
+ // never match an entry whose explicit tool_use_id disagrees with the caller's toolUseId.
1462
+ const primaryStep = stepCandidates[0];
1463
+ if (primaryStep !== undefined) {
1293
1464
  for (let index = entries.length - 1; index >= 0; index -= 1) {
1294
1465
  const entry = entries[index];
1295
- if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
1466
+ if (entry.step_index !== primaryStep || !isToolResultEntry(entry))
1296
1467
  continue;
1297
- if (typeof entry.content !== 'string' || !entry.content.trim())
1468
+ const entryId = entryToolUseId(entry);
1469
+ if (normalizedToolUseId !== null && entryId !== null && entryId !== normalizedToolUseId) {
1298
1470
  continue;
1299
- if (entryToolUseId(entry) === normalizedToolUseId)
1300
- return entry;
1471
+ }
1472
+ return entry;
1301
1473
  }
1302
1474
  }
1303
1475
  return null;
@@ -1333,10 +1505,10 @@ function readStepOutputFallback(baseTarget, conversationId, referenceTexts, cand
1333
1505
  const filePath = parseLocalFileUrlPath(explicitUrl);
1334
1506
  if (!filePath)
1335
1507
  return null;
1336
- const stepTarget = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, filePath);
1337
- if (!stepTarget)
1508
+ const resolution = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, filePath);
1509
+ if (resolution.kind !== 'ok')
1338
1510
  return null;
1339
- return readTarget(stepTarget);
1511
+ return readTarget(resolution.target);
1340
1512
  }
1341
1513
  const sysGenSegments = systemGeneratedPrefixSegments(baseTarget, conversationId);
1342
1514
  if (!sysGenSegments)
@@ -1348,55 +1520,73 @@ function readStepOutputFallback(baseTarget, conversationId, referenceTexts, cand
1348
1520
  continue;
1349
1521
  seenSteps.add(stepNum);
1350
1522
  const candidatePath = join(stepsDir, String(stepNum), 'output.txt');
1351
- const stepTarget = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, candidatePath);
1352
- if (!stepTarget)
1523
+ const resolution = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, candidatePath);
1524
+ if (resolution.kind === 'missing')
1353
1525
  continue;
1354
- const recovered = readTarget(stepTarget);
1355
- if (recovered !== null)
1356
- return recovered;
1526
+ if (resolution.kind === 'rejected')
1527
+ return null;
1528
+ // Candidate file exists and passed path checks; fail closed immediately if reading fails
1529
+ // (oversized >512 KiB, empty, truncation banner, non-Linux, or openat2 rejection) rather
1530
+ // than falling through to another step's output.
1531
+ return readTarget(resolution.target);
1357
1532
  }
1358
1533
  return null;
1359
1534
  }
1360
1535
  export function extractToolResultFromTranscript(transcriptPath, stepIdx, options) {
1361
- const hasStepIdx = typeof stepIdx === 'number' && Number.isSafeInteger(stepIdx);
1536
+ const hasStepIdx = typeof stepIdx === 'number' && Number.isSafeInteger(stepIdx) && stepIdx >= 0;
1362
1537
  const hintToolUseId = typeof options?.toolUseId === 'string' && options.toolUseId.trim()
1363
1538
  ? options.toolUseId.trim()
1364
1539
  : undefined;
1365
1540
  if (!hasStepIdx && !hintToolUseId)
1366
1541
  return null;
1367
- const baseTarget = resolveAuthorizedTranscriptTarget(transcriptPath, options);
1368
- if (!baseTarget || !options)
1542
+ if (!options)
1543
+ return null;
1544
+ const existingBaseTarget = resolveAuthorizedTranscriptTarget(transcriptPath, options);
1545
+ const baseTarget = existingBaseTarget ?? resolveAuthorizedMissingTranscriptTarget(transcriptPath, options);
1546
+ if (!baseTarget)
1369
1547
  return null;
1370
1548
  const conversationId = options.conversationId.trim();
1371
- const baseEntries = readTranscriptEntriesFromTarget(baseTarget, options, TRANSCRIPT_TAIL_MAX_BYTES);
1372
- // Prefer exact step_index match, then immediate neighbor (+1) if wrapper shifted index.
1373
1549
  const stepCandidates = hasStepIdx ? [stepIdx, stepIdx + 1] : [];
1374
- const matchedEntry = findToolEntryInTranscript(baseEntries, stepCandidates, hintToolUseId);
1375
- if (!matchedEntry || typeof matchedEntry.content !== 'string')
1376
- return null;
1377
- const baseStripped = stripToolTimestampHeader(matchedEntry.content);
1378
- if (!baseStripped)
1379
- return null;
1380
- if (!isTruncatedToolResult(matchedEntry, baseStripped)) {
1381
- return Buffer.byteLength(baseStripped, 'utf8') <= TRANSCRIPT_TOOL_RESULT_MAX_BYTES
1382
- ? baseStripped
1383
- : null;
1550
+ let baseEntries = [];
1551
+ let matchedEntry = null;
1552
+ let baseStripped = null;
1553
+ if (existingBaseTarget !== null) {
1554
+ baseEntries = readTranscriptEntriesFromTarget(existingBaseTarget, options, TRANSCRIPT_TAIL_MAX_BYTES);
1555
+ matchedEntry = findToolEntryInTranscript(baseEntries, stepCandidates, hintToolUseId);
1556
+ if (matchedEntry && typeof matchedEntry.content === 'string') {
1557
+ const stripped = stripToolTimestampHeader(matchedEntry.content);
1558
+ if (stripped) {
1559
+ if (!isTruncatedToolResult(matchedEntry, stripped)) {
1560
+ return Buffer.byteLength(stripped, 'utf8') <= TRANSCRIPT_TOOL_RESULT_MAX_BYTES
1561
+ ? stripped
1562
+ : null;
1563
+ }
1564
+ baseStripped = stripped;
1565
+ }
1566
+ }
1384
1567
  }
1385
- const matchedStep = typeof matchedEntry.step_index === 'number' && Number.isSafeInteger(matchedEntry.step_index)
1568
+ const matchedStep = matchedEntry && typeof matchedEntry.step_index === 'number' && Number.isSafeInteger(matchedEntry.step_index)
1386
1569
  ? matchedEntry.step_index
1387
1570
  : null;
1388
1571
  const effectiveStepCandidates = [
1389
1572
  ...(matchedStep !== null ? [matchedStep] : []),
1390
1573
  ...stepCandidates.filter((step) => step !== matchedStep),
1391
1574
  ];
1392
- const effectiveToolUseId = entryToolUseId(matchedEntry) ?? hintToolUseId;
1393
- // 1. Prefer sibling `transcript_full.jsonl` in the exact same authorized logs directory.
1575
+ const effectiveToolUseId = (matchedEntry ? entryToolUseId(matchedEntry) : null) ?? hintToolUseId;
1576
+ // 1. Prefer sibling `transcript_full.jsonl` in the exact same authorized logs directory
1577
+ // (handles both truncated `transcript.jsonl` entries and steps not yet flushed to `transcript.jsonl`).
1578
+ let fullEntries = [];
1579
+ let fullEntry = null;
1394
1580
  let fullStripped = null;
1581
+ let fullMatchedStep = null;
1395
1582
  const fullTarget = resolveSiblingFullTranscriptTarget(baseTarget, options);
1396
1583
  if (fullTarget) {
1397
- const fullEntries = readTranscriptEntriesFromTarget(fullTarget, options, TRANSCRIPT_FULL_TAIL_MAX_BYTES);
1398
- const fullEntry = findToolEntryInTranscript(fullEntries, effectiveStepCandidates, effectiveToolUseId);
1584
+ fullEntries = readTranscriptEntriesFromTarget(fullTarget, options, TRANSCRIPT_FULL_TAIL_MAX_BYTES);
1585
+ fullEntry = findToolEntryInTranscript(fullEntries, effectiveStepCandidates, effectiveToolUseId);
1399
1586
  if (fullEntry && typeof fullEntry.content === 'string') {
1587
+ if (typeof fullEntry.step_index === 'number' && Number.isSafeInteger(fullEntry.step_index)) {
1588
+ fullMatchedStep = fullEntry.step_index;
1589
+ }
1400
1590
  const candidateStripped = stripToolTimestampHeader(fullEntry.content);
1401
1591
  if (candidateStripped) {
1402
1592
  if (!isTruncatedToolResult(fullEntry, candidateStripped)) {
@@ -1410,8 +1600,39 @@ export function extractToolResultFromTranscript(transcriptPath, stepIdx, options
1410
1600
  }
1411
1601
  // 2. Fallback to authorized `<conversation>/.system_generated/steps/<n>/output.txt`
1412
1602
  // (strictly confined by realpath + no-symlink + Linux openat2 RESOLVE_BENEATH).
1413
- const referenceTexts = fullStripped !== null ? [fullStripped, baseStripped] : [baseStripped];
1414
- return readStepOutputFallback(baseTarget, conversationId, referenceTexts, effectiveStepCandidates, options);
1603
+ const hasMatchedTranscriptEntry = matchedEntry !== null || fullEntry !== null;
1604
+ let stepFallbackCandidates;
1605
+ if (hasMatchedTranscriptEntry) {
1606
+ if (fullEntry === null && matchedStep !== null && effectiveToolUseId
1607
+ && hasConflictingToolUseIdAtStep(fullEntries, matchedStep, effectiveToolUseId)) {
1608
+ return null;
1609
+ }
1610
+ stepFallbackCandidates = [
1611
+ ...(fullMatchedStep !== null ? [fullMatchedStep] : []),
1612
+ ...effectiveStepCandidates.filter((step) => step !== fullMatchedStep),
1613
+ ];
1614
+ }
1615
+ else {
1616
+ // Unflushed direct recovery: Antigravity writes `steps/<stepIdx>/output.txt` before flushing
1617
+ // `transcript.jsonl`. Strictly limit candidates to the exact `[stepIdx]` (never `stepIdx + 1`)
1618
+ // and fail closed if either transcript already has an entry at `stepIdx` (e.g. PLANNER_RESPONSE,
1619
+ // USER_INPUT, non-tool entry, or conflicting tool_use_id).
1620
+ if (!hasStepIdx)
1621
+ return null;
1622
+ if (hasStepIndexInTranscript(baseEntries, stepIdx) || hasStepIndexInTranscript(fullEntries, stepIdx)) {
1623
+ return null;
1624
+ }
1625
+ stepFallbackCandidates = [stepIdx];
1626
+ }
1627
+ const referenceTexts = [];
1628
+ if (fullStripped !== null)
1629
+ referenceTexts.push(fullStripped);
1630
+ if (baseStripped !== null)
1631
+ referenceTexts.push(baseStripped);
1632
+ if (referenceTexts.length === 0 && stepFallbackCandidates.length === 0) {
1633
+ return null;
1634
+ }
1635
+ return readStepOutputFallback(baseTarget, conversationId, referenceTexts, stepFallbackCandidates, options);
1415
1636
  }
1416
1637
  /**
1417
1638
  * Extracts a tool result from the authorized transcript / step output and restores
@@ -1782,12 +2003,18 @@ function buildSystemMessageStep(turnId, additionalContext, userMarkdown) {
1782
2003
  `[Brainbase Judgment Turn: ${turnId}]`,
1783
2004
  `※この判断契約・先頭監査行は当ターン(${turnId})のみ有効です。過去のターンに注入された旧ターンの判断契約・先頭監査行は上書きされ無効です。`,
1784
2005
  ].join('\n');
1785
- const modelBody = normalizedContext ?? normalizedMarkdown;
1786
- const modelText = modelBody ? `${guardHeader}\n\n${modelBody}` : '';
2006
+ const bodyParts = [];
2007
+ if (normalizedMarkdown) {
2008
+ bodyParts.push(normalizedMarkdown);
2009
+ }
2010
+ if (normalizedContext && normalizedContext !== normalizedMarkdown) {
2011
+ bodyParts.push(normalizedContext);
2012
+ }
2013
+ const modelBody = bodyParts.join('\n\n');
2014
+ const modelText = `${guardHeader}\n\n${modelBody}`;
1787
2015
  return {
1788
2016
  systemMessage: {
1789
2017
  systemMessage: modelText,
1790
- ...(normalizedMarkdown ? { metadata: { user_markdown: normalizedMarkdown } } : {}),
1791
2018
  },
1792
2019
  };
1793
2020
  }
@@ -2462,6 +2689,8 @@ export function registerAntigravityJudgmentHooks(hooksJson, options) {
2462
2689
  }
2463
2690
  /** @internal Exposed strictly for deterministic concurrency and TOCTOU regression tests. */
2464
2691
  export const __antigravityHookTestInternals = {
2692
+ buildSystemMessageStep,
2693
+ normalizedToolInput,
2465
2694
  withTurnStateLock,
2466
2695
  readTranscriptTailEntries,
2467
2696
  resolveOpenatHelperBinary,
package/dist/cli.js CHANGED
@@ -23,6 +23,7 @@ import { blockedJudgmentOutput, processJudgmentHook, resolveReasoningGateMode }
23
23
  import { applyCanonicalWrites, buildCanonicalEdge } from './canonical-edge-builder.js';
24
24
  import { defaultJudgmentJournalRoot } from './judgment-value-proof-review.js';
25
25
  import { createWorldExtension, readWorldVocabulary } from './world-extension.js';
26
+ import { buildRevalidationQueue, DEFAULT_REVALIDATION_QUEUE_TOP_K, parseCatalogModelsPayload, renderRevalidationQueueText, } from './world-model-revalidation-queue.js';
26
27
  import { createLocalWebHost, LOCAL_WEB_DEFAULT_PORT } from './local-web-host.js';
27
28
  import { assertCredentialsFilePath, BrainbaseLoginError, CREDENTIALS_SCHEMA_VERSION, defaultCredentialsPath, loginWithDeviceCode, normalizeServerUrl, readCredentials, removeCredentials, withCredentialsLock } from './brainbase-login.js';
28
29
  import { CLAUDE_CODE_HOOK_CONFIG_SCHEMA, canonicalFilePath, claudeCodeHookCommand, claudeCodeJudgmentHookGroups, defaultClaudeCodeHookConfigPath, handleClaudeCodeJudgmentHook, hasInstalledClaudeCodeHooks, isClaudeCodeHookConfigText, parseClaudeCodeHookConfig, normalizeRepositoryEntry, registerClaudeCodeJudgmentHooks } from './claude-code-judgment-hook.js';
@@ -109,6 +110,8 @@ export async function runCli(argv = process.argv.slice(2), io = process) {
109
110
  return await ontologyAudit(parsed, io);
110
111
  case 'ontology:migrate':
111
112
  return await ontologyMigrate(parsed, io);
113
+ case 'world-model:revalidation-queue':
114
+ return await worldModelRevalidationQueue(parsed, io);
112
115
  case 'judgment:hook':
113
116
  return await judgmentHook(parsed, io);
114
117
  case 'judgment:install':
@@ -2157,6 +2160,53 @@ async function ontologyMigrate(parsed, io) {
2157
2160
  write(io, `${JSON.stringify(result, null, 2)}\n`);
2158
2161
  return result.status === 'blocked' ? 1 : 0;
2159
2162
  }
2163
+ async function worldModelRevalidationQueue(parsed, io) {
2164
+ if (parsed.flags.has('catalog')) {
2165
+ throw new Error('world-model:revalidation-queue requires --catalog <json>');
2166
+ }
2167
+ const catalogPath = first(parsed, 'catalog')?.trim();
2168
+ if (!catalogPath) {
2169
+ throw new Error('world-model:revalidation-queue requires --catalog <json>');
2170
+ }
2171
+ if (parsed.flags.has('top')) {
2172
+ throw new Error('world-model:revalidation-queue --top requires a positive integer');
2173
+ }
2174
+ if (parsed.values.has('json')) {
2175
+ throw new Error('world-model:revalidation-queue --json does not take a value');
2176
+ }
2177
+ const rawTop = first(parsed, 'top');
2178
+ let topK = DEFAULT_REVALIDATION_QUEUE_TOP_K;
2179
+ if (rawTop !== undefined) {
2180
+ if (!/^[1-9]\d*$/u.test(rawTop)) {
2181
+ throw new Error('world-model:revalidation-queue --top must be a positive integer');
2182
+ }
2183
+ topK = Number(rawTop);
2184
+ if (!Number.isSafeInteger(topK)) {
2185
+ throw new Error('world-model:revalidation-queue --top must be a safe positive integer');
2186
+ }
2187
+ }
2188
+ let rawText;
2189
+ try {
2190
+ rawText = await readFile(catalogPath, 'utf8');
2191
+ }
2192
+ catch (error) {
2193
+ const reason = error instanceof Error ? error.message : String(error);
2194
+ throw new Error(`Failed to read catalog file "${catalogPath}": ${reason}`);
2195
+ }
2196
+ let payload;
2197
+ try {
2198
+ payload = JSON.parse(rawText);
2199
+ }
2200
+ catch (error) {
2201
+ const reason = error instanceof Error ? error.message : String(error);
2202
+ throw new Error(`Invalid JSON in catalog file "${catalogPath}": ${reason}`);
2203
+ }
2204
+ const models = parseCatalogModelsPayload(payload);
2205
+ const queue = buildRevalidationQueue(models, { topK });
2206
+ const asJson = parsed.flags.has('json');
2207
+ write(io, asJson ? `${JSON.stringify(queue, null, 2)}\n` : renderRevalidationQueueText(queue));
2208
+ return 0;
2209
+ }
2160
2210
  function proposedPersonalOs(os, proposed) {
2161
2211
  return { ...os, ...proposed };
2162
2212
  }
@@ -2194,6 +2244,7 @@ function usage() {
2194
2244
  brainbase memory:list [--dir path] [--format text|json]
2195
2245
  brainbase memory:register --id id [--id id...] [--dir path] [--write] [--format text|json]
2196
2246
  brainbase ontology:migrate [--dir path] [--write --expected-input-digest digest]
2247
+ brainbase world-model:revalidation-queue --catalog path [--top n] [--json]
2197
2248
  brainbase judgment:install --target codex [--autonomy-mode off|canary|on] [--autonomy-project code] [--reasoning-gate-mode off|compact_4block_v3|compact_4block_with_wm] [--reasoning-gate-projects code,code] [--dry-run] [--output path]
2198
2249
  brainbase judgment:install --target claude-code --origin url [--server url] [--project code] [--repositories name,name] [--settings path] [--config path] [--dry-run] [--remove]
2199
2250
  brainbase judgment:install --target antigravity --origin baseUrl [--server url] [--project code] [--allow-non-git] [--cwd-prefix path] [--repositories name,name] [--settings hooks.json] [--config path] [--dry-run] [--remove]
@@ -34,7 +34,7 @@ function exactKeys(value, keys) {
34
34
  return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
35
35
  }
36
36
  function cleanText(value, limit, { nullable = false } = {}) {
37
- if (value === null && nullable)
37
+ if (nullable && (value === null || (typeof value === 'string' && value.trim() === '')))
38
38
  return null;
39
39
  if (typeof value !== 'string')
40
40
  return undefined;
@@ -60,18 +60,22 @@ function cleanStringArray(value, limit, { maxItems = MAX_ITEMS } = {}) {
60
60
  }
61
61
  function normalizeInput(value, { includeSchemaVersion = true } = {}) {
62
62
  const expectedKeys = includeSchemaVersion ? RESULT_KEYS : INPUT_KEYS;
63
- if (!exactKeys(value, expectedKeys))
63
+ const candidate = isRecord(value)
64
+ && (!Object.hasOwn(value, 'previous_result_tool_use_id') || value.previous_result_tool_use_id === undefined)
65
+ ? { ...value, previous_result_tool_use_id: null }
66
+ : value;
67
+ if (!exactKeys(candidate, expectedKeys))
64
68
  return null;
65
- if (includeSchemaVersion && value.schema_version !== JUDGMENT_NODE_EVIDENCE_SCHEMA_VERSION)
69
+ if (includeSchemaVersion && candidate.schema_version !== JUDGMENT_NODE_EVIDENCE_SCHEMA_VERSION)
66
70
  return null;
67
- const nodeId = cleanId(value.node_id);
68
- const status = value.status;
69
- const finding = cleanText(value.finding, MAX_TEXT_LENGTH);
70
- const evidenceFit = cleanText(value.evidence_fit, MAX_TEXT_LENGTH);
71
- const unknowns = cleanStringArray(value.unknowns, MAX_UNKNOWN_LENGTH);
72
- const evidenceIds = cleanStringArray(value.evidence_tool_use_ids, MAX_NODE_ID_LENGTH);
73
- const previous = cleanId(value.previous_result_tool_use_id, { nullable: true });
74
- const nextAction = cleanText(value.next_action, MAX_TEXT_LENGTH);
71
+ const nodeId = cleanId(candidate.node_id);
72
+ const status = candidate.status;
73
+ const finding = cleanText(candidate.finding, MAX_TEXT_LENGTH);
74
+ const evidenceFit = cleanText(candidate.evidence_fit, MAX_TEXT_LENGTH);
75
+ const unknowns = cleanStringArray(candidate.unknowns, MAX_UNKNOWN_LENGTH);
76
+ const evidenceIds = cleanStringArray(candidate.evidence_tool_use_ids, MAX_NODE_ID_LENGTH);
77
+ const previous = cleanId(candidate.previous_result_tool_use_id, { nullable: true });
78
+ const nextAction = cleanText(candidate.next_action, MAX_TEXT_LENGTH);
75
79
  if (typeof nodeId !== 'string'
76
80
  || !NODE_STATUSES.has(status)
77
81
  || typeof finding !== 'string'
@@ -1,5 +1,6 @@
1
1
  const SUPPORTED_TYPES = new Set(['object', 'array', 'string', 'number', 'integer', 'boolean']);
2
2
  const NULL_NOTE = 'null is also accepted.';
3
+ const NULLABLE_OMIT_NOTE = 'Omit or pass null when unset.';
3
4
  const CLOSED_EMPTY_OBJECT_NOTE = 'Must be an empty object ({}); additionalProperties: false was relaxed to additionalProperties: true for Gemini schema compatibility.';
4
5
  const EMPTY_ENUM_INTERSECTION_NOTE = 'No string value satisfies the intersected enum constraints (empty enum intersection).';
5
6
  /**
@@ -65,6 +66,24 @@ function appendDescriptions(existing, additions) {
65
66
  }
66
67
  return result || undefined;
67
68
  }
69
+ function appendNullNote(existing) {
70
+ const base = typeof existing === 'string' ? existing.trim() : '';
71
+ if (base.includes(NULLABLE_OMIT_NOTE))
72
+ return base;
73
+ return appendDescription(base, NULL_NOTE);
74
+ }
75
+ function replaceNullNoteWithOmitNote(existing) {
76
+ const base = typeof existing === 'string' ? existing.trim() : '';
77
+ if (!base)
78
+ return NULLABLE_OMIT_NOTE;
79
+ if (base.includes(NULLABLE_OMIT_NOTE)) {
80
+ return base.replaceAll(NULL_NOTE, '').replace(/\s+/gu, ' ').trim();
81
+ }
82
+ if (base.includes(NULL_NOTE)) {
83
+ return base.replace(NULL_NOTE, NULLABLE_OMIT_NOTE).replaceAll(NULL_NOTE, '').replace(/\s+/gu, ' ').trim();
84
+ }
85
+ return `${base} ${NULLABLE_OMIT_NOTE}`;
86
+ }
68
87
  function uniqueStrings(values) {
69
88
  return [...new Set(values)];
70
89
  }
@@ -126,7 +145,15 @@ function finalizeNormalizedSchema(node, isRoot) {
126
145
  if (node.type === 'object') {
127
146
  if (Array.isArray(node.required)) {
128
147
  const props = isPlainObject(node.properties) ? node.properties : {};
129
- const filtered = uniqueStrings(node.required.filter((key) => typeof key === 'string' && Object.hasOwn(props, key)));
148
+ const filtered = [];
149
+ for (const key of uniqueStrings(node.required.filter((entry) => typeof entry === 'string' && Object.hasOwn(props, entry)))) {
150
+ const propSchema = Object.getOwnPropertyDescriptor(props, key)?.value;
151
+ if (isPlainObject(propSchema) && propSchema.nullable === true) {
152
+ propSchema.description = replaceNullNoteWithOmitNote(propSchema.description);
153
+ continue;
154
+ }
155
+ filtered.push(key);
156
+ }
130
157
  if (filtered.length > 0) {
131
158
  node.required = filtered;
132
159
  }
@@ -191,7 +218,7 @@ function mergeNormalizedSchemas(branches, mode, preserveUndeclaredRequired = fal
191
218
  const mergedObject = mergeObjectSchemas(nonNull, mode, preserveUndeclaredRequired);
192
219
  if (anyNullable) {
193
220
  mergedObject.nullable = true;
194
- mergedObject.description = appendDescription(mergedObject.description, NULL_NOTE);
221
+ mergedObject.description = appendNullNote(mergedObject.description);
195
222
  }
196
223
  return { schema: mergedObject, notes: [] };
197
224
  }
@@ -261,7 +288,7 @@ function mergeNormalizedSchemas(branches, mode, preserveUndeclaredRequired = fal
261
288
  }
262
289
  if (anyNullable) {
263
290
  result.nullable = true;
264
- result.description = appendDescription(result.description, NULL_NOTE);
291
+ result.description = appendNullNote(result.description);
265
292
  }
266
293
  return { schema: result, notes };
267
294
  }
@@ -293,7 +320,7 @@ function mergeNormalizedSchemas(branches, mode, preserveUndeclaredRequired = fal
293
320
  result.description = description;
294
321
  if (anyNullable) {
295
322
  result.nullable = true;
296
- result.description = appendDescription(result.description, NULL_NOTE);
323
+ result.description = appendNullNote(result.description);
297
324
  }
298
325
  return { schema: result, notes: [] };
299
326
  }
@@ -322,7 +349,7 @@ function mergeNormalizedSchemas(branches, mode, preserveUndeclaredRequired = fal
322
349
  }
323
350
  if (anyNullable) {
324
351
  base.nullable = true;
325
- base.description = appendDescription(base.description, NULL_NOTE);
352
+ base.description = appendNullNote(base.description);
326
353
  }
327
354
  return { schema: base, notes: [] };
328
355
  }
@@ -356,7 +383,7 @@ function mergeNormalizedSchemas(branches, mode, preserveUndeclaredRequired = fal
356
383
  }
357
384
  if (anyNullable) {
358
385
  result.nullable = true;
359
- result.description = appendDescription(result.description, NULL_NOTE);
386
+ result.description = appendNullNote(result.description);
360
387
  }
361
388
  return { schema: result, notes: [] };
362
389
  }
@@ -377,7 +404,7 @@ function mergeNormalizedSchemas(branches, mode, preserveUndeclaredRequired = fal
377
404
  }
378
405
  if (anyNullable) {
379
406
  merged.nullable = true;
380
- merged.description = appendDescription(merged.description, NULL_NOTE);
407
+ merged.description = appendNullNote(merged.description);
381
408
  }
382
409
  return { schema: merged, notes };
383
410
  }
@@ -728,7 +755,17 @@ function normalizeSchemaNode(rawNode, root, seenRefs, isRoot = false, preserveUn
728
755
  }
729
756
  if (Array.isArray(working.required)) {
730
757
  const props = isPlainObject(working.properties) ? working.properties : {};
731
- const filtered = uniqueStrings(working.required.filter((key) => typeof key === 'string' && (preserveUndeclaredRequired || Object.hasOwn(props, key))));
758
+ const filtered = [];
759
+ for (const key of uniqueStrings(working.required.filter((entry) => typeof entry === 'string' && (preserveUndeclaredRequired || Object.hasOwn(props, entry))))) {
760
+ if (Object.hasOwn(props, key)) {
761
+ const propSchema = Object.getOwnPropertyDescriptor(props, key)?.value;
762
+ if (isPlainObject(propSchema) && propSchema.nullable === true) {
763
+ propSchema.description = replaceNullNoteWithOmitNote(propSchema.description);
764
+ continue;
765
+ }
766
+ }
767
+ filtered.push(key);
768
+ }
732
769
  if (filtered.length > 0) {
733
770
  working.required = filtered;
734
771
  }
@@ -743,7 +780,7 @@ function normalizeSchemaNode(rawNode, root, seenRefs, isRoot = false, preserveUn
743
780
  // Normalize `nullable`: preserve OpenAPI boolean `nullable` (and note `null` in description),
744
781
  // strip invalid non-boolean values.
745
782
  if (working.nullable === true) {
746
- working.description = appendDescription(working.description, NULL_NOTE);
783
+ working.description = appendNullNote(working.description);
747
784
  }
748
785
  else if (working.nullable !== false && Object.hasOwn(working, 'nullable')) {
749
786
  delete working.nullable;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * RFC-003: World Model Revalidation & Outcome-Binding Loop (PR-1)
3
+ *
4
+ * Pure, deterministic triage and prioritization engine for unverified world
5
+ * models. Read-only: never mutates inputs, files, or external stores.
6
+ */
7
+ import type { WorldModelImpactAnalysis } from './world-model-impact-index.js';
8
+ export declare const WORLD_MODEL_REVALIDATION_QUEUE_SCHEMA_VERSION: "world_model_revalidation_queue.v1";
9
+ export declare const DEFAULT_REVALIDATION_QUEUE_TOP_K: 15;
10
+ export declare const MAX_DOWNSTREAM_IMPACT_BONUS: 6;
11
+ export type WorldModelStatus = 'active' | 'adopted_unverified' | 'draft' | 'retired';
12
+ export type RevalidationTier = 'T1_AUTO_TELEMETRY' | 'T2_REVIEW_PROMISE_CASE' | 'T3_LAZY_ON_CITATION';
13
+ export type TelemetrySource = 'github_pr_evals' | 'orca_needs_you_and_stalls' | 'brainbase_judgment_journal' | 'brainbase_meeting_decisions' | 'finance_margin_ledger' | 'sales_crm_pipeline' | 'none_qualitative_only';
14
+ export interface CatalogModelRecord {
15
+ id: string;
16
+ status: WorldModelStatus | string;
17
+ prefix: string;
18
+ text: string;
19
+ hasApply: boolean;
20
+ hasExclude: boolean;
21
+ hasNumber: boolean;
22
+ hasCausal: boolean;
23
+ outcomeCount?: number;
24
+ citationCount30d?: number;
25
+ downstreamImpactCount?: number;
26
+ }
27
+ export interface ScoredWorldModelBreakdown {
28
+ observability: number;
29
+ leverage: number;
30
+ falsifiability: number;
31
+ freshnessOrDraftUrgency: number;
32
+ }
33
+ export interface ScoredWorldModel {
34
+ id: string;
35
+ status: string;
36
+ tier: RevalidationTier;
37
+ lazyPromoted?: boolean;
38
+ telemetrySources: TelemetrySource[];
39
+ priorityScore: number;
40
+ breakdown: ScoredWorldModelBreakdown;
41
+ proposedMetric: string;
42
+ falsifiedIfDraft: string;
43
+ summary: string;
44
+ }
45
+ export interface WorldModelRevalidationQueue {
46
+ schemaVersion: typeof WORLD_MODEL_REVALIDATION_QUEUE_SCHEMA_VERSION;
47
+ totalModels: number;
48
+ verifiedWithOutcomes: number;
49
+ tierCounts: Record<RevalidationTier, number>;
50
+ topQueue: ScoredWorldModel[];
51
+ allScored: ScoredWorldModel[];
52
+ }
53
+ export interface BuildRevalidationQueueOptions {
54
+ topK?: number;
55
+ /**
56
+ * Optional lookup of model ID -> downstream impact count (compatible with
57
+ * `WorldModelImpactAnalysis.affectedItems.length` from `world-model-impact-index.ts`).
58
+ * Applied when a `CatalogModelRecord` omits `downstreamImpactCount`.
59
+ */
60
+ downstreamImpactCounts?: ReadonlyMap<string, number> | Readonly<Record<string, number>>;
61
+ }
62
+ /**
63
+ * Extracts a `downstreamImpactCount` scalar from a `world-model-impact-index`
64
+ * reverse-dependency analysis result.
65
+ */
66
+ export declare function downstreamImpactCountFromAnalysis(analysis: Pick<WorldModelImpactAnalysis, 'affectedItems'>): number;
67
+ /**
68
+ * Deterministically maps a world-model text to existing primary telemetry
69
+ * sources, a proposed metric, and a falsification draft.
70
+ */
71
+ export declare function detectTelemetrySources(text: string): {
72
+ sources: TelemetrySource[];
73
+ metric: string;
74
+ falsifiedIf: string;
75
+ };
76
+ /**
77
+ * Deterministically classifies a world model into T1/T2/T3 (including Lazy
78
+ * Promotion from T3 to T2 when `citationCount30d >= 1`) and computes its
79
+ * bounded 0..100 revalidation priority score.
80
+ */
81
+ export declare function classifyAndScoreModel(model: CatalogModelRecord): ScoredWorldModel;
82
+ /**
83
+ * Builds a deterministic `world_model_revalidation_queue.v1` payload sorted by
84
+ * descending `priorityScore`, breaking ties lexicographically by `id`.
85
+ */
86
+ export declare function buildRevalidationQueue(models: readonly CatalogModelRecord[], options?: BuildRevalidationQueueOptions): WorldModelRevalidationQueue;
87
+ /**
88
+ * Parses and validates a world-model catalog JSON payload (`{ models: [...] }`
89
+ * or a top-level array of `CatalogModelRecord`). Fails loudly on malformed input.
90
+ */
91
+ export declare function parseCatalogModelsPayload(payload: unknown): CatalogModelRecord[];
92
+ /**
93
+ * Formats a `WorldModelRevalidationQueue` as a deterministic, human-readable
94
+ * report for the read-only CLI.
95
+ */
96
+ export declare function renderRevalidationQueueText(queue: WorldModelRevalidationQueue): string;
@@ -0,0 +1,309 @@
1
+ /**
2
+ * RFC-003: World Model Revalidation & Outcome-Binding Loop (PR-1)
3
+ *
4
+ * Pure, deterministic triage and prioritization engine for unverified world
5
+ * models. Read-only: never mutates inputs, files, or external stores.
6
+ */
7
+ export const WORLD_MODEL_REVALIDATION_QUEUE_SCHEMA_VERSION = 'world_model_revalidation_queue.v1';
8
+ export const DEFAULT_REVALIDATION_QUEUE_TOP_K = 15;
9
+ export const MAX_DOWNSTREAM_IMPACT_BONUS = 6;
10
+ const TELEMETRY_RULES = [
11
+ {
12
+ source: 'orca_needs_you_and_stalls',
13
+ pattern: /認知負荷|認知コスト|承認待ち|代理判断|放置可能|ガード|自律|タスク一覧|ボトルネック|並列/u,
14
+ metric: 'Needs you 件数/h・再質問率・In progress 滞留時間・委任×差戻しペア率',
15
+ falsifiedIf: '導入前後 2 週間で Needs you 率または差戻し率が改善せず、逆行(>= +15%)が観測された場合',
16
+ },
17
+ {
18
+ source: 'brainbase_judgment_journal',
19
+ pattern: /正本|SSOT|表記と判断|判断品質|学習ループ|反証|証跡|単発ツール|職責|二重管理|表示内容/u,
20
+ metric: '判断ジャーナル監査通過率・E2E-G4 引用率・矛盾/巻き戻し発生率・PoLL 7 項目 FAIL 率',
21
+ falsifiedIf: '実戦 2 週間カナリアで正本参照あり群の FAIL 率・巻き戻し率がベースラインを下回らない場合',
22
+ },
23
+ {
24
+ source: 'github_pr_evals',
25
+ pattern: /開発時間|再利用|高速|実行速度|複雑|多機能|文脈の受け渡し|並列AI開発|Decision.*Work.*Ship/u,
26
+ metric: 'Unson-LLC 7d PR マージ中央値・自動マージ率・再レビュー往復回数・コード再利用比率',
27
+ falsifiedIf: '4 週間窓で対象介入後の PR マージ中央値悪化(+20% 超)または自動マージ率低下が続く場合',
28
+ },
29
+ {
30
+ source: 'finance_margin_ledger',
31
+ pattern: /粗利率|買収|限界費用|SaaS|受託利益|単価|売上化|ROI|キャッシュ/u,
32
+ metric: '案件別粗利率・モジュール再利用工数比・限界費用推移(月次財務正本)',
33
+ falsifiedIf: '四半期 2 期連続で再利用あり案件の粗利率が非再利用案件を上回らない場合',
34
+ },
35
+ {
36
+ source: 'brainbase_meeting_decisions',
37
+ pattern: /RACI|立ち位置|決裁|非同期文書|属人化|創業者不在|会議/u,
38
+ metric: '創業者非関与での決定完了率・決裁リードタイム・見直しの約束達成率',
39
+ falsifiedIf: 'RACI 明示案件でも創業者エスカレーション比率が 70% 超のまま改善しない場合',
40
+ },
41
+ {
42
+ source: 'sales_crm_pipeline',
43
+ pattern: /営業|商談|顧客|信頼|口コミ|レビュー|面談|高額商材|LP|CVR|紹介|既存顧客|SLA|フィードバック/u,
44
+ metric: '商談化率・受注率・顧客 NPS/継続率・CRM 案件別 ReviewPromise 結果',
45
+ falsifiedIf: '対象セグメント 10 案件以上で適用群の成約/継続率が対照群を下回る場合',
46
+ },
47
+ ];
48
+ const AUTO_TELEMETRY_SOURCES = new Set([
49
+ 'github_pr_evals',
50
+ 'orca_needs_you_and_stalls',
51
+ 'brainbase_judgment_journal',
52
+ 'brainbase_meeting_decisions',
53
+ ]);
54
+ function sanitizeNonNegativeCount(value) {
55
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)
56
+ return 0;
57
+ return Math.floor(value);
58
+ }
59
+ function clampPriorityScore(value) {
60
+ if (!Number.isFinite(value))
61
+ return 0;
62
+ return Math.max(0, Math.min(100, Math.round(value)));
63
+ }
64
+ function lookupDownstreamImpactCount(modelId, counts) {
65
+ if (!counts)
66
+ return undefined;
67
+ if (counts instanceof Map)
68
+ return counts.get(modelId);
69
+ const record = counts;
70
+ return Object.prototype.hasOwnProperty.call(record, modelId) ? record[modelId] : undefined;
71
+ }
72
+ /**
73
+ * Extracts a `downstreamImpactCount` scalar from a `world-model-impact-index`
74
+ * reverse-dependency analysis result.
75
+ */
76
+ export function downstreamImpactCountFromAnalysis(analysis) {
77
+ return analysis.affectedItems.length;
78
+ }
79
+ /**
80
+ * Deterministically maps a world-model text to existing primary telemetry
81
+ * sources, a proposed metric, and a falsification draft.
82
+ */
83
+ export function detectTelemetrySources(text) {
84
+ const matched = TELEMETRY_RULES.filter((rule) => rule.pattern.test(text));
85
+ if (matched.length === 0) {
86
+ return {
87
+ sources: ['none_qualitative_only'],
88
+ metric: '未接続(引用時に個別 ReviewPromise へ指標を紐付け)',
89
+ falsifiedIf: '明示引用された意思決定で予測方向と逆の実測結果が 2 件以上蓄積した場合',
90
+ };
91
+ }
92
+ return {
93
+ sources: matched.map((rule) => rule.source),
94
+ metric: matched[0].metric,
95
+ falsifiedIf: matched[0].falsifiedIf,
96
+ };
97
+ }
98
+ /**
99
+ * Deterministically classifies a world model into T1/T2/T3 (including Lazy
100
+ * Promotion from T3 to T2 when `citationCount30d >= 1`) and computes its
101
+ * bounded 0..100 revalidation priority score.
102
+ */
103
+ export function classifyAndScoreModel(model) {
104
+ const { sources, metric, falsifiedIf } = detectTelemetrySources(model.text);
105
+ const hasAutoTelemetry = sources.some((source) => AUTO_TELEMETRY_SOURCES.has(source));
106
+ const hasCaseTelemetry = sources.includes('finance_margin_ledger') || sources.includes('sales_crm_pipeline');
107
+ const citationCount30d = sanitizeNonNegativeCount(model.citationCount30d);
108
+ let tier;
109
+ let lazyPromoted = false;
110
+ if (hasAutoTelemetry) {
111
+ tier = 'T1_AUTO_TELEMETRY';
112
+ }
113
+ else if (hasCaseTelemetry && (model.hasExclude || model.hasNumber || model.prefix === 'fnd_unson_model')) {
114
+ tier = 'T2_REVIEW_PROMISE_CASE';
115
+ }
116
+ else if (citationCount30d >= 1) {
117
+ tier = 'T2_REVIEW_PROMISE_CASE';
118
+ lazyPromoted = true;
119
+ }
120
+ else {
121
+ tier = 'T3_LAZY_ON_CITATION';
122
+ }
123
+ // 1. Observability (0..35)
124
+ let observability = 5;
125
+ if (hasAutoTelemetry)
126
+ observability = 30 + Math.min(5, (sources.length - 1) * 5);
127
+ else if (hasCaseTelemetry)
128
+ observability = 18;
129
+ // 2. Strategic / operational leverage (0..30)
130
+ let leverage = 10;
131
+ if (model.prefix === 'fnd_unson_model')
132
+ leverage = 28;
133
+ else if (model.prefix === 'fnd_model_phi')
134
+ leverage = 26;
135
+ else if (model.hasCausal && model.hasExclude)
136
+ leverage = 20;
137
+ else if (model.hasCausal)
138
+ leverage = 15;
139
+ const downstreamImpactCount = sanitizeNonNegativeCount(model.downstreamImpactCount);
140
+ if (downstreamImpactCount > 0) {
141
+ leverage = Math.min(30, leverage + Math.min(MAX_DOWNSTREAM_IMPACT_BONUS, downstreamImpactCount * 2));
142
+ }
143
+ // 3. Falsifiability readiness (0..20)
144
+ let falsifiability = 4;
145
+ if (model.hasCausal)
146
+ falsifiability += 6;
147
+ if (model.hasApply)
148
+ falsifiability += 3;
149
+ if (model.hasExclude)
150
+ falsifiability += 4;
151
+ if (model.hasNumber)
152
+ falsifiability += 3;
153
+ falsifiability = Math.min(20, falsifiability);
154
+ // 4. Unverified / draft urgency (0..15)
155
+ let freshnessOrDraftUrgency = 0;
156
+ const outcomes = sanitizeNonNegativeCount(model.outcomeCount);
157
+ if (outcomes === 0)
158
+ freshnessOrDraftUrgency += 8;
159
+ if (model.status === 'draft' && (model.prefix === 'fnd_model_phi' || model.prefix === 'fnd_unson_model')) {
160
+ freshnessOrDraftUrgency += 7;
161
+ }
162
+ else if (model.status === 'adopted_unverified') {
163
+ freshnessOrDraftUrgency += 4;
164
+ }
165
+ const priorityScore = clampPriorityScore(observability + leverage + falsifiability + freshnessOrDraftUrgency);
166
+ return {
167
+ id: model.id,
168
+ status: model.status,
169
+ tier,
170
+ ...(lazyPromoted ? { lazyPromoted: true } : {}),
171
+ telemetrySources: sources,
172
+ priorityScore,
173
+ breakdown: {
174
+ observability,
175
+ leverage,
176
+ falsifiability,
177
+ freshnessOrDraftUrgency,
178
+ },
179
+ proposedMetric: metric,
180
+ falsifiedIfDraft: falsifiedIf,
181
+ summary: model.text.slice(0, 120),
182
+ };
183
+ }
184
+ /**
185
+ * Builds a deterministic `world_model_revalidation_queue.v1` payload sorted by
186
+ * descending `priorityScore`, breaking ties lexicographically by `id`.
187
+ */
188
+ export function buildRevalidationQueue(models, options = {}) {
189
+ const topK = options.topK ?? DEFAULT_REVALIDATION_QUEUE_TOP_K;
190
+ if (!Number.isInteger(topK) || topK < 0) {
191
+ throw new RangeError('topK must be a non-negative integer');
192
+ }
193
+ const scored = models
194
+ .map((model) => {
195
+ if (model.downstreamImpactCount !== undefined) {
196
+ return classifyAndScoreModel(model);
197
+ }
198
+ const mappedImpact = lookupDownstreamImpactCount(model.id, options.downstreamImpactCounts);
199
+ return mappedImpact === undefined
200
+ ? classifyAndScoreModel(model)
201
+ : classifyAndScoreModel({ ...model, downstreamImpactCount: mappedImpact });
202
+ })
203
+ .sort((a, b) => b.priorityScore - a.priorityScore || a.id.localeCompare(b.id));
204
+ const tierCounts = {
205
+ T1_AUTO_TELEMETRY: 0,
206
+ T2_REVIEW_PROMISE_CASE: 0,
207
+ T3_LAZY_ON_CITATION: 0,
208
+ };
209
+ for (const entry of scored) {
210
+ tierCounts[entry.tier] += 1;
211
+ }
212
+ return {
213
+ schemaVersion: WORLD_MODEL_REVALIDATION_QUEUE_SCHEMA_VERSION,
214
+ totalModels: scored.length,
215
+ verifiedWithOutcomes: models.filter((model) => sanitizeNonNegativeCount(model.outcomeCount) > 0).length,
216
+ tierCounts,
217
+ topQueue: scored.slice(0, topK),
218
+ allScored: scored,
219
+ };
220
+ }
221
+ function isPlainRecord(value) {
222
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
223
+ }
224
+ function assertOptionalNonNegativeNumber(value, field, index) {
225
+ if (value === undefined)
226
+ return undefined;
227
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
228
+ throw new Error(`Invalid catalog model at index ${index}: ${field} must be a non-negative number`);
229
+ }
230
+ return value;
231
+ }
232
+ /**
233
+ * Parses and validates a world-model catalog JSON payload (`{ models: [...] }`
234
+ * or a top-level array of `CatalogModelRecord`). Fails loudly on malformed input.
235
+ */
236
+ export function parseCatalogModelsPayload(payload) {
237
+ const rawModels = Array.isArray(payload)
238
+ ? payload
239
+ : isPlainRecord(payload) && Array.isArray(payload.models)
240
+ ? payload.models
241
+ : null;
242
+ if (!rawModels) {
243
+ throw new Error('Catalog JSON must be an object with a "models" array or an array of model records');
244
+ }
245
+ return rawModels.map((entry, index) => {
246
+ if (!isPlainRecord(entry)) {
247
+ throw new Error(`Invalid catalog model at index ${index}: expected an object`);
248
+ }
249
+ if (typeof entry.id !== 'string' || entry.id.trim().length === 0) {
250
+ throw new Error(`Invalid catalog model at index ${index}: id must be a non-empty string`);
251
+ }
252
+ if (typeof entry.status !== 'string' || entry.status.trim().length === 0) {
253
+ throw new Error(`Invalid catalog model at index ${index}: status must be a non-empty string`);
254
+ }
255
+ if (typeof entry.prefix !== 'string') {
256
+ throw new Error(`Invalid catalog model at index ${index}: prefix must be a string`);
257
+ }
258
+ if (typeof entry.text !== 'string') {
259
+ throw new Error(`Invalid catalog model at index ${index}: text must be a string`);
260
+ }
261
+ if (typeof entry.hasApply !== 'boolean'
262
+ || typeof entry.hasExclude !== 'boolean'
263
+ || typeof entry.hasNumber !== 'boolean'
264
+ || typeof entry.hasCausal !== 'boolean') {
265
+ throw new Error(`Invalid catalog model at index ${index}: hasApply, hasExclude, hasNumber, and hasCausal must be booleans`);
266
+ }
267
+ const outcomeCount = assertOptionalNonNegativeNumber(entry.outcomeCount, 'outcomeCount', index);
268
+ const citationCount30d = assertOptionalNonNegativeNumber(entry.citationCount30d, 'citationCount30d', index);
269
+ const downstreamImpactCount = assertOptionalNonNegativeNumber(entry.downstreamImpactCount, 'downstreamImpactCount', index);
270
+ return {
271
+ id: entry.id,
272
+ status: entry.status,
273
+ prefix: entry.prefix,
274
+ text: entry.text,
275
+ hasApply: entry.hasApply,
276
+ hasExclude: entry.hasExclude,
277
+ hasNumber: entry.hasNumber,
278
+ hasCausal: entry.hasCausal,
279
+ ...(outcomeCount !== undefined ? { outcomeCount } : {}),
280
+ ...(citationCount30d !== undefined ? { citationCount30d } : {}),
281
+ ...(downstreamImpactCount !== undefined ? { downstreamImpactCount } : {}),
282
+ };
283
+ });
284
+ }
285
+ /**
286
+ * Formats a `WorldModelRevalidationQueue` as a deterministic, human-readable
287
+ * report for the read-only CLI.
288
+ */
289
+ export function renderRevalidationQueueText(queue) {
290
+ const lines = [
291
+ `World Model Revalidation Queue (${queue.schemaVersion})`,
292
+ `Total models: ${queue.totalModels} | Verified with outcomes: ${queue.verifiedWithOutcomes}`,
293
+ `Tiers: T1=${queue.tierCounts.T1_AUTO_TELEMETRY}, T2=${queue.tierCounts.T2_REVIEW_PROMISE_CASE}, T3=${queue.tierCounts.T3_LAZY_ON_CITATION}`,
294
+ '',
295
+ ];
296
+ if (queue.topQueue.length === 0) {
297
+ lines.push('Top queue: (empty)');
298
+ return `${lines.join('\n')}\n`;
299
+ }
300
+ lines.push(`Top ${queue.topQueue.length}:`);
301
+ queue.topQueue.forEach((item, index) => {
302
+ const promotedTag = item.lazyPromoted ? ' [lazy-promoted]' : '';
303
+ const sources = item.telemetrySources.join(', ');
304
+ lines.push(`${String(index + 1).padStart(2, ' ')}. [${item.priorityScore}] ${item.tier}${promotedTag} | ${item.id} (${item.status})`);
305
+ lines.push(` telemetry: ${sources}`);
306
+ lines.push(` summary: ${item.summary}`);
307
+ });
308
+ return `${lines.join('\n')}\n`;
309
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unson/brainbase-mcp",
3
- "version": "0.51.2",
3
+ "version": "0.51.4",
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",
@@ -419,6 +419,10 @@
419
419
  "types": "./dist/world-model-impact-index.d.ts",
420
420
  "import": "./dist/world-model-impact-index.js"
421
421
  },
422
+ "./world-model-revalidation-queue": {
423
+ "types": "./dist/world-model-revalidation-queue.d.ts",
424
+ "import": "./dist/world-model-revalidation-queue.js"
425
+ },
422
426
  "./streamable-http": {
423
427
  "types": "./dist/streamable-http.d.ts",
424
428
  "import": "./dist/streamable-http.js"
@@ -669,5 +673,5 @@
669
673
  "url": "https://github.com/Unson-LLC/brainbase/issues"
670
674
  },
671
675
  "homepage": "https://github.com/Unson-LLC/brainbase#readme",
672
- "gitHead": "4a7abf68a2e2f8da4b59d3f0c3efd7c5098eb64b"
676
+ "gitHead": "e743dbcbce098f7886dcf2b087a2ec78dd59fae8"
673
677
  }