Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(cycle): peel the extract-atoms parse block into extract-atoms-parse.ts
time-attacke908179c3790
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bc9c597219..0a87987ead 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -15,7 +15,7 @@ src/core/ai/gateway.ts 4423 ratchet +7 fix wave 5 (#5137): provider-key redactorsrc/commands/sync.ts 512 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event fieldsrc/core/cycle.ts 3254 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts)src/core/cycle/synthesize.ts 3195 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition-src/core/cycle/extract-atoms.ts 1814 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts)+src/core/cycle/extract-atoms.ts 1621 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts)src/core/engine.ts 2707 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_isosrc/core/import-file.ts 2179 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied)src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablediff --git a/src/core/cycle/extract-atoms-parse.ts b/src/core/cycle/extract-atoms-parse.tsnew file mode 100644index 0000000000..e39ee218a7--- /dev/null+++ b/src/core/cycle/extract-atoms-parse.ts@@ -0,0 +1,201 @@+/**+ * extract_atoms response parsing: the typed parse outcome, the bounded `[`+ * 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 { ATOM_TYPES } from './extract-atoms-schema.ts';++export interface ExtractedAtom {+ title: string;+ atom_type: typeof ATOM_TYPES[number];+ body: string;+ source_quote?: string;+ lesson?: string;+ /**+ * 1-3 kebab-case topic labels for concept clustering. Consumed by+ * synthesize_concepts (groups atoms by `frontmatter.concepts`; only+ * labels shared by >=2 atoms materialize a concept page, so the prompt+ * biases reuse-over-coinage). #2123.+ */+ concepts?: string[];+ virality_score?: number;+ emotional_register?: string;+}++/** kebab-case validator for concept labels ("captive-portal", "channel-pricing"). */+const CONCEPT_LABEL_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;++/**+ * gbrain#4148 — typed parse outcome. Malformed model output and a legitimate+ * zero-yield extraction both used to collapse into `[]`, so malformed output+ * was tombstoned as success (the page never retried, its atoms silently+ * lost). `ok: false` means the response was not parseable as an atoms array+ * AT ALL — a content-deterministic failure class the caller counts toward a+ * bounded tombstone; `ok: true, atoms: []` means the model genuinely+ * extracted nothing.+ */+export type AtomsParseOutcome =+ | { ok: true; atoms: ExtractedAtom[] }+ | { ok: false; reason: string };++export function parseAtomsOutcome(raw: string): AtomsParseOutcome {+ const direct = parseAtomsOutcomeInner(raw);+ if (direct.ok) return direct;+ // Same reasoning-block hazard as the facts extractor: `indexOf('[')` below+ // finds a bracket inside <think> when the model drafts its array while+ // reasoning, so the parse fails and the page is halted. Ladder, not a+ // pre-filter: raw first, stripped only on failure — and the ORIGINAL+ // outcome is returned when the retry also fails, so error reasons are+ // unchanged for non-reasoning models.+ const stripped = stripReasoningBlocks(raw);+ if (stripped && stripped !== raw.trim()) {+ const retry = parseAtomsOutcomeInner(stripped);+ if (retry.ok) return retry;+ }+ return direct;+}++/**+ * Bound on how many `[` offsets the anchor scan will try. Completions are+ * already capped by `max_output_tokens`, so this is a belt-and-braces guard+ * against a pathological bracket-dense response, not a functional limit —+ * every failing candidate fails at ~offset 0 of its own slice, so the scan is+ * cheap. Reached-the-cap behaves exactly like found-nothing: the FIRST+ * offset's outcome is returned, i.e. today's behaviour.+ */+const MAX_ARRAY_ANCHOR_CANDIDATES = 64;++/**+ * 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`.+ */+function parseArrayAtOffset(+ cleaned: string,+ start: number,+): { ok: true; parsed: unknown[] } | { ok: false; reason: string } {+ const slice = cleaned.slice(start);+ let parsed: unknown;+ try {+ parsed = JSON.parse(slice);+ } catch {+ // 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));+ } catch {+ return { ok: false, reason: 'unparseable JSON array' };+ }+ }+ if (!Array.isArray(parsed)) return { ok: false, reason: 'JSON value is not an array' };+ return { ok: true, parsed };+}++function parseAtomsOutcomeInner(raw: string): AtomsParseOutcome {+ // Strip markdown code fences if the LLM wrapped JSON in them.+ let cleaned = raw.trim();+ const fenceMatch = cleaned.match(/```(?:json)?\s*([\s\S]*?)```/);+ if (fenceMatch) cleaned = fenceMatch[1].trim();++ const firstStart = cleaned.indexOf('[');+ if (firstStart === -1) return { ok: false, reason: 'no JSON array in response' };++ // ANCHOR SCAN. Pre-fix this committed to `indexOf('[')` — the FIRST bracket+ // anywhere in the response. Any bracket in a preamble hijacked the anchor,+ // and a brain whose house style mandates inline `[Source: …]` citations and+ // `[[wikilink]]` backlinks (or whose transcripts carry `[user]` / `[tool: …]`+ // role markers) makes the model echo one while narrating, so a response+ // carrying a perfectly good array was reported `unparseable JSON array`.+ //+ // Acceptance requires the candidate to parse AND to yield >= 1 atom-shaped+ // element (`atomsFromParsedArray` is the single source of truth for+ // "atom-shaped"). Parseability alone is NOT enough: a zero-yield result is+ // exactly what TOMBSTONES an item (#2144), so only ONE parseable shape may+ // produce it — the literal `[]` the #4948 prompt asks for when nothing is+ // extractable, accepted at ANY offset (a model that echoes a `[Source: …]`+ // citation before obeying must not lose its honest `[]` to this gate and+ // burn three strikes into a tombstone + halt). A NON-empty array whose+ // 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.+ let firstAttempt: ReturnType<typeof parseArrayAtOffset> | null = null;+ let sawEmptyArray = false;+ let candidates = 0;+ for (+ let start = firstStart;+ start !== -1 && candidates < MAX_ARRAY_ANCHOR_CANDIDATES;+ start = cleaned.indexOf('[', start + 1)+ ) {+ candidates++;+ const attempt = parseArrayAtOffset(cleaned, start);+ // Captured on the FIRST iteration only — every reason string this function+ // can return still describes the first bracket, unchanged.+ if (firstAttempt === null) firstAttempt = attempt;+ if (attempt.ok) {+ if (attempt.parsed.length === 0) { sawEmptyArray = true; continue; }+ const atoms = atomsFromParsedArray(attempt.parsed);+ if (atoms.length > 0) return { ok: true, atoms };+ }+ }++ // Nothing yielded a real atom. An honest `[]` anywhere is the zero-yield+ // success (#4148 keeps "found nothing" distinct from "malformed"); otherwise+ // fall back to the FIRST offset's outcome — never a later one — so the+ // failure reason the drain surfaces as `last_error` still describes the+ // first bracket.+ if (sawEmptyArray) return { ok: true, atoms: [] };+ if (firstAttempt === null) return { ok: false, reason: 'no JSON array in response' };+ if (firstAttempt.ok) return { ok: false, reason: 'array had no atom-shaped elements' };+ return firstAttempt;+}++/**+ * Back-compat wrapper: parse the response into ExtractedAtom[], returning []+ * for BOTH malformed output and a legitimate zero-yield (legacy callers/tests+ * that don't need the typed distinction — new code uses parseAtomsOutcome).+ */+export function parseAtomsResponse(raw: string): ExtractedAtom[] {+ const outcome = parseAtomsOutcome(raw);+ return outcome.ok ? outcome.atoms : [];+}++function atomsFromParsedArray(parsed: unknown[]): ExtractedAtom[] {++ const atoms: ExtractedAtom[] = [];+ for (const item of parsed) {+ if (typeof item !== 'object' || item === null) continue;+ const obj = item as Record<string, unknown>;+ const title = typeof obj.title === 'string' ? obj.title.slice(0, 200) : null;+ const atomType = typeof obj.atom_type === 'string' ? obj.atom_type.trim().toLowerCase() : null;+ const body = typeof obj.body === 'string' ? obj.body : null;+ if (!title || !atomType || !body) continue;+ if (!ATOM_TYPES.includes(atomType as typeof ATOM_TYPES[number])) continue;+ atoms.push({+ title,+ atom_type: atomType as typeof ATOM_TYPES[number],+ body,+ source_quote: typeof obj.source_quote === 'string' ? obj.source_quote.slice(0, 500) : undefined,+ lesson: typeof obj.lesson === 'string' ? obj.lesson : undefined,+ concepts: (() => {+ if (!Array.isArray(obj.concepts)) return undefined;+ const labels = obj.concepts+ .filter((c): c is string => typeof c === 'string' && CONCEPT_LABEL_RE.test(c))+ .slice(0, 3);+ return labels.length > 0 ? labels : undefined;+ })(),+ virality_score:+ typeof obj.virality_score === 'number' &&+ obj.virality_score >= 0 &&+ obj.virality_score <= 100+ ? obj.virality_score+ : undefined,+ emotional_register:+ typeof obj.emotional_register === 'string' ? obj.emotional_register : undefined,+ });+ }+ return atoms;+}diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 3b1fcfc5b2..d6779cc8ac 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -59,7 +59,6 @@// which made the NOT EXISTS guard ineffective on federated brains.import type { BrainEngine, LinkBatchInput } from '../engine.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';@@ -94,6 +93,8 @@ import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { AtomPageStateError, completeAtomReceipts, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { ATOM_TYPES, ATOMS_RESPONSE_SCHEMA } from './extract-atoms-schema.ts';+import { parseAtomsOutcome } from './extract-atoms-parse.ts';+export { parseAtomsOutcome, parseAtomsResponse, type AtomsParseOutcome } from './extract-atoms-parse.ts';const DEFAULT_BUDGET_USD = 0.3;// #4529 + #4540: per-item extractor caps, overridable via@@ -240,26 +241,6 @@ export interface ExtractAtomsOpts {attempt?: { budgetTracker?: BudgetTracker; writeWait?: MaintenanceWriteWait };}-interface ExtractedAtom {- title: string;- atom_type: typeof ATOM_TYPES[number];- body: string;- source_quote?: string;- lesson?: string;- /**- * 1-3 kebab-case topic labels for concept clustering. Consumed by- * synthesize_concepts (groups atoms by `frontmatter.concepts`; only- * labels shared by >=2 atoms materialize a concept page, so the prompt- * biases reuse-over-coinage). #2123.- */- concepts?: string[];- virality_score?: number;- emotional_register?: string;-}--/** kebab-case validator for concept labels ("captive-portal", "channel-pricing"). */-const CONCEPT_LABEL_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;-/*** #4706 — locate a model-returned quote inside the text it was extracted from.*@@ -1475,180 +1456,6 @@ export async function runPhaseExtractAtoms(};}-/**- * gbrain#4148 — typed parse outcome. Malformed model output and a legitimate- * zero-yield extraction both used to collapse into `[]`, so malformed output- * was tombstoned as success (the page never retried, its atoms silently- * lost). `ok: false` means the response was not parseable as an atoms array- * AT ALL — a content-deterministic failure class the caller counts toward a- * bounded tombstone; `ok: true, atoms: []` means the model genuinely- * extracted nothing.- */-export type AtomsParseOutcome =- | { ok: true; atoms: ExtractedAtom[] }- | { ok: false; reason: string };--export function parseAtomsOutcome(raw: string): AtomsParseOutcome {- const direct = parseAtomsOutcomeInner(raw);- if (direct.ok) return direct;- // Same reasoning-block hazard as the facts extractor: `indexOf('[')` below- // finds a bracket inside <think> when the model drafts its array while- // reasoning, so the parse fails and the page is halted. Ladder, not a- // pre-filter: raw first, stripped only on failure — and the ORIGINAL- // outcome is returned when the retry also fails, so error reasons are- // unchanged for non-reasoning models.- const stripped = stripReasoningBlocks(raw);- if (stripped && stripped !== raw.trim()) {- const retry = parseAtomsOutcomeInner(stripped);- if (retry.ok) return retry;- }- return direct;-}--/**- * Bound on how many `[` offsets the anchor scan will try. Completions are- * already capped by `max_output_tokens`, so this is a belt-and-braces guard- * against a pathological bracket-dense response, not a functional limit —- * every failing candidate fails at ~offset 0 of its own slice, so the scan is- * cheap. Reached-the-cap behaves exactly like found-nothing: the FIRST- * offset's outcome is returned, i.e. today's behaviour.- */-const MAX_ARRAY_ANCHOR_CANDIDATES = 64;--/**- * 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`.- */-function parseArrayAtOffset(- cleaned: string,- start: number,-): { ok: true; parsed: unknown[] } | { ok: false; reason: string } {- const slice = cleaned.slice(start);- let parsed: unknown;- try {- parsed = JSON.parse(slice);- } catch {- // 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));- } catch {- return { ok: false, reason: 'unparseable JSON array' };- }- }- if (!Array.isArray(parsed)) return { ok: false, reason: 'JSON value is not an array' };- return { ok: true, parsed };-}--function parseAtomsOutcomeInner(raw: string): AtomsParseOutcome {- // Strip markdown code fences if the LLM wrapped JSON in them.- let cleaned = raw.trim();- const fenceMatch = cleaned.match(/```(?:json)?\s*([\s\S]*?)```/);- if (fenceMatch) cleaned = fenceMatch[1].trim();-- const firstStart = cleaned.indexOf('[');- if (firstStart === -1) return { ok: false, reason: 'no JSON array in response' };-- // ANCHOR SCAN. Pre-fix this committed to `indexOf('[')` — the FIRST bracket- // anywhere in the response. Any bracket in a preamble hijacked the anchor,- // and a brain whose house style mandates inline `[Source: …]` citations and- // `[[wikilink]]` backlinks (or whose transcripts carry `[user]` / `[tool: …]`- // role markers) makes the model echo one while narrating, so a response- // carrying a perfectly good array was reported `unparseable JSON array`.- //- // Acceptance requires the candidate to parse AND to yield >= 1 atom-shaped- // element (`atomsFromParsedArray` is the single source of truth for- // "atom-shaped"). Parseability alone is NOT enough: a zero-yield result is- // exactly what TOMBSTONES an item (#2144), so only ONE parseable shape may- // produce it — the literal `[]` the #4948 prompt asks for when nothing is- // extractable, accepted at ANY offset (a model that echoes a `[Source: …]`- // citation before obeying must not lose its honest `[]` to this gate and- // burn three strikes into a tombstone + halt). A NON-empty array whose- // 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.- let firstAttempt: ReturnType<typeof parseArrayAtOffset> | null = null;- let sawEmptyArray = false;- let candidates = 0;- for (- let start = firstStart;- start !== -1 && candidates < MAX_ARRAY_ANCHOR_CANDIDATES;- start = cleaned.indexOf('[', start + 1)- ) {- candidates++;- const attempt = parseArrayAtOffset(cleaned, start);- // Captured on the FIRST iteration only — every reason string this function- // can return still describes the first bracket, unchanged.- if (firstAttempt === null) firstAttempt = attempt;- if (attempt.ok) {- if (attempt.parsed.length === 0) { sawEmptyArray = true; continue; }- const atoms = atomsFromParsedArray(attempt.parsed);- if (atoms.length > 0) return { ok: true, atoms };- }- }-- // Nothing yielded a real atom. An honest `[]` anywhere is the zero-yield- // success (#4148 keeps "found nothing" distinct from "malformed"); otherwise- // fall back to the FIRST offset's outcome — never a later one — so the- // failure reason the drain surfaces as `last_error` still describes the- // first bracket.- if (sawEmptyArray) return { ok: true, atoms: [] };- if (firstAttempt === null) return { ok: false, reason: 'no JSON array in response' };- if (firstAttempt.ok) return { ok: false, reason: 'array had no atom-shaped elements' };- return firstAttempt;-}--/**- * Back-compat wrapper: parse the response into ExtractedAtom[], returning []- * for BOTH malformed output and a legitimate zero-yield (legacy callers/tests- * that don't need the typed distinction — new code uses parseAtomsOutcome).- */-export function parseAtomsResponse(raw: string): ExtractedAtom[] {- const outcome = parseAtomsOutcome(raw);- return outcome.ok ? outcome.atoms : [];-}--function atomsFromParsedArray(parsed: unknown[]): ExtractedAtom[] {-- const atoms: ExtractedAtom[] = [];- for (const item of parsed) {- if (typeof item !== 'object' || item === null) continue;- const obj = item as Record<string, unknown>;- const title = typeof obj.title === 'string' ? obj.title.slice(0, 200) : null;- const atomType = typeof obj.atom_type === 'string' ? obj.atom_type.trim().toLowerCase() : null;- const body = typeof obj.body === 'string' ? obj.body : null;- if (!title || !atomType || !body) continue;- if (!ATOM_TYPES.includes(atomType as typeof ATOM_TYPES[number])) continue;- atoms.push({- title,- atom_type: atomType as typeof ATOM_TYPES[number],- body,- source_quote: typeof obj.source_quote === 'string' ? obj.source_quote.slice(0, 500) : undefined,- lesson: typeof obj.lesson === 'string' ? obj.lesson : undefined,- concepts: (() => {- if (!Array.isArray(obj.concepts)) return undefined;- const labels = obj.concepts- .filter((c): c is string => typeof c === 'string' && CONCEPT_LABEL_RE.test(c))- .slice(0, 3);- return labels.length > 0 ? labels : undefined;- })(),- virality_score:- typeof obj.virality_score === 'number' &&- obj.virality_score >= 0 &&- obj.virality_score <= 100- ? obj.virality_score- : undefined,- emotional_register:- typeof obj.emotional_register === 'string' ? obj.emotional_register : undefined,- });- }- return atoms;-}-/*** Soft-delete a source's atoms from earlier extractions (a different or* provisional source_hash) that the current, completed extraction did not