Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
15.5 KB
Raw Blame

Key files: Core Persistence (engine graduation)

Subsystem index · Core Persistence. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG. Verified engine graduation, PGLite to Postgres (operator guide).

  • src/core/persistence/engine-graduation.types.ts — the shared contract every graduation module codes against: manifest, source-row and target-row states with their allowed transitions (assertTransition throws on an illegal one), inventory classes and loss kinds, target identity (host, port, database, user; never the password), batch and table receipts, plan, verify result, receipt, intent marker, tombstone, blockers, GRADUATION_ERROR_CODES, and the CLI-to-orchestrator surface (GraduationCommandOptions, GraduationStatusDoc, GraduationPathState, GraduationProgressSink, GraduationRollbackResult). Changes are additive.
  • src/core/persistence/graduation-inventory.ts — GRADUATION_INVENTORY: every public relation on either engine mapped to exactly one class (carry, rebind, rebuild, discard, schema-owned) with an engine-presence flag, a loss kind and the permitted column transforms. assertRelationSet refuses graduation_unclassified_table (reason newer_schema when the database is ahead of this binary, missing_inventory_row otherwise); copyOrder and fkClosure derive the FK topological order from pg_constraint at run time (self-FKs allowed, cycles throw). Test: test/graduation-inventory.test.ts fails when a migration adds a relation without a row.
  • src/core/persistence/graduation-digest.ts — canonical engine-independent digests: every value read as text under fixed session settings (TimeZone=UTC, DateStyle=ISO, extra_float_digits=3, hex bytea), primary-key keyset batches ordered COLLATE "C", sha256 computed client-side per batch and rolled into a per-table root independent of batch size; identifiers are always quoted from the catalog. Test: test/graduation-digest.test.ts.
  • src/core/persistence/graduation-verify.ts — verifyGraduation, the cutover gate: relation set, column contract, counts and digests (source side transformed by the inventory's transforms), sequence positions, an anti-join per FK, trigger state (gbrain_graduation_fence present until cutover), derived side tables, the target doctor, and replayProbe (resubmits a carried request through admitWriteInTransaction inside a rolled-back transaction; not_available with a reason when no caller input exists). Test: test/graduation-verify.test.ts.
  • src/core/persistence/graduation-errors.ts — one builder per graduation code (sourceWriterHeldError … engineGraduatedError) so the orchestrator, CLI, serve and doctor render each refusal one way: why, a filled fix with real argv (none only for report), a read-only verify (gbrain migrate --status --json, the --plan form, or doctor), GRADUATION_DOCS anchors, and the command helpers planArgv/runArgv/resumeArgv/rollbackArgv/statusArgv, which echo the user's --to spelling and name the URL only through --url-env. Test: test/graduation-errors.test.ts (table-driven over every code; each emitted argv names a real command with accepted flags and parses to its graduation mode).
  • src/core/persistence/graduation-serve-guard.ts — file reads only (marker, tombstone, config, manifest summary; never a lock attempt): serveGraduationStartRefusal (a serve launched while another live run owns the host brain exits 75 with graduation_in_progress, called from connectCliOnlyEngine in src/cli.ts), graduationStatusReason (a tombstoned path is status-only engine_graduated), exitOnEngineIdentityChange (status-only and degraded reconnect gates exit 75 for relaunch when the config names another engine, a tombstone appears or a run starts; a serve started with no config keeps recovering in place), graduationHandoffRequested (the resident stdio serve's 2 s marker poll in installStdioLifecycle), and readGraduationManifestSummary (the redacted view of the 0600 manifest). Test: test/graduation-serve-guard.serial.test.ts (includes a real gbrain serve child exiting 75 and engine status --json).
  • src/core/persistence/engine-graduation.ts — the orchestrator behind gbrain migrate --to postgres: planGraduation (zero mutations: probe-only source open, one read-only target session, refuses while a run is recorded non-terminal), runGraduation (needs yes plus expectPlanHash; a changed plan throws preview_changed), resumeGraduation, rollbackGraduation, reconcileGraduation and graduationStatus (files plus a read-only target-row read; split brain opens both datastores for counts). The kernel lock is held from step 1 to the routing flip: intent marker before the lock, autopilot pause marker, source open (waits up to 30 s for a resident serve's hand-off, else graduation_source_writer_held), in-process source doctor, route cross-check, drain and freeze, target fence, per-table copy with manifest checkpoints, deferred index build on the DDL route, verify (doctor child under GBRAIN_GRADUATION_RUN, plus GBRAIN_GRADUATION_SOURCE_PERSISTENCE naming the source's persistence_brain.enabled; #6331: persistenceEnabledForHealth in ownership.ts lets sync_freshness and ownedContentFreshness treat the fenced target as writer-owned only while its graduation row is this run's verifying target), then fence both and grant authority (source row cutover, lock-retaining close, move-aside, O_EXCL tombstone, one target transaction that sets persistence_brain.enabled and drops the fence) and flip routing (config, mounts). Every state change follows the transition tables and is mirrored into the 0600 manifest (<GBRAIN_HOME>/.gbrain/graduation-manifest.json, the only file holding target URLs) and the marker; each step announces its graduationBoundary. Resume continues from the recorded state with recorded identities; a resume after a lock gap recomputes source digests and re-drains and re-copies changed tables with their FK closure. Rollback before cutover abandons the target (fence kept); after cutover it requires the retained copy (checked before the fence and again under the kernel lock; gone refuses not_found via retainedCopyMissingError with nothing changed), fences first, takes the kernel lock, compares (graduation-losses.ts) and returns the target to authority on any refusal; rollback_approved onward only rolls forward. --resume --yes moves a stray datastore at the old path to <path>.stray-<run_id>. All refusals come from graduation-errors.ts. Tests: test/graduation-state.test.ts, test/graduation-rollback.test.ts, test/e2e/graduation-*.test.ts.
  • src/core/persistence/graduation-custody.ts — filesystem custody and the open-path checks: the sibling intent marker (atomic replace, 0600, fsync), the O_CREAT|O_EXCL tombstone at the old data dir path, inspectGraduationPath (none, in_progress, interrupted, graduated, split_brain; marker liveness from pid, boot id, pid namespace and process start time; a recorded boot id or pid namespace this process cannot read for itself is unknown, never a match), assertPgliteGraduationOpenable (called by PGLiteEngine before acquireLock, so a tombstone refuses engine_graduated and a live run graduation_in_progress without touching the path, and again after the lock, refusing graduation_interrupted past cutover), assertGraduationConnectAllowed (every CLI connect: a non-authoritative target or a cut-over source refuses unless the session is the run's; it reads the custody row in one statement through readGraduationConnectRow, where only an undefined table means no row) and assertGraduationAdmission (writer admission). moveAsideHeld renames under the already-held kernel lock as a sanctioned filesystem publication (a managed brain's datastore is a managed root). Tests: test/graduation-custody.test.ts, test/graduation-custody-probes.test.ts (probe mocked in a child via test/fixtures/graduation-liveness-probe.ts).
  • src/core/persistence/graduation-schema.ts + src/core/schema-migrations/v201-persistence-graduation.ts — the persistence_graduation singleton (each engine's own custody row; schema-owned, never copied) and gbrain_graduation_fence(). installGraduationFence puts a statement-level ENABLE ALWAYS trigger on every table that refuses writes unless gbrain.graduation_run equals the row's run id; dropGraduationFence, setTargetState/setSourceState (transition-table driven) and withGraduationRun.
  • src/core/persistence/graduation-losses.ts — rollback write detection: per carried table, the target digest against the verified receipt (persistence_brain.enabled through its transform), requests after the cutover sequence, and the security tables plus fact_withdrawals against the retained PGLite copy by identity and content (last_used_at ignored, expired OAuth tokens may disappear). Missing or changed security rows and new withdrawals are final.
  • src/commands/migrate-graduation.ts — the gbrain migrate graduation CLI, routed before connect from routeEngineFreeSubcommands in src/cli.ts when routesToGraduation holds (run-scoped verbs and --plan always; a bare --to postgres|supabase on a durable PGLite config unless migrate.graduation is false or the host is Windows). Without --yes --expect it plans and returns the confirmation_required payload (effects egress and destructive, what moves and what stays, plan_hash, the --plan preview; no stdin prompt); --plan/--dry-run prints the plan; the run reports the receipt, retained copy, target doctor, gbrain mcp expose and the MCP restart note. Exit codes 0/1/2/3, 11 for a progressing drain stop (1 when a blocker needs a person), 75 for graduation_in_progress, 130 after SIGINT (stops at the next batch boundary). --json prints one document; progress goes to stderr per table and batch. Test: test/migrate-graduation-cli.serial.test.ts.
  • src/commands/doctor/checks/engine-graduation.ts — graduationStateCheck, emitted from the filesystem lane of local-audits.ts: graduation_interrupted fails when a manifest or marker is non-terminal with no live owner (fix gbrain migrate --resume, rollback named) or a stray brain sits at the old path, is ok while a live run owns it, exempts the run named by GBRAIN_GRADUATION_RUN, and emits nothing on a brain that never graduated. The retained .graduated-* copy is reported by pglite_leftovers (src/core/pglite-leftovers-check.ts), silent while a manifest is non-terminal.
  • src/core/repair/missing-tables.ts — gbrain repair missing-tables (#6911), explicit-only and preview-bound (--apply --expect <hash>), brain-wide, DDL only. The preview lists the missing rebuildable caches readMissingTables reports (recreate), plus user_data_tables and other_tables residuals it never recreates; the hash covers the brain id, LATEST_VERSION and the tables. Apply refuses when the brain schema is newer than the client, leaves a table that already exists alone (already_present, no DDL), runs recreateStep in one transaction per table under the migration statement and lock timeouts (schemaLockBlockedError on a lock timeout), maps 42501 to schema_owner_required (approval kept) and 23505/42P07 races to already_present, and retires the approved set with the last item. Tests: test/purge-missing-cache-6911.test.ts, test/schema-missing-tables.test.ts.
  • src/core/repair/url-clone-fences.ts — gbrain repair url-clone-fences (#6946, GBRA-130 C-2): explicit-only, preview-bound, destructive consent; unmanaged brains only (a managed brain gets a warning naming sources mirror-readonly). The survey lists every tracked file of each owned clone in scope that differs from HEAD (trackedChanges) and proves per file (proveFenceRowsOnly) that HEAD's fence rows are an unchanged prefix of the working copy's and that re-rendering HEAD with the working fence matches byte for byte (fence_rows_only); anything else is listed as non_fence_edit / unparsed_fence / staged_change / deleted / not_in_head / unreadable_checkout and never touched; a file whose HEAD would not import (headHold, the import screen with holdNoncanonicalPrivate) is listed under the hold's code, and at apply its rows still go database-only and the file is restored (so the clone can pull) but HEAD is not imported; the import opts in too, and a held file reports held with the code instead of restored (#7897), with applied: true (its rows moved and its file was restored), and is an apply item, never also a residual (#7910). The preview hash binds the approved set (preview-approval, keyed by the command string). The apply, per file under the source filesystem lock and page lock, rechecks both sides (changed_since_preview), backs the file up under ~/.gbrain/backups/url-clone-fences/, clears row_num/source_markdown_slug on the appended rows in one maintenanceTransaction (inserting database-only any row the database lost), imports HEAD's bytes as the page through importFromContent, and only then restores the file from HEAD; each step is idempotent. Tests: test/pathological/c2-url-clone-fences.test.ts, test/url-clone-fences-private-hold-7897.test.ts.
  • src/core/schema-missing-tables.ts — #6911 expected-table check. readMissingTables: at head every graduation-inventory table for the engine, below head only the recreatable caches whose creating migration (CREATED_BY) already ran, skipped (client_behind) when the brain is newer; each missing table carries its inventory class and loss_kind. recreateStep (own-key lookup, rebuild class only) rebuilds query_cache (v055 DDL sized from the live facts.embedding shape, then the v056/v090/v091 statements) and code_traversal_cache (v059), then on Postgres enables RLS on the recreated table through v275's protectTables (a role that does not bypass RLS or own the table leaves it RLS-off and names it on stderr). test/schema-missing-tables.test.ts pins each recreated table's columns and indexes to the migrated brain's on both engines and checks that every inventory rebuild table is either in RECREATABLE_TABLES or defined by the base schema (so init --migrate-only recreates it). Doctor schema_missing_tables (src/commands/doctor/checks/schema-health.ts) renders it: warn for caches (repair preview fix) and tables without user data, fail for user_data tables.
  • src/commands/doctor/checks/schema-function-bodies.ts — schema_function_bodies (#7776, META, after schema_version): every function this binary's schema blob defines (SCHEMA_SQL or the PGLite template, parsed, never hand-listed; the writer-fence guards v197, v272 and v278 replace among them) must have its body installed, compared after whitespace and FTS-configuration normalization. Checked only at head (skipped with client_behind above it, migrations_pending below); a mismatch fails, names the functions and points at gbrain init --migrate-only after every gbrain on the database is upgraded. test/doctor-schema-function-bodies.test.ts pins that a fresh install matches.
  • src/core/persistence/rebuildable-cache.ts — #6911 purge-side skip: isRebuildableCache (inventory class rebuild), relationExists (to_regclass on the connection's search path), and clearRebuildableCache(tx, table), which returns the rows deleted or null when the cache table is absent; the existence check runs first because a 42P01 aborts a Postgres transaction. Callers: page purge (purge.missing_caches) and fact purge.