Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(facts): relink guide, KEY_FILES entries, TODOS follow-ups and fix-wave notes (#5836)
garrytancb49123b6ff8
diff --git a/TODOS.md b/TODOS.mdindex 3cceac2684..b740a66d9f 100644--- a/TODOS.md+++ b/TODOS.md@@ -17,6 +17,19 @@- [ ] **P3 — Time the System One quickstart on a fresh machine (`/devex-review`).****What:** measure the documented key-in-hand to first-decision clock against the under-5-minute target. **Effort:** S. **Priority:** P3.+## Unlinked facts follow-ups (#5836, filed 2026-10-01)++- [ ] **P3 — Automatic free-tier relink in the dream/autopilot cycle.**+ **What:** run `gbrain facts relink --no-llm` as a bounded cycle phase so facts link when a new entity page appears. **Why:** the free tiers cost nothing and the write-time fix only covers new facts. **Cons:** a new cycle phase with its own lock and budget. **Effort:** M. **Priority:** P3.+- [ ] **P3 — Admin MCP op for relink on hosted/thin-client brains.**+ **What:** a localOnly-free admin operation so a hosted operator can run relink remotely. **Why:** thin clients refuse `gbrain facts`. **Effort:** M. **Priority:** P3.+- [ ] **P3 — `gbrain facts relink --undo <run_id>`.**+ **What:** move a run's links back (attempt rows carry `run_id`). **Why:** the correction path today is forget + remember per fact. **Effort:** M. **Priority:** P3.+- [ ] **P3 — Conflict candidates for facts with no entity page.**+ **What:** let the conflict sweep pick neighbours by embedding when a fact's subject has no page. **Why:** relink only links facts whose subject has a page. **Cons:** touches the conflict slot's candidate selection. **Effort:** M. **Priority:** P3.+- [ ] **P3 — Relink fence-owned subjectless conversation facts.**+ **What:** an entity column for transcript fences so conversation-extractor rows can be linked without leaving their fence. **Why:** relink reports them as `fence_owned` and leaves them. **Effort:** L. **Priority:** P3.+## Fix wave 5 follow-ups (filed 2026-10-01, follow-up from v0.60.28.0)- [ ] **P3 — Windows: unmanaged sync refuses a repo under an 8.3 short path.**diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex fa4c322b43..212997db09 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -78,6 +78,10 @@ rejection of serve-only flags before a brain opens.- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug → 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>-%` (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 → deterministic `slugify` holding fallback. 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-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).+- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text, resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).++- `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` BudgetTracker 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 and provenance kept, context gains `entity relinked from <tier>`) ahead of the page projection; exact duplicates retire expired and detached; nothing is superseded; withdrawn claims 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`) that stop reruns from paying again unless `--retry-model`. `RELINK_REASONS` is the one reason list (code, memoized flag, fix text) used by output, memo and the 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`).diff --git a/docs/fix-wave-notes/facts-relink-5836.md b/docs/fix-wave-notes/facts-relink-5836.mdnew file mode 100644index 0000000000..1867561099--- /dev/null+++ b/docs/fix-wave-notes/facts-relink-5836.md@@ -0,0 +1,40 @@+# facts-relink-5836 (#5836): unlinked facts++Contributor notes for the fix-wave collector (GBRA-37). No version bump on this branch.++## CHANGELOG paragraph++**Facts saved without an entity now get one, and the backlog can be repaired (#5836).**+Facts that no entity owned were invisible to entity recall, never reached the+entity page's `## Facts` fence, and the System One conflict sweep skipped them+as `no_entity` (one production brain had 23% of facts unlinked and 101 of its+last 103 new facts). `remember` and page imports now look for the subject in+the fact text without a model call and link only when exactly one existing+entity is named and no other name competes; the response says what happened+(`entity_inferred`, or `warnings: ["NO_ENTITY"]` with a hint). The new+`gbrain facts relink` repairs old facts: free tiers first, then the fact+extraction model under a `--max-usd` cap (default $1.00), moving each fact by+id onto its entity page's fence through the write coordinator, retiring exact+duplicates, never superseding anything, and queuing linked facts for the+conflict sweep. `gbrain doctor` reports `unlinked_facts`, and `gbrain decide+status` shows the share of conflict skips caused by missing entities.++## Upgrade note++- Migration v187 adds `fact_relink_attempts` and the `idx_facts_unlinked_active`+ index. It is separate from the optional backlog repair.+- New facts may now be filed onto entity pages automatically. Turn it off with+ `gbrain config set facts.entity_inference off`; that does not undo earlier links.+- Repair the backlog on the brain host: `gbrain facts relink --dry-run`, then+ `gbrain facts relink`. Guide: `docs/guides/facts-relink.md`.++## Design notes for reviewers++- Relink publishes through a coordinator mutation (`relink_facts`) on managed+ and unmanaged brains alike, the same coordinator remember uses. That replaced+ the planned unmanaged journal and extract_facts recovery hook: the+ coordinator's journal already makes the request replay or refuse as a unit.+- Alternatives considered and not taken: retrieval-first recall over+ unattributed facts (already partly served by fact-text filtering),+ entity-free conflict candidates (TODOS), LLM entity resolution at write time+ (remember stays zero-LLM).diff --git a/docs/guides/facts-relink.md b/docs/guides/facts-relink.mdnew file mode 100644index 0000000000..ffa53ba2fa--- /dev/null+++ b/docs/guides/facts-relink.md@@ -0,0 +1,127 @@+# Link facts saved without an entity++A fact is only useful to entity lookups when it is pinned to the person,+company or project it is about. Facts saved without that pin (an agent called+`remember` without `entity`, or a page import whose extractor named nobody)+are invisible to entity recall, never show on the entity's page, and the+System One conflict sweep skips them as `no_entity`.++GBrain now prevents most of them at write time and repairs the backlog with+`gbrain facts relink`.++**Say to your agent:** *"Link my unattributed facts to the people and companies they're about."*+The agent runs `gbrain facts relink --dry-run`, shows you the plan, then runs it.++**Say to your agent:** *"Why is the conflict sweep finding nothing?"*+The agent runs `gbrain decide status` and `gbrain doctor`; an `unlinked_facts`+warning or a `no_entity` share points at `gbrain facts relink`.++## What happens at write time++When `remember` gets no `entity`, it looks for one in the fact text without+calling a model. It links only when the text names exactly one existing+entity page by its full name, slug or alias, and no other name competes. "Acme+Example raised a seed round" links to `companies/acme-example`. "Alice Example+introduced me to Charlie Example", "Bob said yes" (a bare first name) and+"Northstar Example copied Acme Example's pricing" (a second company with no+page) stay unattributed. The response says what happened: `entity_inferred:+"mention"` when it linked, or `warnings: ["NO_ENTITY"]` with a hint when it did+not. Pass `infer_entity: false` to skip inference for one call.++Page imports work the same way, and a fact extracted from an entity page with+no other name in it belongs to that page.++Turn write-time inference off with `gbrain config set facts.entity_inference+off`. That does not undo earlier links, and it does not affect `gbrain facts+relink`.++## Repair the backlog++Run these on the brain host (thin clients refuse the command).++```bash+gbrain facts relink --dry-run # what would link; writes nothing, calls no model+gbrain facts relink # free tiers, then the model tier (default cap $1.00)+gbrain facts relink --no-llm # free tiers only+gbrain facts relink --max-usd 5 # raise the model-tier cap (or: off)+gbrain facts relink --json # machine-readable report (schema_version 1)+```++Relink finds a subject in three tiers, cheapest first: the page a fact was+extracted from, a unique entity named in the text, and finally the configured+fact-extraction model (`facts.extraction_model`) for whatever is left. The+model's answer must quote the fact and name an existing entity page, so an+invented or injected name never links. Private facts stay out of the model+tier unless you pass `--include-private`. Before the first model call relink+prints the provider and an estimated cost.++Each linked fact keeps its id, embedding and provenance and is written onto+the entity page's `## Facts` fence exactly as a fresh `remember` with that+entity would write it (the canonical file too, when the source writes+through). Its context cell records how it was linked (`entity relinked from+mention`, `... from page`, `... by model (<model>)`). An exact duplicate of a+fact the entity already has is retired: expired, kept in history, never+deleted. Relink never creates pages and never supersedes a fact.++### Large brains: continue where you stopped++Each run examines `--limit` facts (default 1000), walking by fact id. When more+remain, the report ends with the exact command to continue:++```bash+gbrain facts relink --after-id 48211+```++Facts that can never link do not block the ones after them. `--since+2026-09-01` limits a run to recent facts.++### The conflict sweep++When the System One conflict slot is on, every linked fact is queued for the+next sweep (`queued_for_conflict` in the report). A large backlog drains over+several sweeps within the sweep's normal per-run quota and daily budget;+`gbrain decide status` shows the progress. `--no-conflict-queue` skips the+handoff.++### Reruns and cost++The model's verdicts (`no_subject`, `ambiguous`, `unverified_match`) are+remembered, so a rerun does not pay for the same fact again. Pass+`--retry-model` to ask again. The free tiers always rerun, so creating an+entity page and rerunning links facts that name it.++### Fix a wrong link++`--json` lists the facts each run linked. To move one, forget it and remember+it again with the right entity:++```bash+gbrain forget <fact-id>+gbrain remember "<the fact>" --provenance "<source>" --entity <slug>+```++## Why a fact was not linked++| Reason | Remembered | What to do |+|---|---|---|+| `no_subject` | yes | The model found no single person, company or project in the fact. Nothing to fix; rerun with --retry-model to ask again. |+| `ambiguous` | yes | The fact names more than one entity, or a name competes with the match. Link it by hand: forget it and remember it again with --entity. |+| `unverified_match` | yes | The only match is a bare first name or a name that is not in the fact. Add an alias to the right entity page, then rerun. |+| `no_mention` | no | The fact names no entity. Rerun with the model tier (drop --no-llm), or link it by hand with remember --entity. |+| `no_page` | no | The fact names an entity that has no page. Create the entity page, then rerun. |+| `model_unavailable` | no | The extraction model could not be reached. Configure it (gbrain config set facts.extraction_model <provider:model>) or rerun with --no-llm. |+| `model_unparseable` | no | The model returned output relink could not read. Rerun; if it persists, set a different facts.extraction_model. |+| `withdrawn` | no | This claim was explicitly forgotten for that entity, so relink will not attach it there. |+| `page_file_missing` | no | The entity page exists in the database but its file is missing from the source tree. Restore the file or run gbrain sync, then rerun. |+| `unfenceable` | no | The source writes through to files but has no canonical owner. Bind the source (gbrain sources writer status <source> --json, then gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>), then rerun. |+| `fence_malformed` | no | The entity page has a malformed ## Facts fence. Repair the fence (gbrain doctor names it), then rerun. |+| `fence_owned` | no | The fact lives in another page fence (a transcript). Relink does not move fence-owned facts. |+| `budget_exhausted` | no | The model tier reached --max-usd. Raise --max-usd (or pass off) and rerun with the printed continuation command. |+| `revision_conflict` | no | The fact or the entity page changed while relink ran. Rerun. |++## Doctor++`gbrain doctor` reports `unlinked_facts`: the share of active facts with no+entity, the share among facts created in the last 7 days, the facts the model+already judged subjectless, and how many links write-time inference and relink+made. It warns when more than a quarter of the last week's facts are unlinked.diff --git a/docs/guides/system-one.md b/docs/guides/system-one.mdindex 48a629f8eb..5a822cf867 100644--- a/docs/guides/system-one.md+++ b/docs/guides/system-one.md@@ -257,6 +257,11 @@ TypeSafe key it is on by default and the key is its opt-in for fact textexplicitly, facts default to private, so on Jev it needs`decide.egress.private allow`, or route it to an `llm:` provider.+The sweep only compares facts that belong to an entity; a fact saved without+one is skipped as `no_entity`. When `gbrain decide status` shows a large+`no_entity` share, link those facts with `gbrain facts relink`+([guide](facts-relink.md)); linked facts are queued for the next sweep.+```bashgbrain decide sweep --slot conflict [--since <fact id>] [--source <id>] [--json] # run the sweep nowgbrain decide proposals list [--status pending|accepted|rejected|stale|undone|all] # both facts' text, locallydiff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.mdindex 95593d4599..db2a4c81b8 100644--- a/docs/operations/spend-controls.md+++ b/docs/operations/spend-controls.md@@ -23,7 +23,7 @@ gbrain config set spend.posture gated # default — gates enforce| Value | Effect ||-------|--------|| `gated` (default) | Every cost gate enforces its limit as documented below. |-| `tokenmax` | Every embedding-spend gate in the table below prints its estimate and **proceeds** — informational only. Spend is still recorded to the ledger; posture removes the *ceiling*, not the *accounting*. (Commands with their own LLM cost caps outside this doc's embedding scope — e.g. `extract-conversation-facts --max-cost-usd`, `dream retriage --max-usd` (an estimate-based soft stop) — don't resolve posture; their per-call flags govern.) |+| `tokenmax` | Every embedding-spend gate in the table below prints its estimate and **proceeds** — informational only. Spend is still recorded to the ledger; posture removes the *ceiling*, not the *accounting*. (Commands with their own LLM cost caps outside this doc's embedding scope — e.g. `extract-conversation-facts --max-cost-usd`, `dream retriage --max-usd` (an estimate-based soft stop), `facts relink --max-usd` (default $1.00; its free tiers and moved rows spend nothing) — don't resolve posture; their per-call flags govern.) |`spend.posture` is deliberately separate from `search.mode=tokenmax` (which governsretrieval payload size, not embedding spend). When a gate fires anddiff --git a/test/facts-relink.test.ts b/test/facts-relink.test.tsindex 64070f56db..7341a9e141 100644--- a/test/facts-relink.test.ts+++ b/test/facts-relink.test.ts@@ -277,3 +277,13 @@ describe('relink model tier', () => {expect(calls.length).toBe(0);});});++describe('relink reasons', () => {+ test('the guide reason table matches RELINK_REASONS exactly', async () => {+ const { readFileSync } = await import('node:fs');+ const { RELINK_REASONS } = await import('../src/core/facts/relink-reasons.ts');+ const guide = readFileSync(new URL('../docs/guides/facts-relink.md', import.meta.url), 'utf8');+ const rows = [...guide.matchAll(/^\| `(\w+)` \| (yes|no) \| (.+) \|$/gm)].map(m => [m[1], m[2] === 'yes', m[3]]);+ expect(rows).toEqual(Object.entries(RELINK_REASONS).map(([code, r]) => [code, r.memoized, r.fix]));+ });+});