Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(key-files): keep the merged key-files docs under the 60 KB cap

garrytane643c19debc2
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index da011b6b3b..54c417796a 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -41,4 +41,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/purge-parks.ts` — `purge_parked_pages` (#6741 C): names parked purges with their last error (only this version's parks, `isParked`); fix `gbrain pages purge-deleted --retry-parked --yes` (preview `--dry-run --json`), consent destructive, ask_user.
-- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set, conversation rows excluded), the conversation extractor's unlinked derived rows (`cli:extract-conversation-facts*`, #6764: count, origin `conversation`, and `details.conversation` naming the source with the most and its pages, most rows first, up to `CONVERSATION_FIX_SLUGS` = 50), origins and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` and conversation rows memoized `conversation_unresolved` excluded (`new_7d.conversation_unresolved`); the fix is `gbrain facts relink --dry-run`; when conversation rows are unlinked the envelope `fix` (`details.conversation.fix`) is, for rows the free conversation relink has not tried, `gbrain facts relink --conversation --source <id> --slugs <csv>` (preview `--dry-run`, consent none, actor agent, host operator remotely; test `test/conversation-relink-6764.test.ts`) and, once only rows it memoized `conversation_unresolved` remain (a memo that a page created later re-arms unless the reason is memoized, `core/facts/conversation-memo.ts`), a bounded re-extraction of those pages not yet re-extracted on their current content (`gbrain extract-conversation-facts --source-id <id> --slugs <csv> --force --max-cost-usd <N>`, input `N` the approved USD, preview `--dry-run`, consent paid + egress, ask_user; test `test/conversation-facts-unlinked-6764.test.ts`), both verified by `gbrain doctor --only unlinked_facts --json`, because plain relink never examines derived rows; the remote report asks the brain host operator to run it. When only rows on pages already re-extracted on their current content remain, `details.conversation.fix` is `manual`: no envelope `fix`, and the message names linking by hand with `--entity` (test `test/conversation-memo-6764.test.ts`). Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Assistant and third-party facts are not counted (`ENTITY_LINKABLE_SQL`, #7270). Tests: `test/doctor-unlinked-facts.test.ts`, `test/relink-attribution-7270.test.ts`.
+- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set, conversation rows excluded), the conversation extractor's unlinked derived rows (`cli:extract-conversation-facts*`, #6764: count, origin `conversation`, and `details.conversation` naming the source with the most and its pages, most rows first, up to `CONVERSATION_FIX_SLUGS` = 50), origins and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` and conversation rows memoized `conversation_unresolved` excluded (`new_7d.conversation_unresolved`); the fix is `gbrain facts relink --dry-run`; when conversation rows are unlinked the envelope `fix` (`details.conversation.fix`) is, for rows the free conversation relink has not tried, `gbrain facts relink --conversation --source <id> --slugs <csv>` (preview `--dry-run`, consent none, actor agent, host operator remotely; test `test/conversation-relink-6764.test.ts`) and, once only rows it memoized `conversation_unresolved` remain (a memo that a page created later re-arms unless the reason is memoized, `core/facts/conversation-memo.ts`), a bounded re-extraction of those pages not yet re-extracted on their current content (`gbrain extract-conversation-facts --source-id <id> --slugs <csv> --force --max-cost-usd <N>`, input `N` the approved USD, preview `--dry-run`, consent paid + egress, ask_user; test `test/conversation-facts-unlinked-6764.test.ts`), both verified by `gbrain doctor --only unlinked_facts --json`, because plain relink never examines derived rows; the remote report asks the brain host operator to run it. When only rows on pages already re-extracted on their current content remain, `details.conversation.fix` is `manual`: no envelope `fix`, and the message names linking by hand with `--entity` (test `test/conversation-memo-6764.test.ts`). Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Non-user facts are skipped (#7270). Tests: `test/doctor-unlinked-facts.test.ts`, `test/relink-attribution-7270.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index b497579359..8a103b9843 100644
--- a/docs/architecture/key-files/core-persistence-facts.md
+++ b/docs/architecture/key-files/core-persistence-facts.md
@@ -13,3 +13,5 @@ Managed facts extraction: the entity-intent preparer and publisher, conversation
- `src/core/facts/conversation-relink.ts` — `gbrain facts relink --conversation [--source] [--slugs] [--dry-run] [--json]` (#6764, dispatched from `src/commands/facts.ts`): the free relink of the conversation extractor's unlinked derived rows, which plain relink never examines. Pages are the named `--slugs`, else the 50 with the most unlinked rows not yet tried (`conversationRelinkPages`). Each row runs `inferConversationSubject` (write mode, visibility-filtered, withdrawn claims skipped; no model); a row the assistant or a third party said is never linked, never picks a page, and is counted as `not_user_attributed` (#7270). A page's links are one write: a managed brain publishes one database-only `managed_maintenance_conversation_relink` request on the anchor `.maintenance/conversation-relink` holding the page key (`prepareConversationRelink`, dispatched in `persistence/prepared-maintenance.ts`; the request id comes from the planned links, and a failed attempt retries under the next id), an unmanaged brain one `writeDerivedFacts` transaction. The write sets `entity_slug` and appends `entity relinked from <tier>` only on rows still exactly as planned (same claim, unlinked, active, target page live) and records a `linked` attempt; unresolved rows get a `conversation_unresolved` memo in `fact_relink_attempts` (reason the miss), which moves doctor `unlinked_facts` to the paid re-extraction fallback, and the report prints that command for their pages. Test: `test/conversation-relink-6764.test.ts`.
- `src/core/facts/conversation-memo.ts` — #6764 what makes free relink, then paid re-extraction, then linking by hand converge, all in `fact_relink_attempts`: `conversationTriedSql` (a `conversation_unresolved` memo, re-armed for the free relink by any page created in the source after it unless `RELINK_REASONS` memoizes the reason), `conversationPaidSql` and `recordReextractMemo` (tier `paid_reextract`, `target_slug` the page, `reason` its `content_hash`, keyed on the page's completion outcome row; written when an extraction of the page completes, unmanaged in `extract-conversation-facts.ts` and managed in `conversation-publication.ts` `applyEntry`). No schema change. Test: `test/conversation-memo-6764.test.ts`.
- `src/core/facts/conversation-relink-carry.ts` — #6764 how a free conversation relink survives a batch replacement: `clearConversationFacts` (conversation-publication.ts) expires the page's relinked rows (`RELINKED_DERIVED_ROW`: entity set and `entity relinked from` in the context) instead of deleting them, after deleting the previous clear's expired copies, and `inheritRelinkedEntities` gives each inserted row with no entity whose claim matches one of them that entity (live page only) and the relink note, in every insert `publishConversationFacts` makes (managed and unmanaged, replacement or addition) and in `insertGatedFacts`. One active copy, link kept. Test: `test/conversation-relink-6764.test.ts`.
+
+- `src/core/repair/duplicate-facts.ts` — `gbrain repair duplicate-facts` (#7043), explicit-only and preview-bound (consent `destructive`). `findDuplicateFacts` (read-only) groups active facts by source, visibility, `attributed_to` and `gbrain_fact_fingerprint(fact)`, keeps the oldest row (created_at, id) and classes each group `same_entity` or `cross_entity` (retired only with `--include-cross-entity`). The apply sets `expired_at` and `superseded_by` on database-only copies (`coordinatedDatabaseWrite` with the `relink_facts` operation on a managed brain, one `maintenanceTransaction` per group otherwise) and strikes a fenced copy as `superseded by #N` through a revision-bound `put_page` when the kept row shares its fence; a copy whose kept row is elsewhere is listed as `fence_kept_elsewhere`, one on a segmented page as `segmented_page` (preview and apply). Near duplicates are never touched; a row changed since the preview reports `changed_since_preview`. Tests: `test/repair-duplicate-facts-7043.test.ts` (PGLite and Postgres).
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index ec2cddf784..2b81eaa96a 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -12,7 +12,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/conversation-labels.ts` — `gbrain repair conversation-labels`, explicit-only, preview-bound and destructive (consent payload from the registry's `consentText`). `classifyLabelFacts` (read-only) takes active per-segment extractor facts (`source` exactly `cli:extract-conversation-facts`) on live pages with a bold `METADATA_LABELS` line and classes each `excluded` (page outcome stamped with `extractor_version`, withdrawn, superseded, named by another fact's `superseded_by`, referenced by `open_loops.fact_id`), `evidenced` (context carries `segment 1970-01-01`) or `ambiguous`. The preview decides each page's outcome with the current parser at no cost (`non_extractable`, `awaiting_reextraction`, `cleaned`), hashes it all, saves one approved item per page and prints the capped hand-off (`extract-conversation-facts --slugs … --dry-run`, then `--max-cost-usd`). The apply expires the approved ids still as previewed (appending `retired: conversation-labels <hash>` to the context), expires the completion marker and writes the stamped not-extractable outcome for a page still at the previewed parser input; approved pages apply in batches of `LABEL_BATCH_PAGES` (25): one database-only `managed_maintenance_conversation_label_retire` request per batch on `LABELS_ANCHOR_SLUG` on a managed brain (`prepareConversationLabelRetirement`, every page key locked, each page rechecked), one transaction per batch otherwise. No model calls. Segmented pages are not classified (the label filter reads the body columns): their unstamped per-segment facts are counted as `segmented_pages` / `segmented_facts` and named in a warning. `countLabelFacts` is doctor `conversation_label_facts`' bounded count. Pinned by `test/repair-conversation-labels.test.ts` (+ Postgres arm) and `test/conversation-facts-retained-history.test.ts`.
- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).
- `src/core/repair/redacted-facts.ts` — `gbrain repair redacted-facts` (#7125), explicit-only and preview-bound. `classifyRedactedFacts` (read-only) takes active facts whose text holds a redaction marker and runs `restoreNeutralized` (`think/sanitize.ts`, with the pre-fix `LEGACY_EVAL_SHELL` shape) against the page the fact's context names and the page holding it (`pageTexts`: an inline page's body + timeline, a segmented page's body through `readBodyRange` up to 16 MiB, then up to 50 `page_versions` bodies): `evidenced` when every proving text proves the same restoration, `ambiguous` (`conflicting_sources`) when a text holds two spans around the words or texts disagree, `unproven` (`no_source_page` / `not_in_source`) otherwise. A proved fenced row on a segmented page is `segmented` (`segmented_page`): listed with its restoration, never rewritten (`restoreFencedRows` reads and publishes inline bodies only). The preview hashes every candidate with its restoration and saves one approved item per page; the apply reclassifies each fact, rewrites database-only rows through one database-only `managed_maintenance_restore_redacted_facts` request per page on a managed brain (`prepareRedactedFactsRestore`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain (exact-text compare-and-set; context gets `restored: redacted-facts repair`), and rewrites fenced rows' claims in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection replaces the row. Pinned by `test/repair-redacted-facts.test.ts` (+ Postgres arm).
-- `src/core/repair/duplicate-facts.ts` — `gbrain repair duplicate-facts` (#7043), explicit-only and preview-bound (consent `destructive`). `findDuplicateFacts` (read-only) groups active facts by source, visibility, `attributed_to` and `gbrain_fact_fingerprint(fact)`, keeps the oldest row (created_at, id) and classes each group `same_entity` or `cross_entity` (retired only with `--include-cross-entity`). The apply sets `expired_at` and `superseded_by` on database-only copies (`coordinatedDatabaseWrite` with the `relink_facts` operation on a managed brain, one `maintenanceTransaction` per group otherwise) and strikes a fenced copy as `superseded by #N` through a revision-bound `put_page` when the kept row shares its fence; a copy whose kept row is elsewhere is listed as `fence_kept_elsewhere`, one on a segmented page as `segmented_page` (preview and apply). Near duplicates are never touched; a row changed since the preview reports `changed_since_preview`. Tests: `test/repair-duplicate-facts-7043.test.ts` (PGLite and Postgres).
- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.
- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id, and `file_database_drift` (W4.11) when its last replay attempt was refused `source_changed` and the page has not been written since (`lastFailedAttempt`; the detail and an apply's `file_database_drift` outcome name `gbrain sources reconcile <source> <slug> --preview`; `test/repair-failed-writes-drift-w411.test.ts`); owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969). The superseded / already-written / duplicate rule lives in `persistence/terminal-classify.ts`, shared with the #6650 terminal-failure readers.
- `src/core/repair/ontology-facts.ts` — `gbrain repair ontology-facts` (#6264), explicit-only and preview-bound (`--apply --expect <hash>`). `classifyOntologyFacts` (read-only; also doctor `ontology_facts_fenced`) takes ontology rows (`dimension IS NOT NULL`) carrying the pre-fix fence step's signature, a `row_num` or a `source_markdown_slug` that differs from `source` (`mergeOntologyFact` writes them equal and never sets `row_num`), and classes each `fenced` or `retired`, or excluded as `withdrawn` (`fact_withdrawals`), `consolidated` or `duplicate` (restoring would collide with the ontology dedup key). The apply sets `row_num` NULL, `source_markdown_slug = source` and `expired_at` NULL in one statement that rechecks row number, page, expiry and the dedup key (`changed_since_preview` otherwise), through `coordinatedDatabaseWrite('ontology_propose')` on the entity and page keys on a managed brain or one maintenance transaction otherwise; the withdrawal trigger re-expires a claim forgotten after the preview (`withdrawn`). Page text is never rewritten. Tests: `test/ontology-fence-sweep.test.ts`.