Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(extraction): our own implementation of the #5209 fix (#5209)
time-attack807effe74c5f
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 9f6ddf1517..0e3da94712 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/dream-provenance.ts` — `stampDreamProvenance`, the unmanaged dream-output identity stamp shared by synthesize and patterns: sets `dream_generated`, a stable `dream_cycle_date` / `dream_created_cycle_date` and an optional `raw_source` in page frontmatter, and leaves a page that existed before the child's first write to it (`first_write_at`) unstamped. Managed brains stamp through maintenance writes instead. A ref's optional `seat` is stamped beside `raw_source` (the capturing agent seat, #4618).- `src/core/cycle/extract-atoms-schema.ts` — shared atom-type vocabulary and the extraction response schema. The private model prompt requests an object containing `atoms`; the schema uses closed objects and nullable optional metadata. `extract-atoms.ts` passes it through the gateway's capability gate and existing schema-rejection fallback, while its tolerant parser still accepts legacy bare arrays. Schema submission does not replace grounding or malformed-output checks. Covered by `test/cycle/extract-atoms-structured-output.test.ts` using a local HTTP protocol fixture and isolated PGLite, without live model inference.-- `src/core/cycle/extract-atoms-parse.ts` — extract_atoms response parsing, re-exported by `extract-atoms.ts`. `parseAtomsOutcome` returns a typed outcome (`ok: false` with a stable reason string for malformed output, `ok: true, atoms: []` for an honest zero-yield), retrying once with reasoning blocks stripped. A bounded anchor scan (`MAX_ARRAY_ANCHOR_CANDIDATES`) tries successive `[` offsets; each candidate ends at its own closing bracket (`findJsonCloseIndex` in `llm-json.ts`), the first array yielding an atom-shaped element wins, a literal `[]` at any offset is zero-yield, and failure reasons always describe the first bracket. `atomsFromParsedArray` is the single atom shape gate.+- `src/core/cycle/extract-atoms-parse.ts` — extract_atoms response parsing, re-exported by `extract-atoms.ts`. `parseAtomsOutcome` returns a typed outcome (`ok: false` with a stable reason string for malformed output, `ok: true, atoms: []` for an honest zero-yield), retrying once with reasoning blocks stripped. A bounded anchor scan (`MAX_ARRAY_ANCHOR_CANDIDATES`) tries successive `[` offsets; each candidate ends at its own closing bracket (`matchingCloseBracket` in `llm-json.ts`), the first array yielding an atom-shaped element wins, a literal `[]` at any offset is zero-yield, and failure reasons always describe the first bracket. `atomsFromParsedArray` is the single atom shape gate.- `src/core/cycle/anomaly.ts` — Pure stats helpers for `find_anomalies`. `meanStddev` returns sample stddev (n-1 denominator) and (0,0) for empty input. `computeAnomaliesFromBuckets(baseline, today, sigma, limit)` takes densified daily-count buckets + today's counts per cohort, returns `AnomalyResult[]`. Zero-stddev fallback: cohort fires when `count > mean + 1`, with `sigma_observed = count - mean` as a finite sort proxy (no NaN). Brand-new cohorts (no baseline) have `mean=0, stddev=0` so the fallback fires at count >= 2. Sorted by `sigma_observed` desc, top `limit` (default 20). `page_slugs` capped at 50 per cohort.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex 6086e10c8c..c96c44c965 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/init-embed-check.ts` — embedding-key validation at `gbrain init`. `runInitEmbedCheck(opts)` runs a config-only `diagnoseEmbedding` (catches a missing key for ANY provider) plus a best-effort `liveTestEmbed` (1-token `gateway.embed(['probe'], {inputType:'query', abortSignal})`, 5s `AbortController` timeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (`--no-embedding` is the deferred-setup escape; `--skip-embed-check` / `GBRAIN_INIT_SKIP_EMBED_CHECK=1` skip the check). Builds the effective env (`process.env` + every file-plane provider key `buildGatewayConfig` folds — openai/anthropic/voyage/dashscope/google — from `loadConfigFileOnly()` + `opts.apiKey`) and configures the gateway via `buildGatewayConfig` before diagnose/probe, so the check sees the same keys AND provider base URLs runtime will (no false "missing key" for config.json-keyed users; the probe hits the right endpoint). Init-specific warning text names `--no-embedding` / `--skip-embed-check`, not the sync-flavored `--no-embed`. Wired into `initPGLite` + `initPostgres` in `src/commands/init.ts`, with the result added to the `--json` envelope as `embedding_check {ok, reason?, live_ok?}`. Pinned by `test/init-embed-check.test.ts` (hermetic via the gateway embed-transport seam + `withEnv`).-- `src/core/llm-json.ts` — tolerant JSON extraction from LLM output. `parseLlmJson<T>(raw, {array?})` walks a strategy ladder (strip ```json fences → direct parse → first `{...}`/`[...]` substring; when the fenced extract fails, the same parses retry from the opening fence, or on the whole text when the fence sat inside a JSON string, so a quoted ``` cannot truncate the payload), then — only after the raw parse has failed — retries the same ladder with reasoning blocks stripped, so a payload that parses raw is untouched and a payload legitimately containing `<think>` is unaffected; returns null on any failure (adversarial throws swallowed). Exports `stripReasoningBlocks(raw)`: removes closed `<think>…</think>` pairs AND a truncated never-closed `<think>` tail (output-budget exhaustion) — reasoning models draft their JSON inside the think block, which defeats the greedy first-to-last-brace substring scan. Exports `findJsonCloseIndex(s)`: the index of the bracket closing the array/object opened at `s[0]` (depth tracking that skips brackets inside JSON strings and honors escapes; -1 when unclosed), which the chronicle judge, propose_takes and extract_atoms recovery paths use so a trailing `[Source: X]` citation cannot hijack the slice. `src/core/facts/extract.ts`'s hand-rolled `parseExtractorJsonDetailed` applies the same raw-first fallback ladder with the shared `stripReasoningBlocks`.+- `src/core/llm-json.ts` — tolerant JSON extraction from LLM output. `parseLlmJson<T>(raw, {array?})` walks a strategy ladder (strip ```json fences → direct parse → first `{...}`/`[...]` substring; when the fenced extract fails, the same parses retry from the opening fence, or on the whole text when the fence sat inside a JSON string, so a quoted ``` cannot truncate the payload), then — only after the raw parse has failed — retries the same ladder with reasoning blocks stripped, so a payload that parses raw is untouched and a payload legitimately containing `<think>` is unaffected; returns null on any failure (adversarial throws swallowed). Exports `stripReasoningBlocks(raw)`: removes closed `<think>…</think>` pairs AND a truncated never-closed `<think>` tail (output-budget exhaustion) — reasoning models draft their JSON inside the think block, which defeats the greedy first-to-last-brace substring scan. Exports `matchingCloseBracket(text, openAt = 0)`: the index of the bracket closing the array/object that opens at `text[openAt]` (counts the opener's own kind, skips string literals whole including escapes; -1 when `text[openAt]` is not a bracket or the value never closes), which the chronicle judge, propose_takes and extract_atoms recovery paths use so a trailing `[Source: X]` citation cannot hijack the slice. `src/core/facts/extract.ts`'s hand-rolled `parseExtractorJsonDetailed` applies the same raw-first fallback ladder with the shared `stripReasoningBlocks`.- `src/core/model-config.ts` — Model-string resolution (the seam every internal LLM call walks through). Four-tier system (`ModelTier = 'utility' | 'reasoning' | 'deep' | 'subagent'`) with `TIER_DEFAULTS` (utility→haiku-4-5, reasoning→sonnet-4-6, deep→opus-4-7, subagent→sonnet-4-6) and `tier?: ModelTier` on `ResolveModelOpts`. `resolveModelDetailed()` runs the 8-step chain and reports WHICH step won (`ResolveSource`): cliFlag → config key → deprecated key → `models.tier.<tier>` → `models.default` → env var (`GBRAIN_MODEL`) → key-aware tier default → caller fallback (the tier key sits ABOVE `models.default` — tier-specific beats generic, so setting a cheap utility tier is honored even when `models.default` is also set); `resolveModel()` is the thin wrapper for callers that only want the string. When the subagent capability gate replaces a configured model, the detailed result carries `substituted_from` + `substitution_reason` (`no_tools` / `no_subagent_loop` / `unknown_provider`); `describeResolveOrigin(source, opts)` renders the key-name origin (`models.tier.deep`, `models.default`, `GBRAIN_MODEL`, `built-in default`) used by the skillopt banner and `gbrain models`. Step 7 is KEY-AWARE: `resolveTierDefault(tier, env?)` walks `PROVIDER_TIER_DEFAULTS` (anthropic first — zero change for keyed installs; openai second so an OPENAI_API_KEY-only install resolves servable defaults) over the merged provider env (`mergedProviderEnv`, config-file keys folded, env wins, empty strings dropped); injected `env` is used EXCLUSIVELY (no config read — hermetic for tests); when neither anthropic nor openai key is present, a SERVABLE file-plane pin for the tier (utility→`expansion_model`, other tiers→`chat_model`, checked via `providerKeyReady`, `PIN_KEY_BY_TIER` is the single tier→key map) wins over the floor so a single-provider install (DeepSeek-only, OpenRouter-only, ...) routes every bare-default caller — extract_atoms, facts classify, page-summary — to the provider it actually has a key for; no key and no servable pin → `TIER_DEFAULTS` unchanged. The openai entry carries NO literal model pins: it resolves per call through the latest-model discovery cache (`src/core/ai/openai-latest.ts`, account-discovered, priced-only) with `openaiStaticTierFallback()` — the openai recipe's chat list ranked by the same grammar — as the offline floor, so the recipe is the single human-updated source and the account is the runtime source. The `gpt` alias resolves dynamically through the same path (the map entry is a documentation floor). `resolveEffectiveChatModel(fileCfg, env)` / `resolveEffectiveExpansionModel` are the ENGINE-FREE shared effective-model resolvers (`GBRAIN_MODEL` > servable file pin per `providerKeyReady` (recipe `auth_env.required`) > key-aware tier default; unservable pins warn once and fall through) — used by BOTH `reconfigureGatewayWithEngine`'s fallback layer and `detectCapabilities`' extraction probe so runtime routing and the capability report cannot diverge; they read RAW `loadConfig()` output, never gateway state (the boot fold stamps defaults, making explicit pins indistinguishable there). `isAnthropicProvider(modelString)` checks `provider:model` prefix OR `claude-` bare-id pattern (routes through `splitProviderModelId` from `src/core/model-id.ts` so slash-form ids like `anthropic/claude-sonnet-4-6` classify correctly). `enforceSubagentCapable()` is the layer-2 runtime guard: `tier === 'subagent'` resolutions are classified via `classifyCapabilities()` — `unusable:no_tools`/`unknown` warn once and fall back to `TIER_DEFAULTS.subagent`; `degraded:no_caching` (e.g. OpenAI) passes with a once-per-`(source, model)` cost warn. `_resetDeprecationWarningsForTest()` clears all three warn memos (deprecation, subagent, unservable-pin). Pinned by `test/model-config.serial.test.ts`.diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.tsindex 803727cad0..1dc0f89c62 100644--- a/src/core/chronicle/extract-events.ts+++ b/src/core/chronicle/extract-events.ts@@ -10,7 +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 { matchingCloseBracket } from '../llm-json.ts';import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';import { parseConversation } from '../conversation-parser/parse.ts';import { chroniclePageDate } from './eligibility.ts';@@ -346,8 +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.+ * The slice ends at the array's own closing bracket (`matchingCloseBracket`),+ * not the last `]` in the reply, so a citation after it cannot widen it.*/export function parseJudgeJson(text: string): ChronicleEventProposal[] | null {if (!text) return null;@@ -355,11 +355,10 @@ 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('[');- if (start === -1) return null;- const closeOffset = findJsonCloseIndex(s.slice(start));- if (closeOffset === -1) return null;+ const end = matchingCloseBracket(s, start);+ if (end === -1) return null;try {- const arr = JSON.parse(s.slice(start, start + closeOffset + 1));+ const arr = JSON.parse(s.slice(start, end + 1));return Array.isArray(arr) ? arr : null;} catch {return null;diff --git a/src/core/cycle/extract-atoms-parse.ts b/src/core/cycle/extract-atoms-parse.tsindex e39ee218a7..ad74cd1c62 100644--- a/src/core/cycle/extract-atoms-parse.ts+++ b/src/core/cycle/extract-atoms-parse.ts@@ -3,7 +3,7 @@* anchor scan and the atom shape gate. Peeled out of extract-atoms.ts, which* re-exports the public names.*/-import { findJsonCloseIndex, stripReasoningBlocks } from '../llm-json.ts';+import { matchingCloseBracket, stripReasoningBlocks } from '../llm-json.ts';import { ATOM_TYPES } from './extract-atoms-schema.ts';export interface ExtractedAtom {@@ -83,7 +83,7 @@ function parseArrayAtOffset(parsed = JSON.parse(slice);} catch {// Trim back to the array's own closing bracket to drop trailing prose.- const arrayEnd = findJsonCloseIndex(slice);+ const arrayEnd = matchingCloseBracket(slice);if (arrayEnd === -1) return { ok: false, reason: 'unterminated JSON array' };try {parsed = JSON.parse(slice.slice(0, arrayEnd + 1));diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex 4912328f22..399013d5bc 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -51,7 +51,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 { matchingCloseBracket } from '../llm-json.ts';import { TAKE_KIND_VALUES } from '../takes-fence.ts';import type { OperationContext } from '../operations.ts';import type { BrainEngine } from '../engine.ts';@@ -588,17 +588,13 @@ export function parseExtractorOutput(raw: string): ProposedTake[] {try {parsed = JSON.parse(text.slice(start));} catch {- // 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 closeOffset = findJsonCloseIndex(sliced);- if (closeOffset !== -1) {- try {- parsed = JSON.parse(sliced.slice(0, closeOffset + 1));- } catch {- return [];- }- } else {+ // Trailing noise (a leftover fence, a `[Source: X]` citation): parse only+ // up to the value's own closing bracket, never the last bracket in the text.+ const end = matchingCloseBracket(text, start);+ if (end === -1) return [];+ try {+ parsed = JSON.parse(text.slice(start, end + 1));+ } catch {return [];}}diff --git a/src/core/llm-json.ts b/src/core/llm-json.tsindex 5b16cf0843..4b8b0eff84 100644--- a/src/core/llm-json.ts+++ b/src/core/llm-json.ts@@ -50,38 +50,43 @@ export function stripReasoningBlocks(raw: string): string {}/**- * 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.+ * Where the JSON array or object opening at `text[openAt]` ends: the index of+ * its own closing bracket, or -1 when `text[openAt]` is not `[`/`{` (including+ * an out-of-range `openAt`) or the value is still open at the end of `text`.+ * String literals are skipped whole, so a bracket quoted in a field cannot end+ * the value, and a bracketed citation after the value (`[Source: X]`,+ * `[[wikilink]]`) is never reached. Only the opener's own kind is counted; a+ * stray closer of the other kind is left for JSON.parse to reject.*/-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;- }+export function matchingCloseBracket(text: string, openAt = 0): number {+ const opener = text.charAt(openAt);+ if (opener !== '[' && opener !== '{') return -1;+ const closer = opener === '[' ? ']' : '}';+ let open = 0;+ for (let i = openAt; i < text.length; i++) {+ const ch = text[i];if (ch === '"') {- inString = true;- } else if (ch === open) {- depth++;- } else if (ch === close) {- depth--;- if (depth === 0) return i;+ i = closingQuote(text, i);+ if (i === -1) return -1;+ } else if (ch === opener) {+ open += 1;+ } else if (ch === closer) {+ open -= 1;+ if (open === 0) return i;}}return -1;}+/** Index of the `"` that ends the string literal starting at `text[quoteAt]`, or -1 if it never ends. */+function closingQuote(text: string, quoteAt: number): number {+ for (let i = quoteAt + 1; i < text.length; i++) {+ if (text[i] === '\\') i += 1;+ else if (text[i] === '"') 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);@@ -126,7 +131,7 @@ function parseLlmJsonInner<T>(raw: string, opts: { array?: boolean } = {}): T |* fence regex is non-greedy, so it ends at the first ``` after the opener,* and a verbatim quote of a code block puts exactly that inside a JSON string.* The matched ``` is then one of two things, and the string-aware bracket scan- * (findJsonCloseIndex) tells them apart without trusting any later ```:+ * (matchingCloseBracket) tells them apart without trusting any later ```:** - a quote inside an unfenced reply: the first JSON value in the text* opens before the match and closes after it, so that value is the answer;@@ -147,8 +152,8 @@ function recoverFromQuotedFence<T>(raw: string, fence: RegExpMatchArray, opts: {const offset = raw.slice(from).search(/[[{]/);if (offset < 0) return null;const start = from + offset;- const close = findJsonCloseIndex(raw.slice(start));- return close < 0 ? null : { start, text: raw.slice(start, start + close + 1) };+ const close = matchingCloseBracket(raw, start);+ return close < 0 ? null : { start, text: raw.slice(start, close + 1) };};const leading = firstValueFrom(0);diff --git a/test/chronicle-extract.test.ts b/test/chronicle-extract.test.tsindex 10d9892239..3f2b16e46f 100644--- a/test/chronicle-extract.test.ts+++ b/test/chronicle-extract.test.ts@@ -173,31 +173,32 @@ 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"}';+// #5209: the judge reply's array ends at its own `]`. Slicing to the last `]`+// in the reply pulled a trailing footnote or wikilink into the JSON and lost+// a valid answer as parse_failed.+describe('parseJudgeJson ignores brackets in prose after the array (#5209)', () => {+ const meeting = (what: string) => JSON.stringify({ when: '2027-03-02', who: ['alice-example'], what, 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('a footnote marker after the array', () => {+ expect(parseJudgeJson(`[${meeting('kickoff')}]\nBased on the transcript [1].`)).toEqual([JSON.parse(meeting('kickoff'))]);});- test('recovers the array when a [[wikilink]] backlink follows it', () => {- expect(parseJudgeJson(`[${EVENT}]\nRelated: [[people/alice-example]].`)!.length).toBe(1);+ test('two events, then a wikilink line', () => {+ const out = parseJudgeJson(`Events:\n[${meeting('kickoff')},${meeting('retro')}]\nAlso see [[projects/acme-example]]`);+ expect(out?.map(e => e.what)).toEqual(['kickoff', 'retro']);});- test('a legitimate empty array followed by bracketed prose is still []', () => {- expect(parseJudgeJson('[]\nSee [Source: X].')).toEqual([]);+ test('a closing bracket and an escaped quote inside a field', () => {+ const out = parseJudgeJson(`[${meeting('she said "ship it]" twice')}] (refs: [a], [b])`);+ expect(out?.[0]?.what).toBe('she said "ship it]" twice');});- 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('control: a cut-off array followed by a citation is still a failure', () => {+ expect(parseJudgeJson(`[${meeting('kickoff')}, {"when":"2027-03-03"\n[Source: notes]`)).toBeNull();});- test('an array that never closes is still a parse failure', () => {- expect(parseJudgeJson(`[${EVENT}, {"when":"2026-06-19"`)).toBeNull();+ test('control: prose with brackets but no JSON array is still a failure', () => {+ expect(parseJudgeJson('No events found [see policy].')).toBeNull();});});diff --git a/test/llm-json-close-index.test.ts b/test/llm-json-close-index.test.tsdeleted file mode 100644index f182a8d594..0000000000--- a/test/llm-json-close-index.test.ts+++ /dev/null@@ -1,33 +0,0 @@-/**- * 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/llm-json-matching-close.test.ts b/test/llm-json-matching-close.test.tsnew file mode 100644index 0000000000..a6709b6b99--- /dev/null+++ b/test/llm-json-matching-close.test.ts@@ -0,0 +1,56 @@+/**+ * matchingCloseBracket: the scanner the chronicle judge, propose_takes,+ * extract_atoms and the quoted-fence recovery in parseLlmJson use to end a+ * JSON value at its own bracket. Caller behavior is pinned in each caller's+ * suite; this file pins the scanner's contract once, including the inputs a+ * hostile or truncated model reply can produce.+ */+import { describe, expect, test } from 'bun:test';+import { matchingCloseBracket } from '../src/core/llm-json.ts';++describe('matchingCloseBracket', () => {+ test('stops at the value, not at a later citation', () => {+ const text = '[{"k":"v"}] see [Source: memo]';+ expect(matchingCloseBracket(text)).toBe(text.indexOf('] see'));+ });++ test('scans from openAt and returns an absolute index', () => {+ const text = 'Answer: {"list":[1,2],"n":{}} and {later}';+ const openAt = text.indexOf('{');+ expect(text.slice(openAt, matchingCloseBracket(text, openAt) + 1)).toBe('{"list":[1,2],"n":{}}');+ });++ test('counts nesting of the same kind', () => {+ expect(matchingCloseBracket('[[],[[]]] ]')).toBe(8);+ });++ test('skips string literals whole: brackets, escaped quotes, escaped backslashes', () => {+ expect(matchingCloseBracket('["]]"] x]')).toBe(5);+ expect(matchingCloseBracket('{"q":"a\\"}"} }')).toBe(11);+ expect(matchingCloseBracket('["c:\\\\"] x]')).toBe(7);+ });++ test('a closer of the other kind is not counted', () => {+ expect(matchingCloseBracket('[}]')).toBe(2);+ expect(matchingCloseBracket('{]}')).toBe(2);+ });++ test('returns -1 when the value never closes', () => {+ expect(matchingCloseBracket('[{"k":1}')).toBe(-1);+ expect(matchingCloseBracket('["open string]')).toBe(-1);+ expect(matchingCloseBracket('["trailing backslash\\')).toBe(-1);+ });++ test('returns -1 when openAt is not an opening bracket or is out of range', () => {+ expect(matchingCloseBracket('see [x]')).toBe(-1);+ expect(matchingCloseBracket('')).toBe(-1);+ expect(matchingCloseBracket('[1]', -1)).toBe(-1);+ expect(matchingCloseBracket('[1]', 3)).toBe(-1);+ expect(matchingCloseBracket('a[1]', 0)).toBe(-1);+ });++ test('a deep unclosed run returns -1 without recursion', () => {+ expect(matchingCloseBracket('['.repeat(200_000))).toBe(-1);+ expect(matchingCloseBracket(`${'['.repeat(100_000)}${']'.repeat(100_000)}`)).toBe(199_999);+ });+});diff --git a/test/propose-takes.test.ts b/test/propose-takes.test.tsindex 7aea472d6b..53f145ce01 100644--- a/test/propose-takes.test.ts+++ b/test/propose-takes.test.ts@@ -251,29 +251,28 @@ describe('parseExtractorOutput', () => {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');+ // #5209: recovery must stop at the value's own closing bracket; the last+ // `]`/`}` in the reply can belong to prose after it.+ const take = (claim: string, kind = 'take') => JSON.stringify({ claim_text: claim, kind, holder: 'brain', weight: 0.7 });++ test('an array followed by a numbered citation keeps its takes', () => {+ const out = parseExtractorOutput(`[${take('Pricing beats features')},${take('Hiring lags plan', 'bet')}]\n[1] board memo`);+ expect(out.map(t => [t.claim_text, t.kind])).toEqual([['Pricing beats features', 'take'], ['Hiring lags plan', 'bet']]);});- 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 lone object followed by a stray `]` is recovered', () => {+ const out = parseExtractorOutput(`${take('Churn is seasonal', 'hunch')}\n]`);+ expect(out.map(t => t.claim_text)).toEqual(['Churn is seasonal']);});- 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');+ test('brackets, braces and an escaped quote inside claim_text', () => {+ const claim = 'Ratio {a]/[b} is "stable"';+ const out = parseExtractorOutput(`[${take(claim)}] per [[companies/acme-example]]`);+ expect(out.map(t => t.claim_text)).toEqual([claim]);+ });++ test('control: a cut-off array followed by a citation still yields nothing', () => {+ expect(parseExtractorOutput(`[${take('A')},{"claim_text":"B"\nSee [Source: memo]`)).toEqual([]);});});