@unson/brainbase-mcp 0.51.0 → 0.51.1

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.
@@ -72,6 +72,8 @@ export interface TranscriptReadOptions {
72
72
  conversationId: string;
73
73
  allowedTranscriptRoots?: readonly string[];
74
74
  env?: NodeJS.ProcessEnv;
75
+ /** Optional tool_use_id / tool_call_id hint when resolving truncated or shifted tool results. */
76
+ toolUseId?: string;
75
77
  /** Override for the Linux `openat2` helper executable path (strictly for tests). */
76
78
  openatHelperBinary?: string;
77
79
  /** Override runtime platform check (strictly for tests). */
@@ -105,9 +107,12 @@ export declare function isAntigravityHookConfigText(text: string): boolean;
105
107
  export declare function normalizeAntigravityToolName(name: string, args?: unknown): string;
106
108
  interface TranscriptEntry {
107
109
  step_index?: unknown;
110
+ tool_use_id?: unknown;
111
+ tool_call_id?: unknown;
108
112
  source?: unknown;
109
113
  type?: unknown;
110
114
  content?: unknown;
115
+ truncated_fields?: unknown;
111
116
  }
112
117
  interface TranscriptOpenatTestFaults {
113
118
  /** Force Linux openat2(2) to fail with the specified errno to verify immediate fail-closed rejection (no fallback). */
@@ -26,7 +26,8 @@ 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, isAbsolute, join, relative, resolve, sep } from 'node:path';
29
+ import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
30
+ import { fileURLToPath } from 'node:url';
30
31
  import { BrainbaseLoginError, getAccessTokenOfLogin } from './brainbase-login.js';
31
32
  import { PRE_TOOL_USE_TOOLS, REGISTRATION_ID, bearerTransportSafe, canonicalFilePath, canonicalRepositoryIdentifier, digestSummary, forwardedStopPayload, hostCanMapRepository, resolveRepositoryScope, shellQuote, singleQuotedWords, } from './claude-code-judgment-hook.js';
32
33
  export const ANTIGRAVITY_HOOK_CONFIG_SCHEMA = 'brainbase-antigravity-judgment-hook-v1';
@@ -41,6 +42,8 @@ export const DEFAULT_ANTIGRAVITY_TIMEOUTS_MS = {
41
42
  const TURN_SCHEMA = 'brainbase-antigravity-judgment-turn-v1';
42
43
  const PROJECT_CODE_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
43
44
  const TRANSCRIPT_TAIL_MAX_BYTES = 256 * 1024;
45
+ const TRANSCRIPT_FULL_TAIL_MAX_BYTES = 1024 * 1024;
46
+ const TRANSCRIPT_TOOL_RESULT_MAX_BYTES = 512 * 1024;
44
47
  const TRANSCRIPT_OPENAT_TIMEOUT_MS = 1_500;
45
48
  const MAX_PENDING_MESSAGES = 8;
46
49
  const DEFAULT_STALE_TURN_MS = 30 * 60 * 1000;
@@ -676,7 +679,7 @@ function resolveAuthorizedTranscriptTarget(transcriptPath, options) {
676
679
  function resolveAuthorizedTranscriptPath(transcriptPath, options) {
677
680
  return resolveAuthorizedTranscriptTarget(transcriptPath, options)?.canonicalPath ?? null;
678
681
  }
679
- function buildPythonOpenatTailReader(faults) {
682
+ function buildPythonOpenatReader(faults, mode = 'tail') {
680
683
  const forceOpenat2Errno = faults?.forceOpenat2Errno;
681
684
  const renameAfterRead = faults?.renameAfterTailRead;
682
685
  const lines = [
@@ -759,8 +762,16 @@ function buildPythonOpenatTailReader(faults) {
759
762
  ' verify_fd_exact_path(file_fd, expected_exact_path)',
760
763
  ' size = st.st_size',
761
764
  ' if size <= 0: sys.exit(0)',
762
- ' read_size = min(size, max_bytes)',
763
- ' offset = size - read_size',
765
+ ...(mode === 'full'
766
+ ? [
767
+ ' if size > max_bytes: fail()',
768
+ ' read_size = size',
769
+ ' offset = 0',
770
+ ]
771
+ : [
772
+ ' read_size = min(size, max_bytes)',
773
+ ' offset = size - read_size',
774
+ ]),
764
775
  ' chunks = []',
765
776
  ' remaining = read_size',
766
777
  ' pos = offset',
@@ -777,12 +788,22 @@ function buildPythonOpenatTailReader(faults) {
777
788
  ? [` os.rename(${JSON.stringify(renameAfterRead.from)}, ${JSON.stringify(renameAfterRead.to)})`]
778
789
  : []),
779
790
  ' verify_fd_exact_path(file_fd, expected_exact_path)',
780
- ' if not stat.S_ISREG(os.fstat(file_fd).st_mode): fail()',
791
+ ' post_st = os.fstat(file_fd)',
792
+ ' if not stat.S_ISREG(post_st.st_mode): fail()',
793
+ ...(mode === 'full'
794
+ ? [' if post_st.st_size > max_bytes: fail()']
795
+ : []),
781
796
  ' data = b"".join(chunks)',
782
- ' if offset > 0:',
783
- ' nl = data.find(b"\\n")',
784
- ' if nl < 0: sys.exit(0)',
785
- ' data = data[nl + 1:]',
797
+ ...(mode === 'tail'
798
+ ? [
799
+ ' if offset > 0:',
800
+ ' nl = data.find(b"\\n")',
801
+ ' if nl < 0: sys.exit(0)',
802
+ ' data = data[nl + 1:]',
803
+ ]
804
+ : [
805
+ ' if len(data) > max_bytes: fail()',
806
+ ]),
786
807
  ' if data:',
787
808
  ' sys.stdout.buffer.write(data)',
788
809
  ' sys.stdout.buffer.flush()',
@@ -798,7 +819,8 @@ function buildPythonOpenatTailReader(faults) {
798
819
  ];
799
820
  return lines.join('\n');
800
821
  }
801
- const PYTHON_OPENAT_TAIL_READER = buildPythonOpenatTailReader();
822
+ const PYTHON_OPENAT_TAIL_READER = buildPythonOpenatReader(undefined, 'tail');
823
+ const PYTHON_OPENAT_FULL_READER = buildPythonOpenatReader(undefined, 'full');
802
824
  const DEFAULT_OPENAT_HELPER_CANDIDATES = [
803
825
  '/usr/bin/python3',
804
826
  '/usr/local/bin/python3',
@@ -860,9 +882,10 @@ function readTailViaKernelOpenat(canonicalRoot, segments, maxBytes, options) {
860
882
  return null;
861
883
  }
862
884
  const timeoutMs = options?.helperTimeoutMs ?? TRANSCRIPT_OPENAT_TIMEOUT_MS;
885
+ const mode = options?.mode ?? 'tail';
863
886
  const helperScript = options?.openatTestFaults
864
- ? buildPythonOpenatTailReader(options.openatTestFaults)
865
- : PYTHON_OPENAT_TAIL_READER;
887
+ ? buildPythonOpenatReader(options.openatTestFaults, mode)
888
+ : (mode === 'full' ? PYTHON_OPENAT_FULL_READER : PYTHON_OPENAT_TAIL_READER);
866
889
  try {
867
890
  const result = spawnSync(helperBin, ['-I', '-c', helperScript, canonicalRoot, String(maxBytes), ...segments], {
868
891
  encoding: 'buffer',
@@ -883,18 +906,16 @@ function readTailViaKernelOpenat(canonicalRoot, segments, maxBytes, options) {
883
906
  return null;
884
907
  }
885
908
  }
886
- function readTranscriptTailEntries(transcriptPath, options, testHooks) {
887
- const target = resolveAuthorizedTranscriptTarget(transcriptPath, options);
888
- if (!target || !options)
889
- return [];
909
+ function readTranscriptEntriesFromTarget(target, options, maxBytes, testHooks) {
890
910
  try {
891
911
  testHooks?.onBeforeOpen?.(target.canonicalPath);
892
- const rawTail = readTailViaKernelOpenat(target.canonicalRoot, target.segments, TRANSCRIPT_TAIL_MAX_BYTES, {
912
+ const rawTail = readTailViaKernelOpenat(target.canonicalRoot, target.segments, maxBytes, {
893
913
  openatHelperBinary: testHooks?.openatHelperBinary ?? options.openatHelperBinary,
894
914
  openatHelperCandidates: testHooks?.openatHelperCandidates,
895
915
  helperTimeoutMs: testHooks?.helperTimeoutMs,
896
916
  platform: testHooks?.platform ?? options.platform,
897
917
  openatTestFaults: testHooks?.openatTestFaults,
918
+ mode: 'tail',
898
919
  });
899
920
  if (rawTail === null || rawTail.length === 0)
900
921
  return [];
@@ -920,6 +941,12 @@ function readTranscriptTailEntries(transcriptPath, options, testHooks) {
920
941
  return [];
921
942
  }
922
943
  }
944
+ function readTranscriptTailEntries(transcriptPath, options, testHooks) {
945
+ const target = resolveAuthorizedTranscriptTarget(transcriptPath, options);
946
+ if (!target || !options)
947
+ return [];
948
+ return readTranscriptEntriesFromTarget(target, options, TRANSCRIPT_TAIL_MAX_BYTES, testHooks);
949
+ }
923
950
  function stripUserRequestWrapper(text) {
924
951
  const trimmed = text.trim();
925
952
  const match = /^<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/u.exec(trimmed);
@@ -982,12 +1009,172 @@ function stripToolTimestampHeader(text) {
982
1009
  const body = lines.slice(index).join('\n').trim();
983
1010
  return body || text.trim();
984
1011
  }
985
- export function extractToolResultFromTranscript(transcriptPath, stepIdx, options) {
986
- if (typeof stepIdx !== 'number' || !Number.isSafeInteger(stepIdx))
1012
+ const TOOL_OUTPUT_TRUNCATION_BANNER_PATTERN = /^The tool's output was truncated due to being too long\./u;
1013
+ const INLINE_TRUNCATION_MARKER_PATTERN = /<truncated\s+\d+(?:\s+of\s+\d+)?\s+bytes(?:\s[^><\r\n]{0,256})?>/iu;
1014
+ const TRUNCATED_OUTPUT_FILE_URL_PATTERN = /^The tool's output was truncated due to being too long\.\s+You can find the full output in (?:a )?file at (file:\/\/[^\s"'<>]+)/u;
1015
+ function entryToolUseId(entry) {
1016
+ if (typeof entry.tool_use_id === 'string' && entry.tool_use_id.trim()) {
1017
+ return entry.tool_use_id.trim();
1018
+ }
1019
+ if (typeof entry.tool_call_id === 'string' && entry.tool_call_id.trim()) {
1020
+ return entry.tool_call_id.trim();
1021
+ }
1022
+ return null;
1023
+ }
1024
+ function hasTruncatedContentField(entry) {
1025
+ return Array.isArray(entry.truncated_fields) && entry.truncated_fields.includes('content');
1026
+ }
1027
+ function isValidJsonText(text) {
1028
+ try {
1029
+ JSON.parse(text);
1030
+ return true;
1031
+ }
1032
+ catch {
1033
+ return false;
1034
+ }
1035
+ }
1036
+ function isTruncatedToolResult(entry, strippedContent) {
1037
+ if (hasTruncatedContentField(entry))
1038
+ return true;
1039
+ if (TOOL_OUTPUT_TRUNCATION_BANNER_PATTERN.test(strippedContent))
1040
+ return true;
1041
+ if (INLINE_TRUNCATION_MARKER_PATTERN.test(strippedContent) && !isValidJsonText(strippedContent)) {
1042
+ return true;
1043
+ }
1044
+ return false;
1045
+ }
1046
+ function trimTrailingUrlPunctuation(rawUrl) {
1047
+ let end = rawUrl.length;
1048
+ while (end > 0) {
1049
+ const ch = rawUrl[end - 1];
1050
+ if (ch === '.' || ch === ',' || ch === ';' || ch === ')' || ch === ']') {
1051
+ end -= 1;
1052
+ }
1053
+ else {
1054
+ break;
1055
+ }
1056
+ }
1057
+ return rawUrl.slice(0, end);
1058
+ }
1059
+ function extractTruncatedOutputFileUrl(text) {
1060
+ const match = TRUNCATED_OUTPUT_FILE_URL_PATTERN.exec(text);
1061
+ if (!match)
987
1062
  return null;
988
- const entries = readTranscriptTailEntries(transcriptPath, options);
989
- // Prefer exact step_index match, then immediate neighbor (+1) if wrapper shifted index.
990
- for (const targetStep of [stepIdx, stepIdx + 1]) {
1063
+ const cleaned = trimTrailingUrlPunctuation(match[1]);
1064
+ return cleaned || null;
1065
+ }
1066
+ function parseLocalFileUrlPath(rawUrl) {
1067
+ let url;
1068
+ try {
1069
+ url = new URL(rawUrl);
1070
+ }
1071
+ catch {
1072
+ return null;
1073
+ }
1074
+ if (url.protocol !== 'file:' || url.hostname || url.search || url.hash) {
1075
+ return null;
1076
+ }
1077
+ try {
1078
+ const filePath = fileURLToPath(url);
1079
+ if (!filePath || !isAbsolute(filePath) || filePath.includes('\0')) {
1080
+ return null;
1081
+ }
1082
+ return filePath;
1083
+ }
1084
+ catch {
1085
+ return null;
1086
+ }
1087
+ }
1088
+ function systemGeneratedPrefixSegments(target, conversationId) {
1089
+ const segs = target.segments;
1090
+ if (segs.length === 4
1091
+ && segs[0] === conversationId
1092
+ && segs[1] === '.system_generated'
1093
+ && segs[2] === 'logs') {
1094
+ return [conversationId, '.system_generated'];
1095
+ }
1096
+ if (segs.length === 5
1097
+ && segs[0] === 'brain'
1098
+ && segs[1] === conversationId
1099
+ && segs[2] === '.system_generated'
1100
+ && segs[3] === 'logs') {
1101
+ return ['brain', conversationId, '.system_generated'];
1102
+ }
1103
+ return null;
1104
+ }
1105
+ function resolveSiblingFullTranscriptTarget(baseTarget, options) {
1106
+ if (baseTarget.segments[baseTarget.segments.length - 1] !== 'transcript.jsonl') {
1107
+ return null;
1108
+ }
1109
+ const baseDir = dirname(baseTarget.canonicalPath);
1110
+ const candidatePath = join(baseDir, 'transcript_full.jsonl');
1111
+ const fullTarget = resolveAuthorizedTranscriptTarget(candidatePath, options);
1112
+ if (!fullTarget)
1113
+ return null;
1114
+ if (fullTarget.canonicalRoot !== baseTarget.canonicalRoot)
1115
+ return null;
1116
+ if (dirname(fullTarget.canonicalPath) !== baseDir)
1117
+ return null;
1118
+ return fullTarget;
1119
+ }
1120
+ function resolveAuthorizedStepOutputTarget(baseTarget, conversationId, candidatePath) {
1121
+ if (!candidatePath || !isAbsolute(candidatePath) || candidatePath.includes('\0')) {
1122
+ return null;
1123
+ }
1124
+ const sysGenSegments = systemGeneratedPrefixSegments(baseTarget, conversationId);
1125
+ if (!sysGenSegments)
1126
+ return null;
1127
+ const stepsDirRaw = join(baseTarget.canonicalRoot, ...sysGenSegments, 'steps');
1128
+ try {
1129
+ const stepsDirStat = lstatSync(stepsDirRaw);
1130
+ if (stepsDirStat.isSymbolicLink() || !stepsDirStat.isDirectory())
1131
+ return null;
1132
+ const stepsDir = realpathSync(stepsDirRaw);
1133
+ if (stepsDir !== stepsDirRaw || !isStrictDescendantPath(baseTarget.canonicalRoot, stepsDir)) {
1134
+ return null;
1135
+ }
1136
+ const candidateParentStat = lstatSync(dirname(candidatePath));
1137
+ if (candidateParentStat.isSymbolicLink() || !candidateParentStat.isDirectory())
1138
+ return null;
1139
+ const candidateStat = lstatSync(candidatePath);
1140
+ if (candidateStat.isSymbolicLink() || !candidateStat.isFile())
1141
+ return null;
1142
+ const canonicalFile = realpathSync(candidatePath);
1143
+ if (!isStrictDescendantPath(stepsDir, canonicalFile))
1144
+ return null;
1145
+ const relFromSteps = relative(stepsDir, canonicalFile).split(sep);
1146
+ if (relFromSteps.length !== 2 || !/^\d+$/u.test(relFromSteps[0]) || relFromSteps[1] !== 'output.txt') {
1147
+ return null;
1148
+ }
1149
+ if (!verifyNoSymlinkPathUnderRoot(baseTarget.canonicalRoot, canonicalFile).ok) {
1150
+ return null;
1151
+ }
1152
+ return {
1153
+ canonicalRoot: baseTarget.canonicalRoot,
1154
+ canonicalPath: canonicalFile,
1155
+ segments: [...sysGenSegments, 'steps', relFromSteps[0], 'output.txt'],
1156
+ };
1157
+ }
1158
+ catch {
1159
+ return null;
1160
+ }
1161
+ }
1162
+ function findToolEntryInTranscript(entries, stepCandidates, toolUseId) {
1163
+ const normalizedToolUseId = typeof toolUseId === 'string' && toolUseId.trim() ? toolUseId.trim() : null;
1164
+ for (const targetStep of stepCandidates) {
1165
+ if (normalizedToolUseId !== null) {
1166
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
1167
+ 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())
1173
+ continue;
1174
+ if (entryToolUseId(entry) === normalizedToolUseId)
1175
+ return entry;
1176
+ }
1177
+ }
991
1178
  for (let index = entries.length - 1; index >= 0; index -= 1) {
992
1179
  const entry = entries[index];
993
1180
  if (entry.step_index !== targetStep)
@@ -996,11 +1183,133 @@ export function extractToolResultFromTranscript(transcriptPath, stepIdx, options
996
1183
  continue;
997
1184
  if (typeof entry.content !== 'string' || !entry.content.trim())
998
1185
  continue;
999
- return stripToolTimestampHeader(entry.content);
1186
+ return entry;
1187
+ }
1188
+ }
1189
+ if (normalizedToolUseId !== null) {
1190
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
1191
+ const entry = entries[index];
1192
+ if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
1193
+ continue;
1194
+ if (typeof entry.content !== 'string' || !entry.content.trim())
1195
+ continue;
1196
+ if (entryToolUseId(entry) === normalizedToolUseId)
1197
+ return entry;
1198
+ }
1199
+ }
1200
+ return null;
1201
+ }
1202
+ function readStepOutputFallback(baseTarget, conversationId, referenceTexts, candidateSteps, options) {
1203
+ let explicitUrl = null;
1204
+ for (const text of referenceTexts) {
1205
+ const found = extractTruncatedOutputFileUrl(text);
1206
+ if (found) {
1207
+ explicitUrl = found;
1208
+ break;
1000
1209
  }
1001
1210
  }
1211
+ const readTarget = (stepTarget) => {
1212
+ const raw = readTailViaKernelOpenat(stepTarget.canonicalRoot, stepTarget.segments, TRANSCRIPT_TOOL_RESULT_MAX_BYTES, {
1213
+ openatHelperBinary: options.openatHelperBinary,
1214
+ platform: options.platform,
1215
+ mode: 'full',
1216
+ });
1217
+ if (raw === null || raw.length === 0)
1218
+ return null;
1219
+ const decoded = raw.toString('utf8');
1220
+ const stripped = stripToolTimestampHeader(decoded);
1221
+ if (!stripped)
1222
+ return null;
1223
+ if (Buffer.byteLength(stripped, 'utf8') > TRANSCRIPT_TOOL_RESULT_MAX_BYTES)
1224
+ return null;
1225
+ if (isTruncatedToolResult({ content: decoded }, stripped))
1226
+ return null;
1227
+ return stripped;
1228
+ };
1229
+ if (explicitUrl !== null) {
1230
+ const filePath = parseLocalFileUrlPath(explicitUrl);
1231
+ if (!filePath)
1232
+ return null;
1233
+ const stepTarget = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, filePath);
1234
+ if (!stepTarget)
1235
+ return null;
1236
+ return readTarget(stepTarget);
1237
+ }
1238
+ const sysGenSegments = systemGeneratedPrefixSegments(baseTarget, conversationId);
1239
+ if (!sysGenSegments)
1240
+ return null;
1241
+ const stepsDir = join(baseTarget.canonicalRoot, ...sysGenSegments, 'steps');
1242
+ const seenSteps = new Set();
1243
+ for (const stepNum of candidateSteps) {
1244
+ if (!Number.isSafeInteger(stepNum) || stepNum < 0 || seenSteps.has(stepNum))
1245
+ continue;
1246
+ seenSteps.add(stepNum);
1247
+ const candidatePath = join(stepsDir, String(stepNum), 'output.txt');
1248
+ const stepTarget = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, candidatePath);
1249
+ if (!stepTarget)
1250
+ continue;
1251
+ const recovered = readTarget(stepTarget);
1252
+ if (recovered !== null)
1253
+ return recovered;
1254
+ }
1002
1255
  return null;
1003
1256
  }
1257
+ export function extractToolResultFromTranscript(transcriptPath, stepIdx, options) {
1258
+ const hasStepIdx = typeof stepIdx === 'number' && Number.isSafeInteger(stepIdx);
1259
+ const hintToolUseId = typeof options?.toolUseId === 'string' && options.toolUseId.trim()
1260
+ ? options.toolUseId.trim()
1261
+ : undefined;
1262
+ if (!hasStepIdx && !hintToolUseId)
1263
+ return null;
1264
+ const baseTarget = resolveAuthorizedTranscriptTarget(transcriptPath, options);
1265
+ if (!baseTarget || !options)
1266
+ return null;
1267
+ 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
+ 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;
1281
+ }
1282
+ const matchedStep = typeof matchedEntry.step_index === 'number' && Number.isSafeInteger(matchedEntry.step_index)
1283
+ ? matchedEntry.step_index
1284
+ : null;
1285
+ const effectiveStepCandidates = [
1286
+ ...(matchedStep !== null ? [matchedStep] : []),
1287
+ ...stepCandidates.filter((step) => step !== matchedStep),
1288
+ ];
1289
+ const effectiveToolUseId = entryToolUseId(matchedEntry) ?? hintToolUseId;
1290
+ // 1. Prefer sibling `transcript_full.jsonl` in the exact same authorized logs directory.
1291
+ let fullStripped = null;
1292
+ const fullTarget = resolveSiblingFullTranscriptTarget(baseTarget, options);
1293
+ if (fullTarget) {
1294
+ const fullEntries = readTranscriptEntriesFromTarget(fullTarget, options, TRANSCRIPT_FULL_TAIL_MAX_BYTES);
1295
+ const fullEntry = findToolEntryInTranscript(fullEntries, effectiveStepCandidates, effectiveToolUseId);
1296
+ if (fullEntry && typeof fullEntry.content === 'string') {
1297
+ const candidateStripped = stripToolTimestampHeader(fullEntry.content);
1298
+ if (candidateStripped) {
1299
+ if (!isTruncatedToolResult(fullEntry, candidateStripped)) {
1300
+ return Buffer.byteLength(candidateStripped, 'utf8') <= TRANSCRIPT_TOOL_RESULT_MAX_BYTES
1301
+ ? candidateStripped
1302
+ : null;
1303
+ }
1304
+ fullStripped = candidateStripped;
1305
+ }
1306
+ }
1307
+ }
1308
+ // 2. Fallback to authorized `<conversation>/.system_generated/steps/<n>/output.txt`
1309
+ // (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);
1312
+ }
1004
1313
  // ---- Turn state persistence & exclusive lock ----
1005
1314
  function turnDirectory(env) {
1006
1315
  return env.BRAINBASE_ANTIGRAVITY_JUDGMENT_TURN_DIR
@@ -1348,17 +1657,24 @@ function extractHostMessages(output) {
1348
1657
  * the header binds it to the current `turn_id` and explicitly supersedes earlier turns.
1349
1658
  */
1350
1659
  function buildSystemMessageStep(turnId, additionalContext, userMarkdown) {
1351
- if (!additionalContext && !userMarkdown)
1660
+ const normalizedContext = typeof additionalContext === 'string' && additionalContext.trim()
1661
+ ? additionalContext.trim()
1662
+ : undefined;
1663
+ const normalizedMarkdown = typeof userMarkdown === 'string' && userMarkdown.trim()
1664
+ ? userMarkdown.trim()
1665
+ : undefined;
1666
+ if (!normalizedContext && !normalizedMarkdown)
1352
1667
  return null;
1353
1668
  const guardHeader = [
1354
1669
  `[Brainbase Judgment Turn: ${turnId}]`,
1355
1670
  `※この判断契約・先頭監査行は当ターン(${turnId})のみ有効です。過去のターンに注入された旧ターンの判断契約・先頭監査行は上書きされ無効です。`,
1356
1671
  ].join('\n');
1357
- const modelText = additionalContext ? `${guardHeader}\n\n${additionalContext}` : '';
1672
+ const modelBody = normalizedContext ?? normalizedMarkdown;
1673
+ const modelText = modelBody ? `${guardHeader}\n\n${modelBody}` : '';
1358
1674
  return {
1359
1675
  systemMessage: {
1360
1676
  systemMessage: modelText,
1361
- ...(userMarkdown ? { metadata: { user_markdown: userMarkdown } } : {}),
1677
+ ...(normalizedMarkdown ? { metadata: { user_markdown: normalizedMarkdown } } : {}),
1362
1678
  },
1363
1679
  };
1364
1680
  }
@@ -1727,7 +2043,8 @@ async function handlePostToolUse(payload, conversationId, context) {
1727
2043
  let errorField;
1728
2044
  if (isBrainbase) {
1729
2045
  toolInput = normalizedToolInput(rawName, normalizedName, toolCall?.args);
1730
- const transcriptText = extractToolResultFromTranscript(payload.transcriptPath, payload.stepIdx, transcriptOpts);
2046
+ 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);
1731
2048
  if (transcriptText !== null) {
1732
2049
  toolResponse = {
1733
2050
  content: [{ type: 'text', text: transcriptText }],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unson/brainbase-mcp",
3
- "version": "0.51.0",
3
+ "version": "0.51.1",
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": "8b9acad360928fd94db972da5861ea90044ea481"
672
+ "gitHead": "1a653d52cda7bbbbae6bdad0c83bfa84eeed2c24"
673
673
  }