Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Commands (3/6)
Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/commands/engine-status.ts—gbrain engine status [--json] [--probe] [--brain <id>]: the ENGINE-FREE detection primitive (CLI_ONLY, dispatched in handleCliOnly BEFORE connectEngine like pglite-repair; deliberately NOT an operations.ts op — an MCP server can't serve a status call when its DB is down). Zero round-trips without--probe: reports (JSONschema_version: 1)effective_enginevsconfig_file_engine(can differ under a transient env URL),db_url_source, env-shadow + both-env-URLs precedence note, redacted URLs only, brain id from the engine-free resolver (NOTget_brain_identity, which needs an engine), thin-client flag, and a Postgres pooler block (supabase-pooler detection,resolvePrepare, direct/session-pooler derivability,GBRAIN_DISABLE_DIRECT_POOL, pool sizes).--brain <id>/mount resolution reports the MOUNT's engine/URL, never the host's.--probeis a SINGLE bounded connect +SELECT 1(the driver's built-inconnect_timeout— never a custom race;noRetry, never the 3-attempt ladder); Postgres success also reportsConnectionManager.describeMode(); failure returns a classifiedPgAccessDiagnosis. PGLite probe is LOCK-AWARE: a live serve holding the single-writer data-dir lock reportslocked_by_serve(healthy-with-note) instead of hanging ~30s and misreporting a healthy brain. Exit 0 healthy, 1 on config diagnosis or failed probe, 2 on flag errors. Pinned bytest/engine-status.test.ts.src/commands/enrich.ts+src/core/enrich/thin.ts+src/core/cycle/enrich-thin.ts—gbrain enrich --thin: batch-develops stub (thin) pages via brain-internal grounded synthesis. gbrain's model tooling sees only brain-internal context (search / get_page / facts / backlinks), not the web, so enrich consolidates what the brain ALREADY knows about an entity (scattered across meetings, other pages, deals, facts) into one cited page via ONEgateway.chatcall per page; web research stays the agent-drivenenrichSKILL's job.runEnrichCore(engine, opts, signal)refuses managed mutation before provider work until its resume cursor can retain prepared writes (dry-run remains available); legacy writes expose pending/failed request IDs. It is strict per-source (multi-source iteration is the caller's job) and drivesenrichOneper candidate:withRefreshingLock('enrich:<src>:<slug>')→ coherentreadPageSnapshot(content, tags, revision) → deterministic retrieve (hybridSearch + getBacklinks + facts + raw_data, source-scoped, sanitized viaINJECTION_PATTERNS) →assessGroundinggate (skip <MIN_CONTEXT_CHARS, no LLM) →buildEnrichPrompt(grounded dossier,[Source: slug]citations, SKIP sentinel) → synth →put_pagehandler (remote:false, observed revision and caller-allocated request UUID, atomic projections and receipt) stampingenriched_at+enriched_by:'cli:enrich'. Candidate selection is the SQL-nativeengine.listEnrichCandidates(opts)(src/core/engine.tsinterface +EnrichCandidate/EnrichCandidatesOpts/ENRICH_ORDER_SQLinsrc/core/types.ts+ pg/pglite impls): thin-filter + per-page source-correct inbound count (to_page_id = p.id,mentionsand non-ranking link types excluded) +enriched_atrecency guard + whitelisted ORDER BY + LIMIT, lightweight projection (NO bodies). Resume viasrc/core/op-checkpoint.ts(localenrichFingerprint); budget viaBudgetTracker+withBudgetTracker(best-effort under--workers > 1—runSlidingPoolaborts new claims onBUDGET_EXHAUSTEDbut does NOT cancel in-flightgateway.chat; pin--workers 1for a hard ceiling).sanitizeContext(thin.ts) neutralizes the<context>…</context>data-envelope delimiters (injection escape, mirrors the</trajectory>convention);--backgroundasks consent first and stores a spend group; the--backgroundmulti-source fan-out idempotency key carries the run fingerprint via exportedbackgroundIdempotencyKey(sid, args)(a bareenrich:${sid}would return stale completed jobs);runEnrichCoreflagsbudget_exhaustedpost-hoc whentracker.totalSpent > tracker.capeven when the gateway swallowed the final-call throw (via read-onlyBudgetTracker.capgetter);body()flushes the checkpoint onBudgetExhaustedbefore it propagates so resume doesn't re-charge. The opt-inenrich_thincycle phase (default OFF viacycle.enrich_thin.enabled) tricklesmax_pages_per_tick(default 3) per source with per-source cost cap enforced asmin(per_source_cap, brain_wide_remaining)+ brain-wide total + walltime caps. Wired intocycle.ts(CyclePhase/ALL_PHASESbetweenconversation_facts_backfillandskillopt/embed;PHASE_SCOPE='source';NEEDS_LOCK; dispatch),cli.ts(CLI_ONLY+CLI_ONLY_SELF_HELP+THIN_CLIENT_REFUSED_COMMANDS+ dispatch),jobs.ts(Minionenrichhandler, strict per-source, NOT inPROTECTED_JOB_NAMES). DI seamopts.synthesizeFnkeeps tests hermetic (no API key, no mock.module). Pinned bytest/enrich/thin.test.ts,test/enrich/idempotency.test.ts,test/enrich-cycle-phase.test.ts,test/e2e/enrich-pglite.test.ts(grew-cited, skip, ordering, multi-source, recency, resume, budget abort + checkpoint flush, final-call overage, lock-skip, provenance),test/e2e/engine-parity.test.ts(listEnrichCandidatespg↔pglite parity).src/commands/eval-compare.ts—gbrain eval compare [--suite S] [--modes ...] [--runs ...] [--baseline RUN_ID --candidate RUN_ID] [--draws N] [--seed N] [--md|--json] [--input PATH]. Reads the run ledger<repo>/.gbrain-evals/eval-results.jsonl, keeps the newest record per (suite, mode) and renders the mode table plus any aggregatemetrics. Paired statistics come only from per-query rows: a record whoseparams.outputnames its per-question JSONL (gbrain eval longmemeval --record --output) is joined with its pair onquestion_id, and each per-query metric both rows carry (recall_all@k,recall_any@k,qa_accuracyfromjudge_correct) gets a paired cluster bootstrap 95% CI, a two-sided sign-flip p-value and a Holm p-value across the report's comparisons (src/core/eval/paired-bootstrap.ts). Pairs are every mode pair in a suite, or exactly--baseline/--candidate. Significant means Holm p ≤ 0.05 and a CI that excludes 0. Aparams.outputpath must resolve inside the repository root after following symlinks (pathWithinRoot); a.., absolute or symlinked path outside it is refused and never read. Runs without rows are listed inpaired_unavailable, and a report with no comparisons says it is aggregate-only;_meta.methodologydescribes only what was computed. Pinned bytest/eval-compare.test.ts.src/commands/eval-cross-modal.ts— multi-model quality gate. Three different-provider models score the OUTPUT against the TASK on 5 dims. Verdictpass(exit 0) /fail(exit 1) /inconclusive(exit 2; <2/3 model successes). Reuses gatewaychat()(recipe-registry auth/aliasing, no parallel provider stack). Self-configures the gateway fromloadConfig()+ env (cli.ts skipsconnectEngine());opts.useConfiguredGateway(the nightly probe) keeps the caller's brain-resolved gateway instead. Unkeyed slot defaults take the chat model (substituteUnavailableDefaultSlots, #4636;--slot-*-modelwins). Default cycles 3 in TTY, 1 in non-TTY viaresolveCycleDefault(src/core/eval/cycle-default.ts); the cost banner appendscycleDefaultSuffix(...)on that silent fallback. Receipts:gbrainPath('eval-receipts')/<slug>-<sha8>.json.--batch <jsonl> [--limit N] [--max-usd F] [--yes]scores a LongMemEval-shape JSONL; exclusive with--task(usage error); filterskind: "by_type_summary"rows; pre-flight estimate refuses over--max-usd(default 5) without--yes. SharedrunWithLimitfan-out:--concurrent Nquestions × 3 slots (default 3 → 9 calls). Per-question receipts live in a tempdir deleted at run end; the summary inlines per-question verdicts, slot-indexedslot_scoresand the judgepanel(distinct models/providers of the slots that scored, per-slotslot_scored_questions); stderr names a shared model, a silent slot and a panel under 3 providers, verdict unchanged (the nightly probe, not the batch, turns a collapsed panel inconclusive). Batch exit precedence (not aggregate.ts's): ERROR > FAIL > INCONCLUSIVE > PASS. DI seam:opts.runEval(like LongMemEval'sclient) bypasses real LLM calls and, withoutuseConfiguredGateway, the gateway availability check. Pinned bytest/eval-cross-modal-batch.test.ts.src/commands/eval-export.ts— streamseval_candidatesrows as NDJSON to stdout withschema_version: 1prefix on every line. EPIPE-safe, progress heartbeats on stderr, stable id-desc tiebreaker so--sincewindows never dupe/miss rows. D2:evaldeclaresjsonSubcommands{export, replay, gate: 'ndjson'}; under--jsoneach row is awriteNdjsonLineand argv errors are one{status:'error'}envelope line (invalid_params, exit 2).src/commands/eval-longmemeval.ts+src/eval/longmemeval/{harness,adapter,sanitize,extract,intent,reader,emit,capture,gateway-client,trajectory-route,decide-lane}.ts—gbrain eval longmemeval <dataset.jsonl>runs the public LongMemEval benchmark against gbrain's hybrid retrieval and is the repo's receipt producer for the strict retrieval metric and, with--judge, for judged answer accuracy (both reproduction paths are indocs/eval-bench.md). One in-memory PGLite per run viacreateBenchmarkBrain+withBenchmarkBrain; between questions,TRUNCATEover runtime-enumeratedpg_tableswith the infrastructure tables (sources,config,gbrain_cycle_locks,subagent_rate_leases, anddecide_calibrationsfor System One arms) preserved — which is why the run's pins, written once viaengine.setConfig, hold for every question.cli.tspre-dispatch bypass skipsconnectEngine(), so~/.gbrainis never opened. Embedded callers useRunOpts.exitOnError: falseto throw rather than terminate the host and preflight resolved chat providers before embedding; standalone CLI exits remain unchanged. Metric (metrics.ts): recall joins on RAW dataset session ids through a per-question slug→raw map;recall_all@k(every gold session among the distinct sessions of the top-k CHUNK rows returned atlimit: k) is the headline,recall_any@kthe diagnostic, and the per-rowrecall_hitis a deprecated alias ofrecall_any_hit;_absabstention questions are emitted withabstention: truebut stay out of the recall denominators unless--include-abstention; a slug collision touching a gold id aborts that question with an error row. Pins:--mode,--reranker on|off,--autocut on|off,--expansion(OFF for every mode — the per-call setting wins over the bundle, so--mode tokenmaxalone never expands),--expansion-variant-budget legacy|(0,4],--search-pin KEY=VALUE(repeatable; anysearch.*key, written verbatim viaengine.setConfig); precedence is explicit flag >--search-pin> injectedRunOpts.searchConfigSnapshot> bundle, so a flag wins over a pin on the same key. The raw--search-pinmap folds intoretrieval_config_hash(only when non-empty, so pin-free runs keep their hash identity) while the knobs hash covers only the resolved mode knobs. The reranker gate keys on the RESOLVED pin (flag,--search-pin, snapshot or bundle), not only on an explicit--reranker on: a run that resolves to reranker on preflightsrerankerReadinessForEngineand exits 2 with the fix when the reranker cannot run (abalancedrun with noVOYAGE_API_KEYexits with the fix text —--reranker offor set the key — instead of quietly scoring un-reranked rows). Gates (exit 1): a run in which every question errored, a row that fell through un-reranked under a resolved reranker-on pin (reranker_skipped_rows), a row whose vector arm silently degraded to keyword-only on a non---keyword-onlyrun (vector_degraded_rows:vector_enabled:false/embed_unavailable/embed_timeout), an--expansionrow that did not expand as configured (expansion_failed_rows), an--expansion-replaymiss, and--by-type-floor Fbreaches — which gate onrecall_allby default (--by-type-floor-metric recall_anyselects the lenient rate). The run-end gates andGBRAIN_LME_DEBUG=1prints per-question wall time to stderr;--recordrun through ONEfinishRunfrom both the main path and the no-op resume path. Rows:retrieved[](every returned chunk row:slug,chunk_id, RAWsession_id,rank,score,rerank_score?,alias_hit?),retrieved_session_ids,distinct_sessions_in_top_k,gold_total/gold_found,search_meta(vector_enabled,expansion_applied,degraded, derivedreranked= some finitererank_scoreand no skip stage,autocut),retrieval_config_hash, the reader pins on every answered row (reader_model= the requested id,reader_model_snapshot= the provider-reported id when it differs — a dated API snapshot — else null,reader_prompt_sha,reader_max_tokens;--retrieval-onlyrows carryretrieval_only: trueinstead so a judge backfill can refuse them),expansion_variantswhen expansion ran (--expansion-replay FILEserves them back and stampsexpansion_replayed, so every cell differs only in its knobs), and with--capture-poolarerank_pool— the exact pre-autocutreturnPoolhybridSearchhands toapplyAutocut(viaHybridSearchOpts.onRerankPool; unscored alias/exact-lookup injections included;rrf_rank,pool_rank,est_tokensper row;autocut_kept_keyswhen the returned rows are the kept set) for the offline autocut-floor replay. Summary:--by-typeemits aschema_version: 2by_type_summary(per-type + aggregate{total, all_hit, all_rate, any_hit, any_rate},excluded_abstention,mean_distinct_sessions,legacy_rows,gold_missing_from_haystack,slug_collisions, andrun_config: every pin, embeddermodel@dims, dataset sha256 + question count,knobs_hash+KNOBS_HASH_VERSION,retrieval_config_hash, the embed-cache receipt, the degradation counters); resume-replace keeps exactly ONE summary at the tail (emit.ts:emitByTypeSummary: the summary is always the FINAL line — any priorby_type_summaryis removed before the new one is appended, and the file rewrite is atomic,<path>.summary.tmp+ rename, so a kill mid-write never truncates the paid rows — its_meta.metric_glossaryis the ONE glossary block per response and names exactly the metrics carried,recall_all@k,recall_any@k, andqa_accuracywhen the judge lane ran; a CR inside any emitted line throws rather than splitting a JSONL record). Reader (reader.ts): the selected reader system text is constant across questions — every per-question input (question,Current Date: {question_date}when the dataset row carries one, the trajectory block, the sanitized<chat_session>blocks) lives in the USER message — soreader_prompt_sha(sha256 of the selected system text) is a run-level pin, alongside mode, version, model and output budget. Notes-first/1024 is the reader default; direct/512 retains the original prompt (official cap 500). Disclosed deviations from the officialrun_generation.pyprompt: an abstention instruction (say the information is not available / "I don't know" when the retrieved sessions lack it — without it the 30_absquestions are answered and judged wrong by construction), the #4338 data-boundary framing + pattern stripping, and the configurable cap.resolveReaderConfig,buildReaderRequestandreaderConfigHashare available throughgbrain/eval/longmemeval/readerto companion evals;generateAnswerreturns{text, response_model, finish_reason},response_modelbeing the provider-reported snapshot when it differs from the requested id (the harness's gateway client mapsChatResult.responseModel ?? modelinto the Anthropic-shapedmessage.model). Judge lane (--judge): implies--by-type;--judge --retrieval-onlyis a usage error. Preflight (judge-lane.ts:judgePreflight): no usable chat provider for the judge model → exit 1;--max-usdagainst an unpriced model → exit 2 (pass--max-usd off); estimate over the cap without--yes→ exit 2. The estimate (judge.ts:estimateJudgeRunUsd) assumes the selected reader output cap per live hypothesis and the stored hypothesis for backfill rows; theBudgetLedgersoft-stops at the cap and the remaining rows are stampedjudge_skipped: 'budget'. Live rows are judged inline after each reader call.--judge --resume-from FILEis the judge-only backfill:selectBackfillRowspicks every prior row with a hypothesis and no settled verdict (judge_errorrows are re-judged,--retrieval-onlyrows are refused, rows absent from the dataset are left unjudged with a WARN); a same-file resume ALWAYS appends (makeEmitter(outputPath, append)has no atomic-rewrite mode — appending is the only write path) — judged backfill rows and retries land as newer duplicates the moment they finish, so a timeout or kill loses at most the in-flight question — andcompactJsonlByQuestionId(emit.ts) rewrites the file atomically (<path>.compact.tmp+ rename) to one row per question_id (last wins, first-seen order) before the summary is emitted;readJsonlRows/loadResumeSetread appended files last-wins and--judge-concurrency Nparallelizes the backfill. Every judged row carriesjudge_config_hash— the judge pins (model,JUDGE_PROMPT_VERSION, max_tokens, temperature) plus the reader pins the row was produced under; a prior row hashes from its OWN recordedreader_model/reader_prompt_sha/reader_max_tokens, so a file answered by another reader is never relabelled as this run's, and rows already judged under a different hash are refused unless--allow-mixed-run-config. Run end:qa_accuracy(qa-accuracy.ts) is rebuilt from ALL rows (prior + new, last row perquestion_idwins) whenever the lane ran or any row carries a verdict; a run withjudge_errors > 0,skipped_budget > 0orunjudged > 0(theqa_accuracy.completepredicate) prints aFAIL … NOT publishableline and exits 1 unless--allow-incomplete-judgments(WARN, exit 0) — the fix is--judge --resume-from FILEuntil all three are 0; a row whose judge call threw is stampedjudge_error: 'provider_error'by the backfill, never silently left unjudged. Judge row fields: exactly one ofjudge_correct/judge_error(+ secret-redactedjudge_error_detail) /judge_skipped, plusjudge_model,judge_model_snapshot,judge_raw(first 200 chars),judge_cost_usd,judge_attempts,judge_prompt_kind,judge_prompt_version,judge_config_hash.RunOpts.judgeClient/judgeBackoffMsare the test seams. Embed cache: on by default at~/.cache/gbrain-eval/longmemeval-embed.sqlite(--embed-cache FILE/--no-embed-cache; never installed on--keyword-only), installed through the gateway embed-transport seam so every arm sees byte-identical vectors; the cache transaction wraps only the embed-producing section of a question (import + search), never a reader call. Resume:--resume-from FILEre-scores prior rows fromretrieved[]+ the dataset's gold (stored booleans are never trusted), refuses reader-mode/prompt/model/budget changes unconditionally (historical direct rows require--reader-mode direct), and refuses a differentretrieval_config_hashunless--allow-mixed-run-config; error rows without a hypothesis are retried.--question-ids FILErestricts the run to a listed slice (unknown ids or an empty file exit 1);--recordappends a secret-redactedEvalRunRecord(schema 3, suitelongmemeval, params =run_config) viapersistRunRecord. Flags live in ONE table,LME_FLAGS, that drives bothparseArgsandprintHelp, so the flag-registry scan sees every literal and help cannot drift from the parser; a switch written with a value (--judge=true) exits 1 like an unknown flag. Sanitization parity:harness.tsreusesINJECTION_PATTERNSfromsrc/core/think/sanitize.ts; retrieved chat content is wrapped in<chat_session id="..." date="...">and the answer-gen system prompt declares it UNTRUSTED.RunOptsseams —client,extractorClient/extractorModel,engine,searchConfigSnapshot,expandFn,embedTransport,rerankerReadiness,recordDir— let the full pipeline run hermetically without an API key. Trajectory routing (default on;--no-trajectorybypasses BOTH the extractor and the intent routing, the like-for-like retrieval setting):extract.tsruns the claim extractor (RunOpts.extractorModel, else the utility tier) over each haystack session into the benchmark brain'sfactstable (content-hash cache, per-question alias map, fail-open on every error path),intent.tsprefers the dataset'squestion_typebefore the SHARED regex set fromsrc/core/think/intent.ts, temporal/knowledge_update questions splice afindTrajectoryblock into the reader prompt, and rows carryintent,trajectory_points,entity_resolved,resolution_source,methodology_note(trajectoryMethodologyNote:extractor=haiku-preprocess-full-haystack-v1for a Haiku extractor, elseextractor=<model id>-preprocess-full-haystack-v1— "gbrain + extractor-preprocess", not "gbrain alone"). Incomplete reader output (max_tokens, empty or unknown finish) records its partial text only inreader_partial_output, clears the hypothesis, counts as a failed question and cannot be judged;reader_finish_reasonis stamped on answered attempts. Pinned bytest/eval-longmemeval-reader-mode.slow.test.ts,test/longmemeval-reader.test.ts,test/longmemeval-metrics.test.ts,test/eval-longmemeval-mixedcase.slow.test.ts(raw-id join, strict/any split, abstention, pins, gates over the placeholder fixturetest/fixtures/longmemeval-mixedcase.jsonl),test/eval-longmemeval-cli-smoke.test.ts,test/longmemeval-embed-cache.test.ts,test/longmemeval-judge.test.ts+test/eval-longmemeval-judge.slow.test.ts(the judge lane, reader pins andqa_accuracydenominators),test/eval-longmemeval.slow.test.ts,test/eval-longmemeval-e2e.slow.test.ts,test/eval-longmemeval-search-config.test.ts,test/longmemeval-extract.test.ts,test/longmemeval-intent.test.ts,test/longmemeval-trajectory-routing.test.ts. System One arms (decide-lane.ts, shared flags insrc/eval/decide-eval-flags.ts):--decide <slot>=<mode>and the--decide-*flags configure each benchmark brain so the slot acts, foldrun_config.decideintoretrieval_config_hash, stamp a per-rowdecidereceipt andrun_config.decide_summary, restrict to the--decide-dataseteval half, refuse trajectory routing (it readsquestion_type), and with--decide answerable=onlet the S4 verdictabstainreplace the reader call;--eval-pool-depth N(eval-only,src/core/search/eval-pool-depth.ts) lifts the per-arm cap to N and pinstop_n_in;--capture-poolrows carrypool_recallat fused depths 30/50/100/300 (capture.ts). All-off rows are unchanged. Tests:test/eval-longmemeval-decide.serial.test.ts,test/eval-pool-depth.test.ts.src/commands/eval-prune.ts— explicit retention cleanup. Requires--older-than DUR.--dry-runreports would-delete count.src/commands/eval-replay.ts— contributor-facing replay tool. Reads NDJSON fromgbrain eval export, re-runs each capturedquery/searchop against the current brain, computes set-Jaccard@k between captured + currentretrieved_slugs, top-1 stability rate, and latency Δ. Stable JSON shape (schema_version: 1) for CI gating; human mode prints a regression table. Pure Bun, zero new deps. The dev-loop half of BrainBench-Real. Seedocs/eval-bench.md.parseNdjsonskips lines where_kind === 'baseline_metadata'sogbrain bench publishbaselines parse cleanly without the metadata header polluting row counts. ExportsreplayCore(engine, opts): Promise<{summary, results}>+ReplaySummarytype sogbrain eval gatecalls replay in-process (NOT subprocess — avoids gbrain-version-drift for source-tree CI). CLIrunEvalReplaywrapsreplayCore. D2: under the--jsonguard the result is one compact NDJSON line (writeJsonLine; unguarded callers keep the pretty document) and failures end with a{status:'error'}envelope line (invalid_paramsexit 2,not_found,parse_error).eval gatefollows the same contract; a breached gate is the result line then agate_failederror line (exit 1).src/commands/eval-suspected-contradictions.ts+src/core/eval-contradictions/{judge,runner,types,date-filter,cost-tracker,cache,severity-classify,cross-source,trends,calibration,judge-errors,auto-supersession,scoped-read}.ts—gbrain eval suspected-contradictions [run|trend|review]. Probe samples top-K retrieval pairs per query (cross-slug + intra-page chunk-vs-take), date pre-filters (3-rule layered — same-paragraph-dual-date overrides separation rule), LLM judge (query-conditioned; UTF-8-safe truncation; confidence-floor double-enforcement; resolution_kind output drives paste-ready commands), persistent cache keyed on(chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy)(prompt edits cleanly invalidate prior verdicts), Wilson 95% CI calibration on the headline percentage withsmall_sample_notewhen n<30, judge_errors as first-class typed counters (parse_fail/refusal/timeout/http_5xx/unknown — avoids bias from silent skip), trend writes toeval_contradictions_runs, source-tier breakdown reusesDEFAULT_SOURCE_BOOSTSprefix logic, deterministic sampling (combined_score DESC + lex tiebreaker for stable cache hit-rate). Hermetic viajudgeFn+searchFnDI in the runner; never touches the real gateway in tests. Engine surface:BrainEngine.listActiveTakesForPages(batched),writeContradictionsRun+loadContradictionsTrend,getContradictionCacheEntry+putContradictionCacheEntry+sweepContradictionCache. Schema migrations v51 + v52. Pair members carry only content effective dates; afallbackdate becomes null ((date unknown)). MCP opfind_contradictions(read scope, NOT localOnly, NOT in subagent allowlist — user-initiated only; the stored report as written answers only trusted local callers without a user-selected source or trust floor, keyed onctx.localSourceImplicitfrommakeContext; every other caller goes throughscoped-read.tsresolveScopedFindings, which re-reads each side by chunk or take id underpageReadFilter(live), current text projection, safe chunks, holder allow-list and floor, drops a finding unless both sides are visible and unchanged, rebuilds the resolution command from live rows and withholds a supersede of a higher-trust take). Doctor check surfaces high-severity findings with paste-ready resolution commands; synthesize phase pre-fetches the latest probe's top-5-by-severity findings and threads them intobuildSynthesisPromptas an informational block. Architecture doc:docs/contradictions.md.src/commands/eval-trajectory.ts+src/commands/founder-scorecard.ts+src/core/trajectory.ts— temporal trajectory + founder scorecard.gbrain eval trajectory <entity>shows the chronological typed-claim history (mrr/arr/team_size/etc) with regressions auto-flagged inline;gbrain founder scorecard <entity>rolls up claim_accuracy / consistency / growth_trajectory / red_flags into one JSON. Pure-function math intrajectory.ts:detectRegressions(points, threshold)walks consecutive comparable pairs fromcomparablePairs(same metric, unit and period, strictly later valid_from; values that disagree at one valid_from break the chain) (10% drop default, env overrideGBRAIN_TRAJECTORY_REGRESSION_THRESHOLD);computeDriftScore(points)returns1 - mean(cosine(emb[i], emb[i-1]))over existing embeddings (null when <3 embedded points). Backed byBrainEngine.findTrajectory(opts)— both Postgres and PGLite, single SQL query that selects the NEWESTlimitpoints (ORDER BY valid_from DESC, id DESC) and returns them chronologically, so a capped series keeps its latest value. Source-scoped via thesourceIdscalar /sourceIdsarray dual pattern; visibility-filtered for remote callers. MCP opfind_trajectory(read scope, NOT localOnly) registered afterfind_experts. Migration v67 adds optional typed-claim columns (claim_metric,claim_value,claim_unit,claim_period) + a partial index on(entity_slug, claim_metric, valid_from) WHERE claim_metric IS NOT NULL. Fence widens from 10 to 14 cells when any row has typed data; renderer stays at 10 cells when none do (no churn diff on existing fences). Metric labels normalize to lowercase snake_case vianormalizeMetricLabel(15-entry seed map). Theconsolidatecycle phase does semantic upsert keyed on(page_id, claim, since_date)(so re-running the cycle afterextract_factsclearsconsolidated_atcannot append duplicates viaMAX(row_num)+1) and writes chronologicalvalid_untilon each cluster's older facts. Theextract_factscycle phase batch-embeds viagateway.embed()before insert AND threadspages.effective_dateas thepageEffectiveDatefallback forvalid_from(precedence: fence-row > pageEffectiveDate > now()). The contradiction probe MUST NOT writevalid_until— grep guard attest/eval-contradictions/no-valid-until-write.test.ts. Haiku extraction lives insrc/core/facts/extract.ts(not theextract-facts.tscycle phase); its output cap is configfacts.extraction_max_tokens(default 4000), astopReason: 'length'response retries once at 2× the cap, and persistent truncation warns loudly on stderr instead of silently extracting zero facts. Mixed extractor arrays salvage valid candidates and warn with the dropped malformed count; all-malformed output still fails retryably, while an explicitly empty facts array remains a successful empty result.pageEffectiveDateis OPTIONAL becausefence-write.tscallers have no Page object. Migration v89 adds a nullableevent_type TEXTcolumn onfactsso the substrate carries event-shaped rows (event_type='meeting'/'job_change'/'location_change') alongside metric rows.TrajectoryPoint.event_type: string | nullprojected by both engines.TrajectoryOpts.kind?: 'metric' | 'event' | 'all'filter (default'all');founder-scorecard+eval-trajectorypasskind: 'metric'explicitly. Back-compat pinned bytest/regressions/v0_40_2_0-trajectory-backcompat.test.ts(byte-identicalcomputeFounderScorecard+computeTrajectoryStatswith and without event rows); engine parity intest/engine-parity-event-type.test.ts.src/commands/eval-whoknows.ts—gbrain eval whoknows <fixture.jsonl> [--json] [--skip-replay]: two-layer eval gate. Layer 1 quality (hand-labeled fixture, top-3 hit rate ≥ 0.8). Layer 2 regression (eval_candidatesreplay set-Jaccard@3 ≥ 0.4). Sparseness fallback: < 20 replay-eligible rows → Layer 2 auto-skips with stderr warning. Stable JSON envelope withschema_version: 1; exit 0/1/2 for pass/fail/usage.WhoknowsFncallable abstraction makes the gates impl-agnostic;runEvalWhoknows(engine: BrainEngine | null, args)picks the impl at entry — thin-client mode (isThinClient(cfg)) routes per-query throughcallRemoteTool(cfg, 'find_experts', {topic, limit}), local mode callsfindExperts(engine, ...)directly. cli.ts adds a thin-client bypass beforeconnectEngine(dispatch shape undersrc/commands/eval.ts); the regression gate auto-skips in thin-client mode (no DB access toeval_candidates). Public exportsjaccardAtK,topKHit,readFixture,WhoknowsFn, threshold constants pinned bytest/eval-whoknows.test.ts(25 cases incl. null-engine signature contract).src/commands/eval.ts—gbrain evalcommand: single-run table + A/B config comparison. Sub-subcommand dispatch onargs[0]routesgbrain eval export+gbrain eval prune+gbrain eval replayinto session-capture handlers; baregbrain eval --qrels …fall-through preserves the legacy IR-metrics flow.gbrain eval cross-modalis in the dispatch (the user-facing path is the cli.ts no-DB branch —src/commands/eval.ts:cross-modalonly fires when callers re-enter with an existing engine).src/commands/export.ts+src/core/export-snapshot.ts+src/core/export-stage.ts+src/core/export-publish.ts— local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literalgbrain:facts:marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source throughresolveRestoreTarget(src/core/restore-target.ts, shared withgbrain storage status) and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the<slug>.mdand.raw/<name>.jsonlayout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent.gbrain-export-statusmarker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See safe export. Engine-freeexport --helpdocuments scope, no-overwrite publication and incomplete-output recovery. Wave B PR 2: a segmented page streams (segmentedExportMarkdown: serializeMarkdown's head (an optionalrevisionpins the body open to that page revision, asunreadPageFiledoes with its snapshot's, so a page that moved since refuses instead of mixing one revision's frontmatter with the next one's body), the trusted stored body throughreadBodyRangeunder a body ledger, hereexportBodyLedger, the same withdrawal overlay;restore_pageof a page over the single-string ceiling passes its snapshot's ledger; the timeline separator before the first timeline byte) into its own stage file (ExportStage.addStream, a full collection per 1 MiB read), published with the native path API; its payload estimate isbody_bytes, the per-page limit isexportPayloadLimit(pages.max_bytes)(32 MiB while segmented storage is off), a streamed page adds 1 ms per KiB to the 10-minute snapshot deadline and stage files must leave 512 MiB free on the staging filesystem (test/e2e/large-pages-export.test.ts: inline vs segmented same bytes at 2 and 20 MiB, export(import(F)) == F, a gated 128 MiB memory arm).exportPagePathwrites a page whose slug is not a portable file name under an escaped name with itsslug:line (:and other Windows-unsafe characters become~, a reserved device name or trailing dot/space gets~appended, an over-budget segment is cut with a~<8 hex>hash and marked not restorable);runExportreturns anExportReport, prints the escaped pages, and collects everyExportPathCollisioninto one refusal whose lines name each fix (test/pathological/b5-export-unsafe-slugs.test.ts). Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper. A page's file is rendered byexport-snapshot.ts(inlineExportMarkdown,segmentedExportHeadforsegmentedExportMarkdown; frontmatter with the #5966 slug stamp), which the git-gap equality contract (persistence/git-gap.ts) shares.src/commands/extract-conversation-facts.ts+src/core/cycle/conversation-facts-backfill.ts— bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into bounded windows viasrc/core/facts/conversation-windows.ts(#6267: eligibility per 30-min gap group of ≥2 messages decided before windowing; windows close at 30 messages or when the rendered text with its header would exceed 6,500 chars; oversized turns split at sentence boundaries with the speaker prefix repeated; a trailing single reply of an eligible group is its own window, never glued across a gap; nothing is clipped and an unrepresentable header fails the page before prior-fact cleanup; a page's frontmatterconversation_segment_gap_minutes, an integer from 1 to 10080, overrides the gap for that page, and any other value is ignored with a stderr warning naming the accepted range), prepends a topical/temporal header, and uses the strictextractFactsFromTurnWithOutcome()path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: strict per-source core (runExtractConversationFactsCore({sourceId, ...})always takes one sourceId; CLI + cycle phase each do their own multi-source iteration becausePHASE_SCOPE='source'is taxonomy-only); bounded two-phase enumeration (paginatedlistPages({type, sourceId, limit:10}); per-page body capMAX_PAGE_BODY_BYTES=CONVERSATION_BODY_MAX_BYTESinconversation-parser/body.ts,PAGE_MAX_BYTES+ 1 MiB = 25 MiB, measured on the parser input;readConversationBodyForParsingstats araw_transcriptsidecar and throwsConversationBodyTooLargeErrorover the cap before any read, the snapshot carriesoversizedSidecarBytes, and a size skip writes askipped_too_largereceipt topage_extraction_state(doctorextraction_input_truncated) that a later run under the cap clears; testtest/conversation-facts-oversized-sidecar.test.ts; a segmented page is read in ranges; one overCONVERSATION_WINDOW_BYTESwith no conversation facts is extracted from its newest window (day-header date,tail_windowreceipt,window_rule: no_prior_facts); one with facts is skipped with nothing cleared (skipped_too_large,window_rule: prior_facts_kept), since the run clears prior facts the window may not see, until PR 4's window anchors (testtest/large-pages/segmented-conversation-facts.test.ts)); page-globalrow_numaccumulator (the facts unique index is(source_id, source_markdown_slug, row_num)); versioned snapshot-bound outcomes (cli:extract-conversation-facts:terminal:v2for complete pages and a separatenon-extractable:v2source for recognized pages with no eligible segment); operation checkpoints are scheduling hints only and never suppress a replay without a matching v2 outcome; optionalopts.budgetTracker?is used as-is, while an absent tracker is created withmaxCostUsd(a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, viasrc/core/facts/conversation-budget.tsconversationFactsCostCap(#5823); explicit CLI/caller/cycle caps stay fail-closed and ano_pricingstop reportsbudget_reason/budget_model, exits 1 and namespricing.overrides); body reads cover compiled truth, timeline, and configured raw-transcript sidecars;facts.extraction_enabledkill-switch with--override-disabled;--types LISTallowlist (conversation,meeting,slack,email,imessage,imessage-daily);--backgroundviamaybeBackground; and speaker-shaped-fold decline — when the parse reportsunrecognized_headingscontaining a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted inpages_skipped_unrecognized_speaker(Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only.publishConversationFactsskips a non-outcome row an active conversation fact of the source already states (findCaptureDuplicate, no time bound;duplicates_skipped, #7043). The companionconversation_facts_backfillcycle phase is default-off, iterates every source exceptcycle.conversation_facts_backfill.exclude_sources(reported assources_excluded), reports managed pages left accepted and still publishing aspages_pendingin its details and summary (test/cycle-conversation-facts-backfill-pending-7500.test.ts), and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups.computeConversationFactsBacklogCheckreports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome.sources auditexposesfacts_backfill_estimate: {pages, est_segments, est_cost_usd, types}.--workers Nfor LLM-bound fact extraction over conversation pages, with a per-page advisory lock viasrc/core/db-lock.ts:withRefreshingLock(lock idextract-conversation-facts:<source>:<slug>, TTLPER_PAGE_LOCK_TTL_MINUTES=2with 20s refresh viaMath.max(15s, 120s/6);LockUnavailableErrortriggers skip-and-continue with rate-limited log per (source, minute) +pages_lock_skippedcounter + CLI exits 3 when non-zero AND no hard failures). A page's rows are buffered and published once after its last segment (publishPageFactson an unmanaged brain, onewriteDerivedFactstransaction; the managed batch otherwise), throughpublishConversationFacts(facts/conversation-publication.ts), so a crashed, failed, empty or partial run never removes the prior batch and a terminal audit row commits only with its page's facts (#7013); a run'sscopeispartialwhen fewer segments than in scope ran,windowwhen--sincedropped messages, elsefull, and a page that changed mid-run keeps an unmanaged run's facts as apartialbatch.assertFactsEmbeddingDimMatchesConfig(engine)is the startup preflight (throwsFactsEmbeddingDimMismatchErrorwith paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carriespages_lock_skipped+orphan_facts_cleaned. Additivepages_skipped_unparsed,pages_skipped_type_mismatch,pages_skipped_insufficient_turns, andpages_skipped_sinceexplain the unchangedpages_skippedaggregate across core, CLI, workers, and cycle sources; durable completion remains separate.--dry-runstops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrowpython-dict-utteranceregistry format and its quoted/nested-example rejection are documented in conversation parser patterns. Checkpoint state is a sharedcpMap: Map<slug, endIso>(NOT a per-page-mutatedcpEntries: string[]) so atomicMap.setsurvives parallel workers. Minion handlerextract-conversation-factsinsrc/commands/jobs.tsround-tripsworkersviajob.data.workersfor--background --workers 20. Cycle config keycycle.conversation_facts_backfill.workers(default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned bytest/extract-conversation-facts-diagnostics.serial.test.ts(pool workers, per-page lock skip + exit 3, replay replacing a prior partial run's facts, D15 preflight,--workersround-trip).src/commands/doctor.tsreads the same outcomes, which survive checkpoint GC. Each outcome is bound to the exact parsed snapshot: regular pages usecontent_hashplus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures incrementpages_failed, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Explicitslugsbatches contain page failures like the pool (cancellation and budget stops halt); logs carry only the closed reason and a retry command. Completion requires every in-scope segment (exactly--segment-limitcounts). Extracted rows takefacts.default_visibility(resolved once per run); audit rows stay private. Each page's own entities go to the extractor asentityHints(slugs,src/core/facts/conversation-entity-hints.ts, computed once per page, capCONVERSATION_ENTITY_HINTS_CAP= 40 throughExtractInput.entityHintsCap): authored edges only (the page's frontmatter edges with the page as origin, then outgoing markdown, wikilink-resolved and manual links), same source, live fact-entity pages, and a private entity only when the run's facts are private; theextract_factsop keeps its 5-hint cap and prompt. Pinned bytest/conversation-entity-hints.test.ts. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed.no_match, errors, cancellation, and dry runs never become durable negatives, barfacts/conversation-skip.ts(prose meetings, single emails, undated turns). Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See Conversation backfill durable outcomes for the operator and maintainer contract. Pinned bytest/extract-conversation-facts.test.tsandtest/doctor-conversation-facts-backlog.test.ts.--dry-runalso prints the paid-run estimate (facts/conversation-budget.tsconversationRunEstimate: segments, input and output tokens and dollars on the configured chat model, or apricing sethint for an unpriced model; JSONestimate). On a managed brain the core runsmanagedDerivedFactsPreflight(local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then published in its receipted batch after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests:test/managed-facts-writers.test.ts,test/managed-unsupported-preflight.serial.test.ts(refusal before spend for an unaccepted writer).