Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(persistence): the 5530 coalescing file seeds through put_pages and the #6210 probe cases get their own file
garrytancf9e601decb2
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 0c2b4f50b1..75140ee857 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -42,7 +42,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file; `--json` writes the envelope through `writeJsonDocument`, so under the D2 guard it is the one stdout document. Tests: `test/sync-status-unblock.test.ts`, `test/cli-json-guard.test.ts`. #6402: `cancelled` (a knock-on window cancel) is a `page` / `retry` row, not needs_human, so `sync status` hands the loop the same retry sync's own `Next:` prints (`sync-cancelled-knock-on.test.ts`).- `src/core/persistence/sync-drain.ts` (#6340 additions) — `isConnectionDrop` (a retryable connection error that is not #6329's `CONNECTION_DESTROYED` / `CONNECTION_CLOSED` settle discard; `retry-matcher.ts` now matches `ECONNABORTED`, `ETIMEDOUT` and `EPIPE` beside `ECONNRESET`); `runDrain` reconnects (`DrainInput.reconnect`, `engine.reconnect` from `drainManagedSync`) and retries a dropped pass on `CONNECTION_RETRY_MS` (5/15/45 s), resets the count on every committed page, and after `CONNECTION_STRIKES` drops with no commit between them ends `blocked` / `connection_lost` with `drain.connection { drops, last_error }` (URLs stripped) and the resume command as a loopable `next` (`sync_drain_connection_lost` in the catalogue, `connection_lost` in the registry). `drainManagedSync` takes exactly one extra pass (`drain.extra_pass { from, to }`, counts merged by `mergeExtraPass`) when HEAD moved past the pinned target during a `synced` run, so a live checkout ends at HEAD without looping. Tests: `test/sync-drain-connection.test.ts`. In-pass governor: `src/core/persistence/drain-step.ts` — `runDrain` races every pass against a governor that runs with or without `announce`: the pass gets its own `AbortController`, the governor's head read is bounded (`GOVERN_PROBE_MS`, or the window when shorter), and on a stop the pass signal is aborted with `DrainPassAbandoned` (the pass's `assertActive` / `stampDrainStep` boundaries throw it, so it admits and writes nothing more; `stampDrainStep` does not throw the caller's own cancel, which still banks admitted work) and its late result or rejection is dropped. A head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; `PUBLICATION_CEILING_DEFAULT_MS`) stops `blocked` / `drain_stalled` / `publication_overdue` with `stall.in_pass` and a `next` that says restart (never a promised reclaim); a pass with no commit, no unfinished request and nothing changing for `IN_PASS_NO_PROGRESS_MS` (5 min) stops `no_admission`, an unchanged non-empty head `no_progress` / `owner_missing`; a live preparation is left to its own budget and ceiling. `drain-step.ts` holds the process-local step (`freeze`, `waiver_run`, `admission`, `await_receipt`, stamped in `sync-run.ts`) and the last statement label (`noteDrainSql`, from `waiveNoopRun`). `enterClaimPhase(clock, 'publishing')` stamps `waiting_on: 'publication'`. `drainManagedSync` prints one line when the sync's own pool is a transaction-mode pooler. `sync-waivers.ts` `waiveNoopRun` pipelines at most `WAIVER_PIPELINE_MAX` (64) calls per round trip and sends the next chunk only while the prefix holds. `commands/sync-delegate.ts`: a serve-delegated `no_admission` stop continues once with the CLI's own consumer (`serve_no_admission`); a `publication_overdue` stop is reported as it is. Tests: `test/sync-drain-inpass-stall.test.ts`, `test/sync-drain-no-admission.test.ts`, `test/sync-waivers-chunk.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). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory that `git-checkout.ts` `classifyGitCheckout` reads as `not_git` (no `.git` entry at or above it, no `GIT_DIR`) keeps `tree` scope. 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`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). #6510: `trackedBytes` checks for symlinks with `lstat` on every directory component between the canonical root and the leaf, then the leaf, on every read (no cache across files: a parent swapped to a symlink after the first file would otherwise let a later leaf read outside the root), reading through the Git spelling; the former `realpath(path) === path` proxy refused a checkout whose volume spells a name differently (APFS NFC/NFD, case-insensitive volumes) with no symlink anywhere. Tests: `test/persistence-manifest-git-scope.test.ts`, `test/worktree-manifest-unicode.test.ts` (synthetic realpath-spelling spy on Linux, parent-swap, case-spelling where the tmpdir is case-insensitive), `test/hardened-git-filters.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).+- `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`, `test/persistence-git-durability-probe-6210.slow.test.ts` (Postgres via `test/e2e/persistence-git-durability-probe-6210-postgres.test.ts`; fix wave 16 split it out of the 5530 coalescing file, whose fixture both share through `test/helpers/git-coalescing-fixture.ts`).- `src/core/persistence/consumer-election.ts` — #6317 (B1b): the consumer mode machine (`probing` → `full` | `waiter_only` → `promoted`) and `WaiterOnlyConsumer`, the `PersistenceConsumerLike` surface for a resident process (`sync`, `jobs`, `autopilot`, `mcp`) that found a live full consumer of this host and claims nothing: `wake()` is a no-op, settlement listeners still fire through `settledWaiters`, `status()` reports `waiter_only` with the owner's identity. `electOwner` re-probes every tick and promotes on the owner's progress (lapsed 60 s, wedged, not full, gone); a promoted consumer drains back after three healthy ticks of a `full` owner only, so promotion storms converge. `forceOwnConsumer(reason)` is `--no-delegate`'s process flag.- `src/core/persistence/consumer-lane.ts` — #6317 (reporter ask 2): `consumerStatementEngine`, the Proxy that routes the consumer's own tick statements (idle probe, switch read, recovery and expired-claim scans, capacity, releases, floor) to `executeRawDirect` while the dual pool is active (`GBRAIN_DIRECT_DATABASE_URL` or the Supabase-derived direct URL), so the owner's round-trips avoid a transaction-mode pooler; `status().connection = { lane, pooler_mode, direct_host? }` says which lane is in use, and one `[persistence] phase=start reason=transaction_pooler` line prints when only a `prepare=false` URL exists.- `src/core/persistence/consumer-diagnostics.ts` — #6317 (B3, I1): `hostConsumersReport` (the `host.consumers` block of `writer status --json`), `consumerOverlap` (two resident-kind full rows alive over 30 s), `ownersWithoutHeartbeat` (claim owners on running claims with no row) and `hostIdentityMismatches` (this process's `host.json` id differs from a binding owner's while the owner's checkout resolves on this filesystem or the machine id matches), read-only and shared by doctor and writer status.diff --git a/test/e2e/persistence-git-durability-probe-6210-postgres.test.ts b/test/e2e/persistence-git-durability-probe-6210-postgres.test.tsnew file mode 100644index 0000000000..bad33adb11--- /dev/null+++ b/test/e2e/persistence-git-durability-probe-6210-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../persistence-git-durability-probe-6210.slow.test.ts'));diff --git a/test/helpers/git-coalescing-fixture.ts b/test/helpers/git-coalescing-fixture.tsnew file mode 100644index 0000000000..8daa42cf59--- /dev/null+++ b/test/helpers/git-coalescing-fixture.ts@@ -0,0 +1,156 @@+/**+ * Shared fixture of the Git effect coalescing files (#5530) and the native Git durability probe+ * file (#6210): a hardened local repository with a push-counting bare remote, a brain per test+ * (PGLite, or a clone of one migrated Postgres template), and the paused-then-drained effect+ * runner that makes commit and push counts deterministic.+ *+ * Each test file creates its own fixture (`createGitCoalescingFixture`) and registers+ * `dispose` in its `afterAll`: the repository templates and the Postgres template are per file.+ */+import { expect } from 'bun:test';+import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+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 { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { PAGE_BATCH_MAX_PAGES, submitPageBatch } from '../../src/core/persistence/page-batch.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';+import { localHostId } from '../../src/core/persistence/identity.ts';+import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';+import { isolatedSharedSkillsEngine } from './shared-skills-engine.ts';+import { persistencePostgresTemplate } from './persistence-postgres.ts';+import { withEnv } from './with-env.ts';++export const HOOK = '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n';++export function git(root: string, ...args: string[]): string {+ const result = Bun.spawnSync(['git', '-C', root, ...args]);+ if (result.exitCode) throw new Error(`git ${args.join(' ')}: ${result.stderr.toString()}`);+ return result.stdout.toString();+}++export interface Repo { root: string; remote: string; pushes: () => number; rejectPushes: (on: boolean) => void; commits: () => number }++export interface CoalescingBrain { engine: BrainEngine; home: string; ctx: (source: string) => OperationContext }++export const pageContent = (i: number, note = '') => `---\ntype: note\ntitle: Page ${i}\n---\n\nCoalescing page ${i}.${note}\n`;+export const pageSlug = (i: number) => `notes/page-${String(i).padStart(4, '0')}`;++/** One page through `put_page`: the single writes a test observes (a target page, a probe) stay on this path. */+export async function putPage(ctx: OperationContext, i: number): Promise<Record<string, unknown>> {+ return await submitPageMutation(ctx, { operation: 'put_page', params: { slug: pageSlug(i), request_id: randomUUID(), content: pageContent(i) } }) as Record<string, unknown>;+}++/**+ * Setup-only pages through `put_pages` in batches of PAGE_BATCH_MAX_PAGES: one admission transaction+ * per batch instead of one write round per page, with the same `kind='git'` effect row per page (the+ * 5530 file asserts that equality). Batches are sequential, so effect ids follow page order.+ */+export async function seed(ctx: OperationContext, count: number, offset = 0): Promise<void> {+ for (let start = offset; start < offset + count; start += PAGE_BATCH_MAX_PAGES) {+ const pages = Array.from({ length: Math.min(PAGE_BATCH_MAX_PAGES, offset + count - start) }, (_, k) => ({ slug: pageSlug(start + k), content: pageContent(start + k) }));+ const receipt = await submitPageBatch(ctx, { request_id: randomUUID(), pages });+ expect(receipt.state).toBe('committed');+ }+}++/** `put_page` once per page, the pre-batch seed: kept for the seed-equality assertion only. */+export async function seedSequentially(ctx: OperationContext, count: number, offset = 0): Promise<void> {+ for (let i = offset; i < offset + count; i++) await putPage(ctx, i);+}++export async function bindSource(engine: BrainEngine, source: string, repo: Repo): Promise<void> {+ if (source !== 'default') await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2)', [source, repo.root]);+ else await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [repo.root]);+ await claimWorktree(engine, source, repo.root, localHostId());+}++/** Git effects are held back with a future `next_attempt_at` default while `run` writes, then the consumer is disposed. */+export async function pauseGitEffects<T>(engine: BrainEngine, run: () => Promise<T>): Promise<T> {+ await engine.executeRaw("ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT (now()+interval '1 hour')");+ try { return await run(); } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT now()');+ }+}++export const effectSql = (engine: BrainEngine, sql: string, params: unknown[] = []) =>+ engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw(sql, params); });+export const release = (engine: BrainEngine) => effectSql(engine, "UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git' AND state='queued'");+export const pass = (engine: BrainEngine) => runPersistenceEffects(engine, { engine: engine.kind, embedding_disabled: true } as never, { hostId: localHostId(), limit: 20 });+export const gitStates = async (engine: BrainEngine) => Object.fromEntries((await engine.executeRaw<{ state: string; n: number }>(+ "SELECT state, count(*)::int AS n FROM persistence_effects WHERE kind='git' GROUP BY state ORDER BY state")).map(r => [r.state, Number(r.n)]));++export function harden(repo: Repo): void {+ git(repo.root, 'add', '-A'); git(repo.root, 'commit', '-q', '-m', 'Seed', '--allow-empty'); git(repo.root, 'push', '-q');+ rmSync(join(repo.remote, '..', `${repo.root.split('/').pop()}.pushes`), { force: true });+ const hook = join(repo.root, '.git', 'hooks', 'post-commit');+ writeFileSync(hook, HOOK); chmodSync(hook, 0o755);+}++export function createGitCoalescingFixture(tag: string) {+ // Each repository shape is built once per file and copied per test: a fresh repository costs ten+ // git processes, and under CPU contention process startup dominated every test that made one.+ let repoTemplates: string | undefined;+ function repoTemplate(name: string): string {+ repoTemplates ??= realpathSync.native(mkdtempSync(join(tmpdir(), `gbrain-coalesce-${tag}-repos-`)));+ const root = join(repoTemplates, name), remote = join(repoTemplates, `${name}.git`);+ if (existsSync(remote)) return repoTemplates;+ mkdirSync(root); mkdirSync(remote);+ git(root, 'init', '-q', '-b', 'main');+ git(root, 'config', 'user.name', 'Example Writer');+ git(root, 'config', 'user.email', '[email protected]');+ writeFileSync(join(root, 'README.md'), `${name}\n`);+ git(root, 'add', 'README.md'); git(root, 'commit', '-q', '-m', 'Initial');+ git(remote, 'init', '-q', '--bare');+ git(root, 'remote', 'add', 'origin', remote); git(root, 'push', '-q', '-u', 'origin', 'main');+ return repoTemplates;+ }++ function makeRepo(home: string, name: string): Repo {+ const root = join(home, name), remote = join(home, `${name}.git`), log = join(home, `${name}.pushes`), reject = join(home, `${name}.reject`);+ const template = repoTemplate(name);+ cpSync(join(template, name), root, { recursive: true });+ cpSync(join(template, `${name}.git`), remote, { recursive: true });+ git(root, 'remote', 'set-url', 'origin', remote);+ const preReceive = join(remote, 'hooks', 'pre-receive');+ writeFileSync(preReceive, `#!/bin/sh\necho push >> '${log}'\n[ -f '${reject}' ] && exit 1\nexit 0\n`);+ chmodSync(preReceive, 0o755);+ return {+ root, remote,+ pushes: () => existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n').filter(Boolean).length : 0,+ rejectPushes: on => { if (on) writeFileSync(reject, ''); else rmSync(reject, { force: true }); },+ commits: () => Number(git(root, 'rev-list', '--count', 'HEAD').trim()),+ };+ }++ // PostgreSQL brains are clones of one migrated template database rather than a full migration run per test.+ let pgTemplate: ReturnType<typeof persistencePostgresTemplate> | undefined;++ async function withBrain(kind: 'pglite' | 'postgres', run: (b: CoalescingBrain) => Promise<void>) {+ const home = realpathSync.native(mkdtempSync(join(tmpdir(), `gbrain-coalesce-${tag}-`)));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = kind === 'postgres'+ ? await (pgTemplate ??= persistencePostgresTemplate(process.env.GBRAIN_TEST_COALESCE_PG!)).then(template => template.clone())+ : await isolatedSharedSkillsEngine();+ try {+ const ctx = (source: string) => ({ engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: source,+ remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } }) as OperationContext;+ await run({ engine, home, ctx });+ } finally { await disposePersistenceConsumer(engine); await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ }++ async function dispose(): Promise<void> {+ await (await pgTemplate)?.dispose();+ if (repoTemplates) rmSync(repoTemplates, { recursive: true, force: true });+ }++ return { makeRepo, withBrain, dispose };+}diff --git a/test/persistence-git-coalescing-5530.slow.test.ts b/test/persistence-git-coalescing-5530.slow.test.tsindex f2b1feef9a..9367bd65f7 100644--- a/test/persistence-git-coalescing-5530.slow.test.ts+++ b/test/persistence-git-coalescing-5530.slow.test.ts@@ -17,10 +17,9 @@* PGLite here; Postgres through test/e2e/persistence-git-coalescing-5530-postgres.test.ts.*/import { afterAll, describe, expect, test } from 'bun:test';-import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';+import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';-import { randomUUID } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';import type { BrainEngine } from '../src/core/engine.ts';import type { OperationContext } from '../src/core/ops/contract.ts';import { phaseCGrandfather } from '../src/commands/migrations/v0_13_1.ts';@@ -29,129 +28,74 @@ import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { disposePersistenceConsumer, startPersistenceConsumer } from '../src/core/persistence/service.ts';-import { runPersistenceEffects } from '../src/core/persistence/effects.ts';import { claimCoalescedGitEffects } from '../src/core/persistence/effect-journal.ts';import { localHostId } from '../src/core/persistence/identity.ts';-import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';-import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';-import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { type Repo, bindSource, createGitCoalescingFixture, effectSql, git, gitStates, harden, pageContent, pass, pauseGitEffects, putPage, release, seed, seedSequentially } from './helpers/git-coalescing-fixture.ts';-const HOOK = '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n';+const { makeRepo, withBrain, dispose } = createGitCoalescingFixture('5530');+afterAll(dispose);-function git(root: string, ...args: string[]): string {- const result = Bun.spawnSync(['git', '-C', root, ...args]);- if (result.exitCode) throw new Error(`git ${args.join(' ')}: ${result.stderr.toString()}`);- return result.stdout.toString();-}--interface Repo { root: string; remote: string; pushes: () => number; rejectPushes: (on: boolean) => void; commits: () => number }--// Each repository shape is built once per file and copied per test: a fresh repository costs ten-// git processes, and under CPU contention process startup dominated every test that made one.-let repoTemplates: string | undefined;-function repoTemplate(name: string): string {- repoTemplates ??= realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-coalesce-5530-repos-')));- const root = join(repoTemplates, name), remote = join(repoTemplates, `${name}.git`);- if (existsSync(remote)) return repoTemplates;- mkdirSync(root); mkdirSync(remote);- git(root, 'init', '-q', '-b', 'main');- git(root, 'config', 'user.name', 'Example Writer');- git(root, 'config', 'user.email', '[email protected]');- writeFileSync(join(root, 'README.md'), `${name}\n`);- git(root, 'add', 'README.md'); git(root, 'commit', '-q', '-m', 'Initial');- git(remote, 'init', '-q', '--bare');- git(root, 'remote', 'add', 'origin', remote); git(root, 'push', '-q', '-u', 'origin', 'main');- return repoTemplates;-}--function makeRepo(home: string, name: string): Repo {- const root = join(home, name), remote = join(home, `${name}.git`), log = join(home, `${name}.pushes`), reject = join(home, `${name}.reject`);- const template = repoTemplate(name);- cpSync(join(template, name), root, { recursive: true });- cpSync(join(template, `${name}.git`), remote, { recursive: true });- git(root, 'remote', 'set-url', 'origin', remote);- const preReceive = join(remote, 'hooks', 'pre-receive');- writeFileSync(preReceive, `#!/bin/sh\necho push >> '${log}'\n[ -f '${reject}' ] && exit 1\nexit 0\n`);- chmodSync(preReceive, 0o755);- return {- root, remote,- pushes: () => existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n').filter(Boolean).length : 0,- rejectPushes: on => { if (on) writeFileSync(reject, ''); else rmSync(reject, { force: true }); },- commits: () => Number(git(root, 'rev-list', '--count', 'HEAD').trim()),- };-}--function harden(repo: Repo): void {- git(repo.root, 'add', '-A'); git(repo.root, 'commit', '-q', '-m', 'Seed', '--allow-empty'); git(repo.root, 'push', '-q');- rmSync(join(repo.remote, '..', `${repo.root.split('/').pop()}.pushes`), { force: true });- const hook = join(repo.root, '.git', 'hooks', 'post-commit');- writeFileSync(hook, HOOK); chmodSync(hook, 0o755);-}--const pageContent = (i: number, note = '') => `---\ntype: note\ntitle: Page ${i}\n---\n\nCoalescing page ${i}.${note}\n`;--// PostgreSQL brains are clones of one migrated template database rather than a full migration run per test.-let pgTemplate: ReturnType<typeof persistencePostgresTemplate> | undefined;-afterAll(async () => {- await (await pgTemplate)?.dispose();- if (repoTemplates) rmSync(repoTemplates, { recursive: true, force: true });-});--async function withBrain(kind: 'pglite' | 'postgres', run: (b: { engine: BrainEngine; home: string; ctx: (source: string) => OperationContext }) => Promise<void>) {- const home = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-coalesce-5530-')));- try {- await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {- const { engine, close } = kind === 'postgres'- ? await (pgTemplate ??= persistencePostgresTemplate(process.env.GBRAIN_TEST_COALESCE_PG!)).then(template => template.clone())- : await isolatedSharedSkillsEngine();- try {- const ctx = (source: string) => ({ engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: source,- remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } }) as OperationContext;- await run({ engine, home, ctx });- } finally { await disposePersistenceConsumer(engine); await close(); }- });- } finally { rmSync(home, { recursive: true, force: true }); }-}--async function bindSource(engine: BrainEngine, source: string, repo: Repo): Promise<void> {- if (source !== 'default') await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2)', [source, repo.root]);- else await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [repo.root]);- await claimWorktree(engine, source, repo.root, localHostId());-}--async function seed(ctx: OperationContext, count: number, offset = 0): Promise<void> {- for (let i = offset; i < offset + count; i++) {- await submitPageMutation(ctx, { operation: 'put_page', params: { slug: `notes/page-${String(i).padStart(4, '0')}`, request_id: randomUUID(), content: pageContent(i) } });- }-}--async function pauseGitEffects<T>(engine: BrainEngine, run: () => Promise<T>): Promise<T> {- await engine.executeRaw("ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT (now()+interval '1 hour')");- try { return await run(); } finally {- await disposePersistenceConsumer(engine);- await engine.executeRaw('ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT now()');- }+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;}-const effectSql = (engine: BrainEngine, sql: string, params: unknown[] = []) =>- engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw(sql, params); });-const release = (engine: BrainEngine) => effectSql(engine, "UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git' AND state='queued'");-const pass = (engine: BrainEngine) => runPersistenceEffects(engine, { engine: engine.kind, embedding_disabled: true } as never, { hostId: localHostId(), limit: 20 });-const gitStates = async (engine: BrainEngine) => Object.fromEntries((await engine.executeRaw<{ state: string; n: number }>(- "SELECT state, count(*)::int AS n FROM persistence_effects WHERE kind='git' GROUP BY state ORDER BY state")).map(r => [r.state, Number(r.n)]));-const PAGES = Number(process.env.GBRAIN_TEST_COALESCE_PAGES ?? 250);// Six full groups whose commits each take a second: on master the write waits out about six seconds of them.const BACKLOG = 600, COMMIT_SLEEP_S = 1;/** Two full Git groups and one settle pass: the mixed-backlog probe needs a commit in flight, not the full-group depth. */const MIXED_BACKLOG = 200;+/** One full put_pages batch plus a partial one: the seed-equality check crosses a batch boundary. */+const SEED_EQUALITY_PAGES = 55;for (const kind of testBackends()) describe(`#5530 Git effect coalescing (${kind})`, () => {if (kind === 'postgres') process.env.GBRAIN_TEST_COALESCE_PG ??= process.env.DATABASE_URL;+ // Fix wave 16: setup seeds go through put_pages. The batch seed must leave the brain as the per-page+ // seed did: the same Git effect rows (payload, state, id order), the same page hashes, nothing committed.+ test('the put_pages seed leaves the same Git effect rows and page hashes as put_page per page', async () => {+ const snapshot = async (seeder: (ctx: OperationContext, count: number) => Promise<void>) => {+ let state: unknown;+ await withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ harden(repo);+ const commitsBefore = repo.commits();+ await pauseGitEffects(engine, () => seeder(ctx('default'), SEED_EQUALITY_PAGES));+ const effects = await engine.executeRaw<{ state: string; error_code: string | null; attempts: number; data: Record<string, unknown>; page: string }>(+ `SELECT e.state, e.error_code, e.attempts, e.data, p.slug AS page FROM persistence_effects e JOIN pages p ON p.id=(e.data->>'page_id')::int+ WHERE e.kind='git' ORDER BY e.id`);+ const pages = await engine.executeRaw<{ slug: string; content_hash: string }>('SELECT slug, content_hash FROM pages ORDER BY slug');+ // The written file carries `ingested_at`, so its hash differs between any two seeds: compare the+ // payload keys, the hash against the file it names, and the file with that one line removed.+ state = {+ effects: effects.map(e => {+ const file = readFileSync(join(repo.root, String(e.data.relative_path)), 'utf8');+ return { state: e.state, error_code: e.error_code, attempts: Number(e.attempts), page: e.page,+ keys: Object.keys(e.data).sort(), slug: e.data.slug, relative_path: e.data.relative_path,+ hash_matches_file: e.data.expected_hash === createHash('sha256').update(file).digest('hex'),+ file: file.replace(/^ingested_at: .*\n/m, '') };+ }),+ pages: pages.map(p => [p.slug, p.content_hash]),+ gitStates: await gitStates(engine), commits: repo.commits() - commitsBefore, pushes: repo.pushes(),+ };+ });+ return state as { effects: unknown[]; gitStates: Record<string, number>; commits: number };+ };+ const sequential = await snapshot(seedSequentially);+ expect(sequential.gitStates).toEqual({ queued: SEED_EQUALITY_PAGES });+ expect(sequential.commits).toBe(0);+ expect(sequential.effects.map(e => (e as { slug: string }).slug)).toEqual(Array.from({ length: SEED_EQUALITY_PAGES }, (_, i) => `notes/page-${String(i).padStart(4, '0')}`));+ expect(await snapshot(seed)).toEqual(sequential);+ }, 300_000);+test(`${PAGES} grandfathered pages give ${Math.ceil(PAGES / 100)} commits and 1 push; an interleaved write still completes`, () => withBrain(kind, async ({ engine, home, ctx }) => {const repo = makeRepo(home, 'content');await bindSource(engine, 'default', repo);@@ -257,7 +201,7 @@ for (const kind of testBackends()) describe(`#5530 Git effect coalescing (${kindconst repo = makeRepo(home, 'content');await bindSource(engine, 'default', repo);await activateSharedSkillPersistence(engine, { confirmQuiesced: true });- await seed(ctx('default'), 1, 500);+ await putPage(ctx('default'), 500);await disposePersistenceConsumer(engine);harden(repo);await pauseGitEffects(engine, () => seed(ctx('default'), 3));@@ -402,7 +346,7 @@ for (const kind of testBackends()) describe(`#5530 Git effect coalescing (${kindconst repo = makeRepo(home, 'content');await bindSource(engine, 'default', repo);await activateSharedSkillPersistence(engine, { confirmQuiesced: true });- await seed(ctx('default'), 1);+ await putPage(ctx('default'), 0);const binding = (await getWorktreeBinding(engine, 'default', localHostId()))!;const held = (await acquireWorktree(binding, 30_000, undefined, engine))!;try {@@ -518,156 +462,3 @@ for (const kind of testBackends()) describe(`#5530 Git effect coalescing (${kindexpect(await reference(100)).toHaveLength(6);}), 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'); return {}; }],- // Git's own switch for the "dubious ownership" refusal a checkout owned by another user gets. A runner's- // global or system config can trust every directory (safe.directory=*, common in CI images), which- // suppresses the refusal, so this case reads an empty global config and no system config.- ['dubious ownership', (repo: Repo) => {- const empty = join(repo.root, '..', 'empty-gitconfig');- writeFileSync(empty, '');- return { GIT_TEST_ASSUME_DIFFERENT_OWNER: '1', GIT_CONFIG_GLOBAL: empty, GIT_CONFIG_NOSYSTEM: '1' };- }],- ['a directory at the hook path', (repo: Repo) => { const hook = join(repo.root, '.git', 'custom-hooks', 'post-commit'); rmSync(hook); mkdirSync(hook); return {}; }],- ] as Array<[string, (repo: Repo) => Record<string, string>]>)('%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 {- const env = damage(repo);- if (env.GIT_TEST_ASSUME_DIFFERENT_OWNER) {- // Precondition: this git build must refuse the checkout under that env, or the case proves nothing.- const probe = Bun.spawnSync(['git', '-C', repo.root, 'rev-parse', '--git-path', 'hooks'], { env: { ...process.env, ...env, LC_ALL: 'C' } });- if (probe.exitCode === 0 || !probe.stderr.toString().includes('dubious ownership')) {- console.warn(`[#6210] skipped: this git (${Bun.spawnSync(['git', '--version']).stdout.toString().trim()}) does not refuse a checkout under GIT_TEST_ASSUME_DIFFERENT_OWNER (exit ${probe.exitCode})`);- return;- }- }- await withEnv(env, async () => { await release(engine); await pass(engine); });- } finally { 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);-});diff --git a/test/persistence-git-durability-probe-6210.slow.test.ts b/test/persistence-git-durability-probe-6210.slow.test.tsnew file mode 100644index 0000000000..6a4fa3a5d7--- /dev/null+++ b/test/persistence-git-durability-probe-6210.slow.test.ts@@ -0,0 +1,176 @@+/**+ * #6210: a native Git 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".+ *+ * Split out of test/persistence-git-coalescing-5530.slow.test.ts (fix wave 16):+ * the probe-timeout case alone waits the product's 10 s probe, and the 5530+ * file was running into the E2E per-file cap. The fixture is shared through+ * test/helpers/git-coalescing-fixture.ts.+ *+ * PGLite here; Postgres through test/e2e/persistence-git-durability-probe-6210-postgres.test.ts.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';+import { HOOK, type Repo, bindSource, createGitCoalescingFixture, git, gitStates, harden, pass, pauseGitEffects, release, seed } from './helpers/git-coalescing-fixture.ts';++const { makeRepo, withBrain, dispose } = createGitCoalescingFixture('6210');+afterAll(dispose);++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'); return {}; }],+ // Git's own switch for the "dubious ownership" refusal a checkout owned by another user gets. A runner's+ // global or system config can trust every directory (safe.directory=*, common in CI images), which+ // suppresses the refusal, so this case reads an empty global config and no system config.+ ['dubious ownership', (repo: Repo) => {+ const empty = join(repo.root, '..', 'empty-gitconfig');+ writeFileSync(empty, '');+ return { GIT_TEST_ASSUME_DIFFERENT_OWNER: '1', GIT_CONFIG_GLOBAL: empty, GIT_CONFIG_NOSYSTEM: '1' };+ }],+ ['a directory at the hook path', (repo: Repo) => { const hook = join(repo.root, '.git', 'custom-hooks', 'post-commit'); rmSync(hook); mkdirSync(hook); return {}; }],+ ] as Array<[string, (repo: Repo) => Record<string, string>]>)('%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 {+ const env = damage(repo);+ if (env.GIT_TEST_ASSUME_DIFFERENT_OWNER) {+ // Precondition: this git build must refuse the checkout under that env, or the case proves nothing.+ const probe = Bun.spawnSync(['git', '-C', repo.root, 'rev-parse', '--git-path', 'hooks'], { env: { ...process.env, ...env, LC_ALL: 'C' } });+ if (probe.exitCode === 0 || !probe.stderr.toString().includes('dubious ownership')) {+ console.warn(`[#6210] skipped: this git (${Bun.spawnSync(['git', '--version']).stdout.toString().trim()}) does not refuse a checkout under GIT_TEST_ASSUME_DIFFERENT_OWNER (exit ${probe.exitCode})`);+ return;+ }+ }+ await withEnv(env, async () => { await release(engine); await pass(engine); });+ } finally { 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);+});