Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(git): shared-checkout-safe commit, push and pull for brain repos (#6530)

garrytan64cbd70d0cb0
diff --git a/AGENTS.md b/AGENTS.md
index de3cb2cf65..947fca0314 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -55,6 +55,35 @@ providers can receive text; Markdown export is not a full database backup.
Read [memory boundaries](docs/guides/memory-boundaries.md) before promising
portability, graph freshness, privacy, or recovery.
+<!-- BEGIN multi-agent-rules (identical in AGENTS.md, BOOTSTRAP_FOR_AGENTS.md and INSTALL_FOR_AGENTS.md; bun run check:shared-tree-git) -->
+## Multi-agent rules for a shared brain checkout
+
+Several agents, crons and hooks often commit to one brain checkout on the same
+machine. In such a checkout:
+
+1. **Commit and push with one command, naming your files:**
+ `scripts/brain-commit-push.sh "<msg>" <paths>`, or
+ `gbrain git commit-push -m "<msg>" -- <paths>` when the brain has no helper.
+ It takes the checkout's writer lock, commits only those paths, merges remote
+ commits without touching anyone else's files, and fails loudly if the push
+ does not land.
+2. **Bring remote commits in with `--pull`** (`scripts/brain-commit-push.sh --pull`
+ or `gbrain git commit-push --pull`) at session start and before a batch of writes.
+3. **On a non-zero exit, read the code.** Retry once on `commit_lock_busy`.
+ Stop and relay to the user on `integrate_conflict` (they choose which
+ version wins) and on `writer_coordinator_required` (a managed brain: save
+ pages with `put_page` instead). `pushed_checkout_lagging` is a success.
+<!-- gbrain-allow-shared-tree-git-begin: the forbidden commands, named so agents avoid them -->
+4. **Never run** `git pull --rebase`, `git stash`, `--autostash`, `git add -A`,
+ `git commit -a`, `git reset --hard` or `git push --force` there, and never
+ fall back to them when the command fails. Never delete `.git/rebase-merge`
+ before saving its autostash with `git stash store`.
+<!-- gbrain-allow-shared-tree-git-end -->
+
+Outcomes, conflict recovery, a stuck rebase and the lock contract for host
+daemons: [docs/guides/shared-checkout-git.md](docs/guides/shared-checkout-git.md).
+<!-- END multi-agent-rules -->
+
## Agent operator protocol
Every gbrain error, refusal, degraded result and recommendation carries the same
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index abe725dc74..b9b15c4d21 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -190,6 +190,35 @@ registration only with `--mcp-even-if-plugin`.
block below it — the ownership line and the cold-start offer are the two
things the human must actually understand, not fine print.
+<!-- BEGIN multi-agent-rules (identical in AGENTS.md, BOOTSTRAP_FOR_AGENTS.md and INSTALL_FOR_AGENTS.md; bun run check:shared-tree-git) -->
+## Multi-agent rules for a shared brain checkout
+
+Several agents, crons and hooks often commit to one brain checkout on the same
+machine. In such a checkout:
+
+1. **Commit and push with one command, naming your files:**
+ `scripts/brain-commit-push.sh "<msg>" <paths>`, or
+ `gbrain git commit-push -m "<msg>" -- <paths>` when the brain has no helper.
+ It takes the checkout's writer lock, commits only those paths, merges remote
+ commits without touching anyone else's files, and fails loudly if the push
+ does not land.
+2. **Bring remote commits in with `--pull`** (`scripts/brain-commit-push.sh --pull`
+ or `gbrain git commit-push --pull`) at session start and before a batch of writes.
+3. **On a non-zero exit, read the code.** Retry once on `commit_lock_busy`.
+ Stop and relay to the user on `integrate_conflict` (they choose which
+ version wins) and on `writer_coordinator_required` (a managed brain: save
+ pages with `put_page` instead). `pushed_checkout_lagging` is a success.
+<!-- gbrain-allow-shared-tree-git-begin: the forbidden commands, named so agents avoid them -->
+4. **Never run** `git pull --rebase`, `git stash`, `--autostash`, `git add -A`,
+ `git commit -a`, `git reset --hard` or `git push --force` there, and never
+ fall back to them when the command fails. Never delete `.git/rebase-merge`
+ before saving its autostash with `git stash store`.
+<!-- gbrain-allow-shared-tree-git-end -->
+
+Outcomes, conflict recovery, a stuck rebase and the lock contract for host
+daemons: [docs/guides/shared-checkout-git.md](docs/guides/shared-checkout-git.md).
+<!-- END multi-agent-rules -->
+
## Machine two
If this workspace was cloned from an existing agent repo (agent.json says
@@ -213,7 +242,7 @@ placeholder). Trust the CLI's detection over your own guesses.
only repos attached to the session** — a repo created mid-session is NOT
attached, so `gbrain bootstrap repo` refuses fast in cloud with the flow
that works. Privacy verification falls back to pure git protocol on its own.
-- **`git push` works only against the session's working branch.** A user PAT
+- **`git push` works only against the session's working branch.** A user PAT <!-- gbrain-allow-shared-tree-git: describes the cloud sandbox's push limit, not a command to run -->
does not bypass any of this.
- **Only repo-committed files carry into the next session.** `~/.gbrain`,
`~/.claude`, and the gitignored `.claude/settings.local.json` evaporate.
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 43a2bd1d11..3b9800f1bd 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -563,6 +563,35 @@ gbrain onboard --check --json
See "The onboard surface" below for what the recommendations mean and the
consent gates around unattended remediation.
+<!-- BEGIN multi-agent-rules (identical in AGENTS.md, BOOTSTRAP_FOR_AGENTS.md and INSTALL_FOR_AGENTS.md; bun run check:shared-tree-git) -->
+## Multi-agent rules for a shared brain checkout
+
+Several agents, crons and hooks often commit to one brain checkout on the same
+machine. In such a checkout:
+
+1. **Commit and push with one command, naming your files:**
+ `scripts/brain-commit-push.sh "<msg>" <paths>`, or
+ `gbrain git commit-push -m "<msg>" -- <paths>` when the brain has no helper.
+ It takes the checkout's writer lock, commits only those paths, merges remote
+ commits without touching anyone else's files, and fails loudly if the push
+ does not land.
+2. **Bring remote commits in with `--pull`** (`scripts/brain-commit-push.sh --pull`
+ or `gbrain git commit-push --pull`) at session start and before a batch of writes.
+3. **On a non-zero exit, read the code.** Retry once on `commit_lock_busy`.
+ Stop and relay to the user on `integrate_conflict` (they choose which
+ version wins) and on `writer_coordinator_required` (a managed brain: save
+ pages with `put_page` instead). `pushed_checkout_lagging` is a success.
+<!-- gbrain-allow-shared-tree-git-begin: the forbidden commands, named so agents avoid them -->
+4. **Never run** `git pull --rebase`, `git stash`, `--autostash`, `git add -A`,
+ `git commit -a`, `git reset --hard` or `git push --force` there, and never
+ fall back to them when the command fails. Never delete `.git/rebase-merge`
+ before saving its autostash with `git stash store`.
+<!-- gbrain-allow-shared-tree-git-end -->
+
+Outcomes, conflict recovery, a stuck rebase and the lock contract for host
+daemons: [docs/guides/shared-checkout-git.md](docs/guides/shared-checkout-git.md).
+<!-- END multi-agent-rules -->
+
## Upgrade
When an upgrade crosses v0.60.5.0, confirm a database backup exists before
diff --git a/docs/GBRAIN_RECOMMENDED_SCHEMA.md b/docs/GBRAIN_RECOMMENDED_SCHEMA.md
index 6a379cef2f..81d73ab57c 100644
--- a/docs/GBRAIN_RECOMMENDED_SCHEMA.md
+++ b/docs/GBRAIN_RECOMMENDED_SCHEMA.md
@@ -720,8 +720,12 @@ For **"Alex from Meridian Labs"** (mentioned in the meeting but not an attendee)
**Step 8: Commit and notify.**
```bash
-cd /data/brain && git add -A && git commit -m "meetings: 2026-04-07 product review, investor sync" && git push
+cd /data/brain && scripts/brain-commit-push.sh "meetings: 2026-04-07 product review, investor sync" \
+ meetings/ people/alex-rivera.md people/.raw/alex-rivera.json companies/meridian-labs.md ops/tasks.md
```
+The helper commits only the files this run touched and pushes; on a non-zero
+exit the agent stops and reports the error code instead of posting the
+summary ([outcomes](guides/shared-checkout-git.md#outcomes)).
Posts summary to the Meetings notification channel: "Processed 2 meetings. Created 1 new person page (Alex Rivera). Updated 4 entity pages. 5 action items extracted."
**Files touched in this run:**
@@ -913,9 +917,9 @@ Once you have cron jobs, ingest jobs, and sub-agents all touching the brain repo
Practical mitigations:
- **Treat index.md as derived, not hand-maintained.** Instead of updating it in every ingest workflow, rebuild it periodically (daily or on-demand) by scanning the directory tree. This eliminates it as a write hotspot.
-- **Make log.md append-safe.** Each entry is a self-contained line with a timestamp prefix. Concurrent appends to the end of the file rarely conflict. If they do, both sides are correct — just keep both lines.
+- **Make log.md append-safe.** Each entry is a self-contained line with a timestamp prefix. Two machines that append to the end of the file at the same time do conflict; both sides are correct, so keep both lines (resolve with a merged copy: [conflicts](guides/shared-checkout-git.md#conflicts)).
- **Commit in batches, not per-page.** When an ingest job updates 10 entity pages, commit once at the end, not 10 times. This reduces conflict surface.
-- **Pull before push.** Every workflow should `git pull --rebase` before pushing. With append-only log and independent entity pages, rebases almost always auto-resolve.
+- **Commit and push through the shared-checkout helper.** Every workflow commits with `scripts/brain-commit-push.sh "<msg>" <paths>` (or `gbrain git commit-push`), and pulls with its `--pull` mode. It takes one writer lock per checkout, commits only the named paths and merges remote commits in memory, so it never stashes or rebases files other workflows are writing. With an append-only log and independent entity pages, those merges almost always succeed ([shared-checkout git](guides/shared-checkout-git.md)).
- **Entity pages rarely conflict.** Two workflows updating `people/jane-doe.md` at the same time is rare because they're triggered by different signals about different people. The real conflict hotspots are the shared files (index.md, log.md), which is why those should be append-only or derived.
## Maintenance (Lint)
diff --git a/docs/GBRAIN_VERIFY.md b/docs/GBRAIN_VERIFY.md
index 82b8970f81..7f29e7a25b 100644
--- a/docs/GBRAIN_VERIFY.md
+++ b/docs/GBRAIN_VERIFY.md
@@ -184,10 +184,14 @@ This is the real test. Edit a brain page, push, wait, search.
```bash
# Example: fix a line in alice-example's page
cd /data/brain
-# Make a small edit to any .md file
-git add -A && git commit -m "test: verify live sync" && git push
+# Make a small edit to one .md file, then commit and push only that file
+gbrain git commit-push -m "test: verify live sync" -- people/alice-example.md
```
+It must exit 0 and print `pushed <sha> to origin/<branch>`. On any other
+result, stop the test and follow [outcomes](guides/shared-checkout-git.md#outcomes)
+(retry once on `commit_lock_busy`; ask the user on `integrate_conflict`).
+
2. Wait for the next sync cycle (cron interval or `--watch` poll).
3. Search for the corrected text:
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 6046db371c..09f6439813 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -1041,6 +1041,30 @@ retire another phrase, add a row to `RETIRED`. Fixtures:
scanned location); every pattern and the exemptions are driven in
`test/scripts/check-retired-phrases.test.ts`.
+#### Shared-tree git guard
+
+`scripts/check-shared-tree-git.sh` (`bun run check:shared-tree-git`, in
+`bun run verify`, under a second) keeps agent-facing text from teaching git
+commands that are unsafe in a brain checkout several agents share (#6530).
+It scans `skills/`, `recipes/`, `templates/`, `docs/`, `plugin/`,
+`plugin-variants/` (`*.md`, `*.template`, `*.sh`) and `AGENTS.md`,
+`BOOTSTRAP_FOR_AGENTS.md` and `INSTALL_FOR_AGENTS.md`; in markdown only fenced
+code and inline code spans count. It flags `git pull --rebase`,
+`--autostash`, `git stash` (except `store`, `list`, `show`), `git add -A`,
+`--all` or `.` without `--`, `git commit -a`, `git reset --hard`, force pushes
+and any other `git push` except `--dry-run`. A line that must name one carries
+`# gbrain-allow-shared-tree-git: <reason>` on the same line, an
+`<!-- gbrain-allow-shared-tree-git: <reason> -->` line before it, or sits in a
+`-begin: <reason>` / `-end` region; a marker without a reason fails. Not
+scanned: the generated `docs/guides/error-codes.md`, the contributor docs
+about the gbrain source repo (`docs/RELEASING.md`, `docs/TESTING.md`,
+`docs/contributing/`) and historical records. It also requires the Multi-agent
+rules block to be identical in the three agent docs. The safe replacement and
+the full rules: [shared-checkout git](guides/shared-checkout-git.md).
+Fixtures: `test/fixtures/guards/check-shared-tree-git.sh/`; every form, the
+markers and the exemptions are driven in
+`test/scripts/check-shared-tree-git.test.ts`.
+
#### Bash 3.2 parse guard
macOS ships GNU bash 3.2.57 as `/bin/bash`, and its parser rejects shapes
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.md
index 6fc57404ff..738e9c8f3e 100644
--- a/docs/architecture/key-files/agent-bootstrap.md
+++ b/docs/architecture/key-files/agent-bootstrap.md
@@ -7,7 +7,7 @@ Normative docs: `docs/designs/AGENT_BOOTSTRAP_DESIGN.md` (scope) +
User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetches:
`BOOTSTRAP_FOR_AGENTS.md` (root; carries a version stamp CI pins to VERSION).
-- `src/commands/bootstrap.ts` — the `gbrain bootstrap {status,interview,render,repo,hooks,verify,uninstall,attach,cloud-setup-script}` dispatcher (plus the machine-level `harness` subcommand — see the `core/bootstrap/harness.ts` entry below). Engine-free everywhere except `verify` (which opens/closes its own engine — safe because verify runs with no live serve, before host registration). `cloud-setup-script` is a pure printer (prints `templates/bootstrap/cloud-setup-script.sh` for the cloud environment's setup step) and is dispatched entirely BEFORE workspace resolution, so it works from any cwd, including $HOME. Every other subcommand resolves `--workspace` (default: cwd) through `resolveWorkspace`, which refuses with `BootstrapError('HOME_WORKSPACE')` when the resolved path (realpath-compared, so a symlinked $HOME or cwd still matches) IS `process.env.HOME` (falling back to `os.homedir()` only when HOME is unset) — an unqualified run from a freshly-SSH'd shell must not silently stage a home-directory-scale `git add -A` over `~/.ssh/` and friends; the refusal is still appended to `<home>/bootstrap/install.jsonl` (keyed by the rejected candidate path) before returning. `status`, `uninstall`, and `harness` are exempt from this guard (`HOME_WORKSPACE_GUARD_EXEMPT`): `status` only reads and prints a report, `uninstall` removes exactly `receipt.created_paths` (each containment-checked) — never a `git add`/commit/push, never a workspace-wide scan — and `harness` operates only on `home` and never even receives a `ws` argument (`runHarness`, machine-level wiring), so the value `resolveWorkspace` returns for it is used only for `LogCtx.ws` bookkeeping. Exempting `status`/`uninstall` keeps the recovery path reachable for the guard's own victims: someone who bootstrapped into `$HOME` needs `status` to see what's there and `uninstall` to remove it, both run with `--workspace` pointing AT $HOME; the refusal message for the still-guarded subcommands names that recovery path. Known gap: a process already launched with HOME pointed away from the real account home is not caught (Bun's `os.homedir()` mirrors process-start HOME rather than doing an independent uid lookup, so it collapses to the same wrong value). Mutating subcommands run under the workspace bootstrap lock; render is gated on interview `complete && confirmed` and hard-refuses when the workspace origin is a PUBLIC remote (identity files must never land in a public repo — the same template-door gate `status` enforces; unverifiable visibility warns and proceeds, treating the origin as public); the provider key routes to the 0600 config sink and never touches interview state; every MUTATING subcommand appends a line to `<home>/bootstrap/install.jsonl` (the read-only `status` and `cloud-setup-script` do not log). `hooks` on Claude Code writes the committed carrier in a cloud sandbox (`writeCommittedClaudeHooks`) and the gitignored local file otherwise; `uninstall` tears down the durability wiring and removes this workspace's per-root push/debounce state, and its opencode teardown sweeps BOTH merged global filenames (under the opencode config-dir bootstrap lock) plus the project `opencode.json`, expectation-keyed on this workspace's source id (`skipOtherSource`) — a gbrain entry from a different workspace is skipped with a note, never silently deleted. Consent answers resolve FAIL-CLOSED: `consentAnswer` treats a hand-edited/unusable interview value (non-string, empty) as declined — loudly, with a re-record note — never falling through to a permissive bank default; `hooks` on Codex prints a corrective note when a persisted `project` MCP_SCOPE answer is found (raw state read, not the resolver — `codex mcp add` has no scope flag, registrations are always user-global) with safe clear instructions. `GBRAIN_BOOTSTRAP_ABORT_AFTER` is the deterministic kill-mid-phase test seam.
+- `src/commands/bootstrap.ts` — the `gbrain bootstrap {status,interview,render,repo,hooks,verify,uninstall,attach,cloud-setup-script}` dispatcher (plus the machine-level `harness` subcommand — see the `core/bootstrap/harness.ts` entry below). Engine-free everywhere except `verify` (which opens/closes its own engine — safe because verify runs with no live serve, before host registration). `cloud-setup-script` is a pure printer (prints `templates/bootstrap/cloud-setup-script.sh` for the cloud environment's setup step) and is dispatched entirely BEFORE workspace resolution, so it works from any cwd, including $HOME. Every other subcommand resolves `--workspace` (default: cwd) through `resolveWorkspace`, which refuses with `BootstrapError('HOME_WORKSPACE')` when the resolved path (realpath-compared, so a symlinked $HOME or cwd still matches) IS `process.env.HOME` (falling back to `os.homedir()` only when HOME is unset) — an unqualified run from a freshly-SSH'd shell must not silently stage a home-directory-scale `git add -A` over `~/.ssh/` and friends; the refusal is still appended to `<home>/bootstrap/install.jsonl` (keyed by the rejected candidate path) before returning. `status`, `uninstall`, and `harness` are exempt from this guard (`HOME_WORKSPACE_GUARD_EXEMPT`): `status` only reads and prints a report, `uninstall` removes exactly `receipt.created_paths` (each containment-checked) — never a `git add`/commit/push, never a workspace-wide scan — and `harness` operates only on `home` and never even receives a `ws` argument (`runHarness`, machine-level wiring), so the value `resolveWorkspace` returns for it is used only for `LogCtx.ws` bookkeeping. Exempting `status`/`uninstall` keeps the recovery path reachable for the guard's own victims: someone who bootstrapped into `$HOME` needs `status` to see what's there and `uninstall` to remove it, both run with `--workspace` pointing AT $HOME; the refusal message for the still-guarded subcommands names that recovery path. Known gap: a process already launched with HOME pointed away from the real account home is not caught (Bun's `os.homedir()` mirrors process-start HOME rather than doing an independent uid lookup, so it collapses to the same wrong value). Mutating subcommands run under the workspace bootstrap lock; render is gated on interview `complete && confirmed` and hard-refuses when the workspace origin is a PUBLIC remote (identity files must never land in a public repo — the same template-door gate `status` enforces; unverifiable visibility warns and proceeds, treating the origin as public); the provider key routes to the 0600 config sink and never touches interview state; every MUTATING subcommand appends a line to `<home>/bootstrap/install.jsonl` (the read-only `status` and `cloud-setup-script` do not log). `hooks` on Claude Code writes the committed carrier in a cloud sandbox (`writeCommittedClaudeHooks`) and the gitignored local file otherwise; `uninstall` tears down the durability wiring and removes this workspace's per-root push/debounce state, and its opencode teardown sweeps BOTH merged global filenames (under the opencode config-dir bootstrap lock) plus the project `opencode.json`, expectation-keyed on this workspace's source id (`skipOtherSource`) — a gbrain entry from a different workspace is skipped with a note, never silently deleted. Consent answers resolve FAIL-CLOSED: `consentAnswer` treats a hand-edited/unusable interview value (non-string, empty) as declined — loudly, with a re-record note — never falling through to a permissive bank default; `hooks` on Codex prints a corrective note when a persisted `project` MCP_SCOPE answer is found (raw state read, not the resolver — `codex mcp add` has no scope flag, registrations are always user-global) with safe clear instructions. `GBRAIN_BOOTSTRAP_ABORT_AFTER` is the deterministic kill-mid-phase test seam. <!-- gbrain-allow-shared-tree-git: describes the home-directory refusal, not a command to run -->
- `src/core/gbrain-bin.ts` — `resolveGbrainBin()`: the absolute gbrain binary for harness registrations and hook commands (`Bun.which('gbrain')` when absolute, else this process's executable when it is the compiled binary, else null). A bare `gbrain` is never registered because GUI hosts inherit no PATH. Used by `bootstrap` and readiness's `harness_wiring` fix.
- `src/core/bootstrap/format.ts` — `agent.json` manifest (format_version 1, provisional; `initialized` sentinel distinguishes a template clone from a bootstrapped workspace) + the machine-local install receipt (`<home>/bootstrap/receipt.json`) that proves THIS machine ran bootstrap; uninstall is keyed to the receipt, never the repo manifest. Atomic writes; `readManifest` never throws (typed states incl. conflict markers).
- `src/core/bootstrap/assets.ts` — every template + the question bank embedded via Bun `with { type: 'file' }` imports (the chunkers/code.ts pattern) so the compiled binary renders with no repo checkout; `DERIVED_TOKENS` (GITHUB_REPO_URL, CORPUS_RETENTION_DAYS) is the non-bank half of the template token set the CI bijection guard checks.
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index b446a7da6c..15503c8fd6 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/audit-week-file.ts` — single source of truth for ISO-week audit JSONL filename math. Exports `isoWeek(d)`, `isoWeekFilename(prefix, now?)`, `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). Year-boundary correctness pinned by tests at 2020-W53 (the 53-week year), 2025-W01 rolling in from 2024-12-30 (Monday), 2026-W01. Four call sites: `src/core/minions/handlers/shell-audit.ts`, `src/core/facts/phantom-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/cycle/budget-meter.ts`. Each keeps its `compute<X>AuditFilename` thin wrapper.
-- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a successful push or confirmation that the exact destination branch on origin contains the attempted commit and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). `isDurabilityHardenedAsync(repoPath)` is the owners' non-blocking probe (#6210: rejects `git_unavailable` when unsure); it and the persistence Git runner (`effect-git.ts`) spawn through `execFileBounded` (defined in the import-free `src/core/bounded-child-exec.ts` and re-exported here; `git-remote.ts` `pullRepo` shares it), which settles at its deadline or on abort from its own timer because Bun can drop a child's pipe events and, before 1.3.14, its exit event (oven-sh/bun#30301) when bun:test `expect().resolves/.rejects` re-enters the event loop; an unbounded wait there stranded `disposePersistenceConsumer` and hung every later test in the file (test: `test/bounded-child-exec.test.ts`). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `brain_remote_contains_commit` checks the exact `refs/heads/<branch>` at every effective push URL, fetches each advertised tip without writing `FETCH_HEAD`, and proves ancestry of the captured commit; branch existence, a different fetch destination, or a stale tracking ref is not enough. Probe diagnostics are suppressed, ambiguous URL resolution fails closed, and recovery is skipped if local HEAD has moved since the failed push. This check runs after a rejected push and after retry failure, logging `ok-already-on-remote` on confirmation; `getLastPushOutcome` recognizes it as success. Existing unmanaged installations must rerun `gbrain sources harden <source-id>` to refresh both the local hook and committed helper; upgrading the CLI alone does not rewrite those scripts. Managed worktrees retain the persistence outbox as their Git writer; generated legacy helpers refuse to bypass it. `GBRAIN_PUSH_LOCK_WAIT_SECONDS` (default 30, env-only) tunes the `flock -w` wait in the rendered push-retry block that both the committed helper and the local hook share; on lock timeout the synchronous helper returns rc 1 (fail-loud, no push was attempted) while the detached post-commit hook returns rc 0 (another holder is already pushing — the designed coalescing outcome).
+- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that delegates to `gbrain git commit-push` (`src/core/git/commit-push.ts`, #6530: path-scoped commit under the short commit lock, push under the separate publish lock, remote commits merged in memory, checkout advanced fast-forward only; never `pull --rebase`, stash or reset) and refuses to exit 0 without a confirmed push (exit 4 maps to PUSH FAILED); without a capable CLI it does only a locked path-scoped commit plus a plain push; the hook runs the CLI path captured at harden with `--push-only --require-clean` in the background (it defers to a running push instead of waiting); both carry a `# gbrain-protocol: 2` line and harden refuses to downgrade a newer one, durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). `isDurabilityHardenedAsync(repoPath)` is the owners' non-blocking probe (#6210: rejects `git_unavailable` when unsure); it and the persistence Git runner (`effect-git.ts`) spawn through `execFileBounded` (defined in the import-free `src/core/bounded-child-exec.ts` and re-exported here; `git-remote.ts` `pullRepo` shares it), which settles at its deadline or on abort from its own timer because Bun can drop a child's pipe events and, before 1.3.14, its exit event (oven-sh/bun#30301) when bun:test `expect().resolves/.rejects` re-enters the event loop; an unbounded wait there stranded `disposePersistenceConsumer` and hung every later test in the file (test: `test/bounded-child-exec.test.ts`). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `brain_remote_contains_commit` checks the exact `refs/heads/<branch>` at every effective push URL, fetches each advertised tip without writing `FETCH_HEAD`, and proves ancestry of the captured commit; branch existence, a different fetch destination, or a stale tracking ref is not enough. Probe diagnostics are suppressed, ambiguous URL resolution fails closed, and recovery is skipped if local HEAD has moved since the failed push. This check runs after a rejected push and after retry failure, logging `ok-already-on-remote` on confirmation; `getLastPushOutcome` recognizes it as success. Existing unmanaged installations must rerun `gbrain sources harden <source-id>` to refresh both the local hook and committed helper; upgrading the CLI alone does not rewrite those scripts. Managed worktrees retain the persistence outbox as their Git writer; generated legacy helpers refuse to bypass it. `GBRAIN_COMMIT_LOCK_WAIT_SECONDS` (alias `GBRAIN_PUSH_LOCK_WAIT_SECONDS`, default 60) bounds the commit-lock wait and `GBRAIN_PUBLISH_LOCK_WAIT_SECONDS` (default 300) a foreground publish's wait for another push; the hook never waits on the push lock (`push_deferred`: it leaves a request the running publisher honors after release). An unresolved `integrate_conflict` is recorded per checkout (`brain-integrate-conflict.json` under the git dir) and `getLastPushOutcome(branch, repo)` reports it. Tests: `test/git-commit-push-6530.serial.test.ts`.
- `src/core/content-sanity-literals.ts` — operator literal-substring loader. Reads `~/.gbrain/junk-substrings.txt`, one literal per non-comment non-blank line; optional `# name=<id>` header pairs an identifier with the following literal so audit JSONL groups by site (`linkedin_auth_wall`, `reddit_blocked`, etc.). Fail-soft on ENOENT (missing file = empty array). Loaded on every ingest. Deliberately literal substrings (NOT regex) to defeat ReDoS. Pinned by `test/content-sanity-literals.test.ts`.
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index 52494509c7..bd8c1f037b 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -740,13 +740,13 @@ Git effect commits only the page paths it wrote (`git commit --only`) and then
pushes HEAD. Everything else in the checkout (`MEMORY.md`, daily notes,
`AGENTS.md`, scripts) is the operator's: `git add` and `git commit` it with
plain git in the checkout. Those commits reach the remote on the owner's next
-push, because the owner pushes HEAD, or sooner with a hand `git push` from the
+push, because the owner pushes HEAD, or sooner with a hand `git push` from the <!-- gbrain-allow-shared-tree-git: managed worktrees refuse gbrain git commit-push; a plain push of HEAD is the documented path for non-page files -->
checkout; `gbrain sources push` refuses on a managed root and its secret scan
does not run on a hand push. A hand push and the owner's push race only by
ordinary Git semantics (both push the same HEAD; a push the remote rejects is
retried by the owner and, after repeated failures, parked, which
`writer status --json` shows). Never
-`git pull --rebase`, `git reset` or `git checkout` page paths in the checkout:
+`git pull --rebase`, `git reset` or `git checkout` page paths in the checkout: <!-- gbrain-allow-shared-tree-git: names what never to run -->
the owner never pulls, and moving files under it is what `source_changed`
guards against; bring remote commits in with `gbrain sources refresh <source>`.
The durability block `sources harden` writes into `AGENTS.md`/`RESOLVER.md`
diff --git a/docs/guides/diligence-ingestion.md b/docs/guides/diligence-ingestion.md
index 10fc3eee2f..2929c9ab60 100644
--- a/docs/guides/diligence-ingestion.md
+++ b/docs/guides/diligence-ingestion.md
@@ -100,9 +100,17 @@ Update `brain/companies/{slug}.md`:
**Step 8: Commit.**
```bash
-cd brain/ && git add -A && git commit -m "diligence: {Company} — {doc type} ingestion" && git push
+cd brain/ && scripts/brain-commit-push.sh "diligence: {Company} — {doc type} ingestion" \
+ diligence/{company-slug}/ companies/{company-slug}.md
```
+Name the diligence directory and every page you edited; other agents may have
+uncommitted work in the same checkout, so never commit the whole tree. Without
+the helper, run `gbrain git commit-push -m "<msg>" -- <paths>`. On a non-zero
+exit: retry once on `commit_lock_busy`; stop and tell the user on
+`integrate_conflict` or `writer_coordinator_required`; never fall back to
+stash, `pull --rebase` or a plain push ([outcomes](shared-checkout-git.md#outcomes)).
+
**Step 9: Publish (if asked).**
When the user wants a shareable brief, create a password-protected
published version via the `publish` skill (`skills/publish/`). Strip
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 59296caa9d..001521b616 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -516,6 +516,26 @@ More: [docs/guides/write-refusals.md#colon_slug_windows_write_through](../../doc
|---|---|---|---|---|---|---|
| The command failed before it wrote its JSON result. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |
+### commit_lock_busy
+
+<a id="commit_lock_busy"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Another writer held the checkout's commit lock for the whole wait, so nothing was committed. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |
+
+More: [docs/guides/shared-checkout-git.md#outcomes](../../docs/guides/shared-checkout-git.md#outcomes)
+
+### commit_paths_invalid
+
+<a id="commit_paths_invalid"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The commit was refused before staging: no paths, a path outside the checkout, the whole checkout, or a path git would not stage. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `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>
@@ -1156,6 +1176,16 @@ More: [docs/guides/shared-brain-skills.md#approve-publication-following-and-edit
|---|---|---|---|---|---|---|
| Git index stale. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### git_operation_in_progress
+
+<a id="git_operation_in_progress"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A rebase, merge, cherry-pick or revert is in progress in the checkout, so gbrain will not commit or move it. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/shared-checkout-git.md#stuck-rebase](../../docs/guides/shared-checkout-git.md#stuck-rebase)
+
### git_push_unavailable
<a id="git_push_unavailable"></a>
@@ -1426,6 +1456,16 @@ More: [docs/guides/troubleshooting.md#host-identity-mismatch](../../docs/guides/
|---|---|---|---|---|---|---|
| The connection lacks the OAuth scope the operation requires. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |
+### integrate_conflict
+
+<a id="integrate_conflict"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Local and remote commits changed the same file; nothing was merged and the checkout is unchanged. | 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#conflicts](../../docs/guides/shared-checkout-git.md#conflicts)
+
### internal
<a id="internal"></a>
@@ -2204,6 +2244,16 @@ More: [docs/guides/memory-boundaries.md#purge](../../docs/guides/memory-boundari
More: [docs/guides/memory-boundaries.md#purge](../../docs/guides/memory-boundaries.md#purge)
+### push_unconfirmed
+
+<a id="push_unconfirmed"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The commit is durable locally but no push destination confirmed it. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 4 | yes |
+
+More: [docs/guides/shared-checkout-git.md#outcomes](../../docs/guides/shared-checkout-git.md#outcomes)
+
### question_not_found
<a id="question_not_found"></a>
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index b70805e33f..c03a9259f3 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -474,7 +474,10 @@ vars — incident-time escape hatches, not everyday knobs.
(`N uncommitted file(s) not synced`), the sync result object carries an
`uncommitted` summary (surfaced via `sync_brain` over MCP and in
`gbrain dream --json` phase details), and the nightly dream cycle reports
- the sync phase as `warn` instead of a clean run. The fix is to commit the files. If your
+ the sync phase as `warn` instead of a clean run. The fix is to commit the
+ files, naming them: `gbrain git commit-push -m "<msg>" -- <paths>` (or the
+ brain's `scripts/brain-commit-push.sh`), which is safe when other agents
+ share the checkout ([shared-checkout git](shared-checkout-git.md)). If your
workflow legitimately writes without committing, opt in to importing
uncommitted state with `gbrain sync --working-tree` (one run) or
`gbrain config set sync.include_working_tree true` (standing config,
@@ -511,8 +514,10 @@ vars — incident-time escape hatches, not everyday knobs.
**Say to your agent:** *"Bring my notes source up to date with its remote."*
9. **Turn automatic pulls off for every source.** On an unmanaged brain,
- autopilot's freshness sync and its per-source cycle run `git pull` for a
- source that has a remote URL. A checkout you keep current yourself (a
+ autopilot's freshness sync and its per-source cycle pull a source that has
+ a remote URL: a fetch, then a fast-forward under the checkout's writer lock
+ with autostash off, so the pull never stashes or rebases files another
+ agent is writing ([shared-checkout git](shared-checkout-git.md)). A checkout you keep current yourself (a
deploy script, a mirror, a branch you rebase by hand) should not be
pulled behind your back:
@@ -533,7 +538,9 @@ vars — incident-time escape hatches, not everyday knobs.
## How to Verify
1. **Edit a file and search for the change.** Edit a brain markdown file,
- commit, and push. Wait for the next sync cycle (cron interval or `--watch`
+ then commit and push it with `gbrain git commit-push -m "<msg>" -- <file>`
+ (it must exit 0; on an error code follow
+ [outcomes](shared-checkout-git.md#outcomes)). Wait for the next sync cycle (cron interval or `--watch`
poll). Run `gbrain search "<text from the edit>"`. The updated content
should appear in results. If it returns old content, sync failed.
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index 12643a5be5..16550e7bb2 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -302,7 +302,7 @@ Fix it with:
```bash
git -C <path> init
-git -C <path> add -A
+git -C <path> add -A # gbrain-allow-shared-tree-git: first commit of a brand-new repo nobody else writes yet
git -C <path> commit -m "initial import"
gbrain sources add <id> --path <path>
```
@@ -459,25 +459,34 @@ gbrain sources unharden wiki
What hardening guarantees:
-- **Pull-first, conflict-safe.** Every pull is a divergence-safe rebase. A
- dirty working tree is skipped (your in-progress edits are never touched; the
- pull runs with `--no-autostash`, so a `rebase.autoStash` setting never
- stashes and replays edits under it); a rebase conflict is aborted cleanly and
- flagged for attention, never left half-applied. A brain whose intermediate
- snapshot commits conflict under rebase replay while the two tips merge
- cleanly can record `gbrain sources set-pull-strategy <id> merge`: pulls of
- that source then fast-forward when possible and otherwise make a merge
- commit, and a real conflict is aborted with `merge --abort`. The setting
- lives in the source's config (`sources list --json` shows `pull_strategy`),
- so a repository or global `pull.rebase` never changes it; `--path` pulls with
- no source row keep `rebase`.
+- **Pull-first, safe in a shared checkout.** Nothing rebases or stashes the
+ working tree. A pull fetches, then, under the checkout's writer lock,
+ fast-forwards, or for a diverged branch merges the remote commits in memory
+ into a merge commit (`gbrain: merge origin/<branch> into <branch>`) and
+ fast-forwards to it. A real conflict changes nothing and is flagged for
+ attention ([conflicts](shared-checkout-git.md#conflicts)). `gbrain sources
+ pull`, which the unattended 30-minute cron runs, keeps its conservative
+ rule: a checkout with any local edit is skipped (`skipped_dirty`), so it
+ never moves files under a writer, and a checkout whose writer lock is busy
+ is skipped until the next run. An explicit `scripts/brain-commit-push.sh --pull`
+ (or `gbrain git commit-push --pull`) advances a dirty checkout unless a
+ dirty file is one the pull must change; then it changes nothing and its
+ notice names the files. `gbrain sources set-pull-strategy <id> <rebase|merge>`
+ is still accepted and recorded, but both strategies now integrate by merge,
+ because the shared tree is never rebased.
- **Push is never deferred.** `scripts/brain-commit-push.sh "<msg>" <path>`
- commits and pushes, and refuses to report success without a successful push
- or confirmation that the exact destination branch at every effective origin
- push URL contains the attempted commit. A rejected push can still succeed when another process
- already pushed that commit; a stale local tracking ref is not confirmation.
- The post-commit hook is a best-effort background fallback; the helper is
- the guarantee.
+ delegates to `gbrain git commit-push`: it takes the checkout's writer lock,
+ commits only the named paths, merges a rejected push in memory, and refuses
+ to report success without a push the remote accepted. Other agents'
+ uncommitted files are never staged, stashed or touched. The post-commit
+ hook is a best-effort background fallback (it only publishes, never pulls);
+ the helper is the guarantee. Outcomes and what to do on each:
+ [shared-checkout git](shared-checkout-git.md#outcomes).
+- **One writer at a time per checkout.** Harden also sets
+ `rebase.autoStash=false`, `merge.autoStash=false` and `pull.ff=only` in the
+ checkout's local git config, so a stray `git pull` refuses instead of
+ autostashing. Host daemons that commit the same checkout join through the
+ [lock contract](shared-checkout-git.md#lock-contract).
- **No silent staleness.** A 30-minute background pull keeps an idle session
current. It runs DB-free, so it never contends with a live brain for the
PGLite single-writer lock.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 0d60532d80..8b9d24a03c 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -959,7 +959,7 @@ gbrain older than v0.60.47.0 blocks the source on the first file it refuses.
6. Commit, sync, and read the remaining hold as JSON.
```console
- $ git -C ~/brain/notes commit -qam "Repair frontmatter"
+ $ git -C ~/brain/notes commit -q -m "Repair frontmatter" -- notes/roundup.md notes/standup.md
$ gbrain sync --source notes --no-pull
0 file(s) held this run, 1 held in source notes; they do not block sync. Inspect them with 'gbrain sources status notes'; the repair preview proposes each fix and writes nothing. Preview the repair: gbrain repair frontmatter --source notes
$ gbrain sources status notes --json
@@ -991,7 +991,7 @@ gbrain older than v0.60.47.0 blocks the source on the first file it refuses.
interpretive: notes:notes/digest.md (Kept the later "title" (line 4) and dropped the earlier one (line 2))
$ gbrain repair frontmatter --source notes --include-ambiguous --only notes/digest.md --apply --expect <hash> --yes
repaired: notes:notes/digest path=notes/digest.md, written=true, imported=created, hold_cleared=true, committed=queued
- $ git -C ~/brain/notes commit -qam "Keep the later digest title"
+ $ git -C ~/brain/notes commit -q -m "Keep the later digest title" -- notes/digest.md
$ gbrain sync --source notes --no-pull
+0 added, ~0 modified, -0 soft-deleted (recoverable 72h), R0 renamed
$ gbrain doctor --only git_held_files,frontmatter_repairable
@@ -1308,7 +1308,7 @@ exists). An older gbrain blocked the source on the first fence it refused.
M companies/acme-example.md
M meetings/2026-04-03.md
M projects/widget-launch.md
- $ git -C ~/brain/notes commit -qam "Repair fences"
+ $ git -C ~/brain/notes commit -q -m "Repair fences" -- companies/acme-example.md meetings/2026-04-03.md projects/widget-launch.md
$ gbrain doctor --only fence_integrity
[OK] fence_integrity: No malformed facts or takes fence is held, stored or waiting in a checkout (2 source(s) scanned).
```
diff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.md
new file mode 100644
index 0000000000..63c876d807
--- /dev/null
+++ b/docs/guides/shared-checkout-git.md
@@ -0,0 +1,353 @@
+# Committing and pushing in a brain checkout other agents share
+
+## Goal
+
+Many writers commit to the same brain checkout on one machine: interactive
+sessions, sub-agents, cron jobs, the post-commit hook, gbrain's own page
+writes and sometimes a host sync daemon. Every one of them commits and pushes
+with one command, and none of them can stash, rebase, revert or ship another
+writer's half-written files.
+
+**Say to your agent:** *"Commit the meeting notes you just wrote to my brain and push them."*
+Your agent runs `scripts/brain-commit-push.sh "meetings: 2026-04-03 product review" meetings/2026-04-03.md`
+(or `gbrain git commit-push -m "<msg>" -- <paths>` when the brain has no helper).
+
+**Say to your agent:** *"Bring my brain checkout up to date before you start writing."*
+Your agent runs `scripts/brain-commit-push.sh --pull` (or `gbrain git commit-push --pull`).
+
+**Say to your agent:** *"The push conflicted on people/alice-example.md. Keep the version on GitHub."*
+Your agent runs `gbrain git commit-push --push-only --expect-remote <sha> --resolve people/alice-example.md=theirs`,
+copying the remote commit from the conflict report.
+
+## Why the old way broke
+
+<!-- gbrain-allow-shared-tree-git-begin: describes the commands that caused the incidents -->
+Skills used to tell each agent to run `git pull --rebase` (sometimes with
+`--autostash`) and then a plain push, directly in the shared working tree. A
+rebase stashes every other process's uncommitted work for as long as it runs.
+When it crashes, times out, hits a busy `index.lock` or conflicts, it leaves a
+`.git/rebase-merge` directory with someone else's files inside its autostash.
+Every later pull then refuses, and an agent that "repairs" it by hand can
+silently revert another agent's in-flight edit. A repo-wide `git add -A` or
+`git commit -a` has the same problem from the other side: it commits whatever
+another writer has half-written.
+<!-- gbrain-allow-shared-tree-git-end -->
+
+## The protocol in plain words
+
+`gbrain git commit-push` does five things, in this order:
+
+1. **Takes this checkout's commit lock, briefly.** One commit lock per
+ checkout, held only while it stages and commits (and later while it
+ fast-forwards the checkout), never across the network. A second writer
+ waits (60 seconds by default) and then fails with `commit_lock_busy`
+ instead of skipping silently. The push itself runs under a separate push
+ 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 those
+ paths (`git add -A -- <paths>`, `git commit --only -- <paths>`). Another
+ writer's dirty files are never staged, committed, stashed or touched.
+3. **Pushes your commit, and merges remote commits in memory when the push is
+ rejected.** 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
+ eight attempts, backing off, while the remote keeps moving. One push at a
+ time runs per checkout and it publishes the newest local commit, so writers
+ that queue behind it share its push. The post-commit hook never waits: when
+ a push is already running it asks that push to publish its commit too
+ (`push_deferred`).
+4. **Advances the shared checkout fast-forward only.** `git merge --ff-only`
+ refuses, and changes nothing, when another writer moved HEAD or has a local
+ edit in a file the merge must change. The push has still landed; the
+ checkout just lags until the next commit-push or pull (`pushed_checkout_lagging`).
+5. **Stops on a real conflict.** When both sides changed the same file, it
+ changes nothing and asks you which version wins
+ ([conflicts](#conflicts)).
+
+Remote commits therefore arrive as merge commits named
+`gbrain: merge origin/<branch> into <branch>`, so brain history is no longer
+linear. That is the price of never rewriting a working tree other writers
+are using.
+
+## Commands
+
+A brain hardened with `gbrain sources harden` has a committed helper,
+`scripts/brain-commit-push.sh`. It hands the same arguments to
+`gbrain git commit-push`, so either form works:
+
+```bash
+# Commit and push the files you wrote (paths are relative to the current directory)
+scripts/brain-commit-push.sh "people: add alice-example" people/alice-example.md
+gbrain git commit-push -m "people: add alice-example" -- people/alice-example.md
+
+# Publish commits already on the branch (the hook's job; also the retry after a push failure)
+scripts/brain-commit-push.sh --push-only
+gbrain git commit-push --push-only
+
+# Bring remote commits in (fast-forward, or an in-memory merge); never pushes
+scripts/brain-commit-push.sh --pull
+gbrain git commit-push --pull
+
+# Preview: prints the paths, branch and lock it would use; takes no lock, writes nothing
+gbrain git commit-push --dry-run -m "people: add alice-example" -- people/alice-example.md
+```
+
+Flags: `--path <dir>` acts on a checkout other than the one containing the
+current directory, `--json` prints one JSON result (or the error envelope),
+`--require-clean` makes `--pull` skip when the checkout has any local edit
+(the rule the unattended pull cron uses). The command is local only: it pushes
+with this machine's git credentials and is never exposed over MCP.
+
+When gbrain is not installed on the machine, the helper falls back to a locked
+path-scoped commit and a plain push. A rejected push then fails loudly (exit 4)
+and tells you to install gbrain and run `gbrain git commit-push --push-only`;
+the fallback never integrates remote commits itself.
+
+A managed canonical worktree (`gbrain sources writer git-durability`) refuses
+both forms with `writer_coordinator_required`: its persistence owner is the only
+Git writer there. Save pages with `put_page`, `edit_page`, `remember` or
+`capture`; see [files that are not pages](../architecture/topologies.md#files-that-are-not-pages).
+
+<a id="outcomes"></a>
+## Outcomes
+
+Every run ends in exactly one of these. Successes exit 0; every failure prints
+an `[Error <code>]` line (or a JSON envelope with `--json`) and exits non-zero.
+Follow the error's `fix.next` as the
+[agent operator protocol](../protocol/AGENT_OPERATOR_v1.md) describes.
+
+| Outcome or code | Exit | What the agent does next |
+| --- | --- | --- |
+| `pushed` | 0 | Done. Report the commit; a hosted link to the file works now. |
+| `push_deferred` | 0 | Only with `--require-clean` (the post-commit hook): another push was running in this checkout and was asked to publish HEAD too when it finishes. Nothing to do. |
+| `nothing_to_commit` | 0 | The paths had no change. Any earlier local commit on the branch was still pushed, so nothing is waiting. |
+| `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. |
+| `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). |
+| `git_detached_head` | 1 | The checkout is on a detached HEAD or an unborn branch. Check out the branch the remote tracks (`git switch <branch>`), or make the first commit, then rerun. |
+| `integrate_conflict` | 1 | Local and remote commits changed the same file; nothing was merged and the checkout is unchanged. Stop, relay the question to the user, then [resolve](#conflicts). |
+| `push_unconfirmed` | 4 | The commit is durable locally but no push destination confirmed it (network, credentials, branch protection, a remote that kept moving, or another push that held the push lock for the whole wait). Fix what the message names, then run `gbrain git commit-push --push-only`. Never force-push. |
+| `writer_coordinator_required` | 1 | This is a managed worktree. Stop using git for pages; save them through `put_page` and the other gbrain write tools. |
+| `git_unavailable` | 1 | A git command failed, often a missing `user.name`/`user.email` or a refusing pre-commit hook. Read the message, fix that, rerun. When the branch has no usable remote at all, the run stops before committing: add the remote, or commit locally with `git add <paths> && git commit -m "<msg>" -- <paths>`. |
+
+`--pull` reports `up_to_date`, `advanced`, `ahead` (local commits not yet
+pushed; run `--push-only`), `skipped_dirty` (only with `--require-clean`) or
+`lagging` (a dirty file the pull must change blocked it; a notice names it).
+All of these exit 0. A diverged branch whose two sides changed the same file
+fails with `integrate_conflict`, the same as a push.
+
+The helper's own exits: 2 for a usage error (no message, or no paths: it
+refuses a repo-wide commit), 4 when its no-gbrain fallback could not push.
+
+With `--json`, a success prints `outcome`, `sha` (the commit now on the
+remote), `committed` (your commit, or null), `branch`, `remote`, `paths`,
+`integrated` (remote commits merged in), `checkout` (`advanced`, `unchanged`
+or `lagging`), `lagging_reason` when it lags, and `repo`.
+
+Every run also appends a line to `~/.gbrain/brain-push.log`, which
+`put_page`'s push status and `gbrain doctor` read. An unresolved
+`integrate_conflict` is also recorded in the checkout itself
+(`git rev-parse --git-path brain-integrate-conflict.json`), so `put_page`
+reports it for that checkout until a publish resolves it.
+
+<a id="conflicts"></a>
+## Conflicts
+
+A conflict means this machine's unpushed commit and the remote both changed
+the same file. On git 2.38 and later that means overlapping changes; on older
+git (Ubuntu 22.04 ships 2.34) any change to the same file on both sides counts
+as a conflict, even in different paragraphs.
+
+Nothing changes when it happens: the local commit stays local, the checkout is
+untouched and nothing is pushed. The error names the files, the local and
+remote commits (in its `detail`), and a question to relay to the user. Until it
+is resolved, every later commit-push from this checkout hits the same
+conflict, even for other files, because the unpushed commit is still waiting.
+
+To resolve:
+
+1. Ask the user which version of each file should win, or whether they want
+ the two merged by hand. Choosing a side discards the other side's change to
+ that file, so never pick one yourself.
+2. Look at both versions if it helps the user decide:
+ `git show HEAD:<path>` (this machine) and `git show origin/<branch>:<path>`
+ (the remote).
+3. Rerun with `--expect-remote <remote sha>` (copied from the error) and one
+ `--resolve` per conflicted file, using the path exactly as the error
+ printed it (relative to the checkout root; the error shell-quotes names
+ with spaces or non-ASCII characters):
+
+ ```bash
+ # Keep this machine's version
+ gbrain git commit-push --push-only --expect-remote 1a2b3c4d5e6f --resolve people/alice-example.md=ours
+ # Keep the remote's version
+ gbrain git commit-push --push-only --expect-remote 1a2b3c4d5e6f --resolve people/alice-example.md=theirs
+ # Use a hand-merged copy written OUTSIDE the checkout
+ gbrain git commit-push --push-only --expect-remote 1a2b3c4d5e6f --resolve people/alice-example.md=file:$HOME/.gbrain/merge-alice-example.md
+ ```
+
+ It builds the same in-memory merge with your choice for each file, pushes
+ it and advances the checkout. A conflicted file left without a `--resolve`
+ fails again with every conflicted file listed. If the remote moved since
+ the user chose, it reports the conflict again against the new remote
+ commit instead of applying the choice to a version nobody saw. Delete the
+ merged copy afterwards.
+
+ A file/directory or rename conflict (one side has `topic` as a file, the
+ other as a folder) cannot be settled by picking a side per file, so
+ `--resolve` refuses it. Move or remove the local path in a new commit
+ (`gbrain git commit-push -m "<msg>" -- <paths>`), then run
+ `gbrain git commit-push --push-only`.
+
+Write a merged copy outside the checkout: editing the conflicted file in place
+leaves it dirty, so the checkout cannot fast-forward over it afterwards.
+
+Shared append-only files (a `log.md` every workflow appends to) are the usual
+source of conflicts: two appends at the end of the same file overlap. Keep
+both sides by merging by hand with `file:`, or make such files derived instead
+of hand-appended.
+
+<a id="stuck-rebase"></a>
+## Recovering a stuck rebase
+
+<!-- gbrain-allow-shared-tree-git: names the command that leaves a stuck rebase -->
+An older helper or agent that ran `git pull --rebase --autostash` in the shared
+checkout and crashed leaves `.git/rebase-merge` (or `.git/rebase-apply`)
+behind. gbrain then refuses with `git_operation_in_progress`. The autostash
+inside that directory can hold other writers' uncommitted edits, so save it
+before anything else. Never delete the directory first.
+
+1. Make sure the rebase is not still running: no `git rebase` or `git pull`
+ process in that checkout (`ps -ef | grep '[g]it '`).
+2. Save the autostash to the stash list, where it survives everything below:
+
+ ```bash
+ cd <brain-checkout>
+ for d in rebase-merge rebase-apply; do
+ f="$(git rev-parse --git-path "$d/autostash")"
+ [ -f "$f" ] && git stash store -m "autostash rescued from a stuck $d" "$(cat "$f")"
+ done
+ git stash list
+ ```
+
+3. End the rebase. `git rebase --abort` returns the branch to where it was
+ before the rebase started, so local commits are kept. If it refuses, use
+ `git rebase --quit`, which leaves HEAD, the index and the working tree as
+ they are.
+4. Check whether the edits are back: `git rebase --abort` re-applies the
+ autostash when it can, so `git status` may already show them. If so, the
+ stash entry is only a spare copy. If not, show the user the rescued edits
+ (`git stash show -p stash@{0}`) and ask before putting them back. With
+ their agreement:
+ `git stash apply stash@{0}` <!-- gbrain-allow-shared-tree-git: restores an autostash rescued in step 2, with the user's agreement -->
+ The writers those edits belong to commit them as usual, or you commit them
+ with `gbrain git commit-push -m "<msg>" -- <paths>` if the user asks.
+5. Bring the checkout up to date: `gbrain git commit-push --pull`.
+
+## Never run these in a shared checkout
+
+Each one moves or captures files other writers are using:
+
+<!-- gbrain-allow-shared-tree-git-begin: the list of commands this guide forbids -->
+- `git pull --rebase`, and any pull with `--autostash`: stashes every writer's
+ edits for as long as the rebase runs. Use `--pull` instead.
+- `git stash` in any form other than `git stash store`, `list` or `show`:
+ hides other writers' edits.
+- `git add -A`, `git add .` or `git commit -a` without explicit paths: commits
+ other writers' half-written files. Name your paths.
+- `git reset --hard`: discards other writers' edits.
+- `git push --force`: deletes other writers' published commits.
+- A plain `git push`: not destructive, but it does not take the writer lock or
+ integrate a rejected push. Use `--push-only`.
+- Deleting `.git/rebase-merge` before its autostash is saved
+ ([stuck rebase](#stuck-rebase)).
+<!-- gbrain-allow-shared-tree-git-end -->
+
+`gbrain sources harden` also sets `rebase.autoStash=false`, `merge.autoStash=false`
+and `pull.ff=only` in the checkout's local git config, so a stray `git pull`
+refuses instead of autostashing.
+
+The repository lint `bun run check:shared-tree-git` fails a gbrain skill,
+recipe, template or doc that teaches any of these in a code block or an inline
+code span. A line that must name one (a warning, or a single-writer clone such
+as a fresh export) carries `# gbrain-allow-shared-tree-git: <reason>` on the
+same line inside a code block, or `<!-- gbrain-allow-shared-tree-git: <reason> -->`
+on the line before it in prose. A list of them, like the one above, sits
+between `<!-- gbrain-allow-shared-tree-git-begin: <reason> -->` and
+`<!-- gbrain-allow-shared-tree-git-end -->`. `git push --dry-run` is read-only
+and never flagged.
+
+<a id="lock-contract"></a>
+## Lock contract for host daemons
+
+A process outside gbrain that commits or pulls the same checkout (a host
+git-sync service, your own cron script, an OpenClaw host's sync) joins the
+protocol by taking the same lock. The simplest way is to call
+`gbrain git commit-push --pull` and `gbrain git commit-push -m "<msg>" -- <paths>`,
+which take it for you. A daemon that runs git itself follows this contract:
+
+- **Lock file:** `git rev-parse --git-path brain-commit.lock` (the commit lock), one per checkout
+ (each linked worktree has its own). The lock is an exclusive OS file lock,
+ the same one `flock -x` takes on Linux and macOS. The file existing means
+ nothing; never delete it.
+- **Legacy lock:** helpers and hooks from before this protocol take
+ `gbrain-push.lock` in the same directory. gbrain takes both, always
+ `brain-commit.lock` first; a daemon that may share a checkout with an old
+ helper 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.
+- **Mark your children:** while holding the lock, set
+ `BRAIN_COMMIT_LOCK_HELD` to the lock file's absolute path in the environment
+ of anything you start that may take it, such as `gbrain git commit-push` or a
+ `git commit` whose post-commit hook runs gbrain. gbrain honors the marker only
+ when it names this lock and the lock really is held, so a stale, copied or
+ generic (`1`) marker cannot skip the lock.
+- **Wait time:** gbrain waits `GBRAIN_COMMIT_LOCK_WAIT_SECONDS` (alias
+ `GBRAIN_PUSH_LOCK_WAIT_SECONDS`), default 60, then fails with
+ `commit_lock_busy`. Wait the same way and fail loudly; never skip silently.
+ A push waits `GBRAIN_PUBLISH_LOCK_WAIT_SECONDS` (default 300) for another
+ push in the same checkout, then fails with `push_unconfirmed`.
+- **Inside the lock:** integrate with `git fetch` plus
+ `git -c merge.autoStash=false merge --ff-only`, or call `gbrain git commit-push --pull`;
+ never rebase, stash or reset the shared tree.
+
+```bash
+cd <brain-checkout>
+exec 8>"$(git rev-parse --git-path brain-commit.lock)"
+flock -w "${GBRAIN_COMMIT_LOCK_WAIT_SECONDS:-60}" 8 || { echo "commit_lock_busy" >&2; exit 75; }
+exec 9>"$(git rev-parse --git-path gbrain-push.lock)"
+flock -w "${GBRAIN_COMMIT_LOCK_WAIT_SECONDS:-60}" 9 || { echo "commit_lock_busy" >&2; exit 75; }
+export BRAIN_COMMIT_LOCK_HELD="$(git rev-parse --path-format=absolute --git-path brain-commit.lock)"
+gbrain git commit-push --pull
+gbrain git commit-push -m "host sync: daily notes" -- daily/
+```
+
+## Limits
+
+- **Two agents editing the same file at the same time still conflict.** The
+ lock serializes commits, not edits: if two writers change one file, the
+ second commit carries whatever is on disk when it commits, and edits on two
+ machines meet as an `integrate_conflict`. When agents routinely write the
+ same pages, use managed mode, where pages go through `put_page` and one
+ persistence owner
+ ([topologies](../architecture/topologies.md#files-that-are-not-pages)).
+- **git older than 2.38** has no `merge-tree --write-tree`, so any file changed
+ on both sides is a conflict, even when the changes do not overlap.
+- **A lagging checkout is not repaired automatically** while another writer's
+ edit blocks it. The next commit-push or `--pull` after that edit is
+ committed 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.
+
+## Related
+
+- [Multi-source brains: durability hardening](multi-source-brains.md)
+- [Live sync](live-sync.md)
+- [Agent operator protocol](../protocol/AGENT_OPERATOR_v1.md)
+- [Error codes](error-codes.md)
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index dd79691b5a..e8930c30ee 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -111,7 +111,7 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p
`bootstrap_push_health` and `gbrain bootstrap status` report only the push record of the workspace named by this machine's bootstrap receipt; another workspace's stale or failed push is listed as such (a warn naming that workspace), never as this workspace's state. `reranker_health` auth warnings are audit-log history (`details.live_probe_performed: false`), not a live check of the key. These warns can appear while every other check reads green; each one names a check that did not run.
-<a id="git-convergence"></a>**`gbrain doctor` warns or fails `git_convergence`, or `bootstrap_push_health` warns that a workspace is ahead?** A Git checkout the brain syncs from (a source's `local_path` or `sync.repo_path`) has commits its upstream does not have, or uncommitted changes, so the system of record on the remote is behind the brain (#5063). Commits not on the upstream warn after 6 hours and fail after 24; uncommitted changes older than 6 hours warn. Doctor compares with the local `@{u}` ref and never fetches, so it is only as fresh as the last fetch; checkouts without an upstream and connector sources are skipped. Commit and push the checkout (`gbrain sources push --path <root>` for a bootstrap workspace, `git push` otherwise). `bootstrap_push_health` no longer reports `ok` on a recent successful push while the workspace still has commits not on origin.
+<a id="git-convergence"></a>**`gbrain doctor` warns or fails `git_convergence`, or `bootstrap_push_health` warns that a workspace is ahead?** A Git checkout the brain syncs from (a source's `local_path` or `sync.repo_path`) has commits its upstream does not have, or uncommitted changes, so the system of record on the remote is behind the brain (#5063). Commits not on the upstream warn after 6 hours and fail after 24; uncommitted changes older than 6 hours warn. Doctor compares with the local `@{u}` ref and never fetches, so it is only as fresh as the last fetch; checkouts without an upstream and connector sources are skipped. Commit and push the checkout (`gbrain sources push --path <root>` for a bootstrap workspace; otherwise commit your files with `gbrain git commit-push -m "<msg>" -- <paths>` and publish waiting commits with `gbrain git commit-push --push-only`, see [shared-checkout git](shared-checkout-git.md#outcomes)). `bootstrap_push_health` no longer reports `ok` on a recent successful push while the workspace still has commits not on origin.
<a id="tracked-ownership-marker"></a>**`gbrain doctor` warns `tracked_ownership_marker`, or `gbrain sources push` / `bootstrap verify` refuses a `.gbrain-owner*.json` or `.gbrain-bootstrap.lock/` path?** An ownership marker (`.gbrain-owner.json`, the `.gbrain-owner-<hash>.json` reservation beside a root, a `.gbrain-owner.json.<uuid>.tmp` staging file) or the bootstrap lock directory was committed to a source checkout (#5186). These files are this machine's claim on the checkout, never brain content, and must not reach a remote. Since this fix gbrain appends their patterns to the checkout's `.git/info/exclude` whenever it stamps or adopts a root, the bootstrap `.gitignore` template lists them, and the push deny list refuses a tracked one while an untracked one is excluded from the commit (`excludedUntracked`). None of that un-tracks a file already in the index: run the `git -C <root> rm --cached <paths>` the check prints (the files stay on disk, gbrain keeps reading them), commit, push, then `gbrain doctor --only tracked_ownership_marker --json`. A root stamped before this fix gains the exclude rule on its next stamp or transfer; until then the deny list is the backstop, and `bootstrap verify`'s `deny_globs` treats a merely-on-disk marker as fine. If a marker already reached a remote, rotate it the same way you would any published credential: the token alone is not remote authority (the reservation that proves ownership lives outside the root), but treat the history as exposed.
diff --git a/docs/integrations/qm-harness-snippets/provision-scopes.sh b/docs/integrations/qm-harness-snippets/provision-scopes.sh
index ffa8c666ec..6c845cd2e5 100755
--- a/docs/integrations/qm-harness-snippets/provision-scopes.sh
+++ b/docs/integrations/qm-harness-snippets/provision-scopes.sh
@@ -90,7 +90,7 @@ STATE_FILE="${STATE_FILE:-${ROSTER}.state.tsv}"
SECRETS_OUT="${SECRETS_OUT:-${ROSTER}.new-credentials.tsv}"
# The roster usually lives in the deployment repo, so the default secrets and
-# state paths land there too — one `git add -A` from committing live
+# state paths land there too — one `git add -A` from committing live # gbrain-allow-shared-tree-git: warning, not an instruction
# credentials. The STATE file matters as much as the secrets file: it maps
# employee -> client_id, and this script feeds that id straight to
# `rescope-client`, so whoever can write it decides which client receives a
diff --git a/docs/operations/backup-check.md b/docs/operations/backup-check.md
index 2964ce5e73..75a86a477f 100644
--- a/docs/operations/backup-check.md
+++ b/docs/operations/backup-check.md
@@ -135,7 +135,7 @@ export is not used, and the remote's host key must already be in `known_hosts`.
| `verification.state` | Meaning | What to do |
|---|---|---|
| `verified` | The remote branch HEAD matches a clean local HEAD. | Nothing. |
-| `missing_ref` | The remote answered but has no such branch. | `git push -u origin <branch>`, then `gbrain backup check`. |
+| `missing_ref` | The remote answered but has no such branch. | `git push -u origin <branch>` <!-- gbrain-allow-shared-tree-git: one-time first push that creates the remote branch and sets its upstream -->, then `gbrain backup check`. |
| `mismatch` | The remote HEAD differs from the local HEAD, or the tree changed during the probe. | Push or pull until they match, then `gbrain backup check`. |
| <a id="remote-unavailable"></a>`unavailable` | `git ls-remote` failed: no network, authentication refused, or an unknown host key. `cause` says which kind: `timeout` (the remote did not answer within its full two-second slot) or `exit` (git exited with an error). The probe passes only `HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, `HTTPS_PROXY`/`https_proxy`, `HTTP_PROXY`/`http_proxy`, `NO_PROXY`/`no_proxy` (and `USERPROFILE`, `APPDATA`, `SystemRoot` on Windows). | Run `git -C <root> ls-remote origin` in the same shell; credentials must come from your Git config, a credential helper, `~/.ssh/config` or the SSH agent, not from a prompt or `GIT_SSH_COMMAND`. |
| `budget_exhausted` | The sweep's eight-probe or eight-second budget ran out first, or this remote would not have received its full two-second slot. | Run `gbrain backup check` again. |
@@ -189,7 +189,7 @@ source id. Full per-asset detail (which repo, which fix) is local-only:
- Workspace with no repo: `gbrain bootstrap repo` (creates a private repo,
verifies privacy, pushes).
- A source repo with no remote:
- `git remote add origin [email protected]:you/your-brain-repo.git && git push -u origin main`,
+ `git remote add origin [email protected]:you/your-brain-repo.git && git push -u origin main`, <!-- gbrain-allow-shared-tree-git: one-time first push that creates the remote branch and sets its upstream -->
then `gbrain sources harden <source-id>` for auto-push durability.
- Unpushed workspace work: for a managed canonical worktree, inspect the managed writer with `gbrain sources writer status --probe --json` (legacy bulk push is refused there); otherwise `gbrain sources push --path <workspace>`.
On a managed worktree the persistence coordinator commits and pushes as Git effects; the probe lists `effects`, `blocking_effects` and `recent_failures`, and a parked push is retried with `gbrain sources writer retry-effects <source> --request-id <id>`. gbrain's own ownership stamp (`.gbrain-owner.json`) never counts as uncommitted work, the session hooks never start `sources push` there, and a root with no `origin` remote reads `no_remote` (add one: `git remote add origin <url>`) even after a recorded push refusal. A recorded push failure stops warning once the tree matches its origin branch with nothing uncommitted.
diff --git a/llms-full.txt b/llms-full.txt
index d19692b31f..1788d4dfd1 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1751,6 +1751,35 @@ providers can receive text; Markdown export is not a full database backup.
Read [memory boundaries](docs/guides/memory-boundaries.md) before promising
portability, graph freshness, privacy, or recovery.
+<!-- BEGIN multi-agent-rules (identical in AGENTS.md, BOOTSTRAP_FOR_AGENTS.md and INSTALL_FOR_AGENTS.md; bun run check:shared-tree-git) -->
+## Multi-agent rules for a shared brain checkout
+
+Several agents, crons and hooks often commit to one brain checkout on the same
+machine. In such a checkout:
+
+1. **Commit and push with one command, naming your files:**
+ `scripts/brain-commit-push.sh "<msg>" <paths>`, or
+ `gbrain git commit-push -m "<msg>" -- <paths>` when the brain has no helper.
+ It takes the checkout's writer lock, commits only those paths, merges remote
+ commits without touching anyone else's files, and fails loudly if the push
+ does not land.
+2. **Bring remote commits in with `--pull`** (`scripts/brain-commit-push.sh --pull`
+ or `gbrain git commit-push --pull`) at session start and before a batch of writes.
+3. **On a non-zero exit, read the code.** Retry once on `commit_lock_busy`.
+ Stop and relay to the user on `integrate_conflict` (they choose which
+ version wins) and on `writer_coordinator_required` (a managed brain: save
+ pages with `put_page` instead). `pushed_checkout_lagging` is a success.
+<!-- gbrain-allow-shared-tree-git-begin: the forbidden commands, named so agents avoid them -->
+4. **Never run** `git pull --rebase`, `git stash`, `--autostash`, `git add -A`,
+ `git commit -a`, `git reset --hard` or `git push --force` there, and never
+ fall back to them when the command fails. Never delete `.git/rebase-merge`
+ before saving its autostash with `git stash store`.
+<!-- gbrain-allow-shared-tree-git-end -->
+
+Outcomes, conflict recovery, a stuck rebase and the lock contract for host
+daemons: [docs/guides/shared-checkout-git.md](docs/guides/shared-checkout-git.md).
+<!-- END multi-agent-rules -->
+
## Agent operator protocol
Every gbrain error, refusal, degraded result and recommendation carries the same
@@ -3065,6 +3094,35 @@ gbrain onboard --check --json
See "The onboard surface" below for what the recommendations mean and the
consent gates around unattended remediation.
+<!-- BEGIN multi-agent-rules (identical in AGENTS.md, BOOTSTRAP_FOR_AGENTS.md and INSTALL_FOR_AGENTS.md; bun run check:shared-tree-git) -->
+## Multi-agent rules for a shared brain checkout
+
+Several agents, crons and hooks often commit to one brain checkout on the same
+machine. In such a checkout:
+
+1. **Commit and push with one command, naming your files:**
+ `scripts/brain-commit-push.sh "<msg>" <paths>`, or
+ `gbrain git commit-push -m "<msg>" -- <paths>` when the brain has no helper.
+ It takes the checkout's writer lock, commits only those paths, merges remote
+ commits without touching anyone else's files, and fails loudly if the push
+ does not land.
+2. **Bring remote commits in with `--pull`** (`scripts/brain-commit-push.sh --pull`
+ or `gbrain git commit-push --pull`) at session start and before a batch of writes.
+3. **On a non-zero exit, read the code.** Retry once on `commit_lock_busy`.
+ Stop and relay to the user on `integrate_conflict` (they choose which
+ version wins) and on `writer_coordinator_required` (a managed brain: save
+ pages with `put_page` instead). `pushed_checkout_lagging` is a success.
+<!-- gbrain-allow-shared-tree-git-begin: the forbidden commands, named so agents avoid them -->
+4. **Never run** `git pull --rebase`, `git stash`, `--autostash`, `git add -A`,
+ `git commit -a`, `git reset --hard` or `git push --force` there, and never
+ fall back to them when the command fails. Never delete `.git/rebase-merge`
+ before saving its autostash with `git stash store`.
+<!-- gbrain-allow-shared-tree-git-end -->
+
+Outcomes, conflict recovery, a stuck rebase and the lock contract for host
+daemons: [docs/guides/shared-checkout-git.md](docs/guides/shared-checkout-git.md).
+<!-- END multi-agent-rules -->
+
## Upgrade
When an upgrade crosses v0.60.5.0, confirm a database backup exists before
@@ -6803,7 +6861,10 @@ vars — incident-time escape hatches, not everyday knobs.
(`N uncommitted file(s) not synced`), the sync result object carries an
`uncommitted` summary (surfaced via `sync_brain` over MCP and in
`gbrain dream --json` phase details), and the nightly dream cycle reports
- the sync phase as `warn` instead of a clean run. The fix is to commit the files. If your
+ the sync phase as `warn` instead of a clean run. The fix is to commit the
+ files, naming them: `gbrain git commit-push -m "<msg>" -- <paths>` (or the
+ brain's `scripts/brain-commit-push.sh`), which is safe when other agents
+ share the checkout ([shared-checkout git](shared-checkout-git.md)). If your
workflow legitimately writes without committing, opt in to importing
uncommitted state with `gbrain sync --working-tree` (one run) or
`gbrain config set sync.include_working_tree true` (standing config,
@@ -6840,8 +6901,10 @@ vars — incident-time escape hatches, not everyday knobs.
**Say to your agent:** *"Bring my notes source up to date with its remote."*
9. **Turn automatic pulls off for every source.** On an unmanaged brain,
- autopilot's freshness sync and its per-source cycle run `git pull` for a
- source that has a remote URL. A checkout you keep current yourself (a
+ autopilot's freshness sync and its per-source cycle pull a source that has
+ a remote URL: a fetch, then a fast-forward under the checkout's writer lock
+ with autostash off, so the pull never stashes or rebases files another
+ agent is writing ([shared-checkout git](shared-checkout-git.md)). A checkout you keep current yourself (a
deploy script, a mirror, a branch you rebase by hand) should not be
pulled behind your back:
@@ -6862,7 +6925,9 @@ vars — incident-time escape hatches, not everyday knobs.
## How to Verify
1. **Edit a file and search for the change.** Edit a brain markdown file,
- commit, and push. Wait for the next sync cycle (cron interval or `--watch`
+ then commit and push it with `gbrain git commit-push -m "<msg>" -- <file>`
+ (it must exit 0; on an error code follow
+ [outcomes](shared-checkout-git.md#outcomes)). Wait for the next sync cycle (cron interval or `--watch`
poll). Run `gbrain search "<text from the edit>"`. The updated content
should appear in results. If it returns old content, sync failed.
@@ -9668,10 +9733,14 @@ This is the real test. Edit a brain page, push, wait, search.
```bash
# Example: fix a line in alice-example's page
cd /data/brain
-# Make a small edit to any .md file
-git add -A && git commit -m "test: verify live sync" && git push
+# Make a small edit to one .md file, then commit and push only that file
+gbrain git commit-push -m "test: verify live sync" -- people/alice-example.md
```
+It must exit 0 and print `pushed <sha> to origin/<branch>`. On any other
+result, stop the test and follow [outcomes](guides/shared-checkout-git.md#outcomes)
+(retry once on `commit_lock_busy`; ask the user on `integrate_conflict`).
+
2. Wait for the next sync cycle (cron interval or `--watch` poll).
3. Search for the corrected text:
@@ -10000,7 +10069,7 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p
`bootstrap_push_health` and `gbrain bootstrap status` report only the push record of the workspace named by this machine's bootstrap receipt; another workspace's stale or failed push is listed as such (a warn naming that workspace), never as this workspace's state. `reranker_health` auth warnings are audit-log history (`details.live_probe_performed: false`), not a live check of the key. These warns can appear while every other check reads green; each one names a check that did not run.
-<a id="git-convergence"></a>**`gbrain doctor` warns or fails `git_convergence`, or `bootstrap_push_health` warns that a workspace is ahead?** A Git checkout the brain syncs from (a source's `local_path` or `sync.repo_path`) has commits its upstream does not have, or uncommitted changes, so the system of record on the remote is behind the brain (#5063). Commits not on the upstream warn after 6 hours and fail after 24; uncommitted changes older than 6 hours warn. Doctor compares with the local `@{u}` ref and never fetches, so it is only as fresh as the last fetch; checkouts without an upstream and connector sources are skipped. Commit and push the checkout (`gbrain sources push --path <root>` for a bootstrap workspace, `git push` otherwise). `bootstrap_push_health` no longer reports `ok` on a recent successful push while the workspace still has commits not on origin.
+<a id="git-convergence"></a>**`gbrain doctor` warns or fails `git_convergence`, or `bootstrap_push_health` warns that a workspace is ahead?** A Git checkout the brain syncs from (a source's `local_path` or `sync.repo_path`) has commits its upstream does not have, or uncommitted changes, so the system of record on the remote is behind the brain (#5063). Commits not on the upstream warn after 6 hours and fail after 24; uncommitted changes older than 6 hours warn. Doctor compares with the local `@{u}` ref and never fetches, so it is only as fresh as the last fetch; checkouts without an upstream and connector sources are skipped. Commit and push the checkout (`gbrain sources push --path <root>` for a bootstrap workspace; otherwise commit your files with `gbrain git commit-push -m "<msg>" -- <paths>` and publish waiting commits with `gbrain git commit-push --push-only`, see [shared-checkout git](shared-checkout-git.md#outcomes)). `bootstrap_push_health` no longer reports `ok` on a recent successful push while the workspace still has commits not on origin.
<a id="tracked-ownership-marker"></a>**`gbrain doctor` warns `tracked_ownership_marker`, or `gbrain sources push` / `bootstrap verify` refuses a `.gbrain-owner*.json` or `.gbrain-bootstrap.lock/` path?** An ownership marker (`.gbrain-owner.json`, the `.gbrain-owner-<hash>.json` reservation beside a root, a `.gbrain-owner.json.<uuid>.tmp` staging file) or the bootstrap lock directory was committed to a source checkout (#5186). These files are this machine's claim on the checkout, never brain content, and must not reach a remote. Since this fix gbrain appends their patterns to the checkout's `.git/info/exclude` whenever it stamps or adopts a root, the bootstrap `.gitignore` template lists them, and the push deny list refuses a tracked one while an untracked one is excluded from the commit (`excludedUntracked`). None of that un-tracks a file already in the index: run the `git -C <root> rm --cached <paths>` the check prints (the files stay on disk, gbrain keeps reading them), commit, push, then `gbrain doctor --only tracked_ownership_marker --json`. A root stamped before this fix gains the exclude rule on its next stamp or transfer; until then the deny list is the backstop, and `bootstrap verify`'s `deny_globs` treats a merely-on-disk marker as fine. If a marker already reached a remote, rotate it the same way you would any published credential: the token alone is not remote authority (the reservation that proves ownership lives outside the root), but treat the history as exposed.
diff --git a/llms.txt b/llms.txt
index 0adcb779b5..0acbf67801 100644
--- a/llms.txt
+++ b/llms.txt
@@ -39,6 +39,7 @@ Repo: https://github.com/garrytan/gbrain
- [docs/guides/retrieval-feedback.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/retrieval-feedback.md): Use-attributed retrieval feedback: answer ids, `rate_answer` / `gbrain rate` (whole answer or single pages), how ratings move page weights and ranking (bounded ±λ), citation learning, revision handling, who may teach the brain, `gbrain feedback status|reset`, config keys and every refusal code.
- [docs/guides/pinned-questions.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/pinned-questions.md): Pinned questions: cited answers kept current from your notes (`gbrain questions pin|list|status|refresh|unpin`, `questions_*` MCP tools), read-time staleness, receipts and blocked reasons, owner-private visibility, consent for paid refresh, the standing_questions phase and the dream.auto_think migration.
- [docs/guides/live-sync.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/live-sync.md): Incremental markdown sync setup.
+- [docs/guides/shared-checkout-git.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/shared-checkout-git.md): Committing and pushing when several agents share one brain checkout: `gbrain git commit-push` / `scripts/brain-commit-push.sh` (writer lock, path-scoped commit, in-memory merge, fast-forward-only advance), the outcome table, conflict resolution with --resolve, recovering a stuck rebase, the lock contract for host daemons, and the git commands never to run there.
- [docs/guides/sync-unblock-runbook.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/sync-unblock-runbook.md): Operator-agent loop for a managed catch-up on a live checkout: gbrain sync status --json (cursor, committed_last_10m, each hold and the last error with class / safe_actions / needs_human), gbrain sync unblock --apply, and the decision table (page / connection / systemic) behind them.
- [docs/guides/cron-schedule.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/cron-schedule.md): Recurring job scheduling.
- [docs/guides/minions-deployment.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/minions-deployment.md): Deploying the gbrain jobs worker: crontab + watchdog, inline --follow, systemd/Procfile/fly.toml, upgrade checklist.
diff --git a/package.json b/package.json
index a4ead7ed4c..fcfd75e96d 100644
--- a/package.json
+++ b/package.json
@@ -163,6 +163,7 @@
"check:schema-migrations": "bash scripts/check-schema-migrations-fresh.sh",
"check:schema-fresh": "bash scripts/check-schema-fresh.sh",
"check:retired-phrases": "bash scripts/check-retired-phrases.sh",
+ "check:shared-tree-git": "bash scripts/check-shared-tree-git.sh",
"check:bash32": "bash scripts/check-bash32.sh",
"check:schema-migration-order": "bun scripts/check-schema-migration-order.ts",
"check:compile-autoload": "bash scripts/check-compile-autoload.sh",
diff --git a/plugin-variants/gbrain-coding/skills/brain-link-discipline/SKILL.md b/plugin-variants/gbrain-coding/skills/brain-link-discipline/SKILL.md
index 5408063381..68be2d0822 100644
--- a/plugin-variants/gbrain-coding/skills/brain-link-discipline/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/brain-link-discipline/SKILL.md
@@ -106,10 +106,18 @@ https://<host>/<owner>/<repo>/blob/<branch>/<that-exact-path>
## Sequence (push BEFORE link)
1. Write/edit the brain file.
-2. `git add <file> && git commit -m "..." && git push`
-3. **Verify the push landed** — the push output must show the ref update
- (e.g. `abc123..def456 main -> main`). A hosted URL 404s until the push
- completes.
+2. `scripts/brain-commit-push.sh "<msg>" <file>` (or
+ `gbrain git commit-push -m "<msg>" -- <file>` when the brain has no helper).
+ It commits only that file under the checkout's writer lock and pushes,
+ merging remote commits without touching other agents' files.
+3. **Verify the push landed** — the command must exit 0 and print
+ `pushed <sha> to origin/<branch>` (or `nothing to commit`; a
+ `[gbrain notice]` that the checkout lags is still a landed push). A hosted
+ URL 404s until the push completes. On a non-zero exit, output no link:
+ retry once on `commit_lock_busy`; stop and tell the user on
+ `integrate_conflict` or `writer_coordinator_required`; never fall back to
+ stash, `pull --rebase` or a plain push
+ ([outcomes](https://github.com/garrytan/gbrain/blob/master/docs/guides/shared-checkout-git.md#outcomes)).
4. **In the SAME message that reports the commit, output the link** — as a
clickable markdown link or bare URL, never a backticked code span.
@@ -233,7 +241,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
instead of a link or repo-relative fallback.
- ❌ Committing, then waiting for the user to ask for the link.
- ❌ Relaying a subagent result containing local brain paths verbatim.
-- ❌ Outputting hosted URLs BEFORE `git push` has landed (they 404 until the
+- ❌ Outputting hosted URLs BEFORE the push has landed (they 404 until the
push completes — push first, verify the ref moved, then link).
- ❌ Presenting `gbrain publish` output as a URL. It emits a local HTML file
path; offer it as an attachable artifact.
diff --git a/plugin-variants/gbrain-daily/skills/bulk-ingestion/MANIFEST-PATTERN.md b/plugin-variants/gbrain-daily/skills/bulk-ingestion/MANIFEST-PATTERN.md
index 31da771d82..a06917858d 100644
--- a/plugin-variants/gbrain-daily/skills/bulk-ingestion/MANIFEST-PATTERN.md
+++ b/plugin-variants/gbrain-daily/skills/bulk-ingestion/MANIFEST-PATTERN.md
@@ -138,8 +138,8 @@ file, not a database: there is no compare-and-swap, no row lock, no atomic
process WILL collide — two workers read `pending`, both process the same item,
and you pay twice for the same expensive extraction; worse, two workers writing
the same `manifest.json` concurrently can interleave and corrupt the JSON,
-losing the whole run's state. `git pull --rebase` is NOT synchronization — it
-resolves text conflicts, it does not prevent two workers from having already
+losing the whole run's state. Git is NOT synchronization: merging two
+workers' commits resolves text, it does not stop them from having already
done the same paid work. So the claim is made by PARTITIONING before fan-out:
split the item list into DISJOINT shards (by `group`, or by an offset/limit
range) and hand each worker its own shard. No two workers ever look at the same
@@ -178,9 +178,11 @@ When fanning out processing across chunks/workers/subagents:
When many workers run concurrently, having them all write one JSON races.
Instead each writes `worker-<id>-progress.json` with
`{"processed_ids": [], "stats": {}}`; a merge step folds them into the
-master manifest. (Proven at 20 workers on an email-takeout ingest.) For low
-parallelism (<=4 chunks), direct per-item JSON updates with a
-`git pull --rebase` before each commit is simpler and fine.
+master manifest. (Proven at 20 workers on an email-takeout ingest.) Low
+parallelism (<=4 chunks) is no exception: workers sharing one checkout still
+write per-worker files, because a shared `manifest.json` both races on disk
+and conflicts at commit time. Each worker commits only its own files with
+`scripts/brain-commit-push.sh "<msg>" <its files>`, never with a repo-wide add.
## Periodic commit during long runs
@@ -190,9 +192,18 @@ per [conventions/cron-via-minions.md](../conventions/cron-via-minions.md) —
a recurring shell job shaped like:
```bash
-gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && git add projects/<pipeline-name> <output-dirs> && git commit -m \"<pipeline-name> ingest checkpoint\" && git push"}'
+gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && gbrain git commit-push -m \"<pipeline-name> ingest checkpoint\" -- projects/<pipeline-name> <output-dirs>"}'
```
+`gbrain git commit-push` (or the brain's `scripts/brain-commit-push.sh`)
+takes the checkout's writer lock, commits only the named paths, and merges a
+rejected push without touching other workers' files. A failed checkpoint
+fails the job; read its error: retry once on `commit_lock_busy`, and stop and
+tell the user on `integrate_conflict` or `writer_coordinator_required` (a
+managed brain: checkpoint pages through `put_page` instead). Never fall back to
+stash, `pull --rebase` or a plain push
+([shared-checkout git](https://github.com/garrytan/gbrain/blob/master/docs/guides/shared-checkout-git.md#outcomes)).
+
Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`
(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — see
minion-orchestrator Preconditions. Do not set it yourself: it is an RCE-class
@@ -202,8 +213,9 @@ the daemon lane anyway (the worker's environment decides, not the submitter's).
Pre-commit hooks (privacy/durability) intentionally run on checkpoint
commits — a checkpoint that bypasses them can bank unlintable content.
-Stage explicit paths, never `git add -A` (sweeps unrelated churn). Remove
-the schedule when the job completes.
+Name explicit paths; a repo-wide add sweeps up other writers' unrelated
+churn, which is why `commit-push` refuses to run without paths. Remove the
+schedule when the job completes.
## Hard rules
diff --git a/plugin/skills/brain-link-discipline/SKILL.md b/plugin/skills/brain-link-discipline/SKILL.md
index 5408063381..68be2d0822 100644
--- a/plugin/skills/brain-link-discipline/SKILL.md
+++ b/plugin/skills/brain-link-discipline/SKILL.md
@@ -106,10 +106,18 @@ https://<host>/<owner>/<repo>/blob/<branch>/<that-exact-path>
## Sequence (push BEFORE link)
1. Write/edit the brain file.
-2. `git add <file> && git commit -m "..." && git push`
-3. **Verify the push landed** — the push output must show the ref update
- (e.g. `abc123..def456 main -> main`). A hosted URL 404s until the push
- completes.
+2. `scripts/brain-commit-push.sh "<msg>" <file>` (or
+ `gbrain git commit-push -m "<msg>" -- <file>` when the brain has no helper).
+ It commits only that file under the checkout's writer lock and pushes,
+ merging remote commits without touching other agents' files.
+3. **Verify the push landed** — the command must exit 0 and print
+ `pushed <sha> to origin/<branch>` (or `nothing to commit`; a
+ `[gbrain notice]` that the checkout lags is still a landed push). A hosted
+ URL 404s until the push completes. On a non-zero exit, output no link:
+ retry once on `commit_lock_busy`; stop and tell the user on
+ `integrate_conflict` or `writer_coordinator_required`; never fall back to
+ stash, `pull --rebase` or a plain push
+ ([outcomes](https://github.com/garrytan/gbrain/blob/master/docs/guides/shared-checkout-git.md#outcomes)).
4. **In the SAME message that reports the commit, output the link** — as a
clickable markdown link or bare URL, never a backticked code span.
@@ -233,7 +241,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
instead of a link or repo-relative fallback.
- ❌ Committing, then waiting for the user to ask for the link.
- ❌ Relaying a subagent result containing local brain paths verbatim.
-- ❌ Outputting hosted URLs BEFORE `git push` has landed (they 404 until the
+- ❌ Outputting hosted URLs BEFORE the push has landed (they 404 until the
push completes — push first, verify the ref moved, then link).
- ❌ Presenting `gbrain publish` output as a URL. It emits a local HTML file
path; offer it as an attachable artifact.
diff --git a/plugin/skills/bulk-ingestion/MANIFEST-PATTERN.md b/plugin/skills/bulk-ingestion/MANIFEST-PATTERN.md
index 31da771d82..a06917858d 100644
--- a/plugin/skills/bulk-ingestion/MANIFEST-PATTERN.md
+++ b/plugin/skills/bulk-ingestion/MANIFEST-PATTERN.md
@@ -138,8 +138,8 @@ file, not a database: there is no compare-and-swap, no row lock, no atomic
process WILL collide — two workers read `pending`, both process the same item,
and you pay twice for the same expensive extraction; worse, two workers writing
the same `manifest.json` concurrently can interleave and corrupt the JSON,
-losing the whole run's state. `git pull --rebase` is NOT synchronization — it
-resolves text conflicts, it does not prevent two workers from having already
+losing the whole run's state. Git is NOT synchronization: merging two
+workers' commits resolves text, it does not stop them from having already
done the same paid work. So the claim is made by PARTITIONING before fan-out:
split the item list into DISJOINT shards (by `group`, or by an offset/limit
range) and hand each worker its own shard. No two workers ever look at the same
@@ -178,9 +178,11 @@ When fanning out processing across chunks/workers/subagents:
When many workers run concurrently, having them all write one JSON races.
Instead each writes `worker-<id>-progress.json` with
`{"processed_ids": [], "stats": {}}`; a merge step folds them into the
-master manifest. (Proven at 20 workers on an email-takeout ingest.) For low
-parallelism (<=4 chunks), direct per-item JSON updates with a
-`git pull --rebase` before each commit is simpler and fine.
+master manifest. (Proven at 20 workers on an email-takeout ingest.) Low
+parallelism (<=4 chunks) is no exception: workers sharing one checkout still
+write per-worker files, because a shared `manifest.json` both races on disk
+and conflicts at commit time. Each worker commits only its own files with
+`scripts/brain-commit-push.sh "<msg>" <its files>`, never with a repo-wide add.
## Periodic commit during long runs
@@ -190,9 +192,18 @@ per [conventions/cron-via-minions.md](../conventions/cron-via-minions.md) —
a recurring shell job shaped like:
```bash
-gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && git add projects/<pipeline-name> <output-dirs> && git commit -m \"<pipeline-name> ingest checkpoint\" && git push"}'
+gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && gbrain git commit-push -m \"<pipeline-name> ingest checkpoint\" -- projects/<pipeline-name> <output-dirs>"}'
```
+`gbrain git commit-push` (or the brain's `scripts/brain-commit-push.sh`)
+takes the checkout's writer lock, commits only the named paths, and merges a
+rejected push without touching other workers' files. A failed checkpoint
+fails the job; read its error: retry once on `commit_lock_busy`, and stop and
+tell the user on `integrate_conflict` or `writer_coordinator_required` (a
+managed brain: checkpoint pages through `put_page` instead). Never fall back to
+stash, `pull --rebase` or a plain push
+([shared-checkout git](https://github.com/garrytan/gbrain/blob/master/docs/guides/shared-checkout-git.md#outcomes)).
+
Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`
(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — see
minion-orchestrator Preconditions. Do not set it yourself: it is an RCE-class
@@ -202,8 +213,9 @@ the daemon lane anyway (the worker's environment decides, not the submitter's).
Pre-commit hooks (privacy/durability) intentionally run on checkpoint
commits — a checkpoint that bypasses them can bank unlintable content.
-Stage explicit paths, never `git add -A` (sweeps unrelated churn). Remove
-the schedule when the job completes.
+Name explicit paths; a repo-wide add sweeps up other writers' unrelated
+churn, which is why `commit-push` refuses to run without paths. Remove the
+schedule when the job completes.
## Hard rules
diff --git a/plugin/skills/company-brainify/SKILL.md b/plugin/skills/company-brainify/SKILL.md
index 24af07d03a..14d4a463e4 100644
--- a/plugin/skills/company-brainify/SKILL.md
+++ b/plugin/skills/company-brainify/SKILL.md
@@ -352,11 +352,19 @@ cd "$STAGING"
# ... Phase 4 greps against $STAGING ...
git init -b main
-git add -A && git commit -m "Initial import — sanitized team brain"
+git add -A && git commit -m "Initial import — sanitized team brain" # gbrain-allow-shared-tree-git: first commit of a fresh single-writer export repo
git remote add origin <TEAM_REPO_URL>
-git push -u origin main
+gbrain git commit-push --push-only
```
+The first commit is plain git because `$STAGING` is a brand-new repo only
+this run writes. The push goes through `gbrain git commit-push --push-only`:
+it pushes to `origin/main` and fails loudly if the push does not land. On a
+non-zero exit, stop and tell the user what the error says: usually
+`git_push_unavailable` (check the team repo URL and credentials, then rerun
+it), or a team repo that already has commits (this export needs an empty
+one; ask the user before going further). Never force-push it.
+
Only when a shared repo ALREADY exists with sensitive history in it do you
need the purge below.
@@ -378,11 +386,17 @@ cd "$WORK/shared"
# Apply the sanitized tree, then COMMIT it BEFORE the mirror clone. A mirror
# captures COMMITTED state only; if the clean tree lives only in volatile
# staging during the rewrite window, a crash loses the sanitization work.
-# Committing makes the clean state durable and recoverable.
+# Committing makes the clean state durable and recoverable; pushing it means
+# the remote stops serving the sensitive current versions even if the purge
+# below is declined. Only the sanitized directories are committed. On a
+# non-zero exit stop: retry once on commit_lock_busy; on integrate_conflict
+# someone changed the shared repo meanwhile, so ask the user before going on.
for d in people meetings daily companies projects analysis; do
[ -d "$STAGING/$d" ] && rsync -a "$STAGING/$d/" "./$d/" # or sanitize in place here
done
-git add -A && git commit -m "Sanitize: strip sensitive content before history purge"
+SANITIZED=""
+for d in people meetings daily companies projects analysis; do [ -d "$d" ] && SANITIZED="$SANITIZED $d"; done
+gbrain git commit-push -m "Sanitize: strip sensitive content before history purge" -- $SANITIZED
# Mirror-clone backup = the recoverability line on the card. Capture the path
# in a variable NOW and reuse it verbatim at purge time — a run crossing
@@ -440,7 +454,7 @@ the agent following this skill must not skip it.
**Step 3 — purge (only after the explicit typed yes).** Requires
`git filter-repo` (not bundled with git; install separately). **Run this ONLY
in the shared-repo work dir from Step 1 (`cd "$WORK/shared"`). NEVER run
-`git filter-repo` or `git push --force` in `sync.repo_path` — the personal
+`git filter-repo` or `git push --force` in `sync.repo_path` — the personal <!-- gbrain-allow-shared-tree-git: warns against a force push in the personal brain -->
brain's history must stay intact.** The commands below reuse `$WORK` and
`$BACKUP_PATH` from Step 1; they never recompute a date-stamped path.
@@ -493,7 +507,7 @@ after=$(for d in $PURGE_DIRS; do [ -d "$d" ] && find "$d" -type f; done | wc -l
git -C "$BACKUP_PATH" log -1 >/dev/null \
|| { echo "backup missing/unreadable — ABORT, do not force-push"; exit 1; }
-git push --force origin main
+git push --force origin main # gbrain-allow-shared-tree-git: the confirmed history purge of a private single-writer clone (data-loss-gate answered)
```
**Step 4 — log it (to the PERSONAL brain, NEVER the shared repo).** Per
diff --git a/plugin/skills/schema-author/SKILL.md b/plugin/skills/schema-author/SKILL.md
index 29adec30dc..418851366a 100644
--- a/plugin/skills/schema-author/SKILL.md
+++ b/plugin/skills/schema-author/SKILL.md
@@ -220,15 +220,22 @@ expert-routed types.)
### Phase 7 — Commit (preserve the change)
-If the pack is in source control, commit:
+If the pack is in source control, commit and push only the pack file:
```
cd ~/.gbrain/schema-packs/mine
-git add pack.json
-git commit -m "schema: add researcher + paper types + authored link"
-git push
+gbrain git commit-push -m "schema: add researcher + paper types + authored link" -- pack.json
```
+It takes the checkout's writer lock and merges a rejected push without
+rebasing, so it is safe when other agents share the checkout. On a non-zero
+exit: retry once on `commit_lock_busy`; on `integrate_conflict` stop and ask
+the user which version of `pack.json` wins; on `git_push_unavailable` the
+remote is unreachable (the commit is saved; rerun with `--push-only` later) or,
+when the pack repo has no remote at all, nothing was committed: commit just the
+pack locally with `git add pack.json && git commit -m "<msg>" -- pack.json`. Never fall back to
+stash, `pull --rebase` or a plain push ([outcomes](https://github.com/garrytan/gbrain/blob/master/docs/guides/shared-checkout-git.md#outcomes)).
+
If the brain daemon is running (`gbrain serve --http`), other processes
pick up the change within 1 second (stat-mtime TTL gate in
loadActivePack — v0.40.6.0 closed the cross-process invalidation gap).
diff --git a/recipes/meeting-sync.md b/recipes/meeting-sync.md
index a34d17e420..576d44d15a 100644
--- a/recipes/meeting-sync.md
+++ b/recipes/meeting-sync.md
@@ -342,14 +342,20 @@ tags: [sync]
```
if new_meetings_created > 0:
- shell('git add -A', cwd=BRAIN_DIR)
msg = f'sync: {count} meeting(s) from Circleback ({start} to {end})'
- shell(f'git commit -m "{msg}"', cwd=BRAIN_DIR)
- shell('git push', cwd=BRAIN_DIR)
+ paths = written_paths # the meeting and people files this run wrote
+ run(['scripts/brain-commit-push.sh', msg, *paths], cwd=BRAIN_DIR)
+ # without the helper: ['gbrain', 'git', 'commit-push', '-m', msg, '--', *paths]
```
-The sync script commits and pushes automatically. This triggers GBrain's
-live sync to index the new pages.
+The sync script commits only the files it wrote and pushes them. This
+triggers GBrain's live sync to index the new pages. Other agents may share
+the brain checkout, so it never stages the whole tree. On a non-zero exit
+the script stops and reports the error code: retry once on `commit_lock_busy`;
+stop and tell the user on `integrate_conflict` or
+`writer_coordinator_required` (a managed brain: write the pages with
+`put_page` instead); never fall back to stash, `pull --rebase` or a plain
+push ([outcomes](../docs/guides/shared-checkout-git.md#outcomes)).
### What the Agent Should Test After Setup
diff --git a/scripts/check-shared-tree-git.sh b/scripts/check-shared-tree-git.sh
new file mode 100644
index 0000000000..75878e0b4f
--- /dev/null
+++ b/scripts/check-shared-tree-git.sh
@@ -0,0 +1,205 @@
+#!/usr/bin/env bash
+# CI guard (#6530): agent-facing docs never teach git commands that are unsafe
+# in a brain checkout other agents share.
+#
+# Many writers (sessions, sub-agents, crons, hooks, a host sync daemon) commit
+# to one brain checkout. A rebase there stashes every other writer's edits,
+# a repo-wide add commits their half-written files, and a reset or force push
+# discards them. Agents follow skills, recipes, templates and docs literally,
+# so this guard fails when one of them teaches, in a code block or an inline
+# code span:
+#
+# git pull --rebase (or -r) --autostash git stash (not store/list/show)
+# git add -A / --all / . (unless followed by `--`, i.e. explicit paths)
+# git commit -a / -am / --all git reset --hard git push --force / -f / +ref
+# any other git push (bare push; `git push --dry-run` is read-only and allowed)
+#
+# The safe replacement is `scripts/brain-commit-push.sh` or
+# `gbrain git commit-push` (docs/guides/shared-checkout-git.md).
+#
+# Scanned: skills/, recipes/, templates/, docs/, plugin/, plugin-variants/
+# (*.md, *.template, *.sh) plus AGENTS.md, BOOTSTRAP_FOR_AGENTS.md and
+# INSTALL_FOR_AGENTS.md. In markdown only fenced code blocks and inline code
+# spans are checked; a .sh file is checked whole.
+#
+# Not scanned:
+# - docs/guides/error-codes.md: generated from src/core/error-registry.ts.
+# - docs/RELEASING.md, docs/TESTING.md, docs/contributing/ (and
+# CONTRIBUTING.md, CHANGELOG.md, TODOS.md at the root, which are outside
+# the scanned set): they describe maintainers working in the gbrain SOURCE
+# repository, not agents writing to a brain checkout.
+# - historical records: docs/designs/, docs/plans/, docs/proposals/,
+# docs/research/, docs/incidents/, docs/issues/, docs/test-audit/,
+# docs/superpowers/.
+#
+# Allow a line that must name one of these (a warning, a single-writer clone):
+# same line, inside a code block: <cmd> # gbrain-allow-shared-tree-git: <reason>
+# line before, in prose: <!-- gbrain-allow-shared-tree-git: <reason> -->
+# a region (a "never run" list): <!-- gbrain-allow-shared-tree-git-begin: <reason> -->
+# ...
+# <!-- gbrain-allow-shared-tree-git-end -->
+# A marker without a reason fails.
+#
+# Also checks that the "Multi-agent rules" block (between
+# `<!-- BEGIN multi-agent-rules -->` and `<!-- END multi-agent-rules -->`) is
+# present and identical in every one of AGENTS.md, BOOTSTRAP_FOR_AGENTS.md and
+# INSTALL_FOR_AGENTS.md that exists.
+#
+# Run: bash scripts/check-shared-tree-git.sh [file ...]
+# (with files: scan only those, relative to the root; no block check)
+# Wired into `bun run verify` via package.json `check:shared-tree-git`.
+# Self-test seam: GBRAIN_GUARD_ROOT points at a fixture tree.
+
+set -uo pipefail
+
+ROOT="${GBRAIN_GUARD_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"
+cd "$ROOT" || exit 2
+
+EXEMPT='^(CHANGELOG\.md|TODOS\.md|CONTRIBUTING\.md|docs/guides/error-codes\.md|docs/RELEASING\.md|docs/TESTING\.md|docs/contributing/|docs/(designs|plans|proposals|research|incidents|issues|test-audit|superpowers)/)'
+SEE='docs/guides/shared-checkout-git.md'
+
+LIST="$(mktemp -t gbrain-shared-tree-git-XXXXXX)" || exit 2
+trap 'rm -f "$LIST"' EXIT
+
+if [ "$#" -gt 0 ]; then
+ for f in "$@"; do printf '%s\n' "${f#./}"; done >"$LIST"
+ block_check=0
+else
+ {
+ for f in AGENTS.md BOOTSTRAP_FOR_AGENTS.md INSTALL_FOR_AGENTS.md; do
+ [ -f "$f" ] && printf '%s\n' "$f"
+ done
+ for d in skills recipes templates docs plugin plugin-variants; do
+ [ -d "$d" ] || continue
+ find "$d" -name node_modules -prune -o -type f \( -name '*.md' -o -name '*.template' -o -name '*.sh' \) -print
+ done
+ } | sed 's|^\./||' | grep -vE "$EXEMPT" | LC_ALL=C sort >"$LIST"
+ block_check=1
+fi
+
+# Read with `read -d ''`, never a heredoc inside $(...): macOS /bin/bash 3.2
+# quote-scans that form and dies on the quotes in this program.
+IFS= read -r -d '' AWK_PROG <<'EOF' || true
+function report(kind, frag, fix) {
+ if (kind == "pull-rebase" || kind == "autostash") fix = "bring remote commits in with `scripts/brain-commit-push.sh --pull` or `gbrain git commit-push --pull`; a rebase stashes every other writer's edits"
+ else if (kind == "stash") fix = "never stash a shared checkout; commit only your own paths with `gbrain git commit-push -m <msg> -- <paths>` (git stash store/list/show are allowed)"
+ else if (kind == "add-all" || kind == "commit-all") fix = "stage only the files you wrote: `scripts/brain-commit-push.sh \"<msg>\" <paths>` or `gbrain git commit-push -m <msg> -- <paths>`"
+ else if (kind == "reset-hard") fix = "never reset a shared checkout; it discards other writers' edits (see #stuck-rebase for recovery)"
+ else if (kind == "force-push") fix = "never force-push a brain; a deliberate history rewrite in a private clone carries an allow marker with its reason"
+ else if (kind == "push") fix = "publish with `scripts/brain-commit-push.sh` or `gbrain git commit-push` (`--push-only` for commits already made); they take the writer lock and merge a rejected push safely"
+ else fix = "give the marker its reason: `gbrain-allow-shared-tree-git: <reason>` (or `-begin: <reason>`)"
+ printf "FAIL: %s:%d %s \"%s\"\n", FILENAME, FNR, kind, frag
+ printf "Why: agents follow this text literally in brain checkouts other agents share.\n"
+ printf "Fix: %s.\n", fix
+ printf "See: %s\n", see
+}
+
+function unclosed(f) {
+ printf "FAIL: %s:%d unclosed allow region\n", f, blockline
+ printf "Why: a gbrain-allow-shared-tree-git-begin marker without its end exempts the rest of the file.\n"
+ printf "Fix: close the region with <!-- gbrain-allow-shared-tree-git-end --> right after the lines it covers.\n"
+ printf "See: %s\n", see
+}
+
+function strip(tok) { gsub(/["'`();,]+$/, "", tok); gsub(/^["'`(]+/, "", tok); return tok }
+
+function check(t, s, m, n, parts, i, sub1) {
+ # git pull --rebase / -r
+ s = t
+ while (match(s, G "pull[^|;&]*")) {
+ m = substr(s, RSTART, RLENGTH); s = substr(s, RSTART + RLENGTH)
+ if (m ~ /--rebase/ || m ~ / -r( |$)/) { report("pull-rebase", m); return }
+ }
+ if (t ~ /--autostash/) { report("autostash", "--autostash"); return }
+ s = t
+ while (match(s, G "stash( +[a-z]+)?")) {
+ m = substr(s, RSTART, RLENGTH); s = substr(s, RSTART + RLENGTH)
+ if (m !~ /stash +(store|list|show)$/) { report("stash", m); return }
+ }
+ s = t
+ while (match(s, G "add +[^ ]+( +[^ ]+)?")) {
+ m = substr(s, RSTART, RLENGTH); s = substr(s, RSTART + RLENGTH)
+ sub1 = m; sub(/^.*add +/, "", sub1)
+ n = split(sub1, parts, / +/)
+ parts[1] = strip(parts[1]); if (n >= 2) parts[2] = strip(parts[2]); else parts[2] = ""
+ if (parts[1] == "." || ((parts[1] == "-A" || parts[1] == "--all") && parts[2] != "--")) { report("add-all", m); return }
+ }
+ if (match(t, G "commit +(-[A-Za-z]*a[A-Za-z]*|--all)([^A-Za-z-]|$)")) { report("commit-all", substr(t, RSTART, RLENGTH)); return }
+ if (match(t, G "reset[^|;&]*--hard")) { report("reset-hard", substr(t, RSTART, RLENGTH)); return }
+ s = t
+ while (match(s, G "push([^A-Za-z0-9_-][^|;&]*)?$") || match(s, G "push([^A-Za-z0-9_-][^|;&]*)?[|;&]")) {
+ m = substr(s, RSTART, RLENGTH); s = substr(s, RSTART + RLENGTH)
+ if (m ~ /--dry-run/ || m ~ / -n( |$)/) continue
+ if (m ~ /--force/ || m ~ / -f( |$|[^A-Za-z])/ || m ~ / \+[^ ]/) { report("force-push", m); return }
+ report("push", m); return
+ }
+}
+
+BEGIN { G = "(^|[^A-Za-z0-9_.-])git( +-[Cc] +[^ ]+)* +" }
+
+FNR == 1 {
+ if (lastfile != "" && inblock) unclosed(lastfile)
+ lastfile = FILENAME; infence = 0; inblock = 0; prevallow = 0; issh = (FILENAME ~ /\.sh$/)
+}
+
+{
+ line = $0
+ allow = prevallow
+ prevallow = 0
+ if (index(line, "gbrain-allow-shared-tree-git")) {
+ if (line ~ /^[ \t]*<!-- *gbrain-allow-shared-tree-git-begin: *[^ \t-].*-->[ \t]*$/) { inblock = 1; blockline = FNR; next }
+ if (line ~ /^[ \t]*<!-- *gbrain-allow-shared-tree-git-end *-->[ \t]*$/) { inblock = 0; next }
+ if (line ~ /^[ \t]*<!-- *gbrain-allow-shared-tree-git: *[^ \t-].*-->[ \t]*$/) { prevallow = 1; next }
+ if (line ~ /gbrain-allow-shared-tree-git(-begin)?: *(-->)?[ \t]*$/) { report("allow-marker-without-reason", line); next }
+ if (line ~ /gbrain-allow-shared-tree-git: *[^ \t-]/) allow = 1
+ }
+ if (!issh && line ~ /^[ \t]*(```|~~~)/) { infence = !infence; next }
+ if (allow || inblock) next
+ if (issh || infence) { check(line); next }
+ if (index(line, "`") == 0) next
+ n = split(line, parts, "`")
+ for (i = 2; i <= n; i += 2) check(parts[i])
+}
+
+END { if (lastfile != "" && inblock) unclosed(lastfile) }
+EOF
+
+out=""
+if [ -s "$LIST" ]; then
+ out="$(tr '\n' '\0' <"$LIST" | xargs -0 awk -v see="$SEE" "$AWK_PROG" 2>&1)"
+fi
+
+block_fail=""
+if [ "$block_check" -eq 1 ]; then
+ ref=""; ref_file=""
+ for f in AGENTS.md BOOTSTRAP_FOR_AGENTS.md INSTALL_FOR_AGENTS.md; do
+ [ -f "$f" ] || continue
+ blk="$(sed -n '/<!-- BEGIN multi-agent-rules/,/<!-- END multi-agent-rules -->/p' "$f")"
+ if [ -z "$blk" ]; then
+ block_fail="${block_fail}FAIL: $f has no Multi-agent rules block
+Why: every agent entry doc must carry the shared-checkout rules.
+Fix: copy the block between <!-- BEGIN multi-agent-rules --> and <!-- END multi-agent-rules --> from AGENTS.md.
+See: $SEE
+"
+ continue
+ fi
+ if [ -z "$ref_file" ]; then ref="$blk"; ref_file="$f"
+ elif [ "$blk" != "$ref" ]; then
+ block_fail="${block_fail}FAIL: $f Multi-agent rules block differs from $ref_file
+Why: the three agent entry docs must give agents the same rules.
+Fix: make the block between <!-- BEGIN multi-agent-rules --> and <!-- END multi-agent-rules --> identical in AGENTS.md, BOOTSTRAP_FOR_AGENTS.md and INSTALL_FOR_AGENTS.md.
+See: $SEE
+"
+ fi
+ done
+fi
+
+if [ -n "$out" ] || [ -n "$block_fail" ]; then
+ [ -n "$out" ] && printf '%s\n' "$out" >&2
+ [ -n "$block_fail" ] && printf '%s' "$block_fail" >&2
+ hits=$(printf '%s\n%s' "$out" "$block_fail" | grep -c '^FAIL:')
+ echo "" >&2
+ echo "✗ shared-tree git: $hits hit(s); see $SEE" >&2
+ exit 1
+fi
+echo "✓ shared-tree git: no unsafe git commands in skills, recipes, templates, docs, plugin trees or agent docs"
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
index 44ddaab90e..81af90adae 100644
--- a/scripts/guards-manifest.tsv
+++ b/scripts/guards-manifest.tsv
@@ -75,6 +75,7 @@ check-windows-hide.ts scanner yes #4992 Windows hidden consoles (TS AST): runtim
check-schema-migrations-fresh.sh buildfresh exempt regenerates src/core/schema-migrations/registry.generated.ts + diffs; generator enforces filename/version/name cross-check and duplicate versions (unit: test/scripts/build-schema-migrations.test.ts)
check-schema-fresh.sh buildfresh exempt W2: regenerates the schema chain (fragments -> schema.sql regions -> schema-embedded -> PGLite template) into a temp dir and diffs every output; names the source to edit (unit: test/scripts/build-schema.test.ts)
check-retired-phrases.sh scanner yes W7 (refactor wave 1): retired contributor-workflow phrases (migrations array, two-engine SQL rule, CLI switch case, region policy, hand-synced PGLite schema) fail in CLAUDE.md, AGENTS.md, CONTRIBUTING.md, docs/, skills/; historical records and the porting kit exempt; GBRAIN_GUARD_ROOT seam; bad-<location> fixtures
+check-shared-tree-git.sh scanner yes #6530: unsafe shared-checkout git (pull --rebase, autostash, stash, repo-wide add/commit, reset --hard, bare or force push) fails in fenced code and inline code under skills/, recipes/, templates/, docs/, plugin trees and the three agent docs; allow markers with a reason; multi-agent rules block identical in AGENTS/BOOTSTRAP/INSTALL; GBRAIN_GUARD_ROOT seam; bad-<variant> fixtures
check-bash32.sh scanner todo #5810: every tracked *.sh parses under bash 3.2 (real parser: GBRAIN_BASH32, stock macOS /bin/bash, or the digest-pinned bash:3.2 image); not in verify CHECKS or this self-test, which must not need Docker; its bad/good fixtures run in test/scripts/check-bash32.test.ts, mandatory in the test.yml verify-job step (GBRAIN_TEST_BASH32_REQUIRE=1)
check-schema-migration-order.ts repostate exempt EO10: a migration origin/master lacks must be numbered above its latest version; reads the base ref from git (unit: test/scripts/build-schema-migrations.test.ts)
check-structural-manifest.sh buildfresh exempt regenerate+diff of structural-suites.tsv (classify-tests.ts); the diff IS the self-test
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index fe82b5c99b..fa1a10eb6f 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -173,6 +173,13 @@ export const SECTIONS: DocSection[] = [
description: "Incremental markdown sync setup.",
path: "docs/guides/live-sync.md",
},
+ {
+ title: "docs/guides/shared-checkout-git.md",
+ description:
+ "Committing and pushing when several agents share one brain checkout: `gbrain git commit-push` / `scripts/brain-commit-push.sh` (writer lock, path-scoped commit, in-memory merge, fast-forward-only advance), the outcome table, conflict resolution with --resolve, recovering a stuck rebase, the lock contract for host daemons, and the git commands never to run there.",
+ path: "docs/guides/shared-checkout-git.md",
+ includeInFull: false,
+ },
{
title: "docs/guides/sync-unblock-runbook.md",
description: "Operator-agent loop for a managed catch-up on a live checkout: gbrain sync status --json (cursor, committed_last_10m, each hold and the last error with class / safe_actions / needs_human), gbrain sync unblock --apply, and the decision table (page / connection / systemic) behind them.",
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index ff3de4a518..fff9ce6e21 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -191,6 +191,10 @@ CHECKS=(
# W7 (refactor wave 1): workflow phrases the wave retired stay out of the
# docs agents follow (CLAUDE.md, AGENTS.md, CONTRIBUTING.md, docs/, skills/).
"check:retired-phrases"
+ # #6530: skills, recipes, templates, docs, plugin trees and agent docs never
+ # teach git pull --rebase, stash, autostash, repo-wide add/commit, reset
+ # --hard or a bare/force push for a shared brain checkout (~0.5s).
+ "check:shared-tree-git"
"check:schema-migration-order"
"check:structural-manifest"
# Every generated artifact's freshness in one place (GBRA-47 B8); its Fix
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index e70ec07fd7..4a0cdc355d 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -190,6 +190,7 @@ test/fts-language-migration.serial.test.ts R1 R1: mutates process.env (bracket o
test/fts-language-schema-replay.serial.test.ts R1 R1: mutates process.env (GBRAIN_PGLITE_SNAPSHOT)
test/fts-language.serial.test.ts R1 R1: mutates process.env (bracket or computed key)
test/gateway-reconfigure-clobber.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
+test/git-commit-push-6530.serial.test.ts R1 R1: mutates process.env (GBRAIN_GIT_ALLOW_FILE_TRANSPORT, BRAIN_COMMIT_LOCK_HELD, GBRAIN_GIT_NO_MERGE_TREE, PATH for a racing git shim)
test/git-listing-memo.serial.test.ts R1 R1: puts a git-counting shim on process.env.PATH for every spawn in the process (git child processes inherit it, so withEnv cannot scope it)
test/git-remote-durable.serial.test.ts R1 R1: mutates process.env (GBRAIN_GIT_ALLOW_FILE_TRANSPORT)
test/git-remote-pull-file-transport.serial.test.ts R1 R1: mutates process.env (GBRAIN_GIT_ALLOW_FILE_TRANSPORT)
diff --git a/skills/brain-link-discipline/SKILL.md b/skills/brain-link-discipline/SKILL.md
index cf9caf8027..2111548c86 100644
--- a/skills/brain-link-discipline/SKILL.md
+++ b/skills/brain-link-discipline/SKILL.md
@@ -105,10 +105,18 @@ https://<host>/<owner>/<repo>/blob/<branch>/<that-exact-path>
## Sequence (push BEFORE link)
1. Write/edit the brain file.
-2. `git add <file> && git commit -m "..." && git push`
-3. **Verify the push landed** — the push output must show the ref update
- (e.g. `abc123..def456 main -> main`). A hosted URL 404s until the push
- completes.
+2. `scripts/brain-commit-push.sh "<msg>" <file>` (or
+ `gbrain git commit-push -m "<msg>" -- <file>` when the brain has no helper).
+ It commits only that file under the checkout's writer lock and pushes,
+ merging remote commits without touching other agents' files.
+3. **Verify the push landed** — the command must exit 0 and print
+ `pushed <sha> to origin/<branch>` (or `nothing to commit`; a
+ `[gbrain notice]` that the checkout lags is still a landed push). A hosted
+ URL 404s until the push completes. On a non-zero exit, output no link:
+ retry once on `commit_lock_busy`; stop and tell the user on
+ `integrate_conflict` or `writer_coordinator_required`; never fall back to
+ stash, `pull --rebase` or a plain push
+ ([outcomes](https://github.com/garrytan/gbrain/blob/master/docs/guides/shared-checkout-git.md#outcomes)).
4. **In the SAME message that reports the commit, output the link** — as a
clickable markdown link or bare URL, never a backticked code span.
@@ -232,7 +240,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
instead of a link or repo-relative fallback.
- ❌ Committing, then waiting for the user to ask for the link.
- ❌ Relaying a subagent result containing local brain paths verbatim.
-- ❌ Outputting hosted URLs BEFORE `git push` has landed (they 404 until the
+- ❌ Outputting hosted URLs BEFORE the push has landed (they 404 until the
push completes — push first, verify the ref moved, then link).
- ❌ Presenting `gbrain publish` output as a URL. It emits a local HTML file
path; offer it as an attachable artifact.
diff --git a/skills/bulk-ingestion/MANIFEST-PATTERN.md b/skills/bulk-ingestion/MANIFEST-PATTERN.md
index 31da771d82..a06917858d 100644
--- a/skills/bulk-ingestion/MANIFEST-PATTERN.md
+++ b/skills/bulk-ingestion/MANIFEST-PATTERN.md
@@ -138,8 +138,8 @@ file, not a database: there is no compare-and-swap, no row lock, no atomic
process WILL collide — two workers read `pending`, both process the same item,
and you pay twice for the same expensive extraction; worse, two workers writing
the same `manifest.json` concurrently can interleave and corrupt the JSON,
-losing the whole run's state. `git pull --rebase` is NOT synchronization — it
-resolves text conflicts, it does not prevent two workers from having already
+losing the whole run's state. Git is NOT synchronization: merging two
+workers' commits resolves text, it does not stop them from having already
done the same paid work. So the claim is made by PARTITIONING before fan-out:
split the item list into DISJOINT shards (by `group`, or by an offset/limit
range) and hand each worker its own shard. No two workers ever look at the same
@@ -178,9 +178,11 @@ When fanning out processing across chunks/workers/subagents:
When many workers run concurrently, having them all write one JSON races.
Instead each writes `worker-<id>-progress.json` with
`{"processed_ids": [], "stats": {}}`; a merge step folds them into the
-master manifest. (Proven at 20 workers on an email-takeout ingest.) For low
-parallelism (<=4 chunks), direct per-item JSON updates with a
-`git pull --rebase` before each commit is simpler and fine.
+master manifest. (Proven at 20 workers on an email-takeout ingest.) Low
+parallelism (<=4 chunks) is no exception: workers sharing one checkout still
+write per-worker files, because a shared `manifest.json` both races on disk
+and conflicts at commit time. Each worker commits only its own files with
+`scripts/brain-commit-push.sh "<msg>" <its files>`, never with a repo-wide add.
## Periodic commit during long runs
@@ -190,9 +192,18 @@ per [conventions/cron-via-minions.md](../conventions/cron-via-minions.md) —
a recurring shell job shaped like:
```bash
-gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && git add projects/<pipeline-name> <output-dirs> && git commit -m \"<pipeline-name> ingest checkpoint\" && git push"}'
+gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && gbrain git commit-push -m \"<pipeline-name> ingest checkpoint\" -- projects/<pipeline-name> <output-dirs>"}'
```
+`gbrain git commit-push` (or the brain's `scripts/brain-commit-push.sh`)
+takes the checkout's writer lock, commits only the named paths, and merges a
+rejected push without touching other workers' files. A failed checkpoint
+fails the job; read its error: retry once on `commit_lock_busy`, and stop and
+tell the user on `integrate_conflict` or `writer_coordinator_required` (a
+managed brain: checkpoint pages through `put_page` instead). Never fall back to
+stash, `pull --rebase` or a plain push
+([shared-checkout git](https://github.com/garrytan/gbrain/blob/master/docs/guides/shared-checkout-git.md#outcomes)).
+
Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`
(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — see
minion-orchestrator Preconditions. Do not set it yourself: it is an RCE-class
@@ -202,8 +213,9 @@ the daemon lane anyway (the worker's environment decides, not the submitter's).
Pre-commit hooks (privacy/durability) intentionally run on checkpoint
commits — a checkpoint that bypasses them can bank unlintable content.
-Stage explicit paths, never `git add -A` (sweeps unrelated churn). Remove
-the schedule when the job completes.
+Name explicit paths; a repo-wide add sweeps up other writers' unrelated
+churn, which is why `commit-push` refuses to run without paths. Remove the
+schedule when the job completes.
## Hard rules
diff --git a/skills/company-brainify/SKILL.md b/skills/company-brainify/SKILL.md
index 5ad70f2617..43526a69f5 100644
--- a/skills/company-brainify/SKILL.md
+++ b/skills/company-brainify/SKILL.md
@@ -351,11 +351,19 @@ cd "$STAGING"
# ... Phase 4 greps against $STAGING ...
git init -b main
-git add -A && git commit -m "Initial import — sanitized team brain"
+git add -A && git commit -m "Initial import — sanitized team brain" # gbrain-allow-shared-tree-git: first commit of a fresh single-writer export repo
git remote add origin <TEAM_REPO_URL>
-git push -u origin main
+gbrain git commit-push --push-only
```
+The first commit is plain git because `$STAGING` is a brand-new repo only
+this run writes. The push goes through `gbrain git commit-push --push-only`:
+it pushes to `origin/main` and fails loudly if the push does not land. On a
+non-zero exit, stop and tell the user what the error says: usually
+`git_push_unavailable` (check the team repo URL and credentials, then rerun
+it), or a team repo that already has commits (this export needs an empty
+one; ask the user before going further). Never force-push it.
+
Only when a shared repo ALREADY exists with sensitive history in it do you
need the purge below.
@@ -377,11 +385,17 @@ cd "$WORK/shared"
# Apply the sanitized tree, then COMMIT it BEFORE the mirror clone. A mirror
# captures COMMITTED state only; if the clean tree lives only in volatile
# staging during the rewrite window, a crash loses the sanitization work.
-# Committing makes the clean state durable and recoverable.
+# Committing makes the clean state durable and recoverable; pushing it means
+# the remote stops serving the sensitive current versions even if the purge
+# below is declined. Only the sanitized directories are committed. On a
+# non-zero exit stop: retry once on commit_lock_busy; on integrate_conflict
+# someone changed the shared repo meanwhile, so ask the user before going on.
for d in people meetings daily companies projects analysis; do
[ -d "$STAGING/$d" ] && rsync -a "$STAGING/$d/" "./$d/" # or sanitize in place here
done
-git add -A && git commit -m "Sanitize: strip sensitive content before history purge"
+SANITIZED=""
+for d in people meetings daily companies projects analysis; do [ -d "$d" ] && SANITIZED="$SANITIZED $d"; done
+gbrain git commit-push -m "Sanitize: strip sensitive content before history purge" -- $SANITIZED
# Mirror-clone backup = the recoverability line on the card. Capture the path
# in a variable NOW and reuse it verbatim at purge time — a run crossing
@@ -439,7 +453,7 @@ the agent following this skill must not skip it.
**Step 3 — purge (only after the explicit typed yes).** Requires
`git filter-repo` (not bundled with git; install separately). **Run this ONLY
in the shared-repo work dir from Step 1 (`cd "$WORK/shared"`). NEVER run
-`git filter-repo` or `git push --force` in `sync.repo_path` — the personal
+`git filter-repo` or `git push --force` in `sync.repo_path` — the personal <!-- gbrain-allow-shared-tree-git: warns against a force push in the personal brain -->
brain's history must stay intact.** The commands below reuse `$WORK` and
`$BACKUP_PATH` from Step 1; they never recompute a date-stamped path.
@@ -492,7 +506,7 @@ after=$(for d in $PURGE_DIRS; do [ -d "$d" ] && find "$d" -type f; done | wc -l
git -C "$BACKUP_PATH" log -1 >/dev/null \
|| { echo "backup missing/unreadable — ABORT, do not force-push"; exit 1; }
-git push --force origin main
+git push --force origin main # gbrain-allow-shared-tree-git: the confirmed history purge of a private single-writer clone (data-loss-gate answered)
```
**Step 4 — log it (to the PERSONAL brain, NEVER the shared repo).** Per
diff --git a/skills/migrations/v0.40.5.md b/skills/migrations/v0.40.5.md
index 9f4f946c52..bcf10e9d3c 100644
--- a/skills/migrations/v0.40.5.md
+++ b/skills/migrations/v0.40.5.md
@@ -96,7 +96,7 @@ Per-source lock + migration v92 stay on regardless (those are correctness fixes,
After completing the steps above:
1. **Parallel sync works:** `gbrain sync --all` should complete noticeably faster than before. If multiple sources used to take minutes-to-hours, you should see them run concurrently.
-2. **Webhook fires:** `git push` to a webhook-configured source should produce a `[dispatch]` line in autopilot logs (or `gbrain jobs list` should show a fresh `sync` job within seconds).
+2. **Webhook fires:** a push (`gbrain git commit-push`) to a webhook-configured source should produce a `[dispatch]` line in autopilot logs (or `gbrain jobs list` should show a fresh `sync` job within seconds).
3. **Dashboard is accurate:** `gbrain sources status` should match the numbers from `gbrain stats` per source.
4. **No regressions:** Existing `gbrain sync --source <id>` still works the same way; `gbrain sync` with no flags still syncs the default source.
diff --git a/skills/schema-author/SKILL.md b/skills/schema-author/SKILL.md
index 6baeb5a3b3..49ecc1362e 100644
--- a/skills/schema-author/SKILL.md
+++ b/skills/schema-author/SKILL.md
@@ -219,15 +219,22 @@ expert-routed types.)
### Phase 7 — Commit (preserve the change)
-If the pack is in source control, commit:
+If the pack is in source control, commit and push only the pack file:
```
cd ~/.gbrain/schema-packs/mine
-git add pack.json
-git commit -m "schema: add researcher + paper types + authored link"
-git push
+gbrain git commit-push -m "schema: add researcher + paper types + authored link" -- pack.json
```
+It takes the checkout's writer lock and merges a rejected push without
+rebasing, so it is safe when other agents share the checkout. On a non-zero
+exit: retry once on `commit_lock_busy`; on `integrate_conflict` stop and ask
+the user which version of `pack.json` wins; on `git_push_unavailable` the
+remote is unreachable (the commit is saved; rerun with `--push-only` later) or,
+when the pack repo has no remote at all, nothing was committed: commit just the
+pack locally with `git add pack.json && git commit -m "<msg>" -- pack.json`. Never fall back to
+stash, `pull --rebase` or a plain push ([outcomes](https://github.com/garrytan/gbrain/blob/master/docs/guides/shared-checkout-git.md#outcomes)).
+
If the brain daemon is running (`gbrain serve --http`), other processes
pick up the change within 1 second (stat-mtime TTL gate in
loadActivePack — v0.40.6.0 closed the cross-process invalidation gap).
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 412e3d7230..7149be1c4c 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -18,7 +18,7 @@
"book-mirror/routing-eval.jsonl": "79fd23642cfa37b1255a799907e71bb2904585cf79dd6a596e3a2f019787e54c",
"brain-ingest-gate/SKILL.md": "0c382dc55df9b7b991fd6b8ad367fc9b7ac17ebe5e8610c0740ff32234fdc82b",
"brain-ingest-gate/routing-eval.jsonl": "281e94affbb8631ef7ff44203884cce1c03c468b27f893829da1e6e439401a33",
- "brain-link-discipline/SKILL.md": "4606cffb3d219aa9b89e71d1770ad9a916f07a28dece9a8a4ce700392f1262ca",
+ "brain-link-discipline/SKILL.md": "db2a77319475dd8eb370e9a3bb0eafe81d3b19d2de126113b30df7454dd9a069",
"brain-link-discipline/routing-eval.jsonl": "0adea4c6d72fdb849c12fe2cad718568b9ab704299b00b093c40c2284faf684c",
"brain-ops/SKILL.md": "10dc45cea79792457ea457c05e2cfe50654b7de497ff60fd6399a74765e56d45",
"brain-pdf/SKILL.md": "2dfffd2373f00b5f11c1e4b39a75be48e90870201b4c11979d520bd5975dcae4",
@@ -27,7 +27,7 @@
"brain-taxonomist/routing-eval.jsonl": "8b485b3d735aace60be703854f0f2e9d97c52d52564efdaf7334a0c39e8d20ae",
"briefing/SKILL.md": "9c99cee1e3e6177bfcbaabdc84aab0d9d786db4075b4875ec2e70b80570608bb",
"briefing/routing-eval.jsonl": "c056fea88f673e324d6a72cb70438cd6fcdbd09ec2cd036d44eb31a9ea6bf33d",
- "bulk-ingestion/MANIFEST-PATTERN.md": "6180f09d2dc8d9af5749149f2b3c34c40213f5d6b262b69484e864adbb652b47",
+ "bulk-ingestion/MANIFEST-PATTERN.md": "deb3abad5d8026822a663810abb1f39d60df8bb797a42587ffa6d44eefa15a0b",
"bulk-ingestion/SKILL.md": "18000b3c78fd95fffbe075722cf968b860dde2b0d1b601ef7e7085cde8a24225",
"bulk-ingestion/routing-eval.jsonl": "2bf8ffaf90b8ef761fa3cef54bf3af2eb8cc3ef736d054b5bf8b9361f6448d5a",
"capture/SKILL.md": "11434d995ae4d2d40211f3593f75fa48b3b0e6b6c5445547476462510f63da7f",
@@ -38,7 +38,7 @@
"citation-graph-ingest/SKILL.md": "3c8c4abea96769458e9781ce2f5f305c75118fcb5f68cc62b5e1ed7774259035",
"citation-graph-ingest/routing-eval.jsonl": "a1ba605d35e736b741b9e8aac1e7d50b61a7cbcada893d67099b55bf5a0d2635",
"cold-start/SKILL.md": "57d09cff758c48965cb25b2ec2cf317dcf014c22d9610bee83cfe581cf1a9f76",
- "company-brainify/SKILL.md": "f82a78337021f3cc87ad3e3674b3fbc94698193aff772e458375a3eb144ddf11",
+ "company-brainify/SKILL.md": "89e8cae702d468628d110119e325cece897cd15066c7cc7d27e990021904fc04",
"company-brainify/routing-eval.jsonl": "6f27f835eda9ae77a2b694534c78a043a871349820e8c638c3d8bbba6d3aa17b",
"concept-synthesis/SKILL.md": "a5c67f981c5d0a0ef4f13134ed8602e08b0bfbe289456213b8cd465a7a009220",
"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e",
@@ -132,7 +132,7 @@
"migrations/v0.36.2.0.md": "18f72475a0c0de1489c518219128d331d8ed6b0cdcacfb329e18fbcc643d9c6e",
"migrations/v0.36.5.0.md": "889f42508c28835c99242ec20b610ab002f20cda821cb99039589a212cac2ce0",
"migrations/v0.40.3.0.md": "ec6c3a7c1c2c1d1e78115fb43b35b293134da9405763b56016b55e9ea5da1121",
- "migrations/v0.40.5.md": "f66047f1b6ef18b5b5e35445d61c0a1fe44e3c0f9e1c7a51c6b2342c67a0d92f",
+ "migrations/v0.40.5.md": "92f0fce78502356c0ac5b50d043070b4002455026237004dd3ef7f05584e95b6",
"migrations/v0.41.11.0.md": "75c9741617de4c163052609e64734b4696a1105d3d015ed451097eaf6ea1eb3c",
"migrations/v0.46.3.0.md": "add5bdace741f8f0a75a114e354aa8ea3bcadf4cb54e1823338fdc69a5ae3f5d",
"migrations/v0.46.35.0.md": "145c841d89c4b6b6f7089126354fae272df7db6ceaf9cfcec2797d3301cdab57",
@@ -204,7 +204,7 @@
"research-compendium/routing-eval.jsonl": "7446cdcaf9c43fe2e20aaf129a705f13a7743f5f14455a7a21c663572def9078",
"resolve-before-asking/SKILL.md": "ba5aa2ce7bf45116052625eb14fe90f0cc807b4b1490a4646b1cee11b888e897",
"resolve-before-asking/routing-eval.jsonl": "bac1bcf30337f5255ef4ce1a2a8a2b38d58ebcd576503c483190c79ec6e69489",
- "schema-author/SKILL.md": "549d7d14ae3efd3f9a6189850bf30ecc9911f61a92d2d8e9ff1d52a99dc765fa",
+ "schema-author/SKILL.md": "38efb8b48399a2dc526d7084579aa265b2ab232882605bc2f86f6ba2869619f5",
"schema-unify/SKILL.md": "36259f1510fd693253535bd203e32db1bfa24aaae7278c7a2e8b7d6859022708",
"setup/SKILL.md": "d6b82f858e60699ff8c5ee82d61c94a98c2fbc7a852b5f74571e7ab3f0921139",
"signal-detector/SKILL.md": "426a8a3b01a007dd25638e61adef510c18c3d9ce6f1c18ba3d77fdfcd3281d60",
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index 9058f8e4c3..ecad4e7b10 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -194,6 +194,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// update cache would spawn a detached network-touching check-update child per prompt and emit
// UPGRADE_AVAILABLE stderr per turn. NOTE: this path no-ops under NODE_ENV=test, so membership is
// pinned by a source grep (test/hook-command.serial.test.ts), not a runtime test.
+ // CLI_ONLY (#6530): shared-checkout-safe commit/push/pull; DB-free, pushes with host git credentials, never MCP.
+ { name: 'git', phase: 'pre-connect', thinClient: 'none', selfHelp: true, skipStartupHooks: true, load: () => import('./commands/git.ts') },
{ name: 'hook', phase: 'pre-connect', thinClient: 'none', selfHelp: true, skipStartupHooks: true, load: () => import('./commands/hook.ts') },
// CLI_ONLY: Monthly backup-coverage check (engine via thunk — pre-engine branch, lock-safe).
// selfHelp: backup ships its own HELP (runBackupCli guard, engine-free — the command dispatches in
diff --git a/src/cli/commands/git.ts b/src/cli/commands/git.ts
new file mode 100644
index 0000000000..f16766d0b3
--- /dev/null
+++ b/src/cli/commands/git.ts
@@ -0,0 +1,10 @@
+/**
+ * `gbrain git`: pre-connect dispatch (engine-free, DB-free). The record lives
+ * in src/cli/command-table.ts; the behavior in src/commands/git.ts (#6530).
+ */
+import { setCliExitVerdict } from '../../core/cli-force-exit.ts';
+
+export async function run(args: string[]): Promise<void> {
+ const { runGit } = await import('../../commands/git.ts');
+ setCliExitVerdict(await runGit(args));
+}
diff --git a/src/cli/top-help.ts b/src/cli/top-help.ts
index d842103396..b967237341 100644
--- a/src/cli/top-help.ts
+++ b/src/cli/top-help.ts
@@ -149,6 +149,8 @@ SOURCES (multi-repo / multi-brain)
current, federate, set-cr-mode, webhook, harden, ...)
sync --all Sync all sources with a local_path
sync --source <id> Sync one specific source
+ git commit-push -m <m> -- <paths> Commit + push only those paths in a shared checkout
+ (lock, in-memory merge, no rebase/stash); --pull, --push-only
repos ... DEPRECATED alias for 'sources' (v0.19.0)
CODE INDEXING (v0.19.0 / v0.20.0 Cathedral II)
diff --git a/src/commands/check-resolvable.ts b/src/commands/check-resolvable.ts
index 9a2dd9bf4c..f6b40d4cec 100644
--- a/src/commands/check-resolvable.ts
+++ b/src/commands/check-resolvable.ts
@@ -238,7 +238,7 @@ function printAutoFixHuman(autoFix: AutoFixReport, dryRun: boolean): void {
const label = dryRun ? 'fixes proposed' : 'fixes applied';
console.log(`${n} ${label}${s > 0 ? `, ${s} skipped:` : '.'}`);
for (const sk of autoFix.skipped) {
- const hint = sk.reason === 'working_tree_dirty' ? ' (run `git stash` first)' : '';
+ const hint = sk.reason === 'working_tree_dirty' ? ' (commit or discard your edits to those files first)' : '';
console.log(` - ${sk.skillPath}: ${sk.reason}${hint}`);
}
if (dryRun && n > 0) console.log('Run without --dry-run to apply.\n');
diff --git a/src/commands/doctor/checks/skill-group.ts b/src/commands/doctor/checks/skill-group.ts
index 554b39302d..fa002dea84 100644
--- a/src/commands/doctor/checks/skill-group.ts
+++ b/src/commands/doctor/checks/skill-group.ts
@@ -208,7 +208,7 @@ function printAutoFixReport(report: AutoFixReport, dryRun: boolean, jsonOutput:
const label = dryRun ? 'fixes proposed' : 'fixes applied';
console.log(`${n} ${label}${s > 0 ? `, ${s} skipped:` : '.'}`);
for (const sk of report.skipped) {
- const hint = sk.reason === 'working_tree_dirty' ? ' (run `git stash` first)' : '';
+ const hint = sk.reason === 'working_tree_dirty' ? ' (commit or discard your edits to those files first)' : '';
console.log(` - ${sk.skillPath}: ${sk.reason}${hint}`);
}
if (dryRun && n > 0) console.log('\nRun without --dry-run to apply.');
diff --git a/src/commands/git.ts b/src/commands/git.ts
new file mode 100644
index 0000000000..92ffe93a6a
--- /dev/null
+++ b/src/commands/git.ts
@@ -0,0 +1,180 @@
+/**
+ * `gbrain git commit-push` (#6530): the one way an agent, cron or skill
+ * commits and pushes in a brain checkout that other writers share. DB-free
+ * and trusted-local only (it pushes with this host's git credentials); the
+ * protocol lives in src/core/git/commit-push.ts.
+ *
+ * gbrain git commit-push [--path <dir>] -m <msg> [--json] [--] <paths…>
+ * gbrain git commit-push --push-only [--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…>
+ */
+import { commitAndPush, checkoutRoot, pullShared, scopePaths, COMMIT_LOCK_NAME, type Resolution } from '../core/git/commit-push.ts';
+import { appendPushLog } from '../core/brain-repo-durability.ts';
+import { opError } from '../core/ops/contract.ts';
+import { writeCliError } from '../cli/cli-error.ts';
+import { writeStdoutFinal } from '../core/cli-force-exit.ts';
+import { execFileSync } from '../core/spawn.ts';
+import { gitChildEnv } from '../core/git-env.ts';
+import { GIT_ENV } from '../core/git-transport.ts';
+
+const HELP = `Usage: gbrain git commit-push [--path <dir>] -m <msg> [--json] [--] <paths...>
+ gbrain git commit-push --push-only [--path <dir>] [--branch <b>]
+ gbrain git commit-push --push-only [--path <dir>] --expect-remote <sha> --resolve <path>=ours|theirs|file:<file>...
+ gbrain git commit-push --pull [--path <dir>] [--require-clean]
+
+Commit only the named paths and push them, safely, in a checkout other agents
+share: a short commit lock and a separate push lock per checkout, no
+rebase/stash/reset of the working tree, remote commits merged in memory, and the
+checkout advanced fast-forward only.
+
+Flags:
+ --path <dir> Checkout to act on (default: the checkout containing the cwd).
+ -m, --message <m> Commit message (required unless --push-only or --pull).
+ --push-only Publish commits already on the branch; commit nothing.
+ --branch <name> With --push-only: publish HEAD to this remote branch (one exact name).
+ --pull Bring remote commits in (fast-forward, or an in-memory merge); never pushes.
+ --require-clean Unattended rule: --pull skips when the checkout has any local edit;
+ a push never advances a checkout that has one, and never waits for
+ another push (it asks that push to publish HEAD too: push_deferred).
+ --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.
+ --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 current
+directory. Exit 0 on pushed, nothing_to_commit, push_deferred and
+pushed_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`;
+
+interface Parsed {
+ sub?: string; path?: string; message?: string; branch?: string; expectRemote?: string; json: boolean; pushOnly: boolean; pull: boolean;
+ requireClean: boolean; dryRun: boolean; help: boolean; paths: string[]; resolve: string[];
+}
+
+function parse(args: string[]): Parsed {
+ const p: Parsed = { json: false, pushOnly: false, pull: false, requireClean: false, dryRun: false, help: false, paths: [], resolve: [] };
+ let rest = false;
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ if (rest) { p.paths.push(a); continue; }
+ const take = (name: string): string => {
+ const eq = a.indexOf('=');
+ if (a.startsWith('--') && eq !== -1) return a.slice(eq + 1);
+ const v = args[++i];
+ if (v === undefined) throw opError('commit_paths_invalid', `${name} needs a value.`, HELP.split('\n')[0]);
+ return v;
+ };
+ if (a === '--') rest = true;
+ else if (a === '--help' || a === '-h') p.help = true;
+ else if (a === '--json') p.json = true;
+ else if (a === '--push-only') p.pushOnly = true;
+ 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 === '--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'));
+ else if (a === '--branch' || a.startsWith('--branch=')) p.branch = take('--branch');
+ else if (a === '--expect-remote' || a.startsWith('--expect-remote=')) p.expectRemote = take('--expect-remote');
+ else if (!p.sub) p.sub = a;
+ else if (a.startsWith('-')) throw opError('commit_paths_invalid', `Unknown flag ${a}.`, HELP.split('\n')[0]);
+ else p.paths.push(a);
+ }
+ return p;
+}
+
+function parseResolutions(specs: string[]): Map<string, Resolution> {
+ const out = new Map<string, Resolution>();
+ for (const spec of specs) {
+ const eq = spec.lastIndexOf('=');
+ const path = eq > 0 ? spec.slice(0, eq) : '';
+ const choice = eq > 0 ? spec.slice(eq + 1) : '';
+ if (!path) throw opError('commit_paths_invalid', `--resolve ${spec} is not <path>=ours|theirs|file:<file>.`, 'Example: --resolve people/alice-example.md=theirs');
+ if (choice === 'ours' || choice === 'theirs') out.set(path, { kind: choice });
+ else if (choice.startsWith('file:') && choice.length > 5) out.set(path, { kind: 'file', path: choice.slice(5) });
+ else throw opError('commit_paths_invalid', `--resolve ${spec}: choose ours, theirs or file:<merged copy>.`, 'Example: --resolve people/alice-example.md=theirs');
+ }
+ return out;
+}
+
+function emit(json: boolean, doc: Record<string, unknown>, human: string): void {
+ if (json) void writeStdoutFinal(`${JSON.stringify(doc)}\n`);
+ else console.log(human);
+}
+
+export async function runGit(args: string[]): Promise<number> {
+ let json = args.includes('--json');
+ try {
+ 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 !== 'commit-push') throw opError('commit_paths_invalid', `Unknown subcommand: gbrain git ${p.sub}.`, HELP.split('\n')[0]);
+ 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.pushOnly)) {
+ throw opError('commit_paths_invalid', 'These flags do not combine.',
+ 'Use one mode: -m <msg> -- <paths> (commit + push), --push-only [--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.',
+ 'Copy both from the integrate_conflict report: --expect-remote names the remote commit your choice was made against.');
+ }
+
+ if (p.dryRun) {
+ const lock = execFileSync('git', ['-C', repo, 'rev-parse', '--git-path', COMMIT_LOCK_NAME], { env: gitChildEnv({ ...GIT_ENV }) }).toString().trim();
+ const branch = execFileSync('git', ['-C', repo, 'symbolic-ref', '--quiet', '--short', 'HEAD'], { env: gitChildEnv({ ...GIT_ENV }) }).toString().trim();
+ const paths = p.pull || p.pushOnly ? [] : scopePaths(repo, p.paths, cwd);
+ emit(json, { dry_run: true, repo, branch, lock, paths, mode: p.pull ? 'pull' : p.pushOnly ? 'push-only' : 'commit-push' },
+ `dry run: ${p.pull ? 'pull' : p.pushOnly ? 'push-only' : `commit ${paths.join(' ')}`} on ${branch} in ${repo} (lock ${lock}); nothing written`);
+ return 0;
+ }
+
+ if (p.pull) {
+ const r = pullShared(repo, { requireClean: p.requireClean });
+ emit(json, { ...r, repo }, r.status === 'advanced' ? `advanced ${r.from!.slice(0, 7)}→${r.to!.slice(0, 7)}${r.merged ? ' (merged)' : ''}`
+ : r.status === 'lagging' ? `not advanced: ${r.reason}` : r.status === 'skipped_dirty' ? 'skipped: the checkout has local edits (--require-clean)' : r.status.replace('_', ' '));
+ if (r.status === 'lagging' && !json) process.stderr.write(`[gbrain notice] checkout not advanced: ${r.reason}. Rerun --pull once those edits are committed.\n`);
+ return 0;
+ }
+
+ const result = commitAndPush({
+ repo, cwd, paths: p.paths, message: p.message, pushOnly: p.pushOnly, advanceOnlyWhenClean: p.requireClean,
+ ...(p.branch ? { branch: p.branch } : {}),
+ ...(p.resolve.length ? { resolutions: parseResolutions(p.resolve), expectRemote: p.expectRemote } : {}),
+ });
+ if (result.outcome === 'push_deferred') {
+ emit(json, { ...result, repo }, `push deferred: another push is running in ${repo} and will publish HEAD too`);
+ return 0;
+ }
+ appendPushLog(result.outcome === 'nothing_to_commit' || result.confirmed === 'remote' ? 'nothing' : result.integrated ? 'ok-after-merge' : 'ok',
+ p.branch?.replace(/^refs\/heads\//, '') ?? result.branch, result.sha ?? '');
+ if (result.outcome === 'pushed_checkout_lagging') appendPushLog('checkout-lagging', result.branch, result.sha ?? '', result.lagging_reason);
+ const short = result.sha ? result.sha.slice(0, 7) : '-';
+ 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.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') {
+ try {
+ const bi = args.indexOf('--branch');
+ const branch = bi !== -1 && args[bi + 1] ? args[bi + 1].replace(/^refs\/heads\//, '') : currentBranchOf(args);
+ appendPushLog(code === 'integrate_conflict' ? 'conflict' : 'local-only', branch, (e as { detail?: string }).detail ?? '');
+ } catch { /* best-effort */ }
+ }
+ return writeCliError(e, 'git commit-push', { json });
+ }
+}
+
+function currentBranchOf(args: string[]): string {
+ const i = args.findIndex(a => a === '--path' || a === '--repo');
+ const dir = i !== -1 ? args[i + 1] : process.cwd();
+ return execFileSync('git', ['-C', dir, 'symbolic-ref', '--quiet', '--short', 'HEAD'], { env: gitChildEnv({ ...GIT_ENV }), stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
+}
diff --git a/src/commands/sources-harden.ts b/src/commands/sources-harden.ts
index ec707619fa..5cec809b71 100644
--- a/src/commands/sources-harden.ts
+++ b/src/commands/sources-harden.ts
@@ -179,6 +179,7 @@ export async function runPull(engine: BrainEngine | null, args: string[]): Promi
case 'up_to_date': console.log(`up to date (${branch})`); break;
case 'advanced': console.log(`advanced ${outcome.from.slice(0, 7)}→${outcome.to.slice(0, 7)} (${branch})`); break;
case 'skipped_dirty': console.log(`skipped — working tree dirty (${branch})`); break;
+ case 'skipped_busy': console.log(`skipped — another writer holds the commit lock (${branch})`); break;
case 'conflict_aborted':
console.error(`[gbrain] ${outcome.detail}`);
process.exit(FAILED_EXIT_CODE);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 13077c7ba1..0b844a0d9a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -467,6 +467,12 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.177.0', text: 'The atom-extraction phase (`extract_atoms`) now honors a schema pack that declares one of the built-in extractable types (meeting, source, article, video, book, original) as `extractable: false`, the way facts extraction already did: such pages are no longer mined into atoms. gbrain-base declares meeting and source extractable and is unchanged; on gbrain-recommended, `source` pages stop being atom-extracted. A pack that does not mention a built-in type keeps it extractable.' },
// Fix wave 15 group 1 (managed sync authority and data safety).
{ since: '0.60.177.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },
+ // #6530 (GBRA-82) shared-checkout-safe git. `since` is provisional; restamped at the merge slot.
+ { since: '0.60.185.0', text: 'New `gbrain git commit-push` commits only the paths you name and pushes them safely in a brain checkout other agents share: `-m <msg> -- <paths>`, `--push-only`, `--pull` and `--dry-run`. After `gbrain sources harden`, the committed `scripts/brain-commit-push.sh` and the post-commit hook delegate to it and never run `git pull --rebase`, `git stash` or `git reset` in the shared tree. A rejected push is merged with the remote in memory, so brain history now gets merge commits (`gbrain: merge origin/<branch> into <branch>`) instead of rebased linear history; the checkout only fast-forwards, and a push whose fast-forward a dirty file blocks reports `pushed_checkout_lagging` (exit 0). Exit 4 (`push_unconfirmed`) means the commit is local but no push was confirmed. Guide: docs/guides/shared-checkout-git.md.' },
+ { since: '0.60.185.0', text: 'Brain checkout commits and pushes now coordinate through two OS locks under the git dir: `brain-commit.lock` for staging, committing and moving the checkout (wait `GBRAIN_COMMIT_LOCK_WAIT_SECONDS`, alias `GBRAIN_PUSH_LOCK_WAIT_SECONDS`, default 60, then `commit_lock_busy`) and `brain-publish.lock` for the network push (a foreground push waits `GBRAIN_PUBLISH_LOCK_WAIT_SECONDS`, default 300, then `push_unconfirmed`). The pre-#6530 `gbrain-push.lock` is still taken with the commit lock. The post-commit hook no longer waits for another push: it reports `push_deferred` and the running push publishes its commit too. `BRAIN_COMMIT_LOCK_HELD` is honored only when it names the lock file\'s path, no longer as `1`.' },
+ { since: '0.60.185.0', text: 'gbrain\'s own brain-repo commits (page write-through, facts fences, takes, timeline, `lint --fix`, and `sources harden` scaffolding) now take the checkout\'s commit lock (write-through waits 2 seconds, then commits its one path without it), commit only their own paths, and include both sides of a staged `git mv` rename. Paths passed to the helper or `gbrain git commit-push` are literal: a quoted glob no longer expands and fails `commit_paths_invalid`; name the files.' },
+ { since: '0.60.185.0', text: 'The pull that `gbrain sources pull`, the pull cron, `sources harden` and the workspace push run no longer rebases: a branch whose local and remote sides diverged is merged in memory and the checkout fast-forwards to the merge, for `pull_strategy: rebase` as well as `merge` (`set-pull-strategy` is still accepted). `gbrain sync`\'s pull is now a fetch plus a fast-forward under the commit lock. `gbrain sources harden` sets `rebase.autoStash=false`, `merge.autoStash=false` and `pull.ff=only` in the checkout\'s local git config so a stray `git pull` refuses instead of autostashing. A conflict now stops with `integrate_conflict` (ask the user; resolve with `gbrain git commit-push --push-only --expect-remote <sha> --resolve <path>=ours|theirs`), and `put_page` reports an unresolved one for that checkout.' },
+ { since: '0.60.185.0', text: 'The committed `scripts/brain-commit-push.sh` written by `gbrain sources harden` needs a gbrain that knows `git commit-push` to integrate remote commits. Without one it does only a locked, path-scoped commit and a plain push, and a rejected push now fails loudly (exit 4, PUSH FAILED) instead of rebasing. A helper written by a newer gbrain (a higher `# gbrain-protocol:` line) is never downgraded by an older harden.' },
];
/** 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.ts
index dd02798b4a..9e3e8dec2a 100644
--- a/src/core/brain-repo-durability.ts
+++ b/src/core/brain-repo-durability.ts
@@ -7,7 +7,7 @@ import { assertManagedFilesystemWrite, hasFilesystemPublication, managedFilesyst
* sessions edit a stale tree. The moment gbrain is given a PAT + a GitHub URL
* for a brain repo, `hardenBrainRepo` makes durability work, idempotently:
*
- * 1. pull current state (divergence-safe rebase; skip-on-dirty)
+ * 1. pull current state (fast-forward or in-memory merge; skip-on-dirty)
* 2. repo-scoped credential wiring (reuse an existing helper if present)
* 3. LOCAL untracked post-commit hook (best-effort background auto-push)
* 4. committed `scripts/brain-commit-push.sh` (the DURABILITY GUARANTEE —
@@ -18,10 +18,9 @@ import { assertManagedFilesystemWrite, hasFilesystemPublication, managedFilesyst
*
* Trust boundary (this is gbrain's FIRST push path + FIRST secret storage):
* - The hook is LOCAL + untracked so a pulled commit can't rewrite executed
- * code next to the PAT. Both hook and helper render from ONE bash template
- * (renderPushRetry; the lock-timeout return code is the sole per-renderer
- * knob, #4682) — DRY at the TS source level, NOT by the hook sourcing a
- * repo-controlled script.
+ * code next to the PAT. Since #6530 both hook and helper delegate to
+ * `gbrain git commit-push` (src/core/git/commit-push.ts); the hook runs the
+ * absolute CLI path captured at harden time, never the committed helper.
* - Credential is repo-scoped (local git config), token redacted everywhere
* via shell-redact's exact-value scrubber, store file 0600.
*
@@ -30,13 +29,13 @@ import { assertManagedFilesystemWrite, hasFilesystemPublication, managedFilesyst
*/
import {
- existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync, statSync, renameSync,
+ existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync, statSync, renameSync, appendFileSync,
} from 'fs';
import { join, dirname, relative, isAbsolute } from 'path';
import { execFileSync, execSync } from './spawn.ts';
import { execFileBounded } from './bounded-child-exec.ts';
import {
- GIT_ENV, GIT_ENV_AUTH, divergenceSafePull, detectDefaultBranch, pushProbe,
+ GIT_ENV, divergenceSafePull, detectDefaultBranch, pushProbe,
type PullOutcome, type PullStrategy, type PushProbeResult,
} from './git-remote.ts';
import { findResolverFile, RESOLVER_FILENAMES } from './resolver-filenames.ts';
@@ -51,6 +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';
export { execFileBounded, type BoundedExecOptions } from './bounded-child-exec.ts';
@@ -163,97 +163,59 @@ export function maintainPushLog(): void {
} catch { /* best-effort */ }
}
-// ── Shared bash push-retry template (DRY at the TS source — D7) ──────────────
-// Rendered into BOTH the (committed) helper and the (local, untracked) hook so
-// there is one source of truth without the hook executing repo-controlled code.
-// The ONE rendered divergence is the lock-timeout return code (#4682): the
-// synchronous helper is the fail-loud durability guarantee, so it must NOT
-// claim success when the lock never freed and no push was even attempted
-// (rc 1); the detached post-commit hook is best-effort background work where
-// skipping a push that another holder is already performing is the designed
-// coalescing outcome (rc 0). GBRAIN_PUSH_LOCK_WAIT_SECONDS (default 30) tunes
-// the lock wait — env-only, incident/test escape hatch.
-function renderPushRetry(lockTimeoutRc: 0 | 1): string {
- return `# --- gbrain durability push-retry (generated; one source of truth) ---
-brain_remote_contains_commit() {
- local _remote_tip _push_url
- git check-ref-format "refs/heads/$1" >/dev/null 2>&1 || return 1
- [ -n "$_push_urls" ] || return 1
- while IFS= read -r _push_url; do
- [ -n "$_push_url" ] || return 1
- [ "$(git ls-remote --get-url -- "$_push_url" 2>/dev/null)" = "$_push_url" ] || return 1
- _remote_tip="$(git ls-remote --exit-code -- "$_push_url" "refs/heads/$1" 2>/dev/null)" || return 1
- _remote_tip="\${_remote_tip%%[[:space:]]*}"
- git fetch --quiet --no-tags --no-write-fetch-head -- "$_push_url" "$_remote_tip" >/dev/null 2>&1 &&
- git merge-base --is-ancestor "$2" "$_remote_tip" >/dev/null 2>&1 || return 1
- done <<<"$_push_urls"
+// ── Helper + hook templates (#6530) ─────────────────────────────────────────
+// Both delegate to `gbrain git commit-push` (src/core/git/commit-push.ts):
+// a short commit lock plus a separate push lock per checkout, path-scoped commits, remote commits merged in
+// memory, the checkout advanced fast-forward only. Neither ever runs
+// `pull --rebase`, `stash` or `reset` in the shared tree. The banners above
+// stay byte-identical: they are the ownership markers isDurabilityHardened,
+// installLocalHook and unharden match (changing one would silently turn off
+// write-through commits on every hardened repo). The protocol revision lives
+// on its own `# gbrain-protocol:` line.
+
+export const DURABILITY_PROTOCOL = 2;
+const PROTOCOL_LINE = `# gbrain-protocol: ${DURABILITY_PROTOCOL}`;
+
+/** The protocol revision a rendered hook/helper declares; 1 for pre-#6530 files (no line). */
+export function durabilityProtocolOf(text: string): number {
+ const m = /^# gbrain-protocol: (\d+)$/m.exec(text);
+ return m ? Number(m[1]) : 1;
}
-brain_push() {
- _branch="\${1#refs/heads/}"
- _managed_git="$(git rev-parse --git-dir 2>/dev/null || echo .git)"
- if [ -e "$_managed_git/gbrain-managed.json" ] || [ -e .gbrain-managed ]; then
- echo "writer_coordinator_required: managed worktree git effects belong to the persistence outbox" >&2
- return 1
- fi
- # CX2-8: GBRAIN_HOME is a PARENT dir (matches config.ts semantics — .gbrain appended)
- _log="\${GBRAIN_HOME:-$HOME}/.gbrain/brain-push.log"
- mkdir -p "$(dirname "$_log")" 2>/dev/null || true
- # S3#10: the push log may capture remote errors — never group/other readable.
- [ -e "$_log" ] || { : >"$_log" 2>/dev/null && chmod 600 "$_log" 2>/dev/null; } || true
- _gd="$(git rev-parse --git-dir 2>/dev/null || echo .git)"
- # Serialize concurrent pushes (commit bursts) so they coalesce instead of a
- # rebase-retry herd. No-op if flock is unavailable.
- if command -v flock >/dev/null 2>&1; then
- exec 9>"$_gd/gbrain-push.lock"
- flock -w "\${GBRAIN_PUSH_LOCK_WAIT_SECONDS:-30}" 9 || { echo "$(date -u +%FT%TZ) [push] lock-timeout $_branch" >>"$_log"; return ${lockTimeoutRc}; }
- fi
- _head="$(git rev-parse HEAD)" || return 1
- _push_urls="$(git remote get-url --push --all origin 2>/dev/null)" || _push_urls=""
- if git push origin "$_head:refs/heads/$_branch" >>"$_log" 2>&1; then
- echo "$(date -u +%FT%TZ) [push] ok $_branch $(git rev-parse --short "$_head" 2>/dev/null)" >>"$_log"; return 0
- fi
- if brain_remote_contains_commit "$_branch" "$_head"; then
- echo "$(date -u +%FT%TZ) [push] ok-already-on-remote $_branch $(git rev-parse --short "$_head" 2>/dev/null)" >>"$_log"; return 0
- fi
- if [ "$(git rev-parse HEAD)" = "$_head" ]; then
- echo "$(date -u +%FT%TZ) [push] rejected; rebase-pull $_branch" >>"$_log"
- if git pull --rebase origin "$_branch" >>"$_log" 2>&1; then
- _head="$(git rev-parse HEAD)" || return 1
- _push_urls="$(git remote get-url --push --all origin 2>/dev/null)" || _push_urls=""
- if git push origin "$_head:refs/heads/$_branch" >>"$_log" 2>&1; then
- echo "$(date -u +%FT%TZ) [push] ok-after-rebase $_branch $(git rev-parse --short "$_head" 2>/dev/null)" >>"$_log"; return 0
- fi
- else
- git rebase --abort >/dev/null 2>&1 || true
- fi
- fi
- if brain_remote_contains_commit "$_branch" "$_head"; then
- echo "$(date -u +%FT%TZ) [push] ok-already-on-remote $_branch $(git rev-parse --short "$_head" 2>/dev/null)" >>"$_log"; return 0
- fi
- echo "$(date -u +%FT%TZ) [push] LOCAL-ONLY, NEEDS ATTENTION: $_branch @ $(git rev-parse --short "$_head" 2>/dev/null) could not reach origin. Run: gbrain sources pull <id> && git push" >>"$_log"
- return 1
-}`;
+function shq(v: string): string {
+ return `'${v.replace(/'/g, `'\\''`)}'`;
}
-function renderPostCommitHook(): string {
+function renderPostCommitHook(cli: string): string {
return `#!/usr/bin/env bash
${HOOK_BANNER}
-# LOCAL + untracked — NEVER commit this file. Best-effort background auto-push so
-# agent writes don't sit local-only. The real guarantee is ${HELPER_REL}.
-# Bypass: git commit --no-verify.
-set -euo pipefail
-
-_branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo HEAD)"
+${PROTOCOL_LINE}
+# LOCAL + untracked — NEVER commit this file. Best-effort background push so
+# commits don't sit local-only. Runs the gbrain CLI captured at harden time
+# (never the committed helper), which takes the checkout's commit lock,
+# merges remote commits in memory and never moves files under local edits.
+# The fail-loud guarantee is ${HELPER_REL}. Bypass: git commit --no-verify.
+set -uo pipefail
+unset $(git rev-parse --local-env-vars) 2>/dev/null || true
+
+# The committing process (gbrain git commit-push / ${HELPER_REL}) publishes itself.
+[ -n "\${BRAIN_COMMIT_LOCK_HELD:-}" ] && exit 0
+
+_log="\${GBRAIN_HOME:-$HOME}/.gbrain/brain-push.log"
+mkdir -p "$(dirname "$_log")" 2>/dev/null || true
+[ -e "$_log" ] || { : >"$_log" 2>/dev/null && chmod 600 "$_log" 2>/dev/null; } || true
+_branch="$(git symbolic-ref --quiet --short HEAD 2>/dev/null || echo HEAD)"
if [ "$_branch" = "HEAD" ]; then
- echo "$(date -u +%FT%TZ) [push] detached HEAD; skip" >> "\${GBRAIN_HOME:-$HOME}/.gbrain/brain-push.log" 2>/dev/null || true
+ echo "$(date -u +%FT%TZ) [push] detached HEAD; skip" >>"$_log" 2>/dev/null || true
exit 0
fi
-
-${renderPushRetry(0)}
-
-# Detach so the commit returns instantly; all output goes to the log.
-( brain_push "$_branch" ) </dev/null >/dev/null 2>&1 &
+_cli=${shq(cli)}
+if [ ! -x "$_cli" ]; then
+ echo "$(date -u +%FT%TZ) [push] LOCAL-ONLY, NEEDS ATTENTION: $_branch @ $(git rev-parse --short HEAD 2>/dev/null) gbrain CLI missing at $_cli. Run: gbrain sources harden <id>" >>"$_log" 2>/dev/null || true
+ exit 0
+fi
+# Detach so the commit returns instantly; the CLI logs its own outcome.
+( "$_cli" git commit-push --push-only --require-clean ) </dev/null >/dev/null 2>&1 &
disown 2>/dev/null || true
exit 0
`;
@@ -262,41 +224,82 @@ exit 0
function renderCommitPushHelper(): string {
return `#!/usr/bin/env bash
${HELPER_BANNER}
-# THE DURABILITY GUARANTEE: add -> commit -> push, atomically. Refuses to exit 0
-# without a confirmed push — including on push-lock timeout (#4682). Usage:
+${PROTOCOL_LINE}
+# THE DURABILITY GUARANTEE: commit the named paths and push, safely, in a
+# checkout other agents share. Refuses to exit 0 without a confirmed push.
# scripts/brain-commit-push.sh "message" <path> [path ...]
-# scripts/brain-commit-push.sh --push-only [branch]
+# scripts/brain-commit-push.sh --push-only
+# scripts/brain-commit-push.sh --pull
+# Delegates to \`gbrain git commit-push\` (lock, path-scoped commit, in-memory
+# merge, fast-forward-only checkout). Without a capable gbrain it only commits
+# the paths under the lock and pushes; a rejected push fails loudly. It never
+# runs pull --rebase, stash or reset. Guide: docs/guides/shared-checkout-git.md
set -euo pipefail
+unset $(git rev-parse --local-env-vars) 2>/dev/null || true
-${renderPushRetry(1)}
-
-_branch="$(git rev-parse --abbrev-ref HEAD)"
_managed_git="$(git rev-parse --git-dir 2>/dev/null || echo .git)"
if [ -e "$_managed_git/gbrain-managed.json" ] || [ -e .gbrain-managed ]; then
echo "writer_coordinator_required: submit managed changes through persistence" >&2; exit 1
fi
-if [ "\${1:-}" = "--push-only" ]; then
- brain_push "\${2:-$_branch}"; exit $?
-fi
-_msg="\${1:?usage: brain-commit-push.sh <message> <path> [paths...]}"; shift || true
+_gbrain_cli() {
+ local c
+ for c in "$(command -v gbrain 2>/dev/null || true)" "$(git config --local --get gbrain.cliPath 2>/dev/null || true)"; do
+ [ -n "$c" ] && [ -x "$c" ] && "$c" git commit-push --help >/dev/null 2>&1 && { printf '%s' "$c"; return 0; }
+ done
+ return 1
+}
+
+_branch="$(git symbolic-ref --quiet --short HEAD)" || { echo "detached HEAD: check out a branch first" >&2; exit 1; }
+_run() {
+ local rc=0
+ "$_cli" git commit-push "$@" || rc=$?
+ if [ "$rc" -eq 4 ]; then
+ echo "PUSH FAILED — commit is local-only, NEEDS ATTENTION (see \${GBRAIN_HOME:-$HOME}/.gbrain/brain-push.log)" >&2
+ fi
+ exit "$rc"
+}
+if _cli="$(_gbrain_cli)"; then
+ case "\${1:-}" in
+ --push-only) if [ -n "\${2:-}" ]; then _run --push-only --branch "$2"; else _run --push-only; fi ;;
+ --pull) _run --pull ;;
+ esac
+ _msg="\${1:?usage: brain-commit-push.sh <message> <path> [paths...]}"; shift
+ [ "$#" -gt 0 ] || { echo "refusing a repo-wide commit: pass explicit path(s)" >&2; exit 2; }
+ _run -m "$_msg" -- "$@"
+fi
-# EXPLICIT paths only — never a blind 'git add -A' (would risk committing
-# secrets, temp files, or unrelated edits).
-if [ "$#" -eq 0 ]; then
- echo "refusing blind 'git add -A' — pass explicit path(s) to commit" >&2; exit 2
+# ── Fallback: no gbrain that knows \`git commit-push\` on this machine ──────────
+_branch="$(git symbolic-ref --quiet --short HEAD)" || { echo "detached HEAD: check out a branch first" >&2; exit 1; }
+echo "[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
+if command -v flock >/dev/null 2>&1; then
+ exec 8>"$(git rev-parse --git-path brain-commit.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)"
+ 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
+else
+ echo "[brain-commit-push] flock not found: committing without the writer lock (install gbrain or flock)" >&2
+fi
+case "\${1:-}" in
+ --pull)
+ git fetch --no-tags origin "$_branch"
+ exec git -c core.hooksPath=/dev/null merge --ff-only --no-autostash "origin/$_branch" ;;
+ --push-only) ;;
+ *)
+ _msg="\${1:?usage: brain-commit-push.sh <message> <path> [paths...]}"; shift
+ [ "$#" -gt 0 ] || { echo "refusing a repo-wide commit: pass explicit path(s)" >&2; exit 2; }
+ git add -A -- "$@"
+ if git diff --cached --quiet -- "$@"; then echo "nothing to commit"; else git commit --only -m "$_msg" -- "$@"; fi ;;
+esac
+_head="$(git rev-parse HEAD)"
+if git push origin "$_head:refs/heads/$_branch" >>"$_log" 2>&1; then
+ echo "$(date -u +%FT%TZ) [push] ok $_branch $(git rev-parse --short "$_head")" >>"$_log"; exit 0
fi
-# COMMIT BEFORE PULL (#2426): the old order (fetch + pull --rebase, THEN stage)
-# aborted on any dirty tree — 'cannot pull with rebase: You have unstaged
-# changes' — so the helper could never commit a MODIFIED page (exactly the
-# write-through case). Stage + commit first; brain_push below already handles
-# a remote that advanced (push -> rejected -> pull --rebase -> push).
-git add -- "$@"
-if git diff --cached --quiet; then echo "nothing to commit"; exit 0; fi
-git commit -m "$_msg"
-
-if brain_push "$_branch"; then exit 0; fi
-echo "PUSH FAILED — commit is local-only, NEEDS ATTENTION (see ${'$'}{GBRAIN_HOME:-$HOME}/.gbrain/brain-push.log)" >&2
+echo "$(date -u +%FT%TZ) [push] LOCAL-ONLY, NEEDS ATTENTION: $_branch @ $(git rev-parse --short "$_head") push rejected; run gbrain git commit-push --push-only" >>"$_log"
+echo "PUSH FAILED — the commit is local-only. Install gbrain and run: gbrain git commit-push --push-only (it merges remote commits safely). Never git pull --rebase here." >&2
exit 4
`;
}
@@ -333,7 +336,7 @@ function renderTaxonomyLines(rules: FilingRulesDoc): string {
/**
* The classic rules tell agents to run the push helper after every write and
- * to `git pull --rebase` before writing. On a managed canonical worktree
+ * its `--pull` mode before writing (#6530: never `git pull --rebase`). On a managed canonical worktree
* (#5808) both route agents around the persistence owner, so the block has a
* managed variant: page writes through gbrain, non-page files with plain git,
* never pull or rebase the checkout. `gbrain sources writer git-durability
@@ -358,14 +361,21 @@ function renderManagedBlock(repoPath: string, managed?: { sourceId: string }): s
\`MEMORY.md\`, daily notes) are yours: \`git add\` and \`git commit\` them with plain
git; they reach the remote on the owner's next push, or push them by hand
with \`git push\` (never \`--force\`).` : `2. **Every write is committed AND pushed — push is never deferred.** After any
- persistent write, run \`scripts/brain-commit-push.sh "<msg>" <path>\` (it commits,
- pushes, and FAILS LOUDLY if the push doesn't land), then confirm links resolve
- with \`gbrain check-resolvable\`. Do not move on until the push succeeded. The
- post-commit hook is only a best-effort fallback — the helper is the guarantee.
-
-3. **Pull before you touch anything.** Run \`git fetch && git pull --rebase\` at
- session start and again before each batch of writes, so a long-lived session
- never edits a stale tree (a cron also pulls every ~30 min).`;
+ persistent write, run \`scripts/brain-commit-push.sh "<msg>" <path>\` (or
+ \`gbrain git commit-push -m "<msg>" -- <path>\`). It commits only the paths you
+ name, takes this checkout's writer lock, merges remote commits without
+ touching other agents' files, and FAILS LOUDLY if the push doesn't land. Then
+ confirm links resolve with \`gbrain check-resolvable\`. On \`integrate_conflict\`
+ stop and ask the user; on \`commit_lock_busy\` retry once. The post-commit hook
+ is only a best-effort fallback — the helper is the guarantee.
+
+3. **Bring in remote commits safely; never rebase this checkout.** Other agents
+ share it. Run \`scripts/brain-commit-push.sh --pull\` (or
+ \`gbrain git commit-push --pull\`) at session start and before each batch of
+ writes (a cron also pulls every ~30 min). Never run \`git pull --rebase\`,
+ \`git stash\`, \`--autostash\`, \`git reset --hard\` or \`git push --force\` here, and
+ never delete \`.git/rebase-merge\` without first saving its autostash with
+ \`git stash store\` (docs/guides/shared-checkout-git.md#stuck-rebase).`;
return `${AGENTS_BEGIN}
<!-- gbrain durability rules. This block is regenerated by \`${regeneratedBy}\`.
Do not index as user knowledge; do not edit between the markers. -->
@@ -471,11 +481,14 @@ function ensureExcluded(repoPath: string, relPath: string): void {
function installLocalHook(repoPath: string, dryRun: boolean): { status: StepStatus; detail: string } {
const { dir, tracked } = resolveHooksDir(repoPath);
const hookPath = join(dir, 'post-commit');
- const script = renderPostCommitHook();
+ const script = renderPostCommitHook(resolveGbrainCliPath());
if (existsSync(hookPath)) {
const cur = readFileSync(hookPath, 'utf-8');
if (cur.includes(HOOK_BANNER)) {
+ if (durabilityProtocolOf(cur) > DURABILITY_PROTOCOL) {
+ return { status: 'needs_attention', detail: `${relative(repoPath, hookPath)} was written by a newer gbrain (protocol ${durabilityProtocolOf(cur)}); upgrade gbrain instead of downgrading it` };
+ }
if (tracked && !dryRun) ensureExcluded(repoPath, relative(repoPath, hookPath));
if (cur === script) return { status: 'ok', detail: `${relative(repoPath, hookPath)} already current` };
if (dryRun) return { status: 'fixed', detail: `would refresh ${relative(repoPath, hookPath)} (dry-run)` };
@@ -576,10 +589,13 @@ 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.
*
- * Path-limited (`git commit -- <path>`) so unrelated staged/dirty edits are
- * never swept into the commit. Never throws; returns false on any failure
- * (index.lock contention, nothing changed, detached states) — the DB row and
- * the on-disk file remain the durable sinks either way.
+ * #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.
*
* `git add -- <path>` stages a removal as readily as an edit, so
* `deletePageThrough` reuses this helper with `action: 'delete write-through'`
@@ -594,15 +610,14 @@ export function commitWriteThroughFile(
try {
const rel = relative(repoPath, absPath);
if (!rel || rel.startsWith('..') || isAbsolute(rel)) return false;
- const gitOpts = { stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }) } as const;
- execFileSync('git', ['-C', repoPath, 'add', '--', rel], gitOpts);
- execFileSync('git', ['-C', repoPath, 'commit', '-m', `gbrain: ${action} ${slug}`, '--', rel], gitOpts);
- return true;
+ return commitPathsLocked(repoPath, [absPath], `gbrain: ${action} ${slug}`, { lockWaitMs: WRITE_THROUGH_LOCK_WAIT_MS }) !== null;
} catch {
return false;
}
}
+const WRITE_THROUGH_LOCK_WAIT_MS = 2_000;
+
// ── Push-state query (D14) ───────────────────────────────────────────────────
export type PushLogStatus = 'ok' | 'needs_attention' | 'unknown';
@@ -614,8 +629,34 @@ export interface PushLogOutcome {
at?: string;
}
-const PUSH_LOG_OK = /^(\S+) \[push\] (?:ok|ok-after-rebase|ok-already-on-remote) (\S+)\b/;
-const PUSH_LOG_LOCAL_ONLY = /^(\S+) \[push\] LOCAL-ONLY, NEEDS ATTENTION: (\S+) /;
+const PUSH_LOG_OK = /^(\S+) \[push\] (?:ok|ok-after-rebase|ok-after-merge|ok-already-on-remote) (\S+)\b/;
+const PUSH_LOG_LOCAL_ONLY = /^(\S+) \[push\] (?:LOCAL-ONLY|CONFLICT), NEEDS ATTENTION: (\S+) /;
+
+export type PushLogKind = 'ok' | 'ok-after-merge' | 'nothing' | 'local-only' | 'conflict' | 'lock-timeout' | 'checkout-lagging';
+
+/**
+ * #6530: one `brain-push.log` line per `gbrain git commit-push` outcome, in the
+ * grammar {@link getLastPushOutcome} parses (put_page's `lastPushStatus`).
+ * `checkout-lagging` is informational: the push landed. Best-effort.
+ */
+export function appendPushLog(kind: PushLogKind, branch: string, sha: string, detail?: string): void {
+ try {
+ const at = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
+ const short = sha ? sha.slice(0, 7) : '-';
+ const clean = (detail ?? '').replace(/\s+/g, ' ').slice(0, 200);
+ const line = kind === 'ok' ? `[push] ok ${branch} ${short}`
+ : kind === 'ok-after-merge' ? `[push] ok-after-merge ${branch} ${short}`
+ : kind === 'nothing' ? `[push] ok-already-on-remote ${branch} ${short}`
+ : kind === 'lock-timeout' ? `[push] lock-timeout ${branch}`
+ : kind === 'checkout-lagging' ? `[push] checkout-lagging ${branch} ${short} ${clean}`
+ : kind === 'conflict' ? `[push] CONFLICT, NEEDS ATTENTION: ${branch} local and remote changed the same file. Run: gbrain git commit-push --push-only --resolve <path>=ours|theirs`
+ : `[push] LOCAL-ONLY, NEEDS ATTENTION: ${branch} @ ${short} could not reach the remote. Run: gbrain git commit-push --push-only`;
+ const p = pushLogPath();
+ mkdirSync(dirname(p), { recursive: true });
+ if (!existsSync(p)) writeFileSync(p, '', { mode: 0o600 });
+ appendFileSync(p, `${at} ${line}\n`);
+ } catch { /* best-effort */ }
+}
const PUSH_LOG_LOCK_TIMEOUT = /^(\S+) \[push\] lock-timeout (\S+)\b/;
/**
@@ -629,9 +670,15 @@ const PUSH_LOG_LOCK_TIMEOUT = /^(\S+) \[push\] lock-timeout (\S+)\b/;
* The log is host-wide and keyed only by branch name, not repo path, so two
* different hardened repos sharing a branch name (e.g. both on `main`) share
* this signal. That's an acceptable approximation for a liveness check, not
- * a per-repo guarantee.
+ * a per-repo guarantee. With `repo`, an unresolved integrate_conflict recorded
+ * in that checkout (#6530) wins over the log.
*/
-export function getLastPushOutcome(branch: string): PushLogOutcome {
+export function getLastPushOutcome(branch: string, repo?: string): PushLogOutcome {
+ const conflict = repo ? readIntegrateConflict(repo) : null;
+ if (conflict && conflict.branch === branch) {
+ return { status: 'needs_attention', at: conflict.at,
+ detail: `unresolved integrate_conflict on ${branch} (${conflict.paths.join(', ')}): run gbrain git commit-push --push-only --expect-remote ${String(conflict.remote).slice(0, 12)} --resolve <path>=ours|theirs` };
+ }
const log = pushLogPath();
if (!existsSync(log)) return { status: 'unknown', detail: 'no push attempts logged yet' };
@@ -660,6 +707,9 @@ export function getLastPushOutcome(branch: string): PushLogOutcome {
function installHelper(repoPath: string, dryRun: boolean): { status: StepStatus; detail: string } {
const helperPath = join(repoPath, HELPER_REL);
const script = renderCommitPushHelper();
+ if (existsSync(helperPath) && durabilityProtocolOf(readFileSync(helperPath, 'utf-8')) > DURABILITY_PROTOCOL) {
+ return { status: 'needs_attention', detail: `${HELPER_REL} was written by a newer gbrain (protocol ${durabilityProtocolOf(readFileSync(helperPath, 'utf-8'))}); upgrade gbrain instead of downgrading it` };
+ }
if (existsSync(helperPath) && readFileSync(helperPath, 'utf-8') === script) {
// Ensure exec bit even when content is current — but not in dry-run: a
// preview must not mutate permissions (#3736).
@@ -1010,6 +1060,7 @@ function pullDetail(o: PullOutcome): { status: StepStatus; detail: string } {
case 'up_to_date': return { status: 'ok', detail: 'already up to date with origin' };
case 'advanced': return { status: 'fixed', detail: `advanced ${o.from.slice(0, 7)}→${o.to.slice(0, 7)}` };
case 'skipped_dirty': return { status: 'skipped', detail: 'working tree dirty — pull skipped (in-progress edits preserved)' };
+ case 'skipped_busy': return { status: 'skipped', detail: 'another writer holds the commit lock — pull skipped; the next run catches up' };
case 'conflict_aborted': return { status: 'needs_attention', detail: o.detail };
}
}
@@ -1056,7 +1107,7 @@ export async function hardenBrainRepo(opts: HardenOpts): Promise<DurabilityRepor
if (currentBranch(repoPath) === 'HEAD') {
push('pull', { status: 'needs_attention', detail: 'detached HEAD — checkout a branch before hardening' });
} else if (dryRun) {
- push('pull', { status: 'skipped', detail: `dry-run — would fetch + pull ${opts.pullStrategy === 'merge' ? '--no-rebase' : '--rebase'} origin/${branch}` });
+ push('pull', { status: 'skipped', detail: `dry-run — would fetch origin/${branch} and fast-forward (or merge in memory)` });
} else {
// 1. pull current state
try { push('pull', pullDetail(divergenceSafePull(repoPath, branch, { strategy: opts.pullStrategy }))); }
@@ -1067,8 +1118,18 @@ export async function hardenBrainRepo(opts: HardenOpts): Promise<DurabilityRepor
if (opts.pat) push('credential', wireRepoCredential(repoPath, opts.pat, dryRun));
else push('credential', { status: 'skipped', detail: 'no PAT provided — relying on existing git auth' });
- // 3. local untracked hook
+ // 3. local untracked hook (+ #6530 local git config: the CLI path the
+ // helper falls back to, and autostash off / pull.ff=only so a stray
+ // `git pull` in the shared checkout refuses instead of stashing others' work)
push('hook', installLocalHook(repoPath, dryRun));
+ if (!dryRun) {
+ try {
+ gitConfigSet(repoPath, 'gbrain.cliPath', resolveGbrainCliPath());
+ gitConfigSet(repoPath, 'rebase.autoStash', 'false');
+ gitConfigSet(repoPath, 'merge.autoStash', 'false');
+ gitConfigSet(repoPath, 'pull.ff', 'only');
+ } catch { /* best-effort: the helper still resolves gbrain from PATH */ }
+ }
// 4. committed helper
push('helper', installHelper(repoPath, dryRun));
// 5. resolver/AGENTS rules
@@ -1104,31 +1165,19 @@ export async function hardenBrainRepo(opts: HardenOpts): Promise<DurabilityRepor
}
function commitScaffolding(repoPath: string, branch: string, redact: (s: string) => string): { status: StepStatus; detail: string } | null {
- // Stage only the durability artifacts we manage — never a blind add.
+ // Only the durability artifacts we manage, through the shared-checkout
+ // protocol (#6530): commit --only those paths under the commit lock, push,
+ // merge remote commits in memory if the push is rejected. The commit carries
+ // the lock marker, so the freshly installed post-commit hook stands down and
+ // this push is the only one (#3925).
const paths: string[] = [HELPER_REL];
const resolver = findResolverFile(repoPath);
if (resolver) paths.push(relative(repoPath, resolver));
try {
- execFileSync('git', ['-C', repoPath, 'add', '--', ...paths], { stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }) });
- const staged = execFileSync('git', ['-C', repoPath, 'diff', '--cached', '--name-only'], {
- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }),
- }).toString().trim();
- if (!staged) return { status: 'ok', detail: 'scaffolding already committed' };
- // #3925: suppress hooks on THIS commit. Step 3 already installed the
- // local post-commit hook, so a plain `git commit` here detaches a
- // background brain_push that races the explicit fail-loud push below on
- // the same ref (cannot-lock-ref on origin; the loser's `pull --rebase`
- // retry then takes .git/index.lock — flock is absent on macOS, so the
- // hook can't serialize against us). core.hooksPath=/dev/null makes the
- // push below the ONLY push for the scaffolding commit; every later
- // operator/agent commit still fires the hook normally.
- execFileSync('git', ['-C', repoPath, '-c', 'core.hooksPath=/dev/null', 'commit', '-m', 'chore(gbrain): install brain durability scaffolding'], {
- stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }),
- });
- execFileSync('git', ['-C', repoPath, ...['-c', 'http.followRedirects=false'], 'push', 'origin', `HEAD:${branch}`], {
- stdio: ['ignore', 'pipe', 'pipe'], timeout: 120_000, env: gitChildEnv({ ...GIT_ENV_AUTH }),
- });
- return { status: 'fixed', detail: 'committed + pushed durability scaffolding' };
+ const r = commitAndPush({ repo: repoPath, paths, cwd: repoPath, message: 'chore(gbrain): install brain durability scaffolding' });
+ if (r.branch !== branch) return { status: 'needs_attention', detail: `checkout is on ${r.branch}, not ${branch}` };
+ if (r.outcome === 'nothing_to_commit') return { status: 'ok', detail: 'scaffolding already committed' };
+ return { status: 'fixed', detail: `committed + pushed durability scaffolding${r.checkout === 'lagging' ? ` (checkout lagging: ${r.lagging_reason})` : ''}` };
} catch (e) {
return { status: 'needs_attention', detail: redact(`scaffolding commit/push failed: ${(e as Error).message.slice(0, 140)}`) };
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index cb7cdf1abc..0c8b47b452 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -24,7 +24,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
'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', '--allowed-operations', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--group', '--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', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],
- 'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--exit-code', '--file', '--force', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-rebase', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--oauth-client-id', '--oauth-client-secret', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
+ 'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--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', '--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', '--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', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
'calibration': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--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'],
@@ -47,7 +47,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', '--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', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--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', '--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', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-rebase', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pull', '--pure', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--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', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--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'],
@@ -68,6 +68,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'founder': ['--brain', '--help', '--json', '--mcp-only', '--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', '--brain', '--branch', '--cached', '--cacheinfo', '--count', '--dry-run', '--enable', '--ff-only', '--file', '--force', '--force-remove', '--get', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--literal-pathspecs', '--local', '--local-env-vars', '--message', '--name-only', '--no-autostash', '--no-cron', '--no-gpg-sign', '--no-messages', '--no-recurse-submodules', '--no-tags', '--no-verify', '--no-write-fetch-head', '--only', '--pat-file', '--path', '--porcelain', '--pull', '--push-only', '--quiet', '--rebase', '--repo', '--require-clean', '--resolve', '--short', '--show-toplevel', '--source', '--unset-all', '--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', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--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', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--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'],
@@ -76,7 +77,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--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', '--kind', '--lanes', '--limit', '--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', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--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', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
- 'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--adopt-slug-path', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--dry-run', '--enable', '--exclude', '--exit-code', '--expected-epoch', '--explain', '--file', '--fix', '--follow', '--force', '--get', '--get-url', '--git-dir', '--git-path', '--grammar-diagnostics', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--manifest', '--name-only', '--no-accept-pending', '--no-cron', '--no-rebase', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],
+ 'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--dry-run', '--enable', '--exclude', '--expected-epoch', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--help', '--id', '--is-inside-work-tree', '--json', '--local', '--local-env-vars', '--manifest', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--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': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
@@ -109,7 +110,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--no-llm', '--only', '--probe', '--remediate', '--remediation-plan', '--scopes', '--skip', '--slug', '--slugs', '--source', '--stale', '--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', '--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', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-rebase', '--no-recurse-submodules', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--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', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--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', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--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', '--only', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--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', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--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', '--full', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
@@ -123,11 +124,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', '--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', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--exit-code', '--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-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-rebase', '--no-recurse-submodules', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--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', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--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', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--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-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--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', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--yes'],
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--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', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--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', '--session', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--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-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--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', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--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-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-autostash', '--no-bulk', '--no-capture', '--no-delegate', '--no-edit', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-rebase', '--no-recurse-submodules', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--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-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--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', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--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-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-autostash', '--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', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--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', '--wait'],
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index a2df2162a5..70669aa09d 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -102,6 +102,8 @@ export const CODES = {
code_reused: { class: 'caller', summary: "Google connect credential error: code reused.", docs: 'docs/guides/google-connect.md#troubleshooting' },
colon_slug_windows_write_through: { class: 'caller', summary: "A colon slug cannot be written through on Windows." },
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' },
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 },
@@ -199,6 +201,7 @@ export const CODES = {
git_detached_head: { class: 'host_only', summary: "The canonical checkout is on a detached HEAD, so a push would target the wrong ref.", suggestion: 'Check out the branch the remote should track (git switch <branch>) on the brain host, then rerun.' },
git_index_locked: { class: 'retryable', summary: "Another Git process holds the canonical checkout index lock." },
git_index_stale: { class: 'caller', summary: "Git index stale." },
+ git_operation_in_progress: { class: 'caller', summary: "A rebase, merge, cherry-pick or revert is in progress in the checkout, so gbrain will not commit or move it.", docs: 'docs/guides/shared-checkout-git.md#stuck-rebase' },
git_push_unavailable: { class: 'retryable', summary: "The canonical commit is durable locally; its push will retry." },
git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },
git_unavailable: { class: 'retryable', summary: "A git command did not complete." },
@@ -227,6 +230,7 @@ export const CODES = {
idempotency_conflict: { class: 'caller', summary: "The request_id already belongs to a different accepted operation." },
independent_principal_required: { class: 'consent', summary: "This local CLI principal already owns another source/destination for this harness." },
insufficient_scope: { class: 'host_only', summary: "The connection lacks the OAuth scope the operation requires.", legacy_error: 'permission_denied' },
+ integrate_conflict: { class: 'consent', summary: "Local and remote commits changed the same file; nothing was merged and the checkout is unchanged.", docs: 'docs/guides/shared-checkout-git.md#conflicts', actor: 'user' },
internal: { class: 'server', summary: "A memory verb failed on the server; this is not a caller mistake." },
internal_error: { class: 'server', summary: "The server failed while running the operation; this is not a caller mistake." },
interrupted: { class: 'server', summary: "The operation was interrupted by a signal before it finished.", exit: 130 },
@@ -318,6 +322,7 @@ export const CODES = {
pending_writes: { class: 'retryable', summary: "A pending source write prevents verified completion." },
permission_denied: { class: 'host_only', summary: "This caller is not authorized for the operation." },
persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },
+ push_unconfirmed: { class: 'retryable', summary: "The commit is durable locally but no push destination confirmed it.", docs: 'docs/guides/shared-checkout-git.md#outcomes', exit: 4 },
schema_lock_blocked: { class: 'retryable', summary: "A schema step (the schema.sql replay in init/upgrade, or one migration) waited its lock_timeout for a table lock another session holds and stopped instead of hanging.", why: "Every ALTER TABLE in the replay takes an ACCESS EXCLUSIVE lock even as a no-op, so one open transaction in another client (idle in transaction, a stuck job) blocked gbrain init and upgrade forever with no output. The wait is now bounded (GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS, default 60) and the refusal names the blocking sessions by pid, application and state, sampled while the wait was active; query text is never shown. The cancelled step changed nothing.", docs: 'docs/ENGINES.md#schema-lock-blocked', suggestion: 'Let the named session finish or, with the user\'s agreement, end it on the database host with SELECT pg_terminate_backend(<pid>), then rerun the same gbrain command; init retries a few times on its own with a short backoff.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the database, the pooler and the schema version so the rerun is judged against the current state.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },
pg_connection_stuck: { class: 'retryable', summary: "A pooled Postgres statement waited past the pool's statement_timeout plus grace with nothing coming back from the server, so the driver retired that connection; the statement and everything queued behind it failed with CONNECTION_STUCK.", why: "A legitimate statement cannot outlive the server-side statement_timeout, so a connection that is still waiting past it is wedged: a pipeline the server and client no longer agree on, a transaction-mode pooler that swallowed a CancelRequest and left the backend in ClientRead, or a dead peer. Before #6383 such a connection held its queue forever while /health answered 200. The pool reconnects on its own; the warn line names the pool, the age, the queue depth and the statement by keyword and table.", docs: 'docs/ENGINES.md#pg-connection-stuck', suggestion: 'Retry the failed call. If the line repeats, run gbrain doctor --json and report the warn lines with the operations that preceded them; GBRAIN_PG_STUCK_GRACE_MS raises the grace, and off disables the watchdog.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports pool pressure, the pooler mode and the recent persistence hold lines beside this warning.', requires_exclusive: false } },
pg_pool_stalled: { class: 'retryable', summary: "The Postgres pool of a resident gbrain process has had connections checked out or statements waiting for one across two 30 s ticks without completing a single statement.", why: "One slow statement is one quiet tick; two in a row with nothing settled means every checked-out connection is waiting on the server at once, which is what a wedged pool or an unreachable database looks like from inside the process. With the in-flight watchdog on, the stall ends within statement_timeout plus grace and a pg_pool_recovered line follows; with it off this line is the only trace.", docs: 'docs/ENGINES.md#pg-pool-stalled', suggestion: 'Wait one more tick for pg_pool_recovered or pg_connection_stuck; if the line keeps repeating, check the database and pooler (gbrain doctor --json) and restart the process if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: checks the database and pooler from a fresh process beside the stalled one.', requires_exclusive: false } },
diff --git a/src/core/git-remote.ts b/src/core/git-remote.ts
index 6e38ab0317..0328ca8b6b 100644
--- a/src/core/git-remote.ts
+++ b/src/core/git-remote.ts
@@ -21,42 +21,9 @@ import { isAbsolute, join } from 'path';
import { isInternalUrl } from './url-safety.ts';
import { execFileBounded } from './bounded-child-exec.ts';
import { gitChildEnv } from './git-env.ts';
-
-/**
- * Git CLI accepts two flag positions:
- * git [global -c flags] <subcommand> [subcommand flags] [args]
- *
- * Global flags (the `-c key=value` config overrides) MUST come before the
- * subcommand. Subcommand-specific flags (like `--no-recurse-submodules`)
- * MUST come after the subcommand. Mixing the two positions makes git fail
- * with `unknown option` (exit 129). Pre-v0.34 the single GIT_SSRF_FLAGS
- * constant spliced both positions before the verb; real git rejected the
- * subcommand flag but the test harness used a fake-git script that didn't
- * validate, so every remote-source clone/pull broke silently in production.
- *
- * Split into two constants so the call-site spread is unambiguous and the
- * type/name signal the position rule.
- */
-
-/**
- * Global git config flags. Spread BEFORE the subcommand verb.
- * - http.followRedirects=false: closes DNS rebinding via redirect chains
- * - protocol.file.allow=never: no local-file URLs (defense in depth)
- * - protocol.ext.allow=never: no external helpers (`git-remote-foo`)
- */
-export const GIT_SSRF_FLAGS = [
- '-c', 'http.followRedirects=false',
- '-c', 'protocol.file.allow=never',
- '-c', 'protocol.ext.allow=never',
-] as const;
-
-/**
- * Subcommand-level flags. Spread AFTER the subcommand verb (clone/pull).
- * - --no-recurse-submodules: .gitmodules cannot become a second fetch surface
- */
-export const GIT_SSRF_SUBCOMMAND_FLAGS = [
- '--no-recurse-submodules',
-] as const;
+import { GIT_SSRF_FLAGS, GIT_SSRF_SUBCOMMAND_FLAGS, GIT_ENV, GIT_ENV_AUTH, durableSsrfFlags } from './git-transport.ts';
+export { GIT_SSRF_FLAGS, GIT_SSRF_SUBCOMMAND_FLAGS, buildGitEnv, GIT_ENV, GIT_ENV_AUTH, durableSsrfFlags } from './git-transport.ts';
+import { pullShared, acquireCommitLockAsync } from './git/commit-push.ts';
export type RemoteUrlErrorCode =
| 'invalid_url'
@@ -162,55 +129,6 @@ function gitErrorDetail(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
-/**
- * Build the strict no-prompt git env for the current (or given) platform.
- *
- * POSIX: confine to the gbrain SSRF model — no credential helpers, no SSH
- * askpass, no GUI prompts (`/bin/false` fails any askpass invocation fast).
- *
- * win32 (#1315): `/bin/false` does not exist, so pointing GIT_ASKPASS at it
- * makes every authed operation die with a confusing "could not run askpass"
- * spawn error instead of failing auth cleanly. Drop both askpass overrides
- * there and set `SSH_ASKPASS_REQUIRE=never` (OpenSSH 8.4+) so ssh never
- * pops a GUI prompt; `GIT_TERMINAL_PROMPT=0` remains the no-terminal-prompt
- * guard on every platform.
- *
- * Pure + platform-parameterized so the win32 shape is unit-testable on
- * POSIX CI (no Windows runner exists).
- */
-export function buildGitEnv(
- platform: NodeJS.Platform = process.platform,
-): Record<string, string> {
- const env: Record<string, string> = {
- GIT_TERMINAL_PROMPT: '0',
- GCM_INTERACTIVE: 'never',
- };
- if (platform === 'win32') {
- env.SSH_ASKPASS_REQUIRE = 'never';
- } else {
- env.GIT_ASKPASS = '/bin/false';
- env.SSH_ASKPASS = '/bin/false';
- }
- return env;
-}
-
-export const GIT_ENV = buildGitEnv();
-
-/**
- * Auth-capable git env for the durability push/probe paths (v0.42.44).
- *
- * Read-only clone/pull keep the strict GIT_ENV (askpass=/bin/false) so they can
- * never prompt. But push, push-probe, and the durability cron's authed fetch
- * MUST be able to consult the repo's configured credential helper (repo-scoped
- * `store`/`osxkeychain`) — a `/bin/false` askpass would defeat that. We drop the
- * askpass overrides but KEEP `GIT_TERMINAL_PROMPT=0` so a *missing* credential
- * fails fast instead of hanging a non-interactive cron forever.
- */
-export const GIT_ENV_AUTH = {
- GIT_TERMINAL_PROMPT: '0',
- GCM_INTERACTIVE: 'never',
-} as const;
-
/**
* Clone a remote git repo with SSRF-defensive flags.
* - destDir must NOT exist or must be empty.
@@ -277,17 +195,35 @@ export function cloneRepo(url: string, destDir: string, opts: CloneOpts = {}): v
*/
export async function pullRepo(repoPath: string, opts: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise<void> {
assertManagedFilesystemWrite(repoPath);
- const argv = ['-C', repoPath, ...durableSsrfFlags(), 'pull', ...GIT_SSRF_SUBCOMMAND_FLAGS, '--ff-only'];
- const run = await execFileBounded('git', argv, {
+ const fail = (reason: string, error: unknown): never => {
+ throw new GitOperationError('pull', `git pull failed in ${repoPath}: ${reason}`, error);
+ };
+ // #6530: fetch outside the writer lock, then fast-forward under it with
+ // autostash off, so a shared checkout is never stashed or moved mid-commit.
+ const fetch = await execFileBounded('git', ['-C', repoPath, ...durableSsrfFlags(), 'fetch', ...GIT_SSRF_SUBCOMMAND_FLAGS], {
timeout: opts.timeoutMs ?? 300_000,
env: gitChildEnv({ ...GIT_ENV }),
signal: opts.signal,
});
- if (!run.error) return;
// execFile hands stderr back beside the error rather than on it, so lead
// with it here to keep the #1315 stderr-first message.
- const reason = run.stderr.trim() || run.error.message;
- throw new GitOperationError('pull', `git pull failed in ${repoPath}: ${reason}`, run.error);
+ if (fetch.error) fail(fetch.stderr.trim() || fetch.error.message, fetch.error);
+ let lock: { release(): Promise<void> };
+ try {
+ lock = await acquireCommitLockAsync(repoPath, undefined, opts.signal);
+ } catch (e) {
+ return fail((e as Error).message, opts.signal?.aborted ? Object.assign(new Error('pull stopped'), { code: 'ABORT_ERR' }) : e);
+ }
+ try {
+ const merge = await execFileBounded('git', ['-C', repoPath, '-c', 'core.hooksPath=/dev/null', '-c', 'merge.autoStash=false', 'merge', '--ff-only', '--quiet', '@{upstream}'], {
+ timeout: opts.timeoutMs ?? 300_000,
+ env: gitChildEnv({ ...GIT_ENV }),
+ signal: opts.signal,
+ });
+ if (merge.error) fail(merge.stderr.trim() || merge.error.message, merge.error);
+ } finally {
+ await lock.release();
+ }
}
/**
@@ -478,23 +414,6 @@ export function hasTrackedContent(path: string): boolean {
// the DB-free pull cron. These are the auth-capable, rebase-aware counterparts
// to the strict read-only `pullRepo` (which stays `--ff-only` for `sync.ts`).
-/**
- * Global SSRF flags for the durability fetch/pull/push paths. Identical to
- * GIT_SSRF_FLAGS except `protocol.file.allow` honors the env escape hatch
- * `GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1` (mirrors GBRAIN_ALLOW_PRIVATE_REMOTES) so
- * self-hosted local-filesystem remotes — and the test suite — can use the file
- * transport. Default stays `never`. These ops act on an ALREADY-validated origin
- * (set + checked at clone time); `http.followRedirects=false` is the live guard.
- */
-export function durableSsrfFlags(): string[] {
- const fileAllow = process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT === '1' ? 'always' : 'never';
- return [
- '-c', 'http.followRedirects=false',
- '-c', `protocol.file.allow=${fileAllow}`,
- '-c', 'protocol.ext.allow=never',
- ];
-}
-
/** Run a git subcommand, returning trimmed stdout. Throws GitOperationError. */
function runGit(
repoPath: string,
@@ -567,6 +486,7 @@ export type PullOutcome =
| { status: 'up_to_date' }
| { status: 'advanced'; from: string; to: string }
| { status: 'skipped_dirty' }
+ | { status: 'skipped_busy' }
| { status: 'conflict_aborted'; detail: string };
/** How `divergenceSafePull` reconciles local commits with origin (#5429): `sources.config.pull_strategy`, default `rebase`. */
@@ -581,25 +501,20 @@ export function pullStrategyOf(config: Record<string, unknown> | null | undefine
}
/**
- * Divergence-safe pull: `fetch` + `pull --rebase` (or `pull --no-rebase` under
- * `strategy: 'merge'`), never leaving a mid-rebase or a mid-merge.
+ * Divergence-safe pull for a checkout other writers share (#6530). Delegates
+ * to `pullShared` (src/core/git/commit-push.ts): fetch outside the writer
+ * lock, then under `brain-commit.lock` fast-forward, or merge diverged history
+ * IN MEMORY and fast-forward to the merge. Nothing rebases, stashes or resets
+ * the working tree, and no rebase or merge state can be left behind.
*
- * - Dirty working tree → `skipped_dirty` (NORMAL mid-session state, not an
- * error; never auto-stashes, never touches in-progress edits). The pull
- * itself carries `--no-autostash` (#5429): a repository or user
- * `rebase.autoStash=true` would otherwise stash edits made between the
- * dirty check and the pull and replay them onto the rebased tree.
- * - Rebase conflict → `git rebase --abort`, verify no rebase state remains,
- * return `conflict_aborted` ("manual attention needed"). Never throws past
- * this — the repo is always left clean (possibly un-advanced).
- * - Merge strategy → fast-forward when possible, else a merge commit
- * (`--no-edit`); a conflict runs `git merge --abort`, verifies MERGE_HEAD is
- * gone and returns `conflict_aborted`. For a brain whose intermediate
- * snapshot commits conflict under rebase replay while the two tips merge
- * cleanly (#5429); per source via `sources.config.pull_strategy`.
+ * - Any local edit → `skipped_dirty` (the unattended rule: never move files
+ * under a writer mid-edit), checked before and again under the lock.
+ * - Another writer holds the lock → `skipped_busy`; the next run catches up.
+ * - Both sides changed a file → `conflict_aborted`; nothing changed.
*
- * Auth-capable (GIT_ENV_AUTH) so it works against private remotes via the
- * repo's configured credential helper. SSRF flags applied on every call.
+ * `strategy` is kept for callers and `sources set-pull-strategy`; since #6530
+ * both strategies integrate by merge (the shared tree is never rebased).
+ * Auth-capable and SSRF-hardened through the same transport flags as before.
*/
export function divergenceSafePull(
repoPath: string,
@@ -607,50 +522,19 @@ export function divergenceSafePull(
opts: { timeoutMs?: number; strategy?: PullStrategy } = {},
): PullOutcome {
assertManagedFilesystemWrite(repoPath);
- const timeoutMs = opts.timeoutMs ?? 300_000;
- const merge = opts.strategy === 'merge';
-
- if (isWorkingTreeDirty(repoPath)) return { status: 'skipped_dirty' };
-
- const before = runGit(repoPath, [], 'rev-parse', ['HEAD'], 'pull', { timeoutMs: 10_000 });
- const ssrf = durableSsrfFlags();
-
- runGit(repoPath, ssrf, 'fetch', [...GIT_SSRF_SUBCOMMAND_FLAGS, 'origin', branch], 'pull', {
- timeoutMs, env: { ...GIT_ENV_AUTH },
- });
-
- const mode = merge ? ['--no-rebase', '--no-edit', '--no-autostash'] : ['--rebase', '--no-autostash'];
try {
- runGit(repoPath, ssrf, 'pull', [...GIT_SSRF_SUBCOMMAND_FLAGS, ...mode, 'origin', branch], 'pull', {
- timeoutMs, env: { ...GIT_ENV_AUTH },
- });
+ const r = pullShared(repoPath, { requireClean: true, remoteBranch: branch, fetchTimeoutMs: opts.timeoutMs ?? 300_000 });
+ if (r.status === 'advanced') return { status: 'advanced', from: r.from!, to: r.to! };
+ if (r.status === 'skipped_dirty' || r.status === 'lagging') return { status: 'skipped_dirty' };
+ return { status: 'up_to_date' };
} catch (e) {
- // Abort any half-applied rebase or merge so the tree is never left mid-operation.
- const abort = merge ? ['merge', '--abort'] : ['rebase', '--abort'];
- const inProgress = () => merge ? gitStateExists(repoPath, 'MERGE_HEAD') : rebaseInProgress(repoPath);
- try {
- execFileSync('git', ['-C', repoPath, ...abort], {
- stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }),
- });
- } catch { /* best-effort */ }
- // If state STILL remains, try once more, then report regardless.
- if (inProgress()) {
- try {
- execFileSync('git', ['-C', repoPath, ...abort], {
- stdio: 'ignore', timeout: 30_000, env: gitChildEnv({ ...GIT_ENV }),
- });
- } catch { /* best-effort */ }
+ const code = (e as { code?: string }).code;
+ if (code === 'commit_lock_busy') return { status: 'skipped_busy' };
+ if (code === 'integrate_conflict' || code === 'git_operation_in_progress' || code === 'git_detached_head') {
+ return { status: 'conflict_aborted', detail: `pull on ${branch} conflicted and was not applied: ${(e as Error).message} — manual attention needed` };
}
- return {
- status: 'conflict_aborted',
- detail: merge
- ? `pull --no-rebase (merge) on ${branch} conflicted; merge aborted — manual attention needed (${(e as Error).message.slice(0, 120)})`
- : `pull --rebase on ${branch} conflicted; rebase aborted — manual attention needed (${(e as Error).message.slice(0, 120)})`,
- };
+ throw new GitOperationError('pull', `git pull failed in ${repoPath}: ${(e as Error).message}${(e as { suggestion?: string }).suggestion ? ` ${(e as { suggestion?: string }).suggestion}` : ''}`, e);
}
-
- const after = runGit(repoPath, [], 'rev-parse', ['HEAD'], 'pull', { timeoutMs: 10_000 });
- return before === after ? { status: 'up_to_date' } : { status: 'advanced', from: before, to: after };
}
export type PushProbeResult =
diff --git a/src/core/git-transport.ts b/src/core/git-transport.ts
new file mode 100644
index 0000000000..312f02a6a4
--- /dev/null
+++ b/src/core/git-transport.ts
@@ -0,0 +1,107 @@
+/**
+ * Git transport hardening shared by every remote git call (#6530 split this
+ * out of git-remote.ts so src/core/git/ can use it without an import cycle;
+ * git-remote.ts re-exports every name here).
+ */
+
+/**
+ * Git CLI accepts two flag positions:
+ * git [global -c flags] <subcommand> [subcommand flags] [args]
+ *
+ * Global flags (the `-c key=value` config overrides) MUST come before the
+ * subcommand. Subcommand-specific flags (like `--no-recurse-submodules`)
+ * MUST come after the subcommand. Mixing the two positions makes git fail
+ * with `unknown option` (exit 129). Pre-v0.34 the single GIT_SSRF_FLAGS
+ * constant spliced both positions before the verb; real git rejected the
+ * subcommand flag but the test harness used a fake-git script that didn't
+ * validate, so every remote-source clone/pull broke silently in production.
+ *
+ * Split into two constants so the call-site spread is unambiguous and the
+ * type/name signal the position rule.
+ */
+
+/**
+ * Global git config flags. Spread BEFORE the subcommand verb.
+ * - http.followRedirects=false: closes DNS rebinding via redirect chains
+ * - protocol.file.allow=never: no local-file URLs (defense in depth)
+ * - protocol.ext.allow=never: no external helpers (`git-remote-foo`)
+ */
+export const GIT_SSRF_FLAGS = [
+ '-c', 'http.followRedirects=false',
+ '-c', 'protocol.file.allow=never',
+ '-c', 'protocol.ext.allow=never',
+] as const;
+
+/**
+ * Subcommand-level flags. Spread AFTER the subcommand verb (clone/pull).
+ * - --no-recurse-submodules: .gitmodules cannot become a second fetch surface
+ */
+export const GIT_SSRF_SUBCOMMAND_FLAGS = [
+ '--no-recurse-submodules',
+] as const;
+
+/**
+ * Build the strict no-prompt git env for the current (or given) platform.
+ *
+ * POSIX: confine to the gbrain SSRF model — no credential helpers, no SSH
+ * askpass, no GUI prompts (`/bin/false` fails any askpass invocation fast).
+ *
+ * win32 (#1315): `/bin/false` does not exist, so pointing GIT_ASKPASS at it
+ * makes every authed operation die with a confusing "could not run askpass"
+ * spawn error instead of failing auth cleanly. Drop both askpass overrides
+ * there and set `SSH_ASKPASS_REQUIRE=never` (OpenSSH 8.4+) so ssh never
+ * pops a GUI prompt; `GIT_TERMINAL_PROMPT=0` remains the no-terminal-prompt
+ * guard on every platform.
+ *
+ * Pure + platform-parameterized so the win32 shape is unit-testable on
+ * POSIX CI (no Windows runner exists).
+ */
+export function buildGitEnv(
+ platform: NodeJS.Platform = process.platform,
+): Record<string, string> {
+ const env: Record<string, string> = {
+ GIT_TERMINAL_PROMPT: '0',
+ GCM_INTERACTIVE: 'never',
+ };
+ if (platform === 'win32') {
+ env.SSH_ASKPASS_REQUIRE = 'never';
+ } else {
+ env.GIT_ASKPASS = '/bin/false';
+ env.SSH_ASKPASS = '/bin/false';
+ }
+ return env;
+}
+
+export const GIT_ENV = buildGitEnv();
+
+/**
+ * Auth-capable git env for the durability push/probe paths (v0.42.44).
+ *
+ * Read-only clone/pull keep the strict GIT_ENV (askpass=/bin/false) so they can
+ * never prompt. But push, push-probe, and the durability cron's authed fetch
+ * MUST be able to consult the repo's configured credential helper (repo-scoped
+ * `store`/`osxkeychain`) — a `/bin/false` askpass would defeat that. We drop the
+ * askpass overrides but KEEP `GIT_TERMINAL_PROMPT=0` so a *missing* credential
+ * fails fast instead of hanging a non-interactive cron forever.
+ */
+export const GIT_ENV_AUTH = {
+ GIT_TERMINAL_PROMPT: '0',
+ GCM_INTERACTIVE: 'never',
+} as const;
+
+/**
+ * Global SSRF flags for the durability fetch/pull/push paths. Identical to
+ * GIT_SSRF_FLAGS except `protocol.file.allow` honors the env escape hatch
+ * `GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1` (mirrors GBRAIN_ALLOW_PRIVATE_REMOTES) so
+ * self-hosted local-filesystem remotes — and the test suite — can use the file
+ * transport. Default stays `never`. These ops act on an ALREADY-validated origin
+ * (set + checked at clone time); `http.followRedirects=false` is the live guard.
+ */
+export function durableSsrfFlags(): string[] {
+ const fileAllow = process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT === '1' ? 'always' : 'never';
+ return [
+ '-c', 'http.followRedirects=false',
+ '-c', `protocol.file.allow=${fileAllow}`,
+ '-c', 'protocol.ext.allow=never',
+ ];
+}
diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.ts
new file mode 100644
index 0000000000..4f09af4935
--- /dev/null
+++ b/src/core/git/commit-push.ts
@@ -0,0 +1,792 @@
+/**
+ * Shared-checkout-safe commit, push and pull for classic (unmanaged) brain
+ * repos (#6530). Many writers (agents, crons, hooks, gbrain's own
+ * write-through) commit to ONE checkout, so nothing here rebases, stashes or
+ * resets the working tree:
+ *
+ * 1. two locks per checkout: the short commit lock (`git rev-parse --git-path
+ * brain-commit.lock`, the same flock a bash `flock -x` takes) for local
+ * index/HEAD changes only, and the publish lock (brain-publish.lock) for
+ * the network push; a publisher takes the commit lock only to advance, and
+ * an unattended publisher that finds the publish lock busy leaves a request
+ * the holder honors after it releases (so no commit is stranded);
+ * 2. commits carry only the caller's paths (`commit --only -- <paths>`);
+ * 3. a rejected push is integrated IN MEMORY (`merge-tree --write-tree`, or a
+ * 3-way `read-tree` into a temporary index on git < 2.38) into a merge
+ * commit built with `commit-tree`; no working tree is touched;
+ * 4. the shared checkout advances only by `merge --ff-only`, which refuses
+ * (and changes nothing) when HEAD moved or a file it must change is dirty.
+ *
+ * Managed canonical worktrees are refused: the persistence owner is their
+ * only writer. CLI-only; never exposed over MCP (it pushes with host
+ * credentials).
+ */
+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { isAbsolute, join, relative, resolve } from 'node:path';
+import { execFileSync } from '../spawn.ts';
+import { gitChildEnv } from '../git-env.ts';
+import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, durableSsrfFlags } from '../git-transport.ts';
+import { assertManagedFilesystemWrite } from '../persistence/filesystem-guard.ts';
+import { acquireNativeLock, acquireNativeLockSync, type NativeLockSyncHandle } from '../persistence/native-lock.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+
+export const COMMIT_LOCK_NAME = 'brain-commit.lock';
+/** Taken by pre-#6530 helpers and hooks; held too so they still exclude us during the mixed-version window. */
+export const LEGACY_PUSH_LOCK_NAME = 'gbrain-push.lock';
+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';
+const MAX_PUSH_ATTEMPTS = 8;
+const sleeper = new Int32Array(new SharedArrayBuffer(4));
+const INDEX_LOCK_RETRIES = 5;
+
+export type CheckoutState = 'advanced' | 'unchanged' | 'lagging';
+
+export interface CommitPushResult {
+ /** `push_deferred`: an unattended publish found another publish running and left it a request to publish HEAD too. */
+ outcome: 'pushed' | 'nothing_to_commit' | 'pushed_checkout_lagging' | 'push_deferred';
+ /** The commit now on the remote branch (the caller's commit or the merge built over it). */
+ sha: string | null;
+ committed: string | null;
+ branch: string;
+ remote: string;
+ paths: string[];
+ /** Remote commits merged in to publish. */
+ integrated: number;
+ /** `remote`: a push reported failure but every push destination already holds the commit (a lost acknowledgement or a concurrent pusher). */
+ confirmed?: 'push' | 'remote';
+ checkout: CheckoutState;
+ lagging_reason?: string;
+}
+
+export interface PullResult {
+ status: 'up_to_date' | 'advanced' | 'ahead' | 'skipped_dirty' | 'lagging';
+ from?: string;
+ to?: string;
+ merged?: boolean;
+ /** Why the checkout could not advance (dirty must-change file, HEAD moved). */
+ reason?: string;
+}
+
+export interface CommitPushOptions {
+ repo: string;
+ /** Paths to commit, absolute or relative to `cwd`. Ignored with pushOnly. */
+ paths?: string[];
+ message?: string;
+ pushOnly?: boolean;
+ cwd?: string;
+ lockWaitMs?: number;
+ /** `--resolve`: blob choice per conflicted path for the in-memory merge. */
+ resolutions?: Map<string, Resolution>;
+ /** `--expect-remote`: the remote commit the resolutions were chosen against (required with resolutions). */
+ expectRemote?: string;
+ /** How long a foreground publish waits for another publish to finish. */
+ publishWaitMs?: number;
+ /** Unattended callers (the post-commit hook): publish, but advance the checkout only when it has no local edit. */
+ advanceOnlyWhenClean?: boolean;
+ /** Push-only: publish HEAD to this remote branch instead of the checked-out branch's upstream (the helper's `--push-only <branch>`). */
+ branch?: string;
+}
+
+export type Resolution = { kind: 'ours' } | { kind: 'theirs' } | { kind: 'file'; path: string };
+
+interface Ctx {
+ root: string;
+ branch: string;
+ remote: string;
+ mergeRef: string;
+ trackingRef: string;
+}
+
+interface GitRun { code: number; stdout: string; stderr: string }
+
+function git(root: string, args: string[], opts: { auth?: boolean; timeoutMs?: number; env?: NodeJS.ProcessEnv; input?: string } = {}): GitRun {
+ const base = opts.auth ? { ...GIT_ENV_AUTH } : { ...GIT_ENV };
+ try {
+ const stdout = execFileSync('git', ['-C', root, ...args], {
+ stdio: ['pipe', 'pipe', 'pipe'],
+ input: opts.input ?? '',
+ timeout: opts.timeoutMs ?? 60_000,
+ env: gitChildEnv({ ...base, LC_ALL: 'C', LANGUAGE: 'C', ...opts.env }),
+ }).toString();
+ return { code: 0, stdout, stderr: '' };
+ } catch (e) {
+ const err = e as { status?: number | null; stdout?: Buffer | string; stderr?: Buffer | string; message?: string };
+ return {
+ code: typeof err.status === 'number' ? err.status : -1,
+ stdout: String(err.stdout ?? ''),
+ stderr: String(err.stderr ?? err.message ?? ''),
+ };
+ }
+}
+
+function gitOk(root: string, args: string[], what: string, opts: Parameters<typeof git>[2] = {}): string {
+ const r = git(root, args, opts);
+ if (r.code !== 0) {
+ throw opError('git_unavailable', `git ${what} failed in ${root}.`,
+ `${r.stderr.trim().slice(0, 300) || `exit ${r.code}`}`);
+ }
+ return r.stdout.trim();
+}
+
+/**
+ * Transport flags for this checkout's OWN configured remotes: no redirects, no
+ * external helpers, no submodule fetch surface. The file protocol keeps git's
+ * default (`user`): a bare repo on the same host is a supported brain topology
+ * (the pre-#6530 helper pushed to it with plain git), and the URL is the
+ * operator's own config, not remote-supplied input. GBRAIN_GIT_ALLOW_FILE_TRANSPORT
+ * still forces `always` for tests.
+ */
+function transportFlags(): string[] {
+ return durableSsrfFlags().flatMap((flag, i, all) =>
+ all[i - 1] === '-c' && flag.startsWith('protocol.file.allow=') && process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT !== '1'
+ ? ['protocol.file.allow=user'] : [flag]);
+}
+
+/** Remote operations: transport hardening on every call, credentials allowed, no prompt. */
+function remoteGit(root: string, sub: 'fetch' | 'push', args: string[], timeoutMs = 120_000): GitRun {
+ return git(root, [...transportFlags(), sub, ...GIT_SSRF_SUBCOMMAND_FLAGS, ...args], { auth: true, timeoutMs });
+}
+
+export function gitVersion(root: string): [number, number] {
+ const m = /git version (\d+)\.(\d+)/.exec(gitOk(root, ['version'], 'version'));
+ return m ? [Number(m[1]), Number(m[2])] : [0, 0];
+}
+
+function absGitPath(root: string, rel: string): string {
+ const p = gitOk(root, ['rev-parse', '--git-path', rel], 'rev-parse --git-path');
+ if (!p) throw opError('git_unavailable', `git rev-parse --git-path ${rel} printed nothing in ${root}.`, 'Check that git works in this checkout (git status).');
+ return isAbsolute(p) ? p : resolve(root, p);
+}
+
+/** The checkout's toplevel; throws `commit_paths_invalid` outside a work tree. */
+export function checkoutRoot(dir: string): string {
+ const r = git(dir, ['rev-parse', '--show-toplevel']);
+ if (r.code !== 0 || !r.stdout.trim()) {
+ throw opError('commit_paths_invalid', `${dir} is not inside a git checkout.`,
+ 'Run the command inside the brain checkout or pass --path <checkout>.');
+ }
+ return r.stdout.trim();
+}
+
+function resolveCtx(root: string): Ctx {
+ const sym = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
+ if (sym.code !== 0) {
+ throw opError('git_detached_head', `${root} is on a detached HEAD, so there is no branch to publish.`,
+ 'Check out the branch the remote tracks (git switch <branch>), then rerun.');
+ }
+ const branch = sym.stdout.trim();
+ if (git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']).code !== 0) {
+ throw opError('git_detached_head', `Branch ${branch} in ${root} has no commit yet.`,
+ 'Make the first commit on this branch with git, then rerun.', { reason: 'unborn' });
+ }
+ const remote = git(root, ['config', '--get', `branch.${branch}.remote`]).stdout.trim() || 'origin';
+ const mergeRef = git(root, ['config', '--get', `branch.${branch}.merge`]).stdout.trim() || `refs/heads/${branch}`;
+ if (remote === '.' || git(root, ['remote', 'get-url', '--', remote]).code !== 0) {
+ throw opError('git_unavailable', `Branch ${branch} in ${root} has no usable remote (${remote}); nothing was committed.`,
+ `Add the remote (git remote add ${remote} <url>) or set the branch upstream, then rerun.`);
+ }
+ const short = mergeRef.replace(/^refs\/heads\//, '');
+ return { root, branch, remote, mergeRef, trackingRef: `refs/remotes/${remote}/${short}` };
+}
+
+/** `--push-only <branch>`: publish to an explicit remote branch (validated as one exact ref, never a pattern). */
+function withBranch(ctx: Ctx, branch: string | undefined): Ctx {
+ if (!branch) return ctx;
+ const short = branch.replace(/^refs\/heads\//, '');
+ if (!short || git(ctx.root, ['check-ref-format', `refs/heads/${short}`]).code !== 0) {
+ throw opError('commit_paths_invalid', `${branch} is not a valid branch name.`, 'Pass one exact branch name, e.g. --branch main.', { detail: branch });
+ }
+ return { ...ctx, mergeRef: `refs/heads/${short}`, trackingRef: `refs/remotes/${ctx.remote}/${short}` };
+}
+
+/** Refuse while another git operation is mid-flight; never abort it for the user. */
+function assertNoOperationInProgress(root: string): void {
+ for (const marker of ['rebase-merge', 'rebase-apply', 'MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'sequencer']) {
+ if (existsSync(absGitPath(root, marker))) {
+ throw opError('git_operation_in_progress', `A git ${marker.startsWith('rebase') ? 'rebase' : marker.toLowerCase().replace(/_head$/, '')} is in progress in ${root}.`,
+ `Finish or abort it first. A stuck rebase may hold another writer's autostash: save it with git stash store <sha from .git/${marker}/autostash> before deleting anything. See docs/guides/shared-checkout-git.md#stuck-rebase.`,
+ { detail: marker });
+ }
+ }
+}
+
+// ── Lock ────────────────────────────────────────────────────────────────────
+
+export interface CommitLock { release(): void; lockPath: string; reentrant: boolean }
+
+/**
+ * Take this checkout's commit lock (and the legacy push lock). Re-entrant only
+ * when BRAIN_COMMIT_LOCK_HELD names this exact lock AND the lock is really
+ * held: a stale, spoofed or generic (`1`) marker cannot bypass a lock.
+ */
+export function acquireCommitLock(root: string, waitMs = defaultLockWaitMs()): CommitLock {
+ const lockPath = absGitPath(root, COMMIT_LOCK_NAME);
+ const legacyPath = absGitPath(root, LEGACY_PUSH_LOCK_NAME);
+ const marker = process.env[COMMIT_LOCK_ENV];
+ if (marker && marker !== '1' && resolve(marker) === lockPath) {
+ const probe = acquireNativeLockSync(lockPath, { timeoutMs: 0 });
+ if (!probe) return { release() {}, lockPath, reentrant: true };
+ return withLegacy(root, probe, lockPath, legacyPath, waitMs);
+ }
+ const handle = acquireNativeLockSync(lockPath, { timeoutMs: waitMs });
+ if (!handle) throw lockBusy(lockPath, waitMs);
+ return withLegacy(root, handle, lockPath, legacyPath, waitMs);
+}
+
+function withLegacy(root: string, handle: NativeLockSyncHandle, lockPath: string, legacyPath: string, waitMs: number): CommitLock {
+ let legacy: NativeLockSyncHandle | null;
+ try { legacy = acquireNativeLockSync(legacyPath, { timeoutMs: waitMs }); }
+ catch (e) { handle.release(); throw e; }
+ if (!legacy) { handle.release(); throw lockBusy(legacyPath, waitMs, root); }
+ return { lockPath, reentrant: false, release() { legacy!.release(); handle.release(); } };
+}
+
+/** The same locks for async callers (`gbrain sync`'s pull), without blocking the event loop while waiting. */
+export async function acquireCommitLockAsync(root: string, waitMs = defaultLockWaitMs(), signal?: AbortSignal): Promise<{ release(): Promise<void> }> {
+ const lockPath = absGitPath(root, COMMIT_LOCK_NAME);
+ const legacyPath = absGitPath(root, LEGACY_PUSH_LOCK_NAME);
+ const handle = await acquireNativeLock(lockPath, { timeoutMs: waitMs, signal });
+ if (!handle) throw lockBusy(lockPath, waitMs, root);
+ let legacy;
+ try { legacy = await acquireNativeLock(legacyPath, { timeoutMs: waitMs, signal }); }
+ catch (e) { await handle.release(); throw e; }
+ if (!legacy) { await handle.release(); throw lockBusy(legacyPath, waitMs, root); }
+ return { async release() { await legacy.release(); await handle.release(); } };
+}
+
+function defaultLockWaitMs(): number {
+ const raw = process.env.GBRAIN_COMMIT_LOCK_WAIT_SECONDS ?? process.env.GBRAIN_PUSH_LOCK_WAIT_SECONDS;
+ const secs = raw === undefined ? 60 : Number(raw);
+ return Number.isFinite(secs) && secs >= 0 ? secs * 1000 : 60_000;
+}
+
+function lockBusy(lockPath: string, waitMs: number, root?: string): OperationError {
+ return opError('commit_lock_busy', `Another writer held this checkout's commit lock for ${Math.round(waitMs / 1000)}s.`,
+ `Another commit or push is running in ${root ?? 'this checkout'} (lock ${lockPath}). Retry once it finishes; nothing was committed.`,
+ { detail: lockPath, retryable: true });
+}
+
+// ── Paths ───────────────────────────────────────────────────────────────────
+
+/** Repo-relative paths; refuses the root itself, `.git` and anything outside the checkout. */
+export function scopePaths(root: string, paths: string[], cwd: string): string[] {
+ if (paths.length === 0) {
+ throw opError('commit_paths_invalid', 'No paths to commit.',
+ 'Pass the explicit file(s) you wrote; a repo-wide commit would sweep up other writers\' files.');
+ }
+ const out: string[] = [];
+ for (const p of paths) {
+ const abs = resolve(cwd, p);
+ const rel = relative(root, abs);
+ if (rel === '' || rel === '.' || rel.startsWith('..') || isAbsolute(rel)) {
+ throw opError('commit_paths_invalid', `Path ${p} is ${rel === '' || rel === '.' ? 'the whole checkout' : 'outside the checkout'}.`,
+ 'Pass the explicit file(s) you wrote inside the checkout; a repo-wide commit would sweep up other writers\' files.', { detail: p });
+ }
+ if (rel.split(/[\\/]/)[0] === '.git') {
+ throw opError('commit_paths_invalid', `Path ${p} is inside .git.`, 'Pass files in the working tree.', { detail: p });
+ }
+ out.push(rel.split('\\').join('/'));
+ }
+ return [...new Set(out)];
+}
+
+// ── Commit ──────────────────────────────────────────────────────────────────
+
+function indexLocked(r: GitRun): boolean {
+ return /index\.lock': File exists|Unable to create '.*index\.lock'/.test(r.stderr);
+}
+
+/** 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 {
+ for (let attempt = 0; ; attempt++) {
+ const r = git(root, args, { env, timeoutMs: 120_000 });
+ if (r.code === 0 || !indexLocked(r)) return r;
+ if (attempt >= INDEX_LOCK_RETRIES) {
+ const lock = absGitPath(root, 'index.lock');
+ let ageMs = 0;
+ try { ageMs = Date.now() - statSync(lock).mtimeMs; } catch { /* gone */ }
+ if (ageMs > 10 * 60_000) {
+ throw opError('git_index_stale', `A Git index lock older than 10 minutes blocks ${root}: ${lock}.`,
+ `If no git command is running in that checkout, remove ${lock}, then rerun. Nothing was committed.`, { detail: lock });
+ }
+ throw opError('git_index_locked', `Another git process kept ${root}'s index locked during ${what}.`,
+ 'A git command that does not take the commit lock is running in this checkout. Retry shortly; nothing was committed.', { detail: lock, retryable: true });
+ }
+ Atomics.wait(sleeper, 0, 0, 100 * 2 ** attempt + Math.floor(Math.random() * 100));
+ }
+}
+
+/** A staged rename (`git mv`) commits both sides: committing only the new name would publish a duplicate and leave the deletion staged for another writer's commit. */
+function withRenamePartners(root: string, rel: string[]): string[] {
+ const fields = git(root, ['diff', '--cached', '-M', '--name-status', '-z']).stdout.split('\0');
+ const out = new Set(rel);
+ for (let i = 0; i < fields.length;) {
+ const status = fields[i];
+ if (!status) break;
+ if (/^[RC]/.test(status)) {
+ const [from, to] = [fields[i + 1], fields[i + 2]];
+ if (status.startsWith('R') && (out.has(from) || out.has(to))) { out.add(from); out.add(to); }
+ i += 3;
+ } else i += 2;
+ }
+ return [...out];
+}
+
+function commitPaths(root: string, rel: string[], message: string, lockPath: string | null): string | null {
+ 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.`);
+ }
+ return gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');
+}
+
+/**
+ * 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.
+ */
+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; }
+ try {
+ return commitPaths(root, paths, message, null);
+ } finally {
+ lock?.release();
+ }
+}
+
+// ── In-memory integrate ─────────────────────────────────────────────────────
+
+interface MergeTree {
+ /** The merged tree; with conflicts, a placeholder every conflicted path must be resolved over. */
+ tree: string | null;
+ /** Raw repo-relative paths (NUL-delimited from git, never C-quoted). */
+ conflicts: string[];
+ /** Conflicts that are not one path's content (file/directory, renames): never resolvable by a blob choice. */
+ structural: string[];
+}
+
+/** merge-tree conflict types a per-path blob choice fully resolves; anything else is structural. */
+const RESOLVABLE_CONFLICTS = new Set(['CONFLICT (contents)', 'CONFLICT (add/add)', 'CONFLICT (modify/delete)', 'CONFLICT (binary)']);
+
+const versions = new Map<string, [number, number]>();
+function cachedGitVersion(root: string): [number, number] {
+ let v = versions.get(root);
+ if (!v) { v = gitVersion(root); versions.set(root, v); }
+ return v;
+}
+
+/** `--no-write-fetch-head` exists from git 2.29; older git just writes FETCH_HEAD. */
+function fetchFlags(root: string): string[] {
+ const [maj, min] = cachedGitVersion(root);
+ 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 {
+ 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 (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;
+ if (r.code === 0) return { tree, conflicts: [], structural: [] };
+ let i = 1;
+ const conflicts = new Set<string>();
+ while (i < f.length && f[i] !== '') conflicts.add(f[i++]);
+ i++;
+ const structural = new Set<string>();
+ while (i < f.length && f[i] !== '') {
+ const n = Number(f[i++]);
+ if (!Number.isInteger(n) || n < 1) break;
+ const paths = f.slice(i, i + n);
+ const type = f[i + n] ?? '';
+ i += n + 2;
+ if (type.startsWith('CONFLICT') && !RESOLVABLE_CONFLICTS.has(type)) for (const p of paths) structural.add(p);
+ }
+ 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 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 });
+ 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: [] };
+ const conflicts = [...new Set(unmerged.map(l => l.slice(l.indexOf('\t') + 1)))];
+ const structural: string[] = [];
+ for (const path of conflicts) {
+ gitOk(root, ['update-index', '--force-remove', '--', path], 'update-index', { env });
+ const mine = unmerged.find(l => l.slice(l.indexOf('\t') + 1) === path && l.split('\t')[0].split(' ')[2] === '2');
+ if (!mine) continue;
+ const [mode, sha] = mine.split('\t')[0].split(' ');
+ if (git(root, ['update-index', '--add', '--cacheinfo', `${mode},${sha},${path}`], { env }).code !== 0) structural.push(path);
+ }
+ return { tree: gitOk(root, ['write-tree'], 'write-tree', { env }), conflicts, structural };
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+interface TreeEntry { mode: string; type: string; sha: string }
+
+function treeEntry(root: string, commit: string, path: string): TreeEntry | null {
+ for (const line of git(root, ['--literal-pathspecs', 'ls-tree', '-z', commit, '--', path]).stdout.split('\0')) {
+ const tab = line.indexOf('\t');
+ if (tab === -1 || line.slice(tab + 1) !== path) continue;
+ const [mode, type, sha] = line.slice(0, tab).split(' ');
+ return { mode, type, sha };
+ }
+ return null;
+}
+
+/** One path's content conflict: a blob (or absent) on every side, no side has it as a directory or under a file. */
+function blobConflict(root: string, base: string, ours: string, theirs: string, path: string): boolean {
+ const sides = [base, ours, theirs].map(c => (c ? treeEntry(root, c, path) : null));
+ if (sides.every(e => !e) || sides.some(e => e && e.type !== 'blob')) return false;
+ const parts = path.split('/');
+ for (let k = 1; k < parts.length; k++) {
+ const prefix = parts.slice(0, k).join('/');
+ if ([ours, theirs].some(c => treeEntry(root, c, prefix)?.type === 'blob')) return false;
+ }
+ return true;
+}
+
+/** Apply `--resolve` choices on top of the merge's placeholder tree; structural conflicts are refused. */
+function resolvedTree(ctx: Ctx, ours: string, theirs: string, merged: MergeTree, resolutions: Map<string, Resolution>, cwd: string): string {
+ if (merged.conflicts.some(p => !resolutions.has(p))) throw conflictError(ctx, ours, theirs, merged);
+ const base = git(ctx.root, ['merge-base', ours, theirs]).stdout.trim();
+ const structural = merged.conflicts.filter(p => merged.structural.includes(p) || !blobConflict(ctx.root, base, ours, theirs, p));
+ if (structural.length) throw conflictError(ctx, ours, theirs, { ...merged, structural });
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-resolve-'));
+ try {
+ const env = { GIT_INDEX_FILE: join(dir, 'index') };
+ gitOk(ctx.root, ['read-tree', merged.tree!], 'read-tree', { env });
+ for (const path of merged.conflicts) {
+ const choice = resolutions.get(path)!;
+ if (choice.kind === 'file') {
+ const blob = gitOk(ctx.root, ['hash-object', '-w', '--', resolve(cwd, choice.path)], 'hash-object');
+ gitOk(ctx.root, ['update-index', '--add', '--cacheinfo', `${treeEntry(ctx.root, ours, path)?.mode ?? '100644'},${blob},${path}`], 'update-index', { env });
+ continue;
+ }
+ const entry = treeEntry(ctx.root, choice.kind === 'ours' ? ours : theirs, path);
+ if (entry) gitOk(ctx.root, ['update-index', '--add', '--cacheinfo', `${entry.mode},${entry.sha},${path}`], 'update-index', { env });
+ else gitOk(ctx.root, ['update-index', '--force-remove', '--', path], 'update-index', { env });
+ }
+ return gitOk(ctx.root, ['write-tree'], 'write-tree', { env });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+function shellWord(v: string): string {
+ return /^[A-Za-z0-9._\/@%+:-]+$/.test(v) ? v : `'${v.replace(/'/g, `'\\''`)}'`;
+}
+
+function conflictError(ctx: Ctx, ours: string, theirs: string, merged: MergeTree, preface = ''): OperationError {
+ const paths = merged.conflicts;
+ const local = ours.slice(0, 12);
+ const remote = theirs.slice(0, 12);
+ const compare = `Compare the two versions (this machine's: git show ${local}:<path>; the remote's: git show ${remote}:<path>)`;
+ const fix = merged.structural.length
+ ? `${preface}The local commit ${local} stays local and the checkout is unchanged. ${merged.structural.map(shellWord).join(', ')} ${merged.structural.length === 1 ? 'is' : 'are'} a file/directory or rename conflict that a per-file choice cannot resolve. ${compare}, then move or remove the local path in a new commit (gbrain git commit-push -m "<msg>" -- <paths>) and rerun gbrain git commit-push --push-only. See docs/guides/shared-checkout-git.md#conflicts.`
+ : `${preface}The local commit ${local} stays local and the checkout is unchanged. ${compare}, then run gbrain git commit-push --push-only --expect-remote ${remote} ${paths.map(p => `--resolve ${shellWord(p)}=ours|theirs`).join(' ')} (ours = this machine's version, theirs = the remote's, or =file:<path> with a merged copy). Until then every push from this checkout reports this conflict. See docs/guides/shared-checkout-git.md#conflicts.`;
+ return opError('integrate_conflict', `Local and remote commits both changed ${paths.length} file(s) on ${ctx.branch}; nothing was merged.`, fix,
+ { detail: JSON.stringify({ local: ours, remote: theirs, paths, structural: merged.structural }),
+ fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Choosing which version of a file wins discards the other side; ask the user before resolving.',
+ user_message: `Both this machine and the remote changed ${paths.join(', ')}. Which version should win, or should they be merged by hand?`,
+ ...(merged.structural.length ? {} : { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--path', ctx.root, '--expect-remote', theirs, ...paths.flatMap(p => ['--resolve', `${p}=<ours|theirs>`])] }),
+ docs: 'docs/guides/shared-checkout-git.md#conflicts' } });
+}
+
+/** 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 fetchTracking(ctx: Ctx): string | null {
+ const r = remoteGit(ctx.root, 'fetch', [...fetchFlags(ctx.root), '--', ctx.remote, `+${ctx.mergeRef}:${ctx.trackingRef}`]);
+ if (r.code !== 0) return null;
+ return git(ctx.root, ['rev-parse', '--verify', '--quiet', ctx.trackingRef]).stdout.trim() || null;
+}
+
+function isAncestor(root: string, a: string, b: string): boolean {
+ return git(root, ['merge-base', '--is-ancestor', a, b]).code === 0;
+}
+
+/**
+ * #5138: true only when EVERY effective push destination (pushurl and
+ * pushInsteadOf expanded) has `sha` on the exact target branch. A URL that git
+ * would resolve as another remote alias fails closed, and remote evidence is
+ * read live (ls-remote), never from a stale tracking ref or the fetch repo.
+ */
+function remoteContains(ctx: Ctx, sha: string): boolean {
+ const branchRef = ctx.mergeRef;
+ if (git(ctx.root, ['check-ref-format', branchRef]).code !== 0) return false;
+ const urls = git(ctx.root, ['remote', 'get-url', '--push', '--all', '--', ctx.remote]).stdout.split('\n').map(u => u.trim()).filter(Boolean);
+ if (urls.length === 0) return false;
+ for (const url of urls) {
+ if (git(ctx.root, ['ls-remote', '--get-url', '--', url]).stdout.trim() !== url) return false;
+ const listed = git(ctx.root, [...transportFlags(), 'ls-remote', '--exit-code', '--', url, branchRef], { auth: true, timeoutMs: 60_000 });
+ if (listed.code !== 0) return false;
+ const tip = listed.stdout.split(/\s/)[0];
+ if (!/^[0-9a-f]{40,64}$/.test(tip)) return false;
+ if (git(ctx.root, ['cat-file', '-e', `${tip}^{commit}`]).code !== 0) {
+ const got = git(ctx.root, [...transportFlags(), 'fetch', '--quiet', ...fetchFlags(ctx.root), ...GIT_SSRF_SUBCOMMAND_FLAGS, '--', url, tip], { auth: true, timeoutMs: 120_000 });
+ if (got.code !== 0) return false;
+ }
+ if (!isAncestor(ctx.root, sha, tip)) return false;
+ }
+ return true;
+}
+
+interface Published { sha: string; integrated: number; confirmed: 'push' | 'remote' }
+
+/**
+ * Push `start` (an immutable sha), merging remote commits in memory as needed.
+ * When the remote already holds the candidate, the published tip (which may be
+ * a merge built over it earlier) is returned so a lagging checkout catches up.
+ */
+function publish(ctx: Ctx, start: string, resolutions: Map<string, Resolution> | undefined, expectRemote: string | undefined, cwd: string): Published {
+ let candidate = start;
+ let integrated = 0;
+ let lastError = '';
+ let stalled = 0;
+ const onRemote = (): Published => {
+ const tip = fetchTracking(ctx);
+ return { sha: tip && isAncestor(ctx.root, candidate, tip) ? tip : candidate, integrated, confirmed: 'remote' };
+ };
+ 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.remote, `${candidate}:${ctx.mergeRef}`]);
+ if (push.code === 0) return { sha: candidate, integrated, confirmed: 'push' };
+ lastError = push.stderr.trim();
+ if (remoteContains(ctx, candidate)) return onRemote();
+ const remoteTip = fetchTracking(ctx);
+ if (!remoteTip) break;
+ if (isAncestor(ctx.root, remoteTip, candidate)) {
+ if (++stalled > 1) break;
+ continue;
+ }
+ const merged = mergeTrees(ctx.root, candidate, remoteTip);
+ let tree = merged.tree!;
+ 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,
+ `The remote moved to ${remoteTip.slice(0, 12)}${expectRemote ? ` after the choice was made against ${expectRemote.slice(0, 12)}` : ''}; review the remote's current version before choosing. `);
+ }
+ 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);
+ }
+ 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.`,
+ `git push failed (network, credentials, branch protection, or a remote that kept moving): ${lastError.slice(0, 500) || 'no detail'}. Rerun gbrain git commit-push --push-only once the remote is reachable; never git pull --rebase in this checkout.`,
+ { detail: candidate, retryable: true });
+}
+
+/** 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();
+ if (head === target || isAncestor(root, target, head)) return { checkout: 'unchanged' };
+ if (head !== expectedHead) {
+ return { checkout: 'lagging', reason: isAncestor(root, expectedHead, head)
+ ? `a newer local commit (${head.slice(0, 12)}) landed during the push; publishing it advances the checkout`
+ : `HEAD moved to ${head.slice(0, 12)} during the push (a writer that did not take the commit lock)` };
+ }
+ if (!isAncestor(root, head, target)) return { checkout: 'lagging', reason: `HEAD ${head.slice(0, 12)} is not part of the published history (it was rewritten locally)` };
+ const r = withIndexRetry(root, ['-c', 'core.hooksPath=/dev/null', '-c', 'merge.autoStash=false', 'merge', '--ff-only', '--quiet', target], 'checkout advance');
+ if (r.code === 0) return { checkout: 'advanced' };
+ const dirty = [...r.stderr.matchAll(/^\t(.+)$/gm)].map(m => m[1]);
+ if (dirty.length) return { checkout: 'lagging', reason: `local edits in ${dirty.join(', ')} block the fast-forward` };
+ throw opError('git_unavailable', `git could not fast-forward ${root} to ${target.slice(0, 12)}.`,
+ `${r.stderr.trim().slice(0, 300) || `exit ${r.code}`}. Nothing in the working tree changed; run gbrain git commit-push --pull once git works in this checkout.`, { detail: target });
+}
+
+function advanceWithLock(root: string, target: string, expectedHead: string, onlyWhenClean: boolean, lockWaitMs?: number): { checkout: CheckoutState; reason?: string } {
+ let lock: CommitLock;
+ try { lock = acquireCommitLock(root, lockWaitMs); } catch (e) {
+ if ((e as { code?: string }).code !== 'commit_lock_busy') throw e;
+ return { checkout: 'lagging', reason: 'another writer held the commit lock; the next publish or --pull advances the checkout' };
+ }
+ try {
+ if (onlyWhenClean && git(root, ['status', '--porcelain']).stdout.trim()) {
+ return { checkout: 'lagging', reason: 'the checkout has local edits and this unattended run never moves files under them' };
+ }
+ return advanceLocked(root, target, expectedHead);
+ } finally {
+ lock.release();
+ }
+}
+
+// ── Conflict state (doctor / put_page read it) ──────────────────────────────
+
+export interface IntegrateConflictState { branch: string; at: string; local: string; remote: string; paths: string[] }
+
+/** The unresolved integrate_conflict recorded for this checkout, if any. */
+export function readIntegrateConflict(repo: string): IntegrateConflictState | null {
+ try {
+ const root = checkoutRoot(repo);
+ const p = absGitPath(root, CONFLICT_STATE_NAME);
+ return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) as IntegrateConflictState : null;
+ } catch {
+ return null;
+ }
+}
+
+function recordConflict(root: string, branch: string, e: unknown): void {
+ try {
+ const d = JSON.parse(String((e as { detail?: string }).detail ?? '{}'));
+ writeFileSync(absGitPath(root, CONFLICT_STATE_NAME), JSON.stringify({ branch, at: new Date().toISOString(), local: d.local, remote: d.remote, paths: d.paths ?? [] }));
+ } catch { /* best-effort */ }
+}
+
+// ── Public entry points ─────────────────────────────────────────────────────
+
+function defaultPublishWaitMs(): number {
+ const raw = process.env.GBRAIN_PUBLISH_LOCK_WAIT_SECONDS ?? process.env.GBRAIN_PUSH_LOCK_WAIT_SECONDS;
+ const secs = raw === undefined ? 300 : Number(raw);
+ return Number.isFinite(secs) && secs >= 0 ? secs * 1000 : 300_000;
+}
+
+export function commitAndPush(opts: CommitPushOptions): CommitPushResult {
+ const root = checkoutRoot(opts.repo);
+ assertManagedFilesystemWrite(root);
+ const cwd = opts.cwd ?? process.cwd();
+ const rel = opts.pushOnly ? [] : scopePaths(root, opts.paths ?? [], cwd);
+ if (!opts.pushOnly && !opts.message?.trim()) {
+ throw opError('commit_paths_invalid', 'A commit message is required.', 'Pass -m "<message>".');
+ }
+ const upstream = resolveCtx(root);
+ const ctx = withBranch(upstream, opts.branch);
+ const elsewhere = ctx.mergeRef !== upstream.mergeRef;
+ assertNoOperationInProgress(root);
+
+ let committed: string | null = null;
+ if (!opts.pushOnly) {
+ const lock = acquireCommitLock(root, opts.lockWaitMs);
+ try {
+ assertNoOperationInProgress(root);
+ committed = commitPaths(root, rel, opts.message!.trim(), lock.lockPath);
+ } finally {
+ lock.release();
+ }
+ }
+
+ const unattended = !!opts.advanceOnlyWhenClean;
+ const publishLockPath = absGitPath(root, PUBLISH_LOCK_NAME);
+ const requestPath = absGitPath(root, PUBLISH_REQUEST_NAME);
+ const waitMs = unattended ? 0 : opts.publishWaitMs ?? defaultPublishWaitMs();
+ let pub = acquireNativeLockSync(publishLockPath, { timeoutMs: waitMs });
+ if (!pub) {
+ writeFileSync(requestPath, `${process.pid}\n`);
+ pub = acquireNativeLockSync(publishLockPath, { timeoutMs: 0 });
+ }
+ if (!pub) {
+ if (unattended) {
+ return { outcome: 'push_deferred', sha: null, committed, branch: ctx.branch, remote: ctx.remote, paths: rel, integrated: 0, checkout: 'unchanged' };
+ }
+ throw opError('push_unconfirmed', `${committed ? 'The commit is durable locally, but another' : 'Another'} publish held this checkout's push lock for ${Math.round(waitMs / 1000)}s.`,
+ `The running publish was asked to push HEAD too once it finishes. Rerun gbrain git commit-push --push-only to confirm; never git pull --rebase in this checkout.`,
+ { detail: committed ?? '', retryable: true });
+ }
+
+ const cycle = (onlyWhenClean: boolean, start: string | null, resolutions?: Map<string, Resolution>) => {
+ const requested = existsSync(requestPath);
+ 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);
+ if (!elsewhere) rmSync(absGitPath(root, CONFLICT_STATE_NAME), { force: true });
+ const moved = published.sha === head || elsewhere ? { checkout: 'unchanged' as const } : advanceWithLock(root, published.sha, head, onlyWhenClean, opts.lockWaitMs);
+ return { published, moved };
+ } catch (e) {
+ if ((e as { code?: string }).code === 'integrate_conflict' && !elsewhere) recordConflict(root, ctx.branch, e);
+ if (requested) writeFileSync(requestPath, `${process.pid}\n`);
+ throw e;
+ }
+ };
+
+ let first: ReturnType<typeof cycle>;
+ try {
+ first = cycle(unattended, committed, opts.resolutions);
+ } finally {
+ pub.release();
+ }
+ // Publishers that found the push lock busy left a request; honor it after releasing (no commit is stranded).
+ for (let i = 0; i < 16 && existsSync(requestPath); i++) {
+ const again = acquireNativeLockSync(publishLockPath, { timeoutMs: 0 });
+ if (!again) break;
+ try { cycle(true, null); } catch { break; } finally { again.release(); }
+ }
+
+ const { published, moved } = first;
+ return {
+ 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 } : {}),
+ };
+}
+
+/**
+ * Bring remote commits into the shared checkout without rebasing it: fetch
+ * outside the lock, then (under the commit lock) fast-forward, or merge
+ * diverged history in memory and fast-forward to the merge. Never pushes.
+ * `requireClean` keeps the unattended cron's conservative "any local edit →
+ * skip" rule.
+ */
+export function pullShared(repo: string, opts: { requireClean?: boolean; lockWaitMs?: number; fetchTimeoutMs?: number; remoteBranch?: string } = {}): PullResult {
+ const root = checkoutRoot(repo);
+ assertManagedFilesystemWrite(root);
+ const ctx = withBranch(resolveCtx(root), opts.remoteBranch);
+ if (opts.requireClean && git(root, ['status', '--porcelain']).stdout.trim()) return { status: 'skipped_dirty' };
+ assertNoOperationInProgress(root);
+ const fetched = remoteGit(root, 'fetch', [...fetchFlags(root), '--', ctx.remote, `+${ctx.mergeRef}:${ctx.trackingRef}`], opts.fetchTimeoutMs ?? 300_000);
+ if (fetched.code !== 0) {
+ throw opError('git_unavailable', `git fetch from ${ctx.remote} failed in ${root}.`, fetched.stderr.trim().slice(0, 300) || 'Check the remote and its credentials.');
+ }
+ const remoteTip = gitOk(root, ['rev-parse', ctx.trackingRef], 'rev-parse tracking ref');
+ const lock = acquireCommitLock(root, opts.lockWaitMs);
+ try {
+ assertNoOperationInProgress(root);
+ if (opts.requireClean && git(root, ['status', '--porcelain']).stdout.trim()) return { status: 'skipped_dirty' };
+ const head = gitOk(root, ['rev-parse', 'HEAD'], 'rev-parse HEAD');
+ if (head === remoteTip || isAncestor(root, remoteTip, head)) return { status: head === remoteTip ? 'up_to_date' : 'ahead' };
+ let target = remoteTip;
+ let merged = false;
+ if (!isAncestor(root, head, remoteTip)) {
+ const tree = mergeTrees(root, head, remoteTip);
+ if (tree.conflicts.length) throw conflictError(ctx, head, remoteTip, tree);
+ target = buildMerge(ctx, head, remoteTip, tree.tree!);
+ merged = true;
+ }
+ const moved = advanceLocked(root, target, head);
+ if (moved.checkout === 'lagging') return { status: 'lagging', from: head, reason: moved.reason };
+ return { status: 'advanced', from: head, to: target, merged };
+ } finally {
+ lock.release();
+ }
+}
diff --git a/src/core/persistence/native-lock.ts b/src/core/persistence/native-lock.ts
index b53968b21b..90831323c4 100644
--- a/src/core/persistence/native-lock.ts
+++ b/src/core/persistence/native-lock.ts
@@ -1,9 +1,10 @@
/** Stable OS locks for cooperating writers on one owner host. No TTL takeover. */
import { mkdir } from 'node:fs/promises';
+import { mkdirSync } from 'node:fs';
import { dirname, isAbsolute } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { constants as osConstants } from 'node:os';
-import { family, GLIBC, MUSL } from 'detect-libc';
+import { familySync, GLIBC, MUSL } from 'detect-libc';
export interface NativeExportPublisher {
beginExport(absoluteDestination: string): object;
@@ -66,6 +67,12 @@ export interface NativeLockHandle {
release(): Promise<void>;
}
+/** #6530: a lock taken by {@link acquireNativeLockSync}; release is synchronous and idempotent. */
+export interface NativeLockSyncHandle {
+ readonly released: boolean;
+ release(): void;
+}
+
export interface NativeLockOptions {
/** A zero budget tries once. Defaults to five seconds. */
timeoutMs?: number;
@@ -75,16 +82,22 @@ export interface NativeLockOptions {
}
let bindingPromise: Promise<NativeBinding> | undefined;
+let bindingLoaded: NativeBinding | undefined;
const windowsSocketRemovers = new WeakMap<NativeLockHandle, (path: string) => boolean>();
async function loadBinding(): Promise<NativeBinding> {
+ return loadBindingSync();
+}
+
+function loadBindingSync(): NativeBinding {
+ if (bindingLoaded) return bindingLoaded;
const arch = process.arch;
if (arch !== 'x64' && arch !== 'arm64') throw new NativeLockUnavailableError(`Native writer locking does not support ${process.platform}/${arch}`);
let binding: NativeBinding;
let target: string;
try {
if (process.platform === 'linux') {
- const libc = await family();
+ const libc = familySync();
if (libc !== GLIBC && libc !== MUSL) throw new NativeLockUnavailableError('Cannot identify the Linux C runtime for writer locking');
target = `linux-${arch}-${libc}`;
// Literal requires are intentional: Bun embeds each .node asset in its
@@ -112,6 +125,7 @@ async function loadBinding(): Promise<NativeBinding> {
if (process.platform === 'win32' && (typeof binding.openIpcMutex !== 'function' || typeof binding.removeWindowsUnixSocket !== 'function')) {
throw new NativeLockUnavailableError('Installed native writer lock addon lacks Windows IPC support');
}
+ bindingLoaded = binding;
return binding;
} catch (cause) {
if (cause instanceof NativeLockUnavailableError) throw cause;
@@ -189,6 +203,48 @@ export async function acquireNativeLock(path: string, options: NativeLockOptions
}
}
+/**
+ * #6530: the same OS lock for synchronous callers (git write paths that run
+ * inside sync code). Blocks the thread between attempts, so callers pass a
+ * short budget.
+ */
+export function acquireNativeLockSync(path: string, options: { timeoutMs?: number; pollMs?: number } = {}): NativeLockSyncHandle | null {
+ if (!isAbsolute(path) || path.includes('\0')) throw new TypeError('Native lock path must be absolute and contain no NUL');
+ const timeoutMs = budget(options.timeoutMs, 5000, 0);
+ const pollMs = budget(options.pollMs, 25, 1);
+ const binding = loadBindingSync();
+ let handle: object;
+ try {
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ handle = binding.openLock(path);
+ } catch (cause) {
+ throw new NativeLockUnavailableError('Cannot open the stable writer lock file', cause, 'open');
+ }
+ let released = false;
+ const releaseSync = () => {
+ if (released) return;
+ released = true;
+ try { binding.close(handle); }
+ catch (cause) { throw new NativeLockUnavailableError('Cannot close the writer lock handle; this host must stop publishing', cause); }
+ };
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
+ const deadline = performance.now() + timeoutMs;
+ try {
+ for (;;) {
+ let acquired: boolean;
+ try { acquired = binding.tryLock(handle); }
+ catch (cause) { throw new NativeLockUnavailableError('The OS could not acquire the writer lock', cause); }
+ if (acquired) return { get released() { return released; }, release: releaseSync };
+ const remaining = deadline - performance.now();
+ if (remaining <= 0) { releaseSync(); return null; }
+ Atomics.wait(sleeper, 0, 0, Math.min(pollMs, remaining));
+ }
+ } catch (error) {
+ releaseSync();
+ throw error;
+ }
+}
+
export function tryAcquireNativeLock(path: string): Promise<NativeLockHandle | null> {
return acquireNativeLock(path, { timeoutMs: 0 });
}
diff --git a/src/core/timeline-write-through.ts b/src/core/timeline-write-through.ts
index 6796eee6d3..106f4e0901 100644
--- a/src/core/timeline-write-through.ts
+++ b/src/core/timeline-write-through.ts
@@ -420,7 +420,7 @@ export async function writeTimelineEntryThrough(
committed = commitWriteThroughFile(writeRoot, filePath, slug);
if (committed) {
pushed = 'pending';
- lastPushStatus = getLastPushOutcome(currentBranch(writeRoot));
+ lastPushStatus = getLastPushOutcome(currentBranch(writeRoot), writeRoot);
}
}
} catch { /* best-effort */ }
diff --git a/src/core/write-through.ts b/src/core/write-through.ts
index d7146e13c1..ca60246a99 100644
--- a/src/core/write-through.ts
+++ b/src/core/write-through.ts
@@ -495,7 +495,7 @@ export async function writePageThrough(
committed = commitWriteThroughFile(writeRoot, filePath, slug);
if (committed) {
pushed = 'pending';
- lastPushStatus = getLastPushOutcome(currentBranch(writeRoot));
+ lastPushStatus = getLastPushOutcome(currentBranch(writeRoot), writeRoot);
}
}
} catch { /* best-effort */ }
diff --git a/test/brain-durability-hook.serial.test.ts b/test/brain-durability-hook.serial.test.ts
index d2a22d36b5..ed94dc4bba 100644
--- a/test/brain-durability-hook.serial.test.ts
+++ b/test/brain-durability-hook.serial.test.ts
@@ -61,11 +61,22 @@ async function waitForOrigin(bare: string, expectSha: string, ms = 30_000): Prom
// regression test below pins that.
let root: string, work: string, bare: string;
-let oldHome: string | undefined, oldGbrainHome: string | undefined;
+let oldHome: string | undefined, oldGbrainHome: string | undefined, oldPath: string | undefined;
+
+// #6530: the helper and hook delegate to `gbrain git commit-push`. Tests put a
+// `gbrain` on PATH that runs this checkout's CLI under the current bun, so
+// harden captures it (resolveGbrainCliPath) exactly as it captures a real install.
+function installGbrainShim(dir: string): void {
+ const bin = join(dir, 'gbrain-bin');
+ mkdirSync(bin, { recursive: true });
+ writeFileSync(join(bin, 'gbrain'), `#!/usr/bin/env bash\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(join(import.meta.dir, '..', 'src', 'cli.ts'))} "$@"\n`, { mode: 0o755 });
+ process.env.PATH = `${bin}:${process.env.PATH ?? ''}`;
+}
beforeEach(async () => {
root = mkdtempSync(join(tmpdir(), 'bdh-'));
- oldHome = process.env.HOME; oldGbrainHome = process.env.GBRAIN_HOME;
+ oldHome = process.env.HOME; oldGbrainHome = process.env.GBRAIN_HOME; oldPath = process.env.PATH;
+ installGbrainShim(root);
process.env.HOME = mkdtempSync(join(root, 'home-'));
// CX2-8: GBRAIN_HOME is a PARENT dir (config.ts semantics — `.gbrain` is
// appended by both the TS resolver and the bash template), so the
@@ -85,6 +96,7 @@ beforeEach(async () => {
afterEach(() => {
if (oldHome === undefined) delete process.env.HOME; else process.env.HOME = oldHome;
if (oldGbrainHome === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = oldGbrainHome;
+ process.env.PATH = oldPath;
delete process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT;
rmSync(root, { recursive: true, force: true });
});
@@ -171,9 +183,16 @@ describe('durability push remote confirmation (#5138)', () => {
function interceptGit(script: string): NodeJS.ProcessEnv {
const bin = join(root, 'intercept-bin');
mkdirSync(bin);
+ // #6530: the CLI runs `git -C <root> -c k=v <sub> ...`, so match on the
+ // subcommand after the global options instead of on "$1".
writeFileSync(join(bin, 'git'), `#!/usr/bin/env bash
set -eu
-${script}
+GIT_SUB=""; _i=1
+while [ "$_i" -le "$#" ]; do
+ _a="\${!_i}"
+ case "$_a" in -C|-c) _i=$((_i + 2)) ;; -*) _i=$((_i + 1)) ;; *) GIT_SUB="$_a"; break ;; esac
+done
+${script.replaceAll('"$1"', '"$GIT_SUB"')}
exec "$GBRAIN_TEST_REAL_GIT" "$@"
`, { mode: 0o755 });
return {
@@ -303,7 +322,13 @@ fi`);
const captured = readFileSync(env.GBRAIN_TEST_PUSH_MARKER!, 'utf8').trim();
expect(result.status).toBe(0);
- expect(originHead(bare)).toBe(captured);
+ if (attempt === 'initial') expect(originHead(bare)).toBe(captured);
+ else {
+ // #6530: the retry publishes an in-memory merge built on the captured
+ // commit (never on the moved HEAD), so the captured commit is its parent.
+ expect(originHead(bare)).not.toBe(captured);
+ expect(git(bare, 'rev-parse', 'main^1')).toBe(captured);
+ }
expect(git(work, 'rev-parse', 'HEAD')).not.toBe(captured);
expect(git(bare, 'show', 'main:pending.md')).toBe('pending');
});
@@ -363,7 +388,8 @@ fi`);
expect(result.status).toBe(0);
expect(originHead(bare)).toBe(remoteHead);
- expect(git(work, 'rev-parse', 'HEAD')).toBe(intendedHead);
+ // #6530: the checkout catches up to the published tip (fast-forward only; the dirty file is untouched).
+ expect(git(work, 'rev-parse', 'HEAD')).toBe(remoteHead);
expect(readFileSync(join(work, 'README.md'), 'utf8')).toBe('unrelated dirty edit\n');
const log = readFileSync(join(process.env.HOME!, '.gbrain', 'brain-push.log'), 'utf8');
expect(log).toContain('ok-already-on-remote main');
@@ -372,7 +398,7 @@ fi`);
expect(getLastPushOutcome('main').status).toBe('ok');
});
- test('confirms the rebased commit when the retry push lands but reports failure', () => {
+ test('confirms the merged commit when the retry push lands but reports failure', () => {
const remoteHead = advanceRemote();
const env = interceptGit(`if [ "$1" = push ]; then
if [ ! -e "$GBRAIN_TEST_PUSH_MARKER" ]; then
@@ -396,8 +422,10 @@ fi`);
test('checks again after recovery fails while another pusher lands the commit', () => {
writeFileSync(join(work, 'README.md'), 'unrelated dirty edit\n');
+ // #6530: no pull runs any more; the integrate step's fetch is where the
+ // recovery fails while another pusher lands the commit.
const env = interceptGit(`if [ "$1" = push ]; then exit 1; fi
-if [ "$1" = pull ]; then
+if [ "$1" = fetch ]; then
"$GBRAIN_TEST_REAL_GIT" push origin HEAD:refs/heads/main
exit 1
fi`);
@@ -452,7 +480,7 @@ fi`);
expect(getLastPushOutcome('main').status).toBe('needs_attention');
});
- test('does not confirm the temporary remote HEAD of a conflicted rebase', () => {
+ test('does not confirm the remote HEAD of a conflicting integrate', () => {
writeFileSync(join(work, 'README.md'), 'local edit\n');
git(work, 'add', 'README.md');
git(work, 'commit', '--amend', '--no-edit', '-q');
@@ -466,7 +494,10 @@ fi`);
expect(git(work, 'rev-parse', 'HEAD')).toBe(localHead);
expect(readFileSync(join(work, 'README.md'), 'utf8')).toBe('local edit\n');
expect(existsSync(join(work, '.git', 'rebase-merge'))).toBe(false);
- expect(readFileSync(join(process.env.HOME!, '.gbrain', 'brain-push.log'), 'utf8')).toContain('LOCAL-ONLY, NEEDS ATTENTION');
+ expect(existsSync(join(work, '.git', 'MERGE_HEAD'))).toBe(false);
+ // #6530: a same-file conflict is its own outcome (integrate_conflict), not a lost push.
+ expect(readFileSync(join(process.env.HOME!, '.gbrain', 'brain-push.log'), 'utf8')).toContain('CONFLICT, NEEDS ATTENTION');
+ expect(getLastPushOutcome('main').status).toBe('needs_attention');
});
});
@@ -616,7 +647,8 @@ describe('#4682 — push-lock timeout is fail-loud for the helper only', () => {
const head = git(work, 'rev-parse', 'HEAD');
expect(originHead(bare)).not.toBe(head);
- const lockPath = join(git(work, 'rev-parse', '--absolute-git-dir'), 'gbrain-push.lock');
+ // #6530: pushes serialize on the publish lock (the commit lock is never held across the network).
+ const lockPath = join(git(work, 'rev-parse', '--absolute-git-dir'), 'brain-publish.lock');
const holder = spawn('flock', [lockPath, 'sleep', '30'], { stdio: 'ignore', env: process.env });
try {
expect(await waitForLockHeld(lockPath)).toBe(true);
@@ -628,29 +660,30 @@ describe('#4682 — push-lock timeout is fail-loud for the helper only', () => {
});
} catch (e: any) { code = e.status ?? 1; }
expect(code).not.toBe(0); // pre-fix: exit 0 with no push and no remote-head check
- // The timeout was logged, and the commit is still NOT on origin.
+ // The unconfirmed push was logged, and the commit is still NOT on origin.
const log = join(process.env.HOME!, '.gbrain', 'brain-push.log');
- expect(readFileSync(log, 'utf-8')).toContain('lock-timeout main');
+ expect(readFileSync(log, 'utf-8')).toContain('LOCAL-ONLY, NEEDS ATTENTION: main');
expect(originHead(bare)).not.toBe(head);
} finally {
holder.kill('SIGKILL');
}
}, 60_000);
- test('template parity: helper renders lock-timeout rc 1, hook keeps rc 0, bodies otherwise identical', () => {
+ test('#6530: helper and hook keep their ownership banners, declare protocol 2, and never rebase, stash or reset the shared tree', () => {
const helper = readFileSync(join(work, 'scripts', 'brain-commit-push.sh'), 'utf-8');
const hook = readFileSync(join(work, '.git', 'hooks', 'post-commit'), 'utf-8');
- // The helper (synchronous guarantee) fails loudly on lock timeout...
- expect(helper).toMatch(/lock-timeout \$_branch" >>"\$_log"; return 1; \}/);
- // ...while the hook (detached best-effort) keeps the coalescing skip.
- expect(hook).toMatch(/lock-timeout \$_branch" >>"\$_log"; return 0; \}/);
- // D7 stays intact: apart from that one return code, the rendered
- // brain_push bodies are byte-identical (one template, one knob).
- const body = (s: string): string => {
- const m = s.match(/brain_push\(\) \{[\s\S]*?\n\}/);
- return (m ? m[0] : '').replace(/return [01]; \}/, 'return RC; }');
- };
- expect(body(helper).length).toBeGreaterThan(0);
- expect(body(helper)).toBe(body(hook));
+ expect(helper).toContain('# gbrain brain-commit-push helper (v0.42.44+)');
+ expect(hook).toContain('# gbrain brain-durability post-commit hook (v0.42.44+)');
+ for (const body of [helper, hook]) {
+ expect(body).toContain('# gbrain-protocol: 2');
+ const commands = body.split('\n').filter(line => !line.trimStart().startsWith('#') && !line.includes('echo '));
+ for (const banned of [/git pull/, /git rebase/, /git stash/, /reset --hard/, /push --force/, /--autostash(?!\S)/]) {
+ expect(commands.filter(line => banned.test(line))).toEqual([]);
+ }
+ }
+ // The helper delegates to the CLI; the hook runs the CLI captured at harden, never the committed helper.
+ expect(helper).toContain('git commit-push "$@"');
+ expect(hook).toContain('git commit-push --push-only --require-clean');
+ expect(hook).not.toContain('brain-commit-push.sh"');
});
});
diff --git a/test/divergence-safe-pull-5429.serial.test.ts b/test/divergence-safe-pull-5429.serial.test.ts
index 4127cc92e8..305dd68918 100644
--- a/test/divergence-safe-pull-5429.serial.test.ts
+++ b/test/divergence-safe-pull-5429.serial.test.ts
@@ -89,27 +89,35 @@ beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'gd-5429-')); });
afterEach(() => { rmSync(root, { recursive: true, force: true }); });
describe('--no-autostash (#5429, bug fix)', () => {
- test('the pull git runs carries --no-autostash, in rebase mode and in merge mode', () => {
+ test('#6530: no git pull or rebase runs; the only working-tree move is merge --ff-only with merge.autoStash=false, in rebase mode and in merge mode', () => {
const { bare, work } = makePair();
const other = secondClone(bare);
commitFile(other, 'remote.txt', 'r\n', 'remote');
git(other, 'push', '-q', 'origin', 'main');
- const pulls: string[][] = [];
+ const calls: string[][] = [];
const spy = spyOn(childProcess, 'execFileSync');
try {
divergenceSafePull(work, 'main');
+ commitFile(other, 'remote2.txt', 'r2\n', 'remote 2');
+ git(other, 'push', '-q', 'origin', 'main');
divergenceSafePull(work, 'main', { strategy: 'merge' });
} finally {
for (const call of spy.mock.calls) {
const args = call[1] as string[] | undefined;
- if (call[0] === 'git' && Array.isArray(args) && args.includes('pull')) pulls.push(args);
+ if (call[0] === 'git' && Array.isArray(args)) calls.push(args);
}
spy.mockRestore();
}
- expect(pulls).toHaveLength(2);
- for (const argv of pulls) expect(argv.slice(argv.indexOf('pull'))).toContain('--no-autostash');
- expect(pulls[0]!.slice(pulls[0]!.indexOf('pull'))).toContain('--rebase');
- expect(pulls[1]!.slice(pulls[1]!.indexOf('pull'))).toContain('--no-rebase');
+ expect(calls.some(argv => argv.includes('pull') || argv.includes('rebase') || argv.includes('stash'))).toBe(false);
+ const moves = calls.filter(argv => argv.includes('merge') && !argv.includes('merge-base') && !argv.includes('merge-tree'));
+ expect(moves).toHaveLength(2);
+ for (const argv of moves) {
+ expect(argv.slice(argv.indexOf('merge'))).toContain('--ff-only');
+ const off = argv.indexOf('merge.autoStash=false');
+ expect(argv[off - 1]).toBe('-c');
+ expect(off).toBeLessThan(argv.indexOf('merge'));
+ }
+ expect(existsSync(join(work, 'remote2.txt'))).toBe(true);
});
test('git itself: with rebase.autoStash=true the old argv stashes and replays a dirty edit; --no-autostash refuses and leaves the stash list empty', () => {
@@ -137,6 +145,22 @@ describe('--no-autostash (#5429, bug fix)', () => {
}
});
+ test('git itself: with merge.autoStash=true, the advance argv (-c merge.autoStash=false merge --ff-only) refuses a dirty must-change file and stashes nothing', () => {
+ const { bare, work } = makePair();
+ const other = secondClone(bare);
+ commitFile(other, 'README.md', 'remote edit\n', 'remote');
+ git(other, 'push', '-q', 'origin', 'main');
+ git(work, 'config', 'merge.autoStash', 'true');
+ writeFileSync(join(work, 'README.md'), 'in-flight local edit\n');
+ git(work, 'fetch', '-q', 'origin', 'main');
+ let exit = 0;
+ try { git(work, '-c', 'merge.autoStash=false', 'merge', '--ff-only', '--quiet', 'origin/main'); }
+ catch (error) { exit = (error as { status: number }).status; }
+ expect(exit).not.toBe(0);
+ expect(readFileSync(join(work, 'README.md'), 'utf8')).toBe('in-flight local edit\n');
+ expect(git(work, 'stash', 'list')).toBe('');
+ });
+
test('a dirty tree with rebase.autoStash=true is skipped_dirty in both modes, nothing stashed', () => {
for (const strategy of ['rebase', 'merge'] as const) {
const { work } = makePair();
@@ -150,26 +174,21 @@ describe('--no-autostash (#5429, bug fix)', () => {
});
describe('pull_strategy: merge (#5429, feature)', () => {
- test('tip-equivalent divergence: rebase mode conflict_aborted, merge mode advanced with both histories as ancestors', () => {
- const rebase = tipEquivalentDivergence();
- const before = treeBytes(rebase.work);
- const out = divergenceSafePull(rebase.work, 'main');
- expect(out.status).toBe('conflict_aborted');
- expect(git(rebase.work, 'rev-parse', 'HEAD')).toBe(rebase.localHead);
- expect(existsSync(join(rebase.work, '.git', 'rebase-merge'))).toBe(false);
- expect(treeBytes(rebase.work)).toEqual(before);
-
- const merge = tipEquivalentDivergence();
- const merged = divergenceSafePull(merge.work, 'main', { strategy: 'merge' });
- expect(merged.status).toBe('advanced');
- if (merged.status !== 'advanced') throw new Error('unreachable');
- expect(merged.from).toBe(merge.localHead);
- const head = git(merge.work, 'rev-parse', 'HEAD');
- expect(merged.to).toBe(head);
- expect(git(merge.work, 'merge-base', '--is-ancestor', merge.remoteHead, head)).toBe('');
- expect(git(merge.work, 'merge-base', '--is-ancestor', merge.localHead, head)).toBe('');
- expect(readFileSync(join(merge.work, 'page.md'), 'utf8')).toBe('v2\n');
- expect(existsSync(join(merge.work, '.git', 'MERGE_HEAD'))).toBe(false);
+ test('tip-equivalent divergence: both modes merge the tips in memory (#6530; rebase replay used to conflict) with both histories as ancestors', () => {
+ for (const strategy of ['rebase', 'merge'] as const) {
+ const merge = tipEquivalentDivergence();
+ const merged = divergenceSafePull(merge.work, 'main', { strategy });
+ expect(merged.status).toBe('advanced');
+ if (merged.status !== 'advanced') throw new Error('unreachable');
+ expect(merged.from).toBe(merge.localHead);
+ const head = git(merge.work, 'rev-parse', 'HEAD');
+ expect(merged.to).toBe(head);
+ expect(git(merge.work, 'merge-base', '--is-ancestor', merge.remoteHead, head)).toBe('');
+ expect(git(merge.work, 'merge-base', '--is-ancestor', merge.localHead, head)).toBe('');
+ expect(readFileSync(join(merge.work, 'page.md'), 'utf8')).toBe('v2\n');
+ expect(existsSync(join(merge.work, '.git', 'MERGE_HEAD'))).toBe(false);
+ expect(existsSync(join(merge.work, '.git', 'rebase-merge'))).toBe(false);
+ }
});
test('merge mode fast-forwards when the local branch is behind and reports up_to_date when level', () => {
diff --git a/test/docs-repo-paths.test.ts b/test/docs-repo-paths.test.ts
index fef9341812..c840efa2c0 100644
--- a/test/docs-repo-paths.test.ts
+++ b/test/docs-repo-paths.test.ts
@@ -46,6 +46,24 @@ const ALLOWLIST: Record<string, Record<string, string>> = {
'docs/guides/multi-source-brains.md': {
'scripts/brain-commit-push.sh': 'installed into the brain repo by `gbrain sources harden`',
},
+ 'AGENTS.md': {
+ 'scripts/brain-commit-push.sh': 'installed into the brain repo by `gbrain sources harden`',
+ },
+ 'INSTALL_FOR_AGENTS.md': {
+ 'scripts/brain-commit-push.sh': 'installed into the brain repo by `gbrain sources harden`',
+ },
+ 'docs/GBRAIN_RECOMMENDED_SCHEMA.md': {
+ 'scripts/brain-commit-push.sh': 'installed into the brain repo by `gbrain sources harden`',
+ },
+ 'docs/guides/diligence-ingestion.md': {
+ 'scripts/brain-commit-push.sh': 'installed into the brain repo by `gbrain sources harden`',
+ },
+ 'docs/guides/live-sync.md': {
+ 'scripts/brain-commit-push.sh': 'installed into the brain repo by `gbrain sources harden`',
+ },
+ 'docs/guides/shared-checkout-git.md': {
+ 'scripts/brain-commit-push.sh': 'installed into the brain repo by `gbrain sources harden`',
+ },
'docs/architecture/key-files/files-and-sync-1.md': {
'scripts/brain-commit-push.sh': 'installed into the brain repo by `gbrain sources harden`',
},
diff --git a/test/durability-block-managed-5808.test.ts b/test/durability-block-managed-5808.test.ts
index 77af19d717..d919694fab 100644
--- a/test/durability-block-managed-5808.test.ts
+++ b/test/durability-block-managed-5808.test.ts
@@ -1,7 +1,7 @@
/**
* #5808 [R9]: the AGENTS durability block `gbrain sources harden` renders tells
* agents to run `scripts/brain-commit-push.sh` after every write and to
- * `git fetch && git pull --rebase` before writing. On a managed canonical
+ * `scripts/brain-commit-push.sh --pull` before writing (#6530; formerly `git pull --rebase`). On a managed canonical
* worktree both route agents around the persistence owner, and `sources harden`
* itself refuses there, so a block rendered before activation stayed stale.
*
@@ -28,7 +28,7 @@ import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
const BEGIN = '<!-- BEGIN gbrain-brain-durability (managed; do not edit between markers) -->';
const END = '<!-- END gbrain-brain-durability -->';
-const CLASSIC = ['scripts/brain-commit-push.sh', 'git fetch && git pull --rebase', 'regenerated by `gbrain sources harden`'];
+const CLASSIC = ['scripts/brain-commit-push.sh', 'scripts/brain-commit-push.sh --pull', 'regenerated by `gbrain sources harden`'];
const block = (text: string) => text.slice(text.indexOf(BEGIN), text.indexOf(END) + END.length);
const outside = (text: string) => text.slice(0, text.indexOf(BEGIN)) + text.slice(text.indexOf(END) + END.length);
diff --git a/test/fixtures/guards/check-shared-tree-git.sh/bad-agent-rules/AGENTS.md b/test/fixtures/guards/check-shared-tree-git.sh/bad-agent-rules/AGENTS.md
new file mode 100644
index 0000000000..493813ff64
--- /dev/null
+++ b/test/fixtures/guards/check-shared-tree-git.sh/bad-agent-rules/AGENTS.md
@@ -0,0 +1,5 @@
+# Agents
+
+<!-- BEGIN multi-agent-rules -->
+Commit with `gbrain git commit-push -m "<msg>" -- <paths>`.
+<!-- END multi-agent-rules -->
diff --git a/test/fixtures/guards/check-shared-tree-git.sh/bad-agent-rules/BOOTSTRAP_FOR_AGENTS.md b/test/fixtures/guards/check-shared-tree-git.sh/bad-agent-rules/BOOTSTRAP_FOR_AGENTS.md
new file mode 100644
index 0000000000..3835f935da
--- /dev/null
+++ b/test/fixtures/guards/check-shared-tree-git.sh/bad-agent-rules/BOOTSTRAP_FOR_AGENTS.md
@@ -0,0 +1,5 @@
+# Bootstrap
+
+<!-- BEGIN multi-agent-rules -->
+Commit with plain git.
+<!-- END multi-agent-rules -->
diff --git a/test/fixtures/guards/check-shared-tree-git.sh/bad-marker/recipes/x.md b/test/fixtures/guards/check-shared-tree-git.sh/bad-marker/recipes/x.md
new file mode 100644
index 0000000000..4b507c5c2b
--- /dev/null
+++ b/test/fixtures/guards/check-shared-tree-git.sh/bad-marker/recipes/x.md
@@ -0,0 +1,5 @@
+# Recipe
+
+```bash
+git reset --hard origin/main # gbrain-allow-shared-tree-git:
+```
diff --git a/test/fixtures/guards/check-shared-tree-git.sh/bad-plugin/plugin/skills/demo/SKILL.md b/test/fixtures/guards/check-shared-tree-git.sh/bad-plugin/plugin/skills/demo/SKILL.md
new file mode 100644
index 0000000000..e9a69ccfe6
--- /dev/null
+++ b/test/fixtures/guards/check-shared-tree-git.sh/bad-plugin/plugin/skills/demo/SKILL.md
@@ -0,0 +1,5 @@
+# Demo skill
+
+```bash
+git stash
+```
diff --git a/test/fixtures/guards/check-shared-tree-git.sh/bad-prose/docs/guides/x.md b/test/fixtures/guards/check-shared-tree-git.sh/bad-prose/docs/guides/x.md
new file mode 100644
index 0000000000..e57491d467
--- /dev/null
+++ b/test/fixtures/guards/check-shared-tree-git.sh/bad-prose/docs/guides/x.md
@@ -0,0 +1,3 @@
+# Guide
+
+Run `git add -A && git commit -m "x" && git push` after each write.
diff --git a/test/fixtures/guards/check-shared-tree-git.sh/bad-region/docs/x.md b/test/fixtures/guards/check-shared-tree-git.sh/bad-region/docs/x.md
new file mode 100644
index 0000000000..ee6722c824
--- /dev/null
+++ b/test/fixtures/guards/check-shared-tree-git.sh/bad-region/docs/x.md
@@ -0,0 +1,4 @@
+# Doc
+
+<!-- gbrain-allow-shared-tree-git-begin: never closed -->
+- `git stash`
diff --git a/test/fixtures/guards/check-shared-tree-git.sh/bad/skills/demo/SKILL.md b/test/fixtures/guards/check-shared-tree-git.sh/bad/skills/demo/SKILL.md
new file mode 100644
index 0000000000..3a6806d2f9
--- /dev/null
+++ b/test/fixtures/guards/check-shared-tree-git.sh/bad/skills/demo/SKILL.md
@@ -0,0 +1,5 @@
+# Demo skill
+
+```bash
+git pull --rebase && git push
+```
diff --git a/test/fixtures/guards/check-shared-tree-git.sh/good/AGENTS.md b/test/fixtures/guards/check-shared-tree-git.sh/good/AGENTS.md
new file mode 100644
index 0000000000..493813ff64
--- /dev/null
+++ b/test/fixtures/guards/check-shared-tree-git.sh/good/AGENTS.md
@@ -0,0 +1,5 @@
+# Agents
+
+<!-- BEGIN multi-agent-rules -->
+Commit with `gbrain git commit-push -m "<msg>" -- <paths>`.
+<!-- END multi-agent-rules -->
diff --git a/test/fixtures/guards/check-shared-tree-git.sh/good/INSTALL_FOR_AGENTS.md b/test/fixtures/guards/check-shared-tree-git.sh/good/INSTALL_FOR_AGENTS.md
new file mode 100644
index 0000000000..493813ff64
--- /dev/null
+++ b/test/fixtures/guards/check-shared-tree-git.sh/good/INSTALL_FOR_AGENTS.md
@@ -0,0 +1,5 @@
+# Agents
+
+<!-- BEGIN multi-agent-rules -->
+Commit with `gbrain git commit-push -m "<msg>" -- <paths>`.
+<!-- END multi-agent-rules -->
diff --git a/test/fixtures/guards/check-shared-tree-git.sh/good/docs/guide.md b/test/fixtures/guards/check-shared-tree-git.sh/good/docs/guide.md
new file mode 100644
index 0000000000..0a2e51ddfc
--- /dev/null
+++ b/test/fixtures/guards/check-shared-tree-git.sh/good/docs/guide.md
@@ -0,0 +1,3 @@
+# Guide
+
+Publish with `gbrain git commit-push --push-only`.
diff --git a/test/fixtures/guards/check-shared-tree-git.sh/good/skills/demo/SKILL.md b/test/fixtures/guards/check-shared-tree-git.sh/good/skills/demo/SKILL.md
new file mode 100644
index 0000000000..787d6f68c1
--- /dev/null
+++ b/test/fixtures/guards/check-shared-tree-git.sh/good/skills/demo/SKILL.md
@@ -0,0 +1,21 @@
+# Demo skill
+
+Commit with `scripts/brain-commit-push.sh "<msg>" people/alice-example.md`.
+
+```bash
+gbrain git commit-push -m "people: add alice-example" -- people/alice-example.md
+git add -A -- people/alice-example.md
+git push --dry-run origin HEAD:main
+git stash store -m "rescued" "$(cat .git/rebase-merge/autostash)"
+git push --force origin main # gbrain-allow-shared-tree-git: confirmed purge of a private clone
+```
+
+<!-- gbrain-allow-shared-tree-git: names what never to run -->
+Never run `git pull --rebase` in a shared checkout.
+
+<!-- gbrain-allow-shared-tree-git-begin: the forbidden list -->
+- `git stash`
+- `git reset --hard`
+<!-- gbrain-allow-shared-tree-git-end -->
+
+A git push in plain prose, outside a code span, is not an instruction.
diff --git a/test/git-commit-push-6530.serial.test.ts b/test/git-commit-push-6530.serial.test.ts
new file mode 100644
index 0000000000..0cd66632e9
--- /dev/null
+++ b/test/git-commit-push-6530.serial.test.ts
@@ -0,0 +1,477 @@
+/**
+ * #6530: shared-checkout-safe commit, push and pull. Real git against local
+ * bare remotes. Pins the protocol in src/core/git/commit-push.ts: a short
+ * commit lock and a separate publish lock per checkout, path-scoped commits, remote commits merged in memory,
+ * the checkout advanced fast-forward only, nothing ever rebased or stashed.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+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 { getLastPushOutcome } from '../src/core/brain-repo-durability.ts';
+
+let root: string;
+
+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 of it on one branch `main`, seeded with x/y/z. */
+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');
+ for (const f of ['x.md', 'y.md', 'z.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 status = (dir: string) => execFileSync('git', ['-C', dir, 'status', '--porcelain'], { encoding: 'utf-8', env: process.env }).replace(/\n$/, '');
+const remoteHead = (bare: string) => git(bare, 'rev-parse', 'refs/heads/main');
+
+function conflictOf(fn: () => unknown): { local: string; remote: string; paths: string[]; structural: string[]; fix: string } {
+ try { fn(); } catch (e) {
+ const err = e as { code?: string; detail?: string; fix?: unknown; message?: string };
+ expect(err.code).toBe('integrate_conflict');
+ return { ...JSON.parse(err.detail!), fix: JSON.stringify(err) + String((e as Error).message) };
+ }
+ throw new Error('expected integrate_conflict');
+}
+
+/** Hold an OS lock file in a child (flock) until killed. */
+async function holdLock(path: string): Promise<{ kill(): void }> {
+ writeFileSync(path, '');
+ const holder = spawn('flock', [path, 'sleep', '30'], { stdio: 'ignore' });
+ await new Promise(r => setTimeout(r, 300));
+ return { kill: () => holder.kill('SIGKILL') };
+}
+
+beforeAll(() => { process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT = '1'; });
+afterAll(() => { delete process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT; });
+beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'cp6530-')); });
+afterEach(() => { delete process.env.BRAIN_COMMIT_LOCK_HELD; delete process.env.GBRAIN_GIT_NO_MERGE_TREE; rmSync(root, { recursive: true, force: true }); });
+
+describe('commit scope', () => {
+ test('commits only the named paths; another writer\'s staged and unstaged files stay put', () => {
+ const { bare, a } = setup();
+ writeFileSync(join(a, 'y.md'), 'staged by another writer\n'); git(a, 'add', 'y.md');
+ writeFileSync(join(a, 'z.md'), 'half-written by another writer\n');
+ writeFileSync(join(a, 'x.md'), 'mine\n');
+ const r = commitAndPush({ repo: a, paths: ['x.md'], message: 'mine', cwd: a });
+ expect(r.outcome).toBe('pushed');
+ expect(git(bare, 'show', 'main:x.md')).toBe('mine');
+ expect(git(bare, 'show', 'main:y.md')).toBe('y.md v1');
+ expect(git(bare, 'show', 'main:z.md')).toBe('z.md v1');
+ expect(status(a)).toBe('M y.md\n M z.md');
+ });
+
+ test('refuses the whole checkout, paths outside it, .git and an empty list before staging anything', () => {
+ const { a } = setup();
+ writeFileSync(join(a, 'x.md'), 'dirty\n');
+ for (const paths of [['.'], [a], ['../elsewhere.md'], ['.git/config'], []]) {
+ expect(() => commitAndPush({ repo: a, paths, message: 'm', cwd: a })).toThrow(expect.objectContaining({ code: 'commit_paths_invalid' }));
+ }
+ expect(status(a)).toBe(' M x.md');
+ });
+
+ test('a staged rename (git mv) commits both sides: no duplicate page, no deletion left staged', () => {
+ const { bare, a } = setup();
+ git(a, 'mv', 'x.md', 'renamed.md');
+ commitAndPush({ repo: a, paths: ['renamed.md'], message: 'rename', cwd: a });
+ expect(git(bare, 'ls-tree', '--name-only', 'main').split('\n')).toEqual(['renamed.md', 'y.md', 'z.md']);
+ expect(status(a)).toBe('');
+ });
+
+ test('nothing to commit still publishes a pending local commit (never reports success over an undelivered one)', () => {
+ const { bare, a } = setup();
+ writeFileSync(join(a, 'x.md'), 'committed earlier, never pushed\n');
+ git(a, 'commit', '-qam', 'pending');
+ const pending = git(a, 'rev-parse', 'HEAD');
+ const r = commitAndPush({ repo: a, paths: ['y.md'], message: 'noop', cwd: a });
+ expect(r.outcome).toBe('nothing_to_commit');
+ expect(remoteHead(bare)).toBe(pending);
+ });
+});
+
+describe('integrate in memory', () => {
+ test('a rejected push merges remote commits without touching dirty files; the checkout fast-forwards', () => {
+ const { bare, a, b } = setup();
+ writeFileSync(join(b, 'y.md'), 'remote edit\n');
+ commitAndPush({ repo: b, paths: ['y.md'], message: 'remote', cwd: b });
+ writeFileSync(join(a, 'z.md'), 'dirty, unrelated\n');
+ writeFileSync(join(a, 'x.md'), 'local edit\n');
+ const r = commitAndPush({ repo: a, paths: ['x.md'], message: 'local', cwd: a });
+ expect(r).toMatchObject({ outcome: 'pushed', integrated: 1, checkout: 'advanced' });
+ expect(remoteHead(bare)).toBe(git(a, 'rev-parse', 'HEAD'));
+ expect(git(a, 'log', '-1', '--format=%s')).toBe('gbrain: merge origin/main into main');
+ expect(read(a, 'y.md')).toBe('remote edit\n');
+ expect(read(a, 'z.md')).toBe('dirty, unrelated\n');
+ for (const marker of ['rebase-merge', 'rebase-apply', 'MERGE_HEAD']) expect(existsSync(join(a, '.git', marker))).toBe(false);
+ expect(git(a, 'stash', 'list')).toBe('');
+ });
+
+ test('a dirty file the merge must change keeps its bytes: the push lands and the checkout lags', () => {
+ const { bare, a, b } = setup();
+ writeFileSync(join(b, 'y.md'), 'remote edit\n');
+ commitAndPush({ repo: b, paths: ['y.md'], message: 'remote', cwd: b });
+ writeFileSync(join(a, 'y.md'), 'in-flight edit by another agent\n');
+ writeFileSync(join(a, 'x.md'), 'local edit\n');
+ const before = git(a, 'rev-parse', 'HEAD');
+ const r = commitAndPush({ repo: a, paths: ['x.md'], message: 'local', cwd: a });
+ expect(r.outcome).toBe('pushed_checkout_lagging');
+ expect(r.lagging_reason).toContain('y.md');
+ expect(read(a, 'y.md')).toBe('in-flight edit by another agent\n');
+ expect(git(a, 'rev-parse', 'HEAD')).not.toBe(remoteHead(bare));
+ expect(git(a, 'merge-base', '--is-ancestor', before, remoteHead(bare))).toBe('');
+ // The lag clears on the next pull once that file is no longer dirty.
+ writeFileSync(join(a, 'y.md'), 'y.md v1\n');
+ expect(pullShared(a).status).toBe('advanced');
+ expect(git(a, 'rev-parse', 'HEAD')).toBe(remoteHead(bare));
+ });
+
+ test('a same-file conflict changes nothing; --resolve publishes the chosen side', () => {
+ const { bare, a, b } = setup();
+ writeFileSync(join(b, 'x.md'), 'remote version\n');
+ commitAndPush({ repo: b, paths: ['x.md'], message: 'remote', cwd: b });
+ writeFileSync(join(a, 'x.md'), 'local version\n');
+ let error: { code?: string; detail?: string } = {};
+ try { commitAndPush({ repo: a, paths: ['x.md'], message: 'local', cwd: a }); } catch (e) { error = e as typeof error; }
+ expect(error.code).toBe('integrate_conflict');
+ expect(JSON.parse(error.detail!).paths).toEqual(['x.md']);
+ expect(read(a, 'x.md')).toBe('local version\n');
+ expect(git(a, 'status', '--porcelain')).toBe('');
+ for (const marker of ['rebase-merge', 'MERGE_HEAD']) expect(existsSync(join(a, '.git', marker))).toBe(false);
+ const r = commitAndPush({ repo: a, pushOnly: true, cwd: a, resolutions: new Map([['x.md', { kind: 'theirs' }]]), expectRemote: JSON.parse(error.detail!).remote });
+ expect(r.outcome).toBe('pushed');
+ expect(git(bare, 'show', 'main:x.md')).toBe('remote version');
+ expect(read(a, 'x.md')).toBe('remote version\n');
+ });
+
+ test('a non-ASCII conflicted path is reported raw; resolving it as printed publishes exactly the chosen blob', () => {
+ const { bare, a, b } = setup();
+ const name = 'people/café notes.md';
+ mkdirSync(join(a, 'people')); mkdirSync(join(b, 'people'));
+ writeFileSync(join(b, name), 'remote version\n');
+ commitAndPush({ repo: b, paths: [name], message: 'remote', cwd: b });
+ writeFileSync(join(a, name), 'local version\n');
+ const c = conflictOf(() => commitAndPush({ repo: a, paths: [name], message: 'local', cwd: a }));
+ expect(c.paths).toEqual([name]);
+ expect(c.fix).toContain(`'${name}'=ours|theirs`);
+ commitAndPush({ repo: a, pushOnly: true, cwd: a, resolutions: new Map([[c.paths[0], { kind: 'theirs' }]]), expectRemote: c.remote });
+ expect(git(bare, 'show', `main:${name}`)).toBe('remote version');
+ expect(git(bare, 'show', 'main:x.md')).toBe('x.md v1');
+ });
+
+ test('a choice binds to the remote commit it was made against: a remote that moved since is reported again', () => {
+ const { bare, a, b } = setup();
+ writeFileSync(join(b, 'x.md'), 'remote v1\n');
+ commitAndPush({ repo: b, paths: ['x.md'], message: 'remote 1', cwd: b });
+ writeFileSync(join(a, 'x.md'), 'local\n');
+ const c = conflictOf(() => commitAndPush({ repo: a, paths: ['x.md'], message: 'local', cwd: a }));
+ writeFileSync(join(b, 'x.md'), 'remote v2, never shown to the user\n');
+ commitAndPush({ repo: b, paths: ['x.md'], message: 'remote 2', cwd: b });
+ const tip = remoteHead(bare);
+ const again = conflictOf(() => commitAndPush({ repo: a, pushOnly: true, cwd: a, resolutions: new Map([['x.md', { kind: 'ours' }]]), expectRemote: c.remote }));
+ expect(again.remote).toBe(tip);
+ expect(again.fix).toContain('The remote moved');
+ expect(remoteHead(bare)).toBe(tip);
+ });
+
+ test('a file/directory conflict is refused, never resolved by a per-file choice that could drop a side', () => {
+ const { bare, a, b } = setup();
+ mkdirSync(join(b, 'topic'));
+ writeFileSync(join(b, 'topic', 'remote.md'), 'remote\n');
+ commitAndPush({ repo: b, paths: ['topic/remote.md'], message: 'remote dir', cwd: b });
+ writeFileSync(join(a, 'topic'), 'local file\n');
+ const c = conflictOf(() => commitAndPush({ repo: a, paths: ['topic'], message: 'local file', cwd: a }));
+ expect(c.structural.length).toBeGreaterThan(0);
+ expect(c.fix).toContain('cannot resolve');
+ const tip = remoteHead(bare);
+ const choices = new Map(c.paths.map(p => [p, { kind: 'ours' as const }]));
+ const refused = conflictOf(() => commitAndPush({ repo: a, pushOnly: true, cwd: a, resolutions: choices, expectRemote: c.remote }));
+ expect(refused.structural.length).toBeGreaterThan(0);
+ expect(remoteHead(bare)).toBe(tip);
+ expect(read(a, 'topic')).toBe('local file\n');
+ });
+
+ test('an unresolved conflict is recorded per checkout (put_page / doctor read it) and cleared by the resolving publish', () => {
+ const { a, b } = setup();
+ writeFileSync(join(b, 'x.md'), 'remote\n');
+ commitAndPush({ repo: b, paths: ['x.md'], message: 'remote', cwd: b });
+ writeFileSync(join(a, 'x.md'), 'local\n');
+ const c = conflictOf(() => commitAndPush({ repo: a, paths: ['x.md'], message: 'local', cwd: a }));
+ expect(readIntegrateConflict(a)).toEqual(expect.objectContaining({ branch: 'main', paths: ['x.md'], remote: c.remote }));
+ expect(getLastPushOutcome('main', a).status).toBe('needs_attention');
+ expect(readIntegrateConflict(b)).toBeNull();
+ commitAndPush({ repo: a, pushOnly: true, cwd: a, resolutions: new Map([['x.md', { kind: 'ours' }]]), expectRemote: c.remote });
+ expect(readIntegrateConflict(a)).toBeNull();
+ });
+
+ test('a push-only retry after the blocking edit clears advances the lagging checkout to the published merge', () => {
+ const { bare, a, b } = setup();
+ writeFileSync(join(b, 'y.md'), 'remote edit\n');
+ commitAndPush({ repo: b, paths: ['y.md'], message: 'remote', cwd: b });
+ writeFileSync(join(a, 'y.md'), 'blocking edit\n');
+ writeFileSync(join(a, 'x.md'), 'local\n');
+ expect(commitAndPush({ repo: a, paths: ['x.md'], message: 'local', cwd: a }).outcome).toBe('pushed_checkout_lagging');
+ writeFileSync(join(a, 'y.md'), 'y.md v1\n');
+ const r = commitAndPush({ repo: a, pushOnly: true, cwd: a });
+ expect(r.checkout).toBe('advanced');
+ expect(git(a, 'rev-parse', 'HEAD')).toBe(remoteHead(bare));
+ expect(read(a, 'y.md')).toBe('remote edit\n');
+ });
+
+ test('git < 2.38 fallback: resolving one file keeps the remote\'s clean changes to other files', () => {
+ process.env.GBRAIN_GIT_NO_MERGE_TREE = '1';
+ const { bare, a, b } = setup();
+ writeFileSync(join(b, 'x.md'), 'remote x\n');
+ writeFileSync(join(b, 'y.md'), 'remote y\n');
+ commitAndPush({ repo: b, paths: ['x.md', 'y.md'], message: 'remote', cwd: b });
+ writeFileSync(join(a, 'x.md'), 'local x\n');
+ const c = conflictOf(() => commitAndPush({ repo: a, paths: ['x.md'], message: 'local', cwd: a }));
+ expect(c.paths).toEqual(['x.md']);
+ commitAndPush({ repo: a, pushOnly: true, cwd: a, resolutions: new Map([['x.md', { kind: 'ours' }]]), expectRemote: c.remote });
+ expect(git(bare, 'show', 'main:x.md')).toBe('local x');
+ expect(git(bare, 'show', 'main:y.md')).toBe('remote y');
+ });
+
+ test('git < 2.38 fallback (3-way read-tree into a temporary index) merges disjoint paths and refuses same-file changes', () => {
+ process.env.GBRAIN_GIT_NO_MERGE_TREE = '1';
+ const { bare, a, b } = setup();
+ writeFileSync(join(b, 'y.md'), 'remote edit\n');
+ commitAndPush({ repo: b, paths: ['y.md'], message: 'remote', cwd: b });
+ writeFileSync(join(a, 'x.md'), 'local edit\n');
+ expect(commitAndPush({ repo: a, paths: ['x.md'], message: 'local', cwd: a }).integrated).toBe(1);
+ expect(git(bare, 'show', 'main:y.md')).toBe('remote edit');
+ writeFileSync(join(b, 'z.md'), 'b\n');
+ pullShared(b);
+ commitAndPush({ repo: b, paths: ['z.md'], message: 'b z', cwd: b });
+ writeFileSync(join(a, 'z.md'), 'a\n');
+ expect(() => commitAndPush({ repo: a, paths: ['z.md'], message: 'a z', cwd: a })).toThrow(expect.objectContaining({ code: 'integrate_conflict' }));
+ });
+});
+
+describe('advance is a compare-and-swap', () => {
+ test('a lockless commit that lands while the push is in flight survives (never checkout -B)', () => {
+ const { bare, a, b } = setup();
+ writeFileSync(join(b, 'y.md'), 'remote edit\n');
+ commitAndPush({ repo: b, paths: ['y.md'], message: 'remote', cwd: b });
+ // A git that commits z.md from "another writer" the first time a push runs, then pushes for real.
+ const bin = join(root, 'bin');
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'git'), `#!/usr/bin/env bash
+sub=""; i=1
+while [ "$i" -le "$#" ]; do a="\${!i}"; case "$a" in -C|-c) i=$((i+2));; -*) i=$((i+1));; *) sub="$a"; break;; esac; done
+if [ "$sub" = push ] && [ ! -e "${root}/raced" ]; then
+ : > "${root}/raced"
+ echo racer > "${a}/z.md"
+ "${Bun.which('git')}" -C "${a}" -c user.name=racer -c [email protected] commit -q --only -m racer -- z.md
+fi
+exec "${Bun.which('git')}" "$@"
+`, { mode: 0o755 });
+ const oldPath = process.env.PATH;
+ process.env.PATH = `${bin}:${oldPath}`;
+ try {
+ writeFileSync(join(a, 'x.md'), 'local edit\n');
+ const r = commitAndPush({ repo: a, paths: ['x.md'], message: 'local', cwd: a });
+ expect(r.outcome).toBe('pushed_checkout_lagging');
+ } finally {
+ process.env.PATH = oldPath;
+ }
+ expect(git(a, 'log', '-1', '--format=%s')).toBe('racer');
+ expect(read(a, 'z.md')).toBe('racer\n');
+ expect(git(bare, 'show', 'main:x.md')).toBe('local edit');
+ });
+});
+
+describe('lock', () => {
+ test('a held lock makes commit-push fail loudly (commit_lock_busy) and commits nothing', async () => {
+ const { a } = setup();
+ const lockPath = join(a, '.git', 'brain-commit.lock');
+ writeFileSync(lockPath, '');
+ const holder = spawn('flock', [lockPath, 'sleep', '20'], { stdio: 'ignore' });
+ try {
+ await new Promise(r => setTimeout(r, 300));
+ writeFileSync(join(a, 'x.md'), 'mine\n');
+ expect(() => commitAndPush({ repo: a, paths: ['x.md'], message: 'm', cwd: a, lockWaitMs: 300 }))
+ .toThrow(expect.objectContaining({ code: 'commit_lock_busy' }));
+ expect(status(a)).toBe(' M x.md');
+ } finally { holder.kill('SIGKILL'); }
+ }, 30_000);
+
+ test('the re-entrancy marker is honored only when it names this lock and the lock is really held', () => {
+ const { a } = setup();
+ process.env.BRAIN_COMMIT_LOCK_HELD = join(a, '.git', 'brain-commit.lock');
+ const stale = acquireCommitLock(a, 0);
+ expect(stale.reentrant).toBe(false);
+ const nested = acquireCommitLock(a, 0);
+ expect(nested.reentrant).toBe(true);
+ process.env.BRAIN_COMMIT_LOCK_HELD = '1';
+ expect(() => acquireCommitLock(a, 0)).toThrow(expect.objectContaining({ code: 'commit_lock_busy' }));
+ nested.release(); stale.release();
+ });
+
+ test('a slow push never blocks commits: the commit lock is free while another publish holds the push lock', async () => {
+ const { a } = setup();
+ const holder = await holdLock(join(a, '.git', 'brain-publish.lock'));
+ try {
+ writeFileSync(join(a, 'x.md'), 'page write\n');
+ const started = Date.now();
+ expect(commitPathsLocked(a, [join(a, 'x.md')], 'gbrain: write-through x', { lockWaitMs: 2000 })).not.toBeNull();
+ expect(Date.now() - started).toBeLessThan(2000);
+ const deferred = commitAndPush({ repo: a, pushOnly: true, cwd: a, advanceOnlyWhenClean: true });
+ expect(deferred.outcome).toBe('push_deferred');
+ expect(existsSync(join(a, '.git', 'brain-publish.requested'))).toBe(true);
+ writeFileSync(join(a, 'y.md'), 'foreground\n');
+ let err: { code?: string } = {};
+ try { commitAndPush({ repo: a, paths: ['y.md'], message: 'fg', cwd: a, publishWaitMs: 200 }); } catch (e) { err = e as typeof err; }
+ expect(err.code).toBe('push_unconfirmed');
+ expect(git(a, 'show', 'HEAD:y.md')).toBe('foreground');
+ } finally { holder.kill(); }
+ }, 30_000);
+
+ test('a publish that found the push lock busy is honored by the holder after it releases (no stranded commit)', () => {
+ const { bare, a } = setup();
+ const cli = join(import.meta.dir, '..', 'src', 'cli.ts');
+ const bin = join(root, 'bin');
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'git'), `#!/usr/bin/env bash
+sub=""; i=1
+while [ "$i" -le "$#" ]; do a="\${!i}"; case "$a" in -C|-c) i=$((i+2));; -*) i=$((i+1));; *) sub="$a"; break;; esac; done
+if [ "$sub" = push ] && [ ! -e "${root}/raced" ]; then
+ : > "${root}/raced"
+ echo hook > "${a}/w.md"
+ "${Bun.which('git')}" -C "${a}" add -- w.md && "${Bun.which('git')}" -C "${a}" commit -q -m "write-through w" -- w.md
+ "${process.execPath}" "${cli}" git commit-push --path "${a}" --push-only --require-clean --json > "${root}/deferred.json" 2>/dev/null
+fi
+exec "${Bun.which('git')}" "$@"
+`, { mode: 0o755 });
+ const oldPath = process.env.PATH;
+ process.env.PATH = `${bin}:${oldPath}`;
+ try {
+ writeFileSync(join(a, 'x.md'), 'mine\n');
+ commitAndPush({ repo: a, paths: ['x.md'], message: 'mine', cwd: a });
+ } finally {
+ process.env.PATH = oldPath;
+ }
+ expect(JSON.parse(read(root, 'deferred.json')).outcome).toBe('push_deferred');
+ expect(git(bare, 'show', 'main:w.md')).toBe('hook');
+ expect(git(bare, 'show', 'main:x.md')).toBe('mine');
+ 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 () => {
+ const { a } = setup();
+ const lockPath = join(a, '.git', 'brain-commit.lock');
+ writeFileSync(lockPath, '');
+ const holder = spawn('flock', [lockPath, 'sleep', '20'], { stdio: 'ignore' });
+ 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');
+ } finally { holder.kill('SIGKILL'); }
+ }, 30_000);
+});
+
+describe('pull', () => {
+ test('requireClean (the cron) skips on any local edit; the explicit pull advances past unrelated dirt', () => {
+ const { a, b } = setup();
+ writeFileSync(join(b, 'y.md'), 'remote edit\n');
+ commitAndPush({ repo: b, paths: ['y.md'], message: 'remote', cwd: b });
+ writeFileSync(join(a, 'z.md'), 'dirty\n');
+ expect(pullShared(a, { requireClean: true }).status).toBe('skipped_dirty');
+ expect(read(a, 'y.md')).toBe('y.md v1\n');
+ expect(pullShared(a).status).toBe('advanced');
+ expect(read(a, 'y.md')).toBe('remote edit\n');
+ expect(read(a, 'z.md')).toBe('dirty\n');
+ });
+
+ test('diverged history merges in memory and never pushes', () => {
+ const { bare, a, b } = setup();
+ writeFileSync(join(b, 'y.md'), 'remote edit\n');
+ commitAndPush({ repo: b, paths: ['y.md'], message: 'remote', cwd: b });
+ const remote = remoteHead(bare);
+ writeFileSync(join(a, 'x.md'), 'local\n'); git(a, 'commit', '-qam', 'local only');
+ const r = pullShared(a);
+ expect(r).toMatchObject({ status: 'advanced', merged: true });
+ expect(remoteHead(bare)).toBe(remote);
+ expect(read(a, 'y.md')).toBe('remote edit\n');
+ expect(read(a, 'x.md')).toBe('local\n');
+ });
+
+ test('refuses while a rebase is in progress and never deletes its state', () => {
+ const { a } = setup();
+ mkdirSync(join(a, '.git', 'rebase-merge'));
+ writeFileSync(join(a, '.git', 'rebase-merge', 'autostash'), 'deadbeef\n');
+ expect(() => pullShared(a)).toThrow(expect.objectContaining({ code: 'git_operation_in_progress' }));
+ expect(() => commitAndPush({ repo: a, paths: ['x.md'], message: 'm', cwd: a })).toThrow(expect.objectContaining({ code: 'git_operation_in_progress' }));
+ expect(existsSync(join(a, '.git', 'rebase-merge', 'autostash'))).toBe(true);
+ });
+});
+
+describe('forced probe: the old in-tree rebase vs the new protocol', () => {
+ test('pull --rebase --autostash rewrites another writer\'s in-flight edit; commit-push leaves it byte-identical', () => {
+ for (const mode of ['old', 'new'] as const) {
+ rmSync(root, { recursive: true, force: true }); mkdirSync(root);
+ const { a, b } = setup();
+ writeFileSync(join(b, 'y.md'), 'remote edit\n');
+ commitAndPush({ repo: b, paths: ['y.md'], message: 'remote', cwd: b });
+ writeFileSync(join(a, 'y.md'), 'in-flight edit by another agent\n');
+ writeFileSync(join(a, 'x.md'), 'mine\n');
+ if (mode === 'old') {
+ git(a, 'commit', '-q', '--only', '-m', 'mine', '--', 'x.md');
+ try { git(a, 'pull', '--rebase', '--autostash', 'origin', 'main'); } catch { /* conflicted autostash */ }
+ expect(read(a, 'y.md')).not.toBe('in-flight edit by another agent\n');
+ } else {
+ commitAndPush({ repo: a, paths: ['x.md'], message: 'mine', cwd: a });
+ expect(read(a, 'y.md')).toBe('in-flight edit by another agent\n');
+ expect(git(a, 'stash', 'list')).toBe('');
+ }
+ }
+ });
+});
+
+describe('many writers, two clones, one remote', () => {
+ test('12 concurrent CLI writers: every commit lands, no rebase state, no foreign file committed or lost', async () => {
+ const { bare, a, b } = setup();
+ const cli = join(import.meta.dir, '..', 'src', 'cli.ts');
+ const writers = Array.from({ length: 12 }, (_, i) => ({ dir: i % 2 ? b : a, file: `w${i}.md` }));
+ for (const { dir } of writers) writeFileSync(join(dir, `foreign-${dir === a ? 'a' : 'b'}.md`), 'never committed\n');
+ const runs = writers.map(({ dir, file }) => new Promise<number>(resolve => {
+ writeFileSync(join(dir, file), `${file}\n`);
+ const child = spawn(process.execPath, [cli, 'git', 'commit-push', '--path', dir, '-m', `write ${file}`, '--', file], {
+ stdio: ['ignore', 'ignore', 'pipe'], env: { ...process.env, GBRAIN_COMMIT_LOCK_WAIT_SECONDS: '120' },
+ });
+ let err = '';
+ child.stderr?.on('data', d => { err += d; });
+ child.on('exit', code => { if (code) console.error(`${file}: exit ${code}\n${err}`); resolve(code ?? 1); });
+ }));
+ const codes = await Promise.all(runs);
+ expect(codes).toEqual(writers.map(() => 0));
+ const tree = git(bare, 'ls-tree', '--name-only', 'main').split('\n');
+ for (const { file } of writers) expect(tree).toContain(file);
+ expect(tree.some(f => f.startsWith('foreign-'))).toBe(false);
+ for (const dir of [a, b]) {
+ expect(existsSync(join(dir, '.git', 'rebase-merge'))).toBe(false);
+ expect(git(dir, 'stash', 'list')).toBe('');
+ expect(read(dir, `foreign-${dir === a ? 'a' : 'b'}.md`)).toBe('never committed\n');
+ }
+ }, 180_000);
+});
diff --git a/test/git-remote.test.ts b/test/git-remote.test.ts
index f1db28c835..d8c96f23ed 100644
--- a/test/git-remote.test.ts
+++ b/test/git-remote.test.ts
@@ -43,6 +43,9 @@ const mode = readFileSync(${JSON.stringify(FAKE_GIT_MODE)}, 'utf8');
if (mode === 'fail') process.exit(1);
if (mode === 'url-drift') console.log('https://github.com/different/url');
if (mode === 'url-match') console.log('https://github.com/expected/url');
+// #6530: pullRepo locates the checkout's commit lock with rev-parse --git-path.
+const gitPath = process.argv.indexOf('--git-path');
+if (gitPath !== -1) console.log(${JSON.stringify(FAKE_GIT_DIR)} + '/locks/' + process.argv[gitPath + 1]);
`);
// Use the already-required Bun executable: optional host tools such as jq
// must not decide whether argv security assertions can run in CI.
@@ -330,25 +333,27 @@ describe('cloneRepo', () => {
// ---------------------------------------------------------------------------
describe('pullRepo', () => {
- test('happy path: invokes git -C path with GIT_SSRF_FLAGS + pull --ff-only', async () => {
+ test('happy path (#6530): fetch with GIT_SSRF_FLAGS, then merge --ff-only (merge.autoStash=false) under the commit lock; never git pull', async () => {
const repo = join(FAKE_GIT_DIR, 'pull-target');
mkdirSync(repo, { recursive: true });
await withEnv({ PATH: fakePath() }, async () => {
await pullRepo(repo);
});
- const argv = readArgvLog()[0];
+ const calls = readArgvLog();
+ const argv = calls[0];
expect(argv[0]).toBe('-C');
expect(argv[1]).toBe(repo);
expect(argv.slice(2, 2 + GIT_SSRF_FLAGS.length)).toEqual([...GIT_SSRF_FLAGS]);
- expect(argv).toContain('pull');
- expect(argv).toContain('--ff-only');
+ expect(argv).toContain('fetch');
// v0.34 fix wave: subcommand flag position assertion.
- const pullIdx = argv.indexOf('pull');
- expect(pullIdx).toBeGreaterThan(-1);
+ const fetchIdx = argv.indexOf('fetch');
for (const subFlag of GIT_SSRF_SUBCOMMAND_FLAGS) {
- const flagIdx = argv.indexOf(subFlag);
- expect(flagIdx).toBeGreaterThan(pullIdx);
+ expect(argv.indexOf(subFlag)).toBeGreaterThan(fetchIdx);
}
+ expect(calls.some(call => call.includes('pull') || call.includes('rebase') || call.includes('stash'))).toBe(false);
+ const merge = calls.find(call => call.includes('merge'))!;
+ expect(merge.slice(merge.indexOf('merge'))).toContain('--ff-only');
+ expect(merge[merge.indexOf('merge.autoStash=false') - 1]).toBe('-c');
rmSync(repo, { recursive: true, force: true });
});
diff --git a/test/scripts/check-shared-tree-git.test.ts b/test/scripts/check-shared-tree-git.test.ts
new file mode 100644
index 0000000000..9e717bad72
--- /dev/null
+++ b/test/scripts/check-shared-tree-git.test.ts
@@ -0,0 +1,234 @@
+/**
+ * scripts/check-shared-tree-git.sh — #6530 shared-checkout git guard.
+ *
+ * Protects: skills, recipes, templates, docs, plugin trees and the three agent
+ * entry docs never teach a git command that stashes, rebases, sweeps up or
+ * discards other writers' files in a brain checkout several agents share
+ * (git pull --rebase, --autostash, git stash, repo-wide add/commit, reset
+ * --hard, force or bare push), while `git stash store`, `git push --dry-run`,
+ * path-scoped adds and lines with a reasoned allow marker pass; and the
+ * Multi-agent rules block stays identical in AGENTS.md, BOOTSTRAP_FOR_AGENTS.md
+ * and INSTALL_FOR_AGENTS.md.
+ * Fails when: a flagged form stops failing, an allowed form starts failing,
+ * an allow marker without a reason or an unclosed allow region passes, an
+ * exempt contributor doc starts failing, the failure loses its FAIL / Why /
+ * Fix / See lines or the file:line, or the script stops parsing under
+ * /bin/bash (3.2 on macOS).
+ * Seam: GBRAIN_GUARD_ROOT pointed at temp trees and the committed fixtures.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+const REPO = resolve(import.meta.dir, '..', '..');
+const SCRIPT = join(REPO, 'scripts/check-shared-tree-git.sh');
+const FIXTURES = join(REPO, 'test/fixtures/guards/check-shared-tree-git.sh');
+
+let root: string;
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'shared-tree-git-'));
+});
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+function write(rel: string, content: string): void {
+ const abs = join(root, rel);
+ mkdirSync(resolve(abs, '..'), { recursive: true });
+ writeFileSync(abs, content);
+}
+
+function run(guardRoot = root, args: string[] = [], shell = 'bash') {
+ return spawnSync(shell, [SCRIPT, ...args], { encoding: 'utf8', env: { ...process.env, GBRAIN_GUARD_ROOT: guardRoot } });
+}
+
+const fence = (body: string) => `# Skill\n\n\`\`\`bash\n${body}\n\`\`\`\n`;
+
+const FLAGGED: Array<[string, string]> = [
+ ['git pull --rebase origin main', 'pull-rebase'],
+ ['git -C ~/brain pull -r', 'pull-rebase'],
+ ['git pull --rebase --autostash', 'pull-rebase'],
+ ['git rebase --autostash origin/main', 'autostash'],
+ ['git stash', 'stash'],
+ ['git stash pop', 'stash'],
+ ['git add -A', 'add-all'],
+ ['git add -A && git commit -m "x"', 'add-all'],
+ ['git add --all', 'add-all'],
+ ['git add .', 'add-all'],
+ ['git commit -am "x"', 'commit-all'],
+ ['git commit -a -m "x"', 'commit-all'],
+ ['git -C ~/brain commit -qam "x"', 'commit-all'],
+ ['git reset --hard origin/main', 'reset-hard'],
+ ['git push --force origin main', 'force-push'],
+ ['git push -f', 'force-push'],
+ ['git push --force-with-lease', 'force-push'],
+ ['git push origin +main', 'force-push'],
+ ['git push', 'push'],
+ ['git push -u origin main', 'push'],
+ ['cd brain && git commit -m "x" -- a.md && git push', 'push'],
+];
+
+const ALLOWED = [
+ 'gbrain git commit-push -m "x" -- people/alice-example.md',
+ 'gbrain git commit-push --push-only',
+ 'scripts/brain-commit-push.sh --pull',
+ 'git stash store -m "rescued" "$(cat "$f")"',
+ 'git stash list',
+ 'git stash show -p stash@{0}',
+ 'git push --dry-run origin HEAD:main',
+ 'git add -A -- people/alice-example.md',
+ 'git add people/alice-example.md',
+ 'git commit -m "x" -- people/alice-example.md',
+ 'git commit --amend --no-edit',
+ 'git merge --ff-only --no-autostash origin/main',
+ 'git pull --no-rebase --ff-only',
+ 'ls .git/rebase-merge',
+];
+
+describe('check-shared-tree-git.sh', () => {
+ it('passes a tree that uses the shared-checkout commands', () => {
+ write('skills/s/SKILL.md', fence(ALLOWED.join('\n')));
+ const r = run();
+ expect(r.stderr).toBe('');
+ expect(r.status).toBe(0);
+ expect(r.stdout).toContain('✓ shared-tree git');
+ });
+
+ for (const [cmd, kind] of FLAGGED) {
+ it(`fails on \`${cmd}\` in a code block as ${kind}, with FAIL / Why / Fix / See`, () => {
+ write('skills/s/SKILL.md', fence(cmd));
+ const r = run();
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain(`FAIL: skills/s/SKILL.md:4 ${kind} `);
+ expect(r.stderr).toMatch(/^Why: {2}\S/m);
+ expect(r.stderr).toMatch(/^Fix: {2}\S/m);
+ expect(r.stderr).toContain('See: docs/guides/shared-checkout-git.md');
+ });
+ }
+
+ it('checks inline code spans in prose but not plain prose', () => {
+ write('docs/a.md', 'Run `git pull --rebase` first.\n');
+ write('docs/b.md', 'The recipe spreads at the speed of a git push.\n');
+ const r = run();
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('FAIL: docs/a.md:1 pull-rebase "git pull --rebase"');
+ expect(r.stderr).not.toContain('docs/b.md');
+ });
+
+ it('checks every line of a .sh file, comments included', () => {
+ write('skills/s/scripts/run.sh', '#!/bin/sh\n# then git push\n');
+ const r = run();
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('FAIL: skills/s/scripts/run.sh:2 push ');
+ });
+
+ it('passes the three allow-marker forms, each with a reason', () => {
+ write('skills/s/SKILL.md', [
+ '```bash',
+ 'git push --force origin main # gbrain-allow-shared-tree-git: confirmed purge of a private clone',
+ '```',
+ '',
+ '<!-- gbrain-allow-shared-tree-git: names what never to run -->',
+ 'Never run `git pull --rebase` here.',
+ '',
+ '<!-- gbrain-allow-shared-tree-git-begin: the forbidden list -->',
+ '- `git stash`',
+ '- `git reset --hard`',
+ '<!-- gbrain-allow-shared-tree-git-end -->',
+ '',
+ 'A same-line prose note: `git push -u origin main` <!-- gbrain-allow-shared-tree-git: first push of a new branch -->',
+ '',
+ ].join('\n'));
+ const r = run();
+ expect(r.stderr).toBe('');
+ expect(r.status).toBe(0);
+ });
+
+ it('a prose marker covers only the next line', () => {
+ write('docs/a.md', '<!-- gbrain-allow-shared-tree-git: one line -->\nRun `git stash` once.\nThen `git stash` again.\n');
+ const r = run();
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('FAIL: docs/a.md:3 stash ');
+ expect(r.stderr).not.toContain('docs/a.md:2');
+ });
+
+ it('fails a marker without a reason and an unclosed allow region', () => {
+ write('recipes/a.md', fence('git reset --hard # gbrain-allow-shared-tree-git:'));
+ write('docs/b.md', '<!-- gbrain-allow-shared-tree-git-begin: never closed -->\n- `git stash`\n');
+ const r = run();
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('FAIL: recipes/a.md:4 allow-marker-without-reason ');
+ expect(r.stderr).toContain('FAIL: docs/b.md:1 unclosed allow region');
+ });
+
+ it('scans skills, recipes, templates, docs, plugin trees and the agent docs', () => {
+ const scanned = ['skills/a/SKILL.md', 'recipes/r.md', 'templates/bootstrap/AGENTS.md.template', 'docs/guides/g.md',
+ 'plugin/skills/a/SKILL.md', 'plugin-variants/v/skills/a/SKILL.md'];
+ for (const rel of scanned) write(rel, 'Run `git stash` now.\n');
+ const r = run();
+ expect(r.status).toBe(1);
+ for (const rel of scanned) expect(r.stderr).toContain(`FAIL: ${rel}:1 stash `);
+ });
+
+ it('exempts generated error codes, contributor docs about the gbrain repo and historical records', () => {
+ for (const rel of ['docs/guides/error-codes.md', 'docs/RELEASING.md', 'docs/TESTING.md', 'docs/contributing/v.md',
+ 'docs/designs/d.md', 'docs/plans/p.md', 'CONTRIBUTING.md', 'CHANGELOG.md', 'TODOS.md', 'test/x.md', 'src/x.md']) {
+ write(rel, 'Run `git push --force` now.\n');
+ }
+ const r = run();
+ expect(r.stderr).toBe('');
+ expect(r.status).toBe(0);
+ });
+
+ it('requires the Multi-agent rules block to be identical in every agent doc', () => {
+ const block = (body: string) => `# Doc\n\n<!-- BEGIN multi-agent-rules -->\n${body}\n<!-- END multi-agent-rules -->\n`;
+ write('AGENTS.md', block('Use `gbrain git commit-push`.'));
+ write('INSTALL_FOR_AGENTS.md', block('Use `gbrain git commit-push`.'));
+ expect(run().status).toBe(0);
+ write('BOOTSTRAP_FOR_AGENTS.md', block('Use the helper.'));
+ let r = run();
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('FAIL: BOOTSTRAP_FOR_AGENTS.md Multi-agent rules block differs from AGENTS.md');
+ write('BOOTSTRAP_FOR_AGENTS.md', '# Bootstrap\n');
+ r = run();
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('FAIL: BOOTSTRAP_FOR_AGENTS.md has no Multi-agent rules block');
+ });
+
+ it('scans only the named files when given arguments', () => {
+ write('docs/a.md', 'Run `git stash`.\n');
+ write('docs/b.md', 'Run `git push`.\n');
+ const r = run(root, ['docs/b.md']);
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('FAIL: docs/b.md:1 push ');
+ expect(r.stderr).not.toContain('docs/a.md');
+ });
+
+ it('the committed fixtures: good passes and every bad tree fails', () => {
+ expect(run(join(FIXTURES, 'good')).status).toBe(0);
+ const bad = readdirSync(FIXTURES).filter(d => d === 'bad' || d.startsWith('bad-'));
+ expect(bad.length).toBeGreaterThan(1);
+ for (const d of bad) expect({ d, status: run(join(FIXTURES, d)).status }).toEqual({ d, status: 1 });
+ });
+});
+
+describe('check-shared-tree-git.sh under /bin/bash (3.2 on macOS)', () => {
+ it('parses', () => {
+ const r = spawnSync('/bin/bash', ['-n', SCRIPT], { encoding: 'utf8' });
+ expect(r.stderr).toBe('');
+ expect(r.status).toBe(0);
+ });
+
+ it('still flags a stash', () => {
+ write('docs/a.md', fence('git stash'));
+ const r = run(root, [], '/bin/bash');
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('FAIL: docs/a.md:4 stash ');
+ });
+
+ it('reads the awk program without a heredoc inside $(...)', () => {
+ expect(readFileSync(SCRIPT, 'utf8')).not.toMatch(/\$\(\s*cat\s+<</);
+ });
+});