Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): an atom's nested empty concepts list no longer reads as an honest zero-yield (#6260)
time-attackece771838194
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 0ed796e5b5..37295b1d1f 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 (`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/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 `[]` is zero-yield only when no earlier `[` is still open at its offset (an atom's own `"concepts": []` inside a clipped or malformed array is malformed output, `test/extract-atoms-nested-empty-array.test.ts`), 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/src/core/cycle/extract-atoms-parse.ts b/src/core/cycle/extract-atoms-parse.tsindex ad74cd1c62..c1df284f77 100644--- a/src/core/cycle/extract-atoms-parse.ts+++ b/src/core/cycle/extract-atoms-parse.ts@@ -122,9 +122,20 @@ function parseAtomsOutcomeInner(raw: string): AtomsParseOutcome {// elements all fail the shape gate is malformed output: it rides the// failure streak like every other parse failure instead of tombstoning the// item forever on the first try.+ //+ // #6260: the honest `[]` counts only at top level. An empty array that sits+ // inside an earlier `[` that is still open at its offset (a clipped+ // response, or complete JSON broken by a missing comma) is an atom's own+ // `"concepts": []`, not the model saying "nothing here", so it must not+ // turn malformed output into a zero-yield stamp.let firstAttempt: ReturnType<typeof parseArrayAtOffset> | null = null;let sawEmptyArray = false;let candidates = 0;+ const priorStarts: number[] = [];+ const enclosed = (at: number): boolean => priorStarts.some((s) => {+ const end = matchingCloseBracket(cleaned, s);+ return end === -1 || end > at;+ });for (let start = firstStart;start !== -1 && candidates < MAX_ARRAY_ANCHOR_CANDIDATES;@@ -135,8 +146,10 @@ function parseAtomsOutcomeInner(raw: string): AtomsParseOutcome {// Captured on the FIRST iteration only — every reason string this function// can return still describes the first bracket, unchanged.if (firstAttempt === null) firstAttempt = attempt;+ const nested = enclosed(start);+ priorStarts.push(start);if (attempt.ok) {- if (attempt.parsed.length === 0) { sawEmptyArray = true; continue; }+ if (attempt.parsed.length === 0) { if (!nested) sawEmptyArray = true; continue; }const atoms = atomsFromParsedArray(attempt.parsed);if (atoms.length > 0) return { ok: true, atoms };}diff --git a/test/extract-atoms-nested-empty-array.test.ts b/test/extract-atoms-nested-empty-array.test.tsnew file mode 100644index 0000000000..3fed89d328--- /dev/null+++ b/test/extract-atoms-nested-empty-array.test.ts@@ -0,0 +1,39 @@+/**+ * #6260: an empty array counts as the model's honest "nothing here" only at+ * top level. An atom's own `"concepts": []` inside a clipped or malformed+ * outer array must read as malformed output (a counted failure), never as a+ * zero-yield extraction that stamps the item done.+ */+import { describe, expect, test } from 'bun:test';+import { parseAtomsOutcome } from '../src/core/cycle/extract-atoms-parse.ts';++const ATOM = '{"title":"Acme founded","atom_type":"insight","body":"Acme was founded in 2020.","concepts":[]}';++describe('parseAtomsOutcome: nested empty arrays (#6260)', () => {+ test('a clipped response whose first atom has "concepts": [] is malformed, not zero-yield', () => {+ const outcome = parseAtomsOutcome(`[${ATOM},{"title":"Bob joi`);+ expect(outcome.ok).toBe(false);+ });++ test('complete JSON with a missing comma before a nested [] is malformed', () => {+ const outcome = parseAtomsOutcome('[{"title":"A","atom_type":"insight","body":"x" "concepts":[]}]');+ expect(outcome.ok).toBe(false);+ });++ test('complete JSON with a trailing comma after a nested [] is malformed', () => {+ const outcome = parseAtomsOutcome('[{"title":"A","atom_type":"insight","body":"x","concepts":[],}]');+ expect(outcome.ok).toBe(false);+ });++ test('a top-level [] after closed citation brackets is still the honest zero-yield', () => {+ expect(parseAtomsOutcome('Per [1], nothing: []')).toEqual({ ok: true, atoms: [] });+ expect(parseAtomsOutcome('[]')).toEqual({ ok: true, atoms: [] });+ expect(parseAtomsOutcome('{"atoms": []}')).toEqual({ ok: true, atoms: [] });+ });++ test('a complete atom with an empty concepts list still parses as that atom', () => {+ const outcome = parseAtomsOutcome(`[${ATOM}]`);+ expect(outcome.ok).toBe(true);+ if (outcome.ok) expect(outcome.atoms.map((a) => a.title)).toEqual(['Acme founded']);+ });+});