Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(git): repair fix text prints gbrain git commit-push; -m repeats; --path <subdir> paths are relative to it (GBRA-133)

garrytand70da667626b
diff --git a/docs/architecture/key-files/core-fence-repair.md b/docs/architecture/key-files/core-fence-repair.md
index 0127d406af..c3c59c1210 100644
--- a/docs/architecture/key-files/core-fence-repair.md
+++ b/docs/architecture/key-files/core-fence-repair.md
@@ -15,6 +15,6 @@ The #6188 fence check that coordinated writers share, fence repair tiers, the ce
- `src/core/fence-repair/llm-tail.ts` — #6377 (Lane A3) the Tier 3 request kind `tail`: when a fence has no end marker and lines follow its last row on a world-visible page, the model sees only the fence's begin line, header, every row and the trailing lines to the section end (never the rest of the page) and answers one JSON object `{"tail": "prose" | "rows" | "unsure"}` through the same gateway call, caps, daily ledger and attempt memo as the row requests (memo key: the fence region's sha256 + model + prompt version, so an unchanged tail never costs twice and a transient `llm_unavailable` does not consume it). `prose` makes the close previewable under the `tail_exposure_approval` reason (the preview prints the exact exposed lines and the hash binds them; unattended runs record `needs_human` with the paragraph and the `gbrain repair content --only <path> --apply --expect <hash>` command); `rows` and `unsure` render `unclosed_ambiguous_tail` (manual, the exact edit). On a private page the model is never called: `structure.ts` closes the fence after the last row deterministically (`trailing_lines` on the receipt), because the privacy boundary hides nothing from anyone there. Tests: `test/fence-repair-llm.test.ts`.
- `src/core/fence-repair/stray-cells.ts` — #6188 Tier 1 `stray_empty_cell` (`strayCellPass`, run by `normalizeFences` after the structural pass): in a balanced primary fence with a canonical header, a row with more cells than the layout loses empty cells (slot removed, every other byte kept) only when exactly one distinct deletion leaves every validated column valid; otherwise it stays `extra_cells`, now manual. In a fence with no header, `headerlessMisfit` reads a row that starts with a row number by position: a `kind` cell that is not a kind word is `claim_split`, a row wider than any layout with an invalid validated column is `extra_cells` (after the same empty-cell removal), and `content.ts` holds both as manual, so a claim an unescaped `|` cut never reaches Tier 3. `rules.ts` `kindWord` keeps facts `kind_map` to a kind word (at most three words, no sentence punctuation, link or strikethrough); other text is `claim_split` (manual), never a kind note. Tests: `test/fence-repair-normalize.test.ts`.
- `src/core/fence-repair/{measured,model}.ts` — #6188 the Tier 3 eval's verdicts and the model they pick. `measured.ts`: `FENCE_REPAIR_MEASURED_MODELS` (the models that met the preregistered rule, best first) and `FENCE_REPAIR_MEASURED` (the behavior notice's accuracy sentence), updated together by the next eval. `model.ts`: `resolveFenceRepairModel(WithSource)`: an explicit `models.fence_repair` always (any model, priced or not); unset, the first measured model whose provider key the merged env has; else null (`no_measured_model`, a paid hold whose fix is `gbrain config set models.fence_repair <model>`). `gbrain models` reports the row through it (`measured default`). Tests: `test/repair-fences.test.ts`.
-- `src/core/fence-repair/{repair-io,receipt,uncommitted}.ts` — #6188 fence repair I/O. `loadFenceSource(engine, sourceId, { remote })`: managed owner root, or the `OwnerRefusal` row (`persistence/owner-refusal.ts`) that says why this host may not write it (a remote caller's row names no local path), legacy checkout, mirror flag, and the `RepairBusySet` (`persistence/repair-busy.ts`: in-flight writes plus the not-yet-admitted entries of every unfinished sync cursor, failing closed); an unfinished sync no longer marks the whole source busy. `writeFenceRepair` turns a `sync_in_progress` raised at the write's admission into `{ ok: false, reason: 'sync_in_progress' }`. `readFenceTarget`: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page; `spliceFileSections` puts the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections. `writeFenceRepair`: managed → `submitManagedFileRepair` (bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (`changed_since_read`), backed up under `~/.gbrain/backups/fences/<run>/`, written, `importFromFile` (restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (`uncommitted.ts`, op `fence-repair-uncommitted`, purge-exempt) with the exact `git add`/`git commit` step, dropped on read once the path is committed; db and mirror → a revision-bound `put_page` (mirror: database-only, hold cleared). Every write carries a `FenceRepairReceipt` (`receipt.ts`: actor `fence-repair`, tier, classes, rows, columns, model, before/after sha256, cost, and for a `merge_fences` repair `merged`: per merged fence and section the fence count and every before row as `{occurrence, from_fence, kept_as | duplicate_of}`, at most `MERGED_ROWS_MAX` rows, built by `mergedReceipt`; `parseFenceRepairReceipt` rejects anything malformed) and clears the census parts of the key. Tests: `test/repair-fences.test.ts`.
+- `src/core/fence-repair/{repair-io,receipt,uncommitted}.ts` — #6188 fence repair I/O. `loadFenceSource(engine, sourceId, { remote })`: managed owner root, or the `OwnerRefusal` row (`persistence/owner-refusal.ts`) that says why this host may not write it (a remote caller's row names no local path), legacy checkout, mirror flag, and the `RepairBusySet` (`persistence/repair-busy.ts`: in-flight writes plus the not-yet-admitted entries of every unfinished sync cursor, failing closed); an unfinished sync no longer marks the whole source busy. `writeFenceRepair` turns a `sync_in_progress` raised at the write's admission into `{ ok: false, reason: 'sync_in_progress' }`. `readFenceTarget`: a held or walked file from the checkout (UTF-8 only, confined, slug from the page by origin, hold or path) or the stored page; `spliceFileSections` puts the repaired sections back into the file by locating each changed line range with the fewest unique context lines and refuses unless the result parses back to exactly those sections. `writeFenceRepair`: managed → `submitManagedFileRepair` (bytes bound to the before-hash, page revision and publication digest; refused imports and canonical overlays are not written); legacy → confined path re-hashed (`changed_since_read`), backed up under `~/.gbrain/backups/fences/<run>/`, written, `importFromFile` (restored from the backup if it refuses), hold cleared, and an "uncommitted fence repair" notice (`uncommitted.ts`, op `fence-repair-uncommitted`, purge-exempt) with the exact `gbrain git commit-push` step (`legacyCommitStep`, built by `commitPushCommand` in `src/core/git/commit-push.ts`), dropped on read once the path is committed; db and mirror → a revision-bound `put_page` (mirror: database-only, hold cleared). Every write carries a `FenceRepairReceipt` (`receipt.ts`: actor `fence-repair`, tier, classes, rows, columns, model, before/after sha256, cost, and for a `merge_fences` repair `merged`: per merged fence and section the fence count and every before row as `{occurrence, from_fence, kept_as | duplicate_of}`, at most `MERGED_ROWS_MAX` rows, built by `mergedReceipt`; `parseFenceRepairReceipt` rejects anything malformed) and clears the census parts of the key. Tests: `test/repair-fences.test.ts`.
- `src/core/fence-repair/attempts.ts` — #6188 attempt claims and the attempt memo for paid (Tier 3) fence repairs, one `op_checkpoints` row per candidate (op `fence-repair-attempt`) changed only by compare-and-swap on a record version: `claimed` → `dispatched` → `settled` → `published` | `rejected` | `transient`, at most one paid call plus one corrective re-ask per claim. A rejected or published memo (content sha256, model, fence rules version, prompt version) is not claimed again until one changes; transient failures do not consume it; an expired lease is taken over (a stale dispatch counts a crash, two reject the memo). Records carry location and reason codes and their source incarnation, so the purge keeps them while it lives. Tests: `test/fence-repair-attempts.test.ts` (+ Postgres e2e).
- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a host that may not write the source is skipped with the owner condition as its reason (`host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`; `owner_unavailable` is the fallback; the skip's detail carries `why`, the read-only fix and `retryable`), a candidate a write in flight or an unfinished sync's frozen manifest still names is `sync_in_progress` (#6278: checked at plan, at apply and again at the write's admission in `file-repair.ts`; the rest of the source repairs while the sync runs, and a held path is not busy); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index b1f0693269..0ab1878a22 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -545,7 +545,7 @@ vars — incident-time escape hatches, not everyday knobs.
never holds it. The fence repair still repairs such a file: on a legacy
source it re-reads the file, backs it up under `~/.gbrain/backups/`,
writes and imports it, and leaves the change for you to commit
- (`gbrain sources status` names the `git add`/`git commit` command until
+ (`gbrain sources status` names the `gbrain git commit-push` command until
you do). Holds never count toward the
legacy auto-skip streak below. A source blocked by such a file before this
release recovers on its next sync, or now with
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 9ef6834267..36a7a550ee 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2885,8 +2885,8 @@ On a managed brain each file is one coordinated write (`managed_file_repair`):
the exact approved bytes, the import, and the hold clear commit together, and
the file is committed through the Git effect like any page write. On a legacy
brain the apply backs each file up under `~/.gbrain/backups/frontmatter/`,
-writes it, imports it, clears its hold and prints the `git add`/`git commit`
-step. Per-file outcomes report `written`, `imported`, `hold_cleared` and
+writes it, imports it, clears its hold and prints the `gbrain git commit-push`
+step that commits and pushes only that file. Per-file outcomes report `written`, `imported`, `hold_cleared` and
`committed`. Repair stays explicit-only: `gbrain repair --all` and
`gbrain doctor --remediate` never run it.
@@ -3066,7 +3066,7 @@ to the file's before-hash and page revision, committed through the Git effect);
a legacy (unmanaged) source by backing the file up under
`~/.gbrain/backups/fences/<run>/`, writing it, importing it and recording an
"uncommitted fence repair" notice that `gbrain sources status` and doctor show
-with the exact `git add`/`git commit` step until the path is committed; a
+with the exact `gbrain git commit-push` step until the path is committed; a
stored page with no file by a revision-bound page write; a read-only mirror in
the database only (the file is never written). Every write's receipt carries
the actor `fence-repair`, the tier, the classes, rows and columns, the model,
diff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.md
index 55674ebf8e..c3c79a738c 100644
--- a/docs/guides/shared-checkout-git.md
+++ b/docs/guides/shared-checkout-git.md
@@ -106,7 +106,9 @@ gbrain git commit-push --dry-run -m "people: add alice-example" -- people/alice-
```
Flags: `--path <dir>` acts on a checkout other than the one containing the
-current directory, `--json` prints one JSON result (or the error envelope),
+current directory (the paths are then relative to `<dir>`, like `git -C`),
+`-m` repeats like `git commit` (each one is a new paragraph, so a second `-m`
+carries a trailer), `--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.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 0b7960234c..ea58870118 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -595,9 +595,11 @@ and the same detail and fix). What works:
1. **Write the file, commit, sync** (the classic write path). Write or edit
`<checkout>/<slug>.md`, check generated frontmatter with
- `gbrain frontmatter validate --stdin --path <slug>.md`, `git commit` it, then
+ `gbrain frontmatter validate --stdin --path <slug>.md`, commit it with
+ `gbrain git commit-push --path <checkout> -m <msg> -- <slug>.md`, then
run `gbrain sync --source <id>`. Sync imports commits; `--working-tree`
- imports uncommitted edits for one run. Delete with `git rm`, commit, sync.
+ imports uncommitted edits for one run. Delete the file, commit the deletion
+ the same way, sync.
Tags and timeline entries are frontmatter and `## Timeline` lines in the
same file.
2. **Database-only pages**, if the user accepts that new pages never reach the
diff --git a/llms-full.txt b/llms-full.txt
index 9292698ef3..d1c5e1a848 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7395,7 +7395,7 @@ vars — incident-time escape hatches, not everyday knobs.
never holds it. The fence repair still repairs such a file: on a legacy
source it re-reads the file, backs it up under `~/.gbrain/backups/`,
writes and imports it, and leaves the change for you to commit
- (`gbrain sources status` names the `git add`/`git commit` command until
+ (`gbrain sources status` names the `gbrain git commit-push` command until
you do). Holds never count toward the
legacy auto-skip streak below. A source blocked by such a file before this
release recovers on its next sync, or now with
diff --git a/src/commands/doctor/checks/fence-integrity.ts b/src/commands/doctor/checks/fence-integrity.ts
index 11e307fbc4..39147364cf 100644
--- a/src/commands/doctor/checks/fence-integrity.ts
+++ b/src/commands/doctor/checks/fence-integrity.ts
@@ -203,7 +203,7 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutM
if (uncommitted.length) {
const bySource = [...new Set(uncommitted.map(n => n.source_id))];
sentences.push(`${uncommitted.length} fence repair(s) on legacy source(s) ${bySource.join(', ')} are written and imported but not committed; `
- + `gbrain sources status ${bySource[0]} prints each file's exact git add and git commit step (the backup of the original is kept).`);
+ + `gbrain sources status ${bySource[0]} prints each file's exact gbrain git commit-push step, which commits and pushes only that file (the backup of the original is kept).`);
}
if (partial.length) {
sentences.push(`PARTIAL CENSUS: the scan of ${partial.map(c => c.source_id).join(', ')} did not finish within ${timeoutMs / 1000}s, so more fences may be malformed; `
@@ -217,7 +217,7 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutM
: partial.length || (!unrenderable.total && !unrenderable.complete) ? agentFix(['gbrain', 'doctor', '--only', 'fence_integrity', '--json'], 'Resumes the fence census where the last scan stopped and reports what it found.', 'fence_integrity', { docs: DOCS })
: noisy.length ? agentFix(['gbrain', 'sources', 'status', noisy[0]!.source_id, '--json'], `Shows ${noisy[0]!.source_id}'s recent sync result, including fences_normalized with sample paths, so you can find what writes the malformed fences.`,
'fence_integrity', { docs: DOCS })
- : uncommitted.length ? agentFix(['gbrain', 'sources', 'status', uncommitted[0]!.source_id], 'Lists the uncommitted fence repairs of this legacy source with the exact git add and git commit step for each file.',
+ : uncommitted.length ? agentFix(['gbrain', 'sources', 'status', uncommitted[0]!.source_id], 'Lists the uncommitted fence repairs of this legacy source with the exact gbrain git commit-push step for each file.',
'fence_integrity', { docs: DOCS })
: unbound.length && !unrenderable.total ? agentFix(['gbrain', 'config', 'set', UNBOUND_WRITE_KEY, 'database_only'],
`Allows database-only writes to sources with a checkout but no canonical owner, so the next extract_facts run fences these rows into their database pages. It is brain-wide (every database-only page of such a source stays database-only after binding), so ask the user first.`,
diff --git a/src/commands/git.ts b/src/commands/git.ts
index 0043f26736..f86bb3bc13 100644
--- a/src/commands/git.ts
+++ b/src/commands/git.ts
@@ -11,6 +11,7 @@
* gbrain git commit-push --pending [--path <dir>] [-m <msg>]
* gbrain git guard [--install | --uninstall] [--path <dir>] [--json]
*/
+import { realpathSync } from 'node:fs';
import { commitAndPush, checkoutRoot, pullShared, scopePaths, COMMIT_LOCK_NAME, type Resolution } from '../core/git/commit-push.ts';
import { guardStatus, installGuard, uninstallGuard } from '../core/git/commit-guard.ts';
import { appendPushLog } from '../core/brain-repo-durability.ts';
@@ -37,7 +38,8 @@ move; the owner's next Git publish, or --push-only --keep-checkout, pushes it.
Flags:
--path <dir> Checkout to act on (default: the checkout containing the cwd).
- -m, --message <m> Commit message (required unless --push-only or --pull).
+ -m, --message <m> Commit message (required unless --push-only or --pull); repeat it, like git
+ commit, for more paragraphs (a second -m <trailer> is the body).
--push-only Publish commits already on the branch; commit nothing.
--branch <name> With --push-only: publish HEAD to this remote branch (one exact name).
--keep-checkout With --push-only: never move the checkout and skip its pre-push hook. The one
@@ -102,7 +104,7 @@ function parse(args: string[]): Parsed {
else if (a === '--install') p.install = true;
else if (a === '--uninstall') p.uninstall = true;
else if (a === '--path' || a.startsWith('--path=') || a === '--repo' || a.startsWith('--repo=')) p.path = take('--path');
- else if (a === '-m' || a === '--message' || a.startsWith('--message=')) p.message = take('--message');
+ else if (a === '-m' || a === '--message' || a.startsWith('--message=')) { const m = take('--message'); p.message = p.message === undefined ? m : `${p.message}\n\n${m}`; }
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');
@@ -142,7 +144,7 @@ export async function runGit(args: string[]): Promise<number> {
if (p.sub !== 'commit-push') throw opError('commit_paths_invalid', `Unknown subcommand: gbrain git ${p.sub}.`, HELP.split('\n')[0]);
if (p.install || p.uninstall) throw opError('commit_paths_invalid', '--install and --uninstall belong to gbrain git guard.', 'Run gbrain git guard --install.');
const repo = checkoutRoot(p.path ?? process.cwd());
- const cwd = p.path ? repo : process.cwd();
+ const cwd = p.path ? realpathSync(p.path) : process.cwd();
if ((p.pull && p.pushOnly) || (p.pull && (p.message || p.paths.length || p.resolve.length || p.branch))
|| (p.pushOnly && (p.message || p.paths.length)) || ((p.resolve.length || p.branch || p.expectRemote || p.keepCheckout) && !p.pushOnly)
|| (p.pending && (p.pull || p.pushOnly || p.paths.length)) || (p.allowOutside && p.pull)) {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index ec83bdc3d2..2acfb123ac 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1237,6 +1237,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.433.0', text: 'Hermes transcript import keeps the answers a user gave in a `clarify` form (answered responses of a submitted form, or the answers a timed-out form had already locked) as user turns, each after its question as the assistant\'s turn. A Hermes session imported before re-renders on its next import scan when it holds such answers, which can run fact extraction for that page again (#7396).' },
{ since: '0.60.433.0', text: 'Fact subject inference links more facts and fewer wrong ones: a currency code next to an amount (`CHF 80`) and a record label opening a sentence (`Invoice ...`, `Work session ...`) no longer block a fact that names one person or company, and an entity introduced only as an example (`including X notes`, `for example, X`) is never chosen as the subject. A page named like the code or label still competes. A sentence that opens with `For example, X ...` no longer takes X as its subject (#7405).' },
{ since: '0.60.433.0', text: '`gbrain think` gives reasoning models from gpt-5 on 16,000 output tokens behind any provider or router prefix, as it already did for gpt-5 and the o-series on their own provider; gpt-6 ids get it too. Before, those got 4,000 and long answers came back truncated (`LLM_OUTPUT_TRUNCATED`). Providers bill the tokens used, not the cap (#7421).' },
+ { since: 'TBD', text: '`gbrain git commit-push` takes `-m` more than once, like `git commit`: each `-m` is a new paragraph of the message (a second `-m` carries a trailer). With `--path <dir>` below the checkout top, the paths after `--` are now relative to `<dir>` (like `git -C`), as its help said; they used to be read relative to the checkout top. The commit step that `gbrain repair frontmatter`, `gbrain repair content`, `gbrain repair file-drift` and the legacy fence repair (`gbrain sources status`, doctor `fence_integrity`) print for a legacy source is now `gbrain git commit-push --path <root> -m <subject> [-m <trailer>] -- <paths>`, which takes the writer lock, commits only those paths, merges remote commits and pushes, instead of a bare `git add` plus `git commit` (the frontmatter step named no paths on its commit, so it also committed anything else staged). A checkout with no remote refuses it (`git_unavailable`) and keeps the files uncommitted.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/fence-repair/uncommitted.ts b/src/core/fence-repair/uncommitted.ts
index 6e5d5f1568..886e24e57f 100644
--- a/src/core/fence-repair/uncommitted.ts
+++ b/src/core/fence-repair/uncommitted.ts
@@ -2,7 +2,7 @@
* #6188 (T2): "uncommitted fence repair" notices. A legacy (unmanaged)
* source has no Git effect, so when the fence repair rewrites one of its
* files it backs the file up, imports it, and records a notice here naming
- * the path, the backup and the exact `git add` / `git commit` step. The
+ * the path, the backup and the exact `gbrain git commit-push` step. The
* notice stays until that path is committed: every read checks
* `git status --porcelain -- <path>` and drops the notices whose path is
* clean. `gbrain sources status` and doctor `fence_integrity` show them.
@@ -15,7 +15,7 @@
import { execFileSync } from '../spawn.ts';
import { existsSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
-import { shellQuote } from '../agent-output.ts';
+import { commitPushCommand } from '../git/commit-push.ts';
import type { FenceRepairReceipt } from './receipt.ts';
import { fenceRepairCommitSubject } from './receipt.ts';
import { gitChildEnv } from '../git-env.ts';
@@ -38,9 +38,9 @@ export interface UncommittedFenceRepair {
const fingerprint = (sourceId: string, incarnation: string, path: string) => `${sourceId}:${incarnation}:${path}`;
-/** The commit step printed for a legacy repair: stage only this path and commit it with the fence-repair subject and the `gbrain-repair:` trailer the Git effect would write. */
+/** The commit step printed for a legacy repair: commit and push only this path with the fence-repair subject and the `gbrain-repair:` trailer the Git effect would write. */
export function legacyCommitStep(root: string, path: string, classes: readonly string[], tier: FenceRepairReceipt['tier'] = 'deterministic'): string {
- return `git -C ${shellQuote([root])} add -- ${shellQuote([path])} && git -C ${shellQuote([root])} commit -m ${shellQuote([fenceRepairCommitSubject(path, classes)])} -m ${shellQuote([`gbrain-repair: invalid_fence ${tier} high`])} -- ${shellQuote([path])}`;
+ return commitPushCommand(root, [path], [fenceRepairCommitSubject(path, classes), `gbrain-repair: invalid_fence ${tier} high`]);
}
export async function recordUncommittedFenceRepair(engine: Exec, notice: UncommittedFenceRepair): Promise<void> {
diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.ts
index 9cae295052..eda1bade0e 100644
--- a/src/core/git/commit-push.ts
+++ b/src/core/git/commit-push.ts
@@ -34,6 +34,7 @@ import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, durableSsrfFlags } fr
import { assertManagedFilesystemWrite, hasFilesystemPublication, managedFilesystemRootFor, type ManagedFilesystemRoot } from '../persistence/filesystem-guard.ts';
import { acquireNativeLock, acquireNativeLockSync, type NativeLockSyncHandle } from '../persistence/native-lock.ts';
import { OperationError, opError } from '../ops/contract.ts';
+import { shellQuote } from '../agent-output.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. */
@@ -184,6 +185,11 @@ function absGitPath(root: string, rel: string): string {
}
/** The checkout's toplevel; throws `commit_paths_invalid` outside a work tree. */
+/** The operator step that commits and pushes only `paths` (relative to `root`) with one -m per message paragraph: the fix text doctor and repair print instead of a bare git add/commit. */
+export function commitPushCommand(root: string, paths: readonly string[], messages: readonly string[]): string {
+ return shellQuote(['gbrain', 'git', 'commit-push', '--path', root, ...messages.flatMap(m => ['-m', m]), '--', ...paths]);
+}
+
export function checkoutRoot(dir: string): string {
const r = git(dir, ['rev-parse', '--show-toplevel']);
if (r.code !== 0 || !r.stdout.trim()) {
diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.ts
index bd2b517ec0..7b5fc1749e 100644
--- a/src/core/repair/file-drift.ts
+++ b/src/core/repair/file-drift.ts
@@ -63,6 +63,7 @@ import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import { validateSlug } from '../utils.ts';
import { matchesRepairPath } from './path-glob.ts';
import { shellQuote } from '../agent-output.ts';
+import { commitPushCommand } from '../git/commit-push.ts';
import type { ParsedPage } from '../import-file.ts';
import { digest, stableJson } from '../persistence/digest.ts';
import { currentVerifiedLocalWriter, readLocalWriter, withVerifiedLocalRegistration } from '../persistence/identity.ts';
@@ -802,8 +803,8 @@ export const fileDriftRepair: RepairHandler = {
const binding = await getWorktreeBinding(engine, sourceId);
const root = join(binding!.local_path!, binding!.relative_path);
if (!(await gitDurabilityPolicy(binding, root).catch(() => ({ durable: false }))).durable) {
- if (removed.length) warnings.unshift(`The next sync undoes this repair unless the removals are committed: Git durability is off for ${sourceId}, so the apply leaves each removed file's deletion uncommitted (${removed.length} file(s)) and the next sync holds the committed file again. Commit them right after the apply: git -C ${root} add -- ${removed.join(' ')} && git -C ${root} commit`);
- if (recreated.length) warnings.unshift(`The next sync undoes this repair unless the recreated files are committed: Git durability is off for ${sourceId}, so the apply leaves each recreated file uncommitted (${recreated.length} file(s)) and the next sync imports their committed deletion again. Commit them right after the apply: git -C ${root} add -- ${recreated.join(' ')} && git -C ${root} commit`);
+ if (removed.length) warnings.unshift(`The next sync undoes this repair unless the removals are committed: Git durability is off for ${sourceId}, so the apply leaves each removed file's deletion uncommitted (${removed.length} file(s)) and the next sync holds the committed file again. Commit them right after the apply: ${commitPushCommand(root, removed, [`gbrain: repair file drift in ${sourceId}`])}`);
+ if (recreated.length) warnings.unshift(`The next sync undoes this repair unless the recreated files are committed: Git durability is off for ${sourceId}, so the apply leaves each recreated file uncommitted (${recreated.length} file(s)) and the next sync imports their committed deletion again. Commit them right after the apply: ${commitPushCommand(root, recreated, [`gbrain: repair file drift in ${sourceId}`])}`);
undoneBySync = { recreated: recreated.length, removed: removed.length };
}
}
diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.ts
index 07ba523c17..bacda3a290 100644
--- a/src/core/repair/frontmatter.ts
+++ b/src/core/repair/frontmatter.ts
@@ -64,6 +64,7 @@ import { materializedSnapshot, segmentedOverCeiling } from '../persistence/segme
import { pageBodyOverCeilingError } from '../page-body/page-shape.ts';
import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';
import { gitChildEnv } from '../git-env.ts';
+import { commitPushCommand } from '../git/commit-push.ts';
import { bindOrigin, originConflictMessage, pickCanonicalOrigin } from '../persistence/origin-guard.ts';
type Mode = 'managed' | 'legacy';
@@ -583,5 +584,5 @@ async function applyRepair(ctx: OperationContext, repair: ApprovedRepair, select
'SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [repair.source_id]))[0]!.incarnation, path: repair.path, observedAt: new Date().toISOString() });
return { applied: ok, outcome: ok ? 'repaired' : 'import_refused', ...(ok ? {} : { reason: imported.error ?? 'the import refused the repaired file' }),
detail: { path: repair.path, written: repair.before !== repair.after, ...(backup ? { backup } : {}), imported: imported.status, hold_cleared: holdCleared,
- committed: 'commit_step', commit_step: `git -C ${shellQuote([root])} add -- ${shellQuote([repair.path])} && git -C ${shellQuote([root])} commit -m ${shellQuote([`fix(frontmatter): repair ${repair.path}`])}` } };
+ committed: 'commit_step', commit_step: commitPushCommand(root, [repair.path], [`fix(frontmatter): repair ${repair.path}`]) } };
}
diff --git a/src/core/repair/slug-conflicts.ts b/src/core/repair/slug-conflicts.ts
index 93a7e39f88..09654ded2e 100644
--- a/src/core/repair/slug-conflicts.ts
+++ b/src/core/repair/slug-conflicts.ts
@@ -85,6 +85,7 @@ import { CONTENT_REPAIR_LANE_VERSION, contentRepairLaneCurrent } from '../persis
import { lineDiff } from './frontmatter.ts';
import { repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairPlanOptions, type RepairResult, type RepairScope } from './core.ts';
import { gitChildEnv } from '../git-env.ts';
+import { commitPushCommand } from '../git/commit-push.ts';
import { recordSlugLineAlias } from '../page-state/rename-alias.ts';
import { canonicalOriginPage, originConflictMessage } from '../persistence/origin-guard.ts';
@@ -686,7 +687,7 @@ async function write(ctx: OperationContext, src: FenceSource, cand: Candidate, a
const holdCleared = cand.hold ? await kept(await clearGitHold(engine, { sourceId: src.id, incarnation: src.incarnation, path: cand.path, observedAt: observedAt ?? new Date().toISOString() })) : false;
if (parts.declared_alias) await recordSlugLineAlias(engine, src.id, parts.declared_alias, cand.slug);
if (!edits) return { applied: true, outcome: 'repaired', detail: { ...detail, mode: 'legacy', imported: imported.status, hold_cleared: holdCleared, content_repair: receipt }, ...spend };
- const commitStep = `git -C ${shellQuote([root])} add -- ${shellQuote([cand.path])} && git -C ${shellQuote([root])} commit -m ${shellQuote([contentRepairCommitSubject(cand.path)])} -m ${shellQuote([contentRepairTrailer(receipt)])} -- ${shellQuote([cand.path])}`;
+ const commitStep = commitPushCommand(root, [cand.path], [contentRepairCommitSubject(cand.path), contentRepairTrailer(receipt)]);
return { applied: true, outcome: 'repaired', detail: { ...detail, mode: 'legacy', backup, imported: imported.status, hold_cleared: holdCleared, content_repair: receipt, committed: 'commit_step', commit_step: commitStep }, ...spend };
}
diff --git a/src/core/schema-pack/lint-rules.ts b/src/core/schema-pack/lint-rules.ts
index 044257ebb9..f5cd412246 100644
--- a/src/core/schema-pack/lint-rules.ts
+++ b/src/core/schema-pack/lint-rules.ts
@@ -361,7 +361,7 @@ export const mutationCountAnomaly: LintRule = (manifest, opts) => {
severity: 'warning',
message: `pack '${manifest.name}' has ${forPack.length} mutations in the last ${daysBack} days; consider committing pack.json to source control`,
pack: manifest.name,
- hint: `cd to your brain repo, git add the pack file, commit + push so the changes survive across machines`,
+ hint: `commit and push the pack file from your brain repo (gbrain git commit-push --path <brain repo> -m <msg> -- <pack file>) so the changes survive across machines`,
});
}
} catch {
diff --git a/test/git-commit-push-6530.serial.test.ts b/test/git-commit-push-6530.serial.test.ts
index 9b578af9b8..1d0d3f2cd2 100644
--- a/test/git-commit-push-6530.serial.test.ts
+++ b/test/git-commit-push-6530.serial.test.ts
@@ -11,6 +11,9 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { acquireCommitLock, commitAndPush, commitPathsLocked, pullShared, readIntegrateConflict, readPendingWriteThrough } from '../src/core/git/commit-push.ts';
import { getLastPushOutcome } from '../src/core/brain-repo-durability.ts';
+import { runGit } from '../src/commands/git.ts';
+import { argvFromCommand } from '../src/core/agent-output.ts';
+import { legacyCommitStep } from '../src/core/fence-repair/uncommitted.ts';
let root: string;
@@ -484,3 +487,49 @@ describe('many writers, two clones, one remote', () => {
}
}, 180_000);
});
+
+describe('CLI: repeated -m, --path <subdir>, and the printed repair step', () => {
+ /** A checkout whose source root is the subdirectory brain/, cloned from a bare remote. */
+ function subdirSetup(): { bare: string; a: string; brain: string } {
+ const { bare, a } = setup();
+ mkdirSync(join(a, 'brain', 'notes'), { recursive: true });
+ for (const f of ['model.md', 'other.md']) writeFileSync(join(a, 'brain', 'notes', f), `${f} v1\n`);
+ git(a, 'add', 'brain'); git(a, 'commit', '-qm', 'brain'); git(a, 'push', '-q', 'origin', 'main');
+ return { bare, a, brain: join(a, 'brain') };
+ }
+
+ test('each -m is a new paragraph of the commit message, like git commit', async () => {
+ const { bare, a } = setup();
+ writeFileSync(join(a, 'x.md'), 'mine\n');
+ expect(await runGit(['commit-push', '--path', a, '-m', 'subject line', '-m', 'trailer-key: value', '--', 'x.md'])).toBe(0);
+ expect(git(bare, 'log', '-1', '--format=%B', 'main').startsWith('subject line\n\ntrailer-key: value')).toBe(true);
+ expect(git(bare, 'log', '-1', '--format=%(trailers:key=trailer-key,valueonly)', 'main')).toBe('value');
+ });
+
+ test('--path <subdir>: paths are relative to that directory (like git -C), not the checkout top', async () => {
+ const { bare, a, brain } = subdirSetup();
+ writeFileSync(join(brain, 'notes', 'model.md'), 'edited\n');
+ expect(await runGit(['commit-push', '--path', brain, '-m', 'edit model', '--', 'notes/model.md'])).toBe(0);
+ expect(git(bare, 'show', 'main:brain/notes/model.md')).toBe('edited');
+ expect(git(bare, 'log', '-1', '--format=%s', 'main')).toBe('edit model');
+ expect(status(a)).toBe('');
+ });
+
+ test('the legacy fence-repair commit step runs as printed: only that path, subject and trailer, on the remote', async () => {
+ const { bare, a, brain } = subdirSetup();
+ writeFileSync(join(brain, 'notes', 'model.md'), 'repaired\n');
+ writeFileSync(join(brain, 'notes', 'other.md'), 'another writer\n');
+ const step = legacyCommitStep(brain, 'notes/model.md', ['no_header'], 'llm');
+ expect(step).toBe(`gbrain git commit-push --path ${brain} -m 'gbrain: repair fence in notes/model.md (no_header)' -m 'gbrain-repair: invalid_fence llm high' -- notes/model.md`);
+ const argv = argvFromCommand(step)!;
+ expect(argv.slice(0, 2)).toEqual(['gbrain', 'git']);
+ expect(await runGit(argv.slice(2))).toBe(0);
+ expect(git(bare, 'log', '-1', '--format=%B', 'main').startsWith('gbrain: repair fence in notes/model.md (no_header)\n\ngbrain-repair: invalid_fence llm high')).toBe(true);
+ expect(git(bare, 'log', '-1', '--format=%(trailers:key=gbrain-repair,valueonly)', 'main')).toBe('invalid_fence llm high');
+ expect(git(bare, 'show', '--name-only', '--format=', 'main')).toBe('brain/notes/model.md');
+ expect(git(bare, 'show', 'main:brain/notes/model.md')).toBe('repaired');
+ expect(git(bare, 'show', 'main:brain/notes/other.md')).toBe('other.md v1');
+ expect(remoteHead(bare)).toBe(git(a, 'rev-parse', 'HEAD'));
+ expect(status(a)).toBe(' M brain/notes/other.md');
+ });
+});
diff --git a/test/repair-fences.test.ts b/test/repair-fences.test.ts
index e730feb369..a583aa73ef 100644
--- a/test/repair-fences.test.ts
+++ b/test/repair-fences.test.ts
@@ -52,6 +52,8 @@ import { runFenceRepairPhase } from '../src/core/cycle/fence-repair.ts';
import { fenceIntegrityResult } from '../src/commands/doctor/checks/fence-integrity.ts';
import { fencesRepair, type FencesPreviewDetails } from '../src/core/repair/fences.ts';
import { readUncommittedFenceRepairs } from '../src/core/fence-repair/uncommitted.ts';
+import { runGit } from '../src/commands/git.ts';
+import { argvFromCommand } from '../src/core/agent-output.ts';
import { fenceHoldStatus } from '../src/core/fence-repair/hold-fix.ts';
import { parseRepairArgs, runRepairCommand } from '../src/commands/repair.ts';
import { runModels } from '../src/commands/models.ts';
@@ -507,9 +509,17 @@ test('legacy sources: backup, import and an uncommitted-repair notice that clear
expect(doctor).toMatchObject({ status: 'warn', details: { uncommitted_repairs: 2 } });
expect(doctor.message).toContain('written and imported but not committed');
const step = notices.find(n => n.path === 'notes/model.md')!.commit_step;
- expect(step).toContain("commit -m 'gbrain: repair fence in notes/model.md (no_header)'");
- execFileSync('bash', ['-c', step]);
+ expect(step).toBe(`gbrain git commit-push --path ${r.root} -m 'gbrain: repair fence in notes/model.md (no_header)' -m 'gbrain-repair: invalid_fence llm high' -- notes/model.md`);
+ expect(doctor.message).toContain('gbrain git commit-push step');
+ const bare = join(home, `${r.id}.git`);
+ execFileSync('git', ['init', '-q', '--bare', bare]);
+ git(r.root, 'remote', 'add', 'origin', bare);
+ git(r.root, 'push', '-q', '-u', 'origin', 'HEAD');
+ expect(await withEnv({ GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1' }, () => runGit(argvFromCommand(step)!.slice(2)))).toBe(0);
expect(git(r.root, 'log', '-1', '--format=%s')).toBe('gbrain: repair fence in notes/model.md (no_header)');
+ expect(git(r.root, 'log', '-1', '--format=%(trailers:key=gbrain-repair,valueonly)')).toBe('invalid_fence llm high');
+ expect(git(r.root, 'show', '--name-only', '--format=', 'HEAD')).toBe('notes/model.md');
+ expect(git(bare, 'rev-parse', 'HEAD')).toBe(git(r.root, 'rev-parse', 'HEAD'));
expect((await readUncommittedFenceRepairs(engine, [r.id])).map(n => n.path)).toEqual(['notes/later.md']);
expect((await fenceIntegrityResult(engine, { sourceIds: [r.id] })).details).toMatchObject({ uncommitted_repairs: 1 });
expect(readFileSync(join(home, `${r.id}-target.md`), 'utf8')).toBe(md('Target', noHeader('Linked claim')));
diff --git a/test/repair-file-drift-held-window-gbra133.test.ts b/test/repair-file-drift-held-window-gbra133.test.ts
index d51c2747ba..53fa77cced 100644
--- a/test/repair-file-drift-held-window-gbra133.test.ts
+++ b/test/repair-file-drift-held-window-gbra133.test.ts
@@ -153,6 +153,7 @@ for (const backend of testBackends()) describe(`GBRA-133: a held file-drift prev
const hash = preview.preview_hash!;
// Git durability is off in this fixture: the preview leads with what the next sync does to an uncommitted recreate.
expect(preview.warnings![0]).toStartWith('The next sync undoes this repair unless the recreated files are committed');
+ expect(preview.warnings![0]).toEndWith(`Commit them right after the apply: gbrain git commit-push --path ${f.root} -m 'gbrain: repair file drift in ${f.sourceId}' -- ${slugs.map(slug => `${slug}.md`).join(' ')}`);
expect(preview.details).toMatchObject({ undone_by_next_sync_unless_committed: { recreated: 3, removed: 0 } });
const command = `gbrain repair file-drift --source ${f.sourceId}`;
const first = readArtifact(hash, command);
diff --git a/test/repair-frontmatter.test.ts b/test/repair-frontmatter.test.ts
index ccecc18f57..8d776f8b86 100644
--- a/test/repair-frontmatter.test.ts
+++ b/test/repair-frontmatter.test.ts
@@ -392,7 +392,7 @@ test('legacy brain: the apply backs the file up, writes it, imports it, clears i
expect((await engine.getPage('notes/post', { sourceId: id }))?.title).toBe('alice-example post 4\nsecond line of post 4');
const detail = applied.outcome_items!.find(o => o.detail?.path === 'notes/roundup.md')!.detail!;
expect(detail).toMatchObject({ path: 'notes/roundup.md', written: true, imported: 'imported', committed: 'commit_step' });
- expect(String(detail.commit_step)).toContain(`git -C ${root} add -- notes/roundup.md`);
+ expect(detail.commit_step).toBe(`gbrain git commit-push --path ${root} -m 'fix(frontmatter): repair notes/roundup.md' -- notes/roundup.md`);
expect(readFileSync(String(detail.backup), 'utf8')).toBe(QUOTABLE);
expect(s.read('notes/roundup.md')).toContain('author: "alice-example');
expect((await engine.getPage('notes/roundup', { sourceId: id }))?.frontmatter.author).toBe('alice-example (citing acme-example) (original: https://example.invalid/a)');