Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Workspace push and backup coverage (key files cluster)
The no-daemon workspace push (gbrain sources push and the hook backstops)
and the backup coverage verdicts that read its status records. Operator
guide: backup check.
Key files:
src/core/backup/coverage.ts+src/core/backup/repository.ts— local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. An ordinary (non-forced)getBackupStatusre-probes before the one-hour sweep clock expires when the cached verdict still has pending repository evidence (a configured remote leftbudget_exhausted, relabelledstale, orverifiedolder than the evidence window), at most once perBACKUP_CONTINUATION_THROTTLE_MS(60 s); real failures (unavailable,mismatch,missing_ref) are not retried per check (#6614, #6687;test/backup-pending-continuation.serial.test.ts). A reused cached verdict whose page+fact count still says the brain is too young to coach re-reads that count (brainMaturity), so a verdict cached on an empty brain at init never reports 0 on a full one (GBRA-585). Doctor's fix for anot_a_git_reposource is the engine's full backup,gbrain backup createon PGLite orpostgresDumpFix()(pg_dump,src/core/backup/preflight.ts) on Postgres, nevergbrain export;gbrain backup createon a Postgres brain refuses with that same fix (storage_error, legacy reasonpglite_required).budgetAllowsProbestarts a probe only with its full two-second slot inside the deadline (a sub-slot leftover defers the root asbudget_exhaustedand the sweep keeps that root's first-passverifiedevidence); anunavailableverification carriescause: 'timeout' | 'exit'(#6499). #6907: the slot isresolveBackupRemoteTimeoutMs(envGBRAIN_BACKUP_REMOTE_TIMEOUT_MS> DBbackup.remote_timeout_ms> 2 s, clamped 500-30000 ms; the budget ismax(8 s, 4 slots)), a timed-out probe isisRemoteTimeout(counted intotals.remote_timeouts, reason "remote check timed out"), andworktreeDirtystreamsgit status --porcelainand stops at the first non-metadata line (test/pathological/s-6907-backup-check-bounds.test.ts). Both git calls run withbackupGitEnv(), an allowlist (HOME,PATH,XDG_CONFIG_HOME,SSH_AUTH_SOCK,GIT_CONFIG_GLOBAL, proxy variables, and Windows profile variables) under the no-prompt overrides, so user Git config and credential helpers apply butGIT_DIR/GIT_WORK_TREEnever do (#5794).currentBackupEvidenceretains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match.recoverable_reposcounts clean matching remote HEADs, whileconfigured_reposcounts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor and the advisor's remote collector use the aggregate cache only, read throughcurrentBackupEvidence. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. API connector sources are not repositories: aconnector_databasesource (managed, unbound) and an unmanaged connector whose directory is not a Git repo each become aconnectorinfo asset with thegbrain sync --source <id> --fullfix (notgbrain export: the connector sync rebuilds pages from the provider and never reads a Markdown dump, so an export is an archive, not a restore path), while a bound connector keeps the repository verdict. The doctorbackup_coveragemessage and the advisor collector list each asset that keeps the verdict in warn with its reason (blockingAssetReasonsin status-file.ts:no git remote,remote configured, nothing pushed,dirty, a fixedunknowncode, unverified remote) locally, and reason counts only on the remote surface; a warn with no blocking asset leads with the stale or degraded cause.gbrain backup statusnames a fix for dirty and unverified rows too. Tests:test/backup-verification.serial.test.ts,test/backup-git-env.test.ts,test/backup-coverage.serial.test.ts,test/doctor-backup-coverage.serial.test.ts,test/e2e/backup-coverage-parity.test.ts. #6083:assessBackupRepositorydrops physical-root metadata (withoutPhysicalRootMetadata) from both porcelain probes, classifies a root with no origin remote asno_remoteeven after a recorded push failure, and gives a managed canonical worktree (managedFilesystemRootFor) the read-onlygbrain sources writer status [<source>] --probe --jsonfix instead of the refusedsources push(backup-coverage.tsexplains that fix with the retry-effects step).src/core/workspace-push.ts—gbrain sources push: deny-glob backstop (tracked*.pglite/.env*, and since #5186 the ownership markers.gbrain-owner.json/.gbrain-owner-*.json/.gbrain-owner.json.*.tmpplus.gbrain-bootstrap.lock/**, refused regardless of .gitignore state; untracked matches are excluded from the commit and named inexcludedUntracked) → stage FIRST → secret-scan the STAGED index blobs viagit cat-file(closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS) keyed on the repo's realpath, so a symlinked spelling and git's physical toplevel share it (an absent path hashes its raw string). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (>PUSH_STREAM_SCAN_MAX_BYTES, 512 MiB), or otherwise unscannable staged blob returnsblocked_unscannable(nothing committed) instead of sailing through. A blob up toPUSH_MAX_SCAN_BYTES(25 MiB) is read whole and scanned byscanTextas before; a larger one is found by its index size (onels-files -splus onecat-file --batch-check,stagedBlobSizes), streamed by oid throughgit cat-file blobintoscanTextStream(secret-scan-stream.ts) and fails closed when git errors, runs past 10 minutes or delivers a byte count other than the recorded size (test/workspace-push-large-blob.serial.test.ts: a clean 30 MiB file pushes, secrets across window seams block once each with their line, the ceiling still blocks) — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes insrc/commands/sources.ts:pushed/skipped_in_flight→ 0;blocked_secrets/blocked_tracked_deny/blocked_unscannable/refused_visibility→ 5;pull_conflict/push_failed/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes<home>/bootstrap/push-status.json. Parent-repo-aware (a source may be a subdirectory of the workspace repo). Ablocked_secretsresult carriesPushSecretFinding[]: each finding addsfile,since, the absoluteallowlistPathof the root.gbrain-scan-allow, a shell-quotedallowCommand(printfappend, runnable from any cwd),retryCommand(gbrain sources push --path <abs>plus the run's--branch/--allow-unverified-remote),docs(SECRET_SCAN_REFUSAL_DOCS, thewrite-refusals.md#secret-scan-refusals-and-redactionanchor; keep that heading) and, when the scanner'slegacyFingerprintmatches an allowlist entry,staleAllowlistEntry { entry, replacement }.formatBlockedSecretsrenders the CLI text from the same objects, so human and--jsonoutput carry the same commands, and no field holds a value.blockedSecretsReasonkeepsreasona one-line summary (count, first location, pattern) within the 140 charssanitizePushReasonpasses.bootstrap/verify.tsandbootstrap/repo.tsrefusals reuse the docs anchor and print fingerprint,sinceand the absolute allowlist path.pushStatusForWorkspace(entries, ws)picks the record whoserepoRootresolves tows(a single legacy record withoutrepoRootis attributed to it);bootstrap statussupport.last_pushand doctorbootstrap_push_health's dirty-tree FAIL use only that record (test/doctor-not-verified-5432.test.ts). Tests:test/workspace-push-guidance.test.ts,test/sources-push-cli.serial.test.ts. #6083: the managed-guard refusal record carriescode: writer_coordinator_required(PushStatusEntry.code); the hook push call sites (dirtyTreePush,stopPushIfDue, SessionEnd) skip a managed root with heartbeat reasonpush_managed_coordinator; doctorbootstrap_push_health(src/commands/doctor/bootstrap-checks.tsrecordedPushFailureCheck) reports ok when every recorded failure's tree now matches its configured origin with nothing uncommitted. #5799:isSupersededPushStatus(entry)/livePushStatuses(entries)drop a record the managed topology has superseded (code or reason prefixwriter_coordinator_required, or arepoRootthat is a managed worktree now; an unreadable marker is not assumed managed), because the coordinator's git effect never writes push-status and the refusal would otherwise feed the hook's FAILING banner and staleness note forever (test/workspace-push-superseded-status.test.ts); the hook call sites readlivePushStatuses(readPushStatuses()).readPushStatusesskips per-root records whoserepoRootstat answers ENOENT or ENOTDIR (a deleted workspace) and unreadable files (torn or non-object JSON, a missing-absolute or non-stringrepoRoot, any other stat error such as EACCES); the keyedreadPushStatusForRootparses with the same rule.pushStatusRecordCountstells the two apart, so doctor'sbootstrap_push_healthreports files kept only for deleted workspaces asokand anything unreadable aspush status unreadable; no status file is changed or removed (#7377,test/push-status-gone-roots-7377.test.ts).
Shared-checkout git writer
src/core/git/commit-push.ts+src/core/git/commit-guard.ts— writer safety in a shared checkout (#7381).integratereplaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (rev-list --cherry-mark): it replays the local commits onto the remote tip in memory (merge-tree --merge-baseon git 2.40+, a 3-wayread-treeotherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out.supersededPathsresolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them assuperseded_remote_paths, andintegrate_conflictlists only the rest (detail.supersedednames them).commitPathsrefuses a path outside the source roots (configuredSourceRoots, git configgbrain.sourceRoot, recorded bysources harden'srecordSourceRoot) and a file another writer staged under a named directory (commit_prestaged_paths), stages named tracked paths withadd -uand visible untracked ones withadd -A(a tracked deletion under an ignored directory commits, #7984; any other path keeps git'scommit_paths_invalid), and restores the exact index entries (update-index --index-info) when git refuses the commit. After the commit step (and its index restore)commitPathsreturns the named paths HEAD still lacks (unstagedPaths: a modified entry flagged assume-unchanged or skip-worktree, a named file git did not index such as one inside a nested repository, and unstaged status entries under a named directory; a skip-worktree entry absent from disk, a flagged gitlink and ignored files under a named directory are left out) and keeps an unindexed file out ofcommit --only;commitAndPush(classic, managed and remoteless) andcommitPathsLockedthen throwcommit_paths_skipped, orwriter_coordinator_requiredfor a page in a managed worktree (itsput_pagefix names the managed source), once the rest is committed and, on a classic checkout, pushed (detail:skipped,committed,pushed,branch, andpublishwhen the push failed too). Every commit gbrain makes carriesGBRAIN_COMMIT_VIA=<lock path>. Every pathspec it passes goes throughliteralPathspecs(git-env.ts), nevergit --literal-pathspecs, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (git_unavailable, paths unstaged).commitPathsLocked(write-through) never commits without the lock: a busy lock or refused commit notes the file inbrain-writethrough-pending.log(git dir, O_APPEND lines), which the next locked write-through andcommit-push --pendingcommit andsettlePendingprunes (exported for a caller holding the commit lock: the derived write-through's rollback).notePendingis exported: the derived and dream write-through (cycle/derived-write-through.ts, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (commit_outside_source_root;--allow-outside-source-rootlifts both refusals, andsources hardenpasses it for its root scaffolding). With git configgbrain.quarantine(opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit underrefs/gbrain/quarantine/<time>-<sha>and appends it tobrain-quarantine.log(readQuarantinelists entries whose ref still exists); structural conflicts still refuse.commit-guard.tsinstalls the opt-inprepare-commit-msgguard (gbrain git guard), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honorsGBRAIN_COMMIT_GUARD=off. The helper's no-gbrain fallback (renderCommitPushHelper) marks children with the absolute lock path, passes each path as:(literal)<path>(a glob-named path never commits another file, #7792) and releases the commit lock before pushing underbrain-publish.lock; it runs the same skipped-path check after its commit and reportscommit_paths_skippedafter the push (exit 1, or 4 when the push failed). The CLI (src/commands/git.ts) refusescheckout_not_a_sourcebefore staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has nogbrain.sourceRoot(#8662); a registered checkout must contain the resolved one, or be a subdirectory its HEAD tracks, so a repository that only encloses one is refused, and a registry that cannot be listed refuseswriter_coordinator_required(GST-1623).--untrack(#7753, GST-2519):untrackPathsremoves the files HEAD holds under the named paths (untrackTargets; skip-worktree files refuse) withgit rm --cachedand commits from HEAD in a temporary index, taking back a commit that changed anything else; in a managed canonical worktreeuntrackAdmittedfirst requires each file to sit under astorage.db_onlydir thatgbrain.ymlat HEAD declares and that.gitignoreignores (untrack_not_db_only, index untouched), and the commit stays local like every managed commit;previewUntrackis the dry run. The dry run of a commit ispreviewPaths(#7752):admitPaths(shared withcommitPaths: source roots,--base, pre-staged files), the real staging (stagePaths) asgit add -nagainst a copy of the index, and a staged rename's partner, so each refusal carries the real run's code and text, with no lock and no write. A not_staged path that is a hand-stagedgit rm --cachednames--untrackin thecommit_paths_skippedfix. Tests:test/git-writer-safety-7381.serial.test.ts,test/git-literal-pathspec-hooks-7759.test.ts,test/git-commit-push-not-a-source-8662.test.ts,test/git-commit-push-skipped-paths-gst2116.test.ts,test/git-commit-push-untrack-gst2519.test.ts,test/git-commit-push-door-wave2.test.ts.src/core/git/range-secret-scan.ts—scanRange(root, from, to, timeoutMs, progress), the secret gate for every push gbrain makes:gbrain git commit-pushin every mode,--untrackincluded where it pushes (everycommitAndPushpublish scans, with no opt-out, a push handed over from a busy publish lock included; on a managed worktree the generated-page write-through only commits, and the owner's scanned Git effect push publishes it; a missing tracking ref is fetched first so only what the remote lacks is scanned; the post-commit hook,scripts/brain-commit-push.shand the childgbrain sources refreshruns all go through it) scanstrackingRef..targetunder the publish lock, right before a push that never follows tags or recurses into submodules (--no-follow-tags --recurse-submodules=no, on thesources pushandbootstrap repopushes too). Plumbing only (rev-list, thencat-file --batchanddiff-tree --stdin -p --root --ccover batches of 256 commits, so the temporary patch file stays one batch in size), so log, diff and attribute settings never change what is scanned. The budget is 300 s unless--scan-timeoutsets it;progressgetssecret scan:lines (at once for a whole history, then every 10 s), and withretryArgva timed-out scan refusespublish_scan_unreadablewhose agent fix is that command with--scan-timeoutfour times longer (at least 1200 s). Commit messages, added lines and merge resolutions go throughscanTextwith the.gbrain-scan-allowallowlist; a finding, added text over the scan cap or a change to.gbrain-scan-allow/.gitattributesrefusespublish_secret_found(file, line, rule, commit, never the value), and a range it cannot read in full (git failure, unrecognised output, 300 s budget) refusespublish_scan_unreadable. Commits the commit ledger records as page writes are not scanned: hosted-repository commits, and strict-source door commits and Git effect commits recordedverified(no Git clean filter changed the committed bytes) (effectCommitineffect-git.tsbuilds the commit withcommit-treeand moves HEAD with anupdate-refcompare-and-swap, so the recorded sha is gbrain's own;verifiedwhen each staged blob is the bytes whose sha256 the effect recorded); adopted records, records withoutverifiedand an unreadable ledger leave the commits scanned. Doctorgit_convergence's agent push fixes pass--scan-secretstoo.stagedScanPublishRefusal(root, base, target, opts)is the same refusal forgbrain sources push(workspace-push.ts: origin's tip read from origin itself withls-remoteand a fetch, since the pull may follow another upstream remote, then<tip>..HEADscanned and that exact sha pushed leased on the tip, no push when the local branch lacks the tip; a refusal is theblocked_historyresult, exit 5, printed by--jsontoo) and both first pushes ofgbrain bootstrap repo(bootstrap/repo.ts, the whole history;scanHistoryis the runner-fake seam), with gate changes exempt in commits the ledger records asworkspace_pushorbootstrap, whose blobs those writers scanned staged with the same allowlist. In a managed root below the repository's top level, that root's own.gbrain-scan-allowis the loaded allowlist (path globs relative to the root) and a commit changing it is a gate change. The access-policy commit (access/policy-git.ts, which reports a scan refusal ascommitted_not_pushedwith the refusal in its note) and the durability-scaffolding commit (brain-repo-durability.ts) publish throughcommitAndPush, which scans every push (#8902). The helper's no-gbrain fallback commits and never pushes.gbrain git scan(runScaninsrc/commands/git.ts) runsscanRangeandrangeSecretRefusalover--from..--to(default@{upstream}..HEAD) and writes nothing: the read-only preview of what a push would refuse, with each finding's fingerprint. Tests:test/unmanaged-push-history-scan-8902.serial.test.ts,test/unmanaged-push-every-site-gst2456.serial.test.ts.src/commands/doctor/checks/git-writer.ts—checkout_lagging,dirty_age,commits_outside_source_root,quarantined_changes(#7381, brain category, aftergit_convergence): over the unmanaged source checkouts with an upstream (sourceRootsfrom git-convergence, grouped by toplevel with each source's toplevel-relative root), never fetching, every git call bounded at 5 s. Lagging warns whenHEAD..@{u}holds a commit over an hour old (fix:gbrain git commit-push --pull --path <top>, agent). Dirty age warns on pending write-through files older than 30 minutes (pendingWriteThroughStillDirty; fix:commit-push --pending, agent) and on files staged that long (ask_user: unstage or commit by name). Outside-root warns on unpushed non-merge commits that change files outside the DB source roots plusgbrain.sourceRoot(localCommitsOutsideRoots; ask_user fix with--allow-outside-source-root), and says when the checkout has no root recorded. Test:test/doctor-git-writer-7381.test.ts.src/core/git/commit-ledger.ts— the commit ledger (PR B, docs/designs/REFRESH_WRITE_BARRIER.md part 3):<git common dir>/gbrain/commit-ledger.jsonl, one O_APPEND JSON line under 1 KiB per record, under its own flockcommit-ledger.lock(start line, append, 4 MiB rotation tocommit-ledger.1.jsonl).recordCommit/recordCommitAsynctake the sha and writer kind (commit_push,door,merge,replay,effect,sync_init,workspace_push,bootstrap,hosted_repo); porcelain sites callrecordIntent(head_before,messageDigestof the message) beforegit commit, plumbing sites record thecommit-treesha before the ref moves. A failed append never fails the commit (logged once); a directory outside git records nothing.readLedgerreads both files; only a missing file reads as empty, any other read error throws (GST-1623). Tests:test/commit-ledger.test.ts.src/commands/doctor/checks/foreign-writers.ts—foreign_writers(PR B part 4): every registered source checkout on this host, managed worktrees included, deduplicated by git common dir. Reflogs (logs/HEAD,logs/refs/heads/*,worktrees/*/logs/HEAD, newest 5,000 entries each) are classified byclassifyReflogMessage: porcelain creations by new sha, other ref moves by theold..newrange within 10 minutes of the entry, merges/fast-forwards/resets/checkouts/branch/clone excluded. Unledgered commits fail (plain,amend,rewrite,plumbing;guard_bypassedwhen the enforce guard predates the commit); intent matches areunconfirmed(warn, never written back); entries before the ledger start are uncovered. Dirty page files come fromstatus --porcelain=v2under the source roots minus queued/running git effects and the write-through pending ledger. GST-1623: a foreign commit carriesgbrain_trailerwhen its trailer paragraph has agbrain-*:line (named as possibly an older gbrain without the ledger; still fails);partial_reasonsnames what the scan skipped (a root inside a checkout whoserev-parsefails, roots pastMAX_ROOTS50, an unreadable ledger, a failed or timed-out status, given up to 30 s within doctor's budget, the budget itself), and a scan that read no repository but skipped one warns. Repo-less:not_applicable. Tests:test/doctor-foreign-writers.test.ts.src/commands/sources-guard.ts—gbrain sources guard <source> --install|--uninstall|--status [--mode enforce](PR B part 5): owner host only (permission_deniedelsewhere), install/uninstall under the worktree's native writer lock (acquireWorktree).commit-guard.tsinstallOwnerGuardwrites the hook to<worktree git dir>/gbrain-hooksand setsgit config --worktree core.hooksPath(enablingextensions.worktreeConfig, movingcore.bare/core.worktreetoconfig.worktree, only when linked worktrees exist), refusing when another tool's hook lives at the effective hooks path and copying gbrain's own hooks there (the brain-durability post-commit hook, so an unrecorded binding stays durable); both owner-path modes exit 0 outside the owner worktree (a worktree added after the install inherits its hooks path throughconfig.worktree) and exit 1 whengit rev-parse --absolute-git-dirfails (GST-1623, fail closed),renderGuardHook('enforce')keeps only the merge exemption, andrenderGuardHook()with no mode stays byte-identical to the opt-ingbrain git guardhook. Tests:test/sources-guard.test.ts.