@unson/brainbase-mcp 0.51.1 → 0.51.3

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.
@@ -148,7 +148,25 @@ export declare function extractLatestNonSystemUserInput(transcriptPath: unknown,
148
148
  content: string;
149
149
  } | null;
150
150
  export declare function extractLastAssistantMessage(transcriptPath: unknown, options?: TranscriptReadOptions): string | undefined;
151
+ /**
152
+ * Splits whitespace/newline-concatenated top-level JSON objects/arrays (`{...}` / `[...]`)
153
+ * in a single strict O(n) character scan without regex backtracking.
154
+ *
155
+ * Antigravity CLI concatenates multiple MCP text content blocks with `\n` when writing
156
+ * `steps/<n>/output.txt` and `transcript*.jsonl` (for example, a primary tool result JSON
157
+ * followed by a trailing `{"connection_scope":{...}}` block). When 2+ top-level JSON
158
+ * containers are found and every block validates via `JSON.parse`, returns the individual
159
+ * blocks so `tool_response.content` restores the original multi-block MCP structure.
160
+ * For a single JSON value, non-JSON text, or any malformed/partial block, fails open and
161
+ * returns `[text]`.
162
+ */
163
+ export declare function splitConcatenatedJsonTextBlocks(text: string): string[];
151
164
  export declare function extractToolResultFromTranscript(transcriptPath: unknown, stepIdx: unknown, options?: TranscriptReadOptions): string | null;
165
+ /**
166
+ * Extracts a tool result from the authorized transcript / step output and restores
167
+ * whitespace/newline-concatenated MCP JSON text blocks into individual text block strings.
168
+ */
169
+ export declare function extractToolResultTextBlocksFromTranscript(transcriptPath: unknown, stepIdx: unknown, options?: TranscriptReadOptions): string[] | null;
152
170
  declare function turnKey(conversationId: string, configPath: string): string;
153
171
  declare function statePath(env: NodeJS.ProcessEnv, key: string): string;
154
172
  declare function lockPathFor(env: NodeJS.ProcessEnv, key: string): string;
@@ -160,6 +178,12 @@ export interface TurnStateLockOptions {
160
178
  declare function withTurnStateLock<T>(env: NodeJS.ProcessEnv, key: string, fn: () => T | Promise<T>, options?: TurnStateLockOptions): Promise<T>;
161
179
  /** Namespaces session and turn IDs per registration, matching Claude Code isolation. */
162
180
  export declare function antigravityNamespacedId(id: string, config: Pick<AntigravityHookConfig, 'registration'>): string;
181
+ /**
182
+ * Formats a Brainbase judgment context as an Antigravity `injectSteps` entry.
183
+ * Because `systemMessage` persists in Antigravity's conversation trajectory across turns,
184
+ * the header binds it to the current `turn_id` and explicitly supersedes earlier turns.
185
+ */
186
+ declare function buildSystemMessageStep(turnId: string, additionalContext?: string, userMarkdown?: string): Record<string, unknown> | null;
163
187
  /** Handles one Antigravity lifecycle hook event. Never throws. */
164
188
  export declare function handleAntigravityJudgmentHook(payload: AntigravityHookPayload, options?: AntigravityHookOptions): Promise<AntigravityHookOutput>;
165
189
  /** Builds the POSIX-quoted command registered in Antigravity `hooks.json`. */
@@ -185,6 +209,7 @@ export declare function registerAntigravityJudgmentHooks(hooksJson: Record<strin
185
209
  }): Record<string, unknown>;
186
210
  /** @internal Exposed strictly for deterministic concurrency and TOCTOU regression tests. */
187
211
  export declare const __antigravityHookTestInternals: {
212
+ buildSystemMessageStep: typeof buildSystemMessageStep;
188
213
  withTurnStateLock: typeof withTurnStateLock;
189
214
  readTranscriptTailEntries: typeof readTranscriptTailEntries;
190
215
  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';
@@ -679,6 +679,121 @@ function resolveAuthorizedTranscriptTarget(transcriptPath, options) {
679
679
  function resolveAuthorizedTranscriptPath(transcriptPath, options) {
680
680
  return resolveAuthorizedTranscriptTarget(transcriptPath, options)?.canonicalPath ?? null;
681
681
  }
682
+ function isEnoentError(error) {
683
+ return !!error && typeof error === 'object' && error.code === 'ENOENT';
684
+ }
685
+ /**
686
+ * Resolves an authorized transcript location ONLY when the transcript file itself
687
+ * does not exist yet (`ENOENT`), e.g. on the first tool call before Antigravity
688
+ * flushes `logs/transcript.jsonl` while `steps/<n>/output.txt` already exists.
689
+ *
690
+ * Strictly enforces the same canonical root, conversation structure, and
691
+ * no-symlink ancestor invariants; fails closed if the file exists (and was
692
+ * already rejected by `resolveAuthorizedTranscriptTarget`), contains `.`/`..`,
693
+ * or traverses any symlink inside the authorized root.
694
+ */
695
+ function resolveAuthorizedMissingTranscriptTarget(transcriptPath, options) {
696
+ if (typeof transcriptPath !== 'string' || !transcriptPath.trim() || transcriptPath.includes('\0')) {
697
+ return null;
698
+ }
699
+ const conversationId = options?.conversationId?.trim() ?? '';
700
+ if (!isSafeConversationIdSegment(conversationId))
701
+ return null;
702
+ const rawPath = transcriptPath.trim();
703
+ if (!isAbsolute(rawPath))
704
+ return null;
705
+ const rawSegments = rawPath.split(/[/\\]/u);
706
+ if (rawSegments.includes('..') || rawSegments.includes('.')) {
707
+ return null;
708
+ }
709
+ try {
710
+ lstatSync(rawPath);
711
+ return null;
712
+ }
713
+ catch (error) {
714
+ if (!isEnoentError(error))
715
+ return null;
716
+ }
717
+ const fileName = basename(rawPath);
718
+ if (!ALLOWED_TRANSCRIPT_FILENAMES.has(fileName) || !isSafePathSegment(fileName)) {
719
+ return null;
720
+ }
721
+ let candidateCanonical = null;
722
+ const parentDir = dirname(rawPath);
723
+ try {
724
+ const parentStat = lstatSync(parentDir);
725
+ if (parentStat.isSymbolicLink() || !parentStat.isDirectory())
726
+ return null;
727
+ candidateCanonical = join(realpathSync(parentDir), fileName);
728
+ }
729
+ catch (error) {
730
+ if (!isEnoentError(error))
731
+ return null;
732
+ const parentName = basename(parentDir);
733
+ if (parentName !== 'logs' || !isSafePathSegment(parentName))
734
+ return null;
735
+ const grandParentDir = dirname(parentDir);
736
+ try {
737
+ const grandStat = lstatSync(grandParentDir);
738
+ if (grandStat.isSymbolicLink() || !grandStat.isDirectory())
739
+ return null;
740
+ candidateCanonical = join(realpathSync(grandParentDir), parentName, fileName);
741
+ }
742
+ catch {
743
+ return null;
744
+ }
745
+ }
746
+ if (!candidateCanonical)
747
+ return null;
748
+ const roots = canonicalTranscriptRoots(options);
749
+ if (roots.length === 0)
750
+ return null;
751
+ const matchedRoot = roots.find((root) => (root !== sep
752
+ && root !== '/'
753
+ && matchesConversationTranscriptStructure(root, candidateCanonical, conversationId)));
754
+ if (!matchedRoot)
755
+ return null;
756
+ try {
757
+ const rootStat = lstatSync(matchedRoot);
758
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory())
759
+ return null;
760
+ if (realpathSync(matchedRoot) !== matchedRoot)
761
+ return null;
762
+ }
763
+ catch {
764
+ return null;
765
+ }
766
+ const segments = relative(matchedRoot, candidateCanonical).split(sep);
767
+ if (segments.length === 0 || !segments.every(isSafePathSegment))
768
+ return null;
769
+ let current = matchedRoot;
770
+ let sawMissingDir = false;
771
+ for (let i = 0; i < segments.length - 1; i += 1) {
772
+ current = join(current, segments[i]);
773
+ if (sawMissingDir)
774
+ return null;
775
+ try {
776
+ const dirStat = lstatSync(current);
777
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory())
778
+ return null;
779
+ }
780
+ catch (error) {
781
+ if (!isEnoentError(error) || i !== segments.length - 2 || segments[i] !== 'logs') {
782
+ return null;
783
+ }
784
+ sawMissingDir = true;
785
+ }
786
+ }
787
+ try {
788
+ lstatSync(candidateCanonical);
789
+ return null;
790
+ }
791
+ catch (error) {
792
+ if (!isEnoentError(error))
793
+ return null;
794
+ }
795
+ return { canonicalRoot: matchedRoot, canonicalPath: candidateCanonical, segments };
796
+ }
682
797
  function buildPythonOpenatReader(faults, mode = 'tail') {
683
798
  const forceOpenat2Errno = faults?.forceOpenat2Errno;
684
799
  const renameAfterRead = faults?.renameAfterTailRead;
@@ -1024,6 +1139,9 @@ function entryToolUseId(entry) {
1024
1139
  function hasTruncatedContentField(entry) {
1025
1140
  return Array.isArray(entry.truncated_fields) && entry.truncated_fields.includes('content');
1026
1141
  }
1142
+ function isJsonWhitespaceCode(code) {
1143
+ return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
1144
+ }
1027
1145
  function isValidJsonText(text) {
1028
1146
  try {
1029
1147
  JSON.parse(text);
@@ -1033,12 +1151,112 @@ function isValidJsonText(text) {
1033
1151
  return false;
1034
1152
  }
1035
1153
  }
1154
+ /**
1155
+ * Splits whitespace/newline-concatenated top-level JSON objects/arrays (`{...}` / `[...]`)
1156
+ * in a single strict O(n) character scan without regex backtracking.
1157
+ *
1158
+ * Antigravity CLI concatenates multiple MCP text content blocks with `\n` when writing
1159
+ * `steps/<n>/output.txt` and `transcript*.jsonl` (for example, a primary tool result JSON
1160
+ * followed by a trailing `{"connection_scope":{...}}` block). When 2+ top-level JSON
1161
+ * containers are found and every block validates via `JSON.parse`, returns the individual
1162
+ * blocks so `tool_response.content` restores the original multi-block MCP structure.
1163
+ * For a single JSON value, non-JSON text, or any malformed/partial block, fails open and
1164
+ * returns `[text]`.
1165
+ */
1166
+ export function splitConcatenatedJsonTextBlocks(text) {
1167
+ const length = text.length;
1168
+ if (length === 0)
1169
+ return [text];
1170
+ let i = 0;
1171
+ while (i < length && isJsonWhitespaceCode(text.charCodeAt(i))) {
1172
+ i += 1;
1173
+ }
1174
+ if (i >= length)
1175
+ return [text];
1176
+ const firstCode = text.charCodeAt(i);
1177
+ if (firstCode !== 0x7b && firstCode !== 0x5b) {
1178
+ return [text];
1179
+ }
1180
+ const candidates = [];
1181
+ const closeStack = [];
1182
+ while (i < length) {
1183
+ const start = i;
1184
+ const openCode = text.charCodeAt(i);
1185
+ if (openCode === 0x7b) {
1186
+ closeStack.push(0x7d);
1187
+ }
1188
+ else if (openCode === 0x5b) {
1189
+ closeStack.push(0x5d);
1190
+ }
1191
+ else {
1192
+ return [text];
1193
+ }
1194
+ i += 1;
1195
+ let inString = false;
1196
+ let escaped = false;
1197
+ while (i < length && closeStack.length > 0) {
1198
+ const code = text.charCodeAt(i);
1199
+ if (inString) {
1200
+ if (escaped) {
1201
+ escaped = false;
1202
+ }
1203
+ else if (code === 0x5c) {
1204
+ escaped = true;
1205
+ }
1206
+ else if (code === 0x22) {
1207
+ inString = false;
1208
+ }
1209
+ }
1210
+ else if (code === 0x22) {
1211
+ inString = true;
1212
+ }
1213
+ else if (code === 0x7b) {
1214
+ closeStack.push(0x7d);
1215
+ }
1216
+ else if (code === 0x5b) {
1217
+ closeStack.push(0x5d);
1218
+ }
1219
+ else if (code === 0x7d || code === 0x5d) {
1220
+ if (closeStack[closeStack.length - 1] !== code) {
1221
+ return [text];
1222
+ }
1223
+ closeStack.pop();
1224
+ }
1225
+ i += 1;
1226
+ }
1227
+ if (closeStack.length !== 0 || inString) {
1228
+ return [text];
1229
+ }
1230
+ candidates.push(text.slice(start, i));
1231
+ const wsStart = i;
1232
+ while (i < length && isJsonWhitespaceCode(text.charCodeAt(i))) {
1233
+ i += 1;
1234
+ }
1235
+ if (i < length && i === wsStart) {
1236
+ return [text];
1237
+ }
1238
+ }
1239
+ if (candidates.length < 2) {
1240
+ return [text];
1241
+ }
1242
+ for (const block of candidates) {
1243
+ if (!isValidJsonText(block)) {
1244
+ return [text];
1245
+ }
1246
+ }
1247
+ return candidates;
1248
+ }
1249
+ function isValidJsonOrConcatenatedJsonText(text) {
1250
+ if (isValidJsonText(text))
1251
+ return true;
1252
+ return splitConcatenatedJsonTextBlocks(text).length > 1;
1253
+ }
1036
1254
  function isTruncatedToolResult(entry, strippedContent) {
1037
1255
  if (hasTruncatedContentField(entry))
1038
1256
  return true;
1039
1257
  if (TOOL_OUTPUT_TRUNCATION_BANNER_PATTERN.test(strippedContent))
1040
1258
  return true;
1041
- if (INLINE_TRUNCATION_MARKER_PATTERN.test(strippedContent) && !isValidJsonText(strippedContent)) {
1259
+ if (INLINE_TRUNCATION_MARKER_PATTERN.test(strippedContent) && !isValidJsonOrConcatenatedJsonText(strippedContent)) {
1042
1260
  return true;
1043
1261
  }
1044
1262
  return false;
@@ -1119,82 +1337,120 @@ function resolveSiblingFullTranscriptTarget(baseTarget, options) {
1119
1337
  }
1120
1338
  function resolveAuthorizedStepOutputTarget(baseTarget, conversationId, candidatePath) {
1121
1339
  if (!candidatePath || !isAbsolute(candidatePath) || candidatePath.includes('\0')) {
1122
- return null;
1340
+ return { kind: 'rejected' };
1123
1341
  }
1124
1342
  const sysGenSegments = systemGeneratedPrefixSegments(baseTarget, conversationId);
1125
1343
  if (!sysGenSegments)
1126
- return null;
1344
+ return { kind: 'rejected' };
1127
1345
  const stepsDirRaw = join(baseTarget.canonicalRoot, ...sysGenSegments, 'steps');
1128
1346
  try {
1129
- const stepsDirStat = lstatSync(stepsDirRaw);
1347
+ let stepsDirStat;
1348
+ try {
1349
+ stepsDirStat = lstatSync(stepsDirRaw);
1350
+ }
1351
+ catch (error) {
1352
+ return isEnoentError(error) ? { kind: 'missing' } : { kind: 'rejected' };
1353
+ }
1130
1354
  if (stepsDirStat.isSymbolicLink() || !stepsDirStat.isDirectory())
1131
- return null;
1355
+ return { kind: 'rejected' };
1132
1356
  const stepsDir = realpathSync(stepsDirRaw);
1133
1357
  if (stepsDir !== stepsDirRaw || !isStrictDescendantPath(baseTarget.canonicalRoot, stepsDir)) {
1134
- return null;
1358
+ return { kind: 'rejected' };
1359
+ }
1360
+ let candidateParentStat;
1361
+ try {
1362
+ candidateParentStat = lstatSync(dirname(candidatePath));
1363
+ }
1364
+ catch (error) {
1365
+ return isEnoentError(error) ? { kind: 'missing' } : { kind: 'rejected' };
1135
1366
  }
1136
- const candidateParentStat = lstatSync(dirname(candidatePath));
1137
1367
  if (candidateParentStat.isSymbolicLink() || !candidateParentStat.isDirectory())
1138
- return null;
1139
- const candidateStat = lstatSync(candidatePath);
1368
+ return { kind: 'rejected' };
1369
+ let candidateStat;
1370
+ try {
1371
+ candidateStat = lstatSync(candidatePath);
1372
+ }
1373
+ catch (error) {
1374
+ return isEnoentError(error) ? { kind: 'missing' } : { kind: 'rejected' };
1375
+ }
1140
1376
  if (candidateStat.isSymbolicLink() || !candidateStat.isFile())
1141
- return null;
1377
+ return { kind: 'rejected' };
1142
1378
  const canonicalFile = realpathSync(candidatePath);
1143
1379
  if (!isStrictDescendantPath(stepsDir, canonicalFile))
1144
- return null;
1380
+ return { kind: 'rejected' };
1145
1381
  const relFromSteps = relative(stepsDir, canonicalFile).split(sep);
1146
1382
  if (relFromSteps.length !== 2 || !/^\d+$/u.test(relFromSteps[0]) || relFromSteps[1] !== 'output.txt') {
1147
- return null;
1383
+ return { kind: 'rejected' };
1148
1384
  }
1149
1385
  if (!verifyNoSymlinkPathUnderRoot(baseTarget.canonicalRoot, canonicalFile).ok) {
1150
- return null;
1386
+ return { kind: 'rejected' };
1151
1387
  }
1152
1388
  return {
1153
- canonicalRoot: baseTarget.canonicalRoot,
1154
- canonicalPath: canonicalFile,
1155
- segments: [...sysGenSegments, 'steps', relFromSteps[0], 'output.txt'],
1389
+ kind: 'ok',
1390
+ target: {
1391
+ canonicalRoot: baseTarget.canonicalRoot,
1392
+ canonicalPath: canonicalFile,
1393
+ segments: [...sysGenSegments, 'steps', relFromSteps[0], 'output.txt'],
1394
+ },
1156
1395
  };
1157
1396
  }
1158
1397
  catch {
1159
- return null;
1398
+ return { kind: 'rejected' };
1160
1399
  }
1161
1400
  }
1401
+ function isToolResultEntry(entry) {
1402
+ if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
1403
+ return false;
1404
+ return typeof entry.content === 'string' && entry.content.trim().length > 0;
1405
+ }
1406
+ function hasStepIndexInTranscript(entries, stepIdx) {
1407
+ return entries.some((entry) => entry.step_index === stepIdx);
1408
+ }
1409
+ function hasConflictingToolUseIdAtStep(entries, stepIdx, toolUseId) {
1410
+ return entries.some((entry) => {
1411
+ if (entry.step_index !== stepIdx)
1412
+ return false;
1413
+ const entryId = entryToolUseId(entry);
1414
+ return entryId !== null && entryId !== toolUseId;
1415
+ });
1416
+ }
1162
1417
  function findToolEntryInTranscript(entries, stepCandidates, toolUseId) {
1163
1418
  const normalizedToolUseId = typeof toolUseId === 'string' && toolUseId.trim() ? toolUseId.trim() : null;
1164
- for (const targetStep of stepCandidates) {
1165
- if (normalizedToolUseId !== null) {
1419
+ // 1. Prefer exact tool_use_id / tool_call_id match on step candidates first.
1420
+ if (normalizedToolUseId !== null) {
1421
+ for (const targetStep of stepCandidates) {
1166
1422
  for (let index = entries.length - 1; index >= 0; index -= 1) {
1167
1423
  const entry = entries[index];
1168
- if (entry.step_index !== targetStep)
1169
- continue;
1170
- if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
1171
- continue;
1172
- if (typeof entry.content !== 'string' || !entry.content.trim())
1424
+ if (entry.step_index !== targetStep || !isToolResultEntry(entry))
1173
1425
  continue;
1174
1426
  if (entryToolUseId(entry) === normalizedToolUseId)
1175
1427
  return entry;
1176
1428
  }
1177
1429
  }
1430
+ // 2. Fall back to exact tool_use_id / tool_call_id match anywhere in the transcript tail
1431
+ // (handles step_index shifts between transcript.jsonl and transcript_full.jsonl).
1178
1432
  for (let index = entries.length - 1; index >= 0; index -= 1) {
1179
1433
  const entry = entries[index];
1180
- if (entry.step_index !== targetStep)
1181
- continue;
1182
- if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
1183
- continue;
1184
- if (typeof entry.content !== 'string' || !entry.content.trim())
1434
+ if (!isToolResultEntry(entry))
1185
1435
  continue;
1186
- return entry;
1436
+ if (entryToolUseId(entry) === normalizedToolUseId)
1437
+ return entry;
1187
1438
  }
1188
1439
  }
1189
- if (normalizedToolUseId !== null) {
1440
+ // 3. Untagged step_index match is strictly restricted to the exact primary step (`stepCandidates[0]`).
1441
+ // Never match a neighboring step (`stepIdx + 1`) without an explicit tool_use_id match, and
1442
+ // never match an entry whose explicit tool_use_id disagrees with the caller's toolUseId.
1443
+ const primaryStep = stepCandidates[0];
1444
+ if (primaryStep !== undefined) {
1190
1445
  for (let index = entries.length - 1; index >= 0; index -= 1) {
1191
1446
  const entry = entries[index];
1192
- if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
1447
+ if (entry.step_index !== primaryStep || !isToolResultEntry(entry))
1193
1448
  continue;
1194
- if (typeof entry.content !== 'string' || !entry.content.trim())
1449
+ const entryId = entryToolUseId(entry);
1450
+ if (normalizedToolUseId !== null && entryId !== null && entryId !== normalizedToolUseId) {
1195
1451
  continue;
1196
- if (entryToolUseId(entry) === normalizedToolUseId)
1197
- return entry;
1452
+ }
1453
+ return entry;
1198
1454
  }
1199
1455
  }
1200
1456
  return null;
@@ -1230,10 +1486,10 @@ function readStepOutputFallback(baseTarget, conversationId, referenceTexts, cand
1230
1486
  const filePath = parseLocalFileUrlPath(explicitUrl);
1231
1487
  if (!filePath)
1232
1488
  return null;
1233
- const stepTarget = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, filePath);
1234
- if (!stepTarget)
1489
+ const resolution = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, filePath);
1490
+ if (resolution.kind !== 'ok')
1235
1491
  return null;
1236
- return readTarget(stepTarget);
1492
+ return readTarget(resolution.target);
1237
1493
  }
1238
1494
  const sysGenSegments = systemGeneratedPrefixSegments(baseTarget, conversationId);
1239
1495
  if (!sysGenSegments)
@@ -1245,55 +1501,73 @@ function readStepOutputFallback(baseTarget, conversationId, referenceTexts, cand
1245
1501
  continue;
1246
1502
  seenSteps.add(stepNum);
1247
1503
  const candidatePath = join(stepsDir, String(stepNum), 'output.txt');
1248
- const stepTarget = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, candidatePath);
1249
- if (!stepTarget)
1504
+ const resolution = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, candidatePath);
1505
+ if (resolution.kind === 'missing')
1250
1506
  continue;
1251
- const recovered = readTarget(stepTarget);
1252
- if (recovered !== null)
1253
- return recovered;
1507
+ if (resolution.kind === 'rejected')
1508
+ return null;
1509
+ // Candidate file exists and passed path checks; fail closed immediately if reading fails
1510
+ // (oversized >512 KiB, empty, truncation banner, non-Linux, or openat2 rejection) rather
1511
+ // than falling through to another step's output.
1512
+ return readTarget(resolution.target);
1254
1513
  }
1255
1514
  return null;
1256
1515
  }
1257
1516
  export function extractToolResultFromTranscript(transcriptPath, stepIdx, options) {
1258
- const hasStepIdx = typeof stepIdx === 'number' && Number.isSafeInteger(stepIdx);
1517
+ const hasStepIdx = typeof stepIdx === 'number' && Number.isSafeInteger(stepIdx) && stepIdx >= 0;
1259
1518
  const hintToolUseId = typeof options?.toolUseId === 'string' && options.toolUseId.trim()
1260
1519
  ? options.toolUseId.trim()
1261
1520
  : undefined;
1262
1521
  if (!hasStepIdx && !hintToolUseId)
1263
1522
  return null;
1264
- const baseTarget = resolveAuthorizedTranscriptTarget(transcriptPath, options);
1265
- if (!baseTarget || !options)
1523
+ if (!options)
1524
+ return null;
1525
+ const existingBaseTarget = resolveAuthorizedTranscriptTarget(transcriptPath, options);
1526
+ const baseTarget = existingBaseTarget ?? resolveAuthorizedMissingTranscriptTarget(transcriptPath, options);
1527
+ if (!baseTarget)
1266
1528
  return null;
1267
1529
  const conversationId = options.conversationId.trim();
1268
- const baseEntries = readTranscriptEntriesFromTarget(baseTarget, options, TRANSCRIPT_TAIL_MAX_BYTES);
1269
- // Prefer exact step_index match, then immediate neighbor (+1) if wrapper shifted index.
1270
1530
  const stepCandidates = hasStepIdx ? [stepIdx, stepIdx + 1] : [];
1271
- const matchedEntry = findToolEntryInTranscript(baseEntries, stepCandidates, hintToolUseId);
1272
- if (!matchedEntry || typeof matchedEntry.content !== 'string')
1273
- return null;
1274
- const baseStripped = stripToolTimestampHeader(matchedEntry.content);
1275
- if (!baseStripped)
1276
- return null;
1277
- if (!isTruncatedToolResult(matchedEntry, baseStripped)) {
1278
- return Buffer.byteLength(baseStripped, 'utf8') <= TRANSCRIPT_TOOL_RESULT_MAX_BYTES
1279
- ? baseStripped
1280
- : null;
1531
+ let baseEntries = [];
1532
+ let matchedEntry = null;
1533
+ let baseStripped = null;
1534
+ if (existingBaseTarget !== null) {
1535
+ baseEntries = readTranscriptEntriesFromTarget(existingBaseTarget, options, TRANSCRIPT_TAIL_MAX_BYTES);
1536
+ matchedEntry = findToolEntryInTranscript(baseEntries, stepCandidates, hintToolUseId);
1537
+ if (matchedEntry && typeof matchedEntry.content === 'string') {
1538
+ const stripped = stripToolTimestampHeader(matchedEntry.content);
1539
+ if (stripped) {
1540
+ if (!isTruncatedToolResult(matchedEntry, stripped)) {
1541
+ return Buffer.byteLength(stripped, 'utf8') <= TRANSCRIPT_TOOL_RESULT_MAX_BYTES
1542
+ ? stripped
1543
+ : null;
1544
+ }
1545
+ baseStripped = stripped;
1546
+ }
1547
+ }
1281
1548
  }
1282
- const matchedStep = typeof matchedEntry.step_index === 'number' && Number.isSafeInteger(matchedEntry.step_index)
1549
+ const matchedStep = matchedEntry && typeof matchedEntry.step_index === 'number' && Number.isSafeInteger(matchedEntry.step_index)
1283
1550
  ? matchedEntry.step_index
1284
1551
  : null;
1285
1552
  const effectiveStepCandidates = [
1286
1553
  ...(matchedStep !== null ? [matchedStep] : []),
1287
1554
  ...stepCandidates.filter((step) => step !== matchedStep),
1288
1555
  ];
1289
- const effectiveToolUseId = entryToolUseId(matchedEntry) ?? hintToolUseId;
1290
- // 1. Prefer sibling `transcript_full.jsonl` in the exact same authorized logs directory.
1556
+ const effectiveToolUseId = (matchedEntry ? entryToolUseId(matchedEntry) : null) ?? hintToolUseId;
1557
+ // 1. Prefer sibling `transcript_full.jsonl` in the exact same authorized logs directory
1558
+ // (handles both truncated `transcript.jsonl` entries and steps not yet flushed to `transcript.jsonl`).
1559
+ let fullEntries = [];
1560
+ let fullEntry = null;
1291
1561
  let fullStripped = null;
1562
+ let fullMatchedStep = null;
1292
1563
  const fullTarget = resolveSiblingFullTranscriptTarget(baseTarget, options);
1293
1564
  if (fullTarget) {
1294
- const fullEntries = readTranscriptEntriesFromTarget(fullTarget, options, TRANSCRIPT_FULL_TAIL_MAX_BYTES);
1295
- const fullEntry = findToolEntryInTranscript(fullEntries, effectiveStepCandidates, effectiveToolUseId);
1565
+ fullEntries = readTranscriptEntriesFromTarget(fullTarget, options, TRANSCRIPT_FULL_TAIL_MAX_BYTES);
1566
+ fullEntry = findToolEntryInTranscript(fullEntries, effectiveStepCandidates, effectiveToolUseId);
1296
1567
  if (fullEntry && typeof fullEntry.content === 'string') {
1568
+ if (typeof fullEntry.step_index === 'number' && Number.isSafeInteger(fullEntry.step_index)) {
1569
+ fullMatchedStep = fullEntry.step_index;
1570
+ }
1297
1571
  const candidateStripped = stripToolTimestampHeader(fullEntry.content);
1298
1572
  if (candidateStripped) {
1299
1573
  if (!isTruncatedToolResult(fullEntry, candidateStripped)) {
@@ -1307,8 +1581,49 @@ export function extractToolResultFromTranscript(transcriptPath, stepIdx, options
1307
1581
  }
1308
1582
  // 2. Fallback to authorized `<conversation>/.system_generated/steps/<n>/output.txt`
1309
1583
  // (strictly confined by realpath + no-symlink + Linux openat2 RESOLVE_BENEATH).
1310
- const referenceTexts = fullStripped !== null ? [fullStripped, baseStripped] : [baseStripped];
1311
- return readStepOutputFallback(baseTarget, conversationId, referenceTexts, effectiveStepCandidates, options);
1584
+ const hasMatchedTranscriptEntry = matchedEntry !== null || fullEntry !== null;
1585
+ let stepFallbackCandidates;
1586
+ if (hasMatchedTranscriptEntry) {
1587
+ if (fullEntry === null && matchedStep !== null && effectiveToolUseId
1588
+ && hasConflictingToolUseIdAtStep(fullEntries, matchedStep, effectiveToolUseId)) {
1589
+ return null;
1590
+ }
1591
+ stepFallbackCandidates = [
1592
+ ...(fullMatchedStep !== null ? [fullMatchedStep] : []),
1593
+ ...effectiveStepCandidates.filter((step) => step !== fullMatchedStep),
1594
+ ];
1595
+ }
1596
+ else {
1597
+ // Unflushed direct recovery: Antigravity writes `steps/<stepIdx>/output.txt` before flushing
1598
+ // `transcript.jsonl`. Strictly limit candidates to the exact `[stepIdx]` (never `stepIdx + 1`)
1599
+ // and fail closed if either transcript already has an entry at `stepIdx` (e.g. PLANNER_RESPONSE,
1600
+ // USER_INPUT, non-tool entry, or conflicting tool_use_id).
1601
+ if (!hasStepIdx)
1602
+ return null;
1603
+ if (hasStepIndexInTranscript(baseEntries, stepIdx) || hasStepIndexInTranscript(fullEntries, stepIdx)) {
1604
+ return null;
1605
+ }
1606
+ stepFallbackCandidates = [stepIdx];
1607
+ }
1608
+ const referenceTexts = [];
1609
+ if (fullStripped !== null)
1610
+ referenceTexts.push(fullStripped);
1611
+ if (baseStripped !== null)
1612
+ referenceTexts.push(baseStripped);
1613
+ if (referenceTexts.length === 0 && stepFallbackCandidates.length === 0) {
1614
+ return null;
1615
+ }
1616
+ return readStepOutputFallback(baseTarget, conversationId, referenceTexts, stepFallbackCandidates, options);
1617
+ }
1618
+ /**
1619
+ * Extracts a tool result from the authorized transcript / step output and restores
1620
+ * whitespace/newline-concatenated MCP JSON text blocks into individual text block strings.
1621
+ */
1622
+ export function extractToolResultTextBlocksFromTranscript(transcriptPath, stepIdx, options) {
1623
+ const extracted = extractToolResultFromTranscript(transcriptPath, stepIdx, options);
1624
+ if (extracted === null)
1625
+ return null;
1626
+ return splitConcatenatedJsonTextBlocks(extracted);
1312
1627
  }
1313
1628
  // ---- Turn state persistence & exclusive lock ----
1314
1629
  function turnDirectory(env) {
@@ -1669,12 +1984,18 @@ function buildSystemMessageStep(turnId, additionalContext, userMarkdown) {
1669
1984
  `[Brainbase Judgment Turn: ${turnId}]`,
1670
1985
  `※この判断契約・先頭監査行は当ターン(${turnId})のみ有効です。過去のターンに注入された旧ターンの判断契約・先頭監査行は上書きされ無効です。`,
1671
1986
  ].join('\n');
1672
- const modelBody = normalizedContext ?? normalizedMarkdown;
1673
- const modelText = modelBody ? `${guardHeader}\n\n${modelBody}` : '';
1987
+ const bodyParts = [];
1988
+ if (normalizedMarkdown) {
1989
+ bodyParts.push(normalizedMarkdown);
1990
+ }
1991
+ if (normalizedContext && normalizedContext !== normalizedMarkdown) {
1992
+ bodyParts.push(normalizedContext);
1993
+ }
1994
+ const modelBody = bodyParts.join('\n\n');
1995
+ const modelText = `${guardHeader}\n\n${modelBody}`;
1674
1996
  return {
1675
1997
  systemMessage: {
1676
1998
  systemMessage: modelText,
1677
- ...(normalizedMarkdown ? { metadata: { user_markdown: normalizedMarkdown } } : {}),
1678
1999
  },
1679
2000
  };
1680
2001
  }
@@ -2044,10 +2365,10 @@ async function handlePostToolUse(payload, conversationId, context) {
2044
2365
  if (isBrainbase) {
2045
2366
  toolInput = normalizedToolInput(rawName, normalizedName, toolCall?.args);
2046
2367
  const toolCallId = typeof toolCall?.id === 'string' && toolCall.id.trim() ? toolCall.id.trim() : undefined;
2047
- const transcriptText = extractToolResultFromTranscript(payload.transcriptPath, payload.stepIdx, toolCallId ? { ...transcriptOpts, toolUseId: toolCallId } : transcriptOpts);
2048
- if (transcriptText !== null) {
2368
+ const transcriptBlocks = extractToolResultTextBlocksFromTranscript(payload.transcriptPath, payload.stepIdx, toolCallId ? { ...transcriptOpts, toolUseId: toolCallId } : transcriptOpts);
2369
+ if (transcriptBlocks !== null) {
2049
2370
  toolResponse = {
2050
- content: [{ type: 'text', text: transcriptText }],
2371
+ content: transcriptBlocks.map((text) => ({ type: 'text', text })),
2051
2372
  isError: hasError,
2052
2373
  };
2053
2374
  }
@@ -2349,6 +2670,7 @@ export function registerAntigravityJudgmentHooks(hooksJson, options) {
2349
2670
  }
2350
2671
  /** @internal Exposed strictly for deterministic concurrency and TOCTOU regression tests. */
2351
2672
  export const __antigravityHookTestInternals = {
2673
+ buildSystemMessageStep,
2352
2674
  withTurnStateLock,
2353
2675
  readTranscriptTailEntries,
2354
2676
  resolveOpenatHelperBinary,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unson/brainbase-mcp",
3
- "version": "0.51.1",
3
+ "version": "0.51.3",
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",
@@ -669,5 +669,5 @@
669
669
  "url": "https://github.com/Unson-LLC/brainbase/issues"
670
670
  },
671
671
  "homepage": "https://github.com/Unson-LLC/brainbase#readme",
672
- "gitHead": "1a653d52cda7bbbbae6bdad0c83bfa84eeed2c24"
672
+ "gitHead": "862b25ea71345948f91b70f6b70ba048de576e1a"
673
673
  }