Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
9.6 KB
Raw Blame

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_epoch is migration-only. Edit here, then bun 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 as S:<incarnation>:<slug>. Append, replay, lookup and state_hash share 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_id is 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_xact counters; a full read with track_counts off). The process-local fingerprint cache maps claim-text SHA-256 to gbrain_fact_fingerprint only (no text, bounded); __fingerprintCacheForTests and __suppressBeliefTouchedSignalForTests are the test seams.
  • src/core/belief/ledger.ts — the finalization contract. withBeliefBatch reads the state of the held page keys before and after the transaction's projections and appends the canonical diff (origin live on a managed brain, unmanaged otherwise, or the caller's override). beliefBatchCovers and insideBeliefBatch let a nested writer skip its own batch. Managed mode comes from readManagedMode, never a direct persistence_brain read. publicationBeliefOptions sets ownerEdit (the only input to the redaction release) for a local OWNER_EDIT_OPERATIONS publication with no intent kind; append_page is 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 attributed cause.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 deterministic event_keys. markBeliefCommits writes the post-commit observation (observed_at >= recorded_at); __setBeliefEmitterFaultForTests is the forced-probe seam.
  • src/core/belief/coverage.ts — enableBeliefLedger (coverage.started, a resumable per-page baseline, coverage.complete whose recorded_at is the watermark; certified only on a managed brain) and disableBeliefLedger (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 no complete, 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 than coverage.restored, so a restore never restarts a stopped ledger.
  • src/core/belief/coverage-report.ts — readers: coverageIntervals (restore marks carry purge-mirror's archived_at, purge_replay, replays), coverageAt (refuses coverage_from before the slug's cut, found under the slug or its page lifetime, and coverage_gap in 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 in truncated_walks), beliefEventVisibility (an unmarked publication is unproven until 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 current state_hash with its newest non-backfill event; reconcileBeliefDrift appends reconcile events (the slug interval stays uncertified). orphanLifetimes and unmarkedPublications/fillCommitMarks read a recent window unless deep; cycleBeliefReconcile for the extract phase.
  • src/core/belief/projection-point.ts — unmanagedBeliefPoint (and withUnmanagedBeliefs for one transaction): the legacy import, extract_facts fence 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 an unmanaged batch, then mark the commit. Every other unmanaged writer is found by drift.
  • src/core/belief/backfill.ts — backfillBeliefHistory: marked history from page_versions only (git is not read), origin backfill, historical time in source_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): readPageAtTime replays a slug's page events of every lifetime into validity intervals under the section 5.3 visibility rule (a straddling write refuses known_as_of_unproven), refuses coverage_from / coverage_gap from coverageAt, 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. remoteMayRead applies 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 its revision_before. missingPreimages is the in-batch check finalizeBeliefEvents runs under NODE_ENV=test (off with GBRAIN_BELIEF_PREIMAGE_CHECK=0); preimageGaps is doctor's production scan (large and segmented pages exempt).
  • src/core/belief/changes.ts — W4 weekly change diff (BELIEF_LEDGER.md section 15): beliefChanges reads the window through readBeliefHistory (recordedAfter/recordedUntil, then subjectKeys up to since for each subject's value before), nets each subject end to end, reads a subject with no earlier event from the page body at since (before_known: false when no body answers), lists a page created in the window with its creation body's fence rows, flags a dream-inferred link end upper_bound, and skips backfill and baseline events. Remote callers get world fence rows only where remoteMayRead passes. Served by delta {beliefs: true} and gbrain beliefs changes.
  • src/core/ops/known-as-of.ts — the op surface: get_page {known_as_of} and get_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. parseKnownAsOf refuses a bare date clock_mismatch. A recorded-time read returns the whole page: arguments that shape a current read (window selectors, section, grep, context, include_content, view and the like; GST-2214, GPT-6.1 Sol fills them all) are ignored and named in the response's set_aside {ignored, note}. body: outline or window still refuses invalid_params, with a read fix that keeps only what a recorded-time read takes.
  • src/core/engine-sql/pages.ts updateSlug — 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 is invalid_params. Only changes routes on a thin client: thin-client-routing.ts calls the host's delta {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 — doctor belief_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). --fix reconciles and fills marks; a brain without coverage is information with an ask_user enable.
  • Retention purge (BELIEF_LEDGER.md 6.5): on a managed brain purge-deleted.ts passes the internal retention: true (purge-params.ts accepts it only from a local caller with purge: true): it writes no content tombstone, redacts no history, appends no purge-mirror line and records page.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 appends page.expired; the bulk delete takes the rest, never a recorded tombstone whose expiry failed or is parked.