Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Key files: belief ledger
Subsystem index. Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
Design: BELIEF_LEDGER.md. Operator surface: gbrain beliefs, doctor belief_ledger_coverage.
src/core/belief/schema.ts— the ledger DDL (belief_events,belief_page_lifetimes,belief_commit_marks,belief_redactions,belief_retier_manifest) shared by migration v249 and both schema blobs;sources.purge_epochis migration-only. Edit here, thenbun run build:schema.src/core/belief/keys.ts— subject keys and hashes. A key never holds a row id: page slugs serialize as the lifetime (L:<uuid>), a slug with no page asS:<incarnation>:<slug>. Append, replay, lookup andstate_hashshare this one serialization.src/core/belief/lifetimes.ts— page lifetimes, the ledger's page identity: minted at first need, kept across a rename, ended by a hard delete or a recreate;page_idis a hint only.src/core/belief/state.ts/subjects.ts— raw stream state (a page, its fence and DB-only facts, takes, and links whose origin, else from, page it is) and its keyed subjects; row ids are payload, never keys. The post read reuses the pre read's rows for tables the transaction did not write (pg_stat_xactcounters; a full read withtrack_countsoff). The process-local fingerprint cache maps claim-text SHA-256 togbrain_fact_fingerprintonly (no text, bounded);__fingerprintCacheForTestsand__suppressBeliefTouchedSignalForTestsare the test seams.src/core/belief/ledger.ts— the finalization contract.withBeliefBatchreads the state of the held page keys before and after the transaction's projections and appends the canonical diff (originliveon a managed brain,unmanagedotherwise, or the caller's override).beliefBatchCoversandinsideBeliefBatchlet a nested writer skip its own batch. Managed mode comes fromreadManagedMode, never a directpersistence_brainread.publicationBeliefOptionssetsownerEdit(the only input to the redaction release) for a localOWNER_EDIT_OPERATIONSpublication with no intentkind;append_pageis deliberately not in the list (#7123): an append cannot set a fact or take field, so as an owner edit it could only release a redaction on a field its publication re-derives, and its events are attributedcause.op: 'append_page'regardless (test/belief-ledger-append-owner.test.ts).src/core/belief/append.ts— the one insert (appendBeliefEvents): tombstones and the redaction register first, then deterministicevent_keys.markBeliefCommitswrites the post-commit observation (observed_at >= recorded_at);__setBeliefEmitterFaultForTestsis the forced-probe seam.src/core/belief/coverage.ts—enableBeliefLedger(coverage.started, a resumable per-page baseline,coverage.completewhose recorded_at is the watermark; certified only on a managed brain) anddisableBeliefLedger(coverage.stopped). Start, complete and stop are decided under the source row FOR UPDATE: a second enable resumes the open run, a disable mid-walk ends it with nocomplete, and the completion re-checks the pending set (a page renamed behind the cursor). A slug no page key can name is skipped and listed (unkeyable_slugs). The coverage state is the newest event other thancoverage.restored, so a restore never restarts a stopped ledger.src/core/belief/coverage-report.ts— readers:coverageIntervals(restore marks carry purge-mirror'sarchived_at,purge_replay,replays),coverageAt(refusescoverage_frombefore the slug's cut, found under the slug or its page lifetime, andcoverage_gapin a stopped span or a restore gap; an interval holding a purge whose derivation walk was truncated is not certified,uncertified_reason: 'truncated_walk', its requests intruncated_walks),beliefEventVisibility(an unmarked publication isunprovenuntil a commit mark or a later event of the page proves it). Drift:scanBeliefDrift(sampled, or deep; read-only, it mints no lifetime) compares each slug's currentstate_hashwith its newest non-backfill event;reconcileBeliefDriftappendsreconcileevents (the slug interval stays uncertified).orphanLifetimesandunmarkedPublications/fillCommitMarksread a recent window unlessdeep;cycleBeliefReconcilefor the extract phase.src/core/belief/projection-point.ts—unmanagedBeliefPoint(andwithUnmanagedBeliefsfor one transaction): the legacy import,extract_factsfence reconcile, takes reextract and the derived link writers (derived-links.ts, the remote auto-links effect, attendance repair) lock their sorted page keys and run in anunmanagedbatch, then mark the commit. Every other unmanaged writer is found by drift.src/core/belief/backfill.ts—backfillBeliefHistory: marked history frompage_versionsonly (git is not read), originbackfill, historical time insource_time, recorded_at the run time; a purge during the run retries (belief_stale_preparation), and the summary event says whether pruned versions left it incomplete. A version whose own frontmatter is private (or a pinned question) publishes private events; a carrying field a purge registered from a retained version (registerVersionCarriers) is appended as the marker.src/core/belief/history.ts— the one history reader (readBeliefHistory); remote callers see only events that were world-visible when recorded on a page visible now, failing closed; a quarantined page's fact and take events are hidden from them too (#6259).src/core/belief/page-at-time.ts— W2 page-at-time (BELIEF_LEDGER.md section 10):readPageAtTimereplays a slug's page events of every lifetime into validity intervals under the section 5.3 visibility rule (a straddling write refusesknown_as_of_unproven), refusescoverage_from/coverage_gapfromcoverageAt, and pairs each closed interval with the preimage version the next transition wrote (by revision, in order); the open head reads the live page. A body no version holds is disclosed (body_reason), never borrowed. Purge-redacted events carry no revision, so a purged lifetime splits only on slug and deleted state.remoteMayReadapplies history.ts's remote rule per interval.src/core/belief/preimages.ts— the preimage invariant (BELIEF_LEDGER.md section 14 item 8): a revision-moving publication leaves a version of itsrevision_before.missingPreimagesis the in-batch checkfinalizeBeliefEventsruns underNODE_ENV=test(off withGBRAIN_BELIEF_PREIMAGE_CHECK=0);preimageGapsis doctor's production scan (large and segmented pages exempt).src/core/belief/changes.ts— W4 weekly change diff (BELIEF_LEDGER.md section 15):beliefChangesreads the window throughreadBeliefHistory(recordedAfter/recordedUntil, thensubjectKeysup tosincefor each subject's value before), nets each subject end to end, reads a subject with no earlier event from the page body atsince(before_known: falsewhen no body answers), lists a page created in the window with its creation body's fence rows, flags adream-inferred link endupper_bound, and skips backfill and baseline events. Remote callers get world fence rows only whereremoteMayReadpasses. Served bydelta {beliefs: true}andgbrain beliefs changes.src/core/ops/known-as-of.ts— the op surface:get_page {known_as_of}andget_versions {known_as_of, diff, source_id}(full surface only). One target source (explicit, ambient, or the only granted source whose ledger names the slug); remote callers get only readable intervals of a page visible now at their trust floor, with sanitized bodies.parseKnownAsOfrefuses a bare dateclock_mismatch. A recorded-time read returns the whole page: arguments that shape a current read (window selectors,section,grep,context,include_content,viewand the like; GST-2214, GPT-6.1 Sol fills them all) are ignored and named in the response'sset_aside {ignored, note}.body: outlineorwindowstill refusesinvalid_params, with a readfixthat keeps only what a recorded-time read takes.src/core/engine-sql/pages.tsupdateSlug— versions the page before the move (the move advances the revision), so page-at-time has the body from before a rename.src/commands/beliefs.ts—gbrain beliefs enable|disable|status|changes|reconcile|backfill|replay-purges(--json); an unknown source isinvalid_params. Onlychangesroutes on a thin client:thin-client-routing.tscalls the host'sdelta {beliefs: true}(so it lists the remote world view) and refuses--source; every other subcommand is host-only.src/commands/doctor/checks/belief-ledger.ts— doctorbelief_ledger_coverage: intervals and certification, baseline progress, drift (sampled; complete under--tier deep), orphan lifetimes, unmarked publications, and a restore whose purge replay was partial, unavailable or unverified (ask_user).--fixreconciles and fills marks; a brain without coverage is information with anask_userenable.- Retention purge (BELIEF_LEDGER.md 6.5): on a managed brain
purge-deleted.tspasses the internalretention: true(purge-params.tsaccepts it only from a local caller withpurge: true): it writes no content tombstone, redacts no history, appends no purge-mirror line and recordspage.expired. On an unmanaged brain each expired tombstone of a source with belief coverage is first deleted under its page key in a belief batch that appendspage.expired; the bulk delete takes the rest, never a recorded tombstone whose expiry failed or is parked.