Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(git): shared-checkout writer safety (#7381)
garrytanc7b5eed70c43
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 421cd371de..fcb4143f72 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -87,7 +87,7 @@ link it here rather than raising the cap.| [Google connector + open-loop engine](key-files/google-and-loops.md) | Cross-file contract; [more](key-files/google-and-loops-continued.md), [API](key-files/google-api-access.md) || [Open loops](key-files/open-loops-engine.md) | detect, extract, store || [Always-loaded core memory](key-files/core-memory.md) | Core tier, write-path guard and lock order, delivery lanes, pressure notice |-| [Workspace push and backup coverage](key-files/workspace-push-and-backup.md) | Workspace push, hook push backstops, backup verdicts |+| [Workspace push and backup coverage](key-files/workspace-push-and-backup.md) | Workspace push, hook push backstops, backup verdicts, git writer || [Secret and sensitivity scanning](key-files/secret-scan.md) | `secret-scan*.ts`: detection, allowlist, scan counters || [Ambient capture consent gate](key-files/ambient-capture.md) | `memory.auto_writeback` capture lanes || [Belief ledger](key-files/belief-ledger.md) | `src/core/belief/`, `gbrain beliefs`, doctor coverage |diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.mdindex 9d0b482391..f3f5b53524 100644--- a/docs/architecture/key-files/workspace-push-and-backup.md+++ b/docs/architecture/key-files/workspace-push-and-backup.md@@ -9,3 +9,8 @@ guide: [backup check](../../operations/backup-check.md).Key files:- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. An ordinary (non-forced) `getBackupStatus` re-probes before the one-hour sweep clock expires when the cached verdict still has pending repository evidence (a configured remote left `budget_exhausted`, relabelled `stale`, or `verified` older than the evidence window), at most once per `BACKUP_CONTINUATION_THROTTLE_MS` (60 s); real failures (`unavailable`, `mismatch`, `missing_ref`) are not retried per check (#6614, #6687; `test/backup-pending-continuation.serial.test.ts`). `budgetAllowsProbe` starts a probe only with its full two-second slot inside the deadline (a sub-slot leftover defers the root as `budget_exhausted` and the sweep keeps that root's first-pass `verified` evidence); an `unavailable` verification carries `cause: 'timeout' | 'exit'` (#6499). #6907: the slot is `resolveBackupRemoteTimeoutMs` (env `GBRAIN_BACKUP_REMOTE_TIMEOUT_MS` > DB `backup.remote_timeout_ms` > 2 s, clamped 500-30000 ms; the budget is `max(8 s, 4 slots)`), a timed-out probe is `isRemoteTimeout` (counted in `totals.remote_timeouts`, reason "remote check timed out"), and `worktreeDirty` streams `git status --porcelain` and stops at the first non-metadata line (`test/pathological/s-6907-backup-check-bounds.test.ts`). Both git calls run with `backupGitEnv()`, an allowlist (`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, proxy variables, and Windows profile variables) under the no-prompt overrides, so user Git config and credential helpers apply but `GIT_DIR`/`GIT_WORK_TREE` never do (#5794). `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor and the advisor's remote collector use the aggregate cache only, read through `currentBackupEvidence`. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. API connector sources are not repositories: a `connector_database` source (managed, unbound) and an unmanaged connector whose directory is not a Git repo each become a `connector` info asset with the `gbrain sync --source <id> --full` fix (not `gbrain export`: the connector sync rebuilds pages from the provider and never reads a Markdown dump, so an export is an archive, not a restore path), while a bound connector keeps the repository verdict. The doctor `backup_coverage` message and the advisor collector list each asset that keeps the verdict in warn with its reason (`blockingAssetReasons` in status-file.ts: `no git remote`, `remote configured, nothing pushed`, `dirty`, a fixed `unknown` code, unverified remote) locally, and reason counts only on the remote surface; a warn with no blocking asset leads with the stale or degraded cause. `gbrain backup status` names a fix for dirty and unverified rows too. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/doctor-backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`. #6083: `assessBackupRepository` drops physical-root metadata (`withoutPhysicalRootMetadata`) from both porcelain probes, classifies a root with no origin remote as `no_remote` even after a recorded push failure, and gives a managed canonical worktree (`managedFilesystemRootFor`) the read-only `gbrain sources writer status [<source>] --probe --json` fix instead of the refused `sources push` (`backup-coverage.ts` explains that fix with the retry-effects step).- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*`, and since #5186 the ownership markers `.gbrain-owner.json` / `.gbrain-owner-*.json` / `.gbrain-owner.json.*.tmp` plus `.gbrain-bootstrap.lock/**`, refused regardless of .gitignore state; untracked matches are excluded from the commit and named in `excludedUntracked`) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS) keyed on the repo's realpath, so a symlinked spelling and git's physical toplevel share it (an absent path hashes its raw string). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_STREAM_SCAN_MAX_BYTES`, 512 MiB), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through. A blob up to `PUSH_MAX_SCAN_BYTES` (25 MiB) is read whole and scanned by `scanText` as before; a larger one is found by its index size (one `ls-files -s` plus one `cat-file --batch-check`, `stagedBlobSizes`), streamed by oid through `git cat-file blob` into `scanTextStream` (`secret-scan-stream.ts`) and fails closed when git errors, runs past 10 minutes or delivers a byte count other than the recorded size (`test/workspace-push-large-blob.serial.test.ts`: a clean 30 MiB file pushes, secrets across window seams block once each with their line, the ceiling still blocks) — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo). A `blocked_secrets` result carries `PushSecretFinding[]`: each finding adds `file`, `since`, the absolute `allowlistPath` of the root `.gbrain-scan-allow`, a shell-quoted `allowCommand` (`printf` append, runnable from any cwd), `retryCommand` (`gbrain sources push --path <abs>` plus the run's `--branch`/`--allow-unverified-remote`), `docs` (`SECRET_SCAN_REFUSAL_DOCS`, the `write-refusals.md#secret-scan-refusals-and-redaction` anchor; keep that heading) and, when the scanner's `legacyFingerprint` matches an allowlist entry, `staleAllowlistEntry { entry, replacement }`. `formatBlockedSecrets` renders the CLI text from the same objects, so human and `--json` output carry the same commands, and no field holds a value. `blockedSecretsReason` keeps `reason` a one-line summary (count, first location, pattern) within the 140 chars `sanitizePushReason` passes. `bootstrap/verify.ts` and `bootstrap/repo.ts` refusals reuse the docs anchor and print fingerprint, `since` and the absolute allowlist path. `pushStatusForWorkspace(entries, ws)` picks the record whose `repoRoot` resolves to `ws` (a single legacy record without `repoRoot` is attributed to it); `bootstrap status` `support.last_push` and doctor `bootstrap_push_health`'s dirty-tree FAIL use only that record (`test/doctor-not-verified-5432.test.ts`). Tests: `test/workspace-push-guidance.test.ts`, `test/sources-push-cli.serial.test.ts`. #6083: the managed-guard refusal record carries `code: writer_coordinator_required` (`PushStatusEntry.code`); the hook push call sites (`dirtyTreePush`, `stopPushIfDue`, SessionEnd) skip a managed root with heartbeat reason `push_managed_coordinator`; doctor `bootstrap_push_health` (`src/commands/doctor/bootstrap-checks.ts` `recordedPushFailureCheck`) reports ok when every recorded failure's tree now matches its configured origin with nothing uncommitted. #5799: `isSupersededPushStatus(entry)` / `livePushStatuses(entries)` drop a record the managed topology has superseded (code or reason prefix `writer_coordinator_required`, or a `repoRoot` that is a managed worktree now; an unreadable marker is not assumed managed), because the coordinator's git effect never writes push-status and the refusal would otherwise feed the hook's FAILING banner and staleness note forever (`test/workspace-push-superseded-status.test.ts`); the hook call sites read `livePushStatuses(readPushStatuses())`.++## Shared-checkout git writer++- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`. Tests: `test/git-writer-safety-7381.serial.test.ts`.+- `src/commands/doctor/checks/git-writer.ts` — `checkout_lagging`, `dirty_age`, `commits_outside_source_root`, `quarantined_changes` (#7381, brain category, after `git_convergence`): over the unmanaged source checkouts with an upstream (`sourceRoots` from git-convergence, grouped by toplevel with each source's toplevel-relative root), never fetching, every git call bounded at 5 s. Lagging warns when `HEAD..@{u}` holds a commit over an hour old (fix: `gbrain git commit-push --pull --path <top>`, agent). Dirty age warns on pending write-through files older than 30 minutes (`pendingWriteThroughStillDirty`; fix: `commit-push --pending`, agent) and on files staged that long (ask_user: unstage or commit by name). Outside-root warns on unpushed non-merge commits that change files outside the DB source roots plus `gbrain.sourceRoot` (`localCommitsOutsideRoots`; ask_user fix with `--allow-outside-source-root`), and says when the checkout has no root recorded. Test: `test/doctor-git-writer-7381.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 7792afac66..c779bdcdd7 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -685,6 +685,16 @@ More: [docs/guides/write-refusals.md#colon_slug_windows_write_through](../../docMore: [docs/guides/shared-checkout-git.md#outcomes](../../docs/guides/shared-checkout-git.md#outcomes)+### commit_outside_source_root++<a id="commit_outside_source_root"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The commit or publish was refused: it changes files outside the brain's configured source root (git config gbrain.sourceRoot), often a commit made without gbrain git commit-push. | 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#source-roots](../../docs/guides/shared-checkout-git.md#source-roots)+### commit_paths_invalid<a id="commit_paths_invalid"></a>@@ -695,6 +705,16 @@ More: [docs/guides/shared-checkout-git.md#outcomes](../../docs/guides/shared-cheMore: [docs/guides/shared-checkout-git.md#outcomes](../../docs/guides/shared-checkout-git.md#outcomes)+### commit_prestaged_paths++<a id="commit_prestaged_paths"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The commit was refused before staging: files another writer had already staged sit under a named directory, and committing them would publish that writer's work. | 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#outcomes](../../docs/guides/shared-checkout-git.md#outcomes)+### concurrent_write<a id="concurrent_write"></a>diff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.mdindex e2e19f64f5..ddabf5284c 100644--- a/docs/guides/shared-checkout-git.md+++ b/docs/guides/shared-checkout-git.md@@ -45,11 +45,22 @@ another writer has half-written.lock, so a slow remote never blocks commits or gbrain's own page writes.2. **Commits only the paths you name.** It stages and commits exactly thosepaths (`git add -A -- <paths>`, `git commit --only -- <paths>`). Another- writer's dirty files are never staged, committed, stashed or touched.+ writer's dirty files are never staged, committed, stashed or touched. A file+ another writer already staged under a directory you named is refused+ (`commit_prestaged_paths`) instead of swept in; name the file to claim it.+ A path outside the brain's [source root](#source-roots) is refused+ (`commit_outside_source_root`). When git refuses the commit (a hook, a+ missing identity, a busy index), the paths are unstaged again, so nothing+ is left in the shared index for another writer's commit to pick up.3. **Pushes your commit, and merges remote commits in memory when the push isrejected.** It fetches, builds the merge without touching any working tree(`git merge-tree --write-tree` on git 2.38 and later, a three-way merge in a- temporary index on older git) and pushes the merge commit. It makes up to+ temporary index on older git) and pushes the merge commit. Local commits+ whose patch the remote already has (a cherry-picked or rebased copy) are+ left out of that merge: the local commits are replayed in memory onto the+ remote tip without them, so a copy the remote edited since never conflicts+ and a copy the remote reverted is never put back. The merge commit's message+ lists the commits it left out. It makes up toeight attempts, backing off, while the remote keeps moving. One push at atime runs per checkout and it publishes the newest local commit, so writersthat queue behind it share its push. The post-commit hook never waits: when@@ -87,6 +98,9 @@ gbrain git commit-push --push-onlyscripts/brain-commit-push.sh --pullgbrain git commit-push --pull+# Commit and push the write-through files gbrain could not commit (doctor's dirty_age names them)+gbrain git commit-push --pending+# Preview: prints the paths, branch and lock it would use; takes no lock, writes nothinggbrain git commit-push --dry-run -m "people: add alice-example" -- people/alice-example.md```@@ -136,6 +150,8 @@ Follow the error's `fix.next` as the| `pushed_checkout_lagging` | 0 | The push landed but this checkout was not advanced; a `[gbrain notice]` names the files that blocked it. Change nothing: the next commit-push or `--pull` catches the checkout up. Never stash or reset to "fix" it. || `commit_lock_busy` | 1 | Another writer held the lock for the whole wait; nothing was committed. Retry once. If it is still busy, tell the user which checkout and lock path the message names and stop. || `commit_paths_invalid` | 1 | No paths, a path outside the checkout, the checkout root itself, or a path git would not stage. Name the explicit files you wrote and rerun. |+| `commit_prestaged_paths` | 1 | Another writer staged files under a directory you named; nothing was staged or committed. Name your own files explicitly. Unstage the others (`git restore --staged -- <file>`, which keeps their bytes) only after the user agrees. |+| `commit_outside_source_root` | 1 | The commit, or a local commit about to be published, changes files outside the brain's [source root](#source-roots); nothing was pushed. Show the user `git show --stat <sha>`; rerun with `--allow-outside-source-root` only if they want it published. || `git_index_locked` | 1 | A git command that does not take the writer lock held `index.lock`. Retry once after a few seconds. || `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). |@@ -165,6 +181,41 @@ Every run also appends a line to `~/.gbrain/brain-push.log`, which(`git rev-parse --git-path brain-integrate-conflict.json`), so `put_page`reports it for that checkout until a publish resolves it.+<a id="source-roots"></a>+## Source roots++A brain can be one folder inside a larger repository. `gbrain sources harden`+records the source's folder in the checkout's local git config+(`gbrain.sourceRoot`, one value per source; nothing when the source is the+whole checkout). With a root recorded, `gbrain git commit-push` refuses to+commit a path outside it, and refuses to publish any local commit that changes+a file outside it (`commit_outside_source_root`), whoever made the commit.+That catches a commit made around gbrain, such as a cron's+`git add <dir>/; git commit`, which takes everything any writer had staged.+Merge commits are not judged: gbrain's in-memory merges bring remote files in.+gbrain's own page writes are always confined to their source's folder; the+one exception is the durability scaffolding `gbrain sources harden` commits at+the checkout root (the helper script and the agent instructions file).++**Say to your agent:** *"commit-push refused a commit outside the source root. What is in it?"*+The agent shows you `git show --stat <sha>` for each commit the error names.+If you want it published as it is, it reruns+`gbrain git commit-push --push-only --allow-outside-source-root`.++<a id="pending-write-through"></a>+## Page writes that could not commit++gbrain's own page writes (put_page, remember's facts fences, takes, timeline,+`lint --fix`) commit their one file under the commit lock on a hardened+checkout, waiting 2 seconds for it. They never commit without the lock, since+that races the lock holder on the shared index. When another writer holds the+lock longer, or git refuses the commit, the file is written but not committed,+and gbrain notes it in a pending ledger next to the lock+(`git rev-parse --git-path brain-writethrough-pending.log`). The next page+write that gets the lock commits the pending files with its own, and+`gbrain git commit-push --pending` commits and pushes them on demand.+`gbrain doctor` reports pending files older than 30 minutes as `dirty_age`.+<a id="conflicts"></a>## Conflicts@@ -230,6 +281,34 @@ source of conflicts: two appends at the end of the same file overlap. Keepboth sides by merging by hand with `file:`, or make such files derived insteadof hand-appended.+<a id="quarantine"></a>+### Quarantine (opt-in)++A checkout where no one is around to answer the conflict question (an+unattended agent or a cron) can opt in to quarantine instead:++```bash+git -C <checkout> config gbrain.quarantine true+```++With it on, a content conflict no longer stops the push. gbrain publishes the+remote's version of each conflicted file and every non-conflicting change from+this machine, and keeps this machine's version under a ref named+`refs/gbrain/quarantine/<time>-<commit>`. Nothing is dropped: the parked+commit is also part of the published history. commit-push prints a+`[gbrain notice] quarantine` line (the `quarantined` field in `--json`), and+`gbrain doctor` reports the waiting ref as `quarantined_changes` until the+user is done with it.++**Say to your agent:** *"What did gbrain quarantine?"*+The agent shows you the doctor finding and the difference+(`git diff <remote sha> <ref> -- <path>`). Whatever should stay, it commits+again with `gbrain git commit-push -m "<msg>" -- <path>`; when you're+done, it deletes the ref with `git update-ref -d <ref>`.++File/directory and rename conflicts are never quarantined; they stop the push+as described above. Quarantine is off by default.+<a id="stuck-rebase"></a>## Recovering a stuck rebase@@ -317,11 +396,17 @@ which take it for you. A daemon that runs git itself follows this contract:`gbrain-push.lock` in the same directory. gbrain takes both, always`brain-commit.lock` first; a daemon that may share a checkout with an oldhelper does the same, in the same order.-- **Hold it** for local changes: staging, committing, and moving the- checkout. gbrain itself releases it before pushing and pushes under- `brain-publish.lock`; a daemon that pushes while holding the commit lock is- still safe, it just delays other writers' commits for as long as the push- takes.+- **Hold it** for local changes only: staging, committing, and moving the+ checkout. Release it before pushing and push under `brain-publish.lock`, as+ gbrain does. A daemon that pushes while holding the commit lock cannot make+ gbrain lose or revert its commits, but every gbrain writer waits for it:+ `commit-push` fails `commit_lock_busy` after its wait, page writes leave+ their files pending, and gbrain's publisher reports `pushed_checkout_lagging`+ because it cannot advance the checkout. Its own plain push also loses races+ to gbrain's merged pushes and strands its commit until+ `gbrain git commit-push --push-only` runs.+- **Commit with explicit paths** (`git commit --only -- <paths>`). A commit+ without paths takes everything any writer has staged in the shared index.- **Mark your children:** while holding the lock, set`BRAIN_COMMIT_LOCK_HELD` to the lock file's absolute path in the environmentof anything you start that may take it, such as `gbrain git commit-push` or a@@ -348,6 +433,32 @@ gbrain git commit-push --pullgbrain git commit-push -m "host sync: daily notes" -- daily/```+<a id="commit-guard"></a>+## Commit guard (opt-in)++`gbrain git guard --install` adds a local, untracked `prepare-commit-msg` hook+to the checkout. It refuses every commit that gbrain did not make under the+commit lock: a plain `git commit`, `-a`, `--amend`, and `--no-verify` too,+because that flag skips only the pre-commit and commit-msg hooks. A refused+commit changes nothing; whatever its writer staged stays staged. gbrain's own+commits (commit-push, page writes, the helper, including its no-gbrain+fallback) pass because they name the lock they hold. A merge commit, and a+commit that finishes a merge, cherry-pick, revert or rebase, pass too:+refusing those would leave the operation half done in the shared tree.+`gbrain git guard` prints whether it is installed, and+`gbrain git guard --uninstall` removes it. It refuses to replace another+tool's `prepare-commit-msg` hook and needs git 2.31 or later. It is off+unless you install it.++**Say to your agent:** *"Stop crons and other scripts from committing to my brain around gbrain."*+Your agent runs `gbrain git guard --install` in the brain checkout.++A person who needs a plain commit once bypasses it for that one command:++```bash+GBRAIN_COMMIT_GUARD=off git commit -m "fix the README by hand" -- README.md+```+## Limits- **Two agents editing the same file at the same time still conflict.** The@@ -362,9 +473,18 @@ gbrain git commit-push -m "host sync: daily notes" -- daily/- **A lagging checkout is not repaired automatically** while another writer'sedit blocks it. The next commit-push or `--pull` after that edit iscommitted brings it current.-- **Writers that skip the lock** (a hand-run `git commit`) are not excluded;- they cannot revert a locked writer's commit, because the checkout only- fast-forwards, but they can still sweep up files with a repo-wide add.+- **Writers that skip the lock** (a hand-run `git commit`) are not excluded+ unless the [commit guard](#commit-guard) is installed. They cannot revert a+ locked writer's commit, because the checkout only fast-forwards, but a commit+ without paths can still sweep up staged files; with a+ [source root](#source-roots) recorded, gbrain refuses to publish one that+ reaches outside it. `gbrain doctor` reports such unpushed commits+ (`commits_outside_source_root`), a checkout behind its upstream for over an+ hour (`checkout_lagging`), pending or long-staged files (`dirty_age`), and+ local versions the opt-in [quarantine](#quarantine) parked+ (`quarantined_changes`).+- **No page-aware merge.** Two edits to the same page meet as a text conflict;+ a merge driver that understands page sections is a planned follow-up.## Relateddiff --git a/src/commands/doctor/checks/git-convergence.ts b/src/commands/doctor/checks/git-convergence.tsindex 3e5050a5d6..c7191e8395 100644--- a/src/commands/doctor/checks/git-convergence.ts+++ b/src/commands/doctor/checks/git-convergence.ts@@ -121,7 +121,7 @@ function probe(root: string, sourceIds: string[], now: number, tracked: Map<stri}/** Every non-archived filesystem source root plus `sync.repo_path`, with the source ids that name each root. */-async function sourceRoots(engine: BrainEngine): Promise<Map<string, string[]>> {+export async function sourceRoots(engine: BrainEngine): Promise<Map<string, string[]>> {const sources = await engine.executeRaw<{ id: string; local_path: string | null; config: unknown }>('SELECT id, local_path, config FROM sources WHERE archived IS NOT TRUE AND local_path IS NOT NULL ORDER BY id');const roots = new Map<string, string[]>();diff --git a/src/commands/doctor/checks/git-writer.ts b/src/commands/doctor/checks/git-writer.tsnew file mode 100644index 0000000000..7d2b394bc5--- /dev/null+++ b/src/commands/doctor/checks/git-writer.ts@@ -0,0 +1,170 @@+/**+ * #7381 (GBRA-180): writer-safety checks for the Git checkouts the brain's+ * sources live in, next to `git_convergence`. They never fetch, so "behind"+ * is as of the last fetch, and every git call is time-bounded.+ *+ * checkout_lagging the checkout is behind its upstream and the+ * oldest commit it lacks is over an hour old (a+ * dirty file blocking the fast-forward, or no+ * writer has pulled); the fix is the locked pull.+ * dirty_age write-through files gbrain wrote but could not+ * commit (the pending ledger) older than 30+ * minutes, and staged-but-uncommitted files that+ * old: a commit without paths by any writer+ * would publish them.+ * commits_outside_source_root unpushed commits that change files outside the+ * checkout's brain source roots (a cron's+ * `git add <dir>; git commit` sweeps up staged files).+ * quarantined_changes local versions of conflicting files the opt-in+ * quarantine (git config gbrain.quarantine) parked+ * under refs/gbrain/quarantine/ while publishing+ * the remote's version; they wait for the user.+ *+ * Managed canonical worktrees are skipped: their owner is the only writer.+ */+import { execFileSync } from '../../../core/spawn.ts';+import { realpathSync, statSync } from 'node:fs';+import { join, relative, sep } from 'node:path';+import type { Check } from '../../doctor.ts';+import { isManagedFilesystemPath } from '../../../core/persistence/filesystem-guard.ts';+import { configuredSourceRoots, localCommitsOutsideRoots, pendingWriteThroughStillDirty, readQuarantine } from '../../../core/git/commit-push.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { doctorVerify } from '../check-fix.ts';+import { sourceRoots } from './git-convergence.ts';++export const CHECKOUT_LAG_WARN_MS = 60 * 60_000;+export const DIRTY_AGE_WARN_MS = 30 * 60_000;+const GIT_TIMEOUT_MS = 5_000;+const MAX_ROOTS = 50;+const MAX_LISTED = 20;++function git(root: string, args: string[]): string | null {+ try { return execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'ignore'], timeout: GIT_TIMEOUT_MS }).toString(); }+ catch { return null; }+}++const canonical = (path: string) => { try { return realpathSync(path); } catch { return path; } };++interface Checkout { top: string; source_ids: string[]; roots: string[] }++/** Each unmanaged checkout toplevel with an upstream, and the toplevel-relative roots of the sources in it. */+async function checkouts(ctx: DoctorContext): Promise<Checkout[]> {+ const byTop = new Map<string, Checkout>();+ for (const [root, ids] of [...await sourceRoots(connectedEngine(ctx))].slice(0, MAX_ROOTS)) {+ if (isManagedFilesystemPath(root)) continue;+ const top = git(root, ['rev-parse', '--show-toplevel'])?.trim();+ if (!top || git(top, ['rev-parse', '--verify', '--quiet', '@{u}']) === null) continue;+ const rel = relative(canonical(top), canonical(root)).split(sep).join('/');+ const entry = byTop.get(top) ?? { top, source_ids: [], roots: [] };+ entry.source_ids.push(...ids);+ entry.roots.push(rel.startsWith('..') ? '' : rel);+ byTop.set(top, entry);+ }+ return [...byTop.values()];+}++const list = (items: string[]) => `${items.slice(0, 5).join(', ')}${items.length > 5 ? ', ...' : ''}`;++function lagging(found: Checkout[], now: number): Omit<Check, 'name'> {+ const behind = found.flatMap(c => {+ const count = Number(git(c.top, ['rev-list', '--count', 'HEAD..@{u}'])?.trim() ?? 0);+ if (!count) return [];+ const times = (git(c.top, ['log', '--format=%ct', 'HEAD..@{u}']) ?? '').split('\n').filter(Boolean).map(Number);+ const oldest = times.length ? Math.min(...times) * 1000 : now;+ return now - oldest > CHECKOUT_LAG_WARN_MS ? [{ root: c.top, source_ids: c.source_ids, behind: count, oldest_missing_at: new Date(oldest).toISOString() }] : [];+ });+ const details = { checkouts: behind, warn_after_minutes: CHECKOUT_LAG_WARN_MS / 60_000, fetched: false };+ if (!behind.length) return { status: 'ok', details, message: `${found.length} Git checkout(s) are not behind their last fetched upstream by more than ${CHECKOUT_LAG_WARN_MS / 60_000} minutes.` };+ const first = behind[0]!;+ return { status: 'warn', details,+ message: `Git checkouts are behind their upstream: ${behind.map(b => `${b.root}: ${b.behind} commit(s), the oldest from ${b.oldest_missing_at}`).join(' | ')}. Writers there edit files older than the remote's, and a commit made around gbrain can revert the newer remote work. The locked pull fast-forwards (or merges in memory) and never moves a file with a local edit; it names any file that blocks it. This compares with the last fetch.`,+ fix: { argv: ['gbrain', 'git', 'commit-push', '--pull', '--path', first.root], consent: [], actor: 'agent', requires_exclusive: false,+ why: `${first.root} lacks ${first.behind} upstream commit(s); the pull takes the checkout's commit lock and never rebases, stashes or overwrites a local edit.${behind.length > 1 ? ` ${behind.length - 1} other checkout(s) need the same, see details.checkouts.` : ''}`,+ verify: doctorVerify('checkout_lagging') } };+}++function dirtyAge(found: Checkout[], now: number): Omit<Check, 'name'> {+ const reports = found.flatMap(c => {+ const pending = pendingWriteThroughStillDirty(c.top).filter(e => now - Date.parse(e.since) > DIRTY_AGE_WARN_MS);+ const staged = (git(c.top, ['diff', '--cached', '--no-renames', '--name-only', '-z']) ?? '').split('\0').filter(Boolean).filter(path => {+ try { return now - statSync(join(c.top, path)).mtimeMs > DIRTY_AGE_WARN_MS; } catch { return true; }+ });+ return pending.length || staged.length ? [{ root: c.top, source_ids: c.source_ids, pending: pending.slice(0, MAX_LISTED), pending_count: pending.length, staged: staged.slice(0, MAX_LISTED), staged_count: staged.length }] : [];+ });+ const details = { checkouts: reports, warn_after_minutes: DIRTY_AGE_WARN_MS / 60_000 };+ if (!reports.length) return { status: 'ok', details, message: `No write-through file has waited more than ${DIRTY_AGE_WARN_MS / 60_000} minutes for a commit, and nothing has sat staged that long, in ${found.length} Git checkout(s).` };+ const lines = reports.map(r => `${r.root}: ${[r.pending_count ? `${r.pending_count} write-through file(s) not committed (${list(r.pending.map(p => p.path))})` : '', r.staged_count ? `${r.staged_count} staged file(s) not committed (${list(r.staged)})` : ''].filter(Boolean).join('; ')}`);+ const pending = reports.find(r => r.pending_count);+ if (pending) {+ return { status: 'warn', details,+ message: `Files have waited more than ${DIRTY_AGE_WARN_MS / 60_000} minutes for a commit: ${lines.join(' | ')}. A write-through file waits when another writer held the checkout's commit lock past gbrain's short wait, or git refused the commit; it is not on the remote until committed, and a staged file rides along with the next commit made without paths by any writer.`,+ fix: { argv: ['gbrain', 'git', 'commit-push', '--pending', '--path', pending.root], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Commits and pushes only the files gbrain itself wrote and could not commit, under the commit lock; another writer\'s files are never staged.',+ verify: doctorVerify('dirty_age') } };+ }+ const first = reports[0]!;+ return { status: 'warn', details,+ message: `Files have sat staged but uncommitted for more than ${DIRTY_AGE_WARN_MS / 60_000} minutes: ${lines.join(' | ')}. The next commit made without paths by any writer (a cron's git add plus git commit) publishes them, stale or not.`,+ fix: { ask_user: true, argv: ['git', '-C', first.root, 'restore', '--staged', '--', ...first.staged], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Another writer staged these files and never committed them; unstaging keeps their bytes on disk, committing them publishes that writer\'s work.',+ user_message: `${first.staged_count} file(s) in ${first.root} have been staged but not committed for a while (${list(first.staged)}). Commit them by name with gbrain git commit-push, or unstage them (their bytes stay on disk)?`,+ verify: doctorVerify('dirty_age') } };+}++function outsideRoots(found: Checkout[]): Omit<Check, 'name'> {+ const reports = found.flatMap(c => {+ const configured = configuredSourceRoots(c.top);+ const roots = [...new Set([...c.roots, ...(configured.includes('') ? [] : configured)])];+ const commits = localCommitsOutsideRoots(c.top, 'HEAD', '@{u}', roots) ?? [];+ return commits.length ? [{ root: c.top, source_ids: c.source_ids, roots, configured: !configured.includes(''), commits: commits.slice(0, MAX_LISTED).map(o => ({ sha: o.sha, paths: o.paths.slice(0, MAX_LISTED) })) }] : [];+ });+ const details = { checkouts: reports };+ if (!reports.length) return { status: 'ok', details, message: `No unpushed commit changes files outside its brain source root in ${found.length} Git checkout(s).` };+ const first = reports[0]!;+ const shas = first.commits.map(c => c.sha.slice(0, 12));+ return { status: 'warn', details,+ message: `Unpushed commits change files outside the brain's source root: ${reports.map(r => `${r.root} (roots ${r.roots.join(', ')}): ${r.commits.map(c => `${c.sha.slice(0, 12)} ${list(c.paths)}`).join('; ')}`).join(' | ')}. A commit made without gbrain git commit-push can carry files other writers had staged, and publishing it can overwrite newer work on the remote.${reports.some(r => !r.configured) ? ' The checkout has no gbrain.sourceRoot set, so gbrain git commit-push would still publish them; gbrain sources harden <source> records the root.' : ' gbrain git commit-push refuses to publish them until the user agrees.'}`,+ fix: { ask_user: true, argv: ['gbrain', 'git', 'commit-push', '--push-only', '--allow-outside-source-root', '--path', first.root], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Only the user can say whether these files belong on the remote; show them git show --stat <sha> for each commit first.',+ user_message: `Unpushed commit(s) ${shas.join(', ')} in ${first.root} change files outside the brain's folder. Publish them as they are, or should they be reviewed first?`,+ verify: doctorVerify('commits_outside_source_root') } };+}++function quarantined(found: Checkout[]): Omit<Check, 'name'> {+ const reports = found.flatMap(c => {+ const entries = readQuarantine(c.top);+ return entries.length ? [{ root: c.top, source_ids: c.source_ids, entries: entries.slice(0, MAX_LISTED), count: entries.length }] : [];+ });+ const details = { checkouts: reports };+ if (!reports.length) return { status: 'ok', details, message: `No quarantined local change is waiting in ${found.length} Git checkout(s).` };+ const first = reports[0]!;+ const entry = first.entries[0]!;+ return { status: 'warn', details,+ message: `Local changes were quarantined instead of merged: ${reports.map(r => `${r.root}: ${r.entries.map(e => `${e.ref} (${list(e.paths)})`).join('; ')}`).join(' | ')}. Both this machine and the remote changed these files; the remote's version was published and this machine's version is kept under the ref. Compare with git diff ${entry.remote.slice(0, 12)} ${entry.ref} -- <path>, bring back what should stay with a normal commit (gbrain git commit-push -m "<msg>" -- <path>), then delete the ref.`,+ fix: { ask_user: true, argv: ['git', '-C', first.root, 'update-ref', '-d', entry.ref], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Deleting the ref says the parked version was reviewed; until then it is the only named copy of this machine\'s side of the conflict.',+ user_message: `This machine's version of ${list(entry.paths)} in ${first.root} was parked under ${entry.ref} because the remote changed the same file(s). Review it and keep what you need, then may I delete the ref?`,+ verify: doctorVerify('quarantined_changes') } };+}++async function runGitWriter(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ ctx.progress.heartbeat('checkout_lagging');+ const found = await checkouts(ctx);+ if (!found.length) return checks;+ const now = Date.now();+ checks.push({ name: 'checkout_lagging', ...lagging(found, now) });+ ctx.progress.heartbeat('dirty_age');+ checks.push({ name: 'dirty_age', ...dirtyAge(found, now) });+ ctx.progress.heartbeat('commits_outside_source_root');+ checks.push({ name: 'commits_outside_source_root', ...outsideRoots(found) });+ ctx.progress.heartbeat('quarantined_changes');+ checks.push({ name: 'quarantined_changes', ...quarantined(found) });+ return checks;+}++export const gitWriterEntry: DoctorEntry = {+ name: 'checkout_lagging',+ emits: ['checkout_lagging', 'dirty_age', 'commits_outside_source_root', 'quarantined_changes'],+ run: runGitWriter,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex d9508bb593..f234768170 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -95,6 +95,7 @@ import { linksExtractionLagEntry, syncFreshnessEntry, searchModeEntry } from './import { persistenceConsumersEntry, serveBuildDriftEntry } from './checks/persistence-consumers.ts';import { runtimeBuildSkewEntry } from './checks/runtime-build-skew.ts';import { gitConvergenceEntry } from './checks/git-convergence.ts';+import { gitWriterEntry } from './checks/git-writer.ts';import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';import { transcriptSecretExposureEntry } from './checks/transcript-secrets.ts';import { autoChronicleEntry } from './checks/auto-chronicle.ts';@@ -245,6 +246,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [managedSyncLatencyEntry,commitNotifierEntry,gitConvergenceEntry,+ gitWriterEntry,decideHealthEntry,unlinkedFactsEntry,edgeValidityEntry,diff --git a/src/commands/git.ts b/src/commands/git.tsindex 08d2939465..26d5c61ae3 100644--- a/src/commands/git.ts+++ b/src/commands/git.ts@@ -8,8 +8,11 @@* gbrain git commit-push --push-only [--keep-checkout] [--path <dir>] [--expect-remote <sha> --resolve <p>=ours|theirs|file:<f>…]* gbrain git commit-push --pull [--path <dir>] [--require-clean]* gbrain git commit-push --dry-run [--path <dir>] [-m <msg>] [--] <paths…>+ * gbrain git commit-push --pending [--path <dir>] [-m <msg>]+ * gbrain git guard [--install | --uninstall] [--path <dir>] [--json]*/import { commitAndPush, checkoutRoot, pullShared, scopePaths, COMMIT_LOCK_NAME, type Resolution } from '../core/git/commit-push.ts';+import { guardStatus, installGuard, uninstallGuard } from '../core/git/commit-guard.ts';import { appendPushLog } from '../core/brain-repo-durability.ts';import { opError } from '../core/ops/contract.ts';import { writeCliError } from '../cli/cli-error.ts';@@ -22,6 +25,8 @@ const HELP = `Usage: gbrain git commit-push [--path <dir>] -m <msg> [--json] [--gbrain git commit-push --push-only [--path <dir>] [--branch <b>]gbrain git commit-push --push-only [--keep-checkout] [--path <dir>] --expect-remote <sha> --resolve <path>=ours|theirs|file:<file>...gbrain git commit-push --pull [--path <dir>] [--require-clean]+ gbrain git commit-push --pending [--path <dir>] [-m <msg>]+ gbrain git guard [--install | --uninstall] [--path <dir>] [--json]Commit only the named paths and push them, safely, in a checkout other agentsshare: a short commit lock and a separate push lock per checkout, no@@ -43,21 +48,34 @@ Flags:--resolve <p>=<v> After integrate_conflict: which side wins for path p (ours, theirs, file:<merged copy>).--expect-remote <sha> Required with --resolve: the remote commit the choice was made against(printed by integrate_conflict); a remote that moved since is reported again.+ --pending Commit the write-through files gbrain wrote but could not commit (the pending+ ledger doctor's dirty_age reports), then push.+ --allow-outside-source-root Commit and publish files outside the checkout's source root(s)+ (git config gbrain.sourceRoot); only after the user agrees.--dry-run Print the paths, branch and lock that would be used; take no lock, write nothing.--json One JSON result (or the error envelope) on stdout.Paths are relative to --path when it is given (like git -C), else to the currentdirectory. Exit 0 on pushed, nothing_to_commit, push_deferred andpushed_checkout_lagging (a notice names the blocking files); 4 when the commit is local but no push was-confirmed (push_unconfirmed); 1 on other failures, each with an "Error [<code>]" line. Guide: docs/guides/shared-checkout-git.md`;+confirmed (push_unconfirmed); 1 on other failures, each with an "Error [<code>]" line. Guide: docs/guides/shared-checkout-git.md++gbrain git guard [--install | --uninstall]: the opt-in commit guard, a local+prepare-commit-msg hook that refuses commits in this checkout not made through+gbrain (git commit, -a and --no-verify included; merges and commits that finish a+merge, cherry-pick, revert or rebase pass). A person bypasses it once with+GBRAIN_COMMIT_GUARD=off git <command>. Without a flag it prints whether the guard+is installed.`;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[];+ pending: boolean; allowOutside: boolean; install: boolean; uninstall: 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: [] };+ const p: Parsed = { json: false, pushOnly: false, pull: false, requireClean: false, dryRun: false, help: false, keepCheckout: false, paths: [], resolve: [],+ pending: false, allowOutside: false, install: false, uninstall: false };let rest = false;for (let i = 0; i < args.length; i++) {const a = args[i];@@ -77,6 +95,10 @@ function parse(args: string[]): Parsed {else if (a === '--pull') p.pull = true;else if (a === '--require-clean') p.requireClean = true;else if (a === '--dry-run') p.dryRun = true;+ else if (a === '--pending') p.pending = true;+ else if (a === '--allow-outside-source-root') p.allowOutside = true;+ else if (a === '--install') p.install = true;+ else if (a === '--uninstall') p.uninstall = true;else if (a === '--path' || a.startsWith('--path=') || a === '--repo' || a.startsWith('--repo=')) p.path = take('--path');else if (a === '-m' || a === '--message' || a.startsWith('--message=')) p.message = take('--message');else if (a === '--resolve' || a.startsWith('--resolve=')) p.resolve.push(take('--resolve'));@@ -114,13 +136,16 @@ export async function runGit(args: string[]): Promise<number> {const p = parse(args);json = p.json;if (p.help || !p.sub) { console.log(HELP); return p.sub || p.help ? 0 : 2; }+ if (p.sub === 'guard') return runGuard(p);if (p.sub !== 'commit-push') throw opError('commit_paths_invalid', `Unknown subcommand: gbrain git ${p.sub}.`, HELP.split('\n')[0]);+ if (p.install || p.uninstall) throw opError('commit_paths_invalid', '--install and --uninstall belong to gbrain git guard.', 'Run gbrain git guard --install.');const repo = checkoutRoot(p.path ?? process.cwd());const cwd = p.path ? repo : 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.pushOnly)+ || (p.pending && (p.pull || p.pushOnly || p.paths.length)) || (p.allowOutside && p.pull)) {throw opError('commit_paths_invalid', 'These flags do not combine.',- 'Use one mode: -m <msg> -- <paths> (commit + push), --push-only [--keep-checkout] [--branch <b>] [--expect-remote <sha> --resolve ...], or --pull [--require-clean].');+ '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].');}if (Boolean(p.resolve.length) !== Boolean(p.expectRemote) || (p.expectRemote && !/^[0-9a-f]{7,64}$/i.test(p.expectRemote))) {throw opError('commit_paths_invalid', '--resolve and --expect-remote <sha> go together.',@@ -145,7 +170,10 @@ export async function runGit(args: string[]): Promise<number> {}const result = commitAndPush({- repo, cwd, paths: p.paths, message: p.message, pushOnly: p.pushOnly, advanceOnlyWhenClean: p.requireClean,+ repo, cwd, paths: p.paths, pushOnly: p.pushOnly, advanceOnlyWhenClean: p.requireClean,+ message: p.pending ? p.message ?? 'gbrain: commit pending write-through files' : p.message,+ ...(p.pending ? { pending: true } : {}),+ ...(p.allowOutside ? { allowOutsideSourceRoot: true } : {}),...(p.keepCheckout ? { keepCheckout: true } : {}),...(p.branch ? { branch: p.branch } : {}),...(p.resolve.length ? { resolutions: parseResolutions(p.resolve), expectRemote: p.expectRemote } : {}),@@ -161,13 +189,16 @@ export async function runGit(args: string[]): Promise<number> {emit(json, { ...result, repo },result.outcome === 'nothing_to_commit' ? `nothing to commit; ${result.remote}/${result.branch} at ${short}`: `pushed ${short} to ${result.remote}/${result.branch}${result.integrated ? `; merged ${result.integrated} remote commit(s)` : ''}; checkout ${result.checkout}`);+ if (result.quarantined && !json) {+ process.stderr.write(`[gbrain notice] quarantine: the remote also changed ${result.quarantined.paths.join(', ')}; its version was published and this machine's version is kept under ${result.quarantined.ref}. gbrain doctor lists it (quarantined_changes).\n`);+ }if (result.outcome === 'pushed_checkout_lagging' && !json) {process.stderr.write(`[gbrain notice] the push landed but this checkout was not advanced: ${result.lagging_reason}. The next commit-push or --pull catches it up.\n`);}return 0;} catch (e) {const code = (e as { code?: string }).code;- if (code === 'push_unconfirmed' || code === 'integrate_conflict') {+ if (code === 'push_unconfirmed' || code === 'integrate_conflict' || code === 'commit_outside_source_root') {try {const bi = args.indexOf('--branch');const branch = bi !== -1 && args[bi + 1] ? args[bi + 1].replace(/^refs\/heads\//, '') : currentBranchOf(args);@@ -178,6 +209,16 @@ export async function runGit(args: string[]): Promise<number> {}}+function runGuard(p: Parsed): number {+ if (p.install && p.uninstall) throw opError('commit_paths_invalid', '--install and --uninstall do not combine.', 'Pass one of them, or neither for the status.');+ const repo = checkoutRoot(p.path ?? process.cwd());+ const s = p.install ? installGuard(repo) : p.uninstall ? uninstallGuard(repo) : { ...guardStatus(repo), changed: false };+ emit(p.json, { ...s }, p.install ? `commit guard ${s.changed ? 'installed' : 'already current'}: ${s.hook}`+ : p.uninstall ? (s.changed ? `commit guard removed: ${s.hook}` : 'commit guard was not installed')+ : s.installed ? `commit guard installed: ${s.hook}` : s.foreign ? `not installed; ${s.hook} is another tool's hook` : 'commit guard not installed (gbrain git guard --install)');+ return 0;+}+function currentBranchOf(args: string[]): string {const i = args.findIndex(a => a === '--path' || a === '--repo');const dir = i !== -1 ? args[i + 1] : process.cwd();diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c99b70baa9..c1913bdec8 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1131,6 +1131,12 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.372.0', text: '`gbrain sources status --json` no longer prints every held file of a source by default: `git_holds` now carries `count`, `by_code` (each hold code with its count and one example item, whose `fix` applies to the rest), and the first 10 items with `items_complete: false` and an `items_command`. `--holds` lists every held file read, as before, and `--limit <n> [--cursor <c>]` pages them by path (the cursor needs the source id). The text output is unchanged.' },// #7355: a level read reports progress; pass_abandoned; racy floor{ since: '0.60.377.0', text: 'A managed `gbrain sync` pass no longer stops `drain_stalled` / `no_progress` on a large source while it is still reading and classifying the level before its first commit: the level read reports progress to the drain as it works (its loops and the history walk for the origin evidence of files a page lost), writes the open pass row every 30 s so a follower and `gbrain sync status` see it working, and a pass that asks for a history walk already running joins it. A hung read still stops after 5 minutes. When two passes in a row never end (abandoned by the drain or killed; the newest open one counts after 5 quiet minutes), `gbrain sync status` reads `blocked` with the new reason `pass_abandoned` and `next` is `gbrain doctor --json` and a report, instead of the plain sync. The stat caches of the dirtiness probe and the working level now take the racy window from the earlier of the process clock and the filesystem clock (a file written in the Git directory), so a mount whose clock lags the process no longer keeps a stale `clean` verdict.' },+ // #7381 (GBRA-180): shared-checkout writer safety. `since` is provisional (current VERSION); restamped at the merge slot.+ { since: '0.60.379.0', text: 'When a brain checkout publishes local commits whose patch the remote already has (a cherry-picked or rebased copy), `gbrain git commit-push` and `--pull` now leave those commits out of the merge: the other local commits are replayed onto the remote tip in memory. A copy the remote edited since no longer reports `integrate_conflict` forever, and a copy the remote reverted is no longer silently put back. The merge commit message lists the commits it left out.' },+ { since: '0.60.379.0', text: 'gbrain\'s own page commits (write-through, facts fences, takes, timeline, `lint --fix`) no longer commit without the checkout\'s commit lock after their 2-second wait: the file is written, noted in a pending ledger, and committed by the next page write that gets the lock or by the new `gbrain git commit-push --pending`. A commit git refuses now unstages its paths again, so nothing is left staged for another writer\'s commit to sweep up.' },+ { since: '0.60.379.0', text: '`gbrain git commit-push` refuses to commit a file another writer already staged under a directory you named (`commit_prestaged_paths`; name the file to claim it). `gbrain sources harden` records a source folder below the checkout top in git config `gbrain.sourceRoot`; with it set, commit-push refuses to commit or publish changes outside that folder (`commit_outside_source_root`) until the user reruns with `--allow-outside-source-root`.' },+ { since: '0.60.379.0', text: 'New opt-in `gbrain git guard --install`: a local prepare-commit-msg hook that refuses commits not made through gbrain in that checkout, `--no-verify` included (bypass once with `GBRAIN_COMMIT_GUARD=off`). The committed `scripts/brain-commit-push.sh` fallback (no gbrain on the machine) now releases the commit lock before it pushes and pushes under `brain-publish.lock`; rerun `gbrain sources harden` to refresh it.' },+ { since: '0.60.379.0', text: 'Three new doctor checks on source checkouts: `checkout_lagging` (behind the last fetched upstream for over an hour), `dirty_age` (pending write-through files or staged files waiting over 30 minutes) and `commits_outside_source_root` (unpushed commits that change files outside the brain\'s folder). Each names its fix.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.tsindex 781e506b5e..8b6ae051f0 100644--- a/src/core/brain-repo-durability.ts+++ b/src/core/brain-repo-durability.ts@@ -29,9 +29,9 @@ import { assertManagedFilesystemWrite, hasFilesystemPublication, managedFilesyst*/import {- existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync, statSync, renameSync, appendFileSync,+ existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync, statSync, renameSync, appendFileSync, realpathSync,} from 'fs';-import { join, dirname, relative, isAbsolute } from 'path';+import { join, dirname, relative, isAbsolute, sep } from 'path';import { execFileSync, execSync } from './spawn.ts';import { execFileBounded } from './bounded-child-exec.ts';import {@@ -50,7 +50,7 @@ import { readFix } from './ops/op-fix.ts';// don't ship their own — see resolveFilingRules().import filingRulesDoc from '../../skills/_brain-filing-rules.json';import { gitChildEnv } from './git-env.ts';-import { commitAndPush, commitPathsLocked, readIntegrateConflict } from './git/commit-push.ts';+import { commitAndPush, commitPathsLocked, readIntegrateConflict, SOURCE_ROOT_CONFIG } from './git/commit-push.ts';export { execFileBounded, type BoundedExecOptions } from './bounded-child-exec.ts';@@ -221,7 +221,7 @@ exit 0`;}-function renderCommitPushHelper(): string {+export function renderCommitPushHelper(): string {return `#!/usr/bin/env bash${HELPER_BANNER}${PROTOCOL_LINE}@@ -274,12 +274,16 @@ _branch="$(git symbolic-ref --quiet --short HEAD)" || { echo "detached HEAD: cheecho "[brain-commit-push] gbrain git commit-push unavailable; using the minimal locked commit + push" >&2_log="\${GBRAIN_HOME:-$HOME}/.gbrain/brain-push.log"mkdir -p "$(dirname "$_log")" 2>/dev/null || true+# The absolute lock path, as gbrain spells it: the marker below must name this exact lock.+_gp="$(git rev-parse --git-path brain-commit.lock)"+_gd="$(cd "$(dirname "$_gp")" && pwd -P)"+_lock="$_gd/brain-commit.lock"if command -v flock >/dev/null 2>&1; then- exec 8>"$(git rev-parse --git-path brain-commit.lock)"+ exec 8>"$_lock"flock -w "\${GBRAIN_COMMIT_LOCK_WAIT_SECONDS:-\${GBRAIN_PUSH_LOCK_WAIT_SECONDS:-60}}" 8 || { echo "commit_lock_busy: another writer holds the commit lock" >&2; exit 1; }- exec 9>"$(git rev-parse --git-path gbrain-push.lock)"+ exec 9>"$_gd/gbrain-push.lock"flock -w "\${GBRAIN_COMMIT_LOCK_WAIT_SECONDS:-\${GBRAIN_PUSH_LOCK_WAIT_SECONDS:-60}}" 9 || { echo "commit_lock_busy: another writer holds the push lock" >&2; exit 1; }- export BRAIN_COMMIT_LOCK_HELD=1+ export BRAIN_COMMIT_LOCK_HELD="$_lock" GBRAIN_COMMIT_VIA="$_lock"elseecho "[brain-commit-push] flock not found: committing without the writer lock (install gbrain or flock)" >&2fi@@ -295,6 +299,13 @@ case "\${1:-}" inif git diff --cached --quiet -- "$@"; then echo "nothing to commit"; else git commit --only -m "$_msg" -- "$@"; fi ;;esac_head="$(git rev-parse HEAD)"+# Never hold the commit lock across the network: release it and push under the publish lock, like gbrain.+exec 9>&- 8>&-+unset BRAIN_COMMIT_LOCK_HELD GBRAIN_COMMIT_VIA+if command -v flock >/dev/null 2>&1; then+ exec 7>"$_gd/brain-publish.lock"+ flock -w "\${GBRAIN_PUBLISH_LOCK_WAIT_SECONDS:-300}" 7 || { echo "PUSH FAILED: another push held this checkout's publish lock; the commit is local-only. Run: gbrain git commit-push --push-only" >&2; exit 4; }+fiif git push origin "$_head:refs/heads/$_branch" >>"$_log" 2>&1; thenecho "$(date -u +%FT%TZ) [push] ok $_branch $(git rev-parse --short "$_head")" >>"$_log"; exit 0fi@@ -446,7 +457,7 @@ function pathContains(parent: string, child: string): boolean {return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));}-function resolveHooksDir(repoPath: string): { dir: string; tracked: boolean } {+export function resolveHooksDir(repoPath: string): { dir: string; tracked: boolean } {let hooksPath = '';try {hooksPath = execFileSync('git', ['-C', repoPath, 'config', '--get', 'core.hooksPath'], {@@ -465,7 +476,7 @@ function resolveHooksDir(repoPath: string): { dir: string; tracked: boolean } {}/** Ensure a repo-relative path is in the git exclude file so our hook stays untracked. */-function ensureExcluded(repoPath: string, relPath: string): void {+export function ensureExcluded(repoPath: string, relPath: string): void {const exclude = gitDirPath(repoPath, 'info/exclude');try {mkdirSync(dirname(exclude), { recursive: true });@@ -589,13 +600,14 @@ export async function isDurabilityHardenedAsync(repoPath: string): Promise<boole* remote, froze `last_sync_at` (HEAD never moved), and a later `sync --full`* delete-reconcile treated the never-committed pages as disposable.*- * #6530: commits only `<path>` (`commit --only`), under the checkout's commit- * lock when it frees within a short budget; a writer that holds it longer- * (a push on a slow network) does not stall the page write, and the commit- * still lands path-scoped (the shared checkout only ever fast-forwards, so it- * cannot be reverted by that writer). index.lock contention is retried- * briefly. Never throws; returns false when nothing was committed — the DB- * row and the on-disk file remain the durable sinks either way.+ * #6530: commits only `<path>` (`commit --only`), always under the checkout's+ * commit lock. GBRA-180: a writer that holds the lock past the short budget+ * no longer gets a lockless commit racing it on the shared index; the page+ * write stands, the file goes into the pending ledger, and the next locked+ * write-through (or `gbrain git commit-push --pending`) commits it. A commit+ * git refuses unstages the path again, so nothing is left staged for another+ * writer's commit to sweep up. Never throws; returns false when nothing was+ * committed — the DB row and the on-disk file remain the durable sinks.** `git add -- <path>` stages a removal as readily as an edit, so* `deletePageThrough` reuses this helper with `action: 'delete write-through'`@@ -1029,6 +1041,26 @@ function isGitRepo(repoPath: string): boolean {* the source dir while the enclosing repo owns `.git` — hardening must* assert/operate on the PARENT repo, not fail on the subdir's missing `.git`.*/+/**+ * GBRA-180: a source whose root sits below the checkout toplevel (a brain folder inside a larger repository)+ * records that root in `gbrain.sourceRoot`, so `gbrain git commit-push` refuses commits and publishes that+ * change files outside it. A source at the toplevel records nothing unless another source already narrowed+ * the checkout. Best-effort.+ */+function recordSourceRoot(top: string, sourcePath: string): void {+ const run = (args: string[]) => execFileSync('git', ['-C', top, 'config', '--local', ...args], {+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }) }).toString();+ try {+ const rel = relative(realpathSync(top), realpathSync(sourcePath)).split(sep).join('/');+ if (rel.startsWith('..') || isAbsolute(rel)) return;+ let current: string[] = [];+ try { current = run(['--get-all', SOURCE_ROOT_CONFIG]).split('\n').map(v => v.trim()).filter(Boolean); } catch { /* unset */ }+ const value = rel || '.';+ if (current.includes(value) || (!rel && !current.length)) return;+ run(['--add', SOURCE_ROOT_CONFIG, value]);+ } catch { /* best-effort: without it commit-push treats the whole checkout as the root */ }+}+function resolveRepoRoot(path: string): string {try {return execFileSync('git', ['-C', path, 'rev-parse', '--show-toplevel'], {@@ -1129,6 +1161,7 @@ export async function hardenBrainRepo(opts: HardenOpts): Promise<DurabilityReporgitConfigSet(repoPath, 'merge.autoStash', 'false');gitConfigSet(repoPath, 'pull.ff', 'only');} catch { /* best-effort: the helper still resolves gbrain from PATH */ }+ recordSourceRoot(repoPath, opts.repoPath);}// 4. committed helperpush('helper', installHelper(repoPath, dryRun));@@ -1174,7 +1207,7 @@ function commitScaffolding(repoPath: string, branch: string, redact: (s: string)const resolver = findResolverFile(repoPath);if (resolver) paths.push(relative(repoPath, resolver));try {- const r = commitAndPush({ repo: repoPath, paths, cwd: repoPath, message: 'chore(gbrain): install brain durability scaffolding' });+ const r = commitAndPush({ repo: repoPath, paths, cwd: repoPath, message: 'chore(gbrain): install brain durability scaffolding', allowOutsideSourceRoot: true });if (r.branch !== branch) return { status: 'needs_attention', detail: `checkout is on ${r.branch}, not ${branch}` };if (r.outcome === 'nothing_to_commit') return { status: 'ok', detail: 'scaffolding already committed' };return { status: 'fixed', detail: `committed + pushed durability scaffolding${r.checkout === 'lagging' ? ` (checkout lagging: ${r.lagging_reason})` : ''}` };diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 4feef0b6da..b52e3a4a00 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -26,7 +26,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--timings', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],- 'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],+ 'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--probe', '--resume', '--save', '--source', '--source-id', '--stale', '--strict-budget', '--yes'],'cache': ['--brain', '--help', '--json', '--source', '--yes'],'calibration': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],@@ -49,7 +49,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--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', '--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'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--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', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--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', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--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', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--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', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--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', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--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', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--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', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--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-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--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-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--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', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--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', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--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', '--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', '--path', '--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', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--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'],@@ -70,19 +70,19 @@ 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', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],- 'git': ['--abbrev-ref', '--add', '--aggressive', '--all', '--autostash', '--brain', '--branch', '--cached', '--cacheinfo', '--count', '--dry-run', '--enable', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--literal-pathspecs', '--local', '--local-env-vars', '--message', '--name-only', '--name-status', '--no-autostash', '--no-cron', '--no-recurse-submodules', '--no-tags', '--no-verify', '--no-write-fetch-head', '--only', '--pat-file', '--path', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--repo', '--require-clean', '--resolve', '--short', '--show-toplevel', '--source', '--unset-all', '--verify', '--write-tree'],+ 'git': ['--abbrev-ref', '--add', '--aggressive', '--all', '--allow-outside-source-root', '--autostash', '--brain', '--branch', '--cached', '--cacheinfo', '--cherry-mark', '--count', '--dry-run', '--enable', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--format', '--get', '--get-all', '--get-url', '--git-dir', '--git-path', '--hard', '--help', '--index-info', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--literal-pathspecs', '--local', '--local-env-vars', '--max-count', '--merge-base', '--message', '--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-all', '--untracked-files', '--verify', '--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', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--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': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--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', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--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', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--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', '--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', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--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', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--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', '--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', '--mcp-only', '--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-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--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', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],- 'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],+ 'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--push-only', '--query', '--question', '--queue', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],@@ -112,7 +112,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--held', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--timings', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -126,11 +126,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 91ef95f05b..dfc9077999 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -191,6 +191,11 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['git_convergence',// #5186: an ownership marker committed to a source checkout's Git index.'tracked_ownership_marker',+ // #7381: a source checkout behind its upstream, write-through files or staged files waiting for a commit, unpushed commits outside the source root (doctor/checks/git-writer.ts).+ 'checkout_lagging',+ 'dirty_age',+ 'commits_outside_source_root',+ 'quarantined_changes','takes_count','takes_weight_grid',// #5836: active facts with no entity (invisible to entity recall and the conflict sweep).diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5daa31a51a..61eeca6f3f 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -146,6 +146,8 @@ export const CODES = {command_failed: { class: 'server', summary: "The command failed before it wrote its JSON result." },commit_lock_busy: { class: 'retryable', summary: "Another writer held the checkout's commit lock for the whole wait, so nothing was committed.", docs: 'docs/guides/shared-checkout-git.md#outcomes' },commit_paths_invalid: { class: 'caller', summary: "The commit was refused before staging: no paths, a path outside the checkout, the whole checkout, or a path git would not stage.", docs: 'docs/guides/shared-checkout-git.md#outcomes' },+ commit_prestaged_paths: { class: 'consent', summary: "The commit was refused before staging: files another writer had already staged sit under a named directory, and committing them would publish that writer's work.", docs: 'docs/guides/shared-checkout-git.md#outcomes', actor: 'user' },+ commit_outside_source_root: { class: 'consent', summary: "The commit or publish was refused: it changes files outside the brain's configured source root (git config gbrain.sourceRoot), often a commit made without gbrain git commit-push.", docs: 'docs/guides/shared-checkout-git.md#source-roots', actor: 'user' },concurrent_write: { class: 'caller', summary: "A managed sync import raced a database-only write to the same page, so the file is held and the page keeps the database version; neither was overwritten.", why: "The page's live revision was written by a committed non-sync request after the import was frozen, so the Git file and the database genuinely diverge; choosing either silently would lose the other.", docs: 'docs/guides/write-refusals.md#concurrent_write', suggestion: 'Preview the reconciliation with gbrain sources reconcile <source> <slug> --preview, resolve it with the user, then run gbrain sources retry-held <source> and gbrain sync --source <source> --no-pull.' },config_error: { class: 'caller', summary: "A required configuration value or directory is missing or invalid." },confirmation_required: { class: 'consent', summary: "The command needs the user's authorization before it runs; nothing was changed.", exit: 3 },diff --git a/src/core/git/commit-guard.ts b/src/core/git/commit-guard.tsnew file mode 100644index 0000000000..9b1f2309ea--- /dev/null+++ b/src/core/git/commit-guard.ts@@ -0,0 +1,93 @@+/**+ * GBRA-180: the opt-in commit guard for a brain checkout several writers+ * share. A local, untracked prepare-commit-msg hook refuses every commit+ * gbrain did not make under the checkout's commit lock: a plain git commit,+ * -a, --amend, and --no-verify too (that flag skips only pre-commit and+ * commit-msg). gbrain's own commits carry GBRAIN_COMMIT_VIA naming the lock+ * they hold; its in-memory merges never run commit hooks. A merge commit, and+ * a commit that finishes a merge, cherry-pick, revert or rebase, pass: refusing+ * those would leave the operation half done in the shared tree. A refused+ * commit changes nothing (the index keeps what its writer staged). A person+ * bypasses it for one command with GBRAIN_COMMIT_GUARD=off. Off unless the+ * brain opts in with gbrain git guard --install; CLI-only.+ */+import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join, relative } from 'node:path';+import { ensureExcluded, resolveHooksDir } from '../brain-repo-durability.ts';+import { assertManagedFilesystemWrite } from '../persistence/filesystem-guard.ts';+import { opError } from '../ops/contract.ts';+import { checkoutRoot, gitVersion, COMMIT_LOCK_NAME, COMMIT_VIA_ENV } from './commit-push.ts';++export const GUARD_HOOK = 'prepare-commit-msg';+export const GUARD_BANNER = '# gbrain commit guard (prepare-commit-msg)';+export const GUARD_BYPASS_ENV = 'GBRAIN_COMMIT_GUARD';++export function renderGuardHook(): string {+ return `#!/usr/bin/env bash+${GUARD_BANNER}+# LOCAL + untracked: installed by gbrain git guard --install, removed by --uninstall.+# Refuses commits in this shared brain checkout (--no-verify included) that did not come+# through gbrain git commit-push or gbrain's own page writes, which hold the commit lock.+# A person can bypass it for one command: ${GUARD_BYPASS_ENV}=off git <command>+[ "\${${GUARD_BYPASS_ENV}:-}" = off ] && exit 0+[ "\${2:-}" = merge ] && exit 0+for _op in MERGE_HEAD CHERRY_PICK_HEAD REVERT_HEAD rebase-merge rebase-apply sequencer; do+ [ -e "$(git rev-parse --git-path "$_op")" ] && exit 0+done+_lock="$(git rev-parse --path-format=absolute --git-path ${COMMIT_LOCK_NAME} 2>/dev/null || true)"+if [ -n "$_lock" ] && [ "\${${COMMIT_VIA_ENV}:-}" = "$_lock" ]; then+ command -v flock >/dev/null 2>&1 || exit 0+ flock -n "$_lock" true 2>/dev/null || exit 0+fi+echo "gbrain commit guard: refused a commit that did not come through gbrain git commit-push; nothing changed." >&2+echo " Commit with: gbrain git commit-push -m '<msg>' -- <paths> (or scripts/brain-commit-push.sh '<msg>' <paths>)" >&2+echo " Bring remote commits in with: gbrain git commit-push --pull" >&2+echo " A person can bypass it once: ${GUARD_BYPASS_ENV}=off git <command> (docs/guides/shared-checkout-git.md#commit-guard)" >&2+exit 1+`;+}++export interface GuardStatus { installed: boolean; foreign: boolean; hook: string; repo: string }++function hookFile(root: string): { path: string; tracked: boolean } {+ const { dir, tracked } = resolveHooksDir(root);+ return { path: join(dir, GUARD_HOOK), tracked };+}++export function guardStatus(repo: string): GuardStatus {+ const root = checkoutRoot(repo);+ const { path } = hookFile(root);+ const body = existsSync(path) ? readFileSync(path, 'utf8') : null;+ return { installed: !!body?.includes(GUARD_BANNER), foreign: body !== null && !body.includes(GUARD_BANNER), hook: path, repo: root };+}++/** Install or refresh the guard. Refuses a managed worktree, git older than 2.31, and another tool's hook of the same name. */+export function installGuard(repo: string): GuardStatus & { changed: boolean } {+ const root = checkoutRoot(repo);+ assertManagedFilesystemWrite(root);+ const [maj, min] = gitVersion(root);+ if (maj < 2 || (maj === 2 && min < 31)) {+ throw opError('git_unavailable', `The commit guard needs git 2.31 or later (found ${maj}.${min}).`, 'Upgrade git on this machine, then rerun gbrain git guard --install. Nothing was changed.');+ }+ const { path, tracked } = hookFile(root);+ const script = renderGuardHook();+ const current = existsSync(path) ? readFileSync(path, 'utf8') : null;+ if (current !== null && !current.includes(GUARD_BANNER)) {+ throw opError('git_unavailable', `${path} is another tool's ${GUARD_HOOK} hook; gbrain does not replace it.`,+ 'Move that hook aside or chain it yourself, then rerun gbrain git guard --install. Nothing was changed.', { detail: path });+ }+ if (current === script) return { ...guardStatus(root), changed: false };+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, script);+ chmodSync(path, 0o755);+ if (tracked) ensureExcluded(root, relative(root, path));+ return { ...guardStatus(root), changed: true };+}++export function uninstallGuard(repo: string): GuardStatus & { changed: boolean } {+ const root = checkoutRoot(repo);+ const status = guardStatus(root);+ if (!status.installed) return { ...status, changed: false };+ rmSync(status.hook, { force: true });+ return { ...guardStatus(root), changed: true };+}diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.tsindex d2fdff3720..13c8b23e9e 100644--- a/src/core/git/commit-push.ts+++ b/src/core/git/commit-push.ts@@ -25,7 +25,7 @@* (#7010; the owner's Git effects publish this way). CLI-only; never exposed* over MCP (it pushes with host credentials).*/-import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { appendFileSync, existsSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { isAbsolute, join, relative, resolve } from 'node:path';import { execFileSync } from '../spawn.ts';@@ -42,6 +42,12 @@ export const COMMIT_LOCK_ENV = 'BRAIN_COMMIT_LOCK_HELD';export const PUBLISH_LOCK_NAME = 'brain-publish.lock';const PUBLISH_REQUEST_NAME = 'brain-publish.requested';const CONFLICT_STATE_NAME = 'brain-integrate-conflict.json';+/** Write-through files gbrain wrote but could not commit (lock busy past the short budget, or a refused commit): one `<iso>\t<json path>` line each. */+const PENDING_NAME = 'brain-writethrough-pending.log';+/** Toplevel-relative source root(s) of this checkout, one value each (`gbrain sources harden` writes them); unset means the whole checkout. */+export const SOURCE_ROOT_CONFIG = 'gbrain.sourceRoot';+/** Set to the commit lock path on every commit gbrain makes under that lock; the opt-in commit guard admits only these. */+export const COMMIT_VIA_ENV = 'GBRAIN_COMMIT_VIA';const MAX_PUSH_ATTEMPTS = 8;const sleeper = new Int32Array(new SharedArrayBuffer(4));const INDEX_LOCK_RETRIES = 5;@@ -63,6 +69,8 @@ export interface CommitPushResult {confirmed?: 'push' | 'remote';checkout: CheckoutState;lagging_reason?: string;+ /** Opt-in quarantine (git config gbrain.quarantine): the local versions of conflicting files, parked under a ref; the remote's version was published. */+ quarantined?: QuarantineEntry;}export interface PullResult {@@ -94,6 +102,10 @@ 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;+ /** 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. */+ allowOutsideSourceRoot?: boolean;}export type Resolution = { kind: 'ours' } | { kind: 'theirs' } | { kind: 'file'; path: string };@@ -303,6 +315,26 @@ export function scopePaths(root: string, paths: string[], cwd: string): string[]return [...new Set(out)];}+/** The checkout's configured source roots (`gbrain.sourceRoot`, toplevel-relative); [''] (the whole checkout) when none is set. */+export function configuredSourceRoots(root: string): string[] {+ const roots: string[] = [];+ for (const raw of git(root, ['config', '--get-all', SOURCE_ROOT_CONFIG]).stdout.split('\n').map(v => v.trim()).filter(Boolean)) {+ const rel = (isAbsolute(raw) ? relative(root, raw) : raw).split('\\').join('/').replace(/^(\.\/)+/, '').replace(/\/+$/, '');+ if (rel === '' || rel === '.') return [''];+ if (!rel.startsWith('..')) roots.push(rel);+ }+ return roots.length ? [...new Set(roots)] : [''];+}++const covers = (spec: string, path: string) => spec === '' || path === spec || path.startsWith(`${spec}/`);+export const insideSourceRoots = (path: string, roots: string[]) => roots.some(r => covers(r, path));++function outsideRootError(root: string, roots: string[], paths: string[], what: string): OperationError {+ return opError('commit_outside_source_root', `${what} ${paths.slice(0, 10).join(', ')}${paths.length > 10 ? ', ...' : ''}, outside this brain's source root (${roots.join(', ')}).`,+ `Commit only files under the source root. Files elsewhere in ${root} belong to other projects or writers; commit those with their own tools. Nothing was staged or committed.`,+ { detail: JSON.stringify({ roots, paths }) });+}+// ── Commit ──────────────────────────────────────────────────────────────────function indexLocked(r: GitRun): boolean {@@ -310,9 +342,9 @@ function indexLocked(r: GitRun): boolean {}/** Run an index-writing git command; a lockless git holding index.lock gets a bounded, jittered retry. */-function withIndexRetry(root: string, args: string[], what: string, env?: NodeJS.ProcessEnv): GitRun {+function withIndexRetry(root: string, args: string[], what: string, env?: NodeJS.ProcessEnv, input?: string): GitRun {for (let attempt = 0; ; attempt++) {- const r = git(root, args, { env, timeoutMs: 120_000 });+ const r = git(root, args, { env, timeoutMs: 120_000, input });if (r.code === 0 || !indexLocked(r)) return r;if (attempt >= INDEX_LOCK_RETRIES) {const lock = absGitPath(root, 'index.lock');@@ -345,40 +377,191 @@ function withRenamePartners(root: string, rel: string[]): string[] {return [...out];}-function commitPaths(root: string, rel: string[], message: string, lockPath: string | null): string | null {+/** Index entries that differ from HEAD, whoever staged them, with rename detection off so both sides of a rename are listed. */+function stagedPaths(root: string): string[] {+ return git(root, ['diff', '--cached', '--no-renames', '--name-only', '-z']).stdout.split('\0').filter(Boolean);+}++/** The index entries under `rel` as `ls-files -s` records, so a failed commit can put them back exactly. */+function indexEntries(root: string, rel: string[]): string[] {+ return git(root, ['--literal-pathspecs', 'ls-files', '-s', '-z', '--', ...rel]).stdout.split('\0').filter(Boolean);+}++/**+ * Put the index under `rel` back to `before` after a commit that did not land:+ * `git add` already staged the paths, and an entry left staged in the shared+ * index is what the next writer's commit without paths sweeps up.+ */+function restoreIndex(root: string, rel: string[], before: string[]): void {+ const pathOf = (line: string) => line.slice(line.indexOf('\t') + 1);+ const kept = new Set(before.map(pathOf));+ const zero = '0'.repeat(git(root, ['rev-parse', 'HEAD']).stdout.trim().length || 40);+ const records = [...indexEntries(root, rel).map(pathOf).filter(p => !kept.has(p)).map(p => `0 ${zero}\t${p}`), ...before];+ if (records.length) withIndexRetry(root, ['update-index', '-z', '--index-info'], 'index restore', undefined, records.map(l => `${l}\0`).join(''));+}++interface CommitScope { roots: string[]; lockPath: string; markHeld: boolean }++/**+ * Stage and commit exactly `rel` (the caller holds the commit lock). Refused+ * before anything is staged: a path outside the source root(s), and a file+ * another writer already staged under a named directory (name it to claim+ * it). A commit git refuses leaves the index as it found it.+ */+function commitPaths(root: string, rel: string[], message: string, scope: CommitScope): string | null {+ const outside = rel.filter(p => !insideSourceRoots(p, scope.roots));+ if (outside.length) throw outsideRootError(root, scope.roots, outside, 'Refusing to commit');+ const swept = stagedPaths(root).filter(p => !rel.includes(p) && rel.some(spec => covers(spec, p)));+ if (swept.length) {+ const list = `${swept.slice(0, 10).join(', ')}${swept.length > 10 ? ', ...' : ''}`;+ throw opError('commit_prestaged_paths', `${swept.length} file(s) under the named path(s) were already staged by another writer: ${list}.`,+ 'Nothing was staged or committed. If they are yours, name each file explicitly; otherwise leave them to the writer that staged them, or unstage them with the user\'s agreement (git restore --staged -- <file>; the working tree keeps its bytes).',+ { detail: JSON.stringify({ paths: swept }), fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,+ argv: ['git', '-C', root, 'restore', '--staged', '--', ...swept],+ why: 'Another writer staged these files; committing them would publish whatever that writer had in progress, and unstaging them drops its staging.',+ user_message: `Files already staged by another writer sit under the path you asked to commit (${list}). Commit only the files you name, or unstage those (their bytes stay on disk)?`,+ docs: 'docs/guides/shared-checkout-git.md#outcomes' } });+ }+ const before = indexEntries(root, rel);const add = withIndexRetry(root, ['--literal-pathspecs', 'add', '-A', '--', ...rel], 'git add');if (add.code !== 0) {throw opError('commit_paths_invalid', 'git add refused the given paths.', add.stderr.trim().slice(0, 300) || 'Check the paths exist or are tracked.');}- rel = withRenamePartners(root, rel);- if (git(root, ['--literal-pathspecs', 'diff', '--cached', '--quiet', '--', ...rel]).code === 0) return null;- const commit = withIndexRetry(root, ['--literal-pathspecs', 'commit', '--only', '-m', message, '--', ...rel], 'git commit',- lockPath ? { [COMMIT_LOCK_ENV]: lockPath } : undefined);- if (commit.code !== 0) {- throw opError('git_unavailable', `git commit failed in ${root}.`,- `${commit.stderr.trim().slice(0, 300)} A missing git identity (user.name, user.email) or a refusing pre-commit hook are common causes.`);+ try {+ const paths = withRenamePartners(root, rel);+ const partners = paths.filter(p => !insideSourceRoots(p, scope.roots));+ if (partners.length) throw outsideRootError(root, scope.roots, partners, 'A staged rename would commit');+ if (git(root, ['--literal-pathspecs', 'diff', '--cached', '--quiet', '--', ...paths]).code === 0) return null;+ const env = { [COMMIT_VIA_ENV]: scope.lockPath, ...(scope.markHeld ? { [COMMIT_LOCK_ENV]: scope.lockPath } : {}) };+ const commit = withIndexRetry(root, ['--literal-pathspecs', 'commit', '--only', '-m', message, '--', ...paths], 'git commit', env);+ if (commit.code !== 0) {+ throw opError('git_unavailable', `git commit failed in ${root}; the paths were unstaged again and keep their bytes.`,+ `${commit.stderr.trim().slice(0, 300)} A missing git identity (user.name, user.email) or a refusing pre-commit hook are common causes.`);+ }+ return gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');+ } catch (e) {+ try { restoreIndex(root, rel, before); } catch { /* the index lock outlasted the retries; the error below still stands */ }+ throw e;+ }+}++// ── Pending write-through ───────────────────────────────────────────────────++export interface PendingWriteThrough { path: string; since: string }++const PENDING_NOTED = new Set(['commit_lock_busy', 'git_index_locked', 'git_index_stale', 'git_unavailable', 'git_operation_in_progress']);++function readPendingFile(file: string, into: Map<string, string>): void {+ let text: string;+ try { text = readFileSync(file, 'utf8'); } catch { return; }+ for (const line of text.split('\n')) {+ const tab = line.indexOf('\t');+ if (tab === -1) continue;+ let path: unknown;+ try { path = JSON.parse(line.slice(tab + 1)); } catch { continue; }+ const since = line.slice(0, tab);+ if (typeof path === 'string' && path && (!into.has(path) || since < into.get(path)!)) into.set(path, since);}- return gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');+}++/** Write-through files gbrain wrote in this checkout but could not commit, oldest first. A path committed since stays listed until the next locked commit settles the ledger. */+export function readPendingWriteThrough(repo: string): PendingWriteThrough[] {+ try {+ const file = absGitPath(checkoutRoot(repo), PENDING_NAME);+ const entries = new Map<string, string>();+ readPendingFile(file, entries);+ readPendingFile(`${file}.settle`, entries);+ return [...entries].map(([path, since]) => ({ path, since })).sort((a, b) => a.since.localeCompare(b.since));+ } catch {+ return [];+ }+}++/** The pending ledger's files that still differ from HEAD (doctor's `dirty_age`); the others were committed since. */+export function pendingWriteThroughStillDirty(repo: string): PendingWriteThrough[] {+ const pending = readPendingWriteThrough(repo);+ if (!pending.length) return [];+ const dirty = dirtyPaths(checkoutRoot(repo), pending.map(e => e.path));+ return pending.filter(e => dirty.has(e.path));+}++/** Appends without the lock (O_APPEND), so a writer that could not get it still records its file. */+function notePending(root: string, paths: string[]): void {+ try { appendFileSync(absGitPath(root, PENDING_NAME), paths.map(p => `${new Date().toISOString()}\t${JSON.stringify(p)}\n`).join('')); } catch { /* best-effort */ }+}++/** Which of `paths` differ from HEAD in the index or the working tree. */+function dirtyPaths(root: string, paths: string[]): Set<string> {+ const out = new Set<string>();+ for (let i = 0; i < paths.length; i += 500) {+ const entries = git(root, ['--literal-pathspecs', 'status', '--porcelain', '-z', '--untracked-files=all', '--', ...paths.slice(i, i + 500)]).stdout.split('\0');+ for (let j = 0; j < entries.length; j++) {+ if (entries[j].length < 4) continue;+ out.add(entries[j].slice(3));+ if (/^[RC]/.test(entries[j])) j++;+ }+ }+ return out;+}++/** Drop ledger entries whose file no longer differs from HEAD (the caller holds the commit lock). New lines appended meanwhile go to a fresh ledger file. */+function settlePending(root: string): void {+ try {+ const file = absGitPath(root, PENDING_NAME);+ const settle = `${file}.settle`;+ const moved = `${file}.${process.pid}.tmp`;+ if (existsSync(file)) renameSync(file, moved);+ const entries = new Map<string, string>();+ readPendingFile(settle, entries);+ readPendingFile(moved, entries);+ const dirty = dirtyPaths(root, [...entries.keys()]);+ const keep = [...entries].filter(([path]) => dirty.has(path)).map(([path, since]) => `${since}\t${JSON.stringify(path)}\n`);+ if (keep.length) { writeFileSync(`${settle}.tmp`, keep.join('')); renameSync(`${settle}.tmp`, settle); }+ else rmSync(settle, { force: true });+ rmSync(moved, { force: true });+ } catch { /* best-effort: the ledger only feeds retries and doctor */ }}/**- * Commit-only entry for gbrain's own write paths (write-through pages): the- * commit lock when it frees within `lockWaitMs`, else a path-scoped commit- * without it (safe: the shared checkout only fast-forwards, so no lock holder- * can revert it). No marker is set, so the post-commit hook publishes.- * Returns the new commit, or null when the paths had no change.+ * Commit-only entry for gbrain's own write paths (write-through pages, facts+ * fences, takes, timeline, lint fixes), always under the commit lock. A writer+ * holding the lock past `lockWaitMs` makes this fail `commit_lock_busy` (the+ * file write itself stands) and the file goes into the pending ledger, which+ * the next locked write-through or `gbrain git commit-push --pending` commits and+ * doctor's `dirty_age` reports. It never commits without the lock: that races+ * other writers on the shared index. Paths must sit under `repo` (the source+ * root). No marker is set, so the post-commit hook publishes. Returns the new+ * commit, or null when the paths had no change.*/export function commitPathsLocked(repo: string, rel: string[], message: string, opts: { lockWaitMs: number }): string | null {const root = checkoutRoot(repo);assertManagedFilesystemWrite(root);assertNoOperationInProgress(root);const paths = scopePaths(root, rel, root);- let lock: CommitLock | null = null;- try { lock = acquireCommitLock(root, opts.lockWaitMs); } catch (e) { if ((e as { code?: string }).code !== 'commit_lock_busy') throw e; }+ const own = relative(realpathSync(root), realpathSync(repo)).split('\\').join('/');+ const roots = [own.startsWith('..') ? '' : own];+ let lock: CommitLock;+ try { lock = acquireCommitLock(root, opts.lockWaitMs); } catch (e) {+ if (PENDING_NOTED.has((e as { code?: string }).code ?? '')) notePending(root, paths);+ throw e;+ }try {- return commitPaths(root, paths, message, null);+ const pending = [...dirtyPaths(root, readPendingWriteThrough(root).map(e => e.path).filter(p => !paths.includes(p) && insideSourceRoots(p, roots)))];+ const scope = { roots, lockPath: lock.lockPath, markHeld: false };+ let sha: string | null;+ try {+ sha = commitPaths(root, [...paths, ...pending], pending.length ? `${message} (+${pending.length} pending write-through file(s))` : message, scope);+ } catch (e) {+ if (!pending.length) throw e;+ sha = commitPaths(root, paths, message, scope);+ }+ settlePending(root);+ return sha;+ } catch (e) {+ if (PENDING_NOTED.has((e as { code?: string }).code ?? '')) notePending(root, paths);+ throw e;} finally {- lock?.release();+ lock.release();}}@@ -409,11 +592,15 @@ function fetchFlags(root: string): string[] {return ['--no-tags', ...(maj > 2 || (maj === 2 && min >= 29) ? ['--no-write-fetch-head'] : [])];}-/** merge-tree --write-tree on git >= 2.38; else (or with the GBRAIN_GIT_NO_MERGE_TREE=1 test seam) a 3-way read-tree that treats any same-path change on both sides as a conflict. */-function mergeTrees(root: string, ours: string, theirs: string): MergeTree {+/**+ * merge-tree --write-tree on git >= 2.38; else (or with the GBRAIN_GIT_NO_MERGE_TREE=1 test seam) a 3-way read-tree+ * that treats any same-path change on both sides as a conflict. `base` replaces the merge base (a replayed commit's+ * parent); merge-tree takes it from git 2.40.+ */+function mergeTrees(root: string, ours: string, theirs: string, base?: string): MergeTree {const [maj, min] = cachedGitVersion(root);- if ((maj > 2 || (maj === 2 && min >= 38)) && process.env.GBRAIN_GIT_NO_MERGE_TREE !== '1') {- const r = git(root, ['merge-tree', '--write-tree', '--name-only', '-z', ours, theirs]);+ if ((maj > 2 || (maj === 2 && min >= (base ? 40 : 38))) && process.env.GBRAIN_GIT_NO_MERGE_TREE !== '1') {+ const r = git(root, ['merge-tree', '--write-tree', '--name-only', '-z', ...(base ? [`--merge-base=${base}`] : []), ours, theirs]);if (r.code !== 0 && r.code !== 1) throw opError('git_unavailable', 'git merge-tree failed.', r.stderr.trim().slice(0, 300));const f = r.stdout.split('\0');const tree = f[0] || null;@@ -433,12 +620,12 @@ function mergeTrees(root: string, ours: string, theirs: string): MergeTree {}return { tree, conflicts: [...conflicts], structural: [...conflicts].filter(p => structural.has(p)) };}- const base = git(root, ['merge-base', ours, theirs]).stdout.trim();- if (!base) throw opError('integrate_conflict', 'The local and remote branches share no history.', 'Reconcile the branches by hand.');+ const mergeBase = base ?? git(root, ['merge-base', ours, theirs]).stdout.trim();+ if (!mergeBase) throw opError('integrate_conflict', 'The local and remote branches share no history.', 'Reconcile the branches by hand.');const dir = mkdtempSync(join(tmpdir(), 'gbrain-integrate-'));try {const env = { GIT_INDEX_FILE: join(dir, 'index') };- const read = git(root, ['read-tree', '-m', '-i', '--aggressive', base, ours, theirs], { env });+ const read = git(root, ['read-tree', '-m', '-i', '--aggressive', mergeBase, ours, theirs], { env });if (read.code !== 0) throw opError('git_unavailable', 'git read-tree failed.', read.stderr.trim().slice(0, 300));const unmerged = git(root, ['ls-files', '-u', '-z'], { env }).stdout.split('\0').filter(Boolean);if (!unmerged.length) return { tree: gitOk(root, ['write-tree'], 'write-tree', { env }), conflicts: [], structural: [] };@@ -457,6 +644,52 @@ function mergeTrees(root: string, ours: string, theirs: string): MergeTree {}}+const treeOf = (root: string, commit: string) => gitOk(root, ['rev-parse', `${commit}^{tree}`], 'rev-parse tree');++interface Integration extends MergeTree {+ /** Local commits left out because an upstream commit already carries the same patch (`git patch-id`). */+ skipped: string[];+}++const MAX_REPLAY = 500;++/**+ * The tree a publish of `local` over `remote` should carry. A 3-way merge of the two tips+ * counts a local commit whose patch already reached the remote (cherry-picked or rebased there) as a new+ * change again: a remote that edited those lines since conflicts forever, and a remote that reverted it gets+ * the change back silently. So when any local commit is patch-equivalent to an upstream one, the local+ * commits are replayed in memory onto the remote tip instead, oldest first, leaving out the equivalent ones+ * and the clean merges (their content is their parents'). A merge that carries its own resolution, a root+ * commit, or more than MAX_REPLAY commits fall back to the tip merge.+ */+function integrate(root: string, local: string, remote: string): Integration {+ const commits = git(root, ['rev-list', '--reverse', '--topo-order', '--cherry-mark', '--right-only', '--parents', `${remote}...${local}`])+ .stdout.split('\n').filter(Boolean).map(line => {+ const [head, ...parents] = line.split(' ');+ return { sha: head.slice(1), equivalent: head.startsWith('='), parents };+ });+ const tipMerge = (): Integration => ({ ...mergeTrees(root, local, remote), skipped: [] });+ if (!commits.some(c => c.equivalent) || commits.length > MAX_REPLAY) return tipMerge();+ let acc = remote;+ const conflicts = new Set<string>();+ const structural = new Set<string>();+ const skipped: string[] = [];+ for (const c of commits) {+ if (c.equivalent) { skipped.push(c.sha); continue; }+ if (c.parents.length !== 1) {+ if (c.parents.length !== 2) return tipMerge();+ const own = mergeTrees(root, c.parents[0], c.parents[1]);+ if (own.conflicts.length || own.tree !== treeOf(root, c.sha)) return tipMerge();+ continue;+ }+ const step = mergeTrees(root, acc, c.sha, c.parents[0]);+ for (const p of step.conflicts) conflicts.add(p);+ for (const p of step.structural) structural.add(p);+ acc = gitOk(root, ['commit-tree', '--no-gpg-sign', step.tree!, '-p', acc, '-m', 'gbrain: replay'], 'commit-tree');+ }+ return { tree: treeOf(root, acc), conflicts: [...conflicts], structural: [...structural], skipped };+}+interface TreeEntry { mode: string; type: string; sha: string }function treeEntry(root: string, commit: string, path: string): TreeEntry | null {@@ -530,9 +763,11 @@ function conflictError(ctx: Ctx, ours: string, theirs: string, merged: MergeTree}/** Honors the user's commit signing config, like the `git pull` it replaces. */-function buildMerge(ctx: Ctx, ours: string, theirs: string, tree: string): string {- return gitOk(ctx.root, ['commit-tree', tree, '-p', ours, '-p', theirs,- '-m', `gbrain: merge ${ctx.remote}/${ctx.mergeRef.replace(/^refs\/heads\//, '')} into ${ctx.branch}`], 'commit-tree');+function buildMerge(ctx: Ctx, ours: string, theirs: string, tree: string, skipped: string[] = [], extra: string[] = []): string {+ const remote = `${ctx.remote}/${ctx.mergeRef.replace(/^refs\/heads\//, '')}`;+ const note = skipped.length+ ? ['-m', `Left out ${skipped.length} local commit(s) whose patch ${remote} already has: ${skipped.slice(0, 20).map(s => s.slice(0, 12)).join(' ')}${skipped.length > 20 ? ' ...' : ''}`] : [];+ return gitOk(ctx.root, ['commit-tree', tree, '-p', ours, '-p', theirs, '-m', `gbrain: merge ${remote} into ${ctx.branch}`, ...note, ...extra.flatMap(m => ['-m', m])], 'commit-tree');}function fetchTracking(ctx: Ctx): string | null {@@ -571,7 +806,41 @@ function remoteContains(ctx: Ctx, sha: string): boolean {return true;}-interface Published { sha: string; integrated: number; confirmed: 'push' | 'remote' }+interface Published { sha: string; integrated: number; confirmed: 'push' | 'remote'; quarantined?: QuarantineEntry }++// ── Quarantine (opt-in) ─────────────────────────────────────────────────────++const QUARANTINE_LEDGER_NAME = 'brain-quarantine.log';+export const QUARANTINE_REF_PREFIX = 'refs/gbrain/quarantine/';++export interface QuarantineEntry { ref: string; local: string; remote: string; paths: string[]; at: string }++const quarantineEnabled = (root: string) => git(root, ['config', '--type=bool', '--get', 'gbrain.quarantine']).stdout.trim() === 'true';++/** Name the local commit under refs/gbrain/quarantine/ and note which files it parks; the ref keeps it even if history is later rewritten. */+function parkLocalVersion(root: string, local: string, remote: string, paths: string[]): QuarantineEntry {+ const at = new Date().toISOString();+ const ref = `${QUARANTINE_REF_PREFIX}${at.replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')}-${local.slice(0, 12)}`;+ gitOk(root, ['update-ref', ref, local], 'update-ref quarantine');+ const entry = { ref, local, remote, paths, at };+ appendFileSync(absGitPath(root, QUARANTINE_LEDGER_NAME), `${JSON.stringify(entry)}\n`);+ return entry;+}++/** Parked local versions whose ref still exists (deleting the ref is how the user says they are done with it). */+export function readQuarantine(repo: string): QuarantineEntry[] {+ try {+ const root = checkoutRoot(repo);+ const p = absGitPath(root, QUARANTINE_LEDGER_NAME);+ if (!existsSync(p)) return [];+ const live = new Set(git(root, ['for-each-ref', '--format=%(refname)', QUARANTINE_REF_PREFIX]).stdout.split('\n').filter(Boolean));+ return readFileSync(p, 'utf8').split('\n').flatMap(line => {+ try { const e = JSON.parse(line) as QuarantineEntry; return live.has(e.ref) ? [e] : []; } catch { return []; }+ });+ } catch {+ return [];+ }+}/*** Push `start` (an immutable sha), merging remote commits in memory as needed.@@ -583,14 +852,15 @@ function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> |let integrated = 0;let lastError = '';let stalled = 0;+ let quarantined: QuarantineEntry | undefined;const onRemote = (): Published => {const tip = fetchTracking(ctx);- return { sha: tip && isAncestor(ctx.root, candidate, tip) ? tip : candidate, integrated, confirmed: 'remote' };+ return { sha: tip && isAncestor(ctx.root, candidate, tip) ? tip : candidate, integrated, confirmed: 'remote', ...(quarantined ? { quarantined } : {}) };};for (let attempt = 0; attempt < MAX_PUSH_ATTEMPTS; attempt++) {if (attempt) Atomics.wait(sleeper, 0, 0, Math.min(2000, 50 * 2 ** attempt) + Math.floor(Math.random() * 100));const push = remoteGit(ctx.root, 'push', [...(ctx.keepCheckout ? ['--no-verify'] : []), '--', ctx.remote, `${candidate}:${ctx.mergeRef}`]);- if (push.code === 0) return { sha: candidate, integrated, confirmed: 'push' };+ if (push.code === 0) return { sha: candidate, integrated, confirmed: 'push', ...(quarantined ? { quarantined } : {}) };lastError = push.stderr.trim();if (remoteContains(ctx, candidate)) return onRemote();const remoteTip = fetchTracking(ctx);@@ -599,9 +869,14 @@ function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> |if (++stalled > 1) break;continue;}- const merged = mergeTrees(ctx.root, candidate, remoteTip);+ const merged = integrate(ctx.root, candidate, remoteTip);let tree = merged.tree!;- if (merged.conflicts.length) {+ let parkedNote: string[] = [];+ if (merged.conflicts.length && !resolutions?.size && !merged.structural.length && quarantineEnabled(ctx.root)) {+ tree = resolvedTree(ctx, candidate, remoteTip, merged, new Map(merged.conflicts.map(p => [p, { kind: 'theirs' } as Resolution])), cwd);+ quarantined = parkLocalVersion(ctx.root, candidate, remoteTip, merged.conflicts);+ parkedNote = [`Quarantined this machine's version of ${merged.conflicts.length} conflicting file(s) under ${quarantined.ref}: ${merged.conflicts.slice(0, 20).join(', ')}`];+ } else if (merged.conflicts.length) {if (!resolutions?.size) throw conflictError(ctx, candidate, remoteTip, merged);if (!expectRemote || !remoteTip.startsWith(expectRemote.toLowerCase())) {throw conflictError(ctx, candidate, remoteTip, merged,@@ -610,7 +885,7 @@ function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> |tree = resolvedTree(ctx, candidate, remoteTip, merged, resolutions, cwd);}integrated += Number(git(ctx.root, ['rev-list', '--count', `${candidate}..${remoteTip}`]).stdout.trim() || 0);- candidate = buildMerge(ctx, candidate, remoteTip, tree);+ candidate = buildMerge(ctx, candidate, remoteTip, tree, merged.skipped, parkedNote);}if (remoteContains(ctx, candidate)) return onRemote();throw opError('push_unconfirmed', `The commit is durable locally but no push to ${ctx.remote}/${ctx.mergeRef.replace(/^refs\/heads\//, '')} was confirmed.`,@@ -618,6 +893,41 @@ function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> |{ detail: candidate, retryable: true });}+/** Non-merge commits in `target` but not in `upstream` (at most 200) that change files outside `roots`; null when git cannot list them. */+export function localCommitsOutsideRoots(root: string, target: string, upstream: string, roots: string[]): Array<{ sha: string; paths: string[] }> | null {+ if (roots.includes('')) return [];+ const local = git(root, ['rev-list', '--no-merges', '--max-count=200', target, '--not', upstream]);+ if (local.code !== 0) return null;+ const offending: Array<{ sha: string; paths: string[] }> = [];+ for (const sha of local.stdout.split('\n').filter(Boolean)) {+ const paths = git(root, ['diff-tree', '--no-commit-id', '--name-only', '--no-renames', '-r', '-z', '--root', sha]).stdout.split('\0').filter(p => p && !insideSourceRoots(p, roots));+ if (paths.length) offending.push({ sha, paths });+ }+ return offending;+}++/**+ * Refuse to publish a local commit that changes files outside the configured source root(s). In a shared+ * checkout a commit made without paths (a cron's `git add <dir>; git commit`) carries whatever any writer+ * had staged; the source-root config is how a brain inside a larger repository says which files are its own.+ * Merge commits are not judged (gbrain's in-memory merges bring remote files in). With no root configured+ * the whole checkout is the root and nothing is refused.+ */+function assertLocalCommitsInsideRoots(ctx: Ctx, target: string, roots: string[]): void {+ const offending = localCommitsOutsideRoots(ctx.root, target, ctx.trackingRef, roots) ?? [];+ if (!offending.length) return;+ const files = [...new Set(offending.flatMap(o => o.paths))];+ const shas = offending.map(o => o.sha.slice(0, 12)).join(', ');+ throw opError('commit_outside_source_root', `${offending.length} local commit(s) (${shas}) change ${files.length} file(s) outside this brain's source root (${roots.join(', ')}): ${files.slice(0, 10).join(', ')}${files.length > 10 ? ', ...' : ''}. Nothing was pushed.`,+ `A commit made without gbrain git commit-push (for example a cron's git add plus git commit) can carry files other writers had staged. Show the user git show --stat ${offending[0].sha.slice(0, 12)}; if they want it published as is, rerun with --allow-outside-source-root. See docs/guides/shared-checkout-git.md#source-roots.`,+ { detail: JSON.stringify({ roots, commits: offending }),+ fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,+ argv: ['gbrain', 'git', 'commit-push', '--push-only', '--allow-outside-source-root', '--path', ctx.root],+ why: 'These commits change files that are not the brain\'s; publishing them can overwrite other projects\' or writers\' work on the remote.',+ user_message: `Local commit(s) ${shas} change files outside the brain's folder (${files.slice(0, 5).join(', ')}${files.length > 5 ? ', ...' : ''}). Publish them anyway?`,+ docs: 'docs/guides/shared-checkout-git.md#source-roots' } });+}+/** 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();@@ -687,7 +997,10 @@ export function commitAndPush(opts: CommitPushOptions): CommitPushResult {if (opts.keepCheckout && !opts.pushOnly) throw opError('commit_paths_invalid', 'keepCheckout publishes commits already on the branch; it commits nothing.', 'Use --push-only --keep-checkout.');if (!opts.keepCheckout) assertManagedFilesystemWrite(root);const cwd = opts.cwd ?? process.cwd();- const rel = opts.pushOnly ? [] : scopePaths(root, opts.paths ?? [], cwd);+ const roots = configuredSourceRoots(root);+ const rel = opts.pushOnly ? [] : opts.pending+ ? [...dirtyPaths(root, readPendingWriteThrough(root).map(e => e.path).filter(p => insideSourceRoots(p, roots)))]+ : scopePaths(root, opts.paths ?? [], cwd);if (!opts.pushOnly && !opts.message?.trim()) {throw opError('commit_paths_invalid', 'A commit message is required.', 'Pass -m "<message>".');}@@ -701,7 +1014,8 @@ export function commitAndPush(opts: CommitPushOptions): CommitPushResult {const lock = acquireCommitLock(root, opts.lockWaitMs);try {assertNoOperationInProgress(root);- committed = commitPaths(root, rel, opts.message!.trim(), lock.lockPath);+ committed = rel.length ? commitPaths(root, rel, opts.message!.trim(), { roots: opts.allowOutsideSourceRoot ? [''] : roots, lockPath: lock.lockPath, markHeld: true }) : null;+ settlePending(root);} finally {lock.release();}@@ -730,7 +1044,9 @@ export function commitAndPush(opts: CommitPushOptions): CommitPushResult {rmSync(requestPath, { force: true });try {const head = gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');- const published = publish(ctx, start && !isAncestor(root, start, head) ? start : head, resolutions, opts.expectRemote, cwd);+ const target = start && !isAncestor(root, start, head) ? start : head;+ if (!opts.allowOutsideSourceRoot) assertLocalCommitsInsideRoots(ctx, target, roots);+ const published = publish(ctx, target, resolutions, opts.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);return { published, moved };@@ -759,6 +1075,7 @@ export function commitAndPush(opts: CommitPushOptions): CommitPushResult {outcome: moved.checkout === 'lagging' ? 'pushed_checkout_lagging' : committed || opts.pushOnly ? 'pushed' : 'nothing_to_commit',sha: published.sha, committed, branch: ctx.branch, remote: ctx.remote, paths: rel,integrated: published.integrated, confirmed: published.confirmed, checkout: moved.checkout, ...(moved.reason ? { lagging_reason: moved.reason } : {}),+ ...(published.quarantined ? { quarantined: published.quarantined } : {}),};}@@ -789,9 +1106,9 @@ export function pullShared(repo: string, opts: { requireClean?: boolean; lockWailet target = remoteTip;let merged = false;if (!isAncestor(root, head, remoteTip)) {- const tree = mergeTrees(root, head, remoteTip);+ const tree = integrate(root, head, remoteTip);if (tree.conflicts.length) throw conflictError(ctx, head, remoteTip, tree);- target = buildMerge(ctx, head, remoteTip, tree.tree!);+ target = buildMerge(ctx, head, remoteTip, tree.tree!, tree.skipped);merged = true;}const moved = advanceLocked(root, target, head);diff --git a/test/doctor-git-writer-7381.test.ts b/test/doctor-git-writer-7381.test.tsnew file mode 100644index 0000000000..a0ab7c9699--- /dev/null+++ b/test/doctor-git-writer-7381.test.ts@@ -0,0 +1,127 @@+/**+ * #7381 (GBRA-180): `checkout_lagging`, `dirty_age` and+ * `commits_outside_source_root` read each unmanaged source checkout with an+ * upstream: behind the last fetch for over an hour, write-through files or+ * staged files waiting over 30 minutes, unpushed commits outside the roots.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync, spawn } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { gitWriterEntry, CHECKOUT_LAG_WARN_MS } from '../src/commands/doctor/checks/git-writer.ts';+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { commitAndPush, commitPathsLocked } from '../src/core/git/commit-push.ts';++let engine: PGLiteEngine;+const dir = mkdtempSync(join(tmpdir(), 'gbrain-git-writer-'));+const HOUR = 3_600_000;++function git(cwd: string, args: string[], env: Record<string, string> = {}): string {+ return execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...env } }).toString().trim();+}+function checkout(name: string): { bare: string; work: string } {+ const bare = join(dir, `${name}.git`), work = join(dir, name);+ git(dir, ['init', '-q', '--bare', '-b', 'main', bare]);+ git(dir, ['clone', '-q', bare, work]);+ git(work, ['config', 'user.email', '[email protected]']);+ git(work, ['config', 'user.name', 'Example']);+ mkdirSync(join(work, 'brain'));+ writeFileSync(join(work, 'brain', 'note.md'), 'first\n');+ writeFileSync(join(work, 'other.md'), 'not the brain\n');+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'first']); git(work, ['push', '-q', '-u', 'origin', 'main']);+ return { bare, work };+}+const run = async () => Object.fromEntries(((await gitWriterEntry.run({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext)) as Check[]).map(c => [c.name, c]));++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+});++test('registered and categorized', () => {+ for (const name of ['checkout_lagging', 'dirty_age', 'commits_outside_source_root', 'quarantined_changes']) {+ expect(DOCTOR_CHECK_REGISTRY.some(entry => entry.emits.includes(name))).toBe(true);+ expect(categorizeCheck(name)).toBe('brain');+ }+});++test('a clean checkout is ok on all four; each problem warns with its fix', async () => {+ const { bare, work } = checkout('one');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path) VALUES('notes','notes',$1)", [join(work, 'brain')]);+ let checks = await run();+ for (const name of ['checkout_lagging', 'dirty_age', 'commits_outside_source_root', 'quarantined_changes']) expect(checks[name]?.status).toBe('ok');++ // Behind: another clone pushed a commit two hours ago and this checkout fetched but never advanced.+ const other = join(dir, 'other-clone');+ git(dir, ['clone', '-q', bare, other]);+ git(other, ['config', 'user.email', '[email protected]']); git(other, ['config', 'user.name', 'Example']);+ writeFileSync(join(other, 'brain', 'remote.md'), 'remote\n');+ const old = new Date(Date.now() - 2 * HOUR).toISOString();+ git(other, ['add', '-A']); git(other, ['commit', '-q', '-m', 'remote'], { GIT_AUTHOR_DATE: old, GIT_COMMITTER_DATE: old }); git(other, ['push', '-q']);+ git(work, ['fetch', '-q']);+ checks = await run();+ expect(checks.checkout_lagging).toMatchObject({ status: 'warn', details: { checkouts: [expect.objectContaining({ behind: 1 })] } });+ expect(checks.checkout_lagging!.fix!.argv).toEqual(['gbrain', 'git', 'commit-push', '--pull', '--path', work]);+ expect(CHECKOUT_LAG_WARN_MS).toBe(HOUR);+ git(work, ['merge', '-q', '--ff-only', '@{u}']);++ // Pending write-through: the lock was held past the short wait, 40 minutes ago.+ const lock = join(work, '.git', 'brain-commit.lock');+ writeFileSync(lock, '');+ const holder = spawn('flock', ['-o', lock, 'sleep', '20'], { stdio: 'ignore' });+ try {+ await new Promise(r => setTimeout(r, 300));+ writeFileSync(join(work, 'brain', 'note.md'), 'page write\n');+ expect(() => commitPathsLocked(join(work, 'brain'), [join(work, 'brain', 'note.md')], 'gbrain: write-through note', { lockWaitMs: 100 })).toThrow();+ } finally { holder.kill('SIGKILL'); }+ const ledger = join(work, '.git', 'brain-writethrough-pending.log');+ writeFileSync(ledger, `${new Date(Date.now() - 40 * 60_000).toISOString()}\t"brain/note.md"\n`);+ checks = await run();+ expect(checks.dirty_age).toMatchObject({ status: 'warn', details: { checkouts: [expect.objectContaining({ pending_count: 1 })] } });+ expect(checks.dirty_age!.fix!.argv).toEqual(['gbrain', 'git', 'commit-push', '--pending', '--path', work]);+ git(work, ['add', 'brain/note.md']); git(work, ['commit', '-q', '-m', 'committed by hand']);+ rmSync(ledger);++ // Staged for over 30 minutes by another writer.+ writeFileSync(join(work, 'brain', 'staged.md'), 'staged\n');+ git(work, ['add', 'brain/staged.md']);+ const stale = (Date.now() - HOUR) / 1000; utimesSync(join(work, 'brain', 'staged.md'), stale, stale);+ checks = await run();+ expect(checks.dirty_age).toMatchObject({ status: 'warn', fix: { ask_user: true, actor: 'user' } });+ git(work, ['restore', '--staged', 'brain/staged.md']);++ // An unpushed commit (made around gbrain) that changes a file outside the source root.+ writeFileSync(join(work, 'other.md'), 'swept\n');+ git(work, ['commit', '-q', '-am', 'cron: swept']);+ checks = await run();+ const outside = checks.commits_outside_source_root!;+ const found = (outside.details as { checkouts: Array<{ roots: string[]; configured: boolean; commits: Array<{ paths: string[] }> }> }).checkouts;+ expect(found.map(f => ({ roots: f.roots, configured: f.configured, paths: f.commits.map(x => x.paths) }))).toEqual([{ roots: ['brain'], configured: false, paths: [['other.md']] }]);+ expect(outside).toMatchObject({ status: 'warn', fix: { ask_user: true } });+ expect(checks.commits_outside_source_root!.message).toContain('gbrain sources harden');+ git(work, ['reset', '-q', '--hard', '@{u}']);++ // A conflict the opt-in quarantine parked: the remote's version published, this machine's under a ref.+ git(other, ['pull', '-q']);+ writeFileSync(join(other, 'brain', 'remote.md'), 'remote edit\n');+ git(other, ['commit', '-q', '-am', 'remote edit']); git(other, ['push', '-q']);+ git(work, ['config', 'gbrain.quarantine', 'true']);+ writeFileSync(join(work, 'brain', 'remote.md'), 'local edit\n');+ const pushed = commitAndPush({ repo: work, paths: ['brain/remote.md'], message: 'local edit', cwd: work });+ checks = await run();+ expect(checks.quarantined_changes).toMatchObject({ status: 'warn', fix: { ask_user: true, argv: ['git', '-C', work, 'update-ref', '-d', pushed.quarantined!.ref] } });+ expect(checks.quarantined_changes!.message).toContain('brain/remote.md');+ git(work, ['update-ref', '-d', pushed.quarantined!.ref]);+ checks = await run();+ expect(checks.quarantined_changes!.status).toBe('ok');+}, 60_000);diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 12ba7a015d..0d87420e9f 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -801,6 +801,22 @@"category": "brain","name": "tracked_ownership_marker"},+ {+ "category": "brain",+ "name": "checkout_lagging"+ },+ {+ "category": "brain",+ "name": "dirty_age"+ },+ {+ "category": "brain",+ "name": "commits_outside_source_root"+ },+ {+ "category": "brain",+ "name": "quarantined_changes"+ },{"category": "ops","name": "decide_health"diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex c87076fb8f..4c51ab0e94 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6464,7 +6464,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"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\" | \"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_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\" | \"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\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"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_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"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\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"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\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"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_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"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_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"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\" | \"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\" | \"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_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"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\" | \"runtime_build_skew\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"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\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"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\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"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\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"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\" | \"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_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\" | \"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\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"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_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"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\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"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\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"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_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"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_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"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\" | \"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\" | \"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_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"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\" | \"runtime_build_skew\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"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\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"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\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"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/git-commit-push-6530.serial.test.ts b/test/git-commit-push-6530.serial.test.tsindex 0cd66632e9..9b578af9b8 100644--- a/test/git-commit-push-6530.serial.test.ts+++ b/test/git-commit-push-6530.serial.test.ts@@ -9,7 +9,7 @@ import { execFileSync, spawn } from 'child_process';import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { acquireCommitLock, commitAndPush, commitPathsLocked, pullShared, readIntegrateConflict } from '../src/core/git/commit-push.ts';+import { acquireCommitLock, commitAndPush, commitPathsLocked, pullShared, readIntegrateConflict, readPendingWriteThrough } from '../src/core/git/commit-push.ts';import { getLastPushOutcome } from '../src/core/brain-repo-durability.ts';let root: string;@@ -374,19 +374,28 @@ exec "${Bun.which('git')}" "$@"expect(existsSync(join(a, '.git', 'brain-publish.requested'))).toBe(false);}, 60_000);- test('write-through commits still land path-scoped when another writer holds the lock past the short budget', async () => {+ test('write-through never commits without the lock: a holder past the short budget leaves the file pending, and the next locked write-through commits it', async () => {const { a } = setup();const lockPath = join(a, '.git', 'brain-commit.lock');writeFileSync(lockPath, '');- const holder = spawn('flock', [lockPath, 'sleep', '20'], { stdio: 'ignore' });+ const holder = spawn('flock', ['-o', lockPath, 'sleep', '20'], { stdio: 'ignore' });+ const head = git(a, 'rev-parse', 'HEAD');try {await new Promise(r => setTimeout(r, 300));writeFileSync(join(a, 'x.md'), 'page write\n');writeFileSync(join(a, 'y.md'), 'other writer\n');- expect(commitPathsLocked(a, [join(a, 'x.md')], 'gbrain: write-through x', { lockWaitMs: 200 })).not.toBeNull();- expect(git(a, 'show', 'HEAD:x.md')).toBe('page write');- expect(status(a)).toBe(' M y.md');+ expect(() => commitPathsLocked(a, [join(a, 'x.md')], 'gbrain: write-through x', { lockWaitMs: 200 })).toThrow(expect.objectContaining({ code: 'commit_lock_busy' }));+ expect(git(a, 'rev-parse', 'HEAD')).toBe(head);+ expect(status(a)).toBe(' M x.md\n M y.md');+ expect(readPendingWriteThrough(a).map(e => e.path)).toEqual(['x.md']);} finally { holder.kill('SIGKILL'); }+ await new Promise(r => setTimeout(r, 200));+ writeFileSync(join(a, 'z.md'), 'next page write\n');+ expect(commitPathsLocked(a, [join(a, 'z.md')], 'gbrain: write-through z', { lockWaitMs: 2000 })).not.toBeNull();+ expect(git(a, 'show', '--name-only', '--format=', 'HEAD').split('\n').sort()).toEqual(['x.md', 'z.md']);+ expect(git(a, 'show', 'HEAD:x.md')).toBe('page write');+ expect(status(a)).toBe(' M y.md');+ expect(readPendingWriteThrough(a)).toEqual([]);}, 30_000);});diff --git a/test/git-writer-safety-7381.serial.test.ts b/test/git-writer-safety-7381.serial.test.tsnew file mode 100644index 0000000000..0e286e5e7d--- /dev/null+++ b/test/git-writer-safety-7381.serial.test.ts@@ -0,0 +1,358 @@+/**+ * #7381 (GBRA-180): writer safety in a brain checkout several writers share.+ * Real git against local bare remotes. Pins: integrate never re-applies a+ * change the remote already took (and maybe reverted); gbrain never commits+ * without the lock and never leaves a failed commit's paths staged; commit-push+ * never sweeps another writer's staged files or files outside the source root;+ * the opt-in guard hook refuses branch updates made around gbrain; the helper's+ * no-gbrain fallback releases the commit lock before it pushes.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import { execFileSync, spawn, spawnSync } from 'child_process';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { commitAndPush, commitPathsLocked, pullShared, readPendingWriteThrough, readQuarantine } from '../src/core/git/commit-push.ts';+import { renderCommitPushHelper } from '../src/core/brain-repo-durability.ts';++let root: string;+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');++function git(cwd: string, ...args: string[]): string {+ return execFileSync('git', ['-C', cwd, '-c', 'protocol.file.allow=always', ...args], {+ stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', env: process.env,+ }).trim();+}++function clone(bare: string, name: string): string {+ const dir = join(root, name);+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', bare, dir], { stdio: 'ignore', env: process.env });+ git(dir, 'config', 'user.email', `${name}@example.com`);+ git(dir, 'config', 'user.name', name);+ return dir;+}++/** A bare remote plus two clones on `main`, seeded with a 20-line page and two other files. */+function setup(): { bare: string; a: string; b: string } {+ const bare = join(root, 'remote.git');+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', bare], { stdio: 'ignore', env: process.env });+ const a = clone(bare, 'a');+ writeFileSync(join(a, 'page.md'), Array.from({ length: 20 }, (_, i) => `line ${i + 1}`).join('\n') + '\n');+ for (const f of ['x.md', 'y.md']) writeFileSync(join(a, f), `${f} v1\n`);+ git(a, 'add', '.'); git(a, 'commit', '-qm', 'seed'); git(a, 'push', '-q', '-u', 'origin', 'main');+ const b = clone(bare, 'b');+ return { bare, a, b };+}++const read = (dir: string, f: string) => readFileSync(join(dir, f), 'utf8');+const line3 = (text: string) => text.split('\n')[2];+const status = (dir: string) => execFileSync('git', ['-C', dir, 'status', '--porcelain'], { encoding: 'utf-8', env: process.env }).replace(/\n$/, '');+const editLine3 = (dir: string, to: string) => writeFileSync(join(dir, 'page.md'), read(dir, 'page.md').replace(/^line 3( .*)?$/m, `line 3 ${to}`));++/** Local commit X on a; b carries X' (the same patch under another commit id) to the remote, then runs `after`. */+function copyUpstream(after: (b: string) => void): { bare: string; a: string; b: string; x: string } {+ const { bare, a, b } = setup();+ editLine3(a, 'LOCAL');+ git(a, 'commit', '-qam', 'X: local edit');+ const x = git(a, 'rev-parse', 'HEAD');+ git(b, 'fetch', '-q', a, 'main');+ git(b, 'cherry-pick', '-x', x);+ after(b);+ git(b, 'push', '-q', 'origin', 'main');+ return { bare, a, b, x };+}++function cli(cwd: string, args: string[], env: Record<string, string> = {}) {+ return spawnSync(process.execPath, [CLI, ...args], { cwd, encoding: 'utf8', env: { ...process.env, ...env } });+}++beforeAll(() => { process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT = '1'; });+afterAll(() => { delete process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT; });+beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'cp7381-')); });+afterEach(() => { delete process.env.GBRAIN_GIT_NO_MERGE_TREE; rmSync(root, { recursive: true, force: true }); });++describe('integrate leaves out local commits the remote already has', () => {+ for (const fallback of [false, true]) {+ test(`a change the remote took and then reverted stays reverted${fallback ? ' (git < 2.38 fallback)' : ''}`, () => {+ if (fallback) process.env.GBRAIN_GIT_NO_MERGE_TREE = '1';+ const { bare, a, x } = copyUpstream(b => git(b, 'revert', '--no-edit', 'HEAD'));+ expect(line3(git(bare, 'show', 'main:page.md') + '\n')).toBe('line 3');+ const r = commitAndPush({ repo: a, pushOnly: true, cwd: a });+ expect(r.outcome).toBe('pushed');+ expect(line3(git(bare, 'show', 'main:page.md') + '\n')).toBe('line 3');+ expect(line3(read(a, 'page.md'))).toBe('line 3');+ expect(git(bare, 'log', '-1', '--format=%B', 'main')).toContain(`whose patch origin/main already has: ${x.slice(0, 12)}`);+ expect(git(a, 'merge-base', '--is-ancestor', x, 'main')).toBe('');+ });+ }++ test('the pull path leaves it out too', () => {+ const { bare, a } = copyUpstream(b => git(b, 'revert', '--no-edit', 'HEAD'));+ expect(pullShared(a)).toMatchObject({ status: 'advanced', merged: true });+ expect(line3(read(a, 'page.md'))).toBe('line 3');+ expect(commitAndPush({ repo: a, pushOnly: true, cwd: a }).outcome).toBe('pushed');+ expect(line3(git(bare, 'show', 'main:page.md') + '\n')).toBe('line 3');+ });++ test('a newer remote edit of the copied line publishes without a conflict and keeps the remote\'s line', () => {+ const { bare, a } = copyUpstream(b => { editLine3(b, 'NEWER'); git(b, 'commit', '-qam', 'Y: newer edit'); });+ writeFileSync(join(a, 'x.md'), 'unique local work\n');+ const r = commitAndPush({ repo: a, paths: ['x.md'], message: 'L: unique', cwd: a });+ expect(r).toMatchObject({ outcome: 'pushed', checkout: 'advanced' });+ expect(line3(git(bare, 'show', 'main:page.md') + '\n')).toBe('line 3 NEWER');+ expect(git(bare, 'show', 'main:x.md')).toBe('unique local work');+ expect(line3(read(a, 'page.md'))).toBe('line 3 NEWER');+ });++ test('a rebased copy (another parent, the same patch) publishes cleanly', () => {+ const { bare, a } = setup();+ editLine3(a, 'LOCAL');+ git(a, 'commit', '-qam', 'X');+ const { b } = { b: join(root, 'b') };+ writeFileSync(join(b, 'y.md'), 'remote first\n');+ git(b, 'commit', '-qam', 'R');+ git(b, 'fetch', '-q', a, 'main');+ git(b, 'cherry-pick', git(a, 'rev-parse', 'HEAD'));+ git(b, 'push', '-q', 'origin', 'main');+ expect(commitAndPush({ repo: a, pushOnly: true, cwd: a }).outcome).toBe('pushed');+ expect(line3(git(bare, 'show', 'main:page.md') + '\n')).toBe('line 3 LOCAL');+ expect(git(bare, 'show', 'main:y.md')).toBe('remote first');+ });++ test('a unique local change to the same line as a remote edit still conflicts (nothing is skipped that the remote lacks)', () => {+ const { a } = copyUpstream(b => { writeFileSync(join(b, 'x.md'), 'remote x\n'); git(b, 'commit', '-qam', 'remote x'); });+ writeFileSync(join(a, 'x.md'), 'local x\n');+ expect(() => commitAndPush({ repo: a, paths: ['x.md'], message: 'local x', cwd: a })).toThrow(expect.objectContaining({ code: 'integrate_conflict' }));+ expect(read(a, 'x.md')).toBe('local x\n');+ });+});++describe('opt-in quarantine', () => {+ /** a and b both change x.md; a also changes y.md, which the remote left alone. */+ function bothChanged() {+ const { bare, a, b } = setup();+ writeFileSync(join(b, 'x.md'), 'remote x\n'); git(b, 'commit', '-qam', 'remote x'); git(b, 'push', '-q', 'origin', 'main');+ writeFileSync(join(a, 'x.md'), 'local x\n');+ writeFileSync(join(a, 'y.md'), 'local y\n');+ return { bare, a };+ }++ test('is off by default: the conflict stops the push and nothing is parked', () => {+ const { bare, a } = bothChanged();+ expect(() => commitAndPush({ repo: a, paths: ['x.md', 'y.md'], message: 'local', cwd: a })).toThrow(expect.objectContaining({ code: 'integrate_conflict' }));+ expect(git(bare, 'show', 'main:y.md')).toBe('y.md v1');+ expect(git(a, 'for-each-ref', 'refs/gbrain/quarantine/')).toBe('');+ expect(readQuarantine(a)).toEqual([]);+ });++ test('when enabled, publishes the rest, parks this machine\'s version under a ref, and never drops it', () => {+ const { bare, a } = bothChanged();+ git(a, 'config', 'gbrain.quarantine', 'true');+ const r = commitAndPush({ repo: a, paths: ['x.md', 'y.md'], message: 'local', cwd: a });+ expect(r.outcome).toBe('pushed');+ expect(r.quarantined?.paths).toEqual(['x.md']);+ expect(git(bare, 'show', 'main:x.md')).toBe('remote x');+ expect(git(bare, 'show', 'main:y.md')).toBe('local y');+ const ref = r.quarantined!.ref;+ expect(ref.startsWith('refs/gbrain/quarantine/')).toBe(true);+ expect(git(a, 'show', `${ref}:x.md`)).toBe('local x');+ expect(git(bare, 'cat-file', '-t', r.quarantined!.local)).toBe('commit');+ expect(git(bare, 'log', '-1', '--format=%B', 'main')).toContain(`under ${ref}: x.md`);+ expect(readQuarantine(a).map(e => e.ref)).toEqual([ref]);+ git(a, 'update-ref', '-d', ref);+ expect(readQuarantine(a)).toEqual([]);+ });++ test('a file/directory conflict is never quarantined', () => {+ const { bare, a, b } = setup();+ rmSync(join(b, 'x.md')); mkdirSync(join(b, 'x.md')); writeFileSync(join(b, 'x.md', 'inner.md'), 'dir\n');+ git(b, 'add', '-A'); git(b, 'commit', '-qm', 'x as dir'); git(b, 'push', '-q', 'origin', 'main');+ git(a, 'config', 'gbrain.quarantine', 'true');+ writeFileSync(join(a, 'x.md'), 'local x\n');+ expect(() => commitAndPush({ repo: a, paths: ['x.md'], message: 'local', cwd: a })).toThrow(expect.objectContaining({ code: 'integrate_conflict' }));+ expect(readQuarantine(a)).toEqual([]);+ expect(git(bare, 'cat-file', '-t', 'main:x.md')).toBe('tree');+ });+});++describe('a commit that does not land leaves nothing staged', () => {+ function refuseCommits(dir: string): void {+ writeFileSync(join(dir, '.git', 'hooks', 'pre-commit'), '#!/bin/sh\nexit 1\n');+ chmodSync(join(dir, '.git', 'hooks', 'pre-commit'), 0o755);+ }++ test('commit-push: a refused commit unstages its paths, so a later commit without paths cannot sweep them', () => {+ const { bare, a } = setup();+ refuseCommits(a);+ writeFileSync(join(a, 'x.md'), 'mine, not committed\n');+ mkdirSync(join(a, 'new'), { recursive: true });+ writeFileSync(join(a, 'new', 'page.md'), 'brand new\n');+ expect(() => commitAndPush({ repo: a, paths: ['x.md', 'new'], message: 'm', cwd: a })).toThrow(expect.objectContaining({ code: 'git_unavailable' }));+ expect(status(a)).toBe(' M x.md\n?? new/');+ rmSync(join(a, '.git', 'hooks', 'pre-commit'));+ writeFileSync(join(a, 'y.md'), 'cron\n');+ git(a, 'add', 'y.md');+ git(a, 'commit', '-q', '--no-verify', '-m', 'cron: no pathspec');+ expect(git(a, 'show', '--name-only', '--format=', 'HEAD')).toBe('y.md');+ expect(git(bare, 'show', 'main:x.md')).toBe('x.md v1');+ });++ test('write-through: a refused commit unstages the page and keeps it in the pending ledger', () => {+ const { a } = setup();+ refuseCommits(a);+ writeFileSync(join(a, 'x.md'), 'page write\n');+ expect(() => commitPathsLocked(a, [join(a, 'x.md')], 'gbrain: write-through x', { lockWaitMs: 1000 })).toThrow(expect.objectContaining({ code: 'git_unavailable' }));+ expect(status(a)).toBe(' M x.md');+ expect(readPendingWriteThrough(a).map(e => e.path)).toEqual(['x.md']);+ });++ test('a file staged before the refused commit keeps that staged version, not the newer bytes', () => {+ const { a } = setup();+ writeFileSync(join(a, 'x.md'), 'staged earlier by the caller\n');+ git(a, 'add', 'x.md');+ writeFileSync(join(a, 'x.md'), 'newer bytes\n');+ const staged = git(a, 'ls-files', '-s', 'x.md');+ refuseCommits(a);+ expect(() => commitAndPush({ repo: a, paths: ['x.md'], message: 'm', cwd: a })).toThrow(expect.objectContaining({ code: 'git_unavailable' }));+ expect(git(a, 'ls-files', '-s', 'x.md')).toBe(staged);+ expect(read(a, 'x.md')).toBe('newer bytes\n');+ });+});++describe('commit scope: staged files and source roots', () => {+ test('refuses to sweep files another writer staged under a named directory; naming the file claims it', () => {+ const { bare, a } = setup();+ mkdirSync(join(a, 'daily'), { recursive: true });+ writeFileSync(join(a, 'daily', 'mine.md'), 'mine\n');+ writeFileSync(join(a, 'daily', 'theirs.md'), 'staged by another writer\n');+ git(a, 'add', 'daily/theirs.md');+ let error: { code?: string; detail?: string } = {};+ try { commitAndPush({ repo: a, paths: ['daily'], message: 'daily', cwd: a }); } catch (e) { error = e as typeof error; }+ expect(error.code).toBe('commit_prestaged_paths');+ expect(JSON.parse(error.detail!).paths).toEqual(['daily/theirs.md']);+ expect(status(a)).toBe('A daily/theirs.md\n?? daily/mine.md');+ expect(commitAndPush({ repo: a, paths: ['daily/mine.md'], message: 'mine', cwd: a }).outcome).toBe('pushed');+ expect(git(bare, 'ls-tree', '--name-only', '-r', 'main', 'daily')).toBe('daily/mine.md');+ expect(status(a)).toBe('A daily/theirs.md');+ });++ test('with gbrain.sourceRoot set, commits and publishes that change files outside it are refused until the user agrees', () => {+ const { bare, a } = setup();+ mkdirSync(join(a, 'brain'), { recursive: true });+ git(a, 'config', '--add', 'gbrain.sourceRoot', 'brain');+ writeFileSync(join(a, 'x.md'), 'outside the brain\n');+ expect(() => commitAndPush({ repo: a, paths: ['x.md'], message: 'm', cwd: a })).toThrow(expect.objectContaining({ code: 'commit_outside_source_root' }));+ expect(status(a)).toBe(' M x.md');+ // A cron commits the outside file around gbrain; the next publish of a brain page refuses to carry it.+ git(a, 'commit', '-q', '-am', 'cron: swept');+ const before = git(bare, 'rev-parse', 'main');+ writeFileSync(join(a, 'brain', 'page.md'), 'brain page\n');+ let error: { code?: string; detail?: string } = {};+ try { commitAndPush({ repo: a, paths: ['brain/page.md'], message: 'page', cwd: a }); } catch (e) { error = e as typeof error; }+ expect(error.code).toBe('commit_outside_source_root');+ expect(JSON.parse(error.detail!).commits[0].paths).toEqual(['x.md']);+ expect(git(bare, 'rev-parse', 'main')).toBe(before);+ expect(git(a, 'show', 'HEAD:brain/page.md')).toBe('brain page');+ expect(commitAndPush({ repo: a, pushOnly: true, cwd: a, allowOutsideSourceRoot: true }).outcome).toBe('pushed');+ expect(git(bare, 'show', 'main:x.md')).toBe('outside the brain');+ });++ test('write-through stays inside its source root even when the source sits below the toplevel', () => {+ const { a } = setup();+ mkdirSync(join(a, 'brain'), { recursive: true });+ writeFileSync(join(a, 'brain', 'p.md'), 'page\n');+ writeFileSync(join(a, 'x.md'), 'outside\n');+ expect(() => commitPathsLocked(join(a, 'brain'), [join(a, 'x.md')], 'gbrain: write-through x', { lockWaitMs: 1000 })).toThrow(expect.objectContaining({ code: 'commit_outside_source_root' }));+ expect(commitPathsLocked(join(a, 'brain'), [join(a, 'brain', 'p.md')], 'gbrain: write-through p', { lockWaitMs: 1000 })).not.toBeNull();+ expect(status(a)).toBe(' M x.md');+ });++ test('--pending commits and pushes the files write-through could not commit', async () => {+ const { bare, a } = setup();+ const lockPath = join(a, '.git', 'brain-commit.lock');+ writeFileSync(lockPath, '');+ const holder = spawn('flock', ['-o', lockPath, 'sleep', '20'], { stdio: 'ignore' });+ try {+ await new Promise(r => setTimeout(r, 300));+ writeFileSync(join(a, 'x.md'), 'page write\n');+ expect(() => commitPathsLocked(a, [join(a, 'x.md')], 'gbrain: write-through x', { lockWaitMs: 100 })).toThrow(expect.objectContaining({ code: 'commit_lock_busy' }));+ } finally { holder.kill('SIGKILL'); }+ await new Promise(r => setTimeout(r, 200));+ writeFileSync(join(a, 'y.md'), 'another writer, not pending\n');+ const r = cli(a, ['git', 'commit-push', '--pending', '--json']);+ expect(r.status).toBe(0);+ expect(JSON.parse(r.stdout)).toMatchObject({ outcome: 'pushed', paths: ['x.md'] });+ expect(git(bare, 'show', 'main:x.md')).toBe('page write');+ expect(status(a)).toBe(' M y.md');+ expect(readPendingWriteThrough(a)).toEqual([]);+ }, 30_000);+});++describe('opt-in commit guard', () => {+ test('refuses commits made around gbrain (--no-verify and -a included); gbrain\'s own commits, pulls and the bypass pass', () => {+ const { bare, a, b } = setup();+ expect(cli(a, ['git', 'guard', '--json']).stdout).toContain('"installed":false');+ const install = cli(a, ['git', 'guard', '--install', '--json']);+ expect(install.status).toBe(0);+ expect(JSON.parse(install.stdout)).toMatchObject({ installed: true, changed: true });+ writeFileSync(join(a, 'x.md'), 'cron edit\n');+ git(a, 'add', 'x.md');+ const plain = spawnSync('git', ['-C', a, 'commit', '-q', '--no-verify', '-m', 'cron'], { encoding: 'utf8', env: process.env });+ expect(plain.status).not.toBe(0);+ expect(plain.stderr).toContain('gbrain commit guard: refused');+ git(a, 'restore', '--staged', 'x.md');+ expect(cli(a, ['git', 'commit-push', '-m', 'via gbrain', '--', 'x.md']).status).toBe(0);+ expect(git(bare, 'show', 'main:x.md')).toBe('cron edit');+ writeFileSync(join(a, 'y.md'), 'page write\n');+ expect(commitPathsLocked(a, [join(a, 'y.md')], 'gbrain: write-through y', { lockWaitMs: 1000 })).not.toBeNull();+ writeFileSync(join(a, 'x.md'), 'swept by -a\n');+ const all = spawnSync('git', ['-C', a, 'commit', '-q', '-a', '-m', 'sweep'], { encoding: 'utf8', env: process.env });+ expect(all.status).not.toBe(0);+ expect(status(a)).toBe(' M x.md');+ git(a, 'checkout', '--', 'x.md');+ git(b, 'pull', '-q', '--no-rebase');+ writeFileSync(join(b, 'page.md'), 'remote\n');+ git(b, 'commit', '-qam', 'remote'); git(b, 'push', '-q', 'origin', 'main');+ expect(pullShared(a).status).toBe('advanced');+ expect(read(a, 'page.md')).toBe('remote\n');+ writeFileSync(join(a, 'x.md'), 'a person, deliberately\n');+ execFileSync('git', ['-C', a, 'commit', '-qam', 'by hand'], { env: { ...process.env, GBRAIN_COMMIT_GUARD: 'off' } });+ expect(JSON.parse(cli(a, ['git', 'guard', '--uninstall', '--json']).stdout)).toMatchObject({ installed: false, changed: true });+ writeFileSync(join(a, 'x.md'), 'after uninstall\n');+ git(a, 'commit', '-qam', 'plain again');+ }, 60_000);++ test('refuses to replace another tool\'s prepare-commit-msg hook', () => {+ const { a } = setup();+ writeFileSync(join(a, '.git', 'hooks', 'prepare-commit-msg'), '#!/bin/sh\nexit 0\n');+ const r = cli(a, ['git', 'guard', '--install']);+ expect(r.status).not.toBe(0);+ expect(read(a, '.git/hooks/prepare-commit-msg')).toBe('#!/bin/sh\nexit 0\n');+ });+});++describe('the helper\'s no-gbrain fallback', () => {+ test('marks its children with the real lock path and releases the commit lock before it pushes', async () => {+ const { bare, a } = setup();+ mkdirSync(join(a, 'scripts'), { recursive: true });+ writeFileSync(join(a, 'scripts', 'brain-commit-push.sh'), renderCommitPushHelper(), { mode: 0o755 });+ const lockPath = git(a, 'rev-parse', '--path-format=absolute', '--git-path', 'brain-commit.lock');+ writeFileSync(join(a, '.git', 'hooks', 'pre-commit'), `#!/bin/sh\nprintf '%s' "$BRAIN_COMMIT_LOCK_HELD" > ${JSON.stringify(join(root, 'marker'))}\n`);+ chmodSync(join(a, '.git', 'hooks', 'pre-commit'), 0o755);+ writeFileSync(join(bare, 'hooks', 'pre-receive'), `#!/bin/sh\n: > ${JSON.stringify(join(root, 'pushing'))}\nsleep 3\n`, { mode: 0o755 });+ writeFileSync(join(a, 'x.md'), 'via the fallback\n');+ const helper = spawn('bash', [join(a, 'scripts', 'brain-commit-push.sh'), 'fallback', 'x.md'], {+ cwd: a, stdio: 'ignore', env: { ...process.env, PATH: '/usr/bin:/bin', GIT_CONFIG_PARAMETERS: "'protocol.file.allow=always'" } });+ const exited = new Promise<number | null>(r => helper.on('exit', code => r(code)));+ let freeDuringPush = false;+ for (let i = 0; i < 100 && !freeDuringPush; i++) {+ await new Promise(r => setTimeout(r, 50));+ try { readFileSync(join(root, 'pushing')); } catch { continue; }+ freeDuringPush = spawnSync('flock', ['-n', lockPath, 'true']).status === 0;+ }+ expect(await exited).toBe(0);+ expect(freeDuringPush).toBe(true);+ expect(read(root, 'marker')).toBe(lockPath);+ expect(git(bare, 'show', 'main:x.md')).toBe('via the fallback');+ }, 30_000);+});