Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
38.2 KB
Raw Blame

Key files: Graph And Facts

Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

Attendance evidence and ownership

The shared and filesystem extractors recognize canonical attendance only from supported explicit lists and uniquely resolved person targets when no pack owns the relationship. A pack owns it only when an attended rule has a phrase regex (ownsAttendanceInference); the shipped page-type-bound rule in gbrain-base and company-brain mirrors the in-code meeting prior and gets canonical attendance. Pack frontmatter_links take their direction from the verb's FRONTMATTER_LINK_MAP counterpart for the page type (outgoing when it has none), so pack meeting attendees are canonical person -> meeting too. Callers resolve source identities before resolvedLinkCandidate orients a Markdown or uniquely resolved bare-wikilink claim as person-to-meeting with the meeting as its origin. Only parsed link targets can make canonical body claims; display-label slugs stay ordinary mentions. hasAttendanceEvidence indexes the ordered, nonoverlapping evidence ranges rather than rescanning them for every reference. Strict frontmatter resolution has a separate, source-keyed cache capped at 256 entries within one resolver lifetime. Accepted ranges exclude HTML-comment spans, including comments inside an otherwise valid list line; a reference scanner seeing those spans cannot promote their hidden targets. Engine-backed link extraction requires a loaded ontology before graph writes. Failed local preparation instead returns an automatic-link error so the note can commit without rewriting pack-owned edges. DerivedLinkEndpointChangedError identifies only missing or revision-changed endpoints detected before graph mutation. Automatic publication catches that specific failure, preserving its note and prior graph with retryable auto-link metadata; direct reconciliation still refuses. Other errors propagate and roll back publication rather than being mislabeled as a harmless link conflict. replaceDerivedLinks validates that origin and the locked person/meeting types and revisions; its preserveExisting path keeps matching row identities while refreshing their evidence context and origin field. Ambiguous bare-name spellings remain mentions rather than asserted attendees, and nonmatching constrained pack rules suppress canonical fallback in both extractors. Automatic preparation discovers resolved frontmatter targets before applying pack target-type constraints, so an unchanged pack-owned attendance row is not deleted merely because its endpoint appears only in frontmatter. Missing endpoint metadata remains incomplete; known non-person targets are not admitted. Filesystem attendance reconciliation excludes legacy rows whose producer is unknown; existing canonical-write and sweep handling of those rows is unchanged. prepareAutomaticLinks, DB/stale extraction, filesystem extraction, and sweep share that ownership, so attendee re-extraction cannot delete a meeting claim, and removing the meeting's evidence can remove it. link-reconciliation.ts owns the shared source/default/federation resolution policy, re-exported by the extract command. Filesystem attendance uses file evidence with database endpoint metadata; missing, ambiguous, or denied attendance resolution preserves the prior graph and does not advance extraction watermarks. Incomplete local preparation still allows put_page to commit the note, with auto-link error metadata and retryable extraction. The shared Markdown mask preserves positions while respecting backtick and tilde fence closing rules. Attendance opts into comment masking in that same scanner, so comment openers inside code do not conceal later evidence. Other callers keep their existing code-only masking. Pack-owned outgoing mappings, including the shipped base and company packs, stay unchanged. See explicit attendance evidence for grammar, coverage limits, and the distinction from a historical repair.

Recall source selection

recall.source_id narrows both fact and page arms using the existing authorized scope resolver, then checks source liveness. Explicit default is not omission. With no selector, fact scope and page federation retain their previous behavior. The opted-in thin CLI uses engine-free scope resolution and refuses --brain; its source tests execute the real remote dispatcher, not only a canned response. Degraded serving has its own explicit serve dispatch guard, so the generated registry cannot assign its flags to the preceding thin-recall branch. test/cli-recall-flag-ownership.test.ts pins fresh generation and real CLI rejection of serve-only flags before a brain opens.

Files

  • src/core/facts/extraction-availability.ts — the ONE extraction-availability gate: resolveExtractionAvailability(engine, model?) resolves the extraction model through the engine (getFactsExtractionModel, DB-plane facts.extraction_model included) and asks the configured gateway isAvailable('chat', model); extractionAvailableForEngine(engine, capabilities?) is the corpus-harvest form, where an explicit caller-supplied capability report stays authoritative. Used by the serve checkpoint harvest (both lanes), the maintenance sweep's corpus pass, OpenClaw compact() rung 3 and the facts backstop's execution-time gate, so a servable DB-plane model is never classified keyless by the engine-blind detectCapabilities() probe; an unconfigured gateway answers unavailable (the segment stays banked for the sweep). Pinned by test/facts-extraction-availability.test.ts, test/checkpoint-harvest.serial.test.ts, test/sweep-writeback-corpus.test.ts and test/e2e/context-engine-rung3-extraction.test.ts.

  • src/core/extract-timeline-from-meetings.ts — normalizes canonical incoming and pack-owned outgoing attended edges into meeting/person roles before timeline fan-out. SQL requires a live person and live meeting (including legacy meeting notes); private-meeting filtering, source opt-in and source-qualified dedup apply. An invite waits until its first valid end, start or date passes (#6966). Tests test/extract-timeline-attendance.test.ts (empty gazetteer), test/extract-timeline-future-6966.test.ts. #6273: on a managed brain the rows are grouped per entity page and published by publishMeetingTimelines as database-only managed_maintenance_meeting_timeline requests (at most 200 rows each; the request id binds the page revision and the rows; rows already stored are not resubmitted, so a rerun admits nothing; a pending request stops that source for the run). prepareMeetingTimeline (dispatched from prepared-maintenance.ts) refuses malformed rows invalid_params, and at apply time re-reads each meeting (tier, title, slug, visibility) and runs the #5575 gate at the stored tier under withWriteTrust. The job handler throws on refused or pending writes. Test: test/extract-timeline-from-meetings-managed.test.ts.

  • src/core/context/delta-cursor.ts — pure helpers for delta's per-arm cursor: the opaque base64url cursor ({v:1, p:[since, slug], f:[created_at, id]}, validated like since), microsecond ISO normalization and the one-microsecond clamp, nextPagesPos/nextFactsPos (delivered prefix, now() - 2 s horizon DELTA_COMMIT_LAG_MS, the facts cursor computed from raw rows so a duplicate cluster split by a budget cut loses nothing), resolveDeltaStart and legacyDeltaCursor. test/delta-cursor-integrity.test.ts.

  • src/core/facts/question-recall.ts — recall's question: parseQuestionParam refuses supersessions, include_expired and more than 2,000 characters with the corrected call as fix.mcp; rankFactsByQuestion resolves entity per source to pairs and runs unlinkedNamesakes on the whole filtered pool before ranking, embeds the question once through embedQueryBounded (the gateway's query-embedding cache, so a query of the same text shares it; the embedding opt-out, a missing provider or a failed embed rank by term share and set facts_degraded.reason), ranks with search/fact-relevance.ts under the recall.question_admission rule (reserve default, or facts_arm; pool, uncomparable count and rule read concurrently), hydrates the ranked ids through rowToFact, counts uncomparable facts (facts_degraded.unembedded, the facts_unembedded notice with the embed --stale --facts preview), sets calibration (recall's informational facts_calibration: {status: 'unmeasured', model_key}, #6590) when the cosine arm ran on a model with no row in FACT_ADMISSION_FLOOR_EVIDENCE (search/fact-relevance.ts, shared with doctor fact_admission_floors), with the facts_calibration_unmeasured info notice deduped per brain per session by its dedupe_key (test test/recall-facts-calibration-6590.test.ts), and turns a DB error into unavailable (fix.next: wait). recallHintNotice builds recall_hint. Tests: test/recall-question.test.ts (both engines), test/recall-question-cli.test.ts.

  • src/core/ops/facts.ts — shared fact/memory operations, including recall and the delta cursor. Every recall response carries facts_order (newest, or relevance when question ranked the facts arm through facts/question-recall.ts); a query call without question or a fact filter emits recall_hint. context_pack and delta facts[] carry recall's fact_id and provenance (the stored facts.source), read in one batched withProvenance lookup by the delivered ids, so hot memory and MCP _meta stay unchanged; remote callers get provenance through the same redaction as the fact text, and it never enters text (#6146, test/context-pack-fact-traceability.test.ts). context_pack entity_facts[] carry the packed cards' own facts (#6724, entry in core-services-3.md). Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit facts_first packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional query_first packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add budget_packing effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates and years outside 0001-9999 (on the parsed UTC value) before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. Delta's per-arm cursor (contributor audit wave P0): the start position resolves cursor > since (whole tuple, slug only when supplied) > the session row; each arm advances through its delivered prefix o... (line truncated to 2000 chars)

  • src/core/markdown-code.ts — stripCodeBlocks masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. parseTimelineEntries in src/core/link-extraction.ts groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date and delimiter rules remain unchanged. Standalone backtick and tilde fences require valid closing markers; historical inline triple-backtick spans remain masked. Pinned through real FS/DB link and timeline consumers by test/timeline-parser-regression.test.ts; its adversarial whitespace workload runs in a timeout-bounded child process. #6133: inline spans pair backtick runs of equal length (CommonMark), found read-only by fence-scan.ts scanMarkdownCode/inlineCodeEndAt over a view where a bare CR is a space (so a span may still cross one), so a double-backtick span and a span holding a single backtick are masked whole and a backslash-escaped backtick opens nothing; the lint placeholder-date rule (src/commands/lint.ts) runs over the masked text, so placeholders in inline code no longer fire (test/lint-3958.test.ts, test/timeline-parser-regression.test.ts).

  • src/core/check-resolvable.ts — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. CROSS_CUTTING_PATTERNS.conventions is an array (notability gate accepts conventions/quality.md and _brain-filing-rules.md). extractTriggers() delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. extractDelegationTargets() parses > **Convention:**, > **Filing rule:**, and inline backtick references. DRY suppression is proximity-based via DRY_PROXIMITY_LINES = 40. parseResolverEntries accepts BOTH the markdown table AND a compact list format (- **skill-name**: trigger1 | trigger2 | trigger3 or - skill-name: trigger1 | trigger2); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex [a-z][a-z0-9-]+) so prose bullets like - **Note**:/- **Convention**:/- **TODO**: don't false-match as skill rows. skillPath is ALWAYS derived as skills/<name>/SKILL.md: an optional → \skills/path`(or ASCII->) suffix is stripped from the trigger but NOT honored as the path — two consumers (routing-eval.ts:skillSlugFromPath, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same skillPath; checkResolvablededupes so the reachability count counts each skill once. Pinned bytest/check-resolvable.test.ts(resolver shapes plus trigger array syntax cases) +test/check-resolvable-openclaw-compact.test.ts(8 cases overtest/fixtures/openclaw-compact-resolver/andtest/fixtures/openclaw-mixed-merge/). Tutorial: docs/guides/scaling-skills.md(three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K).checkResolvable(skillsDir, opts?)takes an optionalskillsDirSource(the detection tier fromautoDetectSkillsDir`, threaded by both callers... (line truncated to 2000 chars)

  • src/core/entities/resolve.ts — Free-form entity name → canonical slug resolution. resolveEntitySlug(engine, source_id, raw): exact slug (slug-shaped input via looksLikeSlug: lowercase Unicode letters and numbers plus /, _, -, so non-Latin slugs match exactly) → alias-exact (an unambiguous page_aliases hit via resolveAliases, verified against LIVE pages since page_aliases has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; ResolutionSource reports alias_exact) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across people/<token>-% + companies/<token>-% (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged prefix_expansion, not fuzzy_match: the sole candidate is chosen by cardinality, so facts/backstop.ts appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when sameEntityName holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → per-segment holding fallback (slugify; slugifySegment where slugify would delete letters; null if empty). Bare-name collisions never use popularity as confidence. isIdentityEntity(slug, type) (person/company/fund/organization types or their directories) and sameEntityName are shared with makeResolver. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner... (line truncated to 2000 chars)

  • src/core/facts/drain.ts + drain-scheduler.ts + src/core/cycle/facts-drain.ts + src/commands/doctor/checks/facts-drain.ts — the automatic facts drain on PGLite (no job worker there). runFactsDrain(engine, { owner, signal, wallClockMs }) runs queued facts-absorb jobs one at a time through the real handler (withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)), with authorizeJobExecution/withSubmissionAuthority, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside one BudgetTracker (facts:drain) capped at min(facts.drain_budget_usd 1.00, the rest of facts.drain_daily_budget_usd 5.00 over a rolling 24 h); capSource is user once either cap is set, so an unpriced model warns and runs under the defaults and refuses with the gbrain pricing set fix under a user cap. Before each claim the job's worst case (8,000-char turn + facts.extraction_max_tokens) must fit; facts.drain_max_jobs (50) bounds a run. Every stop other than an empty queue is a deferral that leaves jobs queued with no attempt counted (queue.deferJob): no_key, extraction_unavailable, budget_exhausted, daily_budget_exhausted, job_over_budget, no_pricing, provider_halted, shutdown. Run records (newest 20, 48 h) and the first-run marker live in config facts.drain_state; readFactsDrainStatus feeds doctor facts_drain and the readiness capability facts_drain. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues a facts_drain_first_run notice; deferrals raise one facts_drain_deferred notice per reason per process (takeFactsDrainNotice, taken by stdio dispatch.ts). Never writes stdout. startFactsDrainScheduler owns one unref'd 10-minute timer: it runs when the owner saw no activity since the previous tick or 30 minutes passed since the last run, one run in flight, an owner veto per tick (canRun), the timer callback returns the tick's promise (a test aw... (line truncated to 2000 chars)

  • src/core/facts/capture-dedup.ts — the capture-lane (hook:writeback, sweep:corpus, hook:compact) duplicate policy (#5888). cosineVerdict(source, score, claim, existing) is the one cosine rule at every fact-write decision point (backstop.ts unmanaged loop, single-prepare.ts decideSingleFact and so persistence/facts-prepare.ts under its publication guard): explicit lanes drop at the embedding model's calibrated threshold (supersession-threshold.ts; none for an uncalibrated model); capture lanes never drop by cosine and return near_duplicate only at 0.92+ when claimsDiverge (negation, number, date or amount tokens) is false. wouldDedupSamePage(ctx, existing, score, claim) (#6333, shadow only) is the explicit-lane same-page rewording rule the backstop measures but never acts on: the nearest candidate shares the lane, source_session and visibility, sits at or above SAME_PAGE_REWORDING_THRESHOLD (0.85) and does not claimsDiverge; the backstop counts (would_dedup_same_page) and logs it, and inserts the fact as before. Its measured false positives (Lisbon→Porto) are pinned in test/backstop-same-page-shadow-6333.test.ts and are why no drop path ships. dedupCapturedFacts runs before the backstop's managed/unmanaged branch: one indexed read ((source_id, visibility, gbrain_fact_fingerprint(fact)), LIMIT 50) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/page_aliases the claim names (claimNamesEntity, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of ctx.turnAt (else now) or written by a capture lane in the same canonicalConversationKey conversation (sweep:corpus:<file> and .txt stripped via corpusFileSessionId). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one writeback_dedup... (line truncated to 2000 chars)

  • src/core/facts/relink.ts + relink-publish.ts + relink-model.ts + relink-reasons.ts + relink-schema.ts — gbrain facts relink (src/commands/facts.ts, CLI-only, host-only). Candidates are active database-only rows with entity_slug IS NULL (fence-owned subjectless rows are only counted), walked by id from --after-id over idx_facts_unlinked_active. Free tiers via inferFactSubject, then the model tier (facts.extraction_model, batches of 25, --max-usd cap, private facts only with --include-private; an answer must quote the fact and pass the strict resolver). Publication is one coordinator request per entity page (relink_facts, dispatched from persistence/service.ts, managed or not): each fact's whole row is pinned by hash; prepare and the locked validation must classify identically; linked rows take fresh fence positions (row id, embedding, provenance, trust tier and write origin kept, valid_from/valid_until carried to the millisecond, and a row stored finer than a millisecond left unlinked as claim_unfenceable, #9260; context gains entity relinked from <tier>) ahead of the page projection; exact duplicates retire expired and detached; nothing is superseded; withdrawn claims and facts the user didn't say (not_user_attributed) are skipped; attempt rows and the decide_sweep_deferred handoff (enqueueRelinked, when the conflict slot is not off) commit in the same transaction. Write target follows persistence/fact-write-target.ts (the remember rule): bound write-through publishes the file, write-through off or connector-database publishes the page body only, an unbound write-through source is refused as unfenceable (relink never claims an owner). fact_relink_attempts (migration v187) holds linked/deduped records and model verdict memos (no_subject, ambiguous, unverified_match) stopping paid reruns unless --retry-model. RELINK_REASONS is the one reason list (code, memoized, fix) for output, memo, guide. Pinned by test/facts-relink.test.ts and test/facts-relink-routing.test.ts (+ test/e2e/facts-relink-routing.test.ts).

  • src/core/entity-identity.ts + src/core/ops/entity-identity.ts — cross-source entity identity (cross-source federation). THE IDENTITY KEY IS (source_id, slug): the same real-world entity routinely exists as a different page per mounted source, and nothing else in gbrain asserts "these pages are the same entity". The entity_identities table (migration v137) records that assertion explicitly — member pages grouped under an opaque entity_id handle (validateEntityId: slug-flavored, lowercase, max 128 chars), one optional canonical member per group, a page belongs to at most one identity (UNIQUE (source_id, page_id); re-linking MOVES it). A link's canonical demotion and upsert run in one transaction, and re-linking with canonical omitted keeps the member's canonical flag within the same group (canonical: false demotes explicitly). Posture is MANUAL-ONLY by design: rows come exclusively from the entity_identity_link op — no auto-matching or name-similarity heuristics, because a wrong identity merge silently corrupts retrieval. Three ops: entity_identity_link / entity_identity_unlink (write, localOnly — merges change what retrieval unions across sources, too sharp for a remote surface) + entity_identity_list (read; restricts MEMBER visibility to a federated grant or remote scalar scope, while a trusted local caller sees the full cross-source group — cross-source IS the feature). Retrieval union is OFF by default behind the entity_identity.union config key; when on, get_links/get_backlinks merge edges from identity co-members (dedup'd), never widening past the caller's source grant. Same SQL text on both engines (parity by construction); pinned by the entity-identity test + the DATABASE_URL-gated engine-parity suite. Topology context: docs/architecture/brains-and-sources.md.

  • src/core/extract-frontmatter.ts — resolveIncludeFrontmatter(engine, explicit?): the single answer for "extract related:/sources: frontmatter link edges too?" (autopilot.incremental_extract_include_frontmatter; explicit flag > file plane > DB plane via isConfigTruthy > false, fail-closed on an unreadable config table). Resolved INSIDE the shared helpers — extractLinksForSlugs and extractStaleFromDB default opts.includeFrontmatter through it, the same in-helper pattern as isGlobalBasenameEnabled — so sync's inline extract, the GitHub/Google source inline extracts, the extract_stale minion, gbrain maintain, the cycle's extract phase and gbrain extract --stale (flag absent → configured knob) all agree; no caller passes a literal false. Pinned by test/extract-include-frontmatter-config.serial.test.ts (resolver precedence + a source-text guard on the call sites + a PGLite link-row test through extractLinksForSlugs).

  • src/core/extract/receipt-writer.ts + src/core/extract/rollup-writer.ts + src/commands/extract-status.ts + src/commands/extract-explain.ts + src/commands/extract-benchmark.ts + src/core/schema-pack/scaffold-extractable.ts — unified extract operator surface. Every shipped extractor (deterministic facts.conversation in src/commands/extract-conversation-facts.ts + three LLM-backed cycle phases at src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts) writes ONE sealed DB-only receipt per run (writeReceipt) + UPSERTs a row to extract_rollup_7d (upsertExtractRollup). Receipt slug extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md; page type extract_receipt (not a frontmatter key) AND frontmatter dream_generated: true (belt+suspenders vs loop-guard drift). extract_receipt joins ALL_PAGE_TYPES in src/core/types.ts; extracts/ prefix gets a 0.3x source-boost demote in src/core/search/source-boost.ts. Migration v104 adds extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at) with PK (kind, source_id, day) + idx_extract_rollup_7d_day. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump rollup_write_failures instead of crashing the cycle. Migration v239 adds halt_reasons JSONB NOT NULL DEFAULT '{}' (DDL only, no backfill): classifyRunStop({ error }) takes true (an unclassified halt) or one word of the closed HALT_REASONS vocabulary (provider_auth, provider_billing, provider_rate_limit, provider_model_not_found, no_pricing, integrity_guard, item_error; a budget or deadline cap is an expected stop, never a reason), and the same UPSERT increments that key with bound parameters ($N::text, jsonb_set). unknown is never stored: the doctor read computes it as halt_count - sum(halt_reasons) (haltReasonsWithUnknown), so pre-v239 rows and older w... (line truncated to 2000 chars)

  • src/core/extraction-review.ts — Extraction quarantine lane markers, sibling of src/core/quarantine.ts / embed-skip.ts (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR provenance: 'auto-extracted' + status: 'unverified' (both required — user pages with their own status/provenance never match). Exports quarantineMarkers(), isUnverifiedExtraction() (JS predicate) and unverifiedExtractionFragment(alias) — the single SQL source of truth consumed by buildSourceFactorCase (namespace source-boost guard), both engines' getUnverifiedExtractionPageIds, the extraction_pending op, and the unverified_extractions doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the people//companies/ source-boost (rank as ordinary content), stamped unverified: true in search results (stampUnverifiedExtractions, hybrid.ts), listed by extraction_pending, promoted (status → verified, provenance kept for audit) or rejected (soft-delete) by the owner-only extraction_review op, which also records distinct decisions (distinct_from); every decision publishes through the page door (Git first on a repository source, the database on a repo-less one) under persistence/publication-guard.ts, with the revision it read. Pinned by test/extraction-review.test.ts (PGLite) + test/e2e/extraction-review-postgres.test.ts (live Postgres parity).

  • src/core/facts-fence.ts — the ## Facts fence primitives: parse (parseFactsFence; #6385: cells are read by the column the header names (factsHeaderLayout, FACTS_FENCE_COLUMNS), so an unknown, repeated or missing required header column is one FACTS_TABLE_MALFORMED and no rows, a header in canonical order keeps the positional typed tail, and factsRowProblem lets a row leave off only trailing optional columns and refuses a non-empty cell past the layout; only a struck row reads superseded by #N (supersededBy) or forgotten: from its context cell, so on a live row that text is plain context (#9069); a confidence cell outside 0..1 or not a plain number is FACTS_TABLE_MALFORMED, a claim_value cell parses strictly (plain/scientific numbers, 1,234,567 separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as 1,5 or 0.9abc is FACTS_TABLE_MALFORMED), formatFenceDate writes UTC-midnight dates as YYYY-MM-DD and any other instant as a UTC timestamp so TTLs and write-time valid_from round-trip, so the page is non-authoritative instead of failing the DB CHECK), render (renderFactsTable), and strip (stripFactsFence({keepVisibility}) — the remote-read privacy boundary get_page/fetch_page/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: replaceOrInsertFactsFence(body, fenceBlock) replaces an existing fence in place or inserts a fresh ## Facts section ABOVE the timeline sentinel (timelineSentinelOffset, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (upsertFactRow, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. upsertFactRow throws FenceRewriteRefusal (fence-shared.ts) when the fence it starts from parses with warnings (#6385 R12): it re-renders the parsed rows, so a rewrite would delete the rows the parser skipped. restoreHiddenFactRows(incoming, existing) is the row-level, vis... (line truncated to 2000 chars) GST-2492: parseFactsFenceFor(body, { slug, reader }) reads the optional entity column only on memory/unattributed (HOLDING_FACTS_COLUMNS; a cell must be a page slug other than the holding page, else FACTS_TABLE_MALFORMED), and reader: true tolerates it where only the body is known (withdrawal overlay, remote strip); parseFactsFence(body) and every other page parse as before. GST-2497: a table's parse is kept by its text, whether the entity column is read and the folder holding page's slug (the newest 8), and every caller gets its own copy, so one write parses a table once however many readers see it; factsFenceTableParses() counts real parses for tests.

  • src/core/facts/attribution.ts — speaker attribution's one dedup rule: attributionCompatible(a, b) is false only for two different known speakers (user, assistant, other); NULL (no recorded speaker) is compatible with either. Every dedup path applies it before candidate limits: findCandidateDuplicates (attributedTo option, SQL pre-limit), decideSingleFact exact and cosine matches, capture exact/near matches, hot-memory collapse (collapseHotFacts splits a fingerprint group by speaker when it holds two), fence reindex (duplicateActiveFenceRows) and the managed batch key (facts-prepare.ts). facts.attributed_to (migration v215) is written by the extractor (facts.attribution, default on per docs/eval/decisions/p2-e3-heldout/; false opts out), carried in the fence's 15th cell (only on rows that have it), returned by recall and hot memory, rendered (assistant said) in context packs, and kept out of consolidate (takes are the user's own). Pinned by test/facts/speaker-attribution.test.ts.

  • src/core/fence-shared.ts — shared pipe-table primitives for the ## Takes (takes-fence.ts) and ## Facts (facts-fence.ts) fences: parseRowCells, isSeparatorRow, stripStrikethrough, parseStringCell, escapeFenceCell, and the rewrite guard (#6385 R12) assertFenceRewritable / FenceRewriteRefusal that upsertFactRow, upsertTakeRow, supersedeRow and mergePhantomFenceRows throw when their input fence parses with warnings (the message names the fence only; the warnings, which embed row text, stay on the error). parseRowCells is escape-aware: \| stays inside its cell and decodes back to a literal | (exact inverse of escapeFenceCell), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. escapeFenceCell also encodes fence-marker text (gbrain:facts:begin and the three siblings) by lengthening the ampersand run before #58; (gbrain:X → gbrain&#58;X, a literal gbrain&#58;X → gbrain&amp;#58;X), and decodeFenceCell (the decoder parseRowCells and fence-repair/raw-rows.ts share) removes exactly one level, so a claim that quotes a marker never becomes a live marker and a literal entity round-trips byte-identically; the lexical fail-closed privacy rule is unchanged. Pinned by the escape cases in test/facts-fence.test.ts + the full render → parse → reconcile round-trip in test/e2e/facts-fence-reconcile-postgres.test.ts.

  • src/core/link-extraction.ts — shared library for the graph layer. extractEntityRefs (canonical) matches [Name](../people/slug) markdown links and Obsidian [[people/slug|Name]] wikilinks; extractPageLinks, resolveMarkdownLinkSlug (an href resolved as extractPageLinks does, after pageRelativeMarkdownSlugs for a prefix-less .md dir link, page dir then ancestors like FS resolveSlug, #6983; output/validators/link.ts uses both), inferLinkType heuristics (attended/works_at/invested_in/founded/advises/source/mentions), parseTimelineEntries, isAutoLinkEnabled. In inferLinkType a per-edge verb counts only when it belongs to the link being typed (attachedVerb: a match with another link between it and this one, or written immediately before another link, is that link's), then precedence founded > invested_in > advises > works_at decides; joined [X] as <role> reads as works_at. attendanceEvidenceRanges accepts an Attendees:/Participants: line (plain or bold) and a ## Attendees/## Participants link-list section (Participants since gbrain-evals N12-6, with a LINK_EXTRACTOR_VERSION_TS bump so meeting pages re-extract). Markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (ANY_DIR_SEGMENT), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (resolveCandidateSources, put_page's allSlugs filter, addLinksBatch INNER JOINs) and counted as skippedMissingTarget in the extract summaries; the DIR_PATTERN whitelist is only the typed fast-path for pass-2b wikilinks (non-whitelisted [[dir/...]] get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Opt-in global-basename wikilink resolution (default off): WIKILINK_GENERIC_RE catches bare [[name]] wikilinks outside DIR_PATTERN (third pass 2c in `extractEnti... (line truncated to 2000 chars)

  • src/core/timeline-dedup-repair.ts — schema-drift self-heal for idx_timeline_dedup. A master-merge migration renumbering can leave a brain's version counter stamped past the index change while the index keeps an old shape — and every addTimelineEntry batch then fails its ON CONFLICT inference, silently breaking timeline writes brain-wide. The version counter can't detect this, so the repair is keyed off the actual index SHAPE. Canonical shape is (page_id, date, md5(summary), source) — md5-keyed (migration v138) because a raw long/incompressible summary would overflow the btree v4 row cap (~2704 bytes) and abort every timeline insert for that page; both engines' insert sites infer ON CONFLICT on the md5 tuple, so EXPECTED_COLUMNS MUST carry the md5 form (a raw-shape expectation would make the repair revert v138 on every migrate pass). checkTimelineDedupIndex(engine) returns {tablePresent, indexPresent, columns, needsRepair} (read-only; powers the timeline_dedup_index doctor check; the indexdef column parser is paren-depth-aware so md5(summary) — or any future expression column — parses as ONE column instead of flagging a correct index as drifted forever) and repairTimelineDedupIndex(engine) dedupes-then-rebuilds to the canonical shape (raw-summary grouping ⟺ md5 grouping modulo negligible collisions). runMigrations invokes the repair on every pass (including the no-pending early-return path); idempotent no-op when the index already matches. gbrain apply-migrations --force-schema triggers it on demand. Pinned by test/timeline-dedup-repair.test.ts.

  • src/core/trajectory-format.ts — shared formatTrajectoryBlock(points, entitySlug, opts) consumed by both gbrain think (production) and the LongMemEval harness (benchmark). Groups by (metric ?? event_type), per-metric cap 20, total cap 100, knowledge_update intent annotates a row with (superseded prior) when its value differs from the prior comparable observation (comparablePairs). Emits a <trajectory entity="..."> XML envelope — INJECTION_PATTERNS in src/core/think/sanitize.ts escapes </trajectory>, <trajectory ...> open tags, and attribute injection so adversarial fact text can't break out. Pinned by test/trajectory-format.test.ts.