Garry's Opinionated OpenClaw/Hermes Agent Brain
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-planefacts.extraction_modelincluded) and asks the configured gatewayisAvailable('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-blinddetectCapabilities()probe; an unconfigured gateway answers unavailable (the segment stays banked for the sweep). Pinned bytest/facts-extraction-availability.test.ts,test/checkpoint-harvest.serial.test.ts,test/sweep-writeback-corpus.test.tsandtest/e2e/context-engine-rung3-extraction.test.ts.src/core/extract-timeline-from-meetings.ts— normalizes canonical incoming and pack-owned outgoingattendededges 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). Teststest/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 bypublishMeetingTimelinesas database-onlymanaged_maintenance_meeting_timelinerequests (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 fromprepared-maintenance.ts) refuses malformed rowsinvalid_params, and at apply time re-reads each meeting (tier, title, slug, visibility) and runs the #5575 gate at the stored tier underwithWriteTrust. 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 base64urlcursor({v:1, p:[since, slug], f:[created_at, id]}, validated likesince), microsecond ISO normalization and the one-microsecond clamp,nextPagesPos/nextFactsPos(delivered prefix,now() - 2 shorizonDELTA_COMMIT_LAG_MS, the facts cursor computed from raw rows so a duplicate cluster split by a budget cut loses nothing),resolveDeltaStartandlegacyDeltaCursor.test/delta-cursor-integrity.test.ts.src/core/facts/question-recall.ts— recall'squestion:parseQuestionParamrefusessupersessions,include_expiredand more than 2,000 characters with the corrected call asfix.mcp;rankFactsByQuestionresolvesentityper source to pairs and runsunlinkedNamesakeson the whole filtered pool before ranking, embeds the question once throughembedQueryBounded(the gateway's query-embedding cache, so aqueryof the same text shares it; the embedding opt-out, a missing provider or a failed embed rank by term share and setfacts_degraded.reason), ranks withsearch/fact-relevance.tsunder therecall.question_admissionrule (reservedefault, orfacts_arm; pool, uncomparable count and rule read concurrently), hydrates the ranked ids throughrowToFact, counts uncomparable facts (facts_degraded.unembedded, thefacts_unembeddednotice with theembed --stale --factspreview), setscalibration(recall's informationalfacts_calibration: {status: 'unmeasured', model_key}, #6590) when the cosine arm ran on a model with no row inFACT_ADMISSION_FLOOR_EVIDENCE(search/fact-relevance.ts, shared with doctorfact_admission_floors), with thefacts_calibration_unmeasuredinfo notice deduped per brain per session by itsdedupe_key(testtest/recall-facts-calibration-6590.test.ts), and turns a DB error intounavailable(fix.next: wait).recallHintNoticebuildsrecall_hint. Tests:test/recall-question.test.ts(both engines),test/recall-question-cli.test.ts.src/core/ops/facts.ts— shared fact/memory operations, includingrecalland thedeltacursor. Every recall response carriesfacts_order(newest, orrelevancewhenquestionranked the facts arm throughfacts/question-recall.ts); aquerycall withoutquestionor a fact filter emitsrecall_hint.context_packanddeltafacts[]carry recall'sfact_idandprovenance(the storedfacts.source), read in one batchedwithProvenancelookup by the delivered ids, so hot memory and MCP_metastay unchanged; remote callers get provenance through the same redaction as the fact text, and it never enterstext(#6146,test/context-pack-fact-traceability.test.ts).context_packentity_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/explicitfacts_firstpacking preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optionalquery_firstpacks 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 addbudget_packingeffective-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 resolvescursor>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—stripCodeBlocksmasks 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.parseTimelineEntriesinsrc/core/link-extraction.tsgroups 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 bytest/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 byfence-scan.tsscanMarkdownCode/inlineCodeEndAtover 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 lintplaceholder-daterule (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.conventionsis an array (notability gate acceptsconventions/quality.mdand_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 viaDRY_PROXIMITY_LINES = 40.parseResolverEntriesaccepts BOTH the markdown table AND a compact list format (- **skill-name**: trigger1 | trigger2 | trigger3or- 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.skillPathis ALWAYS derived asskills/<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 sameskillPath;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 vialooksLikeSlug: lowercase Unicode letters and numbers plus/,_,-, so non-Latin slugs match exactly) → alias-exact (an unambiguouspage_aliaseshit viaresolveAliases, verified against LIVE pages sincepage_aliaseshas no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table;ResolutionSourcereportsalias_exact) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion acrosspeople/<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) (taggedprefix_expansion, notfuzzy_match: the sole candidate is chosen by cardinality, sofacts/backstop.tsappends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only whensameEntityNameholds (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;slugifySegmentwhereslugifywould delete letters; null if empty). Bare-name collisions never use popularity as confidence.isIdentityEntity(slug, type)(person/company/fund/organization types or their directories) andsameEntityNameare shared withmakeResolver. 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 queuedfacts-absorbjobs one at a time through the real handler (withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)), withauthorizeJobExecution/withSubmissionAuthority, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside oneBudgetTracker(facts:drain) capped at min(facts.drain_budget_usd1.00, the rest offacts.drain_daily_budget_usd5.00 over a rolling 24 h);capSourceisuseronce either cap is set, so an unpriced model warns and runs under the defaults and refuses with thegbrain pricing setfix 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 configfacts.drain_state;readFactsDrainStatusfeeds doctorfacts_drainand the readiness capabilityfacts_drain. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues afacts_drain_first_runnotice; deferrals raise onefacts_drain_deferrednotice per reason per process (takeFactsDrainNotice, taken by stdiodispatch.ts). Never writes stdout.startFactsDrainSchedulerowns 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.tsunmanaged loop,single-prepare.tsdecideSingleFactand sopersistence/facts-prepare.tsunder 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 returnnear_duplicateonly at 0.92+ whenclaimsDiverge(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_sessionand visibility, sits at or aboveSAME_PAGE_REWORDING_THRESHOLD(0.85) and does notclaimsDiverge; the backstop counts (would_dedup_same_page) and logs it, and inserts the fact as before. Its measured false positives (Lisbon→Porto) are pinned intest/backstop-same-page-shadow-6333.test.tsand are why no drop path ships.dedupCapturedFactsruns 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_aliasesthe claim names (claimNamesEntity, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes ofctx.turnAt(else now) or written by a capture lane in the samecanonicalConversationKeyconversation (sweep:corpus:<file>and.txtstripped viacorpusFileSessionId). 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 onewriteback_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 withentity_slug IS NULL(fence-owned subjectless rows are only counted), walked by id from--after-idoveridx_facts_unlinked_active. Free tiers viainferFactSubject, then the model tier (facts.extraction_model, batches of 25,--max-usdcap, 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 frompersistence/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_untilcarried to the millisecond, and a row stored finer than a millisecond left unlinked asclaim_unfenceable, #9260; context gainsentity 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 thedecide_sweep_deferredhandoff (enqueueRelinked, when the conflict slot is not off) commit in the same transaction. Write target followspersistence/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 asunfenceable(relink never claims an owner).fact_relink_attempts(migration v187) holdslinked/dedupedrecords and model verdict memos (no_subject,ambiguous,unverified_match) stopping paid reruns unless--retry-model.RELINK_REASONSis the one reason list (code, memoized, fix) for output, memo, guide. Pinned bytest/facts-relink.test.tsandtest/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". Theentity_identitiestable (migration v137) records that assertion explicitly — member pages grouped under an opaqueentity_idhandle (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 withcanonicalomitted keeps the member's canonical flag within the same group (canonical: falsedemotes explicitly). Posture is MANUAL-ONLY by design: rows come exclusively from theentity_identity_linkop — 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 theentity_identity.unionconfig 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 "extractrelated:/sources:frontmatter link edges too?" (autopilot.incremental_extract_include_frontmatter; explicit flag > file plane > DB plane viaisConfigTruthy> false, fail-closed on an unreadable config table). Resolved INSIDE the shared helpers —extractLinksForSlugsandextractStaleFromDBdefaultopts.includeFrontmatterthrough it, the same in-helper pattern asisGlobalBasenameEnabled— so sync's inline extract, the GitHub/Google source inline extracts, theextract_staleminion,gbrain maintain, the cycle's extract phase andgbrain extract --stale(flag absent → configured knob) all agree; no caller passes a literalfalse. Pinned bytest/extract-include-frontmatter-config.serial.test.ts(resolver precedence + a source-text guard on the call sites + a PGLite link-row test throughextractLinksForSlugs).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 (deterministicfacts.conversationinsrc/commands/extract-conversation-facts.ts+ three LLM-backed cycle phases atsrc/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts) writes ONE sealed DB-only receipt per run (writeReceipt) + UPSERTs a row toextract_rollup_7d(upsertExtractRollup). Receipt slugextracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md; pagetypeextract_receipt(not a frontmatter key) AND frontmatterdream_generated: true(belt+suspenders vs loop-guard drift).extract_receiptjoinsALL_PAGE_TYPESinsrc/core/types.ts;extracts/prefix gets a 0.3x source-boost demote insrc/core/search/source-boost.ts. Migration v104 addsextract_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 bumprollup_write_failuresinstead of crashing the cycle. Migration v239 addshalt_reasons JSONB NOT NULL DEFAULT '{}'(DDL only, no backfill):classifyRunStop({ error })takestrue(an unclassified halt) or one word of the closedHALT_REASONSvocabulary (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).unknownis never stored: the doctor read computes it ashalt_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 ofsrc/core/quarantine.ts/embed-skip.ts(frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIRprovenance: 'auto-extracted'+status: 'unverified'(both required — user pages with their ownstatus/provenancenever match). ExportsquarantineMarkers(),isUnverifiedExtraction()(JS predicate) andunverifiedExtractionFragment(alias)— the single SQL source of truth consumed bybuildSourceFactorCase(namespace source-boost guard), both engines'getUnverifiedExtractionPageIds, theextraction_pendingop, and theunverified_extractionsdoctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + thepeople//companies/source-boost (rank as ordinary content), stampedunverified: truein search results (stampUnverifiedExtractions, hybrid.ts), listed byextraction_pending, promoted (status →verified, provenance kept for audit) or rejected (soft-delete) by the owner-onlyextraction_reviewop, which also recordsdistinctdecisions (distinct_from); every decision publishes through the page door (Git first on a repository source, the database on a repo-less one) underpersistence/publication-guard.ts, with the revision it read. Pinned bytest/extraction-review.test.ts(PGLite) +test/e2e/extraction-review-postgres.test.ts(live Postgres parity).src/core/facts-fence.ts— the## Factsfence 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 oneFACTS_TABLE_MALFORMEDand no rows, a header in canonical order keeps the positional typed tail, andfactsRowProblemlets a row leave off only trailing optional columns and refuses a non-empty cell past the layout; only a struck row readssuperseded by #N(supersededBy) orforgotten: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 isFACTS_TABLE_MALFORMED, aclaim_valuecell parses strictly (plain/scientific numbers,1,234,567separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as1,5or0.9abcisFACTS_TABLE_MALFORMED),formatFenceDatewrites UTC-midnight dates asYYYY-MM-DDand any other instant as a UTC timestamp so TTLs and write-timevalid_fromround-trip, so the page is non-authoritative instead of failing the DB CHECK), render (renderFactsTable), and strip (stripFactsFence({keepVisibility})— the remote-read privacy boundaryget_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## Factssection 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.upsertFactRowthrowsFenceRewriteRefusal(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 optionalentitycolumn only onmemory/unattributed(HOLDING_FACTS_COLUMNS; a cell must be a page slug other than the holding page, elseFACTS_TABLE_MALFORMED), andreader: truetolerates 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 theentitycolumn 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(attributedTooption, SQL pre-limit),decideSingleFactexact and cosine matches, capture exact/near matches, hot-memory collapse (collapseHotFactssplits 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 perdocs/eval/decisions/p2-e3-heldout/;falseopts out), carried in the fence's 15th cell (only on rows that have it), returned byrecalland hot memory, rendered(assistant said)in context packs, and kept out ofconsolidate(takes are the user's own). Pinned bytest/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/FenceRewriteRefusalthatupsertFactRow,upsertTakeRow,supersedeRowandmergePhantomFenceRowsthrow when their input fence parses with warnings (the message names the fence only; the warnings, which embed row text, stay on the error).parseRowCellsis escape-aware:\|stays inside its cell and decodes back to a literal|(exact inverse ofescapeFenceCell), 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.escapeFenceCellalso encodes fence-marker text (gbrain:facts:beginand the three siblings) by lengthening the ampersand run before#58;(gbrain:X→gbrain:X, a literalgbrain:X→gbrain&#58;X), anddecodeFenceCell(the decoderparseRowCellsandfence-repair/raw-rows.tsshare) 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 intest/facts-fence.test.ts+ the full render → parse → reconcile round-trip intest/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 asextractPageLinksdoes, afterpageRelativeMarkdownSlugsfor a prefix-less.mddir link, page dir then ancestors like FSresolveSlug, #6983;output/validators/link.tsuses both),inferLinkTypeheuristics (attended/works_at/invested_in/founded/advises/source/mentions),parseTimelineEntries,isAutoLinkEnabled. IninferLinkTypea 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.attendanceEvidenceRangesaccepts anAttendees:/Participants:line (plain or bold) and a## Attendees/## Participantslink-list section (Participantssince gbrain-evals N12-6, with aLINK_EXTRACTOR_VERSION_TSbump 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,addLinksBatchINNER JOINs) and counted asskippedMissingTargetin the extract summaries; theDIR_PATTERNwhitelist 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_REcatches bare[[name]]wikilinks outsideDIR_PATTERN(third pass2cin `extractEnti... (line truncated to 2000 chars)src/core/timeline-dedup-repair.ts— schema-drift self-heal foridx_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 everyaddTimelineEntrybatch then fails itsON CONFLICTinference, 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 inferON CONFLICTon the md5 tuple, soEXPECTED_COLUMNSMUST 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 thetimeline_dedup_indexdoctor check; the indexdef column parser is paren-depth-aware somd5(summary)— or any future expression column — parses as ONE column instead of flagging a correct index as drifted forever) andrepairTimelineDedupIndex(engine)dedupes-then-rebuilds to the canonical shape (raw-summary grouping ⟺ md5 grouping modulo negligible collisions).runMigrationsinvokes the repair on every pass (including the no-pending early-return path); idempotent no-op when the index already matches.gbrain apply-migrations --force-schematriggers it on demand. Pinned bytest/timeline-dedup-repair.test.ts.src/core/trajectory-format.ts— sharedformatTrajectoryBlock(points, entitySlug, opts)consumed by bothgbrain 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_PATTERNSinsrc/core/think/sanitize.tsescapes</trajectory>,<trajectory ...>open tags, and attribute injection so adversarial fact text can't break out. Pinned bytest/trajectory-format.test.ts.