Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Scan every earlier local commit before pushing from an unmanaged checkout (#8902)

garrytan60a7162a13bc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cf2b584c82..5b2d883e3e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,21 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**Pushes from an unmanaged checkout now scan every commit they publish for secrets, not only the files they just wrote.** Four gbrain pushes from a checkout that is not a managed worktree carried earlier local commits to the remote unscanned: the access-policy commit, the durability-scaffolding commit, `gbrain sources push` (which scanned only its own staged files, then pushed the whole branch tip, even with nothing new to commit) and the first push of `gbrain bootstrap repo` after the remote branch was gone (which scanned only the current tree). A credential a script committed with plain `git commit`, including one a later commit removed or one in a commit message, went out with them. Each now runs the range scan managed publishes use over what the remote lacks (the whole history when the remote has no such branch) and refuses `publish_secret_found` or `publish_scan_unreadable`, with nothing pushed and the local commits kept. `gbrain sources push` pushes the exact commit it scanned, leased on the remote tip it read, so a remote rewound in between is scanned again. An allowlist edit that `gbrain sources push` or `gbrain bootstrap repo` commits itself, after scanning it, still publishes; one a script committed is left to the user. Remoteless checkouts, managed worktrees and repo-less brains are unchanged, and the policy command's retry hint keeps `--scan-secrets`.
+
+Reported and first fixed by @javieraldape (#9159).
+
+### Itemized changes
+
+- `src/core/access/policy-git.ts`, `src/core/brain-repo-durability.ts`: the policy and scaffolding commits publish with `scanSecrets`; a scaffolding refusal names its code in the harden step.
+- `src/core/workspace-push.ts`: before the push, `stagedScanPublishRefusal` over `origin/<branch>..HEAD`, then `git push --force-with-lease=refs/heads/<branch>:<scanned tip> origin <sha>:refs/heads/<branch>`; a local branch that does not contain the remote tip is not pushed.
+- `src/core/bootstrap/repo.ts`: both first pushes scan the branch they push, with its whole history, and refuse if it moved during the scan (`scanHistory` option, a seam for runner fakes); `src/commands/bootstrap.ts` prints a refusal's code and next step.
+- `src/core/git/commit-push.ts`: a scanned publish whose remote has no such branch yet (no tracking ref) scans the whole history and leases the push on the branch being absent, where it used to refuse `publish_scan_unreadable`.
+- `src/core/git/range-secret-scan.ts`: `stagedScanPublishRefusal`, the range refusal with gate changes in `workspace_push` and `bootstrap` ledger commits exempt, and files over the range scan's cap exempt in `workspace_push` commits (its staged scan streams them up to 512 MiB).
+- Tests: `test/unmanaged-push-history-scan-8902.serial.test.ts` (each path against a local bare remote: a removed credential, a credential in a commit message, clean history, a remoteless policy commit, allowlist edits, a rewound remote).
+
## [0.60.675.0] - 2026-11-11
**Tool calls through native OpenAI models no longer fill every optional argument with a placeholder.** gbrain's tool loop (subagent jobs and SkillOpt rollouts) sends OpenAI models through the Responses API, and that API treats a tool definition with no `strict` field as strict: it marks every property required, so the model has to invent a value for each optional argument. A `get_page` call came back with a zero-line window and an empty byte range, which gbrain's own argument checks then refused. Native OpenAI tool definitions now say `strict: false`, so the schema's own `required` list holds and the model sends only the arguments it means. Anthropic, Google and the OpenAI-compatible providers (chat completions) send the same request as before. Reported and first fixed by @akinduroifedayo.
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.md
index a0062bf2f8..d7d9403f55 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. After the commit step (and its index restore) `commitPaths` returns 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 of `commit --only`; `commitAndPush` (classic, managed and remoteless) and `commitPathsLocked` then throw `commit_paths_skipped`, or `writer_coordinator_required` for a page in a managed worktree (its `put_page` fix names the managed source), once the rest is committed and, on a classic checkout, pushed (`detail`: `skipped`, `committed`, `pushed`, `branch`, and `publish` when the push failed too). 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`; it runs the same skipped-path check after its commit and reports `commit_paths_skipped` after the push (exit 1, or 4 when the push failed). 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`, `test/git-commit-push-skipped-paths-gst2116.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`. Commits the commit ledger records as page writes are not scanned: door and hosted-repository commits, and Git effect commits recorded `verified` (`effectCommit` in `effect-git.ts` builds the commit with `commit-tree` and moves HEAD with an `update-ref` compare-and-swap, so the recorded sha is gbrain's own; `verified` when each staged blob is the bytes whose sha256 the effect recorded); 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/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` (`effectCommit` in `effect-git.ts` builds the commit with `commit-tree` and moves HEAD with an `update-ref` compare-and-swap, so the recorded sha is gbrain's own; `verified` when each staged blob is the bytes whose sha256 the effect recorded); adopted records, records without `verified` and an unreadable ledger leave the commits scanned. Doctor `git_convergence`'s agent push fixes pass `--scan-secrets` too. `stagedScanPublishRefusal(root, base, target)` is the same refusal for `gbrain sources push` (`workspace-push.ts`: `origin/<branch>..HEAD` after its pull, then a push of that exact sha leased on the scanned tip, and no push when the local branch lacks the remote tip) and both first pushes of `gbrain bootstrap repo` (`bootstrap/repo.ts`, the whole history; `scanHistory` is the runner-fake seam), with gate changes exempt in commits the ledger records as `workspace_push` or `bootstrap`, whose blobs those writers scanned staged with the same allowlist. The access-policy commit (`access/policy-git.ts`) and the durability-scaffolding commit (`brain-repo-durability.ts`) publish through `commitAndPush` with `scanSecrets` (#8902). Test: `test/unmanaged-push-history-scan-8902.serial.test.ts`.
- `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 6249ca883a..ce31cdd103 100644
--- a/docs/guides/shared-checkout-git.md
+++ b/docs/guides/shared-checkout-git.md
@@ -189,7 +189,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, 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 by the sha gbrain created for it, when its files held the bytes the effect wrote, so an amended or reworded copy is 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, doctor `git_convergence`'s push fixes, the access-policy and durability-scaffolding commits, `gbrain sources push` and the first push of `gbrain bootstrap repo` (#8902; there the remote has no branch yet, so the whole history is scanned). 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 by the sha gbrain created for it, when its files held the bytes the effect wrote, so an amended or reworded copy is 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. The exception is the commit `gbrain sources push` or `gbrain bootstrap repo` makes itself from files it has just scanned with that allowlist. 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/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f35f590250..2bd7148f2e 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -28,7 +28,7 @@ src/core/minions/queue.ts 2548 ratchet grown #4078 + megawave probe-liveness unl
src/commands/init.ts 1892 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts); +1 GBRA-199: --surface help line names the default verbs listing; +7 GBRA-248 W0b: the implicit-keyless marker on both zero-key fallbacks, the deferred-hint gate on both engine paths and the kept-identity call in both (logic in commands/init-embedding-plane.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
-src/commands/bootstrap.ts 2154 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts); +4 #8426/#8428: the user-scope MCP registration, its verify and the workspace and Codex SessionEnd hooks start gbrain through the hook launcher (logic in core/setup/hook-launcher.ts); +2 #8435: the user-global opencode entry starts serve through the hook launcher (logic in core/setup/hook-launcher.ts); +1 GBRA-224: INSTALL_PIN import (core/install-ref.ts; re-summed at the GBRA-346 merge: master 2153 + 1)
+src/commands/bootstrap.ts 2160 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts); +4 #8426/#8428: the user-scope MCP registration, its verify and the workspace and Codex SessionEnd hooks start gbrain through the hook launcher (logic in core/setup/hook-launcher.ts); +2 #8435: the user-global opencode entry starts serve through the hook launcher (logic in core/setup/hook-launcher.ts); +1 GBRA-224: INSTALL_PIN import (core/install-ref.ts; re-summed at the GBRA-346 merge: master 2153 + 1); +6 #8902: bootstrap prints an OperationError refusal with its code and next step
src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)
src/commands/sources.ts 2130 ratchet +3 url_source_origin: sources record-origin dispatch and help rows (body in sources-record-origin.ts, logic in core/url-source-origin.ts); +3 PR B: sources guard dispatch and help rows (body in sources-guard.ts); +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured); +2 GBRA-220 PR 2: the unmanaged sources add routes --kind meetings|slack to the shared lifecycle parser (body in sources-add-api.ts); re-summed at the master b85dd645 merge (2102 measured); +2 #7701: the archived field of SourceListEntry and its list entry (sources list now marks archived sources; an interface field cannot move): re-summed at the 0.60.583.0 merge: 2102 + 2; +1 GST-1113: sources federate refuses a QM scope source (one line; the check lives in core/access/attest-sources.ts), re-summed at the 0.60.594.0 gate-ahead: 2107 + 1; +5 GST-1113 /ship fix round: sources federate checks the scope mark and writes the config in one transaction under the source row lock (the check lives in core/access/attest-sources.ts); +7 #8982: sources federate and restore print the remote-written pages without readers they expose, federate --json, the prior federation read under the row lock (the read and the lines live in core/access/federation-exposure.ts); +6 sources git-reconcile dispatch, header and help rows (body in sources-git-reconcile.ts), re-summed at the master d25bd680 merge (2124 + 6)
src/core/link-extraction.ts 2424 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edges
@@ -48,5 +48,5 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
-src/core/behavior-change-notice.ts 1727 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3
+src/core/behavior-change-notice.ts 1728 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; +1 #8902 unmanaged_push_history_scan_8902 row
src/commands/auth.ts 1503 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot move
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index 65fe3e411d..d0c87895ee 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -2,6 +2,7 @@
# class: R1 (process.env mutation) | R2 (mock.module) | global-state (other process-wide state) | exclusive (EXCLUSIVE_FILES in scripts/run-serial-tests.sh).
# Before adding a row, run: bash scripts/check-test-isolation.sh --as-parallel <file> (docs/TESTING.md#when-to-quarantine-instead-of-fix)
path class reason
+test/unmanaged-push-history-scan-8902.serial.test.ts R1 R1: mutates HOME, GBRAIN_HOME and GBRAIN_GIT_ALLOW_FILE_TRANSPORT for real policy, scaffolding, sources push and bootstrap pushes to local bare remotes
test/http-db-config.serial.test.ts global-state global-state: binds HTTP listeners; drains process-wide pending eval capture registry; withEnv scopes GBRAIN_HOME and GBRAIN_CONTRIBUTOR_MODE
test/access-as.serial.test.ts global-state global-state: spawns real gbrain CLI children (src/cli.ts --as) that each open one on-disk PGLite brain and take its file lock in a temp GBRAIN_HOME; the cases seed and read that one brain in order
test/access-binding.serial.test.ts global-state global-state: spawns real gbrain CLI children (auth create|rescope|register-client, access member) that each open one on-disk PGLite brain and take its file lock in a temp GBRAIN_HOME; later cases read the bindings earlier ones wrote
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts
index aa4a3c37e6..d67dbc1d0e 100644
--- a/src/commands/bootstrap.ts
+++ b/src/commands/bootstrap.ts
@@ -111,6 +111,7 @@ import {
import { verifyWorkspace, resolveVerifySourceId, deriveWorkspaceSourceId } from '../core/bootstrap/verify.ts';
import { auditWritebackContract, repairWritebackContract } from '../core/bootstrap/contract.ts';
import { INSTALL_PIN } from '../core/install-ref.ts';
+import { OperationError } from '../core/ops/contract.ts';
export const BOOTSTRAP_HELP = `gbrain bootstrap — paste-in agent install (Claude Code / Codex / opencode)
@@ -2146,6 +2147,11 @@ export async function runBootstrap(args: string[], opts: RunBootstrapOpts = {}):
logPhase(logCtx, logPhaseName, 'error', t0);
return 1;
}
+ if (e instanceof OperationError) {
+ console.error(`bootstrap ${sub} refused: ${e.code}: ${e.message}${e.suggestion ? `\nNext: ${e.suggestion}` : ''}`);
+ logPhase(logCtx, logPhaseName, 'error', t0);
+ return 1;
+ }
console.error(`bootstrap ${sub} failed: ${e instanceof Error ? e.message : String(e)}`);
console.error(SUPPORT_HINT);
logPhase(logCtx, logPhaseName, 'error', t0);
diff --git a/src/core/access/policy-git.ts b/src/core/access/policy-git.ts
index 2883854d4d..73c0dfe380 100644
--- a/src/core/access/policy-git.ts
+++ b/src/core/access/policy-git.ts
@@ -212,12 +212,12 @@ export async function commitPolicyFile(root: string, relPath: string, edit: (cur
const next = edit(current);
writeFileSync(file, next);
try {
- const r = commitAndPush({ repo: root, cwd: root, paths: [file], message });
+ const r = commitAndPush({ repo: root, cwd: root, paths: [file], message, scanSecrets: true });
return { outcome: r.outcome, commit: r.committed ?? r.sha, path: relPath,
...(r.outcome === 'committed_local' ? { note: 'Committed locally; this checkout has no remote or is managed, so nothing was pushed.' } : {}) };
} catch (e) {
if (e instanceof OperationError && (e.code === 'push_unconfirmed' || (e as { canonical?: string }).canonical === 'push_unconfirmed') && e.detail) {
- return { outcome: 'committed_not_pushed', commit: String(e.detail), path: relPath, note: 'Committed locally; the push is unconfirmed. Rerun gbrain git commit-push --push-only to publish it.' };
+ return { outcome: 'committed_not_pushed', commit: String(e.detail), path: relPath, note: 'Committed locally; the push is unconfirmed. Rerun gbrain git commit-push --push-only --scan-secrets to publish it.' };
}
if (gitShow(root, 'HEAD', relPath) !== next) {
if (current === null) rmSync(file, { force: true }); else writeFileSync(file, current);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 689d564c00..bcb3fb2e56 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1529,6 +1529,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.673.0', id: 'autopilot_git_reconcile_gbra386', text: 'Autopilot now runs the new `gbrain sources git-reconcile` each tick: every source checkout on the host with an upstream fast-forwards when it is only behind, and one gbrain cloned for the source publishes its local commits (secret scan, rewrite check bound to the push, merged with the upstream in memory, never rebased or forced); a managed checkout goes through `gbrain sources refresh`, with its Git durability rule. A checkout gbrain did not clone keeps its local commits unless `sources.refresh_publish_diverged` is `true`, and a source with sync off is skipped. A refusal is logged and retried next tick. `autopilot.git_pull false` skips it; `sources.refresh_publish_diverged false` leaves local commits unpublished on every source, and `gbrain sources set-sync <id> off` leaves one source out (it also stops that source\'s automatic sync).' },
{ since: '0.60.673.0', id: 'unknown_drift_history_rescreen', text: 'A `file_drift` hold on a page with no import record that an earlier release held after comparing the page only with its file at the last synced commit is now screened once more on the next sync: when the page still holds one of its file\'s earlier committed versions (only Git changed since), the Git edit imports and the hold clears; otherwise the hold stays, unchanged, and is not screened again.' },
{ since: '0.60.673.0', id: 'refresh_abandon_members_gst1465', text: '`gbrain sources refresh --abandon` of a `recovery_required` refresh now also refuses when a member\'s managed sync imported or deleted pages after the refresh began, even with its `last_commit` still at the start commit (a pass its budget stopped), and refuses `sync_drain_lease_held` while a member\'s sync pass still holds its drain lease, so the database is never left ahead of the checkout. At a HEAD past the upstream commit it names `--resume` instead of a reset. Members synced to diverged lines, or to a commit git cannot place, now get their own refusal (merge those lines, or fetch the commit) instead of a fast-forward that `--resume` would refuse again, and the refusals name the revert route for a deliberate rollback. Writer status read off the owner host names no step for such a refresh.' },
+ { since: 'TBD', id: 'unmanaged_push_history_scan_8902', text: 'Four pushes from a checkout that is not a managed worktree now scan every local commit they publish for secrets, not only what they just wrote: the access-policy commit (`gbrain access rule` and the other policy writers), the durability-scaffolding commit of `gbrain sources harden`, `gbrain sources push`, and the first push of `gbrain bootstrap repo` (the whole history, since the remote has no such branch yet). A credential that a commit made with plain `git commit` added, even one a later commit removed, or one in a commit message, now refuses `publish_secret_found` naming the file, line, rule and commit (never the value), and nothing is pushed; history the scan cannot read in full refuses `publish_scan_unreadable`. The local commits stay where they are. `gbrain sources push` now pushes the exact commit it scanned, leased on the remote tip it read, and an allowlist (`.gbrain-scan-allow`) edit it commits itself still publishes; one a script committed is left for the user to review and push. Remove the value from the unpublished commits, or allowlist a false positive by fingerprint, then rerun.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/bootstrap/repo.ts b/src/core/bootstrap/repo.ts
index 0ae197d221..5f3c13d3b3 100644
--- a/src/core/bootstrap/repo.ts
+++ b/src/core/bootstrap/repo.ts
@@ -38,6 +38,8 @@ import { invalidateBackupStatus } from '../backup/status-file.ts';
import { realpathOrResolve } from '../path-confine.ts';
import { defaultRunner, isProxyBlocked403, parseGithubOwnerRepo, type ExecRunner } from '../repo-visibility.ts';
import { detectExecutionEnvironment } from '../execution-env.ts';
+import { stagedScanPublishRefusal } from '../git/range-secret-scan.ts';
+import type { OperationError } from '../ops/contract.ts';
import { loadWorkspaceAllowlist, scanFiles, SCAN_ALLOW_FILENAME, type SecretFinding } from '../secret-scan.ts';
import { SECRET_SCAN_REFUSAL_DOCS } from '../workspace-push.ts';
import { shellQuote } from '../mcp-registration.ts';
@@ -561,6 +563,7 @@ async function ensureRemoteHasWorkspace(
workspaceDir: string,
owner: string,
name: string,
+ scan: HistoryScan,
): Promise<void> {
const branch = await currentBranch(runner, workspaceDir);
const ls = await runner(['git', '-C', workspaceDir, 'ls-remote', '--heads', 'origin', branch]);
@@ -570,6 +573,7 @@ async function ensureRemoteHasWorkspace(
await ensureWorkspaceCommit(runner, workspaceDir);
const pushBranch = await currentBranch(runner, workspaceDir);
await assertOriginMatches(runner, workspaceDir, owner, name);
+ await assertHistoryPublishable(runner, workspaceDir, pushBranch, scan);
const push = await runner(['git', '-C', workspaceDir, 'push', '-u', 'origin', pushBranch]);
if (push.code !== 0) {
throw new BootstrapError(
@@ -589,6 +593,32 @@ export interface CreatePrivateRepoOptions {
runner?: ExecRunner;
/** The gbrain home holding the install receipt (default: configDir()). */
gbrainHomeDir?: string;
+ /** The refusal for publishing `target` and its whole history (default: the range secret scan; a seam for runner fakes). */
+ scanHistory?: HistoryScan;
+}
+
+type HistoryScan = (workspaceDir: string, target: string) => OperationError | null;
+const scanWholeHistory: HistoryScan = (workspaceDir, target) => stagedScanPublishRefusal(workspaceDir, '', target);
+
+/**
+ * #8902: a first push publishes the branch's whole history, including commits a script made with plain `git commit`
+ * that the staged scan never saw, so the commit about to be pushed is scanned with all of its history; a finding or
+ * an unreadable history refuses (publish_secret_found / publish_scan_unreadable) and nothing leaves the machine.
+ */
+async function assertHistoryPublishable(runner: ExecRunner, workspaceDir: string, branch: string, scan: HistoryScan): Promise<void> {
+ const tip = async () => {
+ const ref = await runner(['git', '-C', workspaceDir, 'rev-parse', '--verify', `refs/heads/${branch}^{commit}`]);
+ if (ref.code !== 0) {
+ throw new BootstrapError('REPO_CREATE_FAILED', `could not read branch ${branch} before the first push: ${ref.stderr.trim() || `exit ${ref.code}`} — nothing was pushed`);
+ }
+ return ref.stdout.trim();
+ };
+ const scanned = await tip();
+ const refusal = scan(workspaceDir, scanned);
+ if (refusal) throw refusal;
+ if (await tip() !== scanned) {
+ throw new BootstrapError('REPO_CREATE_FAILED', `branch ${branch} moved while its history was scanned — nothing was pushed; re-run \`gbrain bootstrap repo\``);
+ }
}
export interface CreatePrivateRepoResult {
@@ -621,6 +651,7 @@ export async function createPrivateRepo(
): Promise<CreatePrivateRepoResult> {
const runner = opts.runner ?? defaultRunner;
const gbrainHomeDir = opts.gbrainHomeDir ?? configDir();
+ const scan = opts.scanHistory ?? scanWholeHistory;
// Gate 1: gh on PATH. Exit-code-2 semantics — the human installs gh.
const ghVersion = await runner(['gh', '--version']);
@@ -725,7 +756,7 @@ export async function createPrivateRepo(
// [FIX3] Don't report success on an empty remote — a prior run may have set
// origin but failed to push. Verify the remote has our branch; complete the
// (scan-gated) push if it doesn't.
- await ensureRemoteHasWorkspace(runner, workspaceDir, parsed.owner, parsed.name);
+ await ensureRemoteHasWorkspace(runner, workspaceDir, parsed.owner, parsed.name, scan);
// Record repo_url AFTER a successful push (clears pending): recording before
// push let a push failure look "done" to `bootstrap status` (repo_url
// present), so a re-run skipped the repo phase and never pushed the workspace.
@@ -816,6 +847,7 @@ export async function createPrivateRepo(
const branch = await currentBranch(runner, workspaceDir);
// [FIX4] Bind the verified privacy result to the actual push target.
await assertOriginMatches(runner, workspaceDir, login, name);
+ await assertHistoryPublishable(runner, workspaceDir, branch, scan);
const push = await runner(['git', '-C', workspaceDir, 'push', '-u', 'origin', branch]);
if (push.code !== 0) {
throw new BootstrapError(
diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.ts
index 70f676c071..e8cad50dfd 100644
--- a/src/core/brain-repo-durability.ts
+++ b/src/core/brain-repo-durability.ts
@@ -1295,12 +1295,13 @@ function commitScaffolding(repoPath: string, branch: string, redact: (s: string)
const resolver = findResolverFile(repoPath);
if (resolver) paths.push(relative(repoPath, resolver));
try {
- const r = commitAndPush({ repo: repoPath, paths, cwd: repoPath, message: 'chore(gbrain): install brain durability scaffolding', allowOutsideSourceRoot: true });
+ const r = commitAndPush({ repo: repoPath, paths, cwd: repoPath, message: 'chore(gbrain): install brain durability scaffolding', allowOutsideSourceRoot: true, scanSecrets: true });
if (r.branch !== branch) return { status: 'needs_attention', detail: `checkout is on ${r.branch}, not ${branch}` };
if (r.outcome === 'nothing_to_commit') return { status: 'ok', detail: 'scaffolding already committed' };
return { status: 'fixed', detail: `committed + pushed durability scaffolding${r.checkout === 'lagging' ? ` (checkout lagging: ${r.lagging_reason})` : ''}` };
} catch (e) {
- return { status: 'needs_attention', detail: redact(`scaffolding commit/push failed: ${(e as Error).message.slice(0, 140)}`) };
+ const code = (e as { code?: unknown }).code;
+ return { status: 'needs_attention', detail: redact(`scaffolding commit/push failed${typeof code === 'string' ? ` (${code})` : ''}: ${(e as Error).message.slice(0, 140)}`) };
}
}
diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.ts
index 4e6c2b9e12..659370e193 100644
--- a/src/core/git/commit-push.ts
+++ b/src/core/git/commit-push.ts
@@ -1106,9 +1106,9 @@ function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> |
let remoteTip = bound && !isAncestor(ctx.root, bound, candidate) ? bound : null;
if (!remoteTip) {
const lease = bound ?? (scanSecrets ? scannedBase : undefined);
- if (scanSecrets) assertNoSecretsInRange({ ...ctx, trackingRef: lease || ctx.trackingRef }, candidate);
+ if (scanSecrets) assertNoSecretsInRange({ ...ctx, trackingRef: lease! }, candidate);
const push = lease && !isAncestor(ctx.root, lease, candidate) ? null
- : remoteGit(ctx.root, 'push', [...(ctx.keepCheckout ? ['--no-verify'] : []), ...(lease ? [`--force-with-lease=${ctx.mergeRef}:${lease}`] : []), '--', ctx.remote, `${candidate}:${ctx.mergeRef}`]);
+ : remoteGit(ctx.root, 'push', [...(ctx.keepCheckout ? ['--no-verify'] : []), ...(lease !== undefined ? [`--force-with-lease=${ctx.mergeRef}:${lease}`] : []), '--', ctx.remote, `${candidate}:${ctx.mergeRef}`]);
if (push?.code === 0) return { sha: candidate, integrated, confirmed: 'push', ...notes() };
if (push) lastError = push.stderr.trim();
if (remoteContains(ctx, candidate)) return onRemote();
diff --git a/src/core/git/range-secret-scan.ts b/src/core/git/range-secret-scan.ts
index 9164dc5e22..af3324b4bb 100644
--- a/src/core/git/range-secret-scan.ts
+++ b/src/core/git/range-secret-scan.ts
@@ -258,6 +258,34 @@ export function scanRange(root: string, base: string, head: string, timeoutMs =
}
}
+/**
+ * Writers that commit only blobs they scanned, staged, with the workspace allowlist the range scan also applies
+ * (`gbrain sources push`, `gbrain bootstrap repo`): the allowlist edit such a commit carries is the user's answer to that
+ * scan, so it is not refused as a gate change. Its content is still scanned. `gbrain sources push` also streams staged
+ * files past the range scan's cap (up to its own 512 MiB ceiling), so a file in its commit the range scan calls too large
+ * was scanned; bootstrap's file scan skips files over the cap, so its large files stay refused.
+ */
+const STAGED_SCAN_WRITERS: ReadonlySet<string> = new Set(['workspace_push', 'bootstrap']);
+const STREAMED_SCAN_WRITERS: ReadonlySet<string> = new Set(['workspace_push']);
+
+/**
+ * The refusal for a push by `gbrain sources push` or `gbrain bootstrap repo` of `base..target` (an empty `base` covers
+ * the whole history): the same scan and refusals as an automatic publish, except for what those writers' own commits
+ * already passed (see STAGED_SCAN_WRITERS).
+ */
+export function stagedScanPublishRefusal(root: string, base: string, target: string): OperationError | null {
+ const scan = scanRange(root, base, target);
+ if (!scan.gate_changes.length && !scan.unscanned.length) return rangeSecretRefusal(root, base, target, scan);
+ const own = new Map<string, string>();
+ try {
+ const common = must(run(root, ['rev-parse', '--path-format=absolute', '--git-common-dir'], Date.now() + 60_000), 'rev-parse').toString().trim();
+ for (const record of readLedger(common)) if (record.e === 'commit' && STAGED_SCAN_WRITERS.has(record.writer)) own.set(record.sha, record.writer);
+ } catch { /* an unreadable ledger exempts nothing */ }
+ return rangeSecretRefusal(root, base, target, { ...scan,
+ gate_changes: scan.gate_changes.filter(change => !own.has(change.commit)),
+ unscanned: scan.unscanned.filter(item => item.path === MESSAGE_PATH || !STREAMED_SCAN_WRITERS.has(own.get(item.commit) ?? '')) });
+}
+
/**
* The automatic-publish refusal for the commits in `base..target` of `root`, shared by every publish that scans: null
* when the scan read the whole range and found nothing; `publish_scan_unreadable` when it could not read it all;
diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.ts
index 7f72cf5754..993d284323 100644
--- a/src/core/workspace-push.ts
+++ b/src/core/workspace-push.ts
@@ -79,6 +79,7 @@ import { scanTextStream } from './secret-scan-stream.ts';
import { shellQuote } from './mcp-registration.ts';
import { gitChildEnv } from './git-env.ts';
import { recordCommit, recordIntent } from './git/commit-ledger.ts';
+import { stagedScanPublishRefusal } from './git/range-secret-scan.ts';
// ── Types ───────────────────────────────────────────────────────────────────
@@ -882,6 +883,34 @@ export function managedPushRefusal(dir: string, root: string | null | undefined,
return error;
}
+/**
+ * Step 7 of {@link workspacePush}: the push carries every local commit origin lacks, including ones a script made with
+ * plain `git commit` that the staged scan never saw, so the exact commit pushed is range-scanned against the remote tip
+ * it is leased on (#8902). A scan refusal is recorded and thrown; any other failure is returned; null when pushed.
+ */
+function pushScannedHead(root: string, branch: string, log: (line: string) => void): { status: 'error' | 'push_failed'; reason: string } | null {
+ const target = tryGit(root, ['rev-parse', '--verify', 'HEAD^{commit}']);
+ if (!target) return { status: 'error', reason: 'HEAD names no commit; nothing to push' };
+ const base = tryGit(root, ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branch}^{commit}`]) ?? '';
+ if (base && tryGit(root, ['merge-base', '--is-ancestor', base, target]) === null) {
+ return { status: 'push_failed', reason: `local ${branch} does not contain origin/${branch}; nothing pushed (rerun to pull first)` };
+ }
+ const refusal = stagedScanPublishRefusal(root, base, target);
+ if (refusal) {
+ log(`PUSH BLOCKED: ${refusal.code}: ${refusal.message}`);
+ writePushStatus({ ts: new Date().toISOString(), ok: false, code: refusal.code, reason: `${refusal.code}: ${refusal.message}`, ahead: aheadCount(root, branch), repoRoot: root });
+ throw refusal;
+ }
+ try {
+ git(root, [...pushSsrfFlags(), 'push', ...GIT_SSRF_SUBCOMMAND_FLAGS, `--force-with-lease=refs/heads/${branch}:${base}`, 'origin', `${target}:refs/heads/${branch}`], {
+ timeoutMs: 120_000, auth: true,
+ });
+ return null;
+ } catch (e) {
+ return { status: 'push_failed', reason: `git push failed: ${(e as Error).message.slice(0, 200)}` };
+ }
+}
+
export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspacePushResult> {
const log = (line: string) => opts.logger?.(line);
@@ -1158,17 +1187,8 @@ export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspaceP
}
// 7. push — even with no new commit (a prior failure may have left local ahead).
- try {
- git(root, [...pushSsrfFlags(), 'push', ...GIT_SSRF_SUBCOMMAND_FLAGS, 'origin', `HEAD:${branch}`], {
- timeoutMs: 120_000, auth: true,
- });
- } catch (e) {
- return finish({
- ok: false, status: 'push_failed', repoRoot: root, branch, committed,
- ahead: aheadCount(root, branch),
- reason: `git push failed: ${(e as Error).message.slice(0, 200)}`,
- });
- }
+ const failed = pushScannedHead(root, branch, log);
+ if (failed) return finish({ ok: false, ...failed, repoRoot: root, branch, committed, ahead: aheadCount(root, branch) });
const ahead = aheadCount(root, branch) ?? 0;
log(`pushed ${root} → origin/${branch}${committed ? ' (new commit)' : ''}`);
diff --git a/test/bootstrap-repo.test.ts b/test/bootstrap-repo.test.ts
index bfe7e06ddc..4ef15ee4cf 100644
--- a/test/bootstrap-repo.test.ts
+++ b/test/bootstrap-repo.test.ts
@@ -70,6 +70,9 @@ const INITIALIZED_MANIFEST: AgentManifest = {
let ws: string;
let home: string;
+/** The fake runner holds no real history; the history scan itself is covered by test/unmanaged-push-history-scan-8902.serial.test.ts. */
+const noHistoryScan = () => null;
+
beforeEach(() => {
ws = mkdtempSync(join(tmpdir(), 'gbrain-bootstrap-ws-'));
home = mkdtempSync(join(tmpdir(), 'gbrain-bootstrap-home-'));
@@ -123,7 +126,7 @@ async function expectBootstrapError(p: Promise<unknown>): Promise<BootstrapError
describe('createPrivateRepo', () => {
test('create flow: name collision → -2 suffix, identity set, privacy verified, receipt + GITHUB.md updated', async () => {
const { runner, calls } = makeRunner(happyRules());
- const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home });
+ const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan });
expect(result.name).toBe('test-agent-workspace-2');
expect(result.url).toBe('https://github.com/alice/test-agent-workspace-2');
@@ -165,7 +168,7 @@ describe('createPrivateRepo', () => {
{ key: 'diff --cached --name-only', code: 0, stdout: 'agent.json\nGITHUB.md\n' },
]),
);
- const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home });
+ const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan });
expect(result.reused).toBe(false);
// The commit was created before the push (no empty-remote push).
@@ -190,7 +193,7 @@ describe('createPrivateRepo', () => {
{ key: 'diff --cached --name-only', code: 0, stdout: '' },
]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('REPO_CREATE_FAILED');
expect(err.message).toContain('no files to commit');
expect(calls.some((c) => c.join(' ').includes('push -u origin'))).toBe(false);
@@ -206,7 +209,7 @@ describe('createPrivateRepo', () => {
{ key: 'diff --cached --name-only', code: 0, stdout: 'leak.md\n' },
]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('SECRET_SCAN_BLOCKED');
expect(err.message).not.toContain('sk-A1b2C3d4'); // value never surfaces
expect(err.message).toMatch(/leak\.md:1 \[openai\] sha256:[0-9a-f]{16}/);
@@ -232,7 +235,7 @@ describe('createPrivateRepo', () => {
{ key: 'repo create', code: 0 },
{ key: '--jq .private', code: 0, stdout: 'true\n' },
]);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('ORIGIN_EXISTS');
expect(err.message).toContain('verified-private');
expect(calls.some((c) => c.join(' ').includes('push -u origin'))).toBe(false); // nothing pushed
@@ -240,13 +243,13 @@ describe('createPrivateRepo', () => {
test('privacy verify says false → hard REPO_NOT_PRIVATE error', async () => {
const { runner } = makeRunner(happyRules([{ key: '--jq .private', code: 0, stdout: 'false\n' }]));
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('REPO_NOT_PRIVATE');
});
test('privacy verify 500 → VERIFY_UNAVAILABLE (distinct from not-private), tells the user to re-run', async () => {
const { runner } = makeRunner(happyRules([{ key: '--jq .private', code: 1, stderr: 'gh: HTTP 500 Internal Server Error' }]));
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('VERIFY_UNAVAILABLE');
expect(err.code).not.toBe('REPO_NOT_PRIVATE');
expect(err.message).toContain('re-run');
@@ -256,7 +259,7 @@ describe('createPrivateRepo', () => {
const { runner, calls } = makeRunner(
happyRules([{ key: 'remote get-url origin', code: 0, stdout: 'https://github.com/someone/else.git\n' }]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('ORIGIN_EXISTS');
expect(err.message).toContain('bootstrap attach');
// Refused before any create.
@@ -266,7 +269,7 @@ describe('createPrivateRepo', () => {
test('template manifest → TEMPLATE_UNINITIALIZED [CX2-1]', async () => {
writeManifest(ws, { ...INITIALIZED_MANIFEST, initialized: false });
const { runner } = makeRunner(happyRules());
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('TEMPLATE_UNINITIALIZED');
expect(err.message).toContain('bootstrap render');
});
@@ -274,7 +277,7 @@ describe('createPrivateRepo', () => {
test('absent manifest → NOT_A_WORKSPACE', async () => {
rmSync(join(ws, 'agent.json'));
const { runner } = makeRunner(happyRules());
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('NOT_A_WORKSPACE');
});
@@ -300,7 +303,7 @@ describe('createPrivateRepo', () => {
{ key: 'ls-remote --heads origin', code: 0, stdout: `deadbeef\trefs/heads/main\n` },
]),
);
- const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home });
+ const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan });
expect(result.reused).toBe(true);
expect(result.url).toBe(url);
expect(result.name).toBe('test-agent-workspace-2');
@@ -332,7 +335,7 @@ describe('createPrivateRepo', () => {
{ key: 'ls-remote --heads origin', code: 0, stdout: '' },
]),
);
- const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home });
+ const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan });
expect(result.reused).toBe(true);
expect(calls.some((c) => c.join(' ').includes('repo create'))).toBe(false);
// The deferred push was completed rather than false-succeeding on empty.
@@ -353,7 +356,7 @@ describe('createPrivateRepo', () => {
registrations: [],
});
const { runner } = makeRunner(happyRules([{ key: 'remote get-url origin', code: 0, stdout: `${url}\n` }]));
- const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home });
+ const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan });
expect(result.reused).toBe(true);
expect((readReceipt(home) as RepoReceipt).repo_url).toBe(url);
// Adoption must not clobber the existing receipt's brain ownership.
@@ -376,13 +379,13 @@ describe('createPrivateRepo', () => {
const { runner } = makeRunner(
happyRules([{ key: 'remote get-url origin', code: 0, stdout: 'https://github.com/mallory/swapped\n' }]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('ORIGIN_EXISTS');
});
test('gh missing → GH_MISSING with exit-code-2 semantics', async () => {
const { runner } = makeRunner([{ key: 'gh --version', code: 127, stderr: 'command not found' }]);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('GH_MISSING');
expect(err.exitCode).toBe(2);
});
@@ -392,7 +395,7 @@ describe('createPrivateRepo', () => {
{ key: 'gh --version', code: 0 },
{ key: 'auth status', code: 1, stderr: 'You are not logged into any GitHub hosts' },
]);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('GH_AUTH');
expect(err.exitCode).toBe(2);
expect(err.message).toContain('gh auth login');
@@ -410,7 +413,7 @@ describe('createPrivateRepo', () => {
// both flags on a `gh` that supports them — this test pins the exact
// argv so a regression back to the unscoped bare form is caught.
const { runner, calls } = makeRunner(happyRules());
- await createPrivateRepo(ws, { runner, gbrainHomeDir: home });
+ await createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan });
const authCall = calls.find((c) => c[0] === 'gh' && c[1] === 'auth' && c[2] === 'status');
expect(authCall).toEqual(['gh', 'auth', 'status', '--active', '--hostname', 'github.com']);
});
@@ -430,7 +433,7 @@ describe('createPrivateRepo', () => {
{ key: 'gh --version', code: 0, stdout: 'gh version 2.56.0 (2024-08-01)\n' },
]),
);
- await createPrivateRepo(ws, { runner, gbrainHomeDir: home });
+ await createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan });
const authCall = calls.find((c) => c[0] === 'gh' && c[1] === 'auth' && c[2] === 'status');
expect(authCall).toEqual(['gh', 'auth', 'status', '--hostname', 'github.com']);
});
@@ -439,7 +442,7 @@ describe('createPrivateRepo', () => {
const { runner, calls } = makeRunner(
happyRules([{ key: 'gh --version', code: 0, stdout: 'gh version 2.57.0 (2024-09-11)\n' }]),
);
- await createPrivateRepo(ws, { runner, gbrainHomeDir: home });
+ await createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan });
const authCall = calls.find((c) => c[0] === 'gh' && c[1] === 'auth' && c[2] === 'status');
expect(authCall).toEqual(['gh', 'auth', 'status', '--active', '--hostname', 'github.com']);
});
@@ -448,7 +451,7 @@ describe('createPrivateRepo', () => {
const { runner, calls } = makeRunner(
happyRules([{ key: 'gh --version', code: 0, stdout: 'not a recognizable version string\n' }]),
);
- await createPrivateRepo(ws, { runner, gbrainHomeDir: home });
+ await createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan });
const authCall = calls.find((c) => c[0] === 'gh' && c[1] === 'auth' && c[2] === 'status');
expect(authCall).toEqual(['gh', 'auth', 'status', '--hostname', 'github.com']);
});
@@ -490,7 +493,7 @@ describe('createPrivateRepo', () => {
{ key: '--jq .private', code: 0, stdout: 'true\n' },
]),
);
- const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home });
+ const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan });
expect(result.disposition).toBe('adopted');
expect(result.reused).toBe(true);
expect(result.url).toBe(url);
@@ -516,7 +519,7 @@ describe('createPrivateRepo', () => {
{ key: 'rev-parse --verify HEAD', code: 1, stderr: 'fatal: needed a single revision' },
]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('ORIGIN_NOT_EMPTY');
expect(err.message).toContain('EMPTY');
// No silent no-op: nothing pushed, repo_url never recorded.
@@ -535,7 +538,7 @@ describe('createPrivateRepo', () => {
{ key: 'ls-remote origin', code: 0, stdout: 'abc123\trefs/heads/main\n' },
]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('ORIGIN_NOT_EMPTY');
expect(calls.some((c) => c.join(' ').includes('push -u origin'))).toBe(false);
expect((readReceipt(home) as RepoReceipt).repo_url).toBeUndefined();
@@ -564,7 +567,7 @@ describe('createPrivateRepo', () => {
{ key: '--jq .private', code: 0, stdout: 'true\n' },
]),
);
- const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home });
+ const result = await createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan });
expect(result.disposition).toBe('adopted');
// pending bypassed the emptiness check — never probed all-refs ls-remote.
expect(calls.some((c) => c.join(' ') === `git -C ${ws} ls-remote origin`)).toBe(false);
@@ -579,7 +582,7 @@ describe('createPrivateRepo', () => {
const { runner, calls } = makeRunner(
happyRules([{ key: 'remote get-url origin', code: 0, stdout: `${url}\n` }]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('ORIGIN_EXISTS');
// Ownership fails first — never even probes the remote for emptiness.
expect(calls.some((c) => c.join(' ') === `git -C ${ws} ls-remote origin`)).toBe(false);
@@ -595,7 +598,7 @@ describe('createPrivateRepo', () => {
{ key: '--jq .private', code: 0, stdout: 'false\n' },
]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('REPO_NOT_PRIVATE');
});
@@ -608,7 +611,7 @@ describe('createPrivateRepo', () => {
{ key: 'ls-remote origin', code: 1, stderr: 'fatal: could not read from remote repository' },
]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('REMOTE_CHECK_FAILED');
expect(calls.some((c) => c.join(' ').includes('push -u origin'))).toBe(false);
});
@@ -629,7 +632,7 @@ describe('createPrivateRepo', () => {
{ key: 'push -u origin', code: 1, stderr: 'fatal: unable to access' },
]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('REPO_CREATE_FAILED');
// repo_url must NOT be recorded on push failure (else status false-reports done).
expect((readReceipt(home) as RepoReceipt).repo_url).toBeUndefined();
@@ -650,7 +653,7 @@ describe('createPrivateRepo', () => {
{ key: '--jq .private', code: 0, stdout: 'true\n' },
]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('SECRET_SCAN_BLOCKED');
expect(calls.some((c) => c.join(' ').includes('push -u origin'))).toBe(false);
});
@@ -679,7 +682,7 @@ describe('createPrivateRepo', () => {
{ key: 'ls-files -z', code: 0, stdout: 'secrets.md' }, // committed tree to scan
]),
);
- const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home }));
+ const err = await expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }));
expect(err.code).toBe('SECRET_SCAN_BLOCKED');
expect(calls.some((c) => c.join(' ').includes('push -u origin'))).toBe(false);
});
@@ -787,7 +790,7 @@ describe('createPrivateRepo cloud-sandbox guard [CLOUD_SANDBOX_REPO]', () => {
test('cloud sandbox + no existing origin → CLOUD_SANDBOX_REPO before any create call', async () => {
const { runner, calls } = makeRunner(happyRules());
const err = await withEnv({ CLAUDE_CODE_REMOTE: 'true' }, () =>
- expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home })),
+ expectBootstrapError(createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan })),
);
expect(err.code).toBe('CLOUD_SANDBOX_REPO');
expect(err.message).toContain('gbrain bootstrap attach');
@@ -799,7 +802,7 @@ describe('createPrivateRepo cloud-sandbox guard [CLOUD_SANDBOX_REPO]', () => {
test('local env: the same rules create normally (guard is cloud-only)', async () => {
const { runner, calls } = makeRunner(happyRules());
const result = await withEnv({ CLAUDE_CODE_REMOTE: undefined }, () =>
- createPrivateRepo(ws, { runner, gbrainHomeDir: home }),
+ createPrivateRepo(ws, { runner, gbrainHomeDir: home, scanHistory: noHistoryScan }),
);
expect(result.disposition).toBe('created');
expect(calls.some((c) => c.join(' ').includes('repo create'))).toBe(true);
diff --git a/test/unmanaged-push-history-scan-8902.serial.test.ts b/test/unmanaged-push-history-scan-8902.serial.test.ts
new file mode 100644
index 0000000000..7fe7fee47d
--- /dev/null
+++ b/test/unmanaged-push-history-scan-8902.serial.test.ts
@@ -0,0 +1,253 @@
+/**
+ * #8902: four pushes from an unmanaged checkout publish every local commit the remote lacks, so each scans that range,
+ * not only what it just wrote: the access-policy commit, the durability-scaffolding commit, `gbrain sources push` and the
+ * first push of `gbrain bootstrap repo`. Real git against local bare remotes (bootstrap's remote must be a GitHub URL,
+ * so its gh calls and its push are faked and recorded); synthetic credentials only. HOME, GBRAIN_HOME and the file
+ * transport switch are process-wide.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { commitPolicyFile, POLICY_FILE } from '../src/core/access/policy-git.ts';
+import { hardenBrainRepo } from '../src/core/brain-repo-durability.ts';
+import { createPrivateRepo, type ExecRunner, type RepoReceipt } from '../src/core/bootstrap/repo.ts';
+import { writeManifest, writeReceipt } from '../src/core/bootstrap/format.ts';
+import { defaultRunner } from '../src/core/repo-visibility.ts';
+import { workspacePush } from '../src/core/workspace-push.ts';
+import { SCAN_ALLOW_FILENAME } from '../src/core/secret-scan.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+
+const T = 60_000;
+const TOKEN = 'ghp_' + 'Qx7v'.repeat(9);
+let dir: string, root: string, remote: string, base: string;
+let saved: Record<string, string | undefined>;
+
+const git = (cwd: string, ...args: string[]) => execFileSync('git', ['-C', cwd, '-c', 'protocol.file.allow=always', ...args],
+ { encoding: 'utf8', env: process.env, stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const remoteTip = () => git(remote, 'rev-parse', 'refs/heads/main');
+const plainCommit = (file: string, text: string, message = 'script edit') => {
+ writeFileSync(join(root, file), text);
+ git(root, 'add', file); git(root, 'commit', '-qm', message);
+ return git(root, 'rev-parse', 'HEAD');
+};
+/** A credential committed by a script and removed by its next commit: only the history holds it. */
+const removedSecret = () => { const sha = plainCommit('notes.md', `deploy ${TOKEN}\n`); plainCommit('notes.md', 'removed\n'); return sha; };
+const refusal = (p: Promise<unknown>) => p.then(() => null, e => e as OperationError);
+const expectRedactedRefusal = (error: OperationError | null, code = 'publish_secret_found') => {
+ expect(error).toBeInstanceOf(OperationError);
+ expect(error?.code).toBe(code);
+ expect(JSON.stringify({ message: error?.message, suggestion: error?.suggestion, detail: error?.detail })).not.toContain(TOKEN);
+};
+const policy = () => commitPolicyFile(root, POLICY_FILE, () => 'version: 1\nrules: []\n', 'update folder policy');
+const sourcesPush = () => workspacePush({ dir: root, branch: 'main', allowUnverifiedRemote: true });
+
+beforeEach(() => {
+ dir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-8902-')));
+ saved = { HOME: process.env.HOME, GBRAIN_HOME: process.env.GBRAIN_HOME, GBRAIN_GIT_ALLOW_FILE_TRANSPORT: process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT };
+ process.env.HOME = dir;
+ process.env.GBRAIN_HOME = dir;
+ process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT = '1';
+ remote = join(dir, 'origin.git'); root = join(dir, 'work');
+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', remote]);
+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', remote, root], { stdio: 'ignore', env: process.env });
+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ git(root, 'config', 'commit.gpgsign', 'false');
+ plainCommit('README.md', 'initial\n', 'initial'); git(root, 'push', '-q', '-u', 'origin', 'main');
+ base = remoteTip();
+});
+afterEach(() => {
+ for (const [key, value] of Object.entries(saved)) {
+ if (value === undefined) delete process.env[key]; else process.env[key] = value;
+ }
+ rmSync(dir, { recursive: true, force: true });
+});
+
+describe('access-policy commit', () => {
+ test('refuses a credential an earlier commit added and a later one removed; keeps the policy commit local', async () => {
+ const secret = removedSecret();
+ const error = await refusal(policy());
+ expectRedactedRefusal(error);
+ expect(error?.message).toContain(`notes.md:1`);
+ expect(error?.message).toContain(secret.slice(0, 7));
+ expect(remoteTip()).toBe(base);
+ expect(git(root, 'show', `HEAD:${POLICY_FILE}`)).toBe('version: 1\nrules: []');
+ expect(git(root, 'status', '--porcelain')).toBe('');
+ }, T);
+
+ test('refuses a credential in an earlier commit message', async () => {
+ plainCommit('notes.md', 'safe\n', `rotate ${TOKEN}`);
+ const error = await refusal(policy());
+ expectRedactedRefusal(error);
+ expect(error?.message).toContain('(commit message)');
+ expect(remoteTip()).toBe(base);
+ }, T);
+
+ test('on a remote that has no such branch yet, scans the whole history: clean publishes, a secret refuses', async () => {
+ const fresh = join(dir, 'fresh.git');
+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', fresh]);
+ git(root, 'remote', 'set-url', 'origin', fresh);
+ git(root, 'update-ref', '-d', 'refs/remotes/origin/main');
+ expect((await policy()).outcome).toBe('pushed');
+ expect(git(fresh, 'rev-parse', 'refs/heads/main')).toBe(git(root, 'rev-parse', 'HEAD'));
+ const other = join(dir, 'other.git');
+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', other]);
+ git(root, 'remote', 'set-url', 'origin', other);
+ git(root, 'update-ref', '-d', 'refs/remotes/origin/main');
+ git(root, 'commit', '-q', '--amend', '-m', `policy ${TOKEN}`);
+ expectRedactedRefusal(await refusal(commitPolicyFile(root, POLICY_FILE, () => 'version: 1\nrules: [] # again\n', 'policy again')));
+ expect(() => git(other, 'rev-parse', '--verify', 'refs/heads/main')).toThrow();
+ }, T);
+
+ test('a clean history still publishes, and a checkout without a remote still commits locally', async () => {
+ plainCommit('notes.md', 'clean earlier work\n');
+ expect((await policy()).outcome).toBe('pushed');
+ expect(remoteTip()).toBe(git(root, 'rev-parse', 'HEAD'));
+ git(root, 'remote', 'remove', 'origin');
+ plainCommit('notes.md', `deploy ${TOKEN}\n`);
+ const local = await commitPolicyFile(root, POLICY_FILE, () => 'version: 1\nrules: [] # local\n', 'local policy');
+ expect(local.outcome).toBe('committed_local');
+ }, T);
+});
+
+describe('durability scaffolding commit', () => {
+ test('refuses earlier secret history instead of reporting the repo clean against origin', async () => {
+ removedSecret();
+ const report = await hardenBrainRepo({ repoPath: root, sourceId: 'wiki', installCron: false });
+ expect(remoteTip()).toBe(base);
+ expect(report.clean_against_origin).toBe(false);
+ expect(report.steps.find(s => s.step === 'commit')?.detail).toContain('publish_secret_found');
+ expect(JSON.stringify(report)).not.toContain(TOKEN);
+ }, T);
+
+ test('refuses a credential in an earlier commit message', async () => {
+ plainCommit('notes.md', 'safe\n', `rotate ${TOKEN}`);
+ const report = await hardenBrainRepo({ repoPath: root, sourceId: 'wiki', installCron: false });
+ expect(remoteTip()).toBe(base);
+ expect(report.steps.find(s => s.step === 'commit')?.detail).toContain('publish_secret_found');
+ expect(JSON.stringify(report)).not.toContain(TOKEN);
+ }, T);
+
+ test('clean prior work still publishes with the scaffolding', async () => {
+ plainCommit('notes.md', 'clean earlier work\n');
+ const report = await hardenBrainRepo({ repoPath: root, sourceId: 'wiki', installCron: false });
+ expect(report.needs_attention).toEqual([]);
+ expect(report.clean_against_origin).toBe(true);
+ expect(remoteTip()).toBe(git(root, 'rev-parse', 'HEAD'));
+ }, T);
+});
+
+describe('gbrain sources push', () => {
+ test('with nothing new to commit, refuses the earlier commits it would push and keeps them local', async () => {
+ const head = (removedSecret(), git(root, 'rev-parse', 'HEAD'));
+ expectRedactedRefusal(await refusal(sourcesPush()));
+ expect(remoteTip()).toBe(base);
+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);
+ }, T);
+
+ test('refuses when it also commits new clean work, and keeps that commit', async () => {
+ removedSecret();
+ writeFileSync(join(root, 'page.md'), 'new page\n');
+ expectRedactedRefusal(await refusal(sourcesPush()));
+ expect(remoteTip()).toBe(base);
+ expect(git(root, 'show', 'HEAD:page.md')).toBe('new page');
+ }, T);
+
+ test('refuses a credential in an earlier commit message', async () => {
+ plainCommit('notes.md', 'safe\n', `rotate ${TOKEN}`);
+ const error = await refusal(sourcesPush());
+ expectRedactedRefusal(error);
+ expect(error?.message).toContain('(commit message)');
+ expect(remoteTip()).toBe(base);
+ }, T);
+
+ test('an allowlist edit it commits itself still publishes; one a script committed refuses', async () => {
+ plainCommit('notes.md', `key ${TOKEN}\n`);
+ const first = await refusal(sourcesPush());
+ expectRedactedRefusal(first);
+ const fingerprint = (JSON.parse(String(first!.detail)) as { findings: Array<{ fingerprint: string }> }).findings[0]!.fingerprint;
+ writeFileSync(join(root, SCAN_ALLOW_FILENAME), `${fingerprint}\n`);
+ expect((await sourcesPush()).status).toBe('pushed');
+ expect(remoteTip()).toBe(git(root, 'rev-parse', 'HEAD'));
+ const published = remoteTip();
+ plainCommit(SCAN_ALLOW_FILENAME, `${fingerprint}\n**/*.env\n`);
+ const gate = await refusal(sourcesPush());
+ expectRedactedRefusal(gate);
+ expect(gate?.message).toContain(SCAN_ALLOW_FILENAME);
+ expect(remoteTip()).toBe(published);
+ }, T);
+
+ test('commits a rewound remote dropped are scanned again, not trusted from the tracking ref', async () => {
+ removedSecret();
+ git(root, 'push', '-q');
+ git(remote, 'update-ref', 'refs/heads/main', base);
+ expectRedactedRefusal(await refusal(sourcesPush()));
+ expect(remoteTip()).toBe(base);
+ }, T);
+
+ test('a clean history still pushes', async () => {
+ plainCommit('notes.md', 'clean earlier work\n');
+ const result = await sourcesPush();
+ expect(result.status).toBe('pushed');
+ expect(remoteTip()).toBe(git(root, 'rev-parse', 'HEAD'));
+ }, T);
+});
+
+describe('gbrain bootstrap repo, first push after the remote branch is gone', () => {
+ const url = 'https://github.com/alice-example/agent-workspace';
+ let pushes: string[][];
+ const runner: ExecRunner = async argv => {
+ const joined = argv.join(' ');
+ if (argv[0] === 'gh') {
+ if (joined.includes('--version')) return { code: 0, stdout: 'gh version 2.97.0 (2026-07-31)\n', stderr: '' };
+ if (joined.includes('api user')) return { code: 0, stdout: '{"login":"alice-example","id":1}\n', stderr: '' };
+ if (joined.includes('--jq .private')) return { code: 0, stdout: 'true\n', stderr: '' };
+ return { code: 0, stdout: '', stderr: '' };
+ }
+ if (argv.includes('push')) { pushes.push(argv); return { code: 0, stdout: '', stderr: '' }; }
+ if (argv.includes('ls-remote')) return { code: 0, stdout: '', stderr: '' };
+ if (joined.endsWith('remote get-url origin')) return { code: 0, stdout: `${url}\n`, stderr: '' };
+ return defaultRunner(argv);
+ };
+ const bootstrap = () => createPrivateRepo(root, { runner, gbrainHomeDir: join(dir, 'gbrain-home') });
+
+ beforeEach(() => {
+ pushes = [];
+ git(root, 'remote', 'set-url', 'origin', url);
+ writeManifest(root, { format_version: 1, initialized: true, agent_name: 'Example Agent', created_by: '0.0.0-test', created_at: '2026-01-01T00:00:00.000Z', source_id: 'workspace' });
+ writeFileSync(join(root, 'GITHUB.md'), `Backed up to **${url}**.\n`);
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'render');
+ mkdirSync(join(dir, 'gbrain-home', 'bootstrap'), { recursive: true });
+ writeReceipt(join(dir, 'gbrain-home'), { receipt_version: 1, workspace_dir: root, source_id: 'workspace', agent_name: 'Example Agent',
+ created_at: '2026-01-01T00:00:00.000Z', created_by: '0.0.0-test', brain_created_by_bootstrap: false, created_paths: [], registrations: [], repo_url: url } as RepoReceipt);
+ });
+
+ test('refuses a credential anywhere in the history and never pushes', async () => {
+ removedSecret();
+ expectRedactedRefusal(await refusal(bootstrap()));
+ expect(pushes).toEqual([]);
+ }, T);
+
+ test('refuses a credential in an earlier commit message and never pushes', async () => {
+ plainCommit('notes.md', 'safe\n', `rotate ${TOKEN}`);
+ const error = await refusal(bootstrap());
+ expectRedactedRefusal(error);
+ expect(error?.message).toContain('(commit message)');
+ expect(pushes).toEqual([]);
+ }, T);
+
+ test('on a detached HEAD, scans the branch it pushes, not HEAD', async () => {
+ removedSecret();
+ git(root, 'checkout', '-q', '--detach', 'HEAD~2');
+ expectRedactedRefusal(await refusal(bootstrap()));
+ expect(pushes).toEqual([]);
+ }, T);
+
+ test('a clean history still completes the first push', async () => {
+ plainCommit('notes.md', 'clean earlier work\n');
+ expect((await bootstrap()).reused).toBe(true);
+ expect(pushes).toEqual([['git', '-C', root, 'push', '-u', 'origin', 'main']]);
+ expect(readFileSync(join(root, 'GITHUB.md'), 'utf8')).toContain(url);
+ }, T);
+});