Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(extraction): trailing bracketed prose no longer hijacks array recovery (#5209)
time-attack434fb4d4a0b1
diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.tsindex 32a7919eed..803727cad0 100644--- a/src/core/chronicle/extract-events.ts+++ b/src/core/chronicle/extract-events.ts@@ -10,6 +10,7 @@// failure (no provider, provider error, refusal, truncation, unparseable// output) so none is ever recorded as a genuine no_events answer.import type { BrainEngine } from '../engine.ts';+import { findJsonCloseIndex } from '../llm-json.ts';import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';import { parseConversation } from '../conversation-parser/parse.ts';import { chroniclePageDate } from './eligibility.ts';@@ -345,6 +346,8 @@ export function defaultJudge(engine: BrainEngine): ChronicleJudge {* #2606: returns `null` on parse FAILURE (empty text, no `[...]` found,* JSON.parse throw, non-array result) so callers can distinguish "the model* said no events" (a legitimate `[]`) from "the response was unusable".+ * The array ends at its own closing bracket (`findJsonCloseIndex`), so a+ * bracketed citation after it cannot hijack the slice.*/export function parseJudgeJson(text: string): ChronicleEventProposal[] | null {if (!text) return null;@@ -352,10 +355,11 @@ export function parseJudgeJson(text: string): ChronicleEventProposal[] | null {const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/i);if (fence) s = fence[1].trim();const start = s.indexOf('[');- const end = s.lastIndexOf(']');- if (start === -1 || end === -1 || end < start) return null;+ if (start === -1) return null;+ const closeOffset = findJsonCloseIndex(s.slice(start));+ if (closeOffset === -1) return null;try {- const arr = JSON.parse(s.slice(start, end + 1));+ const arr = JSON.parse(s.slice(start, start + closeOffset + 1));return Array.isArray(arr) ? arr : null;} catch {return null;diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex d0fa1e773e..a3deaa488c 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -48,6 +48,7 @@ import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { upsertExtractRollup, classifyRunStop } from '../extract/rollup-writer.ts';import { GBrainError } from '../types.ts';import { isConfigTruthy } from '../config.ts';+import { findJsonCloseIndex } from '../llm-json.ts';import { TAKE_KIND_VALUES } from '../takes-fence.ts';import type { OperationContext } from '../operations.ts';import type { BrainEngine } from '../engine.ts';@@ -551,15 +552,13 @@ export function parseExtractorOutput(raw: string): ProposedTake[] {try {parsed = JSON.parse(text.slice(start));} catch {- // Fallback: truncate at last ] or } to handle trailing noise (e.g. leftover- // markdown fences after <think> stripping). Try array-closing first.+ // Fallback: trim to the value's own closing bracket so trailing noise+ // (leftover fences, a `[Source: X]` citation) cannot hijack recovery.const sliced = text.slice(start);- const lastArr = sliced.lastIndexOf(']');- const lastObj = sliced.lastIndexOf('}');- const end = Math.max(lastArr, lastObj);- if (end > 0) {+ const closeOffset = findJsonCloseIndex(sliced);+ if (closeOffset !== -1) {try {- parsed = JSON.parse(sliced.slice(0, end + 1));+ parsed = JSON.parse(sliced.slice(0, closeOffset + 1));} catch {return [];}diff --git a/src/core/llm-json.ts b/src/core/llm-json.tsindex d54f9acecd..67e9cb7969 100644--- a/src/core/llm-json.ts+++ b/src/core/llm-json.ts@@ -45,6 +45,39 @@ export function stripReasoningBlocks(raw: string): string {.trim();}+/**+ * Index of the bracket that closes the array or object opened at `s[0]`, or -1+ * when `s[0]` is not `[`/`{` or the value never closes. Depth tracking skips+ * brackets inside JSON strings (honoring escapes), so a `[Source: X]` citation+ * after the value cannot be mistaken for its closer.+ */+export function findJsonCloseIndex(s: string): number {+ const open = s[0];+ const close = open === '[' ? ']' : open === '{' ? '}' : null;+ if (close === null) return -1;+ let depth = 0;+ let inString = false;+ let escaped = false;+ for (let i = 0; i < s.length; i++) {+ const ch = s[i];+ if (inString) {+ if (escaped) escaped = false;+ else if (ch === '\\') escaped = true;+ else if (ch === '"') inString = false;+ continue;+ }+ if (ch === '"') {+ inString = true;+ } else if (ch === open) {+ depth++;+ } else if (ch === close) {+ depth--;+ if (depth === 0) return i;+ }+ }+ return -1;+}+export function parseLlmJson<T>(raw: string, opts: { array?: boolean } = {}): T | null {if (typeof raw !== 'string' || !raw.trim()) return null;const direct = parseLlmJsonInner<T>(raw, opts);diff --git a/test/chronicle-extract.test.ts b/test/chronicle-extract.test.tsindex 360726b947..10d9892239 100644--- a/test/chronicle-extract.test.ts+++ b/test/chronicle-extract.test.ts@@ -173,6 +173,34 @@ describe('parseJudgeJson failure signalling (#2606)', () => {});});+describe('parseJudgeJson: trailing bracketed prose does not hijack recovery', () => {+ const EVENT = '{"when":"2026-06-18","who":[],"what":"x","kind":"meeting"}';++ test('recovers the array when a [Source: X] citation follows it', () => {+ const arr = parseJudgeJson(`[${EVENT}]\nSee [Source: alice-example].`);+ expect(Array.isArray(arr)).toBe(true);+ expect(arr!.length).toBe(1);+ });++ test('recovers the array when a [[wikilink]] backlink follows it', () => {+ expect(parseJudgeJson(`[${EVENT}]\nRelated: [[people/alice-example]].`)!.length).toBe(1);+ });++ test('a legitimate empty array followed by bracketed prose is still []', () => {+ expect(parseJudgeJson('[]\nSee [Source: X].')).toEqual([]);+ });++ test('a bracket inside a quoted string field does not confuse the depth count', () => {+ const arr = parseJudgeJson('[{"when":"2026-06-18","who":[],"what":"see [note]","kind":"meeting"}]\nSee [Source: X].');+ expect(arr!.length).toBe(1);+ expect(arr![0]!.what).toBe('see [note]');+ });++ test('an array that never closes is still a parse failure', () => {+ expect(parseJudgeJson(`[${EVENT}, {"when":"2026-06-19"`)).toBeNull();+ });+});+// #5876 (E2): the default judge used to map a thrown provider error and a// refusal to `{events: []}`, so a failed call was recorded as no_events and// its content never retried.diff --git a/test/llm-json-close-index.test.ts b/test/llm-json-close-index.test.tsnew file mode 100644index 0000000000..f182a8d594--- /dev/null+++ b/test/llm-json-close-index.test.ts@@ -0,0 +1,33 @@+/**+ * Contract of the shared balanced-close scanner used by the chronicle judge,+ * propose_takes and extract_atoms recovery paths. Caller regressions live in+ * their own suites; this pins the scanner's edge cases once.+ */+import { describe, expect, test } from 'bun:test';+import { findJsonCloseIndex } from '../src/core/llm-json.ts';++describe('findJsonCloseIndex', () => {+ test('returns the top-level closer, not a later citation bracket', () => {+ const s = '[{"a":1}]\nSee [Source: alice-example].';+ expect(findJsonCloseIndex(s)).toBe(8);+ });++ test('tracks nested containers of the same kind', () => {+ const s = '[[1,[2]],3] trailing ]';+ expect(findJsonCloseIndex(s)).toBe(10);+ expect(findJsonCloseIndex('{"a":{"b":{}}} }')).toBe(13);+ });++ test('ignores brackets inside strings, including escaped quotes and backslashes', () => {+ expect(findJsonCloseIndex('["]"]')).toBe(4);+ expect(findJsonCloseIndex('["a\\"]"] x]')).toBe(7);+ expect(findJsonCloseIndex('["a\\\\"] x]')).toBe(6);+ });++ test('returns -1 for unclosed input or a non-container start', () => {+ expect(findJsonCloseIndex('[{"a":1}')).toBe(-1);+ expect(findJsonCloseIndex('["unterminated]')).toBe(-1);+ expect(findJsonCloseIndex('see [x]')).toBe(-1);+ expect(findJsonCloseIndex('')).toBe(-1);+ });+});diff --git a/test/propose-takes.test.ts b/test/propose-takes.test.tsindex f02f10554f..7aea472d6b 100644--- a/test/propose-takes.test.ts+++ b/test/propose-takes.test.ts@@ -250,6 +250,31 @@ describe('parseExtractorOutput', () => {expect(out).toHaveLength(1);expect(out[0]!.claim_text).toBe('Z');});++ // Last-bracket recovery picked up a bracket from prose after the JSON, so a+ // well-formed response followed by a citation parsed as nothing.+ test('recovers the array when a [Source: X] citation follows it', () => {+ const raw = '[{"claim_text":"Cities send messages","kind":"take","holder":"brain","weight":0.65}]\n' ++ 'See [Source: alice-example].';+ const out = parseExtractorOutput(raw);+ expect(out).toHaveLength(1);+ expect(out[0]!.claim_text).toBe('Cities send messages');+ });++ test('recovers a single object when a [[wikilink]] backlink follows it', () => {+ const raw = '{"claim_text":"Y","kind":"hunch","holder":"brain","weight":0.4}\nRelated: [[people/alice-example]].';+ const out = parseExtractorOutput(raw);+ expect(out).toHaveLength(1);+ expect(out[0]!.claim_text).toBe('Y');+ });++ test('a bracket inside a quoted string field does not confuse the depth count', () => {+ const raw = '[{"claim_text":"see [note] for context","kind":"take","holder":"brain","weight":0.5}]\n' ++ 'See [Source: X].';+ const out = parseExtractorOutput(raw);+ expect(out).toHaveLength(1);+ expect(out[0]!.claim_text).toBe('see [note] for context');+ });});// ─── isWellFormedEmptyExtraction ────────────────────────────────────