Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(q1): managed checkout path-only commit-push, diverged reconcile fix, checkout state in writer status and doctor
garrytan682fceaba95e
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex fcc14e8bd3..da598cc42c 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -40,3 +40,4 @@ The #6188 fence check and fence repair live in [fence repair](core-fence-repair.- Foreground priority (#5984 Phase 4.5, `foreground_priority` switch, `journal.ts`): `claimableWriteSql` lets a non-sync request pass earlier queued sync rows of its root that have not started and do not name its page (slug, page id or `intent.renameFrom.slug`), claims it first, and holds a passed sync row while that request runs; `claimNextLaneHead` starts no lane head while such a request is unfinished, except one head per foreground commit since the run's last head claim (`seen_sequence`). A consumer whose claimed write passed sync rows (`passed_sync`) claims plain FIFO on that root after it commits (`owesSyncTurn`), so a stream of writes cannot starve the drain. The sync side's pauses (no admit-ahead for 60 s after a write, no group while one is queued, the 25-page credit wait) apply only with the switch off. Receipt health judges a claimed write only against earlier started writes. Pinned by `test/managed-sync-foreground-priority.test.ts` (two processes) and `test/persistence-diagnostics.test.ts`.- `src/core/postgres-engine/reserved-transactions.ts` with `isPersistenceDeclaration` (`src/core/persistence/protocol.ts`) — BEGIN pipelining. `isPersistenceDeclaration` (GBRA-156) accepts exactly the `protocol.ts` declarations (transaction-local `set_config` calls and the brain row FOR SHARE). Admission, the FIFO claim, the effect claims and source guards, the receipt true-up, the single publication (`coordinator.ts`) and the consumer's lent lane transactions (`consumer.ts` `onLane`, through `reservedTransactions`) pass it as `TransactionOptions.pipelineFirst`, so behind a transaction-mode pooler the declaration goes out with BEGIN (one round trip less per transaction) while every later statement still waits for BEGIN's answer; if BEGIN fails, only the declaration has run, in autocommit, where it changes nothing. A reserved transaction gates every statement its body can reach, savepoint and nested-transaction bodies and `file()` included. A sync lane group's publication passes none: its begun mark must follow BEGIN's answer (`sync-lanes.ts` `awaitLaneBegin`). Tests: `test/persistence-pipeline-first.test.ts` (the predicate and the reviewed call sites), `test/e2e/pgbouncer-transaction-pipeline-6930.test.ts`.+- `src/core/persistence/checkout-state.ts` (`readCheckoutState`) — Q1: a canonical checkout against its last fetched upstream, read-only and time-bounded (no fetch): ahead/behind, `diverged`, each commit the upstream lacks (sha, author, date, subject, paths; at most 20) and porcelain counts. `sources writer status` reports it as `checkouts`; doctor `git_convergence` adds the commits and counts for a managed checkout and warns at once on a diverged one.diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.mdindex b42290d3a1..3c1590e20b 100644--- a/docs/architecture/topologies.md+++ b/docs/architecture/topologies.md@@ -822,10 +822,12 @@ or rebases the checkout.<a id="files-that-are-not-pages"></a>**Files that are not pages.** The owner'sGit effect commits only the page paths it wrote (`git commit --only`) and thenpushes 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 <!-- 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+`AGENTS.md`, scripts) is the operator's: commit it with+`gbrain git commit-push -m "<msg>" -- <paths>`, which commits only those paths+under the checkout's commit lock (`committed_local`) and never fetches, pushes+or moves the checkout. Those commits reach the remote on the owner's next+push, because the owner pushes HEAD, or sooner with+`gbrain git commit-push --push-only --keep-checkout` from the checkout; `gbrain sources push` refuses on a managed root and its secret scandoes not run on a hand push. A hand push and the owner's push race only byordinary Git semantics (both push the same HEAD; a push the remote rejects isretried by the owner and, after repeated failures, parked, whichdiff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.mdindex ddabf5284c..55674ebf8e 100644--- a/docs/guides/shared-checkout-git.md+++ b/docs/guides/shared-checkout-git.md@@ -116,10 +116,17 @@ 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).+In a managed canonical worktree (`gbrain sources writer git-durability`) its+persistence owner is the only Git publisher. Save pages with `put_page`,+`edit_page`, `remember` or `capture`. For files written there outside gbrain+(see [files that are not pages](../architecture/topologies.md#files-that-are-not-pages)),+`gbrain git commit-push -m "<msg>" -- <paths>` commits only the named paths+under the checkout's commit lock and reports `committed_local`: it never+fetches, merges, pushes or moves the checkout, and refuses `--pending`,+`--branch`, `--resolve` and `--allow-outside-source-root` there+(`commit_paths_invalid`). The commit reaches the remote on the owner's next Git+publish. `--push-only` without `--keep-checkout` is still refused with+`writer_coordinator_required`.The one form a managed worktree accepts is `--push-only --keep-checkout`. Itpublishes the commits already on the branch, merging a moved remote in memory,diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 8ea8292c74..0b7960234c 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -516,7 +516,7 @@ this anchor (`--json` puts them in one object on stdout); the command exits 1.| <a id="refresh_no_upstream"></a>`refresh_no_upstream` | `refresh_no_upstream` | The checkout's branch tracks no upstream, HEAD is detached, or the checkout is not a Git checkout at all (gbrain never initializes Git on its own), so there is nothing to fast-forward to. | `git -C <checkout> branch --set-upstream-to <remote>/<branch>` (the fix fills in the real values), then retry. A checkout that is not Git has nothing to refresh; making it a clone with an upstream is the user's call. || <a id="fetch_failed"></a>`fetch_failed` | `fetch_failed` | `git fetch` failed or did not finish within `sources.refresh_fetch_timeout_ms` (default 120000; `GBRAIN_REFRESH_FETCH_TIMEOUT_MS`; `--fetch-timeout-ms` wins over both). Nothing changed and no refresh record was written. | Retry. For a slow remote, raise the bound with `--fetch-timeout-ms <ms>` or `gbrain config set sources.refresh_fetch_timeout_ms <ms>`. Credentials are the user's: ask them to fix authentication rather than changing the remote. || <a id="refresh_git_unavailable"></a>`git_unavailable` | `git_unavailable` | A git command that reads the checkout's branch or remote (`symbolic-ref`, `remote`, `config --get branch.<branch>.remote` or `.merge`) failed or did not finish, so the checkout's state is unknown. The message names the command and git's first error line. A detached HEAD or an unset key is not this refusal. Nothing changed and no refresh record was written. | Run `git -C <checkout> status` to see why git cannot read the checkout, repair what it reports, then retry `gbrain sources refresh <source>`. |-| <a id="refresh_diverged"></a>`refresh_diverged` | `refresh_diverged` | The checkout has commits its upstream lacks, so a fast-forward is impossible. Nothing changed. | Reconcile the histories and push from a clone that is not managed, then retry. `gbrain sources reclone <source>` replaces the checkout; ask the user first, because local commits are dropped. |+| <a id="refresh_diverged"></a>`refresh_diverged` | `refresh_diverged` | The checkout has commits its upstream lacks, so a fast-forward is impossible. Nothing changed. | Ask the user, then publish the local commits merged with the upstream: `gbrain git commit-push --push-only --keep-checkout --path <checkout>` merges in memory, pushes the merge, refuses on a conflicting file and never moves the checkout (the refusal's fix fills in the real path and counts the local commits). Then retry `gbrain sources refresh <source>`, which fast-forwards to the merge. `gbrain sources reclone <source>` replaces the checkout instead and drops the local commits. || <a id="refresh_dirty"></a>`refresh_dirty` | `refresh_dirty` | Uncommitted or untracked files overlap the incoming upstream changes (the first 20 are named), or `git merge --ff-only` refused for the same reason. HEAD did not move. Uncommitted files outside the incoming changes do not refuse; they are kept and listed as `preserved_uncommitted`. | Commit or discard the named paths, then retry. Check `gbrain sources writer status <source> --json` first: a pending Git effect may be about to commit a gbrain-published file. || <a id="sync_in_progress"></a>`sync_in_progress` | `sync_in_progress` | A managed sync of one of the checkout's sources has an unfinished cursor. Moving the checkout now would strand it, and the refresh never waits on a sync. `gbrain repair frontmatter --apply` refuses the same way while an unfinished cursor still names a selected file. | Run the printed `gbrain sync --source <source> --no-pull ...` resume command (it keeps the cursor's options), then retry (for a repair, preview again and approve the new hash). || <a id="refresh_in_progress"></a>`refresh_in_progress` | `refresh_in_progress` | Another refresh of the same checkout is active, or a command that changes which sources share the checkout (`sources add`, `remove`, `archive`, `restore`, `reclone`) ran while one was active. | `gbrain sources refresh <source> --resume`, then retry the source command with the same request ID. |diff --git a/src/commands/doctor/checks/git-convergence.ts b/src/commands/doctor/checks/git-convergence.tsindex c7191e8395..32e0862a72 100644--- a/src/commands/doctor/checks/git-convergence.ts+++ b/src/commands/doctor/checks/git-convergence.ts@@ -35,6 +35,7 @@ import { existingLocalHostId } from '../../../core/persistence/identity.ts';import { gitDurabilityPolicy } from '../../../core/persistence/git-durability-policy.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';import { doctorVerify } from '../check-fix.ts';+import { readPorcelain, readUnpushedCommits, type CheckoutCommit, type CheckoutPorcelain } from '../../../core/persistence/checkout-state.ts';import { boundUnknownDetails } from '../bounded-unknown.ts';export const GIT_CONVERGENCE_WARN_MS = 6 * 3_600_000;@@ -44,7 +45,8 @@ const MAX_ROOTS = 50;const MAX_DIRTY_PATHS = 200;interface RootReport { root: string; source_ids: string[]; branch: string | null; ahead: number; behind: number; dirty: number;- oldest_unpushed_at: string | null; oldest_dirty_at: string | null; status: 'ok' | 'warn' | 'fail'; stranded?: true; uncommitted_pages?: string[] }+ oldest_unpushed_at: string | null; oldest_dirty_at: string | null; status: 'ok' | 'warn' | 'fail'; stranded?: true; uncommitted_pages?: string[];+ managed?: true; diverged?: true; unpushed_commits?: CheckoutCommit[]; porcelain?: CheckoutPorcelain }const canonicalPath = (path: string) => { try { return realpathSync(path); } catch { return path; } };@@ -147,6 +149,15 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())}const reports = [...byTop.values()].filter((r): r is RootReport => !('skipped' in r));const unwatched = reports.some(r => r.ahead > 0 || tracked.has(r.root)) ? await unwatchedDurableRoots(engine) : new Map<string, string[]>();+ // Q1 (shape A): on a managed canonical checkout, name each commit the upstream lacks and break the porcelain down; a+ // diverged one blocks gbrain sources refresh (refresh_diverged), so it warns at once.+ for (const report of reports) {+ if (!isManagedFilesystemPath(report.root)) continue;+ report.managed = true;+ if (report.ahead) report.unpushed_commits = readUnpushedCommits(report.root);+ if (report.dirty) report.porcelain = readPorcelain(report.root);+ if (report.ahead && report.behind) { report.diverged = true; if (report.status === 'ok') report.status = 'warn'; }+ }for (const report of reports) {const prefixes = unwatched.get(canonicalPath(report.root));if (!prefixes) continue;@@ -174,7 +185,9 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())const boundNote = bound ? ` Not every checkout was read: ${bound.note}.` : '';if (bound) Object.assign(details, { exact: false, limit: bound.details.limit, timed_out: bound.details.timed_out });const lines = bad.map(r => `${r.root}${r.source_ids.length ? ` (${r.source_ids.join(', ')})` : ''}: `- + [r.ahead ? `${r.ahead} commit(s) not on the upstream since ${r.oldest_unpushed_at}` : '', r.dirty && r.oldest_dirty_at ? `${r.dirty} uncommitted change(s), oldest from ${r.oldest_dirty_at}` : '']+ + [r.ahead ? `${r.ahead} commit(s) not on the upstream since ${r.oldest_unpushed_at}` : '', r.diverged ? `diverged (${r.behind} upstream commit(s) not in HEAD)` : '',+ r.unpushed_commits?.length ? `newest ${r.unpushed_commits[0]!.sha.slice(0, 7)} by ${r.unpushed_commits[0]!.author} at ${r.unpushed_commits[0]!.date} (${r.unpushed_commits[0]!.paths.slice(0, 3).join(', ') || 'no files'})` : '',+ r.dirty && r.oldest_dirty_at ? `${r.dirty} uncommitted change(s), oldest from ${r.oldest_dirty_at}` : ''].filter(Boolean).join('; '));// #5808 (#5606 residue): a managed canonical worktree has no bulk push; its owner pushes page writes and the operator pushes the rest.const remedy = bad.some(r => isManagedFilesystemPath(r.root))@@ -202,6 +215,15 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())why: `${first.root} has ${first.ahead} commit(s) not on its upstream and no Git effect left to push them (#7089); this publishes the commits already on the branch and commits nothing. A conflict with the remote is reported with the user's choice as its fix.${stranded.length > 1 ? ` ${stranded.length - 1} other checkout(s) need the same, see details.roots (stranded).` : ''}`,verify: doctorVerify('git_convergence') } };}+ const diverged = bad.find(r => r.diverged);+ if (diverged) {+ return { name: 'git_convergence', status, details,+ message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. ${diverged.root} is a managed checkout that diverged from its upstream, so gbrain sources refresh refuses (refresh_diverged) until its local commits are published merged with the upstream; details.roots lists each one (sha, author, date, paths). ${remedy}; this compares with the last fetched upstream and does not fetch.${boundNote}`,+ fix: { ask_user: true, argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', diverged.root, '--json'], consent: [], actor: 'user', requires_exclusive: false,+ why: `${diverged.root} holds ${diverged.ahead} commit(s) its upstream lacks while the upstream moved on; this merges the upstream into HEAD in memory, refuses on a conflict, pushes the merge and never moves the checkout, after which gbrain sources refresh fast-forwards. It publishes those commits, so the user reviews them first.`,+ user_message: `${diverged.root} has ${diverged.ahead} local commit(s) that were never pushed (newest ${diverged.unpushed_commits?.[0]?.sha.slice(0, 7) ?? 'unknown'} by ${diverged.unpushed_commits?.[0]?.author ?? 'unknown'}) while its remote moved on. Push them, merged with the remote, so gbrain can bring the checkout up to date?`,+ verify: doctorVerify('git_convergence') } };+ }return { name: 'git_convergence', status, details,message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. ${remedy}; this compares with the last fetched upstream and does not fetch.${boundNote}` };}diff --git a/src/commands/git.ts b/src/commands/git.tsindex 26d5c61ae3..0043f26736 100644--- a/src/commands/git.ts+++ b/src/commands/git.ts@@ -31,7 +31,9 @@ const HELP = `Usage: gbrain git commit-push [--path <dir>] -m <msg> [--json] [--Commit only the named paths and push them, safely, in a checkout other agentsshare: a short commit lock and a separate push lock per checkout, norebase/stash/reset of the working tree, remote commits merged in memory, and the-checkout advanced fast-forward only.+checkout advanced fast-forward only. In a managed canonical worktree it only+commits the named paths (committed_local): no fetch, merge, push or checkout+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).@@ -56,7 +58,7 @@ Flags:--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+directory. Exit 0 on pushed, committed_local, nothing_to_commit, push_deferred andpushed_checkout_lagging (a notice names the blocking files); 4 when the commit is local but no push wasconfirmed (push_unconfirmed); 1 on other failures, each with an "Error [<code>]" line. Guide: docs/guides/shared-checkout-git.md@@ -182,6 +184,10 @@ export async function runGit(args: string[]): Promise<number> {emit(json, { ...result, repo }, `push deferred: another push is running in ${repo} and will publish HEAD too`);return 0;}+ if (result.outcome === 'committed_local') {+ emit(json, { ...result, repo }, `committed ${result.sha!.slice(0, 7)} on ${result.branch}; not pushed: this is a managed checkout, so the owner's next Git publish pushes it (or gbrain git commit-push --push-only --keep-checkout)`);+ 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);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 1931dfef76..289def7d00 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1221,6 +1221,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.427.0', text: 'A Git effect whose target file a .gitignore rule excludes now parks on its first attempt as `git_target_ignored`, naming the rule (`<file>:<line>: <pattern>`), instead of retrying and then parking as `git_target_unsafe`. doctor `parked_effects` and `gbrain sources writer status` (`parked_groups`) group parked Git targets per source and code, each group with one bulk command: `--parked-pushes` for push codes and the new `gbrain sources writer retry-effects <source> --parked-code <code>` otherwise. An ignored target gets no per-request retry suggestion, because a retry parks it again while the rule stands. Nothing already parked changes on upgrade.' },{ since: '0.60.427.0', text: 'The worktree refresh owner check (`refresh_not_owner`) no longer creates a host identity file. A process whose gbrain home has no `persistence/host.json` (for example one started under another HOME or GBRAIN_HOME) used to mint a new identity there and then refuse as a different host; it now refuses without writing anything, and the refusal names the identity file it read, the HOME and GBRAIN_HOME it resolved and the owner it expected. A process that already owns the source refreshes as before.' },{ since: '0.60.427.0', text: 'More gbrain state follows GBRAIN_HOME: feature offers (`feature-offers.json`), the upgrade state and error log, `mounts.json` and the mounts cache, the brain-pull log (including the log paths a newly installed launchd pull job writes), the default supervisor pid file, skillopt captures, the transcript harvest pattern file, notability eval files and the greenfield import audit directory now live under `<GBRAIN_HOME>/.gbrain` when GBRAIN_HOME is set. Before, they were written under `$HOME/.gbrain` whatever GBRAIN_HOME said. With GBRAIN_HOME unset nothing moves. A host that sets GBRAIN_HOME keeps its old copies under `$HOME/.gbrain`: move them by hand if you want the old offers, mounts or upgrade history, and restart a supervisor that was started before the upgrade so `gbrain jobs supervisor status` finds its pid file.' },+ { since: 'TBD', text: 'In a managed canonical worktree, `gbrain git commit-push -m <msg> -- <paths>` now commits the named paths there (outcome `committed_local`, exit 0) instead of refusing `writer_coordinator_required`. It takes the commit lock and commits only those paths: it never fetches, merges, pushes or moves the checkout, so the persistence owner stays the only publisher; the owner\'s next Git publish, or `gbrain git commit-push --push-only --keep-checkout`, pushes the commit. --pending, --branch, --resolve, --expect-remote and --allow-outside-source-root are refused there (`commit_paths_invalid`).' },+ { since: 'TBD', text: 'The `refresh_diverged` refusal of `gbrain sources refresh` now counts the checkout\'s local commits and its fix is `gbrain git commit-push --push-only --keep-checkout --path <root> --json` (actor user, ask_user): it merges the upstream in memory, refuses on a conflict, pushes the merge and never moves the checkout, after which the refresh fast-forwards. It used to suggest reconciling in a separate clone or recloning, which drops the local commits.' },+ { since: 'TBD', text: '`gbrain sources writer status --json` has a new `checkouts` block: each canonical checkout on this host against its last fetched upstream (no fetch), with branch, upstream, ahead, behind, `diverged`, each commit the upstream lacks (sha, author, date, subject, paths; at most 20) and porcelain counts (staged, modified, untracked, conflicted). doctor `git_convergence` adds the same commits and counts for a managed canonical checkout, and now warns at once when one has diverged from its upstream (it blocks `gbrain sources refresh`), with the keep-checkout publish as an ask-user fix.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.tsindex e2c716bc99..5bdc379c27 100644--- a/src/core/brain-repo-durability.ts+++ b/src/core/brain-repo-durability.ts@@ -369,9 +369,11 @@ function renderManagedBlock(repoPath: string, managed?: { sourceId: string }): sHEAD and never pulls, so a pull, rebase, reset or checkout of page paths movesfiles under it. To bring in remote commits run\`gbrain sources refresh ${managed.sourceId}\`. Files that are not pages (this file,- \`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+ \`MEMORY.md\`, daily notes) are yours: commit them with+ \`gbrain git commit-push -m "<msg>" -- <paths>\`, which commits only those paths+ under this checkout's commit lock and never fetches, pushes or moves the+ checkout. They reach the remote on the owner's next push, or publish them with+ \`gbrain git commit-push --push-only --keep-checkout\` (never \`git push --force\`).` : `2. **Every write is committed AND pushed — push is never deferred.** After anypersistent write, run \`scripts/brain-commit-push.sh "<msg>" <path>\` (or\`gbrain git commit-push -m "<msg>" -- <path>\`). It commits only the paths youname, takes this checkout's writer lock, merges remote commits withoutdiff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.tsindex 13c8b23e9e..9cae295052 100644--- a/src/core/git/commit-push.ts+++ b/src/core/git/commit-push.ts@@ -31,7 +31,7 @@ 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 { 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';@@ -55,8 +55,11 @@ 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';+ /**+ * `push_deferred`: an unattended publish found another publish running and left it a request to publish HEAD too.+ * `committed_local`: a managed canonical worktree, where commit-push only commits the named paths and never pushes.+ */+ outcome: 'pushed' | 'nothing_to_commit' | 'pushed_checkout_lagging' | 'push_deferred' | 'committed_local';/** The commit now on the remote branch (the caller's commit or the merge built over it). */sha: string | null;committed: string | null;@@ -992,9 +995,41 @@ function defaultPublishWaitMs(): number {return Number.isFinite(secs) && secs >= 0 ? secs * 1000 : 300_000;}+/**+ * Q1: on a managed canonical worktree commit-push commits only the paths the caller names (pages written outside gbrain,+ * which would otherwise land as bare commits), under the commit lock, and nothing more: no fetch, merge, push or checkout+ * move, so the owner stays the only publisher. The commit reaches the remote on the owner's next Git publish, or with+ * `gbrain git commit-push --push-only --keep-checkout`.+ */+function commitManagedPaths(root: string, opts: CommitPushOptions, managed: ManagedFilesystemRoot): CommitPushResult {+ const where = `${root} is the managed canonical worktree${managed.sourceId ? ` of source ${managed.sourceId}` : ''}`;+ if (opts.pending || opts.branch || opts.resolutions || opts.expectRemote || opts.allowOutsideSourceRoot || opts.advanceOnlyWhenClean) {+ throw opError('commit_paths_invalid', `${where}: commit-push there only commits the paths you name.`,+ `Run gbrain git commit-push with only -m and the page paths after --; gbrain sources refresh${managed.sourceId ? ` ${managed.sourceId}` : ''} brings remote commits in.`);+ }+ if (!opts.message?.trim()) throw opError('commit_paths_invalid', 'A commit message is required.', 'Pass the commit message with -m.');+ const rel = scopePaths(root, opts.paths ?? [], opts.cwd ?? process.cwd());+ if (!rel.length) throw opError('commit_paths_invalid', `${where}: name the paths to commit.`, 'Pass -- <paths> after the message.');+ const branch = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']).stdout.trim();+ if (!branch) throw opError('git_detached_head', `${root} is on a detached HEAD, so there is no branch to commit to.`, 'Leave the checkout to its owner; gbrain sources writer status names its state.');+ assertNoOperationInProgress(root);+ const lock = acquireCommitLock(root, opts.lockWaitMs);+ let committed: string | null;+ try {+ assertNoOperationInProgress(root);+ committed = commitPaths(root, rel, opts.message.trim(), { roots: configuredSourceRoots(root), lockPath: lock.lockPath, markHeld: true });+ } finally {+ lock.release();+ }+ const remote = git(root, ['config', '--get', `branch.${branch}.remote`]).stdout.trim();+ return { outcome: committed ? 'committed_local' : 'nothing_to_commit', sha: committed, committed, branch, remote, paths: rel, integrated: 0, checkout: 'unchanged' };+}+export function commitAndPush(opts: CommitPushOptions): CommitPushResult {const root = checkoutRoot(opts.repo);if (opts.keepCheckout && !opts.pushOnly) throw opError('commit_paths_invalid', 'keepCheckout publishes commits already on the branch; it commits nothing.', 'Use --push-only --keep-checkout.');+ const managed = opts.keepCheckout || opts.pushOnly ? null : managedFilesystemRootFor(root);+ if (managed && !hasFilesystemPublication(root)) return commitManagedPaths(root, opts, managed);if (!opts.keepCheckout) assertManagedFilesystemWrite(root);const cwd = opts.cwd ?? process.cwd();const roots = configuredSourceRoots(root);diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex e980495e26..934ddf5e42 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -21,6 +21,13 @@ import { listWriterVersions } from './writer-versions.ts';import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';+async function writerStatusCheckouts(bindings: Array<{ source_id: string; local_path: string | null }>) {+ const { readCheckoutState } = await import('./checkout-state.ts');+ const roots = new Map<string, string[]>();+ for (const { source_id, local_path } of bindings) if (local_path) roots.set(local_path, [...roots.get(local_path) ?? [], source_id]);+ return [...roots].map(([root, source_ids]) => ({ source_ids, ...readCheckoutState(root) }));+}+export const invalid = (message: string, suggestion: string, fix?: Action) =>opError('invalid_params', message, suggestion, fix ? { fix } : {});const sourcesListFix = (why: string) => readFix(why, { argv: ['gbrain', 'sources', 'list', '--json'] });@@ -294,6 +301,8 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio// #6317 (B3): every process holding a consumer on this host, from the heartbeat rows (kind, pid, nonce, mode, age, wedge report).host: { host_id: existingLocalHostId(), ...await (await import('./consumer-diagnostics.ts')).hostConsumersReport(engine, existingLocalHostId()) },worktree_refreshes: await (await import('./worktree-refresh.ts')).activeWorktreeRefreshes(engine, params.source_id as string | undefined),+ // Q1: each canonical checkout on this host against its last fetched upstream: commits it holds that the upstream lacks, and its porcelain.+ checkouts: await writerStatusCheckouts(bindings as Array<{ source_id: string; local_path: string | null }>),// #6317 (B4): per managed source, whether sync data moves (shares the reader of sources status, doctor and writer movement).movement: await writerStatusMovement(engine, params.source_id === undefined ? undefined : source(params.source_id)) };}diff --git a/src/core/persistence/checkout-state.ts b/src/core/persistence/checkout-state.tsnew file mode 100644index 0000000000..2506636637--- /dev/null+++ b/src/core/persistence/checkout-state.ts@@ -0,0 +1,72 @@+/**+ * Q1 (GBRA-153 shape A): what a managed canonical checkout holds that its upstream does not, read without fetching.+ *+ * A commit made in the checkout outside gbrain (a cron's bare `git commit`, a hand edit) is not on the upstream until+ * the owner's next Git publish, and once the upstream moves on the checkout has diverged: `gbrain sources refresh`+ * refuses `refresh_diverged`. `sources writer status` and doctor `git_convergence` report each such commit (sha,+ * author, date, subject, paths) and the porcelain counts, so an operator sees who wrote what before anything is pushed.+ * Every git call is time-bounded and read-only; the comparison is with the last fetched upstream.+ */+import { execFileSync } from '../spawn.ts';++const GIT_TIMEOUT_MS = 5_000;+export const CHECKOUT_COMMITS_MAX = 20;+export const CHECKOUT_COMMIT_PATHS_MAX = 20;++export interface CheckoutCommit { sha: string; author: string; date: string; subject: string; paths: string[]; paths_total: number }+export interface CheckoutPorcelain { staged: number; modified: number; untracked: number; conflicted: number }+export interface CheckoutState {+ root: string; branch: string | null; upstream: string | null; ahead: number; behind: number; diverged: boolean;+ unpushed_commits: CheckoutCommit[]; unpushed_truncated: boolean; porcelain: CheckoutPorcelain; fetched: false; problem?: string;+}++function git(root: string, args: string[]): string | null {+ try { return execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'ignore'], timeout: GIT_TIMEOUT_MS }).toString(); }+ catch { return null; }+}++/** Each commit on HEAD that `@{upstream}` lacks, newest first, at most CHECKOUT_COMMITS_MAX of them. */+export function readUnpushedCommits(root: string): CheckoutCommit[] {+ const out = git(root, ['log', '@{upstream}..HEAD', `-n${CHECKOUT_COMMITS_MAX}`, '--name-only', '--format=%x1e%H%x1f%an <%ae>%x1f%aI%x1f%s']) ?? '';+ return out.split('\x1e').filter(Boolean).map(record => {+ const [header, ...lines] = record.split('\n');+ const [sha, author, date, subject] = header.split('\x1f');+ const paths = lines.map(line => line.trim()).filter(Boolean);+ return { sha, author, date, subject: subject ?? '', paths: paths.slice(0, CHECKOUT_COMMIT_PATHS_MAX), paths_total: paths.length };+ });+}++export function readPorcelain(root: string): CheckoutPorcelain {+ const counts: CheckoutPorcelain = { staged: 0, modified: 0, untracked: 0, conflicted: 0 };+ const entries = (git(root, ['status', '--porcelain', '-z']) ?? '').split('\0');+ for (let i = 0; i < entries.length; i++) {+ const entry = entries[i];+ if (entry.length < 4) continue;+ if (/^[RC]/.test(entry)) i++;+ const [x, y] = [entry[0], entry[1]];+ if (x === '?') counts.untracked++;+ else if (x === 'U' || y === 'U' || (x === 'A' && y === 'A') || (x === 'D' && y === 'D')) counts.conflicted++;+ else {+ if (x !== ' ' && x !== '!') counts.staged++;+ if (y !== ' ' && y !== '!') counts.modified++;+ }+ }+ return counts;+}++/** The checkout's state against its last fetched upstream; `problem` when git cannot read it or no upstream is set. */+export function readCheckoutState(root: string): CheckoutState {+ const empty = { branch: null, upstream: null, ahead: 0, behind: 0, diverged: false, unpushed_commits: [], unpushed_truncated: false,+ porcelain: { staged: 0, modified: 0, untracked: 0, conflicted: 0 }, fetched: false as const };+ const top = git(root, ['rev-parse', '--show-toplevel'])?.trim();+ if (!top) return { root, ...empty, problem: 'not a readable git checkout' };+ const branch = git(top, ['branch', '--show-current'])?.trim() || null;+ const porcelain = readPorcelain(top);+ const upstream = git(top, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'])?.trim() || null;+ const counts = upstream ? git(top, ['rev-list', '--left-right', '--count', '@{upstream}...HEAD'])?.trim().split(/\s+/).map(Number) : undefined;+ if (!upstream || !counts || counts.length !== 2 || counts.some(n => !Number.isFinite(n))) return { root: top, ...empty, branch, porcelain, problem: 'no upstream branch' };+ const [behind, ahead] = counts as [number, number];+ const unpushed = ahead ? readUnpushedCommits(top) : [];+ return { root: top, branch, upstream, ahead, behind, diverged: ahead > 0 && behind > 0, unpushed_commits: unpushed,+ unpushed_truncated: ahead > unpushed.length, porcelain, fetched: false };+}diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex 582eef5fa1..1b851f4e4f 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -249,13 +249,29 @@ async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTiconst targetHead = await revParse(git, root, '@{upstream}');if (!oldHead || !targetHead) throw refusal('refresh_no_upstream', `The checkout HEAD or its upstream ${upstreamRef} does not resolve to a commit.`,`git -C ${q(root)} fetch ${remote || 'origin'}, then gbrain sources refresh ${sourceId}`);- if (oldHead !== targetHead && !await isAncestor(git, root, oldHead, targetHead)) throw refusal('refresh_diverged',- `The checkout HEAD ${oldHead} is not an ancestor of ${upstreamRef} (${targetHead}); a fast-forward is impossible and nothing changed.`,- `Reconcile the histories and push from a non-managed clone, then retry gbrain sources refresh ${sourceId}; or replace the checkout with gbrain sources reclone ${sourceId} (ask the user first).`);+ if (oldHead !== targetHead && !await isAncestor(git, root, oldHead, targetHead)) throw await divergedRefusal(git, root, sourceId, upstreamRef, oldHead, targetHead);const dirt = await dirtyOverlap(git, root, oldHead, targetHead);if (dirt.overlap.length) throw dirtyRefusal(sourceId, dirt.overlap);return { binding, root, members, upstreamRef, oldHead, targetHead, ...dirt };}+/**+ * Q1: a diverged checkout is reconciled without moving it: `gbrain git commit-push --push-only --keep-checkout` merges the+ * upstream into HEAD in memory and pushes the merge (refusing on a conflict, never touching the checkout), after which HEAD+ * is an ancestor of the upstream and the refresh fast-forwards. It publishes the local commits, so the user decides.+ */+async function divergedRefusal(git: Git, root: string, sourceId: string, upstreamRef: string, oldHead: string, targetHead: string): Promise<OperationError> {+ const count = Number((await git(['-C', root, 'rev-list', '--count', `${targetHead}..${oldHead}`])).stdout.trim()) || 0;+ const local = count ? `${count} local commit(s)` : 'the local commits';+ const argv = ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', root, '--json'];+ const error = refusal('refresh_diverged',+ `The checkout HEAD ${oldHead} is not an ancestor of ${upstreamRef} (${targetHead}); a fast-forward is impossible and nothing changed.`,+ `Publish ${local} merged with ${upstreamRef}: ${argv.map(q).join(' ')} (it merges in memory, refuses on a conflict and never moves the checkout), then retry gbrain sources refresh ${sourceId}. Ask the user first, because it pushes those commits (git -C ${q(root)} log --stat ${upstreamRef}..HEAD lists them). gbrain sources reclone ${sourceId} replaces the checkout instead and drops them.`);+ error.fix = { argv, consent: [], actor: 'user', ask_user: true, requires_exclusive: false,+ why: `HEAD has ${local} that ${upstreamRef} lacks while ${upstreamRef} moved on; pushing HEAD merged with it makes HEAD an ancestor of the upstream, so the refresh can fast-forward.`,+ user_message: `The checkout of source ${sourceId} has ${local} that were never pushed while its remote moved on. Push them, merged with the remote, so gbrain can bring the checkout up to date? Conflicting files stop the push and change nothing.`,+ docs: 'docs/guides/write-refusals.md#refresh_diverged' };+ return error;+}function dirtyRefusal(sourceId: string, overlap: string[], refreshId?: string): OperationError {const named = overlap.slice(0, 20).join(', ') + (overlap.length > 20 ? ` and ${overlap.length - 20} more` : '');return refusal('refresh_dirty', `Uncommitted or untracked paths overlap the incoming upstream changes: ${named}. Nothing changed.`,diff --git a/test/persistence-worktree-refresh.test.ts b/test/persistence-worktree-refresh.test.tsindex 6a5b1ba1ae..6f0d676654 100644--- a/test/persistence-worktree-refresh.test.ts+++ b/test/persistence-worktree-refresh.test.ts@@ -35,6 +35,8 @@ import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecyimport { runPersistenceAdministration } from '../src/core/persistence/administration.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { refreshWorktree, resumeWorktreeRefreshes } from '../src/core/persistence/worktree-refresh.ts';+import { commitAndPush } from '../src/core/git/commit-push.ts';+import { gitConvergenceCheck } from '../src/commands/doctor/checks/git-convergence.ts';import { MANAGED_SYNC_PASS_OP, writePassRow, type ManagedSyncPassValue } from '../src/core/persistence/sync-pass-row.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';@@ -203,6 +205,61 @@ test('4. a diverged checkout is refused with no row and HEAD unchanged', () => eexpect(f.head()).toBe(head);}), 120_000);+test('4b. Q1: the diverged refusal names the keep-checkout publish; running it, then the refresh, brings the checkout up to date with the local commit kept', () => each(async f => {+ f.push('alpha/two.md', page('Alpha two', 'Upstream side.'));+ writeFileSync(join(f.root, 'beta/local.md'), page('Local', 'A local commit nobody pushed.'));+ git(f.root, 'add', 'beta/local.md'); git(f.root, 'commit', '-qm', 'local only');+ const local = f.head();+ const error = await refusedWith(refreshWorktree(f.engine, f.alpha), 'refresh_diverged') as { suggestion?: string; fix?: { argv: string[]; ask_user?: boolean; actor?: string } };+ expect(error.suggestion).toContain('1 local commit(s)');+ expect(error.fix).toMatchObject({ argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', f.root, '--json'], ask_user: true, actor: 'user' });+ git(f.root, 'config', 'user.name', 'Example'); git(f.root, 'config', 'user.email', '[email protected]');+ expect(commitAndPush({ repo: f.root, pushOnly: true, keepCheckout: true })).toMatchObject({ outcome: 'pushed', integrated: 1, checkout: 'unchanged' });+ expect(f.head()).toBe(local);+ const done = await refreshWorktree(f.engine, f.alpha);+ expect(done).toMatchObject({ status: 'completed', old_head: local });+ git(f.root, 'merge-base', '--is-ancestor', local, 'HEAD');+ expect(readFileSync(join(f.root, 'alpha/two.md'), 'utf8')).toContain('Upstream side.');+ expect((await f.engine.getPage('two', { sourceId: f.alpha }))?.compiled_truth ?? (await f.engine.getPage('alpha/two', { sourceId: f.alpha }))?.compiled_truth).toContain('Upstream side.');+}), 120_000);++test('4c. Q1: commit-push on the managed checkout commits only the named page path, fetches and pushes nothing, and keeps other dirt', () => each(async f => {+ git(f.root, 'config', 'user.name', 'Example'); git(f.root, 'config', 'user.email', '[email protected]');+ writeFileSync(join(f.root, 'beta/agent.md'), page('Agent', 'Written by an agent script.'));+ writeFileSync(join(f.root, 'beta/other.md'), page('Other', 'Another writer, not named.'));+ const before = f.head(), remote = git(f.root, 'ls-remote', 'origin', 'refs/heads/main').split('\t')[0];+ const result = commitAndPush({ repo: f.root, cwd: f.root, paths: ['beta/agent.md'], message: 'agent: file one page' });+ expect(result).toMatchObject({ outcome: 'committed_local', paths: ['beta/agent.md'], integrated: 0, checkout: 'unchanged' });+ expect(git(f.root, 'rev-parse', 'HEAD^').trim()).toBe(before);+ expect(git(f.root, 'diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD').trim()).toBe('beta/agent.md');+ expect(git(f.root, 'status', '--porcelain', '--', 'beta/other.md').trim()).toBe('?? beta/other.md');+ expect(git(f.root, 'ls-remote', 'origin', 'refs/heads/main').split('\t')[0]).toBe(remote);+ expect(() => commitAndPush({ repo: f.root, cwd: f.root, pending: true, message: 'pending' })).toThrow(expect.objectContaining({ code: 'commit_paths_invalid' }));+ expect(() => commitAndPush({ repo: f.root, cwd: f.root, pushOnly: true })).toThrow(expect.objectContaining({ code: 'writer_coordinator_required' }));+}), 120_000);++test('4d. Q1: writer status and doctor name each commit a diverged managed checkout holds (sha, author, date, paths) and its porcelain', () => each(async f => {+ f.push('alpha/two.md', page('Alpha two', 'Upstream side.'));+ git(f.root, 'fetch', '-q', 'origin');+ writeFileSync(join(f.root, 'beta/local.md'), page('Local', 'A commit made outside gbrain.'));+ git(f.root, 'add', 'beta/local.md'); git(f.root, 'commit', '-qm', 'cron: bare commit');+ const sha = f.head(), author = git(f.root, 'log', '-1', '--format=%an <%ae>').trim(), date = git(f.root, 'log', '-1', '--format=%aI').trim();+ writeFileSync(join(f.root, 'beta/scratch.txt'), 'untracked\n');+ const status = await runPersistenceAdministration(f.engine, 'writer_status', { source_id: f.beta }) as { checkouts: Array<Record<string, any>> };+ expect(status.checkouts).toHaveLength(1);+ expect(status.checkouts[0]).toMatchObject({ source_ids: [f.beta], branch: 'main', upstream: 'origin/main', ahead: 1, behind: 1, diverged: true, fetched: false,+ unpushed_truncated: false, porcelain: { staged: 0, modified: 0, untracked: 1, conflicted: 0 } });+ expect(status.checkouts[0]!.unpushed_commits).toEqual([{ sha, author, date, subject: 'cron: bare commit', paths: ['beta/local.md'], paths_total: 1 }]);+ const check = await gitConvergenceCheck(f.engine);+ expect(check?.status).toBe('warn');+ expect(check?.message).toContain('diverged');+ expect(check?.message).toContain(sha.slice(0, 7));+ const root = (check?.details as { roots: Array<Record<string, any>> }).roots.find(r => r.root === f.root)!;+ expect(root).toMatchObject({ managed: true, diverged: true, ahead: 1, behind: 1, porcelain: { untracked: 1 } });+ expect(root.unpushed_commits[0]).toMatchObject({ sha, author, paths: ['beta/local.md'] });+ expect(check?.fix).toMatchObject({ ask_user: true, actor: 'user', argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', f.root, '--json'] });+}), 120_000);+test('5. dirt overlapping the incoming diff refuses naming the path; unrelated dirt is preserved and listed', () => each(async f => {const target = f.push('alpha/one.md', page('Alpha one', 'The upstream rewrite.'));writeFileSync(join(f.root, 'alpha/one.md'), page('Alpha one', 'An uncommitted local edit.'));