Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): mark a root no checkout tracks in its own directory, never the enclosing repo (#7988)
garrytan41807e055cc2
diff --git a/docs/architecture/canonical-writers.md b/docs/architecture/canonical-writers.mdindex c8401fbd84..ff6d77ba7f 100644--- a/docs/architecture/canonical-writers.md+++ b/docs/architecture/canonical-writers.md@@ -91,7 +91,8 @@ ancestors are resolved through symlinks, including a not-yet-created target.Records are refreshed when an engine connects and remain usable before a secondprocess opens local PGLite. Stale records conservatively refuse writes until averified drain and explicit administration cleanup. A shared 0600 refusal marker-inside git metadata (or `.gbrain-managed` for non-git roots) also protects supported+inside git metadata (or `.gbrain-managed` for a root no checkout tracks, such as a+connector clone a dotfiles home only encloses) also protects supportedcommands using another home. Marker existence never grants publication authority.The native worktree lock and database ownership rows grant authority. Registrydiff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 5b502954eb..31e304dce8 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -26,7 +26,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/idle-wait.ts` — GBRA-133 2a.4: `IdleWaiter`, the worker claim loop's idle poll wait. `wake(reason)` ends a wait in progress; a wake while the loop is claiming makes the next `wait()` a no-op (`skipped`) instead of being lost, and `claimStarted()` clears it. `idle` says whether a wait is in progress; `history` keeps the last 100 waits and how each ended (`timer`, `wake` with its reason, `skipped`, `stop`), the decisions `test/pathological/s-sync-queue-wake.test.ts` asserts on.- `src/core/autopilot-heartbeat.ts` — #7003: the autopilot daemon's heartbeat sidecar `autopilot.heartbeat.json` beside the lock (`autopilotHeartbeatPath()` in `src/core/autopilot-paths.ts`), written by `autopilot-daemon.ts` at the top of every tick (phase `cycle`) and before every sleep (phase `sleep`, `next_tick_at`). `daemonStaleAfterSeconds` grades it against the lock: stale once the lock is older than the next tick plus max(base interval, 120 s), or 6 x the daemon's base interval mid-cycle; null (the caller's flag rule) for a missing sidecar, one from another pid than the lock, or one older than the lock. `readDaemonStaleAfter` reads the lock's mtime and pid and applies it for `gbrain autopilot --status`. Tests: `test/pathological/s-7003-autopilot-heartbeat.test.ts` + its Postgres twin.-- `src/core/checkout-head.ts` — GBRA-133 2a.4: `readCheckoutHead(root)` for the autopilot HEAD probe: the git directory from the checkout's own `.git` entry (`enclosingGitMetadata`, `src/core/persistence/root-registry.ts`), one bounded `git rev-parse HEAD` (`execFileBounded`, 5 s, `GIT_OPTIONAL_LOCKS=0`), and which `GIT_OPERATION_MARKERS` entry (rebase, merge, cherry-pick, revert) is present. Null when git cannot read HEAD.+- `src/core/checkout-head.ts` — GBRA-133 2a.4: `readCheckoutHead(root)` for the autopilot HEAD probe: the git directory from the checkout's own `.git` entry (`enclosingGitMetadata`, `src/core/persistence/root-registry.ts`), one bounded `git rev-parse HEAD HEAD:./` (null for a root the enclosing checkout does not track, such as a connector clone under a dotfiles home; `execFileBounded`, 5 s, `GIT_OPTIONAL_LOCKS=0`), and which `GIT_OPERATION_MARKERS` entry (rebase, merge, cherry-pick, revert) is present. Null when git cannot read HEAD.- `src/core/minions/sync-queue-wake.ts` — GBRA-133 2a.4: wakes an idle `gbrain jobs work` claim loop when a `sync` job turns `waiting` in its queue. `chooseSyncQueueWake(engine, env)` picks `listen` only on a detected direct session (the engine's dual-pool direct route, or a pool whose `prepare` is not off, read through `consumerConnectionRoute` in persistence/consumer-lane.ts), `poll` behind a transaction pooler or an unknown pooler mode, `off` on PGLite or with `GBRAIN_WORKER_SYNC_WAKE=0`. `startSyncQueueWake` LISTENs on the `minion_jobs` channel (the schema's `notify_minion_job_change` trigger) and requires a probe NOTIFY to arrive within 3 s, else it polls; the poll reads one `minion_jobs` row every `GBRAIN_WORKER_SYNC_WAKE_POLL_MS` (default 1 s, 250 ms-5 s) only while the worker is idle. It logs one line naming the mode and never throws; the worker's own poll stays the backstop. Tests: `test/pathological/s-sync-queue-wake.test.ts` + `test/e2e/s-sync-queue-wake-postgres.test.ts` (listed in `scripts/e2e-backend-matrix.txt`, so it also runs through PgBouncer).- `src/core/minions/tool-write-identity.ts` — Binds a journal mutation to the persisted subagent execution coordinates with a deterministic UUIDv8 before dispatch. Legacy, gateway and oneshot replay preserve the same logical request across process restart; explicit caller IDs remain authoritative. `awaitCommittedToolWrite(job, toolName, dispatch)` wraps every subagent tool dispatch (legacy loop and resume, gateway execute and resume reconciliation, oneshot write loop and recovery): while the write is admitted but still pending it replays the same request ID through `replayWhilePending` (no model call, nothing new admitted) until the write is terminal, the job's signal aborts (the pause ends and the last pending error, receipt included, is rethrown), or the job deadline is closer than `WIRE_WRITE_WAIT_MAX_MS` plus `WRITE_ADMISSION_HEADROOM_MS` (45 s); a job without a deadline replays for the `MaintenanceWriteWait` base (30 s). Only then does the write leave the handler as `write_pending`, so a write that never commits holds the job (and a serial dream drain behind it) until that point. A terminal `failed` receipt and non-mutation tools are never replayed. Pending receipts leave tool ledgers pending for retry and never count as written pages. Pinned by `test/subagent-handler.test.ts`, `test/minions/subagent-pending-write-runners.test.ts`, `test/minions/subagent-oneshot.test.ts` and `test/e2e/subagent-gateway-resume-reconciliation.test.ts`.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex a918b2cda4..190b6f5fff 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -158,7 +158,7 @@ a receipt can report has a row here.| `writer_identity_invalid` | `writer_identity_invalid` | This host's local writer identity file is unreadable or has an unknown format. | Run `gbrain doctor` on the host; it names the identity file to repair. || `writer_not_initialized` | `writer_not_initialized` | The brain has no persistence identity yet, usually because migrations have not run. | Run `gbrain apply-migrations --yes` on the brain host. || <a id="managed-guard-page-children"></a>`writer_coordinator_required: canonical writer must use the persistence coordinator` on a tag, timeline or take write; on the client `storage_error: Publication failed (P0001)` | `writer_coordinator_required` (`storage_error` on the stored receipt) | On a managed brain whose `tags`, `timeline_entries` or `takes` table has a `source_id` column gbrain does not create, the managed writer guard of a gbrain older than v0.60.38.0 refuses every insert and update of those rows, including coordinated ones. gbrain v0.60.38.0 and later take those rows' source from their page and ignore the column; an uncoordinated delete of such a row on a live page is refused, as on every other brain. | Upgrade to v0.60.38.0 or later on the brain host, then follow its recovery steps in the [CHANGELOG](../../CHANGELOG.md#060380---2026-10-03) (or [repair](repair.md#recover-after-an-upgrade)): `gbrain sync … --no-pull`, `gbrain extract --stale`, `gbrain extract timeline --source db`, a previewed `gbrain facts relink`, then `gbrain repair failed-writes` (preview, then `--apply --expect <hash>`) for the refused `put_page`, `add_timeline_entry` and `remember` calls; see [failed writes](repair.md#failed-writes). |-| `writer_coordinator_required` | `writer_coordinator_required` | The operation needs managed persistence (the write coordinator) and this brain or call path does not use it. A file write refused because the path sits in a managed canonical worktree names that worktree in the message, and its `detail` reads `root=<directory> source=<id or unknown> evidence=<marker file, managed-root registry or source binding>`. | Run the operation through the command the message names, on a managed brain. When the brain is not managed and the evidence is an ownership file (`.gbrain-owner.json`, `.gbrain-owner-<hash>.json`, `.gbrain-managed`), check it with `gbrain sources writer status` before removing anything: a half-finished claim is finished or rolled back through writer administration. |+| `writer_coordinator_required` | `writer_coordinator_required` | The operation needs managed persistence (the write coordinator) and this brain or call path does not use it. A file write refused because the path sits in a managed canonical worktree names that worktree in the message, and its `detail` reads `root=<directory> source=<id or unknown> evidence=<marker file, managed-root registry or source binding>`. | Run the operation through the command the message names, on a managed brain. When the brain is not managed and the evidence is an ownership file (`.gbrain-owner.json`, `.gbrain-owner-<hash>.json`, `.gbrain-managed`), check it with `gbrain sources writer status` before removing anything: a half-finished claim is finished or rolled back through writer administration. A `gbrain-managed.json` an older gbrain wrote in a repository that only encloses a managed root (a dotfiles home) is named in the message; `gbrain sources writer deactivate` removes it (preview with `--dry-run --json`), then activate again. || `fact_already_expired` | `fact_already_expired` | The fact the write targets is already expired or withdrawn. | Nothing to do; list active facts to find the current one. || `source_writeback_required` | `source_writeback_required` | The write needs a correction to the source's repository files, and this caller or profile never writes them. | Make the correction in the source repository, then sync. || `writer_upgrade_required` | `writer_upgrade_required` | The brain's schema is older than this operation needs. | Run `gbrain upgrade` (or `gbrain apply-migrations --yes`) on the brain host. |diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 8e5fc61b38..f8d5361c1c 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1755 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned)src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1571 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +1 #7973 plain_directory_sync_7973 row+src/core/behavior-change-notice.ts 1572 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +1 #7973 plain_directory_sync_7973 row; +1 #7988 managed_marker_own_directory_7988 rowdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 1303f61889..d629002792 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1373,6 +1373,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.514.0', id: 'company_db_only_keep_8014', text: 'A company-brain source now keeps a live page under a declared `storage.db_only` directory when its file is not in the approved manifest, and keeps every such page while its gbrain.yml storage section is invalid, as other managed sources do; it used to delete them. The decision reads gbrain.yml at the approved commit, never the working tree.' },{ since: '0.60.514.0', id: 'redaction_marker_not_credential_7997', text: 'The transcript `labeled_credential` detector no longer reads an importer redaction marker (`login **<REDACTED:user-pattern>**`) as a typed user/password pair, so a correctly redacted page clears `gbrain transcripts audit-secrets`; a password written beside a marker is still found. The audit detector version moves to 3, so `gbrain doctor` asks for a fresh audit once.' },{ since: '0.60.516.0', id: 'plain_directory_sync_7973', text: '`gbrain sync` on a plain directory registered with `gbrain sources add --path <dir> --force` (no Git checkout at or above it) now imports its files into the source the way `gbrain import` does; it used to fail with a raw `git rev-parse` internal_error. There are no commits to diff, so a file removed from the directory keeps its page.' },+ { since: '0.60.516.0', id: 'managed_marker_own_directory_7988', text: 'Managed persistence now marks a root that no Git checkout tracks (a connector clone or plain directory under a dotfiles home) in its own directory instead of in the enclosing repository, so legacy writers elsewhere in that repository are no longer refused, and the autopilot HEAD probe no longer reads the enclosing repository\'s HEAD for it. A marker an older release already wrote there stays until `gbrain sources writer deactivate` removes it (preview with `--dry-run --json`; activate again afterwards), and a write it refuses now says so.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/checkout-head.ts b/src/core/checkout-head.tsindex cc7bac3b9f..8d5f0a3862 100644--- a/src/core/checkout-head.ts+++ b/src/core/checkout-head.ts@@ -14,8 +14,10 @@ import { enclosingGitMetadata } from './persistence/root-registry.ts';export async function readCheckoutHead(root: string): Promise<{ head: string; operation: string | null } | null> {const gitDir = enclosingGitMetadata(root);if (!gitDir) return null;- const r = await execFileBounded('git', ['-C', root, 'rev-parse', 'HEAD'], { timeout: 5_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });- const head = r.error ? '' : r.stdout.trim();+ // #7988: `HEAD:./` resolves only when the checkout tracks the root, so a root a checkout merely encloses (a connector+ // clone under a dotfiles home) has no HEAD instead of the enclosing repository's.+ const r = await execFileBounded('git', ['-C', root, 'rev-parse', 'HEAD', 'HEAD:./'], { timeout: 5_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });+ const head = r.error ? '' : r.stdout.split('\n')[0]!.trim();if (!/^[0-9a-f]{40,64}$/.test(head)) return null;return { head, operation: GIT_OPERATION_MARKERS.find(marker => existsSync(join(gitDir, marker))) ?? null };}diff --git a/src/core/persistence/filesystem-guard.ts b/src/core/persistence/filesystem-guard.tsindex ee17842c28..63a4d368f6 100644--- a/src/core/persistence/filesystem-guard.ts+++ b/src/core/persistence/filesystem-guard.ts@@ -1,10 +1,10 @@import { localHostId } from './identity.ts';import { AsyncLocalStorage } from 'node:async_hooks';-import { isAbsolute, relative, resolve, sep } from 'node:path';+import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';import { OperationError } from '../ops/contract.ts';import type { SqlEngine } from './model.ts';import { readManagedMode, readPersistenceBrain } from './managed-mode.ts';-import { canonicalFilesystemPath, managedRootMarkerFor, recordManagedRoots, registeredManagedRootRecords, type ManagedRootRecord } from './root-registry.ts';+import { canonicalFilesystemPath, checkoutGitMetadata, managedRootMarkerFor, recordManagedRoots, registeredManagedRootRecords, type ManagedRootRecord } from './root-registry.ts';interface FileCapability { roots: string[]; active: boolean; }const active = new AsyncLocalStorage<FileCapability>();@@ -65,10 +65,19 @@ export function assertManagedFilesystemWrite(path: string): void {// #5279: name the root, its source and the evidence, so a stray ownership file is findable.const error = new OperationError('writer_coordinator_required',`This path belongs to the managed canonical worktree ${managed.root}${managed.sourceId ? ` (source ${managed.sourceId})` : ''}.`,- 'Submit the change through the persistence coordinator; check the root with gbrain sources writer status.');+ staleEnclosingMarker(managed)+ ? `The evidence is ${managed.evidence}, which an older gbrain wrote in a repository that only encloses a managed root (#7988); gbrain no longer writes it there. `+ + 'Deactivation removes it: preview with gbrain sources writer deactivate --dry-run --json, run the printed command after the user agrees, then activate again.'+ : 'Submit the change through the persistence coordinator; check the root with gbrain sources writer status.');error.detail = `root=${managed.root} source=${managed.sourceId ?? 'unknown'} evidence=${managed.evidence}`;throw error;}+/** #7988: a Git-metadata marker whose checkout encloses registered roots but tracks none of them. */+function staleEnclosingMarker(managed: ManagedFilesystemRoot): boolean {+ if (basename(managed.evidence) !== 'gbrain-managed.json') return false;+ const roots = registeredManagedRootRecords().map(record => record.root).filter(root => root !== managed.root && encloses(managed.root, root));+ return roots.length > 0 && roots.every(root => checkoutGitMetadata(root) !== dirname(managed.evidence));+}/** Invalidate inherited async contexts before the owner releases the kernel lock. */export async function withFilesystemPublication<T>(roots: string[], fn: () => Promise<T>): Promise<T> {const context = { roots: roots.map(root => resolve(root)), active: true };diff --git a/src/core/persistence/root-registry.ts b/src/core/persistence/root-registry.tsindex 00339a67fb..3f89699e8f 100644--- a/src/core/persistence/root-registry.ts+++ b/src/core/persistence/root-registry.ts@@ -3,6 +3,8 @@ import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openimport { basename, dirname, isAbsolute, join, resolve } from 'node:path';import { configDir } from '../config.ts';import { flushDirectory } from '../fs-durable.ts';+import { gitChildEnv } from '../git-env.ts';+import { execFileSync } from '../spawn.ts';import { opError, OperationError } from '../ops/contract.ts';export interface ManagedRootRecord {@@ -33,6 +35,20 @@ export function enclosingGitMetadata(root: string): string | null {current = parent;}}+/**+ * #7988: the git metadata directory of the checkout `root` belongs to: its own `.git`, or an enclosing checkout whose HEAD+ * tracks `root` (a committed subdirectory). A directory a checkout only encloses (a connector clone or a plain directory+ * under a dotfiles home) belongs to none. A Git read that fails for another reason keeps the enclosing checkout.+ */+export function checkoutGitMetadata(root: string): string | null {+ const own = gitMetadataDirectory(root);+ if (own) return own;+ const enclosing = enclosingGitMetadata(root);+ if (!enclosing) return null;+ try { execFileSync('git', ['-C', root, 'rev-parse', '--verify', '--quiet', 'HEAD:./'], { stdio: 'ignore', timeout: 10_000, env: gitChildEnv() }); }+ catch (error) { if ((error as { status?: unknown }).status === 1) return null; }+ return enclosing;+}/** An idle refresh must not touch inode metadata, so chmod only when the mode differs (#5297). */function ensureMode(path: string, mode: number): void {if ((statSync(path).mode & 0o777) !== mode) chmodSync(path, mode);@@ -145,8 +161,9 @@ export function recordManagedRoots(brainId: string, records: ManagedRootRecord[]...(modeEpoch !== undefined ? { mode_epoch: modeEpoch } : {}) });changed = writePrivateRecord(file, value) || changed;if (existsSync(root) && statSync(root).isDirectory()) {- // #7338: a datastore is marked in its own directory, never in the metadata of a repository that happens to enclose it.- const metadata = record.datastore ? null : enclosingGitMetadata(root);+ // #7338/#7988: a datastore, or a root no checkout tracks, is marked in its own directory, never in the metadata of a+ // repository that only encloses it.+ const metadata = record.datastore ? null : checkoutGitMetadata(root);const marker = metadata ? join(metadata, 'gbrain-managed.json') : join(root, '.gbrain-managed');if (!existsSync(marker)) writePrivateRecord(marker, JSON.stringify({ version: 1, managed: true, brain_id: brainId, ...(modeEpoch !== undefined ? { mode_epoch: modeEpoch } : {}) }));}diff --git a/test/managed-root-marker-enclosing-7988.test.ts b/test/managed-root-marker-enclosing-7988.test.tsnew file mode 100644index 0000000000..b961849252--- /dev/null+++ b/test/managed-root-marker-enclosing-7988.test.ts@@ -0,0 +1,103 @@+/**+ * #7988: activation marked the Git repository that merely encloses a non-Git root (a connector clone or a gbrain-owned+ * content directory under a dotfiles \$HOME) as managed, by writing \`<home>/.git/gbrain-managed.json\`; every legacy+ * writer anywhere under \$HOME then refused \`writer_coordinator_required\`, and the autopilot HEAD probe read the dotfiles+ * HEAD as the root's. A root is marked in its enclosing checkout only when that checkout tracks it (its own \`.git\`, or a+ * committed subdirectory); any other root is marked in its own directory, like the datastore (#7338). A marker an older+ * release wrote is never rewritten: the refusal names the deactivate preview, and deactivation removes it.+ * PGLite always; Postgres too when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { readCheckoutHead } from '../src/core/checkout-head.ts';+import { assertLegacyFilesystemWriter, isManagedFilesystemPath, refreshManagedFilesystemRoots } from '../src/core/persistence/filesystem-guard.ts';+import { recordManagedRoots } from '../src/core/persistence/root-registry.ts';+import { deactivatePersistence } from '../src/core/persistence/deactivation.ts';+import { readPersistenceBrain } from '../src/core/persistence/managed-mode.ts';+import { settleManagedGitEffects, managedBrain } from './helpers/managed-brain.ts';+import { withEnv } from './helpers/with-env.ts';++const backends: Array<string | undefined> = [undefined, ...(process.env.DATABASE_URL ? [process.env.DATABASE_URL] : [])];+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+function commitAll(root: string): void {+ git(root, 'add', '.');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'dotfiles');+}+/** A dotfiles-style home beside the brain's content root: a Git repository tracking one dotfile and ignoring `.gbrain/`. */+function dotfilesHome(root: string): string {+ const home = join(dirname(root), 'user-home');+ mkdirSync(home, { recursive: true });+ git(home, 'init', '-q');+ writeFileSync(join(home, '.bashrc'), 'export EDITOR=vi\n');+ writeFileSync(join(home, '.gitignore'), '.gbrain/\n');+ commitAll(home);+ return home;+}++describe.each(backends.map(url => [url ? 'postgres' : 'pglite', url] as const))('managed roots under a Git home (%s)', (_name, url) => {+ test('a connector clone under a Git home is marked in its own directory, never in the home repository', () => managedBrain(async ({ engine, root }) => {+ const home = join(dirname(root), 'user-home'), connector = join(home, '.gbrain', 'clones', 'source-a-google');+ await refreshManagedFilesystemRoots(engine);+ expect(existsSync(join(home, '.git', 'gbrain-managed.json'))).toBe(false);+ expect(existsSync(join(connector, '.gbrain-managed'))).toBe(true);+ expect(isManagedFilesystemPath(join(home, '.gbrain', 'skillpack-bridge-state.json'))).toBe(false);+ expect(isManagedFilesystemPath(join(home, 'notes', 'todo.md'))).toBe(false);+ await assertLegacyFilesystemWriter(engine, join(home, '.gbrain', 'skillpack-bridge-state.json'));+ await expect(assertLegacyFilesystemWriter(engine, join(connector, 'mail.md'))).rejects.toMatchObject({ code: 'writer_coordinator_required' });+ await expect(assertLegacyFilesystemWriter(engine, join(root, 'note.md'))).rejects.toMatchObject({ code: 'writer_coordinator_required' });+ expect(await readCheckoutHead(connector)).toBeNull();+ }, { databaseUrl: url, setup: async ({ engine, root }) => {+ const connector = join(dotfilesHome(root), '.gbrain', 'clones', 'source-a-google');+ mkdirSync(connector, { recursive: true });+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('source-a','source-a',$1,'{\"kind\":\"google\"}')", [connector]);+ } }), 180_000);++ test('a marker an older release wrote in the enclosing repository is kept, named in the refusal, and removed by deactivation', () => managedBrain(async ({ engine, root }) => {+ const home = join(dirname(root), 'user-home'), marker = join(home, '.git', 'gbrain-managed.json');+ const brain = await readPersistenceBrain(engine);+ writeFileSync(marker, JSON.stringify({ version: 1, managed: true, brain_id: brain.brain_id, mode_epoch: Number(brain.mode_epoch) }));+ await refreshManagedFilesystemRoots(engine);+ expect(existsSync(marker)).toBe(true);+ await expect(assertLegacyFilesystemWriter(engine, join(home, '.gbrain', 'skillpack-bridge-state.json'))).rejects.toMatchObject({+ code: 'writer_coordinator_required', suggestion: expect.stringContaining('gbrain sources writer deactivate --dry-run --json') });+ await settleManagedGitEffects(engine);+ expect(await deactivatePersistence(engine, { requestId: randomUUID() })).toMatchObject({ mode: 'classic', deactivated: true });+ expect(existsSync(marker)).toBe(false);+ expect(isManagedFilesystemPath(join(home, '.gbrain', 'skillpack-bridge-state.json'))).toBe(false);+ }, { databaseUrl: url, setup: async ({ engine, root }) => {+ const connector = join(dotfilesHome(root), '.gbrain', 'clones', 'source-a-google');+ mkdirSync(connector, { recursive: true });+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('source-a','source-a',$1,'{\"kind\":\"google\"}')", [connector]);+ } }), 180_000);+});++test('a committed subdirectory of a checkout keeps the enclosing-checkout marker and HEAD', async () => {+ const base = mkdtempSync(join(tmpdir(), 'gbrain-monorepo-7988-'));+ try {+ await withEnv({ GBRAIN_HOME: join(base, 'gbrain-home') }, async () => {+ const repo = join(base, 'repo'), wiki = join(repo, 'wiki');+ mkdirSync(wiki, { recursive: true }); git(repo, 'init', '-q');+ writeFileSync(join(wiki, 'alice-example.md'), '---\ntitle: Alice Example\n---\nNotes.\n');+ commitAll(repo);+ recordManagedRoots(randomUUID(), [{ local_path: wiki, source_id: 'source-b' }]);+ expect(existsSync(join(repo, '.git', 'gbrain-managed.json'))).toBe(true);+ expect(existsSync(join(wiki, '.gbrain-managed'))).toBe(false);+ expect((await readCheckoutHead(wiki))?.head).toBe(git(repo, 'rev-parse', 'HEAD'));+ });+ } finally { rmSync(base, { recursive: true, force: true }); }+});++test('the HEAD probe reads no HEAD for a root its enclosing repository does not track', async () => {+ const base = mkdtempSync(join(tmpdir(), 'gbrain-head-7988-'));+ try {+ const home = dotfilesHome(join(base, 'content'));+ const clone = join(home, '.gbrain', 'clones', 'source-a-google');+ mkdirSync(clone, { recursive: true });+ expect(await readCheckoutHead(clone)).toBeNull();+ expect((await readCheckoutHead(home))?.head).toBe(git(home, 'rev-parse', 'HEAD'));+ } finally { rmSync(base, { recursive: true, force: true }); }+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 258635569e..629a45ec8f 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -239,6 +239,7 @@ test/managed-facts-withdrawn-skip-6506.test.tstest/managed-lint.test.tstest/managed-maintenance-links.test.tstest/managed-root-aliases-7203.test.ts+test/managed-root-marker-enclosing-7988.test.tstest/managed-sweep-corpus-windows.test.tstest/managed-sweep-refused-window-retry.test.tstest/managed-sweep-timeline.test.ts