Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
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 (assertTransitionthrows 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.assertRelationSetrefusesgraduation_unclassified_table(reasonnewer_schemawhen the database is ahead of this binary,missing_inventory_rowotherwise);copyOrderandfkClosurederive the FK topological order frompg_constraintat run time (self-FKs allowed, cycles throw). Test:test/graduation-inventory.test.tsfails 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 orderedCOLLATE "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_fencepresent until cutover), derived side tables, the target doctor, andreplayProbe(resubmits a carried request throughadmitWriteInTransactioninside a rolled-back transaction;not_availablewith 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 filledfixwith real argv (none only forreport), a read-only verify (gbrain migrate --status --json, the--planform, or doctor),GRADUATION_DOCSanchors, and the command helpersplanArgv/runArgv/resumeArgv/rollbackArgv/statusArgv, which echo the user's--tospelling 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 withgraduation_in_progress, called fromconnectCliOnlyEngineinsrc/cli.ts),graduationStatusReason(a tombstoned path is status-onlyengine_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 ininstallStdioLifecycle), andreadGraduationManifestSummary(the redacted view of the 0600 manifest). Test:test/graduation-serve-guard.serial.test.ts(includes a realgbrain servechild exiting 75 andengine status --json).src/core/persistence/engine-graduation.ts— the orchestrator behindgbrain migrate --to postgres:planGraduation(zero mutations: probe-only source open, one read-only target session, refuses while a run is recorded non-terminal),runGraduation(needsyesplusexpectPlanHash; a changed plan throwspreview_changed),resumeGraduation,rollbackGraduation,reconcileGraduationandgraduationStatus(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, elsegraduation_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 underGBRAIN_GRADUATION_RUN, plusGBRAIN_GRADUATION_SOURCE_PERSISTENCEnaming the source'spersistence_brain.enabled; #6331:persistenceEnabledForHealthinownership.tsletssync_freshnessandownedContentFreshnesstreat the fenced target as writer-owned only while its graduation row is this run'sverifyingtarget), then fence both and grant authority (source rowcutover, lock-retaining close, move-aside,O_EXCLtombstone, one target transaction that setspersistence_brain.enabledand 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 itsgraduationBoundary. 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 refusesnot_foundviaretainedCopyMissingErrorwith nothing changed), fences first, takes the kernel lock, compares (graduation-losses.ts) and returns the target to authority on any refusal;rollback_approvedonward only rolls forward.--resume --yesmoves a stray datastore at the old path to<path>.stray-<run_id>. All refusals come fromgraduation-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), theO_CREAT|O_EXCLtombstone 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 isunknown, never a match),assertPgliteGraduationOpenable(called byPGLiteEnginebeforeacquireLock, so a tombstone refusesengine_graduatedand a live rungraduation_in_progresswithout touching the path, and again after the lock, refusinggraduation_interruptedpast 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 throughreadGraduationConnectRow, where only an undefined table means no row) andassertGraduationAdmission(writer admission).moveAsideHeldrenames 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 viatest/fixtures/graduation-liveness-probe.ts).src/core/persistence/graduation-schema.ts+src/core/schema-migrations/v201-persistence-graduation.ts— thepersistence_graduationsingleton (each engine's own custody row; schema-owned, never copied) andgbrain_graduation_fence().installGraduationFenceputs a statement-levelENABLE ALWAYStrigger on every table that refuses writes unlessgbrain.graduation_runequals the row's run id;dropGraduationFence,setTargetState/setSourceState(transition-table driven) andwithGraduationRun.src/core/persistence/graduation-losses.ts— rollback write detection: per carried table, the target digest against the verified receipt (persistence_brain.enabledthrough its transform), requests after the cutover sequence, and the security tables plusfact_withdrawalsagainst the retained PGLite copy by identity and content (last_used_atignored, expired OAuth tokens may disappear). Missing or changed security rows and new withdrawals are final.src/commands/migrate-graduation.ts— thegbrain migrategraduation CLI, routed before connect fromrouteEngineFreeSubcommandsinsrc/cli.tswhenroutesToGraduationholds (run-scoped verbs and--planalways; a bare--to postgres|supabaseon a durable PGLite config unlessmigrate.graduationis false or the host is Windows). Without--yes --expectit plans and returns theconfirmation_requiredpayload (effects egress and destructive, what moves and what stays,plan_hash, the--planpreview; no stdin prompt);--plan/--dry-runprints the plan; the run reports the receipt, retained copy, target doctor,gbrain mcp exposeand the MCP restart note. Exit codes 0/1/2/3, 11 for a progressing drain stop (1 when a blocker needs a person), 75 forgraduation_in_progress, 130 after SIGINT (stops at the next batch boundary).--jsonprints 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 oflocal-audits.ts:graduation_interruptedfails when a manifest or marker is non-terminal with no live owner (fixgbrain migrate --resume, rollback named) or a stray brain sits at the old path, isokwhile a live run owns it, exempts the run named byGBRAIN_GRADUATION_RUN, and emits nothing on a brain that never graduated. The retained.graduated-*copy is reported bypglite_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 cachesreadMissingTablesreports (recreate), plususer_data_tablesandother_tablesresiduals it never recreates; the hash covers the brain id,LATEST_VERSIONand the tables. Apply refuses when the brain schema is newer than the client, leaves a table that already exists alone (already_present, no DDL), runsrecreateStepin one transaction per table under the migration statement and lock timeouts (schemaLockBlockedErroron a lock timeout), maps 42501 toschema_owner_required(approval kept) and 23505/42P07 races toalready_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 namingsources 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 asnon_fence_edit/unparsed_fence/staged_change/deleted/not_in_head/unreadable_checkoutand never touched; a file whose HEAD would not import (headHold, the import screen withholdNoncanonicalPrivate) 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 reportsheldwith the code instead ofrestored(#7897), withapplied: 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/, clearsrow_num/source_markdown_slugon the appended rows in onemaintenanceTransaction(inserting database-only any row the database lost), imports HEAD's bytes as the page throughimportFromContent, 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 andloss_kind.recreateStep(own-key lookup, rebuild class only) rebuildsquery_cache(v055 DDL sized from the livefacts.embeddingshape, then the v056/v090/v091 statements) andcode_traversal_cache(v059), then on Postgres enables RLS on the recreated table through v275'sprotectTables(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.tspins each recreated table's columns and indexes to the migrated brain's on both engines and checks that every inventory rebuild table is either inRECREATABLE_TABLESor defined by the base schema (soinit --migrate-onlyrecreates it). Doctorschema_missing_tables(src/commands/doctor/checks/schema-health.ts) renders it: warn for caches (repair preview fix) and tables without user data, fail foruser_datatables.src/commands/doctor/checks/schema-function-bodies.ts—schema_function_bodies(#7776, META, afterschema_version): every function this binary's schema blob defines (SCHEMA_SQLor 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 (skippedwithclient_behindabove it,migrations_pendingbelow); a mismatch fails, names the functions and points atgbrain init --migrate-onlyafter every gbrain on the database is upgraded.test/doctor-schema-function-bodies.test.tspins that a fresh install matches.src/core/persistence/rebuildable-cache.ts— #6911 purge-side skip:isRebuildableCache(inventory classrebuild),relationExists(to_regclasson the connection's search path), andclearRebuildableCache(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.