Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): Git effects on a source root below the toplevel commit tracked edits and removals (#7091)

garrytan70df3a0abeda
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index 93f0cdb299..db12f7438c 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/extraction-input.ts` — `extraction_input_truncated` (large pages A7, BRAIN, registered after `fence_integrity`, before `search_mode`). Groups the live pages with an `input_truncated` receipt in `page_extraction_state` by pipeline and kind (`facts_backstop/head|tail_window`, `extract_atoms/head|tail_window`, `conversation_facts/skipped_too_large`) with three recent `source:slug` samples and a remedy each. Warns when an atoms or conversation-facts receipt exists; the atoms fix is `gbrain config set cycle.extract_atoms.max_input_chars <n>` (`ask_user`, consent `paid`), otherwise `fix_unavailable_reason: operator_judgement`. Facts-only receipts are `ok` with `severity: info`, `readiness_state: degraded` (no knob raises the facts cap; later appends are read incrementally). Reads the database only. Tests: `test/extraction-watermark-facts.test.ts`, `test/extraction-watermark-atoms.test.ts`, `test/conversation-facts-oversized-sidecar.test.ts`.
- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. #6610: `unbound_legacy_facts` lists, from the same plan, unfenced rows of classic database-only pages that `persistence.unbound_write` keeps unfenced; when it is the only finding the fix is `gbrain config set persistence.unbound_write database_only` with `ask_user`. Test: `test/doctor-fence-integrity.test.ts`, `test/extract-facts-unfenced-rows.test.ts`. Wave B decision #10: `withSkippedSegmented(check, n)` (`src/commands/doctor/check-fix.ts`) adds `Check.skipped_segmented: n` and a `skipped (segmented): n` message tail (unchanged at n = 0) to every check whose scan reads whole bodies: `oversized_pages`, `scraper_junk_pages`, `markdown_body_completeness`, `link_resolution_opportunity`, `fence_integrity` (segmented pages without a walked checkout file), `core_memory`, and `extract_health` via `readFactsReconcileBacklog`'s `skipped_segmented`; each count is one COUNT query that falls back to 0 on a schema without `body_storage`. Test: `test/large-pages/doctor-skipped-segmented.test.ts` (+ Postgres arm).
-- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time), except on a managed checkout this host owns with Git durability on and no Git effect of its worktree queued, running or failed: there they warn at once (`stranded: true` in `details.roots`, #7089) with an agent fix `gbrain git commit-push --push-only --keep-checkout --path <root>` and verify `gbrain doctor --only git_convergence --json`; uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `persistence-git-removal-push-7089.test.ts` (stranded roots, both engines), `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
+- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time), except on a managed checkout this host owns with Git durability on and no Git effect of its worktree queued, running or failed: there they warn at once (`stranded: true` in `details.roots`, #7089) with an agent fix `gbrain git commit-push --push-only --keep-checkout --path <root>` and verify `gbrain doctor --only git_convergence --json`; bindings map to their toplevel, and tracked files modified under such a durable source root warn the same way (`uncommitted_pages`, #7091) with an ask-user commit, then that push; uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `persistence-git-removal-push-7089.test.ts` (stranded roots, both engines), `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
- `src/commands/doctor/checks/keyword-plan.ts` — `keyword_plan` (#6495, OPS, wave check with operator resolution; the keyword-side twin of `vector_plan` in commands-2.md). Postgres only: reads the commonest lexeme the planner knows for `content_chunks.search_vector` (`pg_stats.most_common_elems` with its frequency), EXPLAINs (no ANALYZE) the strict page-count statement for it (`buildKeywordCountStatement`, the builder the engine uses) and times the engine's own bounded `countKeywordPages(term, { timeoutMs: 2000 })`; warns `canary_timed_out` when that count hits its bound and `canary_slow` when it takes more than half of `search.keyword_statement_timeout_ms`, naming the knob with its range (1000-60000), the fail-open to the vector arm (`keyword_arm_failed`), that a longer bound buys time and not a cheaper statement, that one canary term is not workload coverage, and that a timed-out count is never "no matches". Skipped on PGLite, below 10,000 chunks (`pg_class.reltuples`) and without planner statistics (it names `ANALYZE content_chunks`); a failing probe reports unknown health. `engineKeywordPlanProbe(engine)` is the database side; `keywordPlanCheck(engine, probe?)` takes a fake for tests. Tested in `test/doctor-keyword-plan-6495.test.ts` (fake probe for every outcome; with DATABASE_URL the real probe on a seeded brain and a lock-forced timeout).
- `src/commands/doctor/checks/image-embedding-coverage.ts` — `image_embedding_coverage` (#6529, brain category, after `image_assets`). Counts live image pages (`page_kind = 'image'`), those with no `embedding_image` chunk, those with a NULL `source_path`, and the `managed_image_sync_unsupported` holds per source, and reads `isMultimodalEnabled()`. Ok when the brain has no image pages, when every image page has an image vector and a `source_path` and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names `gbrain embed --stale --images` and `gbrain sync --no-pull --source <id>` for the holds. Read-only; no paid call. Test: `test/doctor-image-embedding-coverage.test.ts`.
- `src/commands/doctor/checks/provider-consent.ts` — `provider_consent` (OPS, engine-free filesystem lane right after `embedding_key_source`; not in `doctorReportRemote`): the provider-use decision `gbrain setup` recorded for this install (`localSetupRecords` in `src/core/setup/local-receipts.ts`). A decline (any live receipt; opt-outs win) is `ok` + info `disabled_by_choice`, "skipped by consent", naming the provider key variables present (names only) and carrying `providerConsentFix`: `gbrain setup <harness> --providers` (+ `--name`/`--scope project`), actor `user`, consent `paid`+`egress`, so `next: tell_user_to_run`. Accepted is plain `ok`; no receipt is info `not_applicable`. The same fix rides `embedding_provider`'s `--probe` skip (`checks/embedding-health.ts`), and `probe-consent.ts` authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by `test/doctor-provider-consent.serial.test.ts` (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index d6c8c21a85..85e608f287 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -38,7 +38,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.
- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-supplied `sleep` decides how each pause ends, which is how subagent tool writes stop on abort); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`. `pollCommand` (#6255) renders the envelope's receipt `fix.argv` (`gbrain write-request --brain <id> -- <request_id>`), else pins that argv to the CLI routing; each argument is shell-quoted (`src/core/shell-quote.ts`, fix wave 13 P1.15).
- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB; `boundedUnifiedDiff` keeps its LCS table under `EDIT_PAGE_DIFF_CELL_BUDGET` (4M cells) by diffing only the window between common leading/trailing lines, and a window still over budget becomes one coarse hunk flagged `diff_coarse` (pinned by `test/large-pages/edit-diff-bounded.test.ts`). Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.
-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. That holds for a removal too (#7089): its retry finds the path untracked and absent (`target_absent`), and it joins the push while the root is ahead of its upstream (`gitRootAhead`, a local `rev-list @{upstream}..HEAD`, no upstream is not ahead), as does `publishGitEffect`, recording `target_absent` with the push result; on a root that is not ahead it completes without a push, so a down remote never parks it. A Git page walk that ends while its durable root is ahead pushes before completing (`test/persistence-git-removal-push-7089.test.ts` + Postgres wrapper). In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits), transient database failures and raw errors `classifyItemFailure` calls run-scoped (a lost connection, a failed transaction, an abort, a full disk) do not count). A `links` or `facts-backstop` effect counts its failures the same way (`data.target_failures`, no target; run-scoped failures, including run-scoped refusal codes, never count, and a 57014 counts as `statement_timeout`): at five a links effect completes as skipped with the code (`outcome: { links: 'skipped', reason }`; the edges are derived and `gbrain extract --stale` recovers them) and a facts-backstop effect fails with it; a pass's counted failures settle when the pass ends under an `ItemRun` (`effects.derived_retry_budget`), and a pass where most of them failed counts none (each retries as `item_failures_systemic`) (GBRA-130 A-11, `test/pathological/a11-effect-retry-budget.test.ts`). An embedding scan (a withdrawal's exact targets or a source scan) parks the page whose provider call keeps failing once its per-page budget (`MAX_RATE_LIMIT_RETRIES`) is spent, with the failure's code, and moves on with a fresh budget; provider throttling (`isEmbedRetriableError`), configuration, budget and disabled errors and run-scoped failures stay effect-wide (A-13, `a13-embedding-target-park.test.ts`): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). A page stored in segments is mirrored and committed too, streamed (see the segmented withdrawal mirror entry in `core-persistence-request-indexes.md`). Both claim queries hold a request's Git and embedding effects only while its withdrawal mirror is queued or running; each Git or embedding attempt rereads its mirror (`mirrorGates`, every mirror not committed plus a committed one that recorded its publications): a mirror queued or running again (retry-effects after the claim) makes the attempt wait (`withdrawal_mirror_pending`); otherwise the mirror's recovery records each page whose file it rewrote (`data.published`) and its cursor is never proof: a Git page walk commits a page the mirror passed only when the file's raw bytes hash-equal the mirror rendering of the current snapshot (the serialization `mirrorPage` writes; this also covers a mirror from before publications were recorded and a published file later reverted by hand) and otherwise skips it (`withdrawal_not_mirrored`), a single-file Git effect needs the recorded publication, embedding behind a failed mirror needs the recorded publication, and behind a failed mirror every other page, including a single-file Git effect's page in a coalesced group, is parked with `withdrawal_mirror_failed`, so Git never commits a file that may still hold withdrawn text. When the mirror commits, the same transaction re-arms its request's Git and embedding targets parked `withdrawal_mirror_failed` (`rearmWithheldTargets`: a scan revisits them through `data.retry_slugs`; other parks stay), and each effect pass repeats it for the requests it touched, so no second retry-effects is needed. Lifecycle settlement (`topology-locks.ts`) waits on a queued mirror, not a failed one (A-12, `a12-withdrawal-mirror-gate.test.ts`). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); it also covers parked embedding targets, failed Git, withdrawal-mirror, links and facts-backstop effects without parked targets (one more attempt; a mirror that failed `source_changed` reruns from its cursor once the source is back) and an embedding effect that failed `source_changed`, so one call reruns a failed mirror and re-arms the pages it withheld; `parkedOnly` keeps the credential-change retry (`retryParkedPushes`) to parked Git and withdrawal effects; tests: `persistence-effect-parking.test.ts`. `repair embedding-effects` skips failed embedding effects with parked targets and zero-norm refusals. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated. Only the writer, holding its writer lock, removes a lock `index-lock-reclaim.ts` proves abandoned (its header lists the proof), with a receipt doctor `parked_effects` reports, then retries the step and the effects that lock parked; otherwise `git_index_stale` carries an `ask_user` fix. Steps run with `GIT_OPTIONAL_LOCKS=0`, an index-scaled deadline (`gitStepTimeoutMs`) and a 10 s SIGTERM grace (#6932).
+- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. Every path listing compares relative to the source root, which may sit below the Git toplevel (#7091: status prefix stripped, `diff --relative`). That holds for a removal too (#7089): its retry finds the path untracked and absent (`target_absent`), and it joins the push while the root is ahead of its upstream (`gitRootAhead`, a local `rev-list @{upstream}..HEAD`, no upstream is not ahead), as does `publishGitEffect`, recording `target_absent` with the push result; on a root that is not ahead it completes without a push, so a down remote never parks it. A Git page walk that ends while its durable root is ahead pushes before completing (`test/persistence-git-removal-push-7089.test.ts` + Postgres wrapper). In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits), transient database failures and raw errors `classifyItemFailure` calls run-scoped (a lost connection, a failed transaction, an abort, a full disk) do not count). A `links` or `facts-backstop` effect counts its failures the same way (`data.target_failures`, no target; run-scoped failures, including run-scoped refusal codes, never count, and a 57014 counts as `statement_timeout`): at five a links effect completes as skipped with the code (`outcome: { links: 'skipped', reason }`; the edges are derived and `gbrain extract --stale` recovers them) and a facts-backstop effect fails with it; a pass's counted failures settle when the pass ends under an `ItemRun` (`effects.derived_retry_budget`), and a pass where most of them failed counts none (each retries as `item_failures_systemic`) (GBRA-130 A-11, `test/pathological/a11-effect-retry-budget.test.ts`). An embedding scan (a withdrawal's exact targets or a source scan) parks the page whose provider call keeps failing once its per-page budget (`MAX_RATE_LIMIT_RETRIES`) is spent, with the failure's code, and moves on with a fresh budget; provider throttling (`isEmbedRetriableError`), configuration, budget and disabled errors and run-scoped failures stay effect-wide (A-13, `a13-embedding-target-park.test.ts`): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). A page stored in segments is mirrored and committed too, streamed (see the segmented withdrawal mirror entry in `core-persistence-request-indexes.md`). Both claim queries hold a request's Git and embedding effects only while its withdrawal mirror is queued or running; each Git or embedding attempt rereads its mirror (`mirrorGates`, every mirror not committed plus a committed one that recorded its publications): a mirror queued or running again (retry-effects after the claim) makes the attempt wait (`withdrawal_mirror_pending`); otherwise the mirror's recovery records each page whose file it rewrote (`data.published`) and its cursor is never proof: a Git page walk commits a page the mirror passed only when the file's raw bytes hash-equal the mirror rendering of the current snapshot (the serialization `mirrorPage` writes; this also covers a mirror from before publications were recorded and a published file later reverted by hand) and otherwise skips it (`withdrawal_not_mirrored`), a single-file Git effect needs the recorded publication, embedding behind a failed mirror needs the recorded publication, and behind a failed mirror every other page, including a single-file Git effect's page in a coalesced group, is parked with `withdrawal_mirror_failed`, so Git never commits a file that may still hold withdrawn text. When the mirror commits, the same transaction re-arms its request's Git and embedding targets parked `withdrawal_mirror_failed` (`rearmWithheldTargets`: a scan revisits them through `data.retry_slugs`; other parks stay), and each effect pass repeats it for the requests it touched, so no second retry-effects is needed. Lifecycle settlement (`topology-locks.ts`) waits on a queued mirror, not a failed one (A-12, `a12-withdrawal-mirror-gate.test.ts`). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); it also covers parked embedding targets, failed Git, withdrawal-mirror, links and facts-backstop effects without parked targets (one more attempt; a mirror that failed `source_changed` reruns from its cursor once the source is back) and an embedding effect that failed `source_changed`, so one call reruns a failed mirror and re-arms the pages it withheld; `parkedOnly` keeps the credential-change retry (`retryParkedPushes`) to parked Git and withdrawal effects; tests: `persistence-effect-parking.test.ts`. `repair embedding-effects` skips failed embedding effects with parked targets and zero-norm refusals. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated. Only the writer, holding its writer lock, removes a lock `index-lock-reclaim.ts` proves abandoned (its header lists the proof), with a receipt doctor `parked_effects` reports, then retries the step and the effects that lock parked; otherwise `git_index_stale` carries an `ask_user` fix. Steps run with `GIT_OPTIONAL_LOCKS=0`, an index-scaled deadline (`gitStepTimeoutMs`) and a 10 s SIGTERM grace (#6932).
- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain, as do `takes_remove` and `takes_rebuild` (`LOCAL_CLI_LOCAL_ONLY_OPS`) for the `local_cli` principal (write scope still checked; `gbrain takes remove` and `gbrain takes rebuild` defer their engine like the other takes verbs); other local calls keep no marker (`test/persistence-local-only-ops.test.ts`). `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).
diff --git a/src/commands/doctor/checks/git-convergence.ts b/src/commands/doctor/checks/git-convergence.ts
index ca8500766c..361c305f30 100644
--- a/src/commands/doctor/checks/git-convergence.ts
+++ b/src/commands/doctor/checks/git-convergence.ts
@@ -14,15 +14,19 @@
* #7089: a managed canonical checkout this host owns, with Git durability on,
* whose commits are not on the upstream while no Git effect of its worktree is
* queued, running or parked, warns at once (`stranded`): nothing will push
- * them, so the fix pushes them with the keep-checkout publish.
+ * them, so the fix pushes them with the keep-checkout publish. #7091: so does
+ * one with tracked files modified under its source root (a root below the
+ * toplevel included): no effect will commit them, so the fix asks the user to
+ * commit them, then pushes.
*
* The same entry emits `tracked_ownership_marker` (#5186) for the same roots.
*/
import { execFileSync } from '../../../core/spawn.ts';
import { realpathSync, statSync } from 'node:fs';
-import { join } from 'node:path';
+import { join, relative, sep } from 'node:path';
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
+import type { Action } from '../../../core/agent-output.ts';
import { parseSourceConfig } from '../../../core/sources-load.ts';
import { isConnectorSourceKind } from '../../../core/persistence/connector-identity.ts';
import { isPhysicalRootMetadata } from '../../../core/persistence/root-metadata.ts';
@@ -39,26 +43,33 @@ 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 }
+ oldest_unpushed_at: string | null; oldest_dirty_at: string | null; status: 'ok' | 'warn' | 'fail'; stranded?: true; uncommitted_pages?: string[] }
const canonicalPath = (path: string) => { try { return realpathSync(path); } catch { return path; } };
/**
* #7089: the canonical checkouts this host owns with Git durability on and no Git effect of their worktree queued,
- * running or parked: commits there that are not on the upstream have no effect left to push them.
+ * running or parked: commits there that are not on the upstream have no effect left to push them. Keyed by the
+ * checkout's toplevel (#7091: a binding's local_path may sit below it), each with its source roots' toplevel-relative prefixes.
*/
-async function unwatchedDurableRoots(engine: BrainEngine): Promise<Set<string>> {
+async function unwatchedDurableRoots(engine: BrainEngine): Promise<Map<string, string[]>> {
const hostId = existingLocalHostId();
- if (!hostId) return new Set();
- const bindings = await engine.executeRaw<{ local_path: string; git_durability: 'enabled' | 'disabled' | null }>(
- `SELECT h.local_path,h.git_durability FROM persistence_host_bindings h JOIN persistence_worktrees w ON w.id=h.worktree_id
+ if (!hostId) return new Map();
+ const bindings = await engine.executeRaw<{ local_path: string; git_durability: 'enabled' | 'disabled' | null; relative_paths: string[] | null }>(
+ `SELECT h.local_path,h.git_durability,
+ (SELECT array_agg(b.relative_path) FROM persistence_source_bindings b WHERE b.worktree_id=h.worktree_id) AS relative_paths
+ FROM persistence_host_bindings h JOIN persistence_worktrees w ON w.id=h.worktree_id
WHERE h.host_id=$1::uuid AND w.owner_host_id=$1::uuid AND w.state='active' AND NOT EXISTS (
SELECT 1 FROM persistence_effects e WHERE e.worktree_id=h.worktree_id AND e.kind='git' AND e.state IN ('queued','running','failed'))`,
[hostId]).catch(() => []);
- const roots = new Set<string>();
+ const roots = new Map<string, string[]>();
for (const binding of bindings) {
const durable = await gitDurabilityPolicy(binding, binding.local_path).then(policy => policy.durable, () => false);
- if (durable) roots.add(canonicalPath(binding.local_path));
+ const top = durable ? git(binding.local_path, ['rev-parse', '--show-toplevel'])?.trim() : undefined;
+ if (!top) continue;
+ const prefixes = (binding.relative_paths?.length ? binding.relative_paths : ['']).map(path =>
+ relative(canonicalPath(top), canonicalPath(join(binding.local_path, path))).split(sep).join('/'));
+ roots.set(canonicalPath(top), [...roots.get(canonicalPath(top)) ?? [], ...prefixes]);
}
return roots;
}
@@ -68,7 +79,8 @@ function git(root: string, args: string[]): string | null {
catch { return null; }
}
-function probe(root: string, sourceIds: string[], now: number): RootReport | { root: string; source_ids: string[]; skipped: string } {
+/** `tracked` collects each probed toplevel's modified tracked paths (toplevel-relative). */
+function probe(root: string, sourceIds: string[], now: number, tracked: Map<string, string[]>): RootReport | { root: string; source_ids: string[]; skipped: string } {
const top = git(root, ['rev-parse', '--show-toplevel'])?.trim();
if (!top) return { root, source_ids: sourceIds, skipped: 'not a git checkout' };
const counts = git(top, ['rev-list', '--left-right', '--count', '@{u}...HEAD'])?.trim().split(/\s+/).map(Number);
@@ -80,6 +92,7 @@ function probe(root: string, sourceIds: string[], now: number): RootReport | { r
for (let i = 0; i < entries.length; i++) {
if (entries[i].length < 4) continue;
changed.push(entries[i].slice(3));
+ if (!entries[i].startsWith('??') && !entries[i].startsWith('!!')) tracked.set(top, [...tracked.get(top) ?? [], entries[i].slice(3)]);
if (/^[RC]/.test(entries[i])) i++;
}
const mtimes = changed.slice(0, MAX_DIRTY_PATHS).flatMap(path => { try { return [statSync(join(top, path)).mtimeMs]; } catch { return []; } });
@@ -111,16 +124,21 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())
const roots = await sourceRoots(engine);
if (!roots.size) return null;
const byTop = new Map<string, RootReport | { root: string; source_ids: string[]; skipped: string }>();
+ const tracked = new Map<string, string[]>();
for (const [root, ids] of [...roots].slice(0, MAX_ROOTS)) {
- const report = probe(root, ids, now);
+ const report = probe(root, ids, now, tracked);
const prior = byTop.get(report.root);
byTop.set(report.root, prior ? { ...prior, source_ids: [...prior.source_ids, ...ids] } : report);
}
const reports = [...byTop.values()].filter((r): r is RootReport => !('skipped' in r));
- const unwatched = reports.some(r => r.ahead > 0) ? await unwatchedDurableRoots(engine) : new Set<string>();
+ const unwatched = reports.some(r => r.ahead > 0 || tracked.has(r.root)) ? await unwatchedDurableRoots(engine) : new Map<string, string[]>();
for (const report of reports) {
- if (report.ahead === 0 || !unwatched.has(canonicalPath(report.root))) continue;
+ const prefixes = unwatched.get(canonicalPath(report.root));
+ if (!prefixes) continue;
+ const pages = [...new Set(tracked.get(report.root) ?? [])].filter(path => prefixes.some(prefix => !prefix || path.startsWith(`${prefix}/`))).slice(0, MAX_DIRTY_PATHS);
+ if (report.ahead === 0 && !pages.length) continue;
report.stranded = true;
+ if (pages.length) report.uncommitted_pages = pages;
if (report.status === 'ok') report.status = 'warn';
}
const skipped = [...byTop.values()].filter((r): r is { root: string; source_ids: string[]; skipped: string } => 'skipped' in r);
@@ -141,6 +159,18 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())
: 'Commit and push them (gbrain sources push --path <root> for a bootstrap workspace, or git push in the checkout)';
const stranded = bad.filter(r => r.stranded);
const status = bad.some(r => r.status === 'fail') ? 'fail' : 'warn';
+ const uncommitted = stranded.find(r => r.uncommitted_pages);
+ if (uncommitted) {
+ const pages = uncommitted.uncommitted_pages!;
+ const push: Action = { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', uncommitted.root], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Publishes the commit just made without moving the checkout.', verify: doctorVerify('git_convergence') };
+ return { name: 'git_convergence', status, details,
+ message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. ${uncommitted.root} is a managed checkout with Git durability on, ${pages.length} tracked file(s) modified under its source root (${pages.slice(0, 5).join(', ')}${pages.length > 5 ? ', ...' : ''}) and no Git effect queued, running or parked, so no effect will commit them (#7091: earlier releases committed no edits to tracked pages when the source root sits below the repository top). Review and commit them with plain git, then push with the keep-checkout publish. ${remedy}; this compares with the last fetched upstream and does not fetch.`,
+ fix: { ask_user: true, argv: ['git', '-C', uncommitted.root, 'commit', '-m', 'gbrain: persist canonical memory update', '--', ...pages], consent: [], actor: 'user', requires_exclusive: false,
+ why: `These tracked files under a durable managed source root differ from the last commit and no Git effect will commit them; committing writes them to the checkout's history, so the user reviews them first.${stranded.length > 1 ? ` ${stranded.length - 1} other checkout(s) are stranded too, see details.roots (stranded).` : ''}`,
+ user_message: `${pages.length} page file(s) in ${uncommitted.root} were edited but never committed (${pages.slice(0, 5).join(', ')}${pages.length > 5 ? ', ...' : ''}), so they are not on the remote. Commit them and push?`,
+ verify: doctorVerify('git_convergence'), then: push } };
+ }
if (stranded.length) {
const first = stranded[0]!;
return { name: 'git_convergence', status, details,
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 97bba9d07d..1c420f87ed 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -129,7 +129,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index 14fbe895b0..78e9132fc5 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -169,8 +169,8 @@ async function stageTarget(session: GitSession, relativePath: string): Promise<{
parent = dirname(parent);
}
const scope = relative(root, parent).split(sep).join('/') || '.';
- const deleted = await git(session, ['diff', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope]);
- const staged = await git(session, ['diff', '--cached', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope]);
+ const deleted = await git(session, ['diff', '--name-only', '--relative', '--diff-filter=D', '--no-renames', '-z', '--', scope]);
+ const staged = await git(session, ['diff', '--cached', '--name-only', '--relative', '--diff-filter=D', '--no-renames', '-z', '--', scope]);
if (deleted.code !== 0 || staged.code !== 0) throw gitFailure('Cannot inspect canonical Git deletions.', `git diff could not list the deletions under ${scope}.`);
for (const entry of new Set(`${deleted.stdout}${staged.stdout}`.split('\0').filter(Boolean))) {
if (existsSync(join(root, entry))) continue;
@@ -234,8 +234,12 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
if (out.code !== 0) throw gitFailure('Cannot inspect the canonical Git target.', `git ${args[0]} failed for this group of ${paths.length} file(s).`);
return out.stdout;
};
+ // #7091: ls-files and `diff --relative` print paths relative to the root, but status prints them relative to the
+ // repository toplevel; a root below the toplevel (local_path <repo>/brain) strips its prefix so every listing compares.
+ const prefix = paths.length ? (await git(session, ['rev-parse', '--show-prefix'])).stdout.replace(/\n$/, '') : '';
const tracked = new Set((await list(['ls-files', '-z'])).split('\0').filter(Boolean));
- const dirty = new Set((await list(['status', '--porcelain', '-z', '--no-renames', '--untracked-files=all'])).split('\0').filter(Boolean).map(entry => entry.slice(3)));
+ const dirty = new Set((await list(['status', '--porcelain', '-z', '--no-renames', '--untracked-files=all'])).split('\0').filter(Boolean)
+ .map(entry => entry.slice(3)).map(path => path.startsWith(prefix) ? path.slice(prefix.length) : path));
const changed: { requested: string; path: string }[] = [];
const staged: string[] = [];
// #6665: a tracked path absent on disk is staged as a removal without trusting status, which can
@@ -256,7 +260,7 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
if (staged.length) {
const add = await git(session, ['add', '-A', '--', ...new Set(staged)]);
if (add.code !== 0) throw gitFailure('Cannot stage the canonical Git target.', `git add failed for this group of ${new Set(staged).size} file(s).`);
- const diff = await git(session, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--', ...new Set(staged)]);
+ const diff = await git(session, ['diff', '--cached', '--name-only', '--relative', '-z', '--no-renames', '--', ...new Set(staged)]);
if (diff.code !== 0) throw gitFailure('Cannot compare the canonical Git target.', `git diff --cached failed for this group of ${new Set(staged).size} file(s).`);
const indexed = new Set(diff.stdout.split('\0').filter(Boolean));
for (const [requested, path] of normalized) {
@@ -270,7 +274,7 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
const rm = await git(session, [...NO_FSCACHE, 'rm', '--cached', '--quiet', '--ignore-unmatch', '--', ...removals]);
if (rm.code !== 0) throw gitFailure('Cannot stage the canonical Git target removal.', `git rm --cached failed for this group of ${removals.length} removed file(s).`);
const kept = await git(session, [...NO_FSCACHE, 'ls-files', '-z', '--', ...removals]);
- const diff = await git(session, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--', ...removals]);
+ const diff = await git(session, ['diff', '--cached', '--name-only', '--relative', '-z', '--no-renames', '--', ...removals]);
if (kept.code !== 0 || diff.code !== 0) throw gitFailure('Cannot compare the canonical Git target removal.', `git ls-files or git diff --cached failed for this group of ${removals.length} removed file(s).`);
const still = new Set(kept.stdout.split('\0').filter(Boolean));
const indexed = new Set(diff.stdout.split('\0').filter(Boolean));
diff --git a/src/core/repair/url-clone-fences.ts b/src/core/repair/url-clone-fences.ts
index 261542c44c..1807592802 100644
--- a/src/core/repair/url-clone-fences.ts
+++ b/src/core/repair/url-clone-fences.ts
@@ -124,7 +124,7 @@ async function survey(engine: BrainEngine, sourceIds: string[]): Promise<{ files
let staged: Set<string>;
try {
paths = trackedChanges(root);
- staged = new Set(git(root, ['diff', '--cached', '--name-only', '-z', 'HEAD', '--']).split('\0').filter(Boolean));
+ staged = new Set(git(root, ['diff', '--cached', '--name-only', '--relative', '-z', 'HEAD', '--']).split('\0').filter(Boolean));
} catch (error) {
listing.push({ item: `${source.id}:.`, class: 'unreadable_checkout', detail: `git cannot read the checkout (${(error as Error).message.split('\n')[0]}); fix the checkout, then preview again: ${preview(source.id)}` });
continue;
@@ -176,7 +176,7 @@ async function restoreFile(engine: BrainEngine, file: ClonedFile, runId: string)
const changed = await identityChange(engine, file);
if (changed) return { applied: false, outcome: 'preview_changed', reason: changed, detail: { path: file.path } };
if (!await urlCloneReadOnly(engine, file.source_id)) return { applied: false, outcome: 'refused', reason: 'not_url_clone', detail: { path: file.path } };
- if (git(file.root, ['diff', '--cached', '--name-only', '-z', 'HEAD', '--', file.path])) {
+ if (git(file.root, ['diff', '--cached', '--name-only', '--relative', '-z', 'HEAD', '--', file.path])) {
return { applied: false, outcome: 'preview_changed', reason: `${file.path} has a staged change since the preview, which gbrain never makes`, detail: { path: file.path } };
}
const abs = join(file.root, file.path);
diff --git a/src/core/url-clone.ts b/src/core/url-clone.ts
index feb168409c..18dc9df84c 100644
--- a/src/core/url-clone.ts
+++ b/src/core/url-clone.ts
@@ -90,7 +90,7 @@ export interface UrlClonePullBlock {
/** Tracked files of `root` whose index or working copy differs from HEAD. */
export function trackedChanges(root: string): string[] {
- const out = execFileSync('git', ['-C', root, 'diff', '--name-only', '-z', 'HEAD', '--'], { env: gitChildEnv(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) as string;
+ const out = execFileSync('git', ['-C', root, 'diff', '--name-only', '--relative', '-z', 'HEAD', '--'], { env: gitChildEnv(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) as string;
return out.split('\0').filter(Boolean).sort();
}
diff --git a/test/e2e/persistence-git-subdir-root-7091-postgres.test.ts b/test/e2e/persistence-git-subdir-root-7091-postgres.test.ts
new file mode 100644
index 0000000000..acf9006d81
--- /dev/null
+++ b/test/e2e/persistence-git-subdir-root-7091-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../persistence-git-subdir-root-7091.test.ts'));
diff --git a/test/persistence-git-subdir-root-7091.test.ts b/test/persistence-git-subdir-root-7091.test.ts
new file mode 100644
index 0000000000..217713da51
--- /dev/null
+++ b/test/persistence-git-subdir-root-7091.test.ts
@@ -0,0 +1,169 @@
+/**
+ * #7091: a managed source whose root sits below the Git toplevel (local_path = <repo>/brain) with Git durability on.
+ *
+ * commitGitTargets compared ls-files paths (relative to the root) with status and `diff --cached --name-only` paths
+ * (relative to the toplevel), so an edit to an already-tracked page and a page removal completed `{ git: 'unchanged' }`
+ * and nothing was committed or pushed, while writer status showed nothing pending. Every listing now compares on one
+ * base. Doctor `git_convergence` maps such a root to its toplevel, so its #7089 `stranded` warning fires there too, and
+ * it also warns about tracked files modified under a durable root with no Git effect left to commit them.
+ *
+ * PGLite here; Postgres through test/e2e/persistence-git-subdir-root-7091-postgres.test.ts.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { commitGitTargets } from '../src/core/persistence/effect-git.ts';
+import { gitConvergenceCheck } from '../src/commands/doctor/checks/git-convergence.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { type Repo, bindSource, createGitCoalescingFixture, git, harden, pageSlug, pass, pauseGitEffects, putPage, release } from './helpers/git-coalescing-fixture.ts';
+
+const { makeRepo, withBrain, dispose } = createGitCoalescingFixture('7091');
+afterAll(dispose);
+
+const SUBDIR = 'brain';
+const head = (repo: Repo) => git(repo.root, 'rev-parse', 'HEAD').trim();
+const remoteHead = (repo: Repo) => git(repo.root, 'ls-remote', 'origin', 'refs/heads/main').split('\t')[0]!.trim();
+const pending = (repo: Repo) => git(repo.root, 'status', '--porcelain', '--', '.').trim();
+const latestGitEffect = async (engine: BrainEngine) => (await engine.executeRaw<{ id: string; state: string; error_code: string | null; outcome: Record<string, unknown> | null }>(
+ "SELECT id::text AS id, state, error_code, outcome FROM persistence_effects WHERE kind='git' ORDER BY id DESC LIMIT 1"))[0]!;
+
+/** A repository whose managed source root is its `brain/` subdirectory, with Git durability on through the hook. */
+async function subdirRepo(engine: BrainEngine, home: string): Promise<{ top: Repo; repo: Repo }> {
+ const top = makeRepo(home, 'content');
+ mkdirSync(join(top.root, SUBDIR));
+ writeFileSync(join(top.root, SUBDIR, 'README.md'), 'brain\n');
+ const repo = { ...top, root: join(top.root, SUBDIR) };
+ // The reporter's binding: the worktree recorded at the source directory itself, as when the directory was claimed
+ // before it sat in a larger repository, not at the toplevel a fresh claim inside a repository discovers.
+ renameSync(join(top.root, '.git'), join(top.root, '.git-hidden'));
+ try { await bindSource(engine, 'default', repo); } finally { renameSync(join(top.root, '.git-hidden'), join(top.root, '.git')); }
+ expect((await engine.executeRaw<{ local_path: string }>('SELECT local_path FROM persistence_host_bindings'))[0]!.local_path).toBe(repo.root);
+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });
+ harden(top);
+ return { top, repo };
+}
+
+/** Put page `i`, then run its Git effect: committed and pushed, with nothing left in the source root. */
+async function putAndPublish(engine: BrainEngine, repo: Repo, ctx: OperationContext, i: number, content?: string): Promise<void> {
+ const revision = content === undefined ? undefined : (await engine.readPageSnapshot(pageSlug(i), { sourceId: 'default' }))!.revision;
+ await pauseGitEffects(engine, () => content === undefined ? putPage(ctx, i)
+ : submitPageMutation(ctx, { operation: 'put_page', params: { slug: pageSlug(i), request_id: randomUUID(), content, expected_revision: revision } }));
+ await release(engine);
+ await pass(engine);
+}
+
+const edited = (i: number) => `---\ntype: note\ntitle: Page ${i}\n---\n\nEdited page ${i}.\n`;
+
+for (const kind of testBackends()) describe(`#7091 a source root below the Git toplevel (${kind})`, () => {
+ if (kind === 'postgres') process.env.GBRAIN_TEST_COALESCE_PG ??= process.env.DATABASE_URL;
+
+ test('an edit to a tracked page commits and pushes, never a silent unchanged', () => withBrain(kind, async ({ engine, home, ctx }) => {
+ const { repo } = await subdirRepo(engine, home);
+ await putAndPublish(engine, repo, ctx('default'), 1);
+ expect(git(repo.root, 'log', '-1', '--name-only', '--format=').trim()).toBe(`${SUBDIR}/${pageSlug(1)}.md`);
+ expect(remoteHead(repo)).toBe(head(repo));
+ const before = head(repo);
+ await putAndPublish(engine, repo, ctx('default'), 1, edited(1));
+ expect(head(repo)).not.toBe(before);
+ expect(git(repo.root, 'log', '-1', '--name-only', '--format=').trim()).toBe(`${SUBDIR}/${pageSlug(1)}.md`);
+ expect(remoteHead(repo)).toBe(head(repo));
+ expect(pending(repo)).toBe('');
+ expect(await latestGitEffect(engine)).toMatchObject({ state: 'committed', outcome: { git: 'committed', push: 'committed' } });
+ }), 300_000);
+
+ test('a page delete commits its removal and pushes it', () => withBrain(kind, async ({ engine, home, ctx }) => {
+ const { repo } = await subdirRepo(engine, home);
+ await putAndPublish(engine, repo, ctx('default'), 1);
+ const snapshot = await engine.readPageSnapshot(pageSlug(1), { sourceId: 'default' });
+ await pauseGitEffects(engine, () => submitPageMutation(ctx('default'), { operation: 'delete_page',
+ params: { slug: pageSlug(1), expected_revision: snapshot!.revision, request_id: randomUUID() } }));
+ expect(existsSync(join(repo.root, `${pageSlug(1)}.md`))).toBe(false);
+ await release(engine);
+ await pass(engine);
+ expect(git(repo.root, 'log', '-1', '--name-status', '--format=').trim()).toBe(`D\t${SUBDIR}/${pageSlug(1)}.md`);
+ expect(remoteHead(repo)).toBe(head(repo));
+ expect(pending(repo)).toBe('');
+ expect(await latestGitEffect(engine)).toMatchObject({ state: 'committed', outcome: { git: 'committed', push: 'committed' } });
+ }), 300_000);
+
+ test('a removal whose first push failed is pushed by the next pass (#7089 on a subdirectory root)', () => withBrain(kind, async ({ engine, home, ctx }) => {
+ const { repo } = await subdirRepo(engine, home);
+ await putAndPublish(engine, repo, ctx('default'), 1);
+ const snapshot = await engine.readPageSnapshot(pageSlug(1), { sourceId: 'default' });
+ await pauseGitEffects(engine, () => submitPageMutation(ctx('default'), { operation: 'delete_page',
+ params: { slug: pageSlug(1), expected_revision: snapshot!.revision, request_id: randomUUID() } }));
+ repo.rejectPushes(true);
+ await release(engine);
+ await pass(engine);
+ expect(git(repo.root, 'log', '-1', '--name-status', '--format=').trim()).toBe(`D\t${SUBDIR}/${pageSlug(1)}.md`);
+ expect(await latestGitEffect(engine)).toMatchObject({ state: 'queued', error_code: 'git_push_unavailable' });
+ repo.rejectPushes(false);
+ await release(engine);
+ await pass(engine);
+ expect(remoteHead(repo)).toBe(head(repo));
+ expect(await latestGitEffect(engine)).toMatchObject({ state: 'committed', outcome: { push: 'committed' } });
+ }), 300_000);
+
+ test('managed sync imports a page committed under the subdirectory root and an edit to it', () => withBrain(kind, async ({ engine, home, ctx }) => {
+ const { top, repo } = await subdirRepo(engine, home);
+ await putAndPublish(engine, repo, ctx('default'), 1);
+ const page = `${SUBDIR}/notes/synced.md`;
+ mkdirSync(join(top.root, SUBDIR, 'notes'), { recursive: true });
+ writeFileSync(join(top.root, page), '---\ntype: note\ntitle: Synced\n---\n\nFirst body.\n');
+ git(top.root, 'add', page); git(top.root, 'commit', '-q', '-m', 'Add synced');
+ await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true });
+ expect((await engine.readPageSnapshot('notes/synced', { sourceId: 'default' }))?.page.compiled_truth).toContain('First body.');
+ writeFileSync(join(top.root, page), '---\ntype: note\ntitle: Synced\n---\n\nSecond body.\n');
+ git(top.root, 'commit', '-q', '-am', 'Edit synced');
+ await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true });
+ expect((await engine.readPageSnapshot('notes/synced', { sourceId: 'default' }))?.page.compiled_truth).toContain('Second body.');
+ }), 300_000);
+
+ test('doctor git_convergence calls a subdirectory root stranded: commits ahead, then tracked pages nobody will commit', () => withBrain(kind, async ({ engine, home, ctx }) => {
+ const { top, repo } = await subdirRepo(engine, home);
+ await putAndPublish(engine, repo, ctx('default'), 1);
+ expect((await gitConvergenceCheck(engine))?.status).toBe('ok');
+
+ writeFileSync(join(top.root, 'outside.md'), 'outside\n');
+ git(top.root, 'add', 'outside.md'); git(top.root, 'commit', '-q', '-m', 'Local commit');
+ const ahead = await gitConvergenceCheck(engine);
+ expect(ahead).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', top.root], actor: 'agent' } });
+ expect((ahead!.details as { roots: unknown[] }).roots).toEqual([expect.objectContaining({ root: top.root, ahead: 1, stranded: true })]);
+ git(top.root, 'push', '-q');
+
+ writeFileSync(join(top.root, 'outside.md'), 'outside edit\n');
+ const outside = await gitConvergenceCheck(engine);
+ expect(outside?.status, JSON.stringify(outside)).toBe('ok');
+ const page = `${SUBDIR}/${pageSlug(1)}.md`;
+ writeFileSync(join(top.root, page), edited(1));
+ const dirty = await gitConvergenceCheck(engine);
+ expect(dirty).toMatchObject({ status: 'warn', fix: { ask_user: true, actor: 'user', argv: ['git', '-C', top.root, 'commit', '-m', 'gbrain: persist canonical memory update', '--', page],
+ then: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', top.root] } } });
+ expect((dirty!.details as { roots: unknown[] }).roots).toEqual([expect.objectContaining({ root: top.root, stranded: true, uncommitted_pages: [page] })]);
+ }), 300_000);
+});
+
+if (testBackends().includes('pglite')) describe('#7091 commitGitTargets on a root below the toplevel', () => {
+ test('commits a modified tracked file and a removal, each relative to the root', () => withBrain('pglite', async ({ home }) => {
+ const top = makeRepo(home, 'direct');
+ const root = join(top.root, SUBDIR);
+ mkdirSync(join(root, 'people'), { recursive: true });
+ writeFileSync(join(root, 'people', 'x.md'), 'x\n');
+ writeFileSync(join(root, 'people', 'y.md'), 'y\n');
+ git(top.root, 'add', '-A'); git(top.root, 'commit', '-q', '-m', 'Add');
+ writeFileSync(join(root, 'people', 'x.md'), 'x edited\n');
+ expect(await commitGitTargets(root, ['people/x.md'])).toEqual(new Map([['people/x.md', { git: 'committed' }]]));
+ expect(git(top.root, 'log', '-1', '--name-only', '--format=').trim()).toBe(`${SUBDIR}/people/x.md`);
+ rmSync(join(root, 'people', 'y.md'));
+ const removal = [...await commitGitTargets(root, ['people/y.md'])];
+ expect(removal, JSON.stringify(removal)).toEqual([['people/y.md', { git: 'committed' }]]);
+ expect(git(top.root, 'log', '-1', '--name-status', '--format=').trim()).toBe(`D\t${SUBDIR}/people/y.md`);
+ expect(git(top.root, 'status', '--porcelain').trim()).toBe('');
+ }), 120_000);
+});