Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Add gbrain git scan, a read-only preview of what a push's secret scan would refuse, and name the managed marker in --dry-run

garrytane94393fbfcd7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1fa4a757b0..72f16ae298 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ identifiers and attribution are available in the pre-removal Git revision
- `src/commands/git.ts`: every mode passes `scanSecrets` (`--scan-secrets` is still accepted), `--scan-timeout <s>` (whole seconds, not with `--pull`), progress lines on stderr, and a scan refusal logged as `LOCAL-ONLY, NEEDS ATTENTION ... the push was refused (<code>)`.
- `src/core/git/range-secret-scan.ts`: commit messages read with one `cat-file --batch` and patches with one `diff-tree` per 256 commits (the patch file holds one batch, not the whole history), progress lines, `PublishScanOptions` (budget, progress, retry command), and a timed-out scan refused with an agent fix that reruns with four times the budget (at least 1200 s).
- `src/core/git/commit-push.ts`, `src/core/workspace-push.ts`, `src/core/bootstrap/repo.ts`: `--no-follow-tags --recurse-submodules=no` on every push, so no tag or submodule commit goes out unscanned; `gbrain sources push` fetches origin's branch before it scans and returns the scan refusal as `blocked_history`.
+- `src/commands/git.ts`: `gbrain git scan [--from <rev>] [--to <rev>] [--json]` runs the push's scan over a range and changes nothing (no fetch, lock or push), printing what a push would refuse and each finding's fingerprint for `.gbrain-scan-allow`; `commit-push --dry-run` names the managed-worktree marker, or none.
- `src/commands/sources.ts`, `src/commands/bootstrap.ts`: `--scan-timeout`; `sources push` prints a `blocked_history` refusal and exits 5.
- `src/core/access/policy-git.ts`: a scan refusal returns `committed_not_pushed` with the refusal in its note.
- `src/core/brain-repo-durability.ts`: the post-commit hook and the helper pass `--scan-secrets` (so an older gbrain still scans), the helper uses only a gbrain whose `git commit-push --help` names `--scan-timeout`, and its fallback commits, logs the commit as local-only and exits 4 (0 when the branch is already on the remote).
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.md
index 6c3b6e4cb5..9181626d79 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`), stages named tracked paths with `add -u` and visible untracked ones with `add -A` (a tracked deletion under an ignored directory commits, #7984; any other path keeps git's `commit_paths_invalid`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. After the commit step (and its index restore) `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, timeoutMs, progress)`, the secret gate for every push gbrain makes: `gbrain git commit-push` in every mode (the CLI always sets `scanSecrets`; the post-commit hook, `scripts/brain-commit-push.sh` and the child `gbrain sources refresh` runs all go through it) scans `trackingRef..target` under the publish lock, right before a push that never follows tags or recurses into submodules (`--no-follow-tags --recurse-submodules=no`, on the `sources push` and `bootstrap repo` pushes too). Plumbing only (`rev-list`, then `cat-file --batch` and `diff-tree --stdin -p --root --cc` over batches of 256 commits, so the temporary patch file stays one batch in size), so log, diff and attribute settings never change what is scanned. The budget is 300 s unless `--scan-timeout` sets it; `progress` gets `secret scan:` lines (at once for a whole history, then every 10 s), and with `retryArgv` a timed-out scan refuses `publish_scan_unreadable` whose agent fix is that command with `--scan-timeout` four times longer (at least 1200 s). 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, opts)` is the same refusal for `gbrain sources push` (`workspace-push.ts`: origin's tip read from origin itself with `ls-remote` and a fetch, since the pull may follow another upstream remote, then `<tip>..HEAD` scanned and that exact sha pushed leased on the tip, no push when the local branch lacks the tip; a refusal is the `blocked_history` result, exit 5, printed by `--json` too) 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`, which reports a scan refusal as `committed_not_pushed` with the refusal in its note) and the durability-scaffolding commit (`brain-repo-durability.ts`) publish through `commitAndPush` with `scanSecrets` (#8902). The helper's no-gbrain fallback commits and never pushes. Tests: `test/unmanaged-push-history-scan-8902.serial.test.ts`, `test/unmanaged-push-every-site-gst2456.serial.test.ts`.
+- `src/core/git/range-secret-scan.ts` — `scanRange(root, from, to, timeoutMs, progress)`, the secret gate for every push gbrain makes: `gbrain git commit-push` in every mode (the CLI always sets `scanSecrets`; the post-commit hook, `scripts/brain-commit-push.sh` and the child `gbrain sources refresh` runs all go through it) scans `trackingRef..target` under the publish lock, right before a push that never follows tags or recurses into submodules (`--no-follow-tags --recurse-submodules=no`, on the `sources push` and `bootstrap repo` pushes too). Plumbing only (`rev-list`, then `cat-file --batch` and `diff-tree --stdin -p --root --cc` over batches of 256 commits, so the temporary patch file stays one batch in size), so log, diff and attribute settings never change what is scanned. The budget is 300 s unless `--scan-timeout` sets it; `progress` gets `secret scan:` lines (at once for a whole history, then every 10 s), and with `retryArgv` a timed-out scan refuses `publish_scan_unreadable` whose agent fix is that command with `--scan-timeout` four times longer (at least 1200 s). 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, opts)` is the same refusal for `gbrain sources push` (`workspace-push.ts`: origin's tip read from origin itself with `ls-remote` and a fetch, since the pull may follow another upstream remote, then `<tip>..HEAD` scanned and that exact sha pushed leased on the tip, no push when the local branch lacks the tip; a refusal is the `blocked_history` result, exit 5, printed by `--json` too) 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`, which reports a scan refusal as `committed_not_pushed` with the refusal in its note) and the durability-scaffolding commit (`brain-repo-durability.ts`) publish through `commitAndPush` with `scanSecrets` (#8902). The helper's no-gbrain fallback commits and never pushes. `gbrain git scan` (`runScan` in `src/commands/git.ts`) runs `scanRange` and `rangeSecretRefusal` over `--from..--to` (default `@{upstream}..HEAD`) and writes nothing: the read-only preview of what a push would refuse, with each finding's fingerprint. Tests: `test/unmanaged-push-history-scan-8902.serial.test.ts`, `test/unmanaged-push-every-site-gst2456.serial.test.ts`.
- `src/commands/doctor/checks/git-writer.ts` — `checkout_lagging`, `dirty_age`, `commits_outside_source_root`, `quarantined_changes` (#7381, brain category, 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 67a7d993a7..0c8e30a128 100644
--- a/docs/guides/shared-checkout-git.md
+++ b/docs/guides/shared-checkout-git.md
@@ -168,6 +168,29 @@ The agent reads `gbrain sync status --source <id> --json` (`git_push_holds`) or
failures go through `gbrain sources writer retry-effects <source> --parked-pushes`
(preview with `--dry-run`); a conflict names the user's choice first.
+<a id="preview-the-secret-scan"></a>
+### Preview the secret scan
+
+`gbrain git scan [--path <dir>] [--from <rev>] [--to <rev>] [--json]` runs the
+scan a push runs, over `--from..--to` (by default the upstream as last fetched,
+up to `HEAD`), with the checkout's `.gbrain-scan-allow`, and changes nothing:
+no fetch, lock, commit or push. It says whether a push would refuse
+(`would_refuse`) and lists each finding's commit, path, line, rule and
+fingerprint, never the value. Before an upgrade,
+`--from $(git rev-list -1 --before="30 days ago" HEAD)` shows what the last 30
+days of commits would have hit. `gbrain git commit-push --dry-run` names the
+marker that makes a checkout a managed canonical worktree, or none; every push
+mode scans either way.
+
+A finding that is not a secret: add its fingerprint (`sha256:` and 16 hex
+characters, as the preview prints it) as a line of `.gbrain-scan-allow` at the
+checkout root (`#` starts a comment). The scan reads the file from the working
+tree, so the next push uses it without a commit. Keep it out of commits (list it
+in `.git/info/exclude`): a commit that changes it changes what the scan sees, so
+no automatic push publishes it. A fingerprint accepts that exact value wherever
+it appears; a line without `sha256:` is a path glob and accepts every finding in
+the files it matches.
+
<a id="outcomes"></a>
## Outcomes
diff --git a/src/commands/git.ts b/src/commands/git.ts
index 8133d5c5b8..be900a6f6d 100644
--- a/src/commands/git.ts
+++ b/src/commands/git.ts
@@ -10,6 +10,7 @@
* gbrain git commit-push --dry-run [--path <dir>] [-m <msg>] [--] <paths…>
* gbrain git commit-push --pending [--path <dir>] [-m <msg>]
* gbrain git guard [--install | --uninstall] [--path <dir>] [--json]
+ * gbrain git scan [--path <dir>] [--from <rev>] [--to <rev>] [--scan-timeout <s>] [--json]
*/
import { existsSync, realpathSync } from 'node:fs';
import { isAbsolute, join, relative, sep } from 'node:path';
@@ -22,7 +23,8 @@ import { writeStdoutFinal } from '../core/cli-force-exit.ts';
import { execFileSync } from '../core/spawn.ts';
import { gitChildEnv } from '../core/git-env.ts';
import { GIT_ENV } from '../core/git-transport.ts';
-import { staleEnclosingMarker } from '../core/persistence/filesystem-guard.ts';
+import { managedFilesystemRootFor, staleEnclosingMarker } from '../core/persistence/filesystem-guard.ts';
+import { rangeSecretRefusal, scanRange } from '../core/git/range-secret-scan.ts';
import { canonicalFilesystemPath, checkoutGitMetadata, managedRootMarkerFor, registeredManagedRootRecords } from '../core/persistence/root-registry.ts';
const HELP = `Usage: gbrain git commit-push [--path <dir>] -m <msg> [--json] [--] <paths...>
@@ -31,6 +33,7 @@ const HELP = `Usage: gbrain git commit-push [--path <dir>] -m <msg> [--json] [--
gbrain git commit-push --pull [--path <dir>] [--require-clean]
gbrain git commit-push --pending [--path <dir>] [-m <msg>]
gbrain git guard [--install | --uninstall] [--path <dir>] [--json]
+ gbrain git scan [--path <dir>] [--from <rev>] [--to <rev>] [--scan-timeout <s>] [--json]
Commit only the named paths and push them, safely, in a checkout other agents
share: a short commit lock and a separate push lock per checkout, no
@@ -67,7 +70,8 @@ Flags:
ledger doctor's dirty_age reports), then push.
--allow-outside-source-root Commit and publish files outside the checkout's source root(s)
(git config gbrain.sourceRoot); only after the user agrees.
- --dry-run Print the paths, branch and lock that would be used; take no lock, write nothing.
+ --dry-run Print the paths, branch and lock that would be used, and the marker that makes the
+ checkout a managed canonical worktree (or none); take no lock, write nothing.
--json One JSON result (or the error envelope) on stdout.
Paths are relative to --path when it is given (like git -C), else to the current
@@ -80,12 +84,19 @@ prepare-commit-msg hook that refuses commits in this checkout not made through
gbrain (git commit, -a and --no-verify included; merges and commits that finish a
merge, cherry-pick, revert or rebase pass). A person bypasses it once with
GBRAIN_COMMIT_GUARD=off git <command>. Without a flag it prints whether the guard
-is installed.`;
+is installed.
+
+gbrain git scan: the secret scan a push runs, over --from..--to (default: the
+upstream as last fetched, ..HEAD), with the checkout's .gbrain-scan-allow. It
+fetches, locks, writes and pushes nothing. It prints what a push would refuse
+(would_refuse) and each finding's path, line, rule, commit and fingerprint, never
+the value; a finding's fingerprint line in .gbrain-scan-allow accepts that value.
+Exit 0 when the scan ran, whatever it found.`;
interface Parsed {
sub?: string; path?: string; message?: string; branch?: string; expectRemote?: string; json: boolean; pushOnly: boolean; pull: boolean;
requireClean: boolean; dryRun: boolean; help: boolean; keepCheckout: boolean; paths: string[]; resolve: string[]; base: string[];
- pending: boolean; allowOutside: boolean; install: boolean; uninstall: boolean; scanSecrets: boolean; scanTimeout?: string;
+ pending: boolean; allowOutside: boolean; install: boolean; uninstall: boolean; scanSecrets: boolean; scanTimeout?: string; from?: string; to?: string;
}
function parse(args: string[]): Parsed {
@@ -122,6 +133,8 @@ function parse(args: string[]): Parsed {
else if (a === '--branch' || a.startsWith('--branch=')) p.branch = take('--branch');
else if (a === '--expect-remote' || a.startsWith('--expect-remote=')) p.expectRemote = take('--expect-remote');
else if (a === '--scan-timeout' || a.startsWith('--scan-timeout=')) p.scanTimeout = take('--scan-timeout');
+ else if (a === '--from' || a.startsWith('--from=')) p.from = take('--from');
+ else if (a === '--to' || a.startsWith('--to=')) p.to = take('--to');
else if (!p.sub) p.sub = a;
else if (a.startsWith('-')) throw opError('commit_paths_invalid', `Unknown flag ${a}.`, HELP.split('\n')[0]);
else p.paths.push(a);
@@ -176,6 +189,32 @@ function assertSourceCheckout(repo: string): void {
verify: { argv: ['gbrain', 'git', 'commit-push', '--dry-run', '--path', first] } } });
}
+/** `gbrain git scan`: the push's secret scan over a range, read-only, so an operator can see what a push would refuse. */
+function runScan(p: Parsed): number {
+ const repo = checkoutRoot(p.path ?? process.cwd());
+ if (p.scanTimeout !== undefined && !/^[1-9]\d{0,5}$/.test(p.scanTimeout)) {
+ throw opError('commit_paths_invalid', `--scan-timeout ${p.scanTimeout} is not a number of seconds.`, 'Pass whole seconds, for example --scan-timeout 1800.');
+ }
+ const rev = (spec: string, flag: string): string => {
+ try { return execFileSync('git', ['-C', repo, 'rev-parse', '--verify', '--quiet', '--end-of-options', `${spec}^{commit}`], { env: gitChildEnv({ ...GIT_ENV }) }).toString().trim(); }
+ catch { throw opError('commit_paths_invalid', `${flag} ${spec} names no commit in ${repo}.`, 'Pass a commit, for example --from $(git rev-list -1 --before="30 days ago" HEAD); with no upstream, --from is required.'); }
+ };
+ const from = rev(p.from ?? '@{upstream}', '--from');
+ const to = rev(p.to ?? 'HEAD', '--to');
+ const timeoutMs = p.scanTimeout ? Number(p.scanTimeout) * 1000 : undefined;
+ const started = Date.now();
+ const scan = scanRange(repo, from, to, timeoutMs, line => process.stderr.write(`[gbrain] ${line}\n`));
+ const refusal = rangeSecretRefusal(repo, from, to, scan, { timeoutMs });
+ const commits = Number(execFileSync('git', ['-C', repo, 'rev-list', '--count', `${from}..${to}`], { env: gitChildEnv({ ...GIT_ENV }) }).toString().trim());
+ const seconds = Math.round((Date.now() - started) / 100) / 10;
+ const items = [...scan.findings.map(f => ` ${f.commit.slice(0, 7)} ${f.path}:${f.line} ${f.pattern} ${f.fingerprint}`),
+ ...scan.unscanned.map(u => ` ${u.commit.slice(0, 7)} ${u.path} too large to scan`), ...scan.gate_changes.map(g => ` ${g.commit.slice(0, 7)} ${g.path} changes what the scan sees`)];
+ emit(p.json, { repo, from, to, commits, seconds, would_refuse: refusal?.code ?? null, findings: scan.findings, unscanned: scan.unscanned, gate_changes: scan.gate_changes,
+ unreadable: scan.unreadable ?? null }, [`scanned ${commits} commit(s) ${from.slice(0, 12)}..${to.slice(0, 12)} in ${seconds} s: ${refusal ? `a push would refuse (${refusal.code})` : 'a push would not refuse'}`,
+ ...(scan.unreadable !== undefined ? [` not read in full: ${scan.unreadable}`] : []), ...items].join('\n'));
+ return 0;
+}
+
function emit(json: boolean, doc: Record<string, unknown>, human: string): void {
if (json) void writeStdoutFinal(`${JSON.stringify(doc)}\n`);
else console.log(human);
@@ -188,6 +227,7 @@ export async function runGit(args: string[]): Promise<number> {
json = p.json;
if (p.help || !p.sub) { console.log(HELP); return p.sub || p.help ? 0 : 2; }
if (p.sub === 'guard') return runGuard(p);
+ if (p.sub === 'scan') return runScan(p);
if (p.sub !== 'commit-push') throw opError('commit_paths_invalid', `Unknown subcommand: gbrain git ${p.sub}.`, HELP.split('\n')[0]);
if (p.install || p.uninstall) throw opError('commit_paths_invalid', '--install and --uninstall belong to gbrain git guard.', 'Run gbrain git guard --install.');
const repo = checkoutRoot(p.path ?? process.cwd());
@@ -218,8 +258,9 @@ export async function runGit(args: string[]): Promise<number> {
const lock = execFileSync('git', ['-C', repo, 'rev-parse', '--git-path', COMMIT_LOCK_NAME], { env: gitChildEnv({ ...GIT_ENV }) }).toString().trim();
const branch = execFileSync('git', ['-C', repo, 'symbolic-ref', '--quiet', '--short', 'HEAD'], { env: gitChildEnv({ ...GIT_ENV }) }).toString().trim();
const paths = p.pull || p.pushOnly || !p.paths.length ? [] : scopePaths(repo, p.paths, cwd);
- emit(json, { dry_run: true, repo, branch, lock, paths, mode: p.pull ? 'pull' : p.pushOnly ? 'push-only' : 'commit-push' },
- `dry run: ${p.pull ? 'pull' : p.pushOnly ? 'push-only' : `commit ${paths.join(' ')}`} on ${branch} in ${repo} (lock ${lock}); nothing written`);
+ const managed = managedFilesystemRootFor(repo);
+ emit(json, { dry_run: true, repo, branch, lock, paths, mode: p.pull ? 'pull' : p.pushOnly ? 'push-only' : 'commit-push', managed },
+ `dry run: ${p.pull ? 'pull' : p.pushOnly ? 'push-only' : `commit ${paths.join(' ')}`} on ${branch} in ${repo} (lock ${lock}); ${managed ? `managed canonical worktree (${managed.evidence})` : 'not a managed worktree'}; nothing written`);
return 0;
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index d35b3a782a..04cdefc9bb 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -73,7 +73,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'founder': ['--brain', '--help', '--json', '--mcp-only', '--request-id', '--since', '--source', '--until'],
'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--literal-pathspecs', '--local', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],
- 'git': ['--abbrev-ref', '--absolute-git-dir', '--add', '--aggressive', '--all', '--allow-outside-source-root', '--assume-unchanged', '--autostash', '--base', '--batch-check', '--brain', '--branch', '--cached', '--cacheinfo', '--cherry-mark', '--count', '--diff-filter', '--dry-run', '--enable', '--error-unmatch', '--exclude-standard', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--force-with-lease', '--format', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--help', '--index-info', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--local', '--local-env-vars', '--max-count', '--merge-base', '--message', '--mode', '--name-only', '--name-status', '--no-assume-unchanged', '--no-autostash', '--no-commit-id', '--no-cron', '--no-follow-tags', '--no-gpg-sign', '--no-merges', '--no-optional-locks', '--no-recurse-submodules', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--others', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--recurse-submodules', '--repo', '--request-id', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--scan-secrets', '--scan-timeout', '--short', '--show-toplevel', '--skip-worktree', '--source', '--source-id', '--staged', '--stat', '--stdin', '--topo-order', '--type', '--uninstall', '--unset', '--unset-all', '--untracked-files', '--verify', '--worktree', '--write-tree'],
+ 'git': ['--abbrev-ref', '--absolute-git-dir', '--add', '--aggressive', '--all', '--allow-outside-source-root', '--assume-unchanged', '--attr-source', '--autostash', '--base', '--batch', '--batch-check', '--before', '--brain', '--branch', '--cached', '--cacheinfo', '--cc', '--cherry-mark', '--combined', '--count', '--diff-filter', '--dry-run', '--dst-prefix', '--enable', '--end-of-options', '--error-unmatch', '--exclude-standard', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--force-with-lease', '--format', '--from', '--full-index', '--get', '--get-all', '--get-regexp', '--get-url', '--git', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--help', '--index-info', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--local', '--local-env-vars', '--max-count', '--merge-base', '--message', '--mode', '--name-only', '--name-status', '--no-assume-unchanged', '--no-autostash', '--no-color', '--no-commit-id', '--no-cron', '--no-ext-diff', '--no-follow-tags', '--no-gpg-sign', '--no-merges', '--no-optional-locks', '--no-recurse-submodules', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-textconv', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--others', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--recurse-submodules', '--repo', '--request-id', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--scan-secrets', '--scan-timeout', '--short', '--show-toplevel', '--skip-worktree', '--source', '--source-id', '--src-prefix', '--staged', '--stat', '--stdin', '--to', '--topo-order', '--type', '--unified', '--uninstall', '--unset', '--unset-all', '--untracked-files', '--verify', '--worktree', '--write-tree'],
'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embed', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--probe', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--force-with-lease', '--gbrain-bin', '--get', '--harness', '--heads', '--help', '--instructions', '--instructions-only', '--is-ancestor', '--jq', '--json', '--limit', '--name-only', '--no-follow-tags', '--no-instructions', '--no-tags', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--recurse-submodules', '--remove', '--scope', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],
diff --git a/test/unmanaged-push-every-site-gst2456.serial.test.ts b/test/unmanaged-push-every-site-gst2456.serial.test.ts
index d598de1d60..26cf6de2ce 100644
--- a/test/unmanaged-push-every-site-gst2456.serial.test.ts
+++ b/test/unmanaged-push-every-site-gst2456.serial.test.ts
@@ -121,6 +121,35 @@ describe('gbrain git commit-push', () => {
expect(remoteTip()).toBe(base);
}, T);
+ test('gbrain git scan previews what the next push would refuse and writes nothing; the fingerprint in .gbrain-scan-allow clears it', () => {
+ removedSecret();
+ const head = git(root, 'rev-parse', 'HEAD');
+ const status = git(root, 'status', '--porcelain');
+ const r = cli(['git', 'scan', '--json']);
+ expect(r.status).toBe(0);
+ const doc = JSON.parse(r.stdout) as { from: string; to: string; commits: number; would_refuse: string | null; findings: Array<{ path: string; fingerprint: string }> };
+ expect(doc).toMatchObject({ from: base, to: head, commits: 2, would_refuse: 'publish_secret_found' });
+ expect(doc.findings.map(f => f.path)).toEqual(['notes.md']);
+ expect(r.stdout + r.stderr).not.toContain(TOKEN);
+ expect([remoteTip(), git(root, 'rev-parse', 'HEAD'), git(root, 'status', '--porcelain'), pushLog()]).toEqual([base, head, status, '']);
+ const human = cli(['git', 'scan', '--from', base, '--to', head]);
+ expect(human.status).toBe(0);
+ expect(human.stdout).toContain(`notes.md:1`);
+ expect(human.stdout).toContain(doc.findings[0]!.fingerprint);
+ writeFileSync(join(root, '.gbrain-scan-allow'), `# a synthetic test credential\n${doc.findings[0]!.fingerprint}\n`);
+ expect(JSON.parse(cli(['git', 'scan', '--json']).stdout)).toMatchObject({ would_refuse: null, findings: [] });
+ expect(cli(['git', 'commit-push', '--push-only', '--keep-checkout', '--json']).status).toBe(0);
+ expect(remoteTip()).toBe(head);
+ for (const args of [['--from', 'no-such-rev'], ['--scan-timeout', 'soon']]) expect(envelope(cli(['git', 'scan', ...args, '--json']).stdout).code ?? '').toBe('commit_paths_invalid');
+ }, T);
+
+ test('--dry-run names the managed-worktree marker, or none', () => {
+ expect(JSON.parse(cli(['git', 'commit-push', '--dry-run', '--push-only', '--json']).stdout).managed).toBeNull();
+ writeFileSync(join(git(root, 'rev-parse', '--absolute-git-dir'), 'gbrain-managed.json'), '{}');
+ const doc = JSON.parse(cli(['git', 'commit-push', '--dry-run', '--push-only', '--json']).stdout) as { managed: { root: string; evidence: string } };
+ expect(doc.managed.evidence).toEndWith('gbrain-managed.json');
+ }, T);
+
test('push.followTags never publishes an annotated tag, whose message nothing scans', () => {
git(root, 'config', 'push.followTags', 'true');
plainCommit('notes.md', 'clean\n');