@unson/brainbase-mcp 0.51.6 → 0.51.7

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.
@@ -139,6 +139,32 @@ interface TranscriptOpenTestHooks {
139
139
  }
140
140
  declare function resolveOpenatHelperBinary(override?: string, platform?: NodeJS.Platform, candidates?: readonly string[]): string | null;
141
141
  declare function readTranscriptTailEntries(transcriptPath: unknown, options?: TranscriptReadOptions, testHooks?: TranscriptOpenTestHooks): TranscriptEntry[];
142
+ /**
143
+ * Deterministically strips only exact Orca-injected leading system preamble
144
+ * blocks in linear time without regex backtracking:
145
+ * - `[Your SOUL.md was updated; ...]` (with an accompanying `<<<\n...\n>>>` fence
146
+ * or bounded by a subsequent valid known Orca / MEMORY.md preamble)
147
+ * - `[Your MEMORY.md changed outside this chat ...]` ONLY when followed by at least
148
+ * one `Added:` / `Removed:` / bare `<<<\n...\n>>>` fence block
149
+ * - Fenced Orca `[Orca: ...]` preambles (`your other chats active in the last `,
150
+ * `your live work now, `, `your MEMORY.md, as notes to consult, `) ONLY when
151
+ * immediately followed by a `<<<\n...\n>>>` fence block
152
+ * - Exact full-string `[Orca: if you asked your owner something in this chat ...]`
153
+ * system reminder (standalone; never consumes a following `<<<\n...\n>>>` block)
154
+ * - Strict ISO-8601 `[Orca: it is <ISO-8601>, the time you were asked to act at.( This is the only run.)?]`
155
+ * scheduled-time header with strict calendar/clock/timezone validation
156
+ * (standalone; never consumes a following `<<<\n...\n>>>` block)
157
+ *
158
+ * Any utterance that does not match one of these exact system formats — including
159
+ * invalid ISO-8601 timestamps, fenceless known prefixes, shortened unanswered-question
160
+ * headers, unknown `[Orca: ...]` headers (with or without fences), and ordinary prompts
161
+ * with leading/trailing whitespace — is returned 100% byte-for-byte untouched.
162
+ *
163
+ * Fail-safe: when 0 preambles are consumed or stripping would yield an empty/whitespace-only
164
+ * string, returns the original `text` untouched. Never alters ordinary user utterances or
165
+ * bot-to-bot `──── From: ORCA_SESSION_ID:...` message bodies.
166
+ */
167
+ export declare function stripOrcaInjectedPreambles(text: string): string;
142
168
  /**
143
169
  * Identifies system-injected USER_INPUT messages (e.g. Reason Network hooks)
144
170
  * so they never masquerade as a fresh human prompt or trigger duplicate turns.
@@ -150,16 +176,19 @@ export declare function extractLatestNonSystemUserInput(transcriptPath: unknown,
150
176
  } | null;
151
177
  export declare function extractLastAssistantMessage(transcriptPath: unknown, options?: TranscriptReadOptions): string | undefined;
152
178
  /**
153
- * Splits whitespace/newline-concatenated top-level JSON objects/arrays (`{...}` / `[...]`)
154
- * in a single strict O(n) character scan without regex backtracking.
179
+ * Restores Antigravity's `\n`-concatenated MCP text content blocks into individual
180
+ * blocks in strictly linear O(n) time without regex backtracking:
181
+ * 1. When the entire text consists of 2+ whitespace/newline-separated valid top-level
182
+ * JSON containers (`{...}` / `[...]`), splits them into individual JSON blocks.
183
+ * 2. Otherwise, inspects at most 2 known MCP trailer lines from the very end of the
184
+ * output — an optional single-line `{"connection_scope":{...}}` block and an optional
185
+ * immediately preceding single-line `<!-- brainbase-knowledge-owner-audit:{...} -->`
186
+ * block (`schema_version === 'brainbase-knowledge-owner-audit-v1'`) — and restores
187
+ * `[...bodyBlocks, ...trailers]` (applying pure JSON splitting to `body` when applicable,
188
+ * or preserving non-JSON Markdown/text `body` as a single leading block).
155
189
  *
156
- * Antigravity CLI concatenates multiple MCP text content blocks with `\n` when writing
157
- * `steps/<n>/output.txt` and `transcript*.jsonl` (for example, a primary tool result JSON
158
- * followed by a trailing `{"connection_scope":{...}}` block). When 2+ top-level JSON
159
- * containers are found and every block validates via `JSON.parse`, returns the individual
160
- * blocks so `tool_response.content` restores the original multi-block MCP structure.
161
- * For a single JSON value, non-JSON text, or any malformed/partial block, fails open and
162
- * returns `[text]`.
190
+ * Fails open and returns `[text]` for single blocks, non-matching text, or any
191
+ * embedded/spoofed markers not strictly positioned as trailing MCP blocks.
163
192
  */
164
193
  export declare function splitConcatenatedJsonTextBlocks(text: string): string[];
165
194
  export declare function extractToolResultFromTranscript(transcriptPath: unknown, stepIdx: unknown, options?: TranscriptReadOptions): string | null;
@@ -1088,6 +1088,381 @@ function stripUserRequestWrapper(text) {
1088
1088
  return match[1].trim();
1089
1089
  return trimmed;
1090
1090
  }
1091
+ const ORCA_PREAMBLE_PREFIX = '[Orca:';
1092
+ const FENCED_ORCA_SYSTEM_PREAMBLE_PREFIXES = [
1093
+ '[Orca: your other chats active in the last ',
1094
+ '[Orca: your live work now, ',
1095
+ '[Orca: your MEMORY.md, as notes to consult, ',
1096
+ ];
1097
+ const ORCA_UNANSWERED_QUESTION_PREAMBLE = '[Orca: if you asked your owner something in this chat that they\'ve clearly left unanswered and that still matters, put it on an item as Needs you ("${ORCA_CLI_COMMAND:-orca}" bot item set <n> --status needs-you --comment "<context>" --ask "<question>", adding --option "..." per choice when it has choices), or add an item for it. Skip anything already on an item, and items your owner snoozed.]';
1098
+ const ORCA_SCHEDULED_TIME_PREFIX = '[Orca: it is ';
1099
+ const ORCA_SCHEDULED_TIME_SUFFIX = ', the time you were asked to act at.';
1100
+ const ORCA_SCHEDULED_TIME_ONLY_RUN_TAIL = ' This is the only run.';
1101
+ const MEMORY_CHANGED_PREAMBLE_PREFIX = '[Your MEMORY.md changed outside this chat ';
1102
+ const SOUL_UPDATED_PREAMBLE_PREFIX = '[Your SOUL.md was updated; ';
1103
+ function isAsciiWhitespaceCode(code) {
1104
+ return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
1105
+ }
1106
+ function isAsciiDigitCode(code) {
1107
+ return code >= 0x30 /* '0' */ && code <= 0x39 /* '9' */;
1108
+ }
1109
+ function parseAsciiUint(text, pos, count) {
1110
+ if (pos + count > text.length)
1111
+ return null;
1112
+ let value = 0;
1113
+ for (let i = 0; i < count; i += 1) {
1114
+ const code = text.charCodeAt(pos + i);
1115
+ if (!isAsciiDigitCode(code))
1116
+ return null;
1117
+ value = value * 10 + (code - 0x30);
1118
+ }
1119
+ return value;
1120
+ }
1121
+ function daysInMonth(year, month) {
1122
+ if (month === 2) {
1123
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28;
1124
+ }
1125
+ if (month === 4 || month === 6 || month === 9 || month === 11) {
1126
+ return 30;
1127
+ }
1128
+ return 31;
1129
+ }
1130
+ function skipAsciiWhitespace(text, pos) {
1131
+ let cursor = pos;
1132
+ while (cursor < text.length && isAsciiWhitespaceCode(text.charCodeAt(cursor))) {
1133
+ cursor += 1;
1134
+ }
1135
+ return cursor;
1136
+ }
1137
+ function consumeBracketHeader(text, pos) {
1138
+ if (text.charCodeAt(pos) !== 0x5b /* '[' */)
1139
+ return null;
1140
+ let depth = 0;
1141
+ for (let index = pos; index < text.length; index += 1) {
1142
+ const code = text.charCodeAt(index);
1143
+ if (code === 0x0a /* '\n' */ || code === 0x0d /* '\r' */) {
1144
+ return null;
1145
+ }
1146
+ if (code === 0x5b /* '[' */) {
1147
+ depth += 1;
1148
+ }
1149
+ else if (code === 0x5d /* ']' */) {
1150
+ depth -= 1;
1151
+ if (depth === 0)
1152
+ return index + 1;
1153
+ }
1154
+ }
1155
+ return null;
1156
+ }
1157
+ function findLastValidOrcaFenceClose(text, minPos) {
1158
+ let searchFrom = text.length;
1159
+ while (searchFrom >= minPos) {
1160
+ const closeIdx = text.lastIndexOf('>>>', searchFrom);
1161
+ if (closeIdx === -1 || closeIdx < minPos)
1162
+ return -1;
1163
+ const atLineStart = closeIdx === 0 || text[closeIdx - 1] === '\n';
1164
+ const afterClose = closeIdx + 3;
1165
+ const atLineEnd = afterClose === text.length
1166
+ || text[afterClose] === '\n'
1167
+ || (text[afterClose] === '\r' && text[afterClose + 1] === '\n');
1168
+ if (atLineStart && atLineEnd)
1169
+ return closeIdx;
1170
+ searchFrom = closeIdx - 1;
1171
+ }
1172
+ return -1;
1173
+ }
1174
+ function consumeOrcaFenceBlock(text, pos, maxFenceClose) {
1175
+ const start = skipAsciiWhitespace(text, pos);
1176
+ if (!text.startsWith('<<<', start))
1177
+ return null;
1178
+ let afterOpen = start + 3;
1179
+ if (text[afterOpen] === '\r' && text[afterOpen + 1] === '\n') {
1180
+ afterOpen += 2;
1181
+ }
1182
+ else if (text[afterOpen] === '\n') {
1183
+ afterOpen += 1;
1184
+ }
1185
+ else {
1186
+ return null;
1187
+ }
1188
+ if (maxFenceClose !== undefined && (maxFenceClose === -1 || afterOpen > maxFenceClose)) {
1189
+ return null;
1190
+ }
1191
+ let searchFrom = afterOpen;
1192
+ while (searchFrom <= text.length) {
1193
+ const closeIdx = text.indexOf('>>>', searchFrom);
1194
+ if (closeIdx === -1)
1195
+ return null;
1196
+ const atLineStart = closeIdx === afterOpen || text[closeIdx - 1] === '\n';
1197
+ const afterClose = closeIdx + 3;
1198
+ const atLineEnd = afterClose === text.length
1199
+ || text[afterClose] === '\n'
1200
+ || (text[afterClose] === '\r' && text[afterClose + 1] === '\n');
1201
+ if (atLineStart && atLineEnd) {
1202
+ if (text[afterClose] === '\r' && text[afterClose + 1] === '\n')
1203
+ return afterClose + 2;
1204
+ if (text[afterClose] === '\n')
1205
+ return afterClose + 1;
1206
+ return afterClose;
1207
+ }
1208
+ searchFrom = closeIdx + 3;
1209
+ }
1210
+ return null;
1211
+ }
1212
+ /**
1213
+ * Matches only the exact Orca scheduled-time header format:
1214
+ * `[Orca: it is YYYY-MM-DDTHH:MM:SS(.fff)?(Z|+HH:MM|-HH:MM), the time you were asked to act at.( This is the only run.)?]`
1215
+ * with strict calendar, clock, leap-year, and timezone offset validation in linear time without regex backtracking.
1216
+ */
1217
+ function isOrcaScheduledTimePreamble(text, pos, afterHeader) {
1218
+ if (!text.startsWith(ORCA_SCHEDULED_TIME_PREFIX, pos))
1219
+ return false;
1220
+ const headerClose = afterHeader - 1;
1221
+ let cursor = pos + ORCA_SCHEDULED_TIME_PREFIX.length;
1222
+ // YYYY-MM-DDTHH:MM:SS (19 ASCII chars)
1223
+ if (cursor + 19 > headerClose)
1224
+ return false;
1225
+ const year = parseAsciiUint(text, cursor, 4);
1226
+ const month = parseAsciiUint(text, cursor + 5, 2);
1227
+ const day = parseAsciiUint(text, cursor + 8, 2);
1228
+ const hour = parseAsciiUint(text, cursor + 11, 2);
1229
+ const minute = parseAsciiUint(text, cursor + 14, 2);
1230
+ const second = parseAsciiUint(text, cursor + 17, 2);
1231
+ if (year === null
1232
+ || text.charCodeAt(cursor + 4) !== 0x2d /* '-' */
1233
+ || month === null
1234
+ || month < 1
1235
+ || month > 12
1236
+ || text.charCodeAt(cursor + 7) !== 0x2d /* '-' */
1237
+ || day === null
1238
+ || day < 1
1239
+ || day > daysInMonth(year, month)
1240
+ || text.charCodeAt(cursor + 10) !== 0x54 /* 'T' */
1241
+ || hour === null
1242
+ || hour > 23
1243
+ || text.charCodeAt(cursor + 13) !== 0x3a /* ':' */
1244
+ || minute === null
1245
+ || minute > 59
1246
+ || text.charCodeAt(cursor + 16) !== 0x3a /* ':' */
1247
+ || second === null
1248
+ || second > 59) {
1249
+ return false;
1250
+ }
1251
+ cursor += 19;
1252
+ // Optional fractional seconds: (?:\.\d+)?
1253
+ if (cursor < headerClose && text.charCodeAt(cursor) === 0x2e /* '.' */) {
1254
+ cursor += 1;
1255
+ const fracStart = cursor;
1256
+ while (cursor < headerClose && isAsciiDigitCode(text.charCodeAt(cursor))) {
1257
+ cursor += 1;
1258
+ }
1259
+ if (cursor === fracStart)
1260
+ return false;
1261
+ }
1262
+ // Timezone: (?:Z|[+-]HH:MM) with strict tzHour 0..23 and tzMinute 0..59
1263
+ if (cursor >= headerClose)
1264
+ return false;
1265
+ const tzCode = text.charCodeAt(cursor);
1266
+ if (tzCode === 0x5a /* 'Z' */) {
1267
+ cursor += 1;
1268
+ }
1269
+ else if (tzCode === 0x2b /* '+' */ || tzCode === 0x2d /* '-' */) {
1270
+ if (cursor + 6 > headerClose)
1271
+ return false;
1272
+ const tzHour = parseAsciiUint(text, cursor + 1, 2);
1273
+ const tzMinute = parseAsciiUint(text, cursor + 4, 2);
1274
+ if (tzHour === null
1275
+ || tzHour > 23
1276
+ || text.charCodeAt(cursor + 3) !== 0x3a /* ':' */
1277
+ || tzMinute === null
1278
+ || tzMinute > 59) {
1279
+ return false;
1280
+ }
1281
+ cursor += 6;
1282
+ }
1283
+ else {
1284
+ return false;
1285
+ }
1286
+ if (cursor + ORCA_SCHEDULED_TIME_SUFFIX.length > headerClose)
1287
+ return false;
1288
+ if (!text.startsWith(ORCA_SCHEDULED_TIME_SUFFIX, cursor))
1289
+ return false;
1290
+ cursor += ORCA_SCHEDULED_TIME_SUFFIX.length;
1291
+ return (cursor === headerClose
1292
+ || (headerClose - cursor === ORCA_SCHEDULED_TIME_ONLY_RUN_TAIL.length
1293
+ && text.startsWith(ORCA_SCHEDULED_TIME_ONLY_RUN_TAIL, cursor)));
1294
+ }
1295
+ function isFencedOrcaSystemPreambleHeader(text, pos, afterHeader) {
1296
+ const headerClose = afterHeader - 1;
1297
+ for (const prefix of FENCED_ORCA_SYSTEM_PREAMBLE_PREFIXES) {
1298
+ if (pos + prefix.length <= headerClose && text.startsWith(prefix, pos)) {
1299
+ return true;
1300
+ }
1301
+ }
1302
+ return false;
1303
+ }
1304
+ function isOrcaUnansweredQuestionPreamble(text, pos, afterHeader) {
1305
+ return (afterHeader - pos === ORCA_UNANSWERED_QUESTION_PREAMBLE.length
1306
+ && text.startsWith(ORCA_UNANSWERED_QUESTION_PREAMBLE, pos));
1307
+ }
1308
+ function consumeKnownOrcaSystemPreamble(text, pos, maxFenceClose) {
1309
+ if (!text.startsWith(ORCA_PREAMBLE_PREFIX, pos))
1310
+ return null;
1311
+ const afterHeader = consumeBracketHeader(text, pos);
1312
+ if (afterHeader === null)
1313
+ return null;
1314
+ if (isFencedOrcaSystemPreambleHeader(text, pos, afterHeader)) {
1315
+ return consumeOrcaFenceBlock(text, afterHeader, maxFenceClose);
1316
+ }
1317
+ if (isOrcaUnansweredQuestionPreamble(text, pos, afterHeader)
1318
+ || isOrcaScheduledTimePreamble(text, pos, afterHeader)) {
1319
+ // Standalone system preambles never carry a fence block; keep any user-authored
1320
+ // `<<<\n...\n>>>` block immediately following them intact.
1321
+ return afterHeader;
1322
+ }
1323
+ return null;
1324
+ }
1325
+ function consumeMemoryChangedPreamble(text, pos, maxFenceClose) {
1326
+ if (!text.startsWith(MEMORY_CHANGED_PREAMBLE_PREFIX, pos))
1327
+ return null;
1328
+ const afterHeader = consumeBracketHeader(text, pos);
1329
+ if (afterHeader === null)
1330
+ return null;
1331
+ let nextPos = afterHeader;
1332
+ let consumedFences = 0;
1333
+ while (nextPos < text.length) {
1334
+ const probe = skipAsciiWhitespace(text, nextPos);
1335
+ if (text.startsWith('Added:', probe)) {
1336
+ const afterFence = consumeOrcaFenceBlock(text, probe + 'Added:'.length, maxFenceClose);
1337
+ if (afterFence === null)
1338
+ break;
1339
+ nextPos = afterFence;
1340
+ consumedFences += 1;
1341
+ continue;
1342
+ }
1343
+ if (text.startsWith('Removed:', probe)) {
1344
+ const afterFence = consumeOrcaFenceBlock(text, probe + 'Removed:'.length, maxFenceClose);
1345
+ if (afterFence === null)
1346
+ break;
1347
+ nextPos = afterFence;
1348
+ consumedFences += 1;
1349
+ continue;
1350
+ }
1351
+ const bareFence = consumeOrcaFenceBlock(text, probe, maxFenceClose);
1352
+ if (bareFence !== null) {
1353
+ nextPos = bareFence;
1354
+ consumedFences += 1;
1355
+ continue;
1356
+ }
1357
+ break;
1358
+ }
1359
+ return consumedFences > 0 ? nextPos : null;
1360
+ }
1361
+ function findNextKnownOrcaPreambleStart(text, from) {
1362
+ const lastFenceClose = findLastValidOrcaFenceClose(text, from);
1363
+ let earliest = -1;
1364
+ let searchFrom = from;
1365
+ while (searchFrom < text.length) {
1366
+ const idx = text.indexOf(MEMORY_CHANGED_PREAMBLE_PREFIX, searchFrom);
1367
+ if (idx === -1)
1368
+ break;
1369
+ if ((idx === from || text[idx - 1] === '\n')
1370
+ && consumeMemoryChangedPreamble(text, idx, lastFenceClose) !== null) {
1371
+ earliest = idx;
1372
+ break;
1373
+ }
1374
+ searchFrom = idx + MEMORY_CHANGED_PREAMBLE_PREFIX.length;
1375
+ }
1376
+ searchFrom = from;
1377
+ while (searchFrom < text.length) {
1378
+ const idx = text.indexOf(ORCA_PREAMBLE_PREFIX, searchFrom);
1379
+ if (idx === -1 || (earliest !== -1 && idx >= earliest))
1380
+ break;
1381
+ if ((idx === from || text[idx - 1] === '\n')
1382
+ && consumeKnownOrcaSystemPreamble(text, idx, lastFenceClose) !== null) {
1383
+ earliest = idx;
1384
+ break;
1385
+ }
1386
+ searchFrom = idx + ORCA_PREAMBLE_PREFIX.length;
1387
+ }
1388
+ return earliest;
1389
+ }
1390
+ /**
1391
+ * Deterministically strips only exact Orca-injected leading system preamble
1392
+ * blocks in linear time without regex backtracking:
1393
+ * - `[Your SOUL.md was updated; ...]` (with an accompanying `<<<\n...\n>>>` fence
1394
+ * or bounded by a subsequent valid known Orca / MEMORY.md preamble)
1395
+ * - `[Your MEMORY.md changed outside this chat ...]` ONLY when followed by at least
1396
+ * one `Added:` / `Removed:` / bare `<<<\n...\n>>>` fence block
1397
+ * - Fenced Orca `[Orca: ...]` preambles (`your other chats active in the last `,
1398
+ * `your live work now, `, `your MEMORY.md, as notes to consult, `) ONLY when
1399
+ * immediately followed by a `<<<\n...\n>>>` fence block
1400
+ * - Exact full-string `[Orca: if you asked your owner something in this chat ...]`
1401
+ * system reminder (standalone; never consumes a following `<<<\n...\n>>>` block)
1402
+ * - Strict ISO-8601 `[Orca: it is <ISO-8601>, the time you were asked to act at.( This is the only run.)?]`
1403
+ * scheduled-time header with strict calendar/clock/timezone validation
1404
+ * (standalone; never consumes a following `<<<\n...\n>>>` block)
1405
+ *
1406
+ * Any utterance that does not match one of these exact system formats — including
1407
+ * invalid ISO-8601 timestamps, fenceless known prefixes, shortened unanswered-question
1408
+ * headers, unknown `[Orca: ...]` headers (with or without fences), and ordinary prompts
1409
+ * with leading/trailing whitespace — is returned 100% byte-for-byte untouched.
1410
+ *
1411
+ * Fail-safe: when 0 preambles are consumed or stripping would yield an empty/whitespace-only
1412
+ * string, returns the original `text` untouched. Never alters ordinary user utterances or
1413
+ * bot-to-bot `──── From: ORCA_SESSION_ID:...` message bodies.
1414
+ */
1415
+ export function stripOrcaInjectedPreambles(text) {
1416
+ if (!text)
1417
+ return text;
1418
+ let cursor = 0;
1419
+ let strippedCount = 0;
1420
+ while (cursor < text.length) {
1421
+ cursor = skipAsciiWhitespace(text, cursor);
1422
+ if (cursor >= text.length)
1423
+ break;
1424
+ if (text.startsWith(ORCA_PREAMBLE_PREFIX, cursor)) {
1425
+ const nextPos = consumeKnownOrcaSystemPreamble(text, cursor);
1426
+ if (nextPos === null)
1427
+ break;
1428
+ cursor = nextPos;
1429
+ strippedCount += 1;
1430
+ continue;
1431
+ }
1432
+ if (text.startsWith(MEMORY_CHANGED_PREAMBLE_PREFIX, cursor)) {
1433
+ const nextPos = consumeMemoryChangedPreamble(text, cursor);
1434
+ if (nextPos === null)
1435
+ break;
1436
+ cursor = nextPos;
1437
+ strippedCount += 1;
1438
+ continue;
1439
+ }
1440
+ if (text.startsWith(SOUL_UPDATED_PREAMBLE_PREFIX, cursor)) {
1441
+ const afterHeader = consumeBracketHeader(text, cursor);
1442
+ if (afterHeader === null)
1443
+ break;
1444
+ const directFence = consumeOrcaFenceBlock(text, afterHeader);
1445
+ if (directFence !== null) {
1446
+ cursor = directFence;
1447
+ strippedCount += 1;
1448
+ continue;
1449
+ }
1450
+ const nextKnown = findNextKnownOrcaPreambleStart(text, afterHeader);
1451
+ if (nextKnown !== -1) {
1452
+ cursor = nextKnown;
1453
+ strippedCount += 1;
1454
+ continue;
1455
+ }
1456
+ // Fail-safe: no subsequent known preamble marks the end of SOUL.md body.
1457
+ break;
1458
+ }
1459
+ break;
1460
+ }
1461
+ if (strippedCount === 0)
1462
+ return text;
1463
+ const stripped = text.slice(cursor).trim();
1464
+ return stripped || text;
1465
+ }
1091
1466
  const SYSTEM_INJECTED_PROMPT_PREFIXES = [
1092
1467
  /^Reason Network:/iu,
1093
1468
  /^<SYSTEM_MESSAGE>/iu,
@@ -1112,7 +1487,8 @@ export function extractLatestNonSystemUserInput(transcriptPath, options) {
1112
1487
  continue;
1113
1488
  if (isSystemInjectedUserInput(entry.content, entry.source))
1114
1489
  continue;
1115
- const content = stripUserRequestWrapper(entry.content);
1490
+ const unwrapped = stripUserRequestWrapper(entry.content);
1491
+ const content = stripOrcaInjectedPreambles(unwrapped);
1116
1492
  if (!content)
1117
1493
  continue;
1118
1494
  const stepIndex = typeof entry.step_index === 'number' && Number.isSafeInteger(entry.step_index)
@@ -1170,19 +1546,106 @@ function isValidJsonText(text) {
1170
1546
  return false;
1171
1547
  }
1172
1548
  }
1549
+ const OWNER_AUDIT_TRAILER_PREFIX = '<!-- brainbase-knowledge-owner-audit:';
1550
+ const OWNER_AUDIT_TRAILER_SUFFIX = ' -->';
1551
+ const OWNER_AUDIT_SCHEMA_VERSION = 'brainbase-knowledge-owner-audit-v1';
1552
+ function isConnectionScopeTrailerLine(line) {
1553
+ if (line.length < 2 || !line.startsWith('{') || !line.endsWith('}')) {
1554
+ return false;
1555
+ }
1556
+ if (line.includes('\r') || line.includes('\n')) {
1557
+ return false;
1558
+ }
1559
+ let parsed;
1560
+ try {
1561
+ parsed = JSON.parse(line);
1562
+ }
1563
+ catch {
1564
+ return false;
1565
+ }
1566
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
1567
+ return false;
1568
+ }
1569
+ const keys = Object.keys(parsed);
1570
+ if (keys.length !== 1 || keys[0] !== 'connection_scope') {
1571
+ return false;
1572
+ }
1573
+ const scope = parsed.connection_scope;
1574
+ return Boolean(scope) && typeof scope === 'object' && !Array.isArray(scope);
1575
+ }
1576
+ function isOwnerAuditTrailerLine(line) {
1577
+ if (!line.startsWith(OWNER_AUDIT_TRAILER_PREFIX)
1578
+ || !line.endsWith(OWNER_AUDIT_TRAILER_SUFFIX)) {
1579
+ return false;
1580
+ }
1581
+ const jsonText = line.slice(OWNER_AUDIT_TRAILER_PREFIX.length, line.length - OWNER_AUDIT_TRAILER_SUFFIX.length);
1582
+ if (jsonText.length < 2 || !jsonText.startsWith('{') || !jsonText.endsWith('}')) {
1583
+ return false;
1584
+ }
1585
+ if (jsonText.includes('\r') || jsonText.includes('\n')) {
1586
+ return false;
1587
+ }
1588
+ let parsed;
1589
+ try {
1590
+ parsed = JSON.parse(jsonText);
1591
+ }
1592
+ catch {
1593
+ return false;
1594
+ }
1595
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
1596
+ return false;
1597
+ }
1598
+ return parsed.schema_version === OWNER_AUDIT_SCHEMA_VERSION;
1599
+ }
1600
+ function popLastLine(text, end) {
1601
+ if (end <= 0)
1602
+ return null;
1603
+ const lastNl = text.lastIndexOf('\n', end - 1);
1604
+ const lineStart = lastNl === -1 ? 0 : lastNl + 1;
1605
+ const lineEnd = end > lineStart && text.charCodeAt(end - 1) === 0x0d /* '\r' */ ? end - 1 : end;
1606
+ const line = text.slice(lineStart, lineEnd);
1607
+ const nextEnd = lastNl === -1
1608
+ ? 0
1609
+ : (lastNl > 0 && text.charCodeAt(lastNl - 1) === 0x0d /* '\r' */ ? lastNl - 1 : lastNl);
1610
+ return { nextEnd, line };
1611
+ }
1173
1612
  /**
1174
- * Splits whitespace/newline-concatenated top-level JSON objects/arrays (`{...}` / `[...]`)
1175
- * in a single strict O(n) character scan without regex backtracking.
1613
+ * Extracts at most 2 known MCP trailer lines from the very end of a concatenated tool output:
1614
+ * 1. At most one trailing single-line `{"connection_scope":{...}}` JSON object line.
1615
+ * 2. At most one single-line `<!-- brainbase-knowledge-owner-audit:{...} -->` line
1616
+ * immediately preceding `connection_scope` (or at the very end if absent).
1176
1617
  *
1177
- * Antigravity CLI concatenates multiple MCP text content blocks with `\n` when writing
1178
- * `steps/<n>/output.txt` and `transcript*.jsonl` (for example, a primary tool result JSON
1179
- * followed by a trailing `{"connection_scope":{...}}` block). When 2+ top-level JSON
1180
- * containers are found and every block validates via `JSON.parse`, returns the individual
1181
- * blocks so `tool_response.content` restores the original multi-block MCP structure.
1182
- * For a single JSON value, non-JSON text, or any malformed/partial block, fails open and
1183
- * returns `[text]`.
1618
+ * Strictly ignores any `owner-audit` or `connection_scope` markers embedded in the middle
1619
+ * of the body, on the same line as body text, or behind duplicate `connection_scope` lines.
1184
1620
  */
1185
- export function splitConcatenatedJsonTextBlocks(text) {
1621
+ function extractTrailingMcpBlocks(text) {
1622
+ let end = text.length;
1623
+ while (end > 0 && text.charCodeAt(end - 1) === 0x0a /* '\n' */) {
1624
+ end -= 1;
1625
+ if (end > 0 && text.charCodeAt(end - 1) === 0x0d /* '\r' */) {
1626
+ end -= 1;
1627
+ }
1628
+ }
1629
+ let scopeBlock = null;
1630
+ let auditBlock = null;
1631
+ const last = popLastLine(text, end);
1632
+ if (last && isConnectionScopeTrailerLine(last.line)) {
1633
+ scopeBlock = last.line;
1634
+ end = last.nextEnd;
1635
+ }
1636
+ const prev = popLastLine(text, end);
1637
+ if (prev && isOwnerAuditTrailerLine(prev.line)) {
1638
+ auditBlock = prev.line;
1639
+ end = prev.nextEnd;
1640
+ }
1641
+ const trailers = [];
1642
+ if (auditBlock !== null)
1643
+ trailers.push(auditBlock);
1644
+ if (scopeBlock !== null)
1645
+ trailers.push(scopeBlock);
1646
+ return { body: text.slice(0, end), trailers };
1647
+ }
1648
+ function splitPureConcatenatedJsonBlocks(text) {
1186
1649
  const length = text.length;
1187
1650
  if (length === 0)
1188
1651
  return [text];
@@ -1265,10 +1728,42 @@ export function splitConcatenatedJsonTextBlocks(text) {
1265
1728
  }
1266
1729
  return candidates;
1267
1730
  }
1731
+ /**
1732
+ * Restores Antigravity's `\n`-concatenated MCP text content blocks into individual
1733
+ * blocks in strictly linear O(n) time without regex backtracking:
1734
+ * 1. When the entire text consists of 2+ whitespace/newline-separated valid top-level
1735
+ * JSON containers (`{...}` / `[...]`), splits them into individual JSON blocks.
1736
+ * 2. Otherwise, inspects at most 2 known MCP trailer lines from the very end of the
1737
+ * output — an optional single-line `{"connection_scope":{...}}` block and an optional
1738
+ * immediately preceding single-line `<!-- brainbase-knowledge-owner-audit:{...} -->`
1739
+ * block (`schema_version === 'brainbase-knowledge-owner-audit-v1'`) — and restores
1740
+ * `[...bodyBlocks, ...trailers]` (applying pure JSON splitting to `body` when applicable,
1741
+ * or preserving non-JSON Markdown/text `body` as a single leading block).
1742
+ *
1743
+ * Fails open and returns `[text]` for single blocks, non-matching text, or any
1744
+ * embedded/spoofed markers not strictly positioned as trailing MCP blocks.
1745
+ */
1746
+ export function splitConcatenatedJsonTextBlocks(text) {
1747
+ if (text.length === 0)
1748
+ return [text];
1749
+ const pureJsonBlocks = splitPureConcatenatedJsonBlocks(text);
1750
+ if (pureJsonBlocks.length > 1) {
1751
+ return pureJsonBlocks;
1752
+ }
1753
+ const { body, trailers } = extractTrailingMcpBlocks(text);
1754
+ if (trailers.length === 0) {
1755
+ return [text];
1756
+ }
1757
+ if (body.trim().length === 0) {
1758
+ return trailers;
1759
+ }
1760
+ const bodyBlocks = splitPureConcatenatedJsonBlocks(body);
1761
+ return [...bodyBlocks, ...trailers];
1762
+ }
1268
1763
  function isValidJsonOrConcatenatedJsonText(text) {
1269
1764
  if (isValidJsonText(text))
1270
1765
  return true;
1271
- return splitConcatenatedJsonTextBlocks(text).length > 1;
1766
+ return splitPureConcatenatedJsonBlocks(text).length > 1;
1272
1767
  }
1273
1768
  function isTruncatedToolResult(entry, strippedContent) {
1274
1769
  if (hasTruncatedContentField(entry))
@@ -2099,7 +2594,7 @@ async function handlePreInvocation(payload, conversationId, context) {
2099
2594
  const transcriptUser = extractLatestNonSystemUserInput(payload.transcriptPath, transcriptOpts);
2100
2595
  const rawLastUserInput = typeof payload.lastUserInput === 'string' ? payload.lastUserInput : '';
2101
2596
  const prompt = rawLastUserInput && !isSystemInjectedUserInput(rawLastUserInput)
2102
- ? stripUserRequestWrapper(rawLastUserInput)
2597
+ ? stripOrcaInjectedPreambles(stripUserRequestWrapper(rawLastUserInput))
2103
2598
  : (transcriptUser?.content ?? null);
2104
2599
  const currentUserStepIndex = transcriptUser?.stepIndex ?? null;
2105
2600
  const promptDigest = prompt ? sha256(prompt) : null;
@@ -1184,6 +1184,8 @@ export async function loginWithDeviceCode(options) {
1184
1184
  catch {
1185
1185
  continue; // A dropped poll is retried until the code expires.
1186
1186
  }
1187
+ if (poll.bodyLost)
1188
+ continue;
1187
1189
  const error = poll.json?.error;
1188
1190
  if (!poll.ok) {
1189
1191
  if (error === 'authorization_pending') {
@@ -330,8 +330,8 @@ function sameScope(state, scope) {
330
330
  function destinationOf(context) {
331
331
  return JSON.stringify([context.configPath, context.config.origin, context.config.project_code ?? null]);
332
332
  }
333
- function sameDestination(state, context) {
334
- return state.destination === destinationOf(context);
333
+ function sameDestinationAndRegistration(state, context) {
334
+ return state.destination === destinationOf(context) && state.registration_id === context.config.registration.id;
335
335
  }
336
336
  // ---- Turn state ----
337
337
  function turnDirectory(env) {
@@ -657,6 +657,7 @@ async function handleUserPromptSubmit(payload, context) {
657
657
  repository: context.scope.repository,
658
658
  checkout: context.scope.checkout,
659
659
  destination: destinationOf(context),
660
+ registration_id: context.config.registration.id,
660
661
  };
661
662
  if (!isAuditedRepository(context.scope, context.config)) {
662
663
  writeState(env, sessionId, { ...state, start_status: 'out_of_scope' });
@@ -692,7 +693,7 @@ async function handlePostToolUse(payload, context, eventName) {
692
693
  const state = currentTurn(payload, context);
693
694
  if (!state)
694
695
  return unannouncedTurn(payload, context);
695
- if (state.start_status !== 'started' || !sameScope(state, context.scope) || !sameDestination(state, context)
696
+ if (state.start_status !== 'started' || !sameScope(state, context.scope) || !sameDestinationAndRegistration(state, context)
696
697
  || !isAuditedRepository(context.scope, context.config))
697
698
  return {};
698
699
  try {
@@ -727,7 +728,7 @@ async function handlePreToolUse(payload, context) {
727
728
  const state = currentTurn(payload, context);
728
729
  if (!state)
729
730
  return unannouncedTurn(payload, context);
730
- if (state.start_status !== 'started' || !sameScope(state, context.scope) || !sameDestination(state, context)
731
+ if (state.start_status !== 'started' || !sameScope(state, context.scope) || !sameDestinationAndRegistration(state, context)
731
732
  || !isAuditedRepository(context.scope, context.config))
732
733
  return {};
733
734
  try {
@@ -746,8 +747,8 @@ async function handleStop(payload, context) {
746
747
  if (!sameScope(state, context.scope)) {
747
748
  return warning('ターンの途中で別のリポジトリに移ったため、回答を送らずに監査未完了のまま終了します(judgment_turn_repository_changed)。');
748
749
  }
749
- if (!sameDestination(state, context)) {
750
- return warning('ターンの途中で判断フックの送り先が変わったため、回答を送らずに監査未完了のまま終了します(judgment_turn_destination_changed)。');
750
+ if (!sameDestinationAndRegistration(state, context)) {
751
+ return warning('ターンの途中で判断フックの登録または送り先が変わったため、回答を送らずに監査未完了のまま終了します(judgment_turn_destination_changed)。');
751
752
  }
752
753
  // The config is read again for every event: a repository taken off the list
753
754
  // mid-turn sends nothing more, though the destination stays the same.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unson/brainbase-mcp",
3
- "version": "0.51.6",
3
+ "version": "0.51.7",
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",
@@ -673,5 +673,5 @@
673
673
  "url": "https://github.com/Unson-LLC/brainbase/issues"
674
674
  },
675
675
  "homepage": "https://github.com/Unson-LLC/brainbase#readme",
676
- "gitHead": "e249e7f92f904b813c9725c11bed012049b8f227"
676
+ "gitHead": "e15a6fd96a68b50142e9a8ee0ee47fbda4fa1ba5"
677
677
  }