Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): a failed durability probe keeps the Git effect unfinished; only a positively non-Git directory reads as not durable (#6210)
time-attack4b3abc2380bc
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex 2f9d213d10..b538e0ce31 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/audit-week-file.ts` — single source of truth for ISO-week audit JSONL filename math. Exports `isoWeek(d)`, `isoWeekFilename(prefix, now?)`, `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). Year-boundary correctness pinned by tests at 2020-W53 (the 53-week year), 2025-W01 rolling in from 2024-12-30 (Monday), 2026-W01. Four call sites: `src/core/minions/handlers/shell-audit.ts`, `src/core/facts/phantom-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/cycle/budget-meter.ts`. Each keeps its `compute<X>AuditFilename` thin wrapper.-- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a successful push or confirmation that the exact destination branch on origin contains the attempted commit and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). `isDurabilityHardenedAsync(repoPath)` is the non-blocking probe long-running persistence owners use; it and the persistence Git runner (`effect-git.ts`) spawn through `execFileBounded` (defined in the import-free `src/core/bounded-child-exec.ts` and re-exported here; `git-remote.ts` `pullRepo` shares it), which settles at its deadline or on abort from its own timer because Bun can drop a child's pipe events (still on 1.4.2) and, before 1.3.14, its exit event (oven-sh/bun#30301) when bun:test `expect().resolves/.rejects` re-enters the event loop; an unbounded wait there stranded `disposePersistenceConsumer` and hung every later test in the file (test: `test/bounded-child-exec.test.ts`). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `brain_remote_contains_commit` checks the exact `refs/heads/<branch>` at every effective push URL, fetches each advertised tip without writing `FETCH_HEAD`, and proves ancestry of the captured commit; branch existence, a different fetch destination, or a stale tracking ref is not enough. Probe diagnostics are suppressed, ambiguous URL resolution fails closed, and recovery is skipped if local HEAD has moved since the failed push. This check runs after a rejected push and after retry failure, logging `ok-already-on-remote` on confirmation; `getLastPushOutcome` recognizes it as success. Existing unmanaged installations must rerun `gbrain sources harden <source-id>` to refresh both the local hook and committed helper; upgrading the CLI alone does not rewrite those scripts. Managed worktrees retain the persistence outbox as their Git writer; generated legacy helpers refuse to bypass it. `GBRAIN_PUSH_LOCK_WAIT_SECONDS` (default 30, env-only) tunes the `flock -w` wait in the rendered push-retry block that both the committed helper and the local hook share; on lock timeout the synchronous helper returns rc 1 (fail-loud, no push was attempted) while the detached post-commit hook returns rc 0 (another holder is already pushing — the designed coalescing outcome).+- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a successful push or confirmation that the exact destination branch on origin contains the attempted commit and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. `isDurabilityHardened(repoPath)` (the durability hook banner is installed) and `commitWriteThroughFile(repoPath, absPath, slug, action = 'write-through')` are the shared helpers every write-through sink (page write/delete, facts fence, timeline, lint --fix) uses to best-effort commit ONE file path-limited on a hardened repo — never throws, false on any failure; `action` only labels the subject (`gbrain: <action> <slug>`; `'delete write-through'` for removals). `isDurabilityHardenedAsync(repoPath)` is the owners' non-blocking probe (#6210: rejects `git_unavailable` when unsure); it and the persistence Git runner (`effect-git.ts`) spawn through `execFileBounded` (defined in the import-free `src/core/bounded-child-exec.ts` and re-exported here; `git-remote.ts` `pullRepo` shares it), which settles at its deadline or on abort from its own timer because Bun can drop a child's pipe events and, before 1.3.14, its exit event (oven-sh/bun#30301) when bun:test `expect().resolves/.rejects` re-enters the event loop; an unbounded wait there stranded `disposePersistenceConsumer` and hung every later test in the file (test: `test/bounded-child-exec.test.ts`). Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`. `brain_remote_contains_commit` checks the exact `refs/heads/<branch>` at every effective push URL, fetches each advertised tip without writing `FETCH_HEAD`, and proves ancestry of the captured commit; branch existence, a different fetch destination, or a stale tracking ref is not enough. Probe diagnostics are suppressed, ambiguous URL resolution fails closed, and recovery is skipped if local HEAD has moved since the failed push. This check runs after a rejected push and after retry failure, logging `ok-already-on-remote` on confirmation; `getLastPushOutcome` recognizes it as success. Existing unmanaged installations must rerun `gbrain sources harden <source-id>` to refresh both the local hook and committed helper; upgrading the CLI alone does not rewrite those scripts. Managed worktrees retain the persistence outbox as their Git writer; generated legacy helpers refuse to bypass it. `GBRAIN_PUSH_LOCK_WAIT_SECONDS` (default 30, env-only) tunes the `flock -w` wait in the rendered push-retry block that both the committed helper and the local hook share; on lock timeout the synchronous helper returns rc 1 (fail-loud, no push was attempted) while the detached post-commit hook returns rc 0 (another holder is already pushing — the designed coalescing outcome).- `src/core/content-sanity-literals.ts` — operator literal-substring loader. Reads `~/.gbrain/junk-substrings.txt`, one literal per non-comment non-blank line; optional `# name=<id>` header pairs an identifier with the following literal so audit JSONL groups by site (`linkedin_auth_wall`, `reddit_blocked`, etc.). Fail-soft on ENOENT (missing file = empty array). Loaded on every ingest. Deliberately literal substrings (NOT regex) to defeat ReDoS. Pinned by `test/content-sanity-literals.test.ts`.diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 397965bf47..ee1151bb7d 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -5,7 +5,7 @@Fix wave 11's managed-sync and persistence modules: claim phases and the`persistence_write_stall` doctor check (#6176), releasing a source claimedbefore activation (#6122), the `concurrent_write` sync hold (#6194) and-Git-scoped writer manifests (#6099). The modules they extend (consumer,+Git-scoped writer manifests (#6099); fix wave 12 adds the shared Git checkout classifier (#6210). The modules they extend (consumer,sync-run, sync-holds, deactivation, source lifecycle) are in[core persistence](core-persistence.md).@@ -13,3 +13,4 @@ sync-run, sync-holds, deactivation, source lifecycle) are in- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks, then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`). Tests: `test/persistence-manifest-git-scope.test.ts`.+- `src/core/git-checkout.ts` — #6210 (fix wave 12): `classifyGitCheckout(dir, env = process.env): 'git' | 'not_git' | 'unknown'` decides from the filesystem alone whether a directory is inside a Git checkout: `not_git` only when the directory exists and no `.git` entry (directory or gitdir file) is at or above it and `GIT_DIR` is unset; `unknown` for a missing directory or any lookup error other than absence. Git's own exit 128 is locale-dependent and also means a damaged HEAD, a bad gitdir or dubious ownership, so callers that soften "not a checkout" use this instead. `isDurabilityHardenedAsync` (`brain-repo-durability.ts`) returns false only for `not_git` or an absent hook; every other failure (a git probe run with `LC_ALL=C` failing, a timeout, an unreadable hook) rejects `git_unavailable`, and `runPersistenceEffects` (`persistence/effects.ts`) settles each cached per-root probe to `{durable}|{error}` and records the error on every coalesced effect, so the effects stay queued (and park after repeated failures) instead of completing as `durability_not_enabled`. Tests: `test/git-checkout.test.ts`, the `#6210` block of `test/persistence-git-coalescing-5530.slow.test.ts` (Postgres via its e2e twin).diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.tsindex 9b56c734df..98ad753385 100644--- a/src/core/brain-repo-durability.ts+++ b/src/core/brain-repo-durability.ts@@ -44,6 +44,9 @@ import { redactSecretsInText } from './minions/handlers/shell-redact.ts';import { ensureGbrainHome, resolveGbrainHome } from './gbrain-home.ts';import { binaryOnPath } from './execution-env.ts';import { loadFilingRules, type FilingRulesDoc } from './filing-audit.ts';+import { classifyGitCheckout } from './git-checkout.ts';+import { OperationError, opError } from './ops/contract.ts';+import { readFix } from './ops/op-fix.ts';// Bundled into the --compile binary as the fallback taxonomy for repos that// don't ship their own — see resolveFilingRules().import filingRulesDoc from '../../skills/_brain-filing-rules.json';@@ -485,29 +488,53 @@ export function isDurabilityHardened(repoPath: string): boolean {}}-/** A git probe that does not block the event loop; a failed probe reads as ''. */-async function gitOutput(repoPath: string, args: string[]): Promise<string> {- const { error, stdout } = await execFileBounded('git', ['-C', repoPath, ...args], { timeout: 10_000, env: { ...process.env, ...GIT_ENV } });- return error ? '' : stdout.trim();+/**+ * #6210: the durability probe never reads a failure as "not hardened". A+ * failed probe is `git_unavailable` and the caller keeps its Git effect+ * unfinished; only a directory that is positively not a Git checkout+ * (`classifyGitCheckout`) or a hook file that is absent reads as false.+ */+function durabilityProbeFailure(detail: string): OperationError {+ return opError('git_unavailable', 'Cannot determine whether native Git durability is enabled.',+ `${detail} This does not show that durability is off, so the Git effect stays unfinished and retries; nothing was committed or pushed for it yet. Check that the checkout is readable and that git works there (git status in the checkout), then read the owner's effect status.`,+ { fix: readFix('Shows the canonical owner and its pending Git effects, read-only.', { argv: ['gbrain', 'sources', 'writer', 'status', '--json'] }) });+}++/** A git probe that does not block the event loop. Exit 1 is an unset key for `config --get`; every other failure throws. */+async function gitProbe(repoPath: string, args: string[]): Promise<string> {+ const { error, stdout } = await execFileBounded('git', ['-C', repoPath, ...args],+ { timeout: 10_000, env: { ...process.env, ...GIT_ENV, LC_ALL: 'C', LANGUAGE: 'C' } });+ if (!error) return stdout.trim();+ if (error.code === 1 && args[0] === 'config' && args[1] === '--get') return '';+ const status = typeof error.code === 'number' ? `exit ${error.code}` : typeof error.code === 'string' && /^[A-Z_]+$/.test(error.code) ? error.code : 'no exit status';+ throw durabilityProbeFailure(`git ${args.slice(0, 2).join(' ')} failed (${status}).`);}/*** {@link isDurabilityHardened} for long-running owners: the same two git* probes, run concurrently as child processes the event loop does not wait on.+ * Rejects with `git_unavailable` when it cannot tell (#6210).*/export async function isDurabilityHardenedAsync(repoPath: string): Promise<boolean> {+ const checkout = classifyGitCheckout(repoPath);+ if (checkout === 'not_git') return false;+ if (checkout === 'unknown') throw durabilityProbeFailure('The checkout directory, or a parent directory, could not be read.');+ const [hooksPath, gitHooks] = await Promise.all([gitProbe(repoPath, ['config', '--get', 'core.hooksPath']),+ gitProbe(repoPath, ['rev-parse', '--git-path', 'hooks'])]);+ const reported = hooksPath || gitHooks;+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- repoPath is a registered local worktree root and the hooks path comes from git itself, resolved exactly as resolveHooksDir/gitDirPath do+ const dir = !reported ? join(repoPath, '.git', 'hooks') : isAbsolute(reported) ? reported : join(repoPath, reported);+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- fixed hook filename inside the git-reported hooks directory, as in isDurabilityHardened+ const hookPath = join(dir, 'post-commit');+ let hook: string;try {- const [hooksPath, gitHooks] = await Promise.all([gitOutput(repoPath, ['config', '--get', 'core.hooksPath']),- gitOutput(repoPath, ['rev-parse', '--git-path', 'hooks'])]);- const reported = hooksPath || gitHooks;- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- repoPath is a registered local worktree root and the hooks path comes from git itself, resolved exactly as resolveHooksDir/gitDirPath do- const dir = !reported ? join(repoPath, '.git', 'hooks') : isAbsolute(reported) ? reported : join(repoPath, reported);- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- fixed hook filename inside the git-reported hooks directory, as in isDurabilityHardened- const hookPath = join(dir, 'post-commit');- return existsSync(hookPath) && readFileSync(hookPath, 'utf-8').includes(HOOK_BANNER);- } catch {- return false;+ hook = readFileSync(hookPath, 'utf-8');+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code === 'ENOENT' || code === 'ENOTDIR') return false;+ throw durabilityProbeFailure(`The post-commit hook could not be read (${typeof code === 'string' && /^E[A-Z]+$/.test(code) ? code : 'read error'}).`);}+ return hook.includes(HOOK_BANNER);}/**diff --git a/src/core/git-checkout.ts b/src/core/git-checkout.tsnew file mode 100644index 0000000000..c67b80e6a9--- /dev/null+++ b/src/core/git-checkout.ts@@ -0,0 +1,49 @@+/**+ * Whether a directory is positively NOT inside a Git checkout, decided from+ * the filesystem alone (fix wave 12, W1.1 / #6210; shared with the writer+ * manifest scope check).+ *+ * Git's own "not a git repository" answer is exit 128 with locale-dependent+ * stderr, and exit 128 also means a damaged HEAD, a bad gitdir file or a+ * refused ("dubious ownership") checkout. Callers that turn "not a checkout"+ * into a softer outcome (durability not enabled, hash the plain tree) must+ * not inherit those failures, so this reads only the filesystem:+ *+ * - `not_git`: no `.git` entry (directory or gitdir file) at the directory or+ * any ancestor, and no `GIT_DIR` in the environment.+ * - `git`: a `.git` entry exists at or above the directory (or `GIT_DIR` is+ * set); whether Git can use it is the Git probe's question.+ * - `unknown`: the directory itself is missing or not a directory, or a+ * lookup failed for any reason other than absence (EACCES, ELOOP, I/O).+ * Callers treat it like a failed Git probe.+ *+ * Git can stop discovery earlier (GIT_CEILING_DIRECTORIES, a filesystem+ * boundary); this reports `git` there and the Git probe then fails, which+ * callers treat as unavailable: fail closed, never "not a checkout".+ */+import { lstatSync, statSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';++export type GitCheckoutClass = 'git' | 'not_git' | 'unknown';++export function classifyGitCheckout(dir: string, env: NodeJS.ProcessEnv = process.env): GitCheckoutClass {+ if (env.GIT_DIR) return 'git';+ let current = resolve(dir);+ try {+ if (!statSync(current).isDirectory()) return 'unknown';+ } catch {+ return 'unknown';+ }+ for (;;) {+ try {+ lstatSync(join(current, '.git'));+ return 'git';+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code !== 'ENOENT' && code !== 'ENOTDIR') return 'unknown';+ }+ const parent = dirname(current);+ if (parent === current) return 'not_git';+ current = parent;+ }+}diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex cb98bf8298..e0521d998f 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -542,8 +542,11 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC// effect; a push failure leaves the whole group retryable (the next pass// finds nothing to commit and pushes once). Nothing holds a lock or a// database connection while waiting.- const probes = new Map<string, Promise<boolean>>();- const deferred: { effects: PersistenceEffect[]; binding: WorktreeBinding; hardened: Promise<boolean> }[] = [];+ // #6210: each cached probe settles to a value, so a failed probe is never an+ // unhandled rejection while it waits in the map; it fails every effect it covers.+ type DurabilityProbe = { durable: boolean } | { error: unknown };+ const probes = new Map<string, Promise<DurabilityProbe>>();+ const deferred: { effects: PersistenceEffect[]; binding: WorktreeBinding; hardened: Promise<DurabilityProbe> }[] = [];const unpushed = new Map<string, { binding: WorktreeBinding; items: { effect: PersistenceEffect; git: string; target?: string }[] }>();const commitGroup = async (effects: PersistenceEffect[], binding: WorktreeBinding & { local_path: string }) => {// A short group yields to publications still queued for its worktree, so a@@ -611,7 +614,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC} catch (error) { await recordFailure(engine, effect, error, opts.signal); continue; }if (effect.kind === 'git' && binding?.local_path) {const root = binding.local_path;- if (!probes.has(root)) probes.set(root, isDurabilityHardenedAsync(root));+ if (!probes.has(root)) probes.set(root, isDurabilityHardenedAsync(root).then(durable => ({ durable }), error => ({ error })));const group = singleFileGitEffect(effect) && effect.worktree_id? [effect, ...await claimCoalescedGitEffects(engine, opts.hostId, effect.worktree_id, GIT_GROUP_SIZE - 1)] : [effect];deferred.push({ effects: group, binding, hardened: probes.get(root)! });@@ -619,7 +622,12 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC}if (!deferred.length) break;for (const { effects, binding, hardened } of deferred.splice(0)) {- const durable = await hardened;+ const probe = await hardened;+ if ('error' in probe) {+ for (const effect of effects) await recordFailure(engine, effect, probe.error, opts.signal);+ continue;+ }+ const durable = probe.durable;if (durable && singleFileGitEffect(effects[0]!)) await commitGroup(effects, { ...binding, local_path: binding.local_path! });// Coalesced siblings run with their own source's binding (sources can share a worktree).else for (const effect of effects) {diff --git a/test/git-checkout.test.ts b/test/git-checkout.test.tsnew file mode 100644index 0000000000..66f734b9a2--- /dev/null+++ b/test/git-checkout.test.ts@@ -0,0 +1,44 @@+/** #6210 (fix wave 12, W1.1): the filesystem-only "is this a Git checkout" classifier. */+import { afterEach, expect, test } from 'bun:test';+import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { classifyGitCheckout } from '../src/core/git-checkout.ts';++const dirs: string[] = [];+const scratch = () => { const dir = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-git-checkout-'))); dirs.push(dir); return dir; };+afterEach(() => { for (const dir of dirs.splice(0)) { try { chmodSync(dir, 0o755); } catch {} rmSync(dir, { recursive: true, force: true }); } });+const noGitDir = {} as NodeJS.ProcessEnv;++test('a plain directory with no .git at or above it is not a checkout', () => {+ expect(classifyGitCheckout(join(scratch()), noGitDir)).toBe('not_git');+});++test('a .git directory or gitdir file at or above the directory makes it a checkout, whatever it contains', () => {+ const repo = scratch();+ mkdirSync(join(repo, '.git'));+ mkdirSync(join(repo, 'a', 'b'), { recursive: true });+ expect(classifyGitCheckout(join(repo, 'a', 'b'), noGitDir)).toBe('git');+ const linked = scratch();+ writeFileSync(join(linked, '.git'), 'gitdir: /nowhere\n');+ expect(classifyGitCheckout(linked, noGitDir)).toBe('git');+});++test('GIT_DIR in the environment defers to Git', () => {+ expect(classifyGitCheckout(scratch(), { GIT_DIR: '/elsewhere/.git' })).toBe('git');+});++test('a missing directory or a file is unknown, never "not a checkout"', () => {+ const dir = scratch();+ expect(classifyGitCheckout(join(dir, 'missing'), noGitDir)).toBe('unknown');+ writeFileSync(join(dir, 'file'), 'x');+ expect(classifyGitCheckout(join(dir, 'file'), noGitDir)).toBe('unknown');+});++test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('an unreadable parent is unknown', () => {+ const dir = scratch();+ mkdirSync(join(dir, 'locked', 'inner'), { recursive: true });+ chmodSync(join(dir, 'locked'), 0o000);+ try { expect(classifyGitCheckout(join(dir, 'locked', 'inner'), noGitDir)).toBe('unknown'); }+ finally { chmodSync(join(dir, 'locked'), 0o755); }+});diff --git a/test/persistence-git-coalescing-5530.slow.test.ts b/test/persistence-git-coalescing-5530.slow.test.tsindex b9e9371ce9..93ba2c18fd 100644--- a/test/persistence-git-coalescing-5530.slow.test.ts+++ b/test/persistence-git-coalescing-5530.slow.test.ts@@ -286,3 +286,141 @@ for (const kind of testBackends()) describe(`#5530 Git effect coalescing (${kind.toEqual(new Set(['durability_not_enabled']));}), 300_000);});++// #6210 (fix wave 12, W1.1): a durability probe that cannot tell must keep the+// Git effect unfinished (`git_unavailable`); only a directory that is positively+// not a Git checkout, or an absent hook, reads as "durability not enabled".+const gitEffects = (engine: BrainEngine) => engine.executeRaw<{ state: string; error_code: string | null; outcome: { reason?: string } | null }>(+ "SELECT state,error_code,outcome FROM persistence_effects WHERE kind='git' ORDER BY id");+function plainDir(home: string, name: string): Repo {+ const root = join(home, name);+ mkdirSync(root);+ writeFileSync(join(root, 'README.md'), `${name}\n`);+ return { root, remote: '', pushes: () => 0, rejectPushes: () => {}, commits: () => 0 };+}+function stubGit(home: string, body: string): string {+ const dir = join(home, `stub-git-${randomUUID()}`);+ mkdirSync(dir);+ writeFileSync(join(dir, 'git'), `#!/bin/sh\n${body}\n`);+ chmodSync(join(dir, 'git'), 0o755);+ return dir;+}+// The hook lives in a configured core.hooksPath, as `gbrain sources harden` installs it when one is set:+// a probe failure must not fall back to .git/hooks, find nothing there and read as "not hardened".+function hardenCustomHooks(repo: Repo): void {+ harden(repo);+ rmSync(join(repo.root, '.git', 'hooks', 'post-commit'));+ const custom = join(repo.root, '.git', 'custom-hooks');+ mkdirSync(custom);+ writeFileSync(join(custom, 'post-commit'), HOOK); chmodSync(join(custom, 'post-commit'), 0o755);+ git(repo.root, 'config', 'core.hooksPath', custom);+}+async function expectUnfinished(engine: BrainEngine, count: number): Promise<void> {+ const effects = await gitEffects(engine);+ expect(effects.length).toBe(count);+ for (const effect of effects) expect(effect).toMatchObject({ state: 'queued', error_code: 'git_unavailable', outcome: null });+}++for (const kind of testBackends()) describe(`#6210 native Git durability probe failures (${kind})`, () => {+ if (kind === 'postgres') process.env.GBRAIN_TEST_COALESCE_PG ??= process.env.DATABASE_URL;++ test.each([['C'], ['de_DE.UTF-8']])('a directory that is not a Git checkout completes as durability_not_enabled (LANG=%s)', (lang) => withBrain(kind, async ({ engine, home, ctx }) => {+ const plain = plainDir(home, 'plain');+ await bindSource(engine, 'default', plain);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ await pauseGitEffects(engine, () => seed(ctx('default'), 2));+ await withEnv({ LANG: lang, LC_ALL: lang === 'C' ? undefined : lang, LC_MESSAGES: lang === 'C' ? undefined : lang }, async () => { await release(engine); await pass(engine); });+ const effects = await gitEffects(engine);+ expect(effects.map(e => [e.state, e.outcome?.reason])).toEqual([['committed', 'durability_not_enabled'], ['committed', 'durability_not_enabled']]);+ }), 300_000);++ test('a hardened repository still commits under a non-C locale', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ harden(repo);+ const before = repo.commits();+ await pauseGitEffects(engine, () => seed(ctx('default'), 2));+ await withEnv({ LANG: 'de_DE.UTF-8', LC_ALL: 'de_DE.UTF-8' }, async () => { await release(engine); await pass(engine); });+ expect(await gitStates(engine)).toEqual({ committed: 2 });+ expect(repo.commits() - before).toBe(1);+ }), 300_000);++ test.each([+ ['damaged HEAD', (repo: Repo) => writeFileSync(join(repo.root, '.git', 'HEAD'), 'not a ref\n')],+ ['dubious ownership', () => { process.env.GIT_TEST_ASSUME_DIFFERENT_OWNER = '1'; }],+ ['a directory at the hook path', (repo: Repo) => { const hook = join(repo.root, '.git', 'custom-hooks', 'post-commit'); rmSync(hook); mkdirSync(hook); }],+ ])('%s keeps Git effects unfinished with git_unavailable', (_name, damage) => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ hardenCustomHooks(repo);+ await pauseGitEffects(engine, () => seed(ctx('default'), 2));+ const before = repo.commits();+ try {+ damage(repo);+ await release(engine); await pass(engine);+ } finally { delete process.env.GIT_TEST_ASSUME_DIFFERENT_OWNER; writeFileSync(join(repo.root, '.git', 'HEAD'), 'ref: refs/heads/main\n'); }+ await expectUnfinished(engine, 2);+ expect(repo.commits()).toBe(before); expect(repo.pushes()).toBe(0);+ }), 300_000);++ test('a .git file naming a missing gitdir keeps Git effects unfinished', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const plain = plainDir(home, 'linked');+ await bindSource(engine, 'default', plain);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ await pauseGitEffects(engine, () => seed(ctx('default'), 2));+ writeFileSync(join(plain.root, '.git'), `gitdir: ${join(home, 'missing-gitdir')}\n`);+ await release(engine); await pass(engine);+ await expectUnfinished(engine, 2);+ }), 300_000);++ test.each([+ ['git that outlives the probe timeout', 'exec sleep 30'],+ ['git that cannot run', 'exit 126'],+ ])('%s keeps Git effects unfinished', (_name, body) => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ hardenCustomHooks(repo);+ await pauseGitEffects(engine, () => seed(ctx('default'), 2));+ const stub = stubGit(home, body);+ await withEnv({ PATH: `${stub}:${process.env.PATH}` }, async () => { await release(engine); await pass(engine); });+ await expectUnfinished(engine, 2);+ }), 300_000);++ // Windows chmod cannot remove search permission; root bypasses it.+ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('an unreadable hooks directory is not absent durability', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ hardenCustomHooks(repo);+ await pauseGitEffects(engine, () => seed(ctx('default'), 2));+ const hooks = join(repo.root, '.git', 'custom-hooks');+ chmodSync(hooks, 0o000);+ try { await release(engine); await pass(engine); } finally { chmodSync(hooks, 0o755); }+ await expectUnfinished(engine, 2);+ expect(repo.pushes()).toBe(0);+ }), 300_000);++ test('a failed probe fails every coalesced sibling of a shared worktree, with no unhandled rejection', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ mkdirSync(join(repo.root, 'nested'));+ await bindSource(engine, 'default', repo);+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('nested', 'nested', $1)", [join(repo.root, 'nested')]);+ await claimWorktree(engine, 'nested', join(repo.root, 'nested'), localHostId());+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ hardenCustomHooks(repo);+ await pauseGitEffects(engine, async () => { await seed(ctx('nested'), 2, 700); await seed(ctx('default'), 3); });+ const stub = stubGit(home, 'exit 126');+ const unhandled: unknown[] = [];+ const onUnhandled = (reason: unknown) => { unhandled.push(reason); };+ process.on('unhandledRejection', onUnhandled);+ try {+ await withEnv({ PATH: `${stub}:${process.env.PATH}` }, async () => { await release(engine); await pass(engine); });+ await new Promise(resolve => setTimeout(resolve, 50));+ } finally { process.off('unhandledRejection', onUnhandled); }+ expect(unhandled).toEqual([]);+ await expectUnfinished(engine, 5);+ }), 300_000);+});