Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Scan for secrets inside the publish child, on the exact commits it pushes, and refuse publish_secret_found
garrytanb4f8c09f4ffd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 82dc2edbb5..f21dcdf367 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,15 +12,15 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]-**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. Before anything is pushed, every blob those commits added or changed is scanned for values that look like secrets, including one a later commit removed; a finding refuses `refresh_diverged` naming the file, line, rule and commit, never the value. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off. The keep-checkout publish now runs the checkout's pre-push hook when the push is a plain fast-forward of HEAD (it still skips it for the in-memory merge it builds).+**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, or added text too large to scan, refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.### Itemized changes-- `src/core/git/range-secret-scan.ts` (new): `scanCommitRange(root, base, head)` lists the blobs each non-merge commit in `base..head` adds or changes, skips path-allowlisted, binary and over-cap blobs, and scans each once with `scanText` and the workspace allowlist; `null` when git cannot list or read them.-- `src/core/persistence/worktree-refresh.ts`: an unset `sources.refresh_publish_diverged` publishes only when `gitDurabilityPolicy` says durable (otherwise `refresh_diverged` names the durability and the `--enable` command); every automatic publish refuses on a secret finding or an unreadable range.-- `src/core/git/commit-push.ts`: `--no-verify` only for a candidate the publish merged, not for HEAD itself.-- Docs: `docs/guides/write-refusals.md` (`refresh_diverged`), `docs/guides/live-sync.md`, `docs/guides/shared-checkout-git.md`, `docs/guides/troubleshooting.md`, `docs/architecture/canonical-writers.md`.-- Tests: `test/guarded-publish.test.ts` (the range scan: a secret added then removed is found without its value, allowlist and binary skips, an unreadable range; the pre-push hook runs and can stop a keep-checkout fast-forward); `test/refresh-publish-diverged-7686.test.ts` (unset with durability off refuses naming `--enable`, unset with durability on publishes, a secret in the local commits refuses with nothing pushed).+- `src/core/git/range-secret-scan.ts` (new): reads one `git log -p --diff-merges=dense-combined` of the range and scans each commit's message, each file's added lines and each merge's lines neither parent has with `scanText` and the workspace allowlist (`.gbrain-scan-allow`); binary changes carry no lines, and added text over the scan cap is reported unscanned.+- `src/core/persistence/worktree-refresh.ts`: an unset `sources.refresh_publish_diverged` publishes only when `gitDurabilityPolicy` says durable (otherwise `refresh_diverged` names the durability and the `--enable` command); the publish child runs with `--scan-secrets`.+- `src/core/git/commit-push.ts`, `src/commands/git.ts`: `scanSecrets` / `--scan-secrets` (push-only) scans `trackingRef..target` inside the publish lock, right before the push, and refuses `publish_secret_found` (new error code) on a finding, an over-cap file or a range git cannot list; its fix lists the commits and asks the user to remove the value or allowlist a false positive, never to push anyway.+- Docs: `docs/guides/shared-checkout-git.md` (`publish_secret_found` row), `docs/guides/write-refusals.md` (`refresh_diverged`), `docs/guides/live-sync.md`, `docs/guides/shared-checkout-git.md`, `docs/guides/troubleshooting.md`, `docs/architecture/canonical-writers.md`.+- Tests: `test/guarded-publish.test.ts` (a secret added then removed, one in a commit message and one in a merge resolution each refuse with nothing pushed and no value printed; an allowlisted fingerprint and a binary file are skipped; a clean range publishes); `test/refresh-publish-diverged-7686.test.ts` (unset with durability off refuses naming `--enable`, unset with durability on publishes, a secret in the local commits refuses `publish_secret_found` with nothing pushed or fenced).## [0.60.616.0] - 2026-11-08diff --git a/docs/architecture/canonical-writers.md b/docs/architecture/canonical-writers.mdindex eafcd9b472..19fc0f992e 100644--- a/docs/architecture/canonical-writers.md+++ b/docs/architecture/canonical-writers.md@@ -79,8 +79,8 @@ ordinary managed `--no-pull` sync that follows, so every imported page is ajournaled request. A durable `persistence_worktree_refreshes` row lets arestarted owner converge an interrupted refresh without adopting an unverifiedHEAD. With `sources.refresh_publish_diverged` on (unset means on when the-worktree's Git durability is on; `false` turns it off), a diverged refresh first scans-the local commits for secrets, then runs the keep-checkout publish, which+worktree's Git durability is on; `false` turns it off), a diverged refresh runs the+keep-checkout publish with a secret scan of the local commits, whichpushes HEAD merged with the upstream in memory and never moves the checkout orwrites the database, then fast-forwards as above. Remote sync retains theoriginal `submit_job` principal, admin/source/operation ceiling and normalizeddiff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 3038d6c9c0..3c70425887 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3652,6 +3652,16 @@ More: [docs/guides/repair.md#projection-owner-resident](../../docs/guides/repair|---|---|---|---|---|---|---|| The catalog adoption is accepted but not fully committed. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### publish_secret_found++<a id="publish_secret_found"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| An automatic publish found values that look like secrets (or text too large to scan) in the commits it was about to push; nothing was pushed. | The step needs the user's decision before it runs. | Stop and ask the user; re-run only with the authorization the message names. | user | `repeat the read that failed` | 1 | no |++More: [docs/guides/shared-checkout-git.md#publish_secret_found](../../docs/guides/shared-checkout-git.md#publish_secret_found)+### pull_blocked_local_changes<a id="pull_blocked_local_changes"></a>diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex f7b1a88b28..fdb96705f9 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -683,13 +683,14 @@ vars — incident-time escape hatches, not everyday knobs.([scripts and the managed checkout](shared-checkout-git.md#scripts-and-the-managed-checkout)).When the worktree's Git durability is on, a diverged refresh publishes thelocal commits itself (`sources.refresh_publish_diverged` unset; `false` turns it- off, `true` publishes even with durability off): it scans every blob those- commits added for values that look like secrets and refuses- `refresh_diverged` naming the file, line and rule when it finds one, then pushes+ off, `true` publishes even with durability off): under its publish lock it scans+ what those commits add (messages, added lines, merge resolutions) and refuses+ `publish_secret_found` naming the file, line and rule when one looks like a+ secret, otherwise it pushesthe local commits merged with the upstream in memory, the same publish as`gbrain git commit-push --push-only --keep-checkout` run as a child process- (the checkout's pre-push hook runs when the push is a fast-forward of HEAD),- and fast-forwards to the merge. It never moves the checkout to merge, a conflicting file refuses+ with `--scan-secrets` (it skips the checkout's pre-push hook), and fast-forwards+ to the merge. It never moves the checkout to merge, a conflicting file refuses`integrate_conflict` naming it with nothing pushed (with `gbrain.quarantine`on, the remote's version is published, this machine's is kept under`refs/gbrain/quarantine/`, and the refresh says so), an uncommitted edit to adiff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.mdindex 9b0430c77b..51db647699 100644--- a/docs/guides/shared-checkout-git.md+++ b/docs/guides/shared-checkout-git.md@@ -181,6 +181,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` (the publish `gbrain sources refresh` runs on its own): a commit about to be pushed adds a value that looks like a secret, in its message, an added line (even one a later commit removed) or a merge resolution, or adds text too large to scan; 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. Never publish them with a command that skips the scan. || `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. || `writer_coordinator_required` | 1 | This is a managed worktree. Stop using git for pages; save them through `put_page` and the other gbrain write tools. |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex ca84cc5041..9048c42e42 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -564,7 +564,7 @@ this anchor (`--json` puts them in one object on stdout); the command exits 1.| <a id="refresh_no_upstream"></a>`refresh_no_upstream` | `refresh_no_upstream` | The checkout's branch tracks no upstream, HEAD is detached, or the checkout is not a Git checkout at all (gbrain never initializes Git on its own), so there is nothing to fast-forward to. | `git -C <checkout> branch --set-upstream-to <remote>/<branch>` (the fix fills in the real values), then retry. A checkout that is not Git has nothing to refresh; making it a clone with an upstream is the user's call. || <a id="fetch_failed"></a>`fetch_failed` | `fetch_failed` | `git fetch` failed or did not finish within `sources.refresh_fetch_timeout_ms` (default 120000; `GBRAIN_REFRESH_FETCH_TIMEOUT_MS`; `--fetch-timeout-ms` wins over both). Nothing changed and no refresh record was written. | Retry. For a slow remote, raise the bound with `--fetch-timeout-ms <ms>` or `gbrain config set sources.refresh_fetch_timeout_ms <ms>`. Credentials are the user's: ask them to fix authentication rather than changing the remote. || <a id="refresh_git_unavailable"></a>`git_unavailable` | `git_unavailable` | A git command that reads the checkout's branch or remote (`symbolic-ref`, `remote`, `config --get branch.<branch>.remote` or `.merge`) failed or did not finish, so the checkout's state is unknown. The message names the command and git's first error line. A detached HEAD or an unset key is not this refusal. Nothing changed and no refresh record was written. | Run `git -C <checkout> status` to see why git cannot read the checkout, repair what it reports, then retry `gbrain sources refresh <source>`. |-| <a id="refresh_diverged"></a>`refresh_diverged` | `refresh_diverged` | The checkout has commits its upstream lacks, so a fast-forward is impossible. Nothing changed. | Ask the user, then publish the local commits merged with the upstream: `gbrain git commit-push --push-only --keep-checkout --path <checkout>` merges in memory, pushes the merge, refuses on a conflicting file and never moves the checkout (the refusal's fix fills in the real path and counts the local commits). Then retry `gbrain sources refresh <source>`, which fast-forwards to the merge. `gbrain sources reclone <source>` replaces the checkout instead and drops the local commits. With `sources.refresh_publish_diverged` unset on a worktree whose Git durability is on, or set to `true`, the refresh runs that publish itself, in a child process (the pre-push hook runs when the push is a fast-forward of HEAD), and then fast-forwards; it first scans every blob the local commits added and refuses `refresh_diverged` naming the file, line and rule (never the value) when one looks like a secret, and unset with durability not on refuses naming `gbrain sources writer git-durability <source> --enable`; a conflicting file then refuses `integrate_conflict` (with `gbrain.quarantine` on, the remote's version is published instead, this machine's is kept under `refs/gbrain/quarantine/`, and the refresh says so), and an uncommitted edit to a file the upstream changed refuses `refresh_dirty`, both with nothing pushed. The setting never publishes over a rewritten upstream: when the checkout holds a commit the upstream held before but no longer contains (a force-push), or gbrain has no record of the upstream before the fetch, the refresh still refuses `refresh_diverged` and the user decides. |+| <a id="refresh_diverged"></a>`refresh_diverged` | `refresh_diverged` | The checkout has commits its upstream lacks, so a fast-forward is impossible. Nothing changed. | Ask the user, then publish the local commits merged with the upstream: `gbrain git commit-push --push-only --keep-checkout --path <checkout>` merges in memory, pushes the merge, refuses on a conflicting file and never moves the checkout (the refusal's fix fills in the real path and counts the local commits). Then retry `gbrain sources refresh <source>`, which fast-forwards to the merge. `gbrain sources reclone <source>` replaces the checkout instead and drops the local commits. With `sources.refresh_publish_diverged` unset on a worktree whose Git durability is on, or set to `true`, the refresh runs that publish itself, in a child process that skips the pre-push hook, and then fast-forwards; that child first scans what the local commits add (messages, added lines, merge resolutions) and refuses [`publish_secret_found`](shared-checkout-git.md#publish_secret_found) naming the file, line and rule (never the value) when one looks like a secret, and unset with durability not on refuses naming `gbrain sources writer git-durability <source> --enable`; a conflicting file then refuses `integrate_conflict` (with `gbrain.quarantine` on, the remote's version is published instead, this machine's is kept under `refs/gbrain/quarantine/`, and the refresh says so), and an uncommitted edit to a file the upstream changed refuses `refresh_dirty`, both with nothing pushed. The setting never publishes over a rewritten upstream: when the checkout holds a commit the upstream held before but no longer contains (a force-push), or gbrain has no record of the upstream before the fetch, the refresh still refuses `refresh_diverged` and the user decides. || <a id="refresh_dirty"></a>`refresh_dirty` | `refresh_dirty` | Uncommitted or untracked files overlap the incoming upstream changes (the first 20 are named), or `git merge --ff-only` refused for the same reason. HEAD did not move. The merge runs under the checkout's commit lock, so a `gbrain git commit-push` in progress is waited out (#8117); a lock held past its wait refuses as `commit_lock_busy`, and another git process holding `.git/index.lock` refuses as `git_index_locked` after brief retries. Both are retryable. Uncommitted files outside the incoming changes do not refuse; they are kept and listed as `preserved_uncommitted`. | Commit or discard the named paths, then retry. Check `gbrain sources writer status <source> --json` first: a pending Git effect may be about to commit a gbrain-published file. || <a id="sync_in_progress"></a>`sync_in_progress` | `sync_in_progress` | A managed sync of one of the checkout's sources has an unfinished cursor. Moving the checkout now would strand it, and the refresh never waits on a sync. `gbrain repair frontmatter --apply` refuses the same way while an unfinished cursor still names a selected file. | Run the printed `gbrain sync --source <source> --no-pull ...` resume command (it keeps the cursor's options), then retry (for a repair, preview again and approve the new hash). || <a id="refresh_in_progress"></a>`refresh_in_progress` | `refresh_in_progress` | Another refresh of the same checkout is active and its process is still running (the message names its holder's pid and host when the active refresh row is already readable), or a command that changes which sources share the checkout (`sources add`, `remove`, `archive`, `restore`, `reclone`) ran while one was active. A refresh whose process died is not a reason to refuse: the next refresh on the owner host finishes it first (`--dry-run` does not, so it still refuses while the orphan stands, and neither does a refresh that cannot read the checkout's HEAD: it leaves the orphan as it is and refuses until git can read HEAD again; writer status then names `git -C <checkout> status` instead of the next refresh). A refresh whose holder is recorded on another host, or whose lock file this host cannot open, is never taken over either: writer status shows its `liveness` as `unknown` (its `next` names the host to run on), and `gbrain sources refresh <source> --resume` on the owner host finishes it once that host's refresh is known to have stopped. Pending publication or topology recovery on the checkout refuses `refresh_recovery_required` first. An interrupted refresh that needs a reset decision refuses `refresh_recovery_required` instead. | Wait for the running refresh, or check it with `gbrain sources writer status <source>` (`liveness`, `holder`). `gbrain sources refresh <source> --resume` finishes an orphaned one now; then retry the source command with the same request ID. |diff --git a/llms-full.txt b/llms-full.txtindex aa888256a4..b8356e3356 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -7686,13 +7686,16 @@ vars — incident-time escape hatches, not everyday knobs.means something commits into the checkout outside gbrain: fix that writerinstead of forcing the checkout([scripts and the managed checkout](shared-checkout-git.md#scripts-and-the-managed-checkout)).- When local commits there are expected (automations committing alongside a- sibling checkout that pushes the same branch), the user can give standing- consent with `gbrain config set sources.refresh_publish_diverged true`- (default off): a diverged refresh then pushes the local commits merged with- the upstream in memory, the same publish as+ When the worktree's Git durability is on, a diverged refresh publishes the+ local commits itself (`sources.refresh_publish_diverged` unset; `false` turns it+ off, `true` publishes even with durability off): under its publish lock it scans+ what those commits add (messages, added lines, merge resolutions) and refuses+ `publish_secret_found` naming the file, line and rule when one looks like a+ secret, otherwise it pushes+ the local commits merged with the upstream in memory, the same publish as`gbrain git commit-push --push-only --keep-checkout` run as a child process- (it skips the checkout's pre-push hook), and fast-forwards to the merge. It never moves the checkout to merge, a conflicting file refuses+ with `--scan-secrets` (it skips the checkout's pre-push hook), and fast-forwards+ to the merge. It never moves the checkout to merge, a conflicting file refuses`integrate_conflict` naming it with nothing pushed (with `gbrain.quarantine`on, the remote's version is published, this machine's is kept under`refs/gbrain/quarantine/`, and the refresh says so), an uncommitted edit to a@@ -10044,7 +10047,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| A command exited 3 (`confirmation_required`) | relay `user_message`; run `fix.command` only after the user agrees | agent, after the user agrees | the payload's `effects` | the fix's `verify` || A scheduled job, workspace script or hook finds nothing in the brain (every lookup empty), or its log shows `no_brain` or `GBRAIN_DB_ACCESS no_url`, while the same command works by hand | the job runs without the brain's config: call gbrain through one wrapper that sets `GBRAIN_HOME` and loads the brain's env file, and stop discarding its stderr ([the wrapper](cron-schedule.md#calling-gbrain-unattended)); `gbrain doctor --only cron_gbrain_home --json` names crontab lines that skip it | agent | none | the job's log shows results, and `gbrain engine status --json` run through the wrapper names the expected `db_url_source` || `gbrain sources refresh` refuses `refresh_not_owner` from cron or a script but works by hand | the caller resolves another gbrain home, so it is another host; the refusal names the identity file, `HOME` and `GBRAIN_HOME` it read. Set the owner's `GBRAIN_HOME` in the wrapper (not `HOME`, which also swaps git credentials); never copy or delete a `host.json` | agent | none | `gbrain sources refresh <id> --dry-run` through the wrapper |-| `gbrain sources refresh` refuses `refresh_diverged` on every run | something commits into the managed checkout outside gbrain, usually a script that writes files and runs `git commit` without pushing. `git log @{upstream}..HEAD` names the commits; move that writer to `gbrain git commit-push -- <paths>`, then publish the stray commits merged with the upstream (`gbrain git commit-push --push-only --keep-checkout --path <checkout>`) and retry, as the [refusal](write-refusals.md#refresh_diverged) says; never force ([scripts and the managed checkout](shared-checkout-git.md#scripts-and-the-managed-checkout)). When local commits there are expected, the user can instead turn on `sources.refresh_publish_diverged` (default off) so each refresh publishes them itself ([live sync](live-sync.md)) | agent; reconciling after the user agrees | `destructive` when reconciling drops local commits | `gbrain sources refresh <id> --dry-run` |+| `gbrain sources refresh` refuses `refresh_diverged` on every run | something commits into the managed checkout outside gbrain, usually a script that writes files and runs `git commit` without pushing. `git log @{upstream}..HEAD` names the commits; move that writer to `gbrain git commit-push -- <paths>`, then publish the stray commits merged with the upstream (`gbrain git commit-push --push-only --keep-checkout --path <checkout>`) and retry, as the [refusal](write-refusals.md#refresh_diverged) says; never force ([scripts and the managed checkout](shared-checkout-git.md#scripts-and-the-managed-checkout)). With the worktree's Git durability on, each refresh publishes them itself unless `sources.refresh_publish_diverged` is `false` (the refusal names a durability that is not on, or a value that looks like a secret in the local commits) ([live sync](live-sync.md)) | agent; reconciling after the user agrees | `destructive` when reconciling drops local commits | `gbrain sources refresh <id> --dry-run` || A `--json` caller fails to parse gbrain's output | something other than gbrain wrote to stdout, usually a wrapper or a hook it runs; send that output to a log file or stderr (gbrain's own notices already go to stderr) | agent | none | the same call piped to `jq .` parses || gbrain calls time out from a script or language runtime but finish by hand, or each search takes several seconds | a cold CLI start takes 3–6 s on a pooled Postgres brain: set caller timeouts of at least 10 s in both the shell and the runtime (a runtime exec timeout can override the shell's), and turn on the [warm CLI socket](cli-socket.md). If warm searches stay slow, measure the round trip to the database; one in another region dominates search time | agent; moving the database after the user agrees | none | `GBRAIN_DEBUG=1 gbrain search <query>` prints a `[cli-socket] warm:` line || After a database change some processes still use the old server, or a URL variable silently keeps its old value | a shell-sourced env file has an unquoted `&` (the assignment ends there), or a process kept the environment it started with. Quote every value, keep Postgres URLs to `?sslmode=require` (driver options as variables, such as `GBRAIN_PREPARE=false`), update every URL variable the tooling reads, restart every gbrain process, and prove the switch from the database side ([switching a database](../../INSTALL_FOR_AGENTS.md#switching-a-database)). Never paste `env` output into a transcript while debugging | agent, after the user agrees | none | a row written after the restart appears on the new server |diff --git a/src/commands/git.ts b/src/commands/git.tsindex 21a58cd48f..0768737dbe 100644--- a/src/commands/git.ts+++ b/src/commands/git.ts@@ -50,6 +50,8 @@ Flags:--keep-checkout With --push-only: never move the checkout and skip its pre-push hook. The onepublish allowed in a managed canonical worktree (its Git effects' integrate_conflictfix); gbrain sources refresh brings the merged remote files in afterwards.+ --scan-secrets With --push-only: before pushing, scan what the unpublished commits add (messages,+ added lines, merge resolutions) and refuse publish_secret_found on a finding.--pull Bring remote commits in (fast-forward, or an in-memory merge); never pushes.--require-clean Unattended rule: --pull skips when the checkout has any local edit;a push never advances a checkout that has one, and never waits for@@ -81,12 +83,12 @@ is installed.`;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;+ pending: boolean; allowOutside: boolean; install: boolean; uninstall: boolean; scanSecrets: boolean;}function parse(args: string[]): Parsed {const p: Parsed = { json: false, pushOnly: false, pull: false, requireClean: false, dryRun: false, help: false, keepCheckout: false, paths: [], resolve: [], base: [],- pending: false, allowOutside: false, install: false, uninstall: false };+ pending: false, allowOutside: false, install: false, uninstall: false, scanSecrets: false };let rest = false;for (let i = 0; i < args.length; i++) {const a = args[i];@@ -103,6 +105,7 @@ function parse(args: string[]): Parsed {else if (a === '--json') p.json = true;else if (a === '--push-only') p.pushOnly = true;else if (a === '--keep-checkout') p.keepCheckout = true;+ else if (a === '--scan-secrets') p.scanSecrets = true;else if (a === '--pull') p.pull = true;else if (a === '--require-clean') p.requireClean = true;else if (a === '--dry-run') p.dryRun = true;@@ -188,7 +191,7 @@ export async function runGit(args: string[]): Promise<number> {if (!p.path) assertSourceCheckout(repo);const cwd = p.path ? realpathSync(p.path) : process.cwd();if ((p.pull && p.pushOnly) || (p.pull && (p.message || p.paths.length || p.resolve.length || p.branch))- || (p.pushOnly && (p.message || p.paths.length)) || ((p.resolve.length || p.branch || p.expectRemote || p.keepCheckout) && !p.pushOnly)+ || (p.pushOnly && (p.message || p.paths.length)) || ((p.resolve.length || p.branch || p.expectRemote || p.keepCheckout || p.scanSecrets) && !p.pushOnly)|| (p.pending && (p.pull || p.pushOnly || p.paths.length)) || (p.allowOutside && p.pull) || (p.base.length && (p.pull || p.pushOnly || p.pending))) {throw opError('commit_paths_invalid', 'These flags do not combine.','Use one mode: -m <msg> -- <paths> (commit + push), --pending [-m <msg>], --push-only [--keep-checkout] [--branch <b>] [--expect-remote <sha> --resolve ...], or --pull [--require-clean].');@@ -228,6 +231,7 @@ export async function runGit(args: string[]): Promise<number> {...(p.pending ? { pending: true } : {}),...(p.allowOutside ? { allowOutsideSourceRoot: true } : {}),...(p.keepCheckout ? { keepCheckout: true } : {}),+ ...(p.scanSecrets ? { scanSecrets: true } : {}),...(p.branch ? { branch: p.branch } : {}),...(p.resolve.length ? { resolutions: parseResolutions(p.resolve) } : {}),...(p.expectRemote ? { expectRemote: p.expectRemote } : {}),diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 9e398da54b..1dbec06493 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1485,7 +1485,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.611.0', id: 'managed_sync_kind_reserved_8765', text: 'A page write that passes a `kind` starting with `managed_sync_` (for example `capture` with `kind: managed_sync_import`) is now refused `invalid_params` and writes nothing: that prefix is reserved for managed sync, and with `persistence.refresh_barrier` on a waiting write now tells sync\'s own imports apart from later writes by the operation that wrote them, not by the kind. Use another kind, or drop `kind`.' },{ since: '0.60.614.0', id: 'refresh_barrier_aborted_refresh_sync_gst1853', text: 'While a checkout\'s last `gbrain sources refresh` ended without completing (aborted, abandoned, or rolled back after its process died), every refresh run on the owner host, including one refused `refresh_diverged`, now ends by running the managed `--no-pull` sync of each source behind the checkout HEAD, listed in its `synced` (a refusal\'s message names them). With `persistence.refresh_barrier` on, a write held behind that refresh for a commit sync had not imported is therefore decided in that run instead of waiting for a later refresh: a `put_page` with `expected_revision` ends `revision_conflict`, a blind one lands and names what it replaced in `supersedes`, and a `remember` or `add_timeline_entry` applies on top.' },{ since: '0.60.608.0', id: 'refresh_barrier_later_write_gst1623', text: 'With `persistence.refresh_barrier` on, a write that waited behind a refresh or an import (other than a `remember` or `add_timeline_entry`, which still applies on top) now ends `revision_conflict` instead of applying when a later write to the same page committed first, which a consumer from an older release can cause; read the page again and resubmit with a new `request_id`. A write held again and again behind imports now expires once it has waited four wait limits (at least 4 hours) since its admission, even when each hold is shorter than one wait limit. With the barrier on or off, a plain-git commit that lands on the start commit right before a refresh merges makes git refuse the fast-forward, and the refresh now ends `refresh_source_changed` with the fence lifted and the commit kept, instead of leaving the checkout `recovery_required`; one that lands right after the merge is recorded and synced.' },- { since: '0.60.616.0', id: 'refresh_publish_diverged_default_gbra386', text: 'A diverged managed checkout now publishes its local commits on `gbrain sources refresh` by default when the worktree\'s Git durability is on: `sources.refresh_publish_diverged` unset now means on there (it used to mean off), merged with the upstream in memory, never rebased or forced. Every automatic publish first scans the blobs the local commits added and refuses `refresh_diverged` naming the file, line and rule when one looks like a secret. Unset with durability not on still refuses, naming `gbrain sources writer git-durability <source> --enable`; `false` turns it off. The keep-checkout publish now runs the checkout\'s pre-push hook when it pushes HEAD itself as a fast-forward.' },+ { since: '0.60.616.0', id: 'refresh_publish_diverged_default_gbra386', text: 'A diverged managed checkout now publishes its local commits on `gbrain sources refresh` by default when the worktree\'s Git durability is on: `sources.refresh_publish_diverged` unset now means on there (it used to mean off), merged with the upstream in memory, never rebased or forced. Every automatic publish first scans what the local commits add (messages, added lines, merge resolutions) and refuses the new `publish_secret_found` naming the file, line and rule, never the value, when one looks like a secret; `gbrain git commit-push --push-only --scan-secrets` runs the same gate. Unset with durability not on still refuses, naming `gbrain sources writer git-durability <source> --enable`; `false` turns it off.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex b7eb67e502..fce071d59d 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -73,12 +73,12 @@ 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', '--autostash', '--base', '--batch-check', '--brain', '--branch', '--cached', '--cacheinfo', '--cherry-mark', '--count', '--dry-run', '--enable', '--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-autostash', '--no-commit-id', '--no-cron', '--no-gpg-sign', '--no-merges', '--no-recurse-submodules', '--no-renames', '--no-tags', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--repo', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--short', '--show-toplevel', '--source', '--staged', '--stat', '--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', '--autostash', '--base', '--batch-check', '--brain', '--branch', '--cached', '--cacheinfo', '--cherry-mark', '--count', '--dry-run', '--enable', '--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-autostash', '--no-commit-id', '--no-cron', '--no-gpg-sign', '--no-merges', '--no-recurse-submodules', '--no-renames', '--no-tags', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--repo', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--scan-secrets', '--short', '--show-toplevel', '--source', '--staged', '--stat', '--topo-order', '--type', '--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-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', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--gbrain-bin', '--get', '--harness', '--help', '--instructions', '--instructions-only', '--jq', '--json', '--limit', '--name-only', '--no-instructions', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--scan-secrets', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 24093bca22..5d2d158761 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -577,6 +577,7 @@ export const CODES = {serve_self_exit_suppressed: { class: 'host_only', summary: "gbrain serve stayed at restart_required past GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS but did not exit, because it had already exited on its own 3 times within the hour; `/health?deep=1` reports self_exit_suppressed.", why: "The opt-in self-exit keeps a durable ledger (serve-self-exit.json under the gbrain home). A serve that reaches restart_required again right after every restart has a cause a restart does not fix, so after 3 self-exits in an hour it keeps serving reads and leaves the decision to a human instead of looping.", docs: 'docs/ENGINES.md#serve-unhealthy-exit', suggestion: 'Run gbrain sources writer status --json and gbrain doctor --json, report both with the serve log lines, then restart serve by hand.' },serve_unhealthy_exit: { class: 'unavailable', exit: 69, summary: "gbrain serve exited on its own because its persistence consumer reported restart_required continuously for GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS.", why: "Opt-in (off by default, at least 120 s): a supervisor that restarts on failure, such as the installed gbrain-serve service, then starts a fresh serve without a human. Cleanup is bounded (5 s) because the consumer's stop waits on the stuck work, so the process exits even when it cannot drain. Abandoned claims lapse with the exited process's heartbeat; journaled writes resume on the next owner.", docs: 'docs/ENGINES.md#serve-unhealthy-exit', suggestion: 'Let the supervisor restart serve; if it exits this way again soon after, run gbrain doctor --json and gbrain sources writer status --json and report both with the exit line.' },persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },+ publish_secret_found: { class: 'consent', summary: "An automatic publish found values that look like secrets (or text too large to scan) in the commits it was about to push; nothing was pushed.", docs: 'docs/guides/shared-checkout-git.md#publish_secret_found', actor: 'user' },push_unconfirmed: { class: 'retryable', summary: "The commit is durable locally but no push destination confirmed it.", docs: 'docs/guides/shared-checkout-git.md#outcomes', exit: 4 },schema_lock_blocked: { class: 'retryable', summary: "A schema step (the schema.sql replay in init/upgrade, or one migration) waited its lock_timeout for a table lock another session holds and stopped instead of hanging.", why: "Every ALTER TABLE in the replay takes an ACCESS EXCLUSIVE lock even as a no-op, so one open transaction in another client (idle in transaction, a stuck job) blocked gbrain init and upgrade forever with no output. The wait is now bounded (GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS, default 60) and the refusal names the blocking sessions by pid, application and state, sampled while the wait was active; query text is never shown. The cancelled step changed nothing.", docs: 'docs/ENGINES.md#schema-lock-blocked', suggestion: 'Let the named session finish or, with the user\'s agreement, end it on the database host with SELECT pg_terminate_backend(<pid>), then rerun the same gbrain command; init retries a few times on its own with a short backoff.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the database, the pooler and the schema version so the rerun is judged against the current state.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },pg_connection_recovery_failed: { class: 'retryable', summary: "A Postgres connection the driver retired after an incident (stuck, desynced, or closed under running statements) could not reconnect; statements waiting for it failed with the connect error.", why: "The database or pooler refused or dropped the new connection (unreachable host, exhausted connection slots, rotated credentials). The next statement retries the connect, and the connection stays marked until one succeeds, so a repeating line means the pool is not recovering on its own.", docs: 'docs/ENGINES.md#pg-connection-recovery-failed', suggestion: 'Check the database and pooler from the serve host (gbrain doctor --only pool_reap_health --json); a serve that keeps logging this line needs the database reachable again, then a restart if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--only', 'pool_reap_health', '--json'], consent: [], actor: 'agent', why: 'Read-only: counts the recent stuck, desync and recovery events serve recorded.', requires_exclusive: false } },diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.tsindex 436380ea90..5692c165a0 100644--- a/src/core/git/commit-push.ts+++ b/src/core/git/commit-push.ts@@ -27,6 +27,7 @@*/import { appendFileSync, existsSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';+import { findingsInLog, rangeScanArgs } from './range-secret-scan.ts';import { isAbsolute, join, relative, resolve } from 'node:path';import { execFileSync } from '../spawn.ts';import { gitChildEnv, literalPathspecs } from '../git-env.ts';@@ -115,6 +116,8 @@ export interface CommitPushOptions {branch?: string;/** Push-only: never advance the checkout and skip its pre-push hook (a managed canonical worktree; see the header). */keepCheckout?: boolean;+ /** Before pushing, scan what the commits the upstream lacks add (messages, added lines, merge resolutions) and refuse `publish_secret_found` on a finding: the gate for automatic publishes of commits gbrain did not write. */+ scanSecrets?: boolean;/** Commit the pending write-through files (`--pending`) instead of named paths. */pending?: boolean;/** Commit and publish files outside the configured source root(s): the user's explicit choice, or gbrain's own scaffolding at the checkout root. */@@ -136,13 +139,14 @@ interface Ctx {interface GitRun { code: number; stdout: string; stderr: string }-function git(root: string, args: string[], opts: { auth?: boolean; timeoutMs?: number; env?: NodeJS.ProcessEnv; input?: string } = {}): GitRun {+function git(root: string, args: string[], opts: { auth?: boolean; timeoutMs?: number; env?: NodeJS.ProcessEnv; input?: string; maxBuffer?: number } = {}): GitRun {const base = opts.auth ? { ...GIT_ENV_AUTH } : { ...GIT_ENV };try {const stdout = execFileSync('git', ['-C', root, ...args], {stdio: ['pipe', 'pipe', 'pipe'],input: opts.input ?? '',timeout: opts.timeoutMs ?? 60_000,+ ...(opts.maxBuffer ? { maxBuffer: opts.maxBuffer } : {}),env: gitChildEnv({ ...base, LC_ALL: 'C', LANGUAGE: 'C', ...opts.env }),}).toString();return { code: 0, stdout, stderr: '' };@@ -938,7 +942,7 @@ function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> |if (attempt) Atomics.wait(sleeper, 0, 0, Math.min(2000, 50 * 2 ** attempt) + Math.floor(Math.random() * 100));let remoteTip = bound && !isAncestor(ctx.root, bound, candidate) ? bound : null;if (!remoteTip) {- const push = remoteGit(ctx.root, 'push', [...(ctx.keepCheckout && candidate !== start ? ['--no-verify'] : []), ...(bound ? [`--force-with-lease=${ctx.mergeRef}:${bound}`] : []), '--', ctx.remote, `${candidate}:${ctx.mergeRef}`]);+ const push = remoteGit(ctx.root, 'push', [...(ctx.keepCheckout ? ['--no-verify'] : []), ...(bound ? [`--force-with-lease=${ctx.mergeRef}:${bound}`] : []), '--', ctx.remote, `${candidate}:${ctx.mergeRef}`]);if (push.code === 0) return { sha: candidate, integrated, confirmed: 'push', ...notes() };lastError = push.stderr.trim();if (remoteContains(ctx, candidate)) return onRemote();@@ -1019,6 +1023,24 @@ function assertLocalCommitsInsideRoots(ctx: Ctx, target: string, roots: string[]docs: 'docs/guides/shared-checkout-git.md#source-roots' } });}+/** The automatic-publish secret gate: scan what the commits in trackingRef..target add (the exact range this publish pushes, under its lock). */+function assertNoSecretsInRange(ctx: Ctx, target: string): void {+ const log = git(ctx.root, rangeScanArgs(ctx.trackingRef, target), { timeoutMs: 300_000, maxBuffer: 1024 * 1024 * 1024 });+ const scan = log.code === 0 ? findingsInLog(ctx.root, log.stdout) : null;+ if (scan && !scan.findings.length && !scan.unscanned.length) return;+ const named = scan ? [...scan.findings.map(f => `${f.path}:${f.line} (${f.pattern}, ${f.commit.slice(0, 7)})`), ...scan.unscanned.map(u => `${u.path} (too large to scan, ${u.commit.slice(0, 7)})`)] : [];+ throw opError('publish_secret_found', scan+ ? `${named.length} item(s) in the local commits ${ctx.trackingRef}..${target.slice(0, 12)} look like secrets or could not be scanned: ${named.slice(0, 10).join(', ')}${named.length > 10 ? ', ...' : ''}. Nothing was pushed.`+ : `git could not list the local commits ${ctx.trackingRef}..${target.slice(0, 12)} to scan them for secrets (${log.stderr.trim().slice(0, 200) || `exit ${log.code}`}). Nothing was pushed.`,+ 'Remove the value from those commits (rewriting unpushed local commits is the user\'s call), or add a false positive\'s fingerprint to .gbrain-scan-allow, then retry. Never publish them with a command that skips this scan.',+ { detail: JSON.stringify(scan ?? { error: 'unreadable' }),+ fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,+ argv: ['git', '-C', ctx.root, 'log', '--stat', `${ctx.trackingRef}..${target}`],+ why: 'Lists the unpublished commits the scan refused; read-only. A secret pushed to the remote stays in its history.',+ user_message: `Unpublished commits in ${ctx.root} hold ${named.length || 'some'} item(s) that look like secrets or could not be scanned (${named.slice(0, 3).join(', ')}). Nothing was pushed. Remove them from those commits, or confirm a false positive so it can be allowlisted by fingerprint?`,+ docs: 'docs/guides/shared-checkout-git.md#publish_secret_found' } });+}+/** Advance the shared checkout (caller holds the commit lock) with a real compare-and-swap: fast-forward only, hooks off, never autostash. */function advanceLocked(root: string, target: string, expectedHead: string): { checkout: CheckoutState; reason?: string } {const head = git(root, ['rev-parse', 'HEAD']).stdout.trim();@@ -1194,6 +1216,7 @@ export function commitAndPush(opts: CommitPushOptions): CommitPushResult {const head = gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');const target = start && !isAncestor(root, start, head) ? start : head;if (!opts.allowOutsideSourceRoot) assertLocalCommitsInsideRoots(ctx, target, roots);+ if (opts.scanSecrets) assertNoSecretsInRange(ctx, target);const published = publish(ctx, target, resolutions, expectRemote, cwd);if (!elsewhere) rmSync(absGitPath(root, CONFLICT_STATE_NAME), { force: true });const moved = published.sha === head || elsewhere || opts.keepCheckout ? { checkout: 'unchanged' as const } : advanceWithLock(root, published.sha, head, onlyWhenClean, opts.lockWaitMs);diff --git a/src/core/git/range-secret-scan.ts b/src/core/git/range-secret-scan.tsindex d90bcf6afc..879f533495 100644--- a/src/core/git/range-secret-scan.ts+++ b/src/core/git/range-secret-scan.ts@@ -1,59 +1,59 @@/**- * Secret scan over the commits an automatic publish would push. A push from a checkout gbrain did not write (a script's- * plain `git commit`) never passed the write path's scan, so before refresh publishes a diverged checkout on its own every- * blob a commit in `base..head` adds or changes is scanned once with the workspace allowlist (`.gbrain-scan-allow`).- * Findings carry the path, line, rule and fingerprint, never the matched value. Merge commits are not listed (their- * parents' blobs are), binary and over-cap blobs are skipped like scanFiles skips them.+ * Secret scan over the commits an automatic publish pushes. A commit gbrain did not write (a script's plain+ * `git commit`) never passed the write path's scan, so the publish scans, under its publish lock and for the exact+ * commit it pushes, what each commit in `base..head` adds: its message, the lines it adds file by file (a value a later+ * commit removed is still in the pushed history), and for a merge commit the lines it adds that neither parent has+ * (a conflict resolution). The workspace allowlist (`.gbrain-scan-allow`: path globs and fingerprints) applies.+ * Findings carry the path, line, rule, fingerprint and commit, never the matched value. Binary changes carry no lines;+ * a file whose added text is over the scan cap cannot be scanned and is reported as such, so callers refuse.*/-import { spawn } from 'node:child_process';-import { gitChildEnv } from '../git-env.ts';import { loadWorkspaceAllowlist, pathAllowlisted } from '../secret-scan-allowlist.ts';-import { looksBinaryBuffer, scanText, SCAN_MAX_FILE_BYTES } from '../secret-scan.ts';+import { scanText, SCAN_MAX_FILE_BYTES } from '../secret-scan.ts';export interface RangeSecretFinding { path: string; commit: string; line: number; pattern: string; fingerprint: string }+export interface RangeScan { findings: RangeSecretFinding[]; unscanned: Array<{ path: string; commit: string }> }-function run(root: string, args: string[], input?: string): Promise<{ code: number; stdout: Buffer }> {- return new Promise(resolve => {- const child = spawn('git', ['-C', root, '-c', 'core.quotePath=false', ...args], { env: gitChildEnv({ GIT_TERMINAL_PROMPT: '0' }), stdio: ['pipe', 'pipe', 'ignore'] });- const chunks: Buffer[] = [];- child.stdout.on('data', (chunk: Buffer) => chunks.push(chunk));- child.on('error', () => resolve({ code: -1, stdout: Buffer.alloc(0) }));- child.on('close', code => resolve({ code: code ?? -1, stdout: Buffer.concat(chunks) }));- child.stdin.end(input ?? '');- });+/** The `git log` arguments whose output findingsInLog reads. */+export function rangeScanArgs(base: string, head: string): string[] {+ return ['-c', 'core.quotePath=false', 'log', '--no-renames', '--no-ext-diff', '--no-textconv', '--no-color', '--diff-merges=dense-combined',+ '--unified=0', '-p', '--format=commit %H%n%B%n%x00', `${base}..${head}`, '--'];}-/** Findings in the blobs `base..head` adds or changes; null when git cannot list or read them (callers refuse). */-export async function scanCommitRange(root: string, base: string, head: string): Promise<RangeSecretFinding[] | null> {- const log = await run(root, ['log', '--no-renames', '--raw', '--no-abbrev', '--format=commit %H', `${base}..${head}`, '--']);- if (log.code !== 0) return null;- const blobs = new Map<string, { path: string; commit: string }>();- let commit = '';- for (const line of log.stdout.toString('utf8').split('\n')) {- if (line.startsWith('commit ')) { commit = line.slice(7).trim(); continue; }- const raw = /^:\d+ (\d+) [0-9a-f]+ ([0-9a-f]+) [AMT]\t(.+)$/.exec(line);- if (raw && raw[1] !== '160000' && !/^0+$/.test(raw[2]) && !blobs.has(raw[2])) blobs.set(raw[2], { path: raw[3], commit });- }- if (!blobs.size) return [];+/** The commit message as `path` in a finding. */+export const MESSAGE_PATH = '(commit message)';++export function findingsInLog(root: string, log: string): RangeScan {const allowlist = loadWorkspaceAllowlist(root);- const wanted = [...blobs].filter(([, at]) => !pathAllowlisted(at.path, allowlist));- const sizes = await run(root, ['cat-file', '--batch-check=%(objectname) %(objectsize)'], wanted.map(([sha]) => sha).join('\n') + '\n');- if (sizes.code !== 0) return null;- const small = new Set(sizes.stdout.toString('utf8').split('\n').map(line => line.split(' ')).filter(([, size]) => Number(size) <= SCAN_MAX_FILE_BYTES).map(([sha]) => sha));- const read = wanted.filter(([sha]) => small.has(sha));- if (!read.length) return [];- const batch = await run(root, ['cat-file', '--batch'], read.map(([sha]) => sha).join('\n') + '\n');- if (batch.code !== 0) return null;- const out: RangeSecretFinding[] = [];- let at = 0;- for (const [sha, where] of read) {- const headerEnd = batch.stdout.indexOf(0x0a, at);- const [name, , size] = batch.stdout.subarray(at, headerEnd).toString('utf8').split(' ');- if (name !== sha) return null;- const body = batch.stdout.subarray(headerEnd + 1, headerEnd + 1 + Number(size));- at = headerEnd + 1 + Number(size) + 1;- if (looksBinaryBuffer(body)) continue;- for (const f of scanText(body.toString('utf8'), { allowlist })) out.push({ path: where.path, commit: where.commit, line: f.line, pattern: f.pattern, fingerprint: f.fingerprint });+ const scan: RangeScan = { findings: [], unscanned: [] };+ let commit = '', path: string | null = null, next = 0, combined = false, inMessage = false;+ let added: string[] = [], at: number[] = [];+ const flush = () => {+ if (path && added.length && (path === MESSAGE_PATH || !pathAllowlisted(path, allowlist))) {+ const text = added.join('\n');+ if (Buffer.byteLength(text) > SCAN_MAX_FILE_BYTES) scan.unscanned.push({ path, commit });+ else for (const f of scanText(text, { allowlist })) scan.findings.push({ path, commit, line: at[f.line - 1] ?? f.line, pattern: f.pattern, fingerprint: f.fingerprint });+ }+ added = []; at = [];+ };+ for (const line of log.split('\n')) {+ if (inMessage) {+ if (line === '\0') { flush(); inMessage = false; path = null; continue; }+ added.push(line); at.push(added.length);+ continue;+ }+ if (line.startsWith('commit ') && /^commit [0-9a-f]{40,64}$/.test(line)) { flush(); commit = line.slice(7); path = MESSAGE_PATH; inMessage = true; continue; }+ if (line.startsWith('diff --git ') || line.startsWith('diff --cc ') || line.startsWith('diff --combined ')) { flush(); path = null; combined = !line.startsWith('diff --git '); continue; }+ if (line.startsWith('+++ ')) { path = line === '+++ /dev/null' ? null : line.slice(4).replace(/^"?b\//, '').replace(/"$/, ''); continue; }+ const hunk = /^@@@? -\d+(?:,\d+)? (?:-\d+(?:,\d+)? )?\+(\d+)(?:,\d+)? @@@?/.exec(line);+ if (hunk) { next = Number(hunk[1]); continue; }+ if (!path) continue;+ if (combined) {+ const prefix = line.slice(0, 2);+ if (prefix.includes('-') || prefix.length < 2) continue;+ if (prefix === '++') { added.push(line.slice(2)); at.push(next); }+ next++;+ } else if (line.startsWith('+')) { added.push(line.slice(1)); at.push(next++); }}- return out;+ flush();+ return scan;}diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex bbf0b54742..4f83509688 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -50,7 +50,6 @@ import { classifyPgAccessError } from '../pg-access-classify.ts';import { classifyOriginUniqueViolation } from './origin-guard.ts';import { refreshProgress, refreshRetryHint, seconds } from './refresh-retry-hint.ts';import { ledgerLocation, readLedger } from '../git/commit-ledger.ts';-import { scanCommitRange } from '../git/range-secret-scan.ts';import { gitDurabilityPolicy } from './git-durability-policy.ts';export interface WorktreeRefreshRow {@@ -496,10 +495,6 @@ async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTiif (publishDiverged === 'default' && !(await gitDurabilityPolicy(binding, root)).durable) throw await divergedRefusal(git, root, sourceId, upstreamRef, oldHead, targetHead,'Git durability is not on for this worktree, so nothing leaves it through Git on its own.',` To let every refresh publish it on its own, the user can turn Git durability on (gbrain sources writer git-durability ${sourceId} --enable) or run gbrain config set ${REFRESH_PUBLISH_DIVERGED_KEY} true.`);- const secrets = await scanCommitRange(root, targetHead, oldHead);- if (!secrets || secrets.length) throw await divergedRefusal(git, root, sourceId, upstreamRef, oldHead, targetHead, !secrets- ? `gbrain could not read the local commits to scan them for secrets (git log or git cat-file failed).`- : `Its local commits hold ${secrets.length} value(s) that look like secrets: ${secrets.slice(0, 10).map(s => `${s.path}:${s.line} (${s.pattern}, ${s.commit.slice(0, 7)})`).join(', ')}${secrets.length > 10 ? ', ...' : ''}. Remove them from those commits, or allowlist a false positive by its fingerprint in .gbrain-scan-allow.`);const localCommits = Number((await read(['rev-list', '--count', `${targetHead}..${oldHead}`])).stdout.trim()) || 0;const pushed = await publishInChild(root, sourceId, targetHead);const published = { sha: pushed.sha ?? targetHead, local_commits: localCommits, integrated: pushed.integrated,@@ -525,7 +520,7 @@ async function publishInChild(root: string, sourceId: string, checkedUpstream: sconst cli = resolveChildCliInvocation(process.env, process.execPath, process.argv[1], () => null);if (!cli) throw opError('git_push_unavailable', `This process could not locate its own CLI executable to publish the diverged checkout ${root}; nothing was pushed.`,`Set ${CHILD_ENV.childCliOverride} to the path of the CLI executable and retry gbrain sources refresh ${sourceId}, or publish by hand: gbrain git commit-push --push-only --keep-checkout --path ${q(root)}.`);- const child = await execFileBounded(cli.cmd, [...cli.argsPrefix, 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', root, '--expect-remote', checkedUpstream, '--json'], {+ const child = await execFileBounded(cli.cmd, [...cli.argsPrefix, 'git', 'commit-push', '--push-only', '--keep-checkout', '--scan-secrets', '--path', root, '--expect-remote', checkedUpstream, '--json'], {timeout: PUBLISH_TIMEOUT_MS, termGraceMs: 10_000, maxBuffer: 1024 * 1024,env: { ...process.env, GBRAIN_PUBLISH_LOCK_WAIT_SECONDS: '0', GBRAIN_PUSH_LOCK_WAIT_SECONDS: '0' },});diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex ea91f74979..16daec3912 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6840,7 +6840,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/guarded-publish.test.ts b/test/guarded-publish.test.tsindex 2045f2f845..8a10d77f29 100644--- a/test/guarded-publish.test.ts+++ b/test/guarded-publish.test.ts@@ -1,19 +1,18 @@/**- * Guards on an automatic publish of commits gbrain did not write: the commit-range secret scan- * (scanCommitRange) and the pre-push hook on a keep-checkout publish that is a plain fast-forward.- * Protects: a value that looks like a secret in any blob a local commit added is found even when a later- * commit removed it, with the path, line and rule but never the value; a fingerprint in .gbrain-scan-allow- * and binary blobs are skipped; a keep-checkout publish of HEAD itself runs the checkout's pre-push hook, so- * a refusing hook stops the push.+ * The secret gate on automatic publishes (`commitAndPush({ pushOnly, keepCheckout, scanSecrets })`, the publish+ * `gbrain sources refresh` runs in its child): it scans, under the publish lock, what the commits it is about to push add.+ * Protects: a value that looks like a secret is found in an added line even when a later commit removed it, in a+ * commit message, and in a merge commit's conflict resolution, named by path, line, rule and commit but never by+ * value, and nothing is pushed; a fingerprint in .gbrain-scan-allow and a binary file are skipped; a clean range+ * publishes; without scanSecrets nothing changes.* Seams: none; real repositories and a bare remote.*/import { afterAll, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';-import { chmodSync, existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { commitAndPush } from '../src/core/git/commit-push.ts';-import { scanCommitRange } from '../src/core/git/range-secret-scan.ts';const dir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-guarded-publish-')));afterAll(() => rmSync(dir, { recursive: true, force: true }));@@ -30,44 +29,63 @@ function repo(name: string): { remote: string; root: string; base: string } {git(root, 'add', '.'); git(root, 'commit', '-qm', 'init'); git(root, 'push', '-q', '-u', 'origin', 'main');return { remote, root, base: git(root, 'rev-parse', 'HEAD') };}-const commit = (root: string, file: string, content: string | Buffer) => {- writeFileSync(join(root, file), content); git(root, 'add', file); git(root, 'commit', '-qm', `edit ${file}`);+const commit = (root: string, file: string, content: string | Buffer, message = `edit ${file}`) => {+ writeFileSync(join(root, file), content); git(root, 'add', file); git(root, 'commit', '-qm', message);return git(root, 'rev-parse', 'HEAD');};+const publish = (root: string, scanSecrets = true) => commitAndPush({ repo: root, cwd: root, paths: [], pushOnly: true, keepCheckout: true, ...(scanSecrets ? { scanSecrets: true } : {}) });+const refused = (fn: () => unknown) => {+ try { fn(); } catch (e) { return e as { code: string; message: string; detail?: string; fix?: { user_message?: string } }; }+ throw new Error('expected publish_secret_found');+};+const remoteTip = (r: { remote: string }) => git(r.remote, 'rev-parse', 'refs/heads/main');-test('a secret a local commit added is found even after a later commit removed it, without its value', async () => {- const r = repo('scan');+test('a secret an unpushed commit added is refused even after a later commit removed it, named without its value', () => {+ const r = repo('removed');const added = commit(r.root, 'notes.md', `line one\nDeploy token ${token}\n`);commit(r.root, 'notes.md', 'line one\nredacted\n');- commit(r.root, 'clean.md', 'nothing here\n');- const findings = await scanCommitRange(r.root, r.base, 'HEAD');- expect(findings).toHaveLength(1);- expect(findings![0]).toMatchObject({ path: 'notes.md', commit: added, line: 2 });- expect(JSON.stringify(findings)).not.toContain(token);- expect(await scanCommitRange(r.root, 'HEAD', 'HEAD')).toEqual([]);+ const error = refused(() => publish(r.root));+ expect(error.code).toBe('publish_secret_found');+ expect(error.message).toContain(`notes.md:2 (`);+ expect(error.message).toContain(added.slice(0, 7));+ expect(JSON.stringify(error)).not.toContain(token);+ expect(remoteTip(r)).toBe(r.base);+});++test('a secret in a commit message is refused', () => {+ const r = repo('message');+ commit(r.root, 'page.md', 'a page\n', `rotate ${token}`);+ const error = refused(() => publish(r.root));+ expect(error.message).toContain('(commit message):1 (');+ expect(remoteTip(r)).toBe(r.base);});-test('a fingerprint in .gbrain-scan-allow and a binary blob are skipped; an unreadable range is null', async () => {+test('a secret typed into a merge commit\'s conflict resolution is refused', () => {+ const r = repo('merge');+ git(r.root, 'checkout', '-q', '-b', 'side');+ commit(r.root, 'readme.md', 'side version\n');+ git(r.root, 'checkout', '-q', 'main');+ commit(r.root, 'readme.md', 'main version\n');+ try { git(r.root, 'merge', '-q', 'side'); } catch { /* conflict expected */ }+ writeFileSync(join(r.root, 'readme.md'), `resolved with ${token}\n`);+ git(r.root, 'add', 'readme.md'); git(r.root, 'commit', '-qm', 'merge side');+ const error = refused(() => publish(r.root));+ expect(error.message).toContain('readme.md:1 (');+ expect(remoteTip(r)).toBe(r.base);+});++test('an allowlisted fingerprint and a binary file are skipped and the clean range publishes; without scanSecrets nothing is scanned', () => {const r = repo('allow');commit(r.root, 'data.bin', Buffer.concat([Buffer.from([0, 1, 2]), Buffer.from(token)]));commit(r.root, 'notes.md', `Deploy token ${token}\n`);- const [finding] = (await scanCommitRange(r.root, r.base, 'HEAD'))!;- expect(finding.path).toBe('notes.md');- writeFileSync(join(r.root, '.gbrain-scan-allow'), `${finding.fingerprint}\n`);- expect(await scanCommitRange(r.root, r.base, 'HEAD')).toEqual([]);- expect(await scanCommitRange(r.root, r.base, 'no-such-ref')).toBeNull();-});+ const error = refused(() => publish(r.root));+ const fingerprint = (JSON.parse(error.detail!) as { findings: Array<{ path: string; fingerprint: string }> }).findings.find(f => f.path === 'notes.md')!.fingerprint;+ expect((JSON.parse(error.detail!) as { findings: unknown[] }).findings).toHaveLength(1);+ writeFileSync(join(r.root, '.gbrain-scan-allow'), `${fingerprint}\n`);+ expect(publish(r.root)).toMatchObject({ outcome: 'pushed', checkout: 'unchanged' });+ expect(remoteTip(r)).toBe(git(r.root, 'rev-parse', 'HEAD'));-test('a keep-checkout publish of HEAD runs the pre-push hook, and a refusing hook stops the push', () => {- const r = repo('hook');- const marker = join(dir, 'hook-ran');- const hook = join(r.root, '.git', 'hooks', 'pre-push');- writeFileSync(hook, `#!/bin/sh\ntouch '${marker}'\nexit 1\n`); chmodSync(hook, 0o755);- commit(r.root, 'page.md', 'a page\n');- expect(() => commitAndPush({ repo: r.root, cwd: r.root, paths: [], pushOnly: true, keepCheckout: true })).toThrow(/no push to origin\/main was confirmed/);- expect(existsSync(marker)).toBe(true);- expect(git(r.remote, 'rev-parse', 'refs/heads/main')).toBe(r.base);- writeFileSync(hook, '#!/bin/sh\nexit 0\n');- expect(commitAndPush({ repo: r.root, cwd: r.root, paths: [], pushOnly: true, keepCheckout: true })).toMatchObject({ outcome: 'pushed', checkout: 'unchanged' });- expect(git(r.remote, 'rev-parse', 'refs/heads/main')).toBe(git(r.root, 'rev-parse', 'HEAD'));+ const plain = repo('plain');+ commit(plain.root, 'notes.md', `Deploy token ${token}\n`);+ expect(publish(plain.root, false)).toMatchObject({ outcome: 'pushed' });});diff --git a/test/refresh-publish-diverged-7686.test.ts b/test/refresh-publish-diverged-7686.test.tsindex 616dfff846..145531d464 100644--- a/test/refresh-publish-diverged-7686.test.ts+++ b/test/refresh-publish-diverged-7686.test.ts@@ -8,7 +8,7 @@* which never moves the checkout), then fast-forwards, keeping the local commits;* with the setting false, or unset while Git durability is not on, it refuses* `refresh_diverged`; local commits holding a value that looks like a secret refuse- * before anything is pushed; a conflicting path+ * `publish_secret_found` in the publish child, before anything is pushed; a conflicting path* refuses `integrate_conflict` naming the path and changes nothing; an uncommitted* edit on an incoming path refuses `refresh_dirty` before anything is pushed; a dry* run never publishes; with gbrain.quarantine on, the refresh names the parked@@ -149,14 +149,14 @@ test('setting unset with Git durability on: a diverged refresh publishes the loc}}), 120_000);-test('setting on: local commits holding a value that looks like a secret refuse refresh_diverged naming the file and rule, never the value, and nothing is pushed', () => each(async f => {+test('setting on: local commits holding a value that looks like a secret refuse publish_secret_found naming the file and rule, never the value, and nothing is pushed', () => each(async f => {const token = 'ghp_' + 'Zt4q'.repeat(9);const local = diverge(f, { path: 'beta/local.md', content: page('Local', `Deploy token ${token}`) });git(f.root, 'rm', '-q', 'beta/local.md'); git(f.root, 'commit', '-qm', 'remove it again');const remote = remoteHead(f);await f.engine.setConfig(REFRESH_PUBLISH_DIVERGED_KEY, 'true');- const error = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_diverged');- expect(error.message).toContain('look like secrets: beta/local.md:');+ const error = await refusedWith(refreshWorktree(f.engine, f.alpha), 'publish_secret_found');+ expect(error.message).toContain('look like secrets or could not be scanned: beta/local.md:');expect(error.message).toContain(local.slice(0, 7));expect(`${error.message}${error.suggestion}`).not.toContain(token);expect(remoteHead(f)).toBe(remote);