Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(git): commit-push publishes a tracked deletion under an ignored directory (#7984)

garrytan3b61cce206a7
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.md
index 728a9db5ac..0d9fecf950 100644
--- a/docs/architecture/key-files/workspace-push-and-backup.md
+++ b/docs/architecture/key-files/workspace-push-and-backup.md
@@ -12,7 +12,7 @@ Key files:
## Shared-checkout git writer
-- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --literal-pathspecs`, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (`git_unavailable`, paths unstaged). `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. `notePending` is exported: the derived and dream write-through (`cycle/derived-write-through.ts`, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`. The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.sourceRoot` (#8662); a registered checkout must contain the resolved one, or be a subdirectory its HEAD tracks, so a repository that only encloses one is refused, and a registry that cannot be listed refuses `writer_coordinator_required` (GST-1623). Tests: `test/git-writer-safety-7381.serial.test.ts`, `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`.
+- `src/core/git/commit-push.ts` + `src/core/git/commit-guard.ts` — writer safety in a shared checkout (#7381). `integrate` replaces the tip 3-way merge when any local commit is patch-equivalent to an upstream one (`rev-list --cherry-mark`): it replays the local commits onto the remote tip in memory (`merge-tree --merge-base` on git 2.40+, a 3-way `read-tree` otherwise), leaving out the equivalent ones and clean merges, so a copy the remote edited never conflicts and one it reverted is never re-applied; the merge message lists what it left out. `supersededPaths` resolves a content conflict to ours when the remote's blob is one the same path held earlier in ours' history (last 200 commits touching it) and a different blob replaced it there; the push reports them as `superseded_remote_paths`, and `integrate_conflict` lists only the rest (`detail.superseded` names them). `commitPaths` refuses a path outside the source roots (`configuredSourceRoots`, git config `gbrain.sourceRoot`, recorded by `sources harden`'s `recordSourceRoot`) and a file another writer staged under a named directory (`commit_prestaged_paths`), stages named tracked paths with `add -u` and visible untracked ones with `add -A` (a tracked deletion under an ignored directory commits, #7984; any other path keeps git's `commit_paths_invalid`), and restores the exact index entries (`update-index --index-info`) when git refuses the commit. Every commit gbrain makes carries `GBRAIN_COMMIT_VIA=<lock path>`. Every pathspec it passes goes through `literalPathspecs` (`git-env.ts`), never `git --literal-pathspecs`, so the commit's hooks keep Git's normal pathspec rules: a pre-commit guard that selects files by glob still sees and can refuse them (`git_unavailable`, paths unstaged). `commitPathsLocked` (write-through) never commits without the lock: a busy lock or refused commit notes the file in `brain-writethrough-pending.log` (git dir, O_APPEND lines), which the next locked write-through and `commit-push --pending` commit and `settlePending` prunes. `notePending` is exported: the derived and dream write-through (`cycle/derived-write-through.ts`, #8073) records each file it writes before its batch commit, so a crash in between leaves the file for that sweep. A publish refuses local non-merge commits outside the roots (`commit_outside_source_root`; `--allow-outside-source-root` lifts both refusals, and `sources harden` passes it for its root scaffolding). With git config `gbrain.quarantine` (opt-in) a content conflict publishes the remote's version of each conflicted file plus every other local change, names the local commit under `refs/gbrain/quarantine/<time>-<sha>` and appends it to `brain-quarantine.log` (`readQuarantine` lists entries whose ref still exists); structural conflicts still refuse. `commit-guard.ts` installs the opt-in `prepare-commit-msg` guard (`gbrain git guard`), which admits only commits naming a held commit lock, passes merges and in-progress operations, and honors `GBRAIN_COMMIT_GUARD=off`. The helper's no-gbrain fallback (`renderCommitPushHelper`) marks children with the absolute lock path and releases the commit lock before pushing under `brain-publish.lock`. The CLI (`src/commands/git.ts`) refuses `checkout_not_a_source` before staging when this brain home's managed-root registry records source checkouts and the resolved checkout is none of them and has no `gbrain.sourceRoot` (#8662); a registered checkout must contain the resolved one, or be a subdirectory its HEAD tracks, so a repository that only encloses one is refused, and a registry that cannot be listed refuses `writer_coordinator_required` (GST-1623). Tests: `test/git-writer-safety-7381.serial.test.ts`, `test/git-literal-pathspec-hooks-7759.test.ts`, `test/git-commit-push-not-a-source-8662.test.ts`.
- `src/core/git/range-secret-scan.ts` — `scanRange(root, from, to)`, the secret gate for automatic publishes: `gbrain git commit-push --push-only --scan-secrets` (the child `gbrain sources refresh` runs to publish a diverged managed checkout) scans `trackingRef..target` under the publish lock, right before the push. Plumbing only (`rev-list`, `cat-file commit`, one streamed `diff-tree --stdin -p --root --cc`), so log, diff and attribute settings never change what is scanned. Commit messages, added lines and merge resolutions go through `scanText` with the `.gbrain-scan-allow` allowlist; a finding, added text over the scan cap or a change to `.gbrain-scan-allow`/`.gitattributes` refuses `publish_secret_found` (file, line, rule, commit, never the value), and a range it cannot read in full (git failure, unrecognised output, 300 s budget) refuses `publish_scan_unreadable`.
- `src/commands/doctor/checks/git-writer.ts` — `checkout_lagging`, `dirty_age`, `commits_outside_source_root`, `quarantined_changes` (#7381, brain category, after `git_convergence`): over the unmanaged source checkouts with an upstream (`sourceRoots` from git-convergence, grouped by toplevel with each source's toplevel-relative root), never fetching, every git call bounded at 5 s. Lagging warns when `HEAD..@{u}` holds a commit over an hour old (fix: `gbrain git commit-push --pull --path <top>`, agent). Dirty age warns on pending write-through files older than 30 minutes (`pendingWriteThroughStillDirty`; fix: `commit-push --pending`, agent) and on files staged that long (ask_user: unstage or commit by name). Outside-root warns on unpushed non-merge commits that change files outside the DB source roots plus `gbrain.sourceRoot` (`localCommitsOutsideRoots`; ask_user fix with `--allow-outside-source-root`), and says when the checkout has no root recorded. Test: `test/doctor-git-writer-7381.test.ts`.
- `src/core/git/commit-ledger.ts` — the commit ledger (PR B, docs/designs/REFRESH_WRITE_BARRIER.md part 3): `<git common dir>/gbrain/commit-ledger.jsonl`, one O_APPEND JSON line under 1 KiB per record, under its own flock `commit-ledger.lock` (start line, append, 4 MiB rotation to `commit-ledger.1.jsonl`). `recordCommit`/`recordCommitAsync` take the sha and writer kind (`commit_push`, `door`, `merge`, `replay`, `effect`, `sync_init`, `workspace_push`, `bootstrap`, `hosted_repo`); porcelain sites call `recordIntent` (head_before, `messageDigest` of the message) before `git commit`, plumbing sites record the `commit-tree` sha before the ref moves. A failed append never fails the commit (logged once); a directory outside git records nothing. `readLedger` reads both files; only a missing file reads as empty, any other read error throws (GST-1623). Tests: `test/commit-ledger.test.ts`.
diff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.md
index 36e8520cb5..e01b54fb28 100644
--- a/docs/guides/shared-checkout-git.md
+++ b/docs/guides/shared-checkout-git.md
@@ -44,7 +44,9 @@ another writer has half-written.
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>`), each
+ paths (`git add -u -- <paths>` for tracked ones, so a deletion under an
+ ignored directory still commits, `git add -A -- <paths>` for new files,
+ then `git commit --only -- <paths>`), each
marked literal (`:(literal)<path>`), so a name with `*`, `?` or `[` matches
only itself. The repository's hooks run as they do for a plain
`git commit`: a pre-commit check that picks files by pattern still sees
diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.ts
index 66ccfa80df..ff7609a4eb 100644
--- a/src/core/git/commit-push.ts
+++ b/src/core/git/commit-push.ts
@@ -471,11 +471,21 @@ function commitPaths(root: string, rel: string[], message: string, scope: Commit
docs: 'docs/guides/shared-checkout-git.md#outcomes' } });
}
const before = indexEntries(root, rel);
- const add = withIndexRetry(root, ['add', '-A', '--', ...literalPathspecs(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.');
- }
+ // #7984: a tracked path stages with `add -u`, because `add -A` refuses a deletion whose only match left is an ignored
+ // path; visible untracked files stage with `add -A`; a path already staged as deleted is staged. Any other path keeps
+ // git's own refusal (missing, or only an ignored untracked file).
+ const listed = (args: string[]) => git(root, [...args, '-z', '--', ...literalPathspecs(rel)]).stdout.split('\0').filter(Boolean);
+ const tracked = before.map(line => line.slice(line.indexOf('\t') + 1));
+ const untracked = listed(['ls-files', '--others', '--exclude-standard']);
+ const deleted = listed(['diff', '--cached', '--no-renames', '--name-only', '--diff-filter=D']);
+ const matching = (paths: string[]) => rel.filter(spec => paths.some(p => covers(spec, p)));
+ const unmatched = rel.filter(spec => !matching([...tracked, ...untracked, ...deleted]).includes(spec));
try {
+ for (const [mode, specs] of [['-u', matching(tracked)], ['-A', matching(untracked)], ['-A', unmatched]] as const) {
+ if (!specs.length) continue;
+ const add = withIndexRetry(root, ['add', mode, '--', ...literalPathspecs(specs)], '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.');
+ }
const paths = withRenamePartners(root, rel);
const partners = paths.filter(p => !insideSourceRoots(p, scope.roots));
if (partners.length) throw outsideRootError(root, scope.roots, partners, 'A staged rename would commit');
diff --git a/test/commit-push-ignored-deletion-7984.test.ts b/test/commit-push-ignored-deletion-7984.test.ts
new file mode 100644
index 0000000000..6f53244a69
--- /dev/null
+++ b/test/commit-push-ignored-deletion-7984.test.ts
@@ -0,0 +1,73 @@
+/**
+ * #7984: `gbrain git commit-push -- <path>` publishes a tracked file's deletion under a wildcard-ignored directory.
+ *
+ * Protects: a named tracked path is staged as a tracked path (`git add -u`), so its deletion commits and pushes whether
+ * or not it was already staged, with the ignore policy left as it is; visible untracked files still go through
+ * `git add -A`. Only the named paths are committed, and a named path that matches nothing, or only an ignored
+ * untracked file, is still refused `commit_paths_invalid` with the index unchanged.
+ * Fails when: the named paths go through one `git add -A` again: Git refuses a pathspec that now matches only an
+ * ignored path (`commit_paths_invalid`) and the approved deletion never leaves the checkout.
+ * Seam: real Git against a local bare remote.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { commitAndPush } from '../src/core/git/commit-push.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let root: string;
+const git = (cwd: string, ...args: string[]) => execFileSync('git', ['-C', cwd, '-c', 'protocol.file.allow=always', ...args],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const status = (cwd: string) => execFileSync('git', ['-C', cwd, 'status', '--porcelain'], { encoding: 'utf8' }).replace(/\n$/, '');
+const publish = (repo: string, paths: string[]) => withEnv({ GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1' },
+ () => commitAndPush({ repo, paths, message: 'remove artifacts', cwd: repo }));
+
+beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'gbrain-7984-')); });
+afterEach(() => rmSync(root, { recursive: true, force: true }));
+
+/** A pushed checkout whose `.gitignore` ignores everything (`*`), with force-tracked files under artifact/. */
+function ignoredCheckout(): { bare: string; repo: string } {
+ const bare = join(root, 'remote.git'), repo = join(root, 'repo');
+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', bare]);
+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', bare, repo], { stdio: 'ignore' });
+ git(repo, 'config', 'user.email', '[email protected]'); git(repo, 'config', 'user.name', 'Example');
+ writeFileSync(join(repo, '.gitignore'), '*\n');
+ mkdirSync(join(repo, 'artifact'));
+ for (const name of ['a.bin', 'b.bin', 'c.bin']) writeFileSync(join(repo, 'artifact', name), `${name}\n`);
+ git(repo, 'add', '-f', '.gitignore', 'artifact/a.bin', 'artifact/b.bin', 'artifact/c.bin');
+ git(repo, 'commit', '-qm', 'seed'); git(repo, 'push', '-q', '-u', 'origin', 'main');
+ return { bare, repo };
+}
+const remoteFiles = (bare: string) => git(bare, 'ls-tree', '-r', '--name-only', 'main').split('\n');
+
+describe('commit-push: tracked deletions under a wildcard ignore (#7984)', () => {
+ test('a staged deletion publishes, and only the named path is committed', async () => {
+ const { bare, repo } = ignoredCheckout();
+ rmSync(join(repo, 'artifact', 'a.bin')); git(repo, 'add', '-u', '--', 'artifact/a.bin');
+ rmSync(join(repo, 'artifact', 'b.bin')); git(repo, 'add', '-u', '--', 'artifact/b.bin');
+ expect((await publish(repo, ['artifact/a.bin'])).outcome).toBe('pushed');
+ expect(remoteFiles(bare)).toEqual(['.gitignore', 'artifact/b.bin', 'artifact/c.bin']);
+ expect(status(repo)).toBe('D artifact/b.bin');
+ });
+
+ test('an unstaged deletion publishes too', async () => {
+ const { bare, repo } = ignoredCheckout();
+ rmSync(join(repo, 'artifact', 'a.bin'));
+ expect((await publish(repo, ['artifact/a.bin'])).outcome).toBe('pushed');
+ expect(remoteFiles(bare)).toEqual(['.gitignore', 'artifact/b.bin', 'artifact/c.bin']);
+ expect(status(repo)).toBe('');
+ });
+
+ test('a path that matches nothing, or only an ignored untracked file, is still refused with the index unchanged', async () => {
+ const { bare, repo } = ignoredCheckout();
+ rmSync(join(repo, 'artifact', 'a.bin')); git(repo, 'add', '-u', '--', 'artifact/a.bin');
+ writeFileSync(join(repo, 'artifact', 'new.bin'), 'ignored\n');
+ for (const paths of [['artifact/a.bin', 'artifact/missing.bin'], ['artifact/a.bin', 'artifact/new.bin']]) {
+ await expect(publish(repo, paths)).rejects.toMatchObject({ code: 'commit_paths_invalid' });
+ expect(status(repo)).toBe('D artifact/a.bin');
+ }
+ expect(remoteFiles(bare)).toEqual(['.gitignore', 'artifact/a.bin', 'artifact/b.bin', 'artifact/c.bin']);
+ });
+});