Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Exempt a Git effect commit from the secret scan only when its sha, parent, paths and blobs check out; doctor push fixes scan

garrytan0d8747e419b6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 972078d50d..a22720e676 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,16 +12,17 @@ identifiers and attribution are available in the pre-removal Git revision
## [0.60.621.0] - 2026-11-09
-**The Git effects of page writes no longer publish a script's secret.** A script that commits into a managed checkout with plain `git commit` never passes the write path's secret scan. The refresh publish refused such a commit with `publish_secret_found`, but the next page write's Git effect pushed it anyway: its plain push published every unpublished commit unscanned, and when the remote had moved its keep-checkout publish ran without the scan. Both paths now scan the exact commits they push, except the ones gbrain made itself for page writes (a Git effect's commit or a hosted repository's door commit, as its commit ledger records them): page bodies are stored raw by design and their Git backups keep going, and the refresh publish now skips them the same way. A value that looks like a secret, added text too large to scan, a commit that changes `.gbrain-scan-allow` or a `.gitattributes` holds the effects with `publish_secret_found`; commits the scan cannot read in full hold them with `publish_scan_unreadable`. A first push to a remote that has no such branch yet scans the branch's whole history and creates the branch only when that scan passes. A commit that changes `.gbrain-scan-allow` or a `.gitattributes` is never published automatically: the user reviews it and pushes it. Nothing is pushed, and the page writes stay safe in the database and in local commits. `gbrain sync status` and doctor name the user's choice: remove the value from those commits, or allowlist a false positive by fingerprint. Then `gbrain sources writer retry-effects <source> --parked-pushes` runs the effects that parked. Every scanned push is also leased on the remote tip it scanned against. Before, a remote rewound past a pushed secret (an admin removing it with a force-push) left a stale tracking ref that hid the commit from the scan, and the next fast-forward put it back; now the scan runs against the remote's real tip. The in-process scan on the owner's event loop is capped at 10 seconds, inside the writer heartbeat's live window; a longer range goes to the keep-checkout publish, whose child process scans with the full budget.
+**The Git effects of page writes no longer publish a script's secret.** A script that commits into a managed checkout with plain `git commit` never passes the write path's secret scan. The refresh publish refused such a commit with `publish_secret_found`, but the next page write's Git effect pushed it anyway: its plain push published every unpublished commit unscanned, and when the remote had moved its keep-checkout publish ran without the scan. Both paths now scan the exact commits they push, except the ones gbrain made itself for page writes (a Git effect's commit, recorded only after checking it holds exactly the bytes the effect wrote, or a hosted repository's door commit, as its commit ledger records them): page bodies are stored raw by design and their Git backups keep going, and the refresh publish now skips them the same way. A value that looks like a secret, added text too large to scan, a commit that changes `.gbrain-scan-allow` or a `.gitattributes` holds the effects with `publish_secret_found`; commits the scan cannot read in full hold them with `publish_scan_unreadable`. A first push to a remote that has no such branch yet scans the branch's whole history and creates the branch only when that scan passes. A commit that changes `.gbrain-scan-allow` or a `.gitattributes` is never published automatically: the user reviews it and pushes it. Nothing is pushed, and the page writes stay safe in the database and in local commits. `gbrain sync status` and doctor name the user's choice: remove the value from those commits, or allowlist a false positive by fingerprint. Then `gbrain sources writer retry-effects <source> --parked-pushes` runs the effects that parked. Every scanned push is also leased on the remote tip it scanned against. Before, a remote rewound past a pushed secret (an admin removing it with a force-push) left a stale tracking ref that hid the commit from the scan, and the next fast-forward put it back; now the scan runs against the remote's real tip. The in-process scan on the owner's event loop is capped at 10 seconds, inside the writer heartbeat's live window; a longer range goes to the keep-checkout publish, whose child process scans with the full budget.
### Itemized changes
- `src/core/persistence/effect-git.ts`: `pushGitRoot` reads the remote branch tip with `git ls-remote`, scans `<tip>..<HEAD sha>` and pushes that sha only as a fast-forward of the tip, leased on it; a tip that is not an ancestor, or a remote that moves before the push lands (`stale info`), goes to the keep-checkout publish, which now runs with `--scan-secrets`. The in-process scan gets 10 s; a range it cannot finish goes to the keep-checkout publish. A remote without the branch gets HEAD's whole history scanned and the branch created with a lease that it does not exist; one too large to scan in process holds with `publish_scan_unreadable` naming `git ls-remote --heads`. A refusal from either path holds the effects as `publish_secret_found` with the user's fix.
- `src/core/git/commit-push.ts`: a `scanSecrets` publish scans `<base>..<candidate>` before every push and leases the push on that base, so each merge with a newly fetched remote tip is scanned again.
-- `src/core/git/range-secret-scan.ts`: `rangeSecretRefusal`, the one refusal both callers throw (`publish_scan_unreadable` for a scan that could not read the range, `publish_secret_found` otherwise; a gate-file change says the user pushes it). `scanRange` marks a scan that ran past its budget (`timed_out`) and scans a whole history when the base is empty. It skips commits the commit ledger records as page writes (`effect`, `door`, `hosted_repo`); `gbrain git commit-push` commits, adopted outside edits and commits the ledger no longer holds are still scanned, and an unreadable ledger means everything is scanned. A Git effect records its commit in the ledger only when that commit's parent is the HEAD it started from, so a script commit landing right after it is never recorded as gbrain's. Its time budget is also checked while the diff is parsed.
+- `src/core/git/range-secret-scan.ts`: `rangeSecretRefusal`, the one refusal both callers throw (`publish_scan_unreadable` for a scan that could not read the range, `publish_secret_found` otherwise; a gate-file change says the user pushes it). `scanRange` marks a scan that ran past its budget (`timed_out`) and scans a whole history when the base is empty. It skips commits the commit ledger records as page writes (`effect`, `door`, `hosted_repo`); `gbrain git commit-push` commits, adopted outside edits and commits the ledger no longer holds are still scanned, and an unreadable ledger means everything is scanned. A Git effect's commit is skipped only when its record is `verified`: the sha read under the writer lock right after the commit, its only parent the HEAD the commit started from, its paths exactly the effect's, each committed blob the bytes whose sha256 the effect recorded, and HEAD unchanged after those checks. A script commit or amend landing in between, or a page file changed after the effect checked it, fails one of them and stays scanned, and so do records written before this check existed. Its time budget is also checked while the diff is parsed.
+- `src/commands/doctor/checks/git-convergence.ts`: the agent push fixes for a stranded managed checkout and after committing its modified pages run `gbrain git commit-push --push-only --keep-checkout --scan-secrets`, so a script's commit is scanned there too.
- `src/core/persistence/git-push-holds.ts`: `publish_secret_found` and `publish_scan_unreadable` are held push codes, so doctor, `gbrain sync status` and `retry-effects --parked-pushes` cover them, with an ask-the-user fix (the refused commits, or `git fsck`).
- Docs: `docs/guides/shared-checkout-git.md` (`publish_secret_found` and `publish_scan_unreadable` rows), `docs/guides/live-sync.md`.
-- Tests: `test/effect-git-secret-gate.test.ts` (an ahead checkout, a diverged one, a remote rewound past a pushed secret, a `.gitattributes` change and a remote without the branch whose history holds a secret each refuse with nothing pushed; a clean ahead checkout pushes, a clean history creates a missing branch, and a scan past the in-process budget still scans in the child; through the effect worker the page write's effect holds, sync status names the fix, and an allowlisted false positive releases it, parked or not; a page write whose body holds a credential-shaped value still backs up; a repaired unreadable commit releases its hold); `test/guarded-publish.test.ts` (a remote rewound past a pushed secret is not published again); `test/git-literal-pathspec-hooks-7759.test.ts` publishes its probe `.gitattributes` commit first, since the effect's push now refuses one; `test/cli-flag-equals.test.ts` lists `range-secret-scan.ts` as a git child argv reader.
+- Tests: `test/effect-git-secret-gate.test.ts` (an ahead checkout, a diverged one, a remote rewound past a pushed secret, a `.gitattributes` change and a remote without the branch whose history holds a secret each refuse with nothing pushed; a clean ahead checkout pushes, a clean history creates a missing branch, and a scan past the in-process budget still scans in the child; through the effect worker the page write's effect holds, sync status names the fix, and an allowlisted false positive releases it, parked or not; a page write whose body holds a credential-shaped value still backs up; a script commit or amend racing the effect commit, a page file changed after the effect checked it, and an unverified ledger record each hold with nothing pushed; a repaired unreadable commit releases its hold); `test/persistence-git-removal-push-7089.test.ts` and `test/persistence-git-subdir-root-7091.test.ts` (doctor's push fixes scan); `test/guarded-publish.test.ts` (a remote rewound past a pushed secret is not published again); `test/git-literal-pathspec-hooks-7759.test.ts` publishes its probe `.gitattributes` commit first, since the effect's push now refuses one; `test/cli-flag-equals.test.ts` lists `range-secret-scan.ts` as a git child argv reader.
## [0.60.620.0] - 2026-11-09
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index b2c2321d0c..50acc88b48 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/bounded-unknown.ts` — #7145: `boundUnknownDetails(bound)` returns `{ health: 'unknown', reason: 'bound', bound, exact: false }`, the details shape a doctor check uses when it stopped at its own bound (`files`, `time`, `rows`, `roots`, `sample`) before it could say clear; the check adds its `limit` beside it, grades `warn`, and names the bound and the rerun or wider command in its message. Used by `multi_source_drift`, `ghost_pages`, `missing_recorded_files`, `conversation_outcomes_stale`, `maintenance_write_drift`, `git_convergence`, `tracked_ownership_marker`, `orphaned_private_queue`, `link_resolution_opportunity` and `frontmatter_integrity`. A capped list that found rows says "at least N" or "N+" with `exact: false` instead. Tests: `test/doctor-bound-unknown-7145.test.ts`, `test/doctor-capped-counts-7145.test.ts`, `test/doctor-unknown-reads-7145.test.ts`.
- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. #6610: `unbound_legacy_facts` lists, from the same plan, unfenced rows of classic database-only pages that `persistence.unbound_write` keeps unfenced; when it is the only finding the fix is `gbrain config set persistence.unbound_write database_only` with `ask_user`. Test: `test/doctor-fence-integrity.test.ts`, `test/extract-facts-unfenced-rows.test.ts`. Wave B decision #10: `withSkippedSegmented(check, n)` (`src/commands/doctor/check-fix.ts`) adds `Check.skipped_segmented: n` and a `skipped (segmented): n` message tail (unchanged at n = 0) to every check whose scan reads whole bodies: `oversized_pages`, `scraper_junk_pages`, `markdown_body_completeness`, `link_resolution_opportunity`, `fence_integrity` (segmented pages without a walked checkout file), `core_memory`, and `extract_health` via `readFactsReconcileBacklog`'s `skipped_segmented`; each count is one COUNT query that falls back to 0 on a schema without `body_storage`. Test: `test/large-pages/doctor-skipped-segmented.test.ts` (+ Postgres arm).
-- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time), except on a managed checkout this host owns with Git durability on and no Git effect of its worktree queued, running or failed: there they warn at once (`stranded: true` in `details.roots`, #7089) with an agent fix `gbrain git commit-push --push-only --keep-checkout --path <root>` and verify `gbrain doctor --only git_convergence --json`; bindings map to their toplevel, and tracked files modified under such a durable source root warn the same way (`uncommitted_pages`, #7091) with an ask-user commit, then that push; uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `persistence-git-removal-push-7089.test.ts` (stranded roots, both engines), `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
+- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s, at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit), except on a managed checkout this host owns with Git durability on and no Git effect of its worktree queued, running or failed: there they warn at once (`stranded: true` in `details.roots`, #7089) with an agent fix `gbrain git commit-push --push-only --keep-checkout --scan-secrets --path <root>` (verify `gbrain doctor --only git_convergence`); bindings map to their toplevel, and tracked files modified under such a durable source root warn the same way (`uncommitted_pages`, #7091) with an ask-user commit, then that push; uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `persistence-git-removal-push-7089.test.ts` (stranded roots, both engines), `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
- `src/commands/doctor/checks/keyword-plan.ts` — `keyword_plan` (#6495, OPS, wave check with operator resolution; the keyword-side twin of `vector_plan` in commands-2.md). Postgres only: reads the commonest lexeme the planner knows for `content_chunks.search_vector` (`pg_stats.most_common_elems` with its frequency), EXPLAINs (no ANALYZE) the strict page-count statement for it (`buildKeywordCountStatement`, the builder the engine uses) and times the engine's own bounded `countKeywordPages(term, { timeoutMs: 2000 })`; warns `canary_timed_out` when that count hits its bound and `canary_slow` when it takes more than half of `search.keyword_statement_timeout_ms`, naming the knob with its range (1000-60000), the fail-open to the vector arm (`keyword_arm_failed`), that a longer bound buys time and not a cheaper statement, that one canary term is not workload coverage, and that a timed-out count is never "no matches". Skipped on PGLite, below 10,000 chunks (`pg_class.reltuples`) and without planner statistics (it names `ANALYZE content_chunks`); a failing probe reports unknown health. `engineKeywordPlanProbe(engine)` is the database side; `keywordPlanCheck(engine, probe?)` takes a fake for tests. Tested in `test/doctor-keyword-plan-6495.test.ts` (fake probe for every outcome; with DATABASE_URL the real probe on a seeded brain and a lock-forced timeout).
- `src/commands/doctor/checks/image-embedding-coverage.ts` — `image_embedding_coverage` (#6529, brain category, after `image_assets`). Counts live image pages (`page_kind = 'image'`), those with no `embedding_image` chunk, those with a NULL `source_path`, and the `managed_image_sync_unsupported` holds per source, and reads `isMultimodalEnabled()`. Ok when the brain has no image pages, when every image page has an image vector and a `source_path` and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names `gbrain embed --stale --images` and `gbrain sync --no-pull --source <id>` for the holds. Read-only; no paid call. Test: `test/doctor-image-embedding-coverage.test.ts`.
- `src/commands/doctor/checks/provider-consent.ts` — `provider_consent` (OPS, engine-free filesystem lane right after `embedding_key_source`; not in `doctorReportRemote`): the provider-use decision `gbrain setup` recorded for this install (`localSetupRecords` in `src/core/setup/local-receipts.ts`). A decline (any live receipt; opt-outs win) is `ok` + info `disabled_by_choice`, "skipped by consent", naming the provider key variables present (names only) and carrying `providerConsentFix`: `gbrain setup <harness> --providers` (+ `--name`/`--scope project`), actor `user`, consent `paid`+`egress`, so `next: tell_user_to_run`. Accepted is plain `ok`; no receipt is info `not_applicable`. The same fix rides `embedding_provider`'s `--probe` skip (`checks/embedding-health.ts`), and `probe-consent.ts` authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by `test/doctor-provider-consent.serial.test.ts` (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.md
index 728a9db5ac..1f028aafe6 100644
--- a/docs/architecture/key-files/workspace-push-and-backup.md
+++ b/docs/architecture/key-files/workspace-push-and-backup.md
@@ -13,7 +13,7 @@ Key files:
## Shared-checkout git writer
- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces 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-base` on git 2.40+, a 3-way `read-tree` otherwise), 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. `supersededPaths` resolves 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 as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --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 in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. `notePending` is 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-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`. The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.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 refuses `writer_coordinator_required` (GST-1623). 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`.
-- `src/core/git/range-secret-scan.ts` — `scanRange(root, from, to)`, the secret gate for automatic publishes: `gbrain git commit-push --push-only --scan-secrets` (the child `gbrain sources refresh` runs to publish a diverged managed checkout) scans `trackingRef..target` under the publish lock, right before the push. Plumbing only (`rev-list`, `cat-file commit`, one streamed `diff-tree --stdin -p --root --cc`), so log, diff and attribute settings never change what is scanned. Commit messages, added lines and merge resolutions go through `scanText` with the `.gbrain-scan-allow` allowlist; a finding, added text over the scan cap or a change to `.gbrain-scan-allow`/`.gitattributes` refuses `publish_secret_found` (file, line, rule, commit, never the value), and a range it cannot read in full (git failure, unrecognised output, 300 s budget) refuses `publish_scan_unreadable`.
+- `src/core/git/range-secret-scan.ts` — `scanRange(root, from, to)`, the secret gate for automatic publishes: `gbrain git commit-push --push-only --scan-secrets` (the child `gbrain sources refresh` runs to publish a diverged managed checkout) scans `trackingRef..target` under the publish lock, right before the push. Plumbing only (`rev-list`, `cat-file commit`, one streamed `diff-tree --stdin -p --root --cc`), so log, diff and attribute settings never change what is scanned. Commit messages, added lines and merge resolutions go through `scanText` with the `.gbrain-scan-allow` allowlist; a finding, added text over the scan cap or a change to `.gbrain-scan-allow`/`.gitattributes` refuses `publish_secret_found` (file, line, rule, commit, never the value), and a range it cannot read in full (git failure, unrecognised output, 300 s budget) refuses `publish_scan_unreadable`. Commits the commit ledger records as page writes are not scanned: door and hosted-repository commits, and Git effect commits recorded `verified` (`ownCommit` in `effect-git.ts`: the sha read under the writer lock right after the commit, its only parent the start HEAD, its paths exactly the effect's, each blob the bytes whose sha256 the effect recorded, HEAD unchanged after the checks); adopted records, records without `verified` and an unreadable ledger leave the commits scanned. Doctor `git_convergence`'s agent push fixes pass `--scan-secrets` too.
- `src/commands/doctor/checks/git-writer.ts` — `checkout_lagging`, `dirty_age`, `commits_outside_source_root`, `quarantined_changes` (#7381, brain category, after `git_convergence`): over the unmanaged source checkouts with an upstream (`sourceRoots` from git-convergence, grouped by toplevel with each source's toplevel-relative root), never fetching, every git call bounded at 5 s. Lagging warns when `HEAD..@{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 plus `gbrain.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 flock `commit-ledger.lock` (start line, append, 4 MiB rotation to `commit-ledger.1.jsonl`). `recordCommit`/`recordCommitAsync` take the sha and writer kind (`commit_push`, `door`, `merge`, `replay`, `effect`, `sync_init`, `workspace_push`, `bootstrap`, `hosted_repo`); porcelain sites call `recordIntent` (head_before, `messageDigest` of the message) before `git commit`, plumbing sites record the `commit-tree` sha before the ref moves. A failed append never fails the commit (logged once); a directory outside git records nothing. `readLedger` reads 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 by `classifyReflogMessage`: porcelain creations by new sha, other ref moves by the `old..new` range within 10 minutes of the entry, merges/fast-forwards/resets/checkouts/branch/clone excluded. Unledgered commits fail (`plain`, `amend`, `rewrite`, `plumbing`; `guard_bypassed` when the enforce guard predates the commit); intent matches are `unconfirmed` (warn, never written back); entries before the ledger start are uncovered. Dirty page files come from `status --porcelain=v2` under the source roots minus queued/running git effects and the write-through pending ledger. GST-1623: a foreign commit carries `gbrain_trailer` when its trailer paragraph has a `gbrain-*:` line (named as possibly an older gbrain without the ledger; still fails); `partial_reasons` names what the scan skipped (a root inside a checkout whose `rev-parse` fails, roots past `MAX_ROOTS` 50, 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`.
diff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.md
index 4f44c96383..242919eb93 100644
--- a/docs/guides/shared-checkout-git.md
+++ b/docs/guides/shared-checkout-git.md
@@ -185,7 +185,7 @@ Follow the error's `fix.next` as the
| `git_index_stale` | 1 | An `index.lock` older than 10 minutes blocks the checkout. Check that no git command is running there, tell the user, and remove the named lock file only with their agreement. |
| `git_operation_in_progress` | 1 | A rebase, merge, cherry-pick or revert is unfinished in the checkout. gbrain never aborts it for you. Follow [stuck rebase](#stuck-rebase). |
| `git_detached_head` | 1 | The checkout is on a detached HEAD or an unborn branch. Check out the branch the remote tracks (`git switch <branch>`), or make the first commit, then rerun. |
-| <a id="publish_secret_found"></a>`publish_secret_found` | 1 | Only with `--scan-secrets`, which every automatic publish uses: the one `gbrain sources refresh` runs on its own and the push of a managed worktree's Git effects. A commit about to be pushed that gbrain did not make for a page write (its commit ledger records its own page-write commits, whose bodies are stored raw by design and are not scanned; one that adopted a file edited outside gbrain, or one older than the retained ledger, is scanned) adds a value that looks like a secret, in its message, an added line (even one a later commit removed) or a merge resolution, adds text too large to scan, or changes `.gbrain-scan-allow` or a `.gitattributes` (files that decide what the scan sees); nothing was pushed. The message names each file, line, rule and commit, never the value. Ask the user: remove the value from those unpushed commits, or add a false positive's fingerprint to `.gbrain-scan-allow`, then retry. A commit that changes `.gbrain-scan-allow` or a `.gitattributes` is never published automatically: the user reviews it and pushes it. Never publish them with a command that skips the scan. On a managed worktree its Git effects hold meanwhile (`gbrain sync status` and doctor list them; the page writes are safe in the database and in local commits); after the fix, `gbrain sources writer retry-effects <source> --parked-pushes` runs the ones that parked. |
+| <a id="publish_secret_found"></a>`publish_secret_found` | 1 | Only with `--scan-secrets`, which every automatic publish uses: the one `gbrain sources refresh` runs on its own, the push of a managed worktree's Git effects and doctor `git_convergence`'s push fixes. A commit about to be pushed that gbrain did not make for a page write (its commit ledger records its own page-write commits, whose bodies are stored raw by design and are not scanned; a Git effect's commit counts only when it was checked, right after it was made, to have the effect's start HEAD as parent, exactly the effect's files and the bytes the effect wrote; one that adopted a file edited outside gbrain, or one older than the retained ledger, is scanned) adds a value that looks like a secret, in its message, an added line (even one a later commit removed) or a merge resolution, adds text too large to scan, or changes `.gbrain-scan-allow` or a `.gitattributes` (files that decide what the scan sees); nothing was pushed. The message names each file, line, rule and commit, never the value. Ask the user: remove the value from those unpushed commits, or add a false positive's fingerprint to `.gbrain-scan-allow`, then retry. A commit that changes `.gbrain-scan-allow` or a `.gitattributes` is never published automatically: the user reviews it and pushes it. Never publish them with a command that skips the scan. On a managed worktree its Git effects hold meanwhile (`gbrain sync status` and doctor list them; the page writes are safe in the database and in local commits); after the fix, `gbrain sources writer retry-effects <source> --parked-pushes` runs the ones that parked. |
| <a id="publish_scan_unreadable"></a>`publish_scan_unreadable` | 1 | Only with `--scan-secrets`: the scan could not read the commits about to be pushed in full (a missing or corrupt object, git output it does not recognise, or its 300 s budget), so it reported no secret and nothing was pushed. Run `git fsck` in the checkout, fix what it names, then retry. When the remote has no such branch, a managed worktree's Git effect scans the branch's whole history and creates it only when that scan passes; a history too large to scan in the owner process holds the effects with this code and names `git ls-remote --heads <remote>`: check the upstream, then point it at the right branch or review the history and push the branch yourself. Never publish with a command that skips the scan. On a managed worktree its Git effects hold meanwhile, as for `publish_secret_found`. |
| `integrate_conflict` | 1 | Local and remote commits changed the same file; nothing was merged and the checkout is unchanged. Stop, relay the question to the user, then [resolve](#conflicts). |
| `push_unconfirmed` | 4 | The commit is durable locally but no push destination confirmed it (network, credentials, branch protection, a remote that kept moving, or another push that held the push lock for the whole wait). Fix what the message names, then run `gbrain git commit-push --push-only`. Never force-push. |
diff --git a/src/commands/doctor/checks/git-convergence.ts b/src/commands/doctor/checks/git-convergence.ts
index 24059d201b..bf2babaf39 100644
--- a/src/commands/doctor/checks/git-convergence.ts
+++ b/src/commands/doctor/checks/git-convergence.ts
@@ -198,8 +198,8 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())
const uncommitted = stranded.find(r => r.uncommitted_pages);
if (uncommitted) {
const pages = uncommitted.uncommitted_pages!;
- const push: Action = { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', uncommitted.root], consent: [], actor: 'agent', requires_exclusive: false,
- why: 'Publishes the commit just made without moving the checkout.', verify: doctorVerify('git_convergence') };
+ const push: Action = { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--scan-secrets', '--path', uncommitted.root], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Publishes the commit just made without moving the checkout, after scanning what the unpublished commits add for secrets.', verify: doctorVerify('git_convergence') };
return { name: 'git_convergence', status, details,
message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. ${uncommitted.root} is a managed checkout with Git durability on, ${pages.length} tracked file(s) modified under its source root (${pages.slice(0, 5).join(', ')}${pages.length > 5 ? ', ...' : ''}) and no Git effect queued, running or parked, so no effect will commit them (#7091: earlier releases committed no edits to tracked pages when the source root sits below the repository top). Review them and commit them with gbrain git commit-push, then push with the keep-checkout publish. ${remedy}; this compares with the last fetched upstream and does not fetch.${boundNote}`,
fix: { ask_user: true, argv: ['gbrain', 'git', 'commit-push', '--path', uncommitted.root, '-m', 'gbrain: persist canonical memory update', '--', ...pages], consent: [], actor: 'user', requires_exclusive: false,
@@ -211,8 +211,8 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())
const first = stranded[0]!;
return { name: 'git_convergence', status, details,
message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. ${stranded.map(r => r.root).join(', ')} ${stranded.length === 1 ? 'is a managed checkout' : 'are managed checkouts'} with Git durability on and no Git effect queued, running or parked, so no effect will push ${stranded.length === 1 ? 'its' : 'their'} commits; push them with the keep-checkout publish, which merges a moved remote in memory and never moves the checkout. ${remedy}; this compares with the last fetched upstream and does not fetch.${boundNote}`,
- fix: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', first.root], consent: [], actor: 'agent', requires_exclusive: false,
- why: `${first.root} has ${first.ahead} commit(s) not on its upstream and no Git effect left to push them (#7089); this publishes the commits already on the branch and commits nothing. A conflict with the remote is reported with the user's choice as its fix.${stranded.length > 1 ? ` ${stranded.length - 1} other checkout(s) need the same, see details.roots (stranded).` : ''}`,
+ fix: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--scan-secrets', '--path', first.root], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `${first.root} has ${first.ahead} commit(s) not on its upstream and no Git effect left to push them (#7089); this publishes the commits already on the branch and commits nothing, refusing with publish_secret_found when what they add looks like a secret. A conflict with the remote is reported with the user's choice as its fix.${stranded.length > 1 ? ` ${stranded.length - 1} other checkout(s) need the same, see details.roots (stranded).` : ''}`,
verify: doctorVerify('git_convergence') } };
}
const diverged = bad.find(r => r.diverged);
diff --git a/src/core/git/commit-ledger.ts b/src/core/git/commit-ledger.ts
index fda616b5d3..e83f0cbf27 100644
--- a/src/core/git/commit-ledger.ts
+++ b/src/core/git/commit-ledger.ts
@@ -32,12 +32,12 @@ export const LEDGER_ROTATE_BYTES = 4 * 1024 * 1024;
const LINE_MAX_BYTES = 1023;
const LOCK_WAIT_MS = 2_000;
-export interface LedgerCommit { sha: string; writer: LedgerWriter; ref?: string | null; request_id?: string | null; worktree_id?: string | null; supersedes?: string[]; adopted?: string[] }
+export interface LedgerCommit { sha: string; writer: LedgerWriter; ref?: string | null; request_id?: string | null; worktree_id?: string | null; supersedes?: string[]; adopted?: string[]; verified?: true }
export interface LedgerIntent { writer: LedgerWriter; head_before: string | null; message: string }
export type LedgerRecord =
| { v: 1; e: 'start'; t: string }
- | { v: 1; e: 'commit'; t: string; sha: string; writer: LedgerWriter; request_id: string | null; worktree: string | null; worktree_id: string | null; ref: string | null; pid: number; host: string | null; supersedes?: string[]; adopted?: string[] }
+ | { v: 1; e: 'commit'; t: string; sha: string; writer: LedgerWriter; request_id: string | null; worktree: string | null; worktree_id: string | null; ref: string | null; pid: number; host: string | null; supersedes?: string[]; adopted?: string[]; verified?: true }
| { v: 1; e: 'intent'; t: string; writer: LedgerWriter; head_before: string | null; msg_sha256: string; worktree: string | null; pid: number; host: string | null };
interface Location { common: string; gitDir: string; worktree: string | null }
@@ -110,7 +110,8 @@ function line(record: LedgerRecord): string {
function commitRecord(loc: Location, entry: LedgerCommit): LedgerRecord {
return { v: 1, e: 'commit', t: new Date().toISOString(), sha: entry.sha, writer: entry.writer, request_id: entry.request_id ?? null,
worktree: loc.worktree, worktree_id: entry.worktree_id ?? null, ref: entry.ref === undefined ? headRef(loc.gitDir) : entry.ref, pid: process.pid, host: hostId(),
- ...(entry.supersedes?.length ? { supersedes: entry.supersedes } : {}), ...(entry.adopted?.length ? { adopted: entry.adopted } : {}) };
+ ...(entry.supersedes?.length ? { supersedes: entry.supersedes } : {}), ...(entry.adopted?.length ? { adopted: entry.adopted } : {}),
+ ...(entry.verified ? { verified: true } : {}) };
}
function intentRecord(loc: Location, intent: LedgerIntent): LedgerRecord {
diff --git a/src/core/git/range-secret-scan.ts b/src/core/git/range-secret-scan.ts
index 5ccd82eac6..9164dc5e22 100644
--- a/src/core/git/range-secret-scan.ts
+++ b/src/core/git/range-secret-scan.ts
@@ -51,8 +51,10 @@ const DIFF = ['diff-tree', '--stdin', '-r', '-p', '--root', '--cc', '--no-rename
/**
* Ledger writers whose commits hold only page writes: a Git effect's commit and a hosted repository's door commits. A
- * record that adopted a file edited outside gbrain (`adopted`) carries bytes gbrain did not write, so it is scanned, and
- * so is a page-write commit older than the retained ledger or made before it existed.
+ * Git effect's record counts only when `verified` (its sha, parent, paths and blobs were checked against what the effect
+ * wrote; records from releases before that check carry none). A record that adopted a file edited outside gbrain
+ * (`adopted`) carries bytes gbrain did not write, so it is scanned, and so is a page-write commit older than the retained
+ * ledger or made before it existed.
*/
const PAGE_WRITERS: ReadonlySet<string> = new Set(['effect', 'door', 'hosted_repo']);
@@ -68,7 +70,10 @@ function run(root: string, args: string[], deadline: number, opts: { input?: str
/** The commits the ledger records as page writes; an unreadable ledger reads as none, so everything is scanned. */
function pageWriteCommits(root: string, deadline: number): Set<string> {
const common = must(run(root, ['rev-parse', '--path-format=absolute', '--git-common-dir'], deadline), 'rev-parse').toString().trim();
- try { return new Set(readLedger(common).flatMap(record => record.e === 'commit' && PAGE_WRITERS.has(record.writer) && !record.adopted?.length ? [record.sha] : [])); }
+ try {
+ return new Set(readLedger(common).flatMap(record => record.e === 'commit' && PAGE_WRITERS.has(record.writer) && !record.adopted?.length
+ && (record.writer !== 'effect' || record.verified) ? [record.sha] : []));
+ }
catch { return new Set(); }
}
function must(r: Run, what: string): Buffer {
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index 25e96d74e7..6615ab8efe 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -1,4 +1,5 @@
-import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { closeSync, existsSync, fstatSync, mkdirSync, mkdtempSync, openSync, readSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { basename, dirname, join, relative, resolve as resolvePath, sep } from 'node:path';
import { execFileBounded } from '../brain-repo-durability.ts';
import { gitDurabilityPolicy } from './git-durability-policy.ts';
@@ -291,7 +292,7 @@ export function commitMessageArgs(paragraphs: string[], dir: string | (() => str
* that is provably abandoned is reclaimed and the step retried (#6932).
*/
export async function commitGitTargets(root: string, relativePaths: string[], signal?: AbortSignal,
- notes?: ReadonlyMap<string, GitCommitNote>, owner?: GitEffectOwner): Promise<Map<string, GitOutcome | OperationError>> {
+ notes?: ReadonlyMap<string, GitCommitNote>, owner?: GitEffectOwner, expected?: ReadonlyMap<string, string | null>): Promise<Map<string, GitOutcome | OperationError>> {
const results = new Map<string, GitOutcome | OperationError>();
await withSession(root, signal, owner, true, async session => {
// One ls-files, one status, one add and one diff for the group; targets
@@ -379,13 +380,17 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
result = await git(session, [...(commitPaths.some(path => removed.has(path)) ? NO_FSCACHE : []), 'commit', '--only', ...message, '--', ...literalPathspecs(commitPaths)]);
} finally { if (messageDir) rmSync(messageDir, { recursive: true, force: true }); }
if (result.code === 0) {
- // #8896: the secret scan trusts ledgered page writes, so HEAD is recorded only when its parent is the HEAD this commit
- // started from: a commit that landed on top in between (a script's plain `git commit`) stays unrecorded and scanned.
- const head = await git(session, ['rev-list', '--parents', '-n', '1', 'HEAD']);
- const [sha, ...parents] = head.code === 0 ? head.stdout.trim().split(' ') : [];
+ const wanted = new Map<string, string | null>();
+ for (const c of changed) {
+ const hash = expected?.get(c.requested);
+ if (hash !== undefined && (!wanted.has(c.path) || wanted.get(c.path) === hash)) wanted.set(c.path, hash);
+ else wanted.set(c.path, '');
+ }
+ const own = await ownCommit(session, root, prefix, headBefore, commitPaths, wanted);
const trailers = [...noted.values()].flatMap(note => note.trailers ?? []);
const supersedes = supersededBy(trailers), adopted = adoptedBy(trailers);
- if (sha && parents.join(' ') === (headBefore ?? '')) await recordCommitAsync(root, { sha, writer: 'effect', ...(supersedes.length ? { supersedes } : {}), ...(adopted.length ? { adopted } : {}) });
+ if (own) await recordCommitAsync(root, { sha: own.sha, writer: 'effect', ...(own.verified ? { verified: true } : {}),
+ ...(supersedes.length ? { supersedes } : {}), ...(adopted.length ? { adopted } : {}) });
}
const outcome = result.code === 0 ? { git: 'committed' } : gitFailure('Cannot commit the canonical Git target.',
`git commit failed for ${commitPaths.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);
@@ -394,6 +399,54 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
return results;
}
+/**
+ * #8896: the commit `commit --only` just made, read with rev-parse under the writer lock, and whether the secret scan may
+ * trust it as a page write. Null (left out of the ledger) unless its only parent is `headBefore` and it changes exactly
+ * `paths`: a script's commit or amend that landed in between differs in one of them. `verified` also needs, for every
+ * path, the sha256 of the bytes the effect wrote (`wanted`; null for a removal, '' for none known) to match the file read
+ * once now, the committed blob to have that read's object id, and HEAD to be unchanged after the checks. Any mismatch,
+ * unknown expectation or git failure leaves the commit scanned.
+ */
+async function ownCommit(session: GitSession, root: string, prefix: string, headBefore: string | null, paths: string[],
+ wanted: ReadonlyMap<string, string | null>): Promise<{ sha: string; verified: boolean } | null> {
+ const head = async () => { const r = await git(session, ['rev-parse', '--verify', '--quiet', 'HEAD']); return r.code === 0 ? r.stdout.trim() : ''; };
+ const sha = await head();
+ if (!sha) return null;
+ const parents = await git(session, ['rev-list', '--parents', '-n', '1', sha]);
+ if (parents.code !== 0 || parents.stdout.trim().split(' ').slice(1).join(' ') !== (headBefore ?? '')) return null;
+ const full = new Set(paths.map(path => prefix + path));
+ const diff = await git(session, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', '--no-renames', '--root', sha]);
+ const touched = diff.code === 0 ? diff.stdout.split('\0').filter(Boolean) : null;
+ if (!touched || touched.length !== full.size || !touched.every(path => full.has(path))) return null;
+ if (paths.some(path => wanted.get(path) === '' || !wanted.has(path))) return { sha, verified: false };
+ const format = await git(session, ['rev-parse', '--show-object-format']);
+ const listed = await git(session, ['ls-tree', '-r', '-z', '--full-tree', sha, '--', ...literalPathspecs([...full])]);
+ if (format.code !== 0 || listed.code !== 0) return { sha, verified: false };
+ const blobs = new Map(listed.stdout.split('\0').filter(Boolean).map(entry => {
+ const [mode, type, oid] = entry.slice(0, entry.indexOf('\t')).split(' ');
+ return [entry.slice(entry.indexOf('\t') + 1), mode?.startsWith('100') && type === 'blob' ? oid : ''] as const;
+ }));
+ for (const path of paths) {
+ const hash = wanted.get(path)!, oid = blobs.get(prefix + path);
+ if (hash === null ? oid !== undefined : !oid || fileDigests(join(root, path), format.stdout.trim()) !== `${hash} ${oid}`) return { sha, verified: false };
+ }
+ return { sha, verified: await head() === sha };
+}
+
+/** `<sha256> <git blob id>` of the file's bytes, read once; null when it cannot be read or changes size while read. */
+function fileDigests(path: string, objectFormat: string): string | null {
+ let fd: number;
+ try { fd = openSync(path, 'r'); } catch { return null; }
+ try {
+ const size = fstatSync(fd).size;
+ const content = createHash('sha256'), blob = createHash(objectFormat === 'sha256' ? 'sha256' : 'sha1').update(`blob ${size}\0`);
+ const buffer = Buffer.alloc(1024 * 1024);
+ let read = 0;
+ for (let n; (n = readSync(fd, buffer, 0, buffer.length, null)); read += n) { content.update(buffer.subarray(0, n)); blob.update(buffer.subarray(0, n)); }
+ return read === size ? `${content.digest('hex')} ${blob.digest('hex')}` : null;
+ } finally { closeSync(fd); }
+}
+
/**
* #7089: whether `root`'s branch has commits its upstream (the local remote-tracking ref, never fetched) lacks; false
* without an upstream. A Git effect whose target is absent asks this before completing: its removal may have been
@@ -549,9 +602,11 @@ export const DURABILITY_NOT_ENABLED = { git: 'skipped', reason: 'durability_not_
* root that is not ahead it completes without a push, as before.
*/
export async function publishGitEffect(root: string, relativePath: string, signal?: AbortSignal,
- hardened?: boolean, note?: GitCommitNote, binding?: Pick<WorktreeBinding, 'git_durability'> | null, owner?: GitEffectOwner): Promise<Record<string, unknown>> {
+ hardened?: boolean, note?: GitCommitNote, binding?: Pick<WorktreeBinding, 'git_durability'> | null, owner?: GitEffectOwner,
+ expectedHash?: string | null): Promise<Record<string, unknown>> {
if (!(hardened ?? (await gitDurabilityPolicy(binding, root)).durable)) return { ...DURABILITY_NOT_ENABLED };
- const outcome = (await commitGitTargets(root, [relativePath], signal, note ? new Map([[relativePath, note]]) : undefined, owner)).get(relativePath)!;
+ const outcome = (await commitGitTargets(root, [relativePath], signal, note ? new Map([[relativePath, note]]) : undefined, owner,
+ expectedHash === undefined ? undefined : new Map([[relativePath, expectedHash]]))).get(relativePath)!;
if (outcome instanceof OperationError) throw outcome;
if (outcome.reason === 'target_absent' && !(await gitRootAhead(root, signal))) return outcome;
const pushed = await pushGitRoot(root, signal);
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index df9f25e24c..e424f847c2 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -346,7 +346,8 @@ async function publishGitPage(engine: BrainEngine, effect: PersistenceEffect, bi
const root = binding.local_path;
if (!targetedWithdrawalEffect(effect) && !effect.data.source_scan) {
const target = await singleFileGitTarget(engine, effect, { ...binding, local_path: root }, attempt);
- if (target !== null) await completeEffect(engine, effect, await publishGitEffect(root, target, opts.signal, hardened, await gitCommitNote(engine, effect), undefined, owner));
+ if (target !== null) await completeEffect(engine, effect, await publishGitEffect(root, target, opts.signal, hardened, await gitCommitNote(engine, effect), undefined, owner,
+ effect.data.expected_hash));
return;
}
// Only a page walk reads snapshots; a single-file effect completes by its recorded hash.
@@ -973,7 +974,8 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
const notes = new Map<string, GitCommitNote>();
for (const { effect, path } of targets) { const note = await gitCommitNote(engine, effect); if (note) notes.set(path, note); }
const outcomes = targets.length ? await commitGitTargets(binding.local_path, targets.map(t => t.path), opts.signal, notes,
- { writerLock: lock, onReclaim: () => { reclaimed = true; } }) : new Map();
+ { writerLock: lock, onReclaim: () => { reclaimed = true; } },
+ new Map(targets.flatMap(t => t.effect.data.expected_hash === undefined ? [] : [[t.path, t.effect.data.expected_hash] as const]))) : new Map();
const pending = unpushed.get(binding.local_path) ?? { binding, items: [] };
// #7089: an absent target whose removal an earlier attempt committed (its push failed) joins the push like an
// unchanged one while the root is ahead of its upstream; on a root that is not ahead it completes without a push.
diff --git a/test/effect-git-secret-gate.test.ts b/test/effect-git-secret-gate.test.ts
index c47982642a..91cda30781 100644
--- a/test/effect-git-secret-gate.test.ts
+++ b/test/effect-git-secret-gate.test.ts
@@ -208,7 +208,7 @@ describe('#8896 pushGitRoot scans the commits it publishes', () => {
test('a commit the ledger records as a page write is not scanned; a commit-push commit still is', async () => {
const c = checkout();
const page = scriptCommit(c.root, 'notes/page.md', `Saved note with ${token}\n`);
- recordCommit(c.root, { sha: page, writer: 'effect', ref: null });
+ recordCommit(c.root, { sha: page, writer: 'effect', ref: null, verified: true });
expect(await withEnv(childEnv(c), () => pushGitRoot(c.root))).toEqual({ push: 'committed' });
expect(remoteTip(c)).toBe(page);
const script = scriptCommit(c.root, 'notes/deploy.md', `Deploy token ${token}\n`);
@@ -220,15 +220,20 @@ describe('#8896 pushGitRoot scans the commits it publishes', () => {
expect(remoteTip(c)).toBe(page);
}, 60_000);
- test('a page-write record that adopted an outside edit, or a ledger that cannot be read, leaves the commit scanned', async () => {
+ test('a page-write record that adopted an outside edit, an unverified one, or a ledger that cannot be read, leaves the commit scanned', async () => {
const c = checkout();
const adopted = scriptCommit(c.root, 'notes/page.md', `Adopted edit with ${token}\n`);
- recordCommit(c.root, { sha: adopted, writer: 'effect', ref: null, adopted: ['notes/page.md'] });
+ recordCommit(c.root, { sha: adopted, writer: 'effect', ref: null, verified: true, adopted: ['notes/page.md'] });
expect((await withEnv(childEnv(c), () => refusal(pushGitRoot(c.root)))).code).toBe('publish_secret_found');
+ const e = checkout();
+ const legacy = scriptCommit(e.root, 'notes/page.md', `Saved note with ${token}\n`);
+ recordCommit(e.root, { sha: legacy, writer: 'effect', ref: null });
+ expect((await withEnv(childEnv(e), () => refusal(pushGitRoot(e.root)))).code).toBe('publish_secret_found');
+
const d = checkout();
const page = scriptCommit(d.root, 'notes/page.md', `Saved note with ${token}\n`);
- recordCommit(d.root, { sha: page, writer: 'effect', ref: null });
+ recordCommit(d.root, { sha: page, writer: 'effect', ref: null, verified: true });
const ledger = join(d.root, '.git', 'gbrain', 'commit-ledger.jsonl');
rmSync(ledger); mkdirSync(ledger);
expect((await withEnv(childEnv(d), () => refusal(pushGitRoot(d.root)))).code).toBe('publish_secret_found');
@@ -243,6 +248,24 @@ describe('#8896 pushGitRoot scans the commits it publishes', () => {
}, 60_000);
});
+/**
+ * A PATH whose `git` runs `step` once (`{git}` in it is the real git), before or after the first call whose arguments
+ * contain `match`. The real git runs with the original PATH, so a git that is itself a PATH-resolving shim never finds
+ * this wrapper again.
+ */
+function racingGit(c: Checkout, match: string, when: 'before' | 'after', step: string): string {
+ const path = process.env.PATH ?? '', real = `PATH='${path}' '${Bun.which('git')!}'`;
+ const bin = join(c.home, 'race-bin'), mark = join(c.home, 'raced');
+ const hook = `if [ ! -f '${mark}' ]; then touch '${mark}'; ${step.replaceAll('{git}', real)}; fi`;
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'git'), ['#!/bin/sh',
+ when === 'before' ? `case " $* " in *" ${match} "*) ${hook};; esac` : '',
+ `${real} "$@"`, 'code=$?',
+ when === 'after' ? `case " $* " in *" ${match} "*) if [ $code -eq 0 ]; then ${hook}; fi;; esac` : '',
+ 'exit $code', ''].join('\n'), { mode: 0o755 });
+ return `${bin}:${path}`;
+}
+
interface ManagedWrite { engine: BrainEngine; sourceId: string; worktreeId: string; runEffects: () => Promise<void>; effect: () => Promise<{ state: string; error_code: string | null }> }
/** A managed source on the checkout with git durability on; `script` commits into the checkout before one page write whose Git effect is queued. */
@@ -341,16 +364,9 @@ describe('#8896 through the effect worker', () => {
test('a script commit that lands right after the effect commit is not ledgered as a page write, so its secret holds the push', async () => {
const c = checkout();
const before = remoteTip(c);
- const real = Bun.which('git')!;
- const bin = join(c.home, 'race-bin'), mark = join(c.home, 'raced');
- mkdirSync(bin);
- writeFileSync(join(bin, 'git'), [
- '#!/bin/sh', `'${real}' "$@"`, 'code=$?',
- `case " $* " in *" commit --only "*) if [ $code -eq 0 ] && [ ! -f '${mark}' ]; then touch '${mark}';`,
- ` mkdir -p '${c.root}/scripts-out'; printf 'Deploy token %s\\n' '${token}' > '${c.root}/scripts-out/race.md';`,
- ` '${real}' -C '${c.root}' add scripts-out/race.md && '${real}' -C '${c.root}' -c core.hooksPath=/dev/null commit -q -m 'script races the effect'; fi;; esac`,
- 'exit $code', ''].join('\n'), { mode: 0o755 });
- await withEnv({ PATH: `${bin}:${process.env.PATH}` }, () => managedWrite(c, () => {}, async w => {
+ const PATH = racingGit(c, 'commit --only', 'after', `mkdir -p '${c.root}/scripts-out'; printf 'Deploy token %s\\n' '${token}' > '${c.root}/scripts-out/race.md';`
+ + ` {git} -C '${c.root}' add scripts-out/race.md && {git} -C '${c.root}' -c core.hooksPath=/dev/null commit -q -m 'script races the effect'`);
+ await withEnv({ PATH }, () => managedWrite(c, () => {}, async w => {
await w.runEffects();
expect(git(c.root, 'log', '-1', '--format=%s').trim()).toBe('script races the effect');
expect(await w.effect()).toMatchObject({ error_code: 'publish_secret_found' });
@@ -358,6 +374,32 @@ describe('#8896 through the effect worker', () => {
}));
}, 180_000);
+ test('a script amending the effect commit (same parent) is not ledgered as a page write, so its secret holds the push', async () => {
+ const c = checkout();
+ const before = remoteTip(c);
+ const PATH = racingGit(c, 'commit --only', 'after', `mkdir -p '${c.root}/scripts-out'; printf 'Deploy token %s\\n' '${token}' > '${c.root}/scripts-out/race.md';`
+ + ` {git} -C '${c.root}' add scripts-out/race.md && {git} -C '${c.root}' -c core.hooksPath=/dev/null commit -q --amend --no-edit`);
+ await withEnv({ PATH }, () => managedWrite(c, () => {}, async w => {
+ await w.runEffects();
+ expect(git(c.root, 'log', '-1', '--format=%s').trim()).not.toBe('script races the effect');
+ expect(git(c.root, 'show', '--name-only', '--format=', 'HEAD').split('\n')).toContain('scripts-out/race.md');
+ expect(await w.effect()).toMatchObject({ error_code: 'publish_secret_found' });
+ expect(remoteTip(c)).toBe(before);
+ }));
+ }, 180_000);
+
+ test('a page file changed after the effect checked its bytes is not ledgered as verified, so the changed bytes are scanned', async () => {
+ const c = checkout();
+ const before = remoteTip(c);
+ const PATH = racingGit(c, 'add -A', 'before', `printf 'Deploy token %s\\n' '${token}' >> '${c.root}/notes/acme-example.md'`);
+ await withEnv({ PATH }, () => managedWrite(c, () => {}, async w => {
+ await w.runEffects();
+ expect(git(c.root, 'show', 'HEAD:notes/acme-example.md')).toContain(token);
+ expect(await w.effect()).toMatchObject({ error_code: 'publish_secret_found' });
+ expect(remoteTip(c)).toBe(before);
+ }));
+ }, 180_000);
+
test('a parked publish_secret_found effect is released by retry-effects --parked-pushes once the value is allowlisted', async () => {
const c = checkout();
const before = remoteTip(c);
diff --git a/test/persistence-git-removal-push-7089.test.ts b/test/persistence-git-removal-push-7089.test.ts
index dd86391653..50991a2c59 100644
--- a/test/persistence-git-removal-push-7089.test.ts
+++ b/test/persistence-git-removal-push-7089.test.ts
@@ -125,7 +125,7 @@ for (const kind of testBackends()) describe(`#7089 removal commits are pushed on
expect((await gitConvergenceCheck(engine))?.status).toBe('ok');
localCommit(repo);
const check = await gitConvergenceCheck(engine);
- expect(check).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', repo.root],
+ expect(check).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--scan-secrets', '--path', repo.root],
actor: 'agent', verify: { argv: expect.arrayContaining(['doctor', 'git_convergence']) } } });
expect(check!.message).toContain('no Git effect queued, running or parked');
expect((check!.details as { roots: unknown[] }).roots).toEqual([expect.objectContaining({ root: repo.root, ahead: 1, stranded: true })]);
diff --git a/test/persistence-git-subdir-root-7091.test.ts b/test/persistence-git-subdir-root-7091.test.ts
index 6aa8dd4386..d50ce67756 100644
--- a/test/persistence-git-subdir-root-7091.test.ts
+++ b/test/persistence-git-subdir-root-7091.test.ts
@@ -135,7 +135,7 @@ for (const kind of testBackends()) describe(`#7091 a source root below the Git t
writeFileSync(join(top.root, 'outside.md'), 'outside\n');
git(top.root, 'add', 'outside.md'); git(top.root, 'commit', '-q', '-m', 'Local commit');
const ahead = await gitConvergenceCheck(engine);
- expect(ahead).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', top.root], actor: 'agent' } });
+ expect(ahead).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--scan-secrets', '--path', top.root], actor: 'agent' } });
expect((ahead!.details as { roots: unknown[] }).roots).toEqual([expect.objectContaining({ root: top.root, ahead: 1, stranded: true })]);
git(top.root, 'push', '-q');
@@ -146,7 +146,7 @@ for (const kind of testBackends()) describe(`#7091 a source root below the Git t
writeFileSync(join(top.root, page), edited(1));
const dirty = await gitConvergenceCheck(engine);
expect(dirty).toMatchObject({ status: 'warn', fix: { ask_user: true, actor: 'user', argv: ['gbrain', 'git', 'commit-push', '--path', top.root, '-m', 'gbrain: persist canonical memory update', '--', page],
- then: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', top.root] } } });
+ then: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--scan-secrets', '--path', top.root] } } });
expect((dirty!.details as { roots: unknown[] }).roots).toEqual([expect.objectContaining({ root: top.root, stranded: true, uncommitted_pages: [page] })]);
const fixed = commitAndPush({ repo: top.root, cwd: top.root, paths: [page], message: 'gbrain: persist canonical memory update' });