Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(cycle): extract-atoms trailing-prose recovery ends at the array's own bracket (#5064)

time-attack9f25b8340293
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 81518f8525..3b1fcfc5b2 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -59,7 +59,7 @@
// which made the NOT EXISTS guard ineffective on federated brains.
import type { BrainEngine, LinkBatchInput } from '../engine.ts';
-import { stripReasoningBlocks } from '../llm-json.ts';
+import { findJsonCloseIndex, stripReasoningBlocks } from '../llm-json.ts';
import type { PhaseResult } from '../cycle.ts';
import type { GBrainConfig } from '../config.ts';
import type { ProgressReporter } from '../progress.ts';
@@ -1516,9 +1516,9 @@ export function parseAtomsOutcome(raw: string): AtomsParseOutcome {
const MAX_ARRAY_ANCHOR_CANDIDATES = 64;
/**
- * Parse the JSON array anchored at ONE `[` offset, reproducing the historical
- * two-step exactly: whole-slice parse, then a trim-back to the last `]` to
- * recover from trailing prose. Split out of parseAtomsOutcomeInner so the
+ * Parse the JSON array anchored at ONE `[` offset: whole-slice parse, then a
+ * trim-back to the array's own closing `]` so trailing prose cannot hijack it
+ * (the first complete array wins). Split out of parseAtomsOutcomeInner so the
* anchor scan can try successive offsets without duplicating the reason
* strings — those are asserted by tests and ride the drain's `last_error`.
*/
@@ -1531,8 +1531,8 @@ function parseArrayAtOffset(
try {
parsed = JSON.parse(slice);
} catch {
- // Try trimming back from the end to recover from trailing prose.
- const arrayEnd = slice.lastIndexOf(']');
+ // Trim back to the array's own closing bracket to drop trailing prose.
+ const arrayEnd = findJsonCloseIndex(slice);
if (arrayEnd === -1) return { ok: false, reason: 'unterminated JSON array' };
try {
parsed = JSON.parse(slice.slice(0, arrayEnd + 1));
diff --git a/test/extract-atoms-array-anchor-scan.test.ts b/test/extract-atoms-array-anchor-scan.test.ts
index e71bf6f2a3..529df69fab 100644
--- a/test/extract-atoms-array-anchor-scan.test.ts
+++ b/test/extract-atoms-array-anchor-scan.test.ts
@@ -61,9 +61,9 @@ describe('anchor scan — bracketed preamble no longer hijacks the parse', () =>
test('preamble recovery: a parseable-but-WRONG array ahead of the real one is skipped', () => {
// `["a","b"]` parses cleanly but yields no atom, so the scan moves on and
- // recovers the real payload below. NOTE: this passes with OR without the
- // shape gate (the first-bracket offset fails to parse either way), so it
- // pins recovery, not the gate — the gate is pinned directly further down.
+ // recovers the real payload below. The first-bracket offset parses on its
+ // own (bounded to `["a","b"]`) and the SHAPE GATE rejects it, so this pins
+ // recovery; the gate itself is pinned directly further down.
const raw = 'Candidate labels were ["a","b"] before I settled on:\n' + ATOM_ARRAY;
const atoms = atomsOf(raw);
expect(atoms).toHaveLength(1);
@@ -137,6 +137,42 @@ describe('anchor scan — preserved behaviour', () => {
expect(atomsOf(ATOM_ARRAY + '\n\nThose are the atoms I found.')).toHaveLength(1);
});
+ test('trailing prose containing a bracketed citation does not hijack the recovery boundary', () => {
+ // Last-`]` trim-back included the citation in the re-parse, so a valid
+ // array was reported `unparseable JSON array`.
+ const raw = ATOM_ARRAY + '\nSee [Source: alice-example, agent session, 2026-09-03].';
+ expect(atomsOf(raw)).toHaveLength(1);
+ expect(atomsOf(raw)[0]!.title).toBe(ATOM.title);
+ });
+
+ test('trailing prose with an unmatched trailing bracket after a valid array is still recovered', () => {
+ const raw = ATOM_ARRAY + '\nas noted above]';
+ expect(atomsOf(raw)).toHaveLength(1);
+ });
+
+ test('recovery still finds the true boundary when the array body has escaped quotes, brackets inside strings, and a nested array', () => {
+ const nestedAtom = {
+ title: 'Escapes and nesting inside the array body',
+ atom_type: 'insight' as const,
+ body: 'She said \\"data is in [brackets]\\" and listed refs [1, 2].',
+ tags: ['[a]', '[b]'],
+ };
+ const raw = JSON.stringify([nestedAtom]) + '\nSee [Source: alice-example, 2026-09-03].';
+ const atoms = atomsOf(raw);
+ expect(atoms).toHaveLength(1);
+ expect(atoms[0]!.title).toBe(nestedAtom.title);
+ });
+
+ test('two complete top-level arrays: the FIRST one wins, pinning the anchor scan precedence', () => {
+ // Not a prompted shape, but the anchor scan's first-candidate-wins policy
+ // now applies because each candidate ends at its own closing bracket.
+ const secondAtom = { ...ATOM, title: 'A later, different array' };
+ const raw = ATOM_ARRAY + '\nCorrected answer:\n' + JSON.stringify([secondAtom]);
+ const atoms = atomsOf(raw);
+ expect(atoms).toHaveLength(1);
+ expect(atoms[0]!.title).toBe(ATOM.title);
+ });
+
test('an empty array after BRACKETED prose is a zero-yield success (#4948 rule holds at any offset)', () => {
// The #4948 prompt tells the model to answer exactly `[]` when nothing is
// extractable. A model that first echoes a bracketed citation and then