Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(effects): record a non-durable single-file Git group in one update with one guard per source

time-attack232c1ab9af07
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 358cc13ec0..ea01675da2 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -45,7 +45,7 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast
- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB. Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.
- `src/core/persistence/suffixed-slug.ts` — `.md`/`.mdx`-suffixed slugs (#4807). `preparePageAdmission` refuses a new put_page/put_pages slug ending in `.md`/`.mdx` before any journal row (`invalid_params`, why, suggestion naming the bare slug, read-only `get_page` fix and verify); a live page with that exact (source_id, slug) still updates and the put_page response carries `slug_advisory` (put under the bare slug, then delete_page). `suffixedSlugDryRun` serves put_page dry runs; `suffixedFrontmatterSlugHold` holds a file import whose frontmatter `slug:` identity ends in `.md` as `frontmatter_slug_conflict`. `validateSlug` and path-derived import slugs are unchanged. Test: `test/ingestion/put-page-write-through.test.ts`.
-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group shorter than 100 yields to publications still queued or running for its worktree (`retryEffect` with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group; the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.
+- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group shorter than 100 yields to publications still queued or running for its worktree (`retryEffect` with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group; the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.
- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`).
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index ba75ead993..7d4616182b 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -219,6 +219,9 @@ export async function pushGitRoot(root: string, signal?: AbortSignal): Promise<{
});
}
+/** The outcome a Git effect records when its root has no durability hook: no git command ran. */
+export const DURABILITY_NOT_ENABLED = { git: 'skipped', reason: 'durability_not_enabled', push: 'skipped' } as const;
+
/**
* Caller owns the native worktree lock. Never run pull, rebase, or legacy hooks.
* `hardened` is the caller's durability probe of `root`, taken before it locked
@@ -226,7 +229,7 @@ export async function pushGitRoot(root: string, signal?: AbortSignal): Promise<{
*/
export async function publishGitEffect(root: string, relativePath: string, signal?: AbortSignal,
hardened?: boolean, note?: GitCommitNote): Promise<Record<string, unknown>> {
- if (!(hardened ?? await isDurabilityHardenedAsync(root))) return { git: 'skipped', reason: 'durability_not_enabled', push: 'skipped' };
+ if (!(hardened ?? await isDurabilityHardenedAsync(root))) return { ...DURABILITY_NOT_ENABLED };
const outcome = (await commitGitTargets(root, [relativePath], signal, note ? new Map([[relativePath, note]]) : undefined)).get(relativePath)!;
if (outcome instanceof OperationError) throw outcome;
if (outcome.reason === 'target_absent') return outcome;
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index e4ad984a81..da84ef2dd6 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -30,8 +30,9 @@ import { prepareFileTarget } from './page-prepare.ts';
import { isSourceDbOnlySlug } from './source-storage.ts';
import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, failEffect, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect } from './effect-journal.ts';
import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';
-import { commitGitTargets, publishGitEffect, pushGitRoot } from './effect-git.ts';
+import { commitGitTargets, DURABILITY_NOT_ENABLED, publishGitEffect, pushGitRoot } from './effect-git.ts';
import { isDurabilityHardenedAsync } from '../brain-repo-durability.ts';
+import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';
import { dispatchFactsBackstopEffect } from './effect-facts.ts';
import { runLinksEffect } from './effect-links.ts';
import { PARK_AFTER_FAILURES, type EffectRecovery, type GitCommitNote, type PersistenceEffect, type SkippedTarget } from './effect-model.ts';
@@ -49,6 +50,9 @@ const embeddingsFix = (): Action => readFix('Reports whether this brain has a us
const writerBusy = (effect: Pick<PersistenceEffect, 'source_id'>) => opError('writer_busy', 'The canonical worktree is busy.',
`Another write holds source ${effect.source_id}'s canonical worktree. The committed write is unaffected and the effect worker tries this effect again shortly; nothing needs resubmitting.`,
{ fix: effectStatusFix(effect) });
+const ownerUnavailable = (effect: PersistenceEffect) => opError('owner_unavailable', 'The canonical effect owner is unavailable.',
+ `This host does not hold source ${effect.source_id}'s canonical worktree, so its ${effect.kind} effect waits for the owner. Check which host owns the source; the effect runs there.`,
+ { fix: effectStatusFix(effect) });
const recoveryFirst = (effect: Pick<PersistenceEffect, 'source_id'>) => opError('recovery_required', 'Canonical publication recovery must finish first.',
`An earlier publication in source ${effect.source_id}'s worktree is still being recovered, so this effect waits; the worker resumes it once recovery completes. Inspect the owner rather than resubmitting writes.`,
{ fix: effectStatusFix(effect) });
@@ -506,9 +510,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
const recordOnly = effect.kind === 'git' && hardened === false && !targetedWithdrawalEffect(effect) && !effect.data.source_scan;
try {
if (effect.worktree_id && !['embedding', 'facts-backstop', 'links'].includes(effect.kind)) {
- if (!binding) throw opError('owner_unavailable', 'The canonical effect owner is unavailable.',
- `This host does not hold source ${effect.source_id}'s canonical worktree, so its ${effect.kind} effect waits for the owner. Check which host owns the source; the effect runs there.`,
- { fix: effectStatusFix(effect) });
+ if (!binding) throw ownerUnavailable(effect);
lock = await acquireWorktree(binding, 0, undefined, engine);
if (!lock) throw writerBusy(effect);
if (recordOnly) { await lock.release(); lock = null; }
@@ -601,6 +603,57 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
for (const { effect, attempt } of targets) await recordFailure(engine, effect, error, opts.signal, attempt.target);
} finally { await lock.release(); }
};
+ // A group of single-file Git effects in a root without the durability hook
+ // runs no git command: each effect only records its outcome. The group takes
+ // each root's lock once, guards each source incarnation once, validates every
+ // path as before and records the plain outcomes in one statement, instead of
+ // a lock, a guard transaction and an update per effect.
+ const recordGroup = async (effects: PersistenceEffect[], first: WorktreeBinding) => {
+ const bindings = new Map<string, WorktreeBinding | null>([[effects[0]!.source_id, first]]);
+ const roots = new Map<string, unknown>();
+ const guards = new Map<string, unknown>();
+ const mirrors = new Map<string, boolean>();
+ const recorded: PersistenceEffect[] = [];
+ for (const effect of effects) {
+ const attempt: EffectAttempt = {};
+ try {
+ let binding = bindings.get(effect.source_id);
+ if (binding === undefined) bindings.set(effect.source_id, binding = await getWorktreeBinding(engine, effect.source_id, opts.hostId));
+ if (!binding) throw ownerUnavailable(effect);
+ const root = binding.local_path ?? '';
+ if (!roots.has(root)) {
+ const lock = await acquireWorktree(binding, 0, undefined, engine).catch(error => ({ error }));
+ if (lock && 'release' in lock) await lock.release();
+ roots.set(root, lock ? 'error' in lock ? lock.error : null : writerBusy(effect));
+ }
+ if (roots.get(root)) throw roots.get(root);
+ const key = `${effect.source_id}\0${effect.source_incarnation}`;
+ if (!guards.has(key)) guards.set(key, await engine.transaction(async tx => {
+ await guardEffectSource(tx, effect, opts.hostId);
+ const blocked = await tx.executeRaw('SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1', [effect.worktree_id]);
+ if (blocked.length) throw recoveryFirst(effect);
+ return null;
+ }).catch(error => error ?? new Error('effect guard failed')));
+ if (guards.get(key)) throw guards.get(key);
+ if (!binding.local_path) { await completeEffect(engine, effect, { git: 'skipped', reason: 'no_repo_configured' }); continue; }
+ if (!mirrors.has(effect.source_id)) mirrors.set(effect.source_id, await sourceMirrorReadOnly(engine, effect.source_id));
+ if (mirrors.get(effect.source_id)) { await completeEffect(engine, effect, { git: 'skipped', reason: 'mirror_read_only' }); continue; }
+ if (await singleFileGitTarget(engine, effect, { ...binding, local_path: binding.local_path }, attempt) !== null) recorded.push(effect);
+ } catch (error) { await recordFailure(engine, effect, error, opts.signal, attempt.target); }
+ }
+ if (!recorded.length) return;
+ try {
+ for (const effect of recorded) await faultPoint(EFFECT_FAULT_POINTS.git, { effectId: effect.id, requestId: effect.request_id, sourceId: effect.source_id });
+ await engine.executeRaw(`UPDATE persistence_effects e SET
+ state=CASE WHEN jsonb_array_length(COALESCE(e.data->'parked','[]'::jsonb))>0 THEN 'failed' ELSE 'committed' END,
+ error_code=CASE WHEN jsonb_array_length(COALESCE(e.data->'parked','[]'::jsonb))>0 THEN 'targets_parked' END,
+ data=e.data-'retry_slugs'-'target_failures'-'failing_target',execution_token=NULL,claim_expires_at=NULL,
+ outcome=$2::text::jsonb,updated_at=now()
+ FROM jsonb_to_recordset($1::text::jsonb) AS t(id bigint,token uuid)
+ WHERE e.id=t.id AND e.execution_token=t.token AND e.recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE}`,
+ [JSON.stringify(recorded.map(effect => ({ id: effect.id, token: effect.execution_token }))), JSON.stringify(DURABILITY_NOT_ENABLED)]);
+ } catch (error) { for (const effect of recorded) await recordFailure(engine, effect, error, opts.signal); }
+ };
// A deferred effect that requeues itself (a page walk advancing its cursor,
// or work unblocked by an earlier effect) is claimable again after the flush.
for (;;) {
@@ -629,6 +682,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
}
const durable = probe.durable;
if (durable && singleFileGitEffect(effects[0]!)) await commitGroup(effects, { ...binding, local_path: binding.local_path! });
+ else if (singleFileGitEffect(effects[0]!) && effects[0]!.worktree_id) await recordGroup(effects, binding);
// Coalesced siblings run with their own source's binding (sources can share a worktree).
else for (const effect of effects) {
let own: WorktreeBinding | null;
diff --git a/test/persistence-git-coalescing-5530.slow.test.ts b/test/persistence-git-coalescing-5530.slow.test.ts
index 9ab960a18f..2b61244c34 100644
--- a/test/persistence-git-coalescing-5530.slow.test.ts
+++ b/test/persistence-git-coalescing-5530.slow.test.ts
@@ -309,6 +309,57 @@ for (const kind of testBackends()) describe(`#5530 Git effect coalescing (${kind
expect(new Set((await engine.executeRaw<{ reason: string }>("SELECT outcome->>'reason' AS reason FROM persistence_effects WHERE kind='git'")).map(r => r.reason)))
.toEqual(new Set(['durability_not_enabled']));
}), 300_000);
+ // Wave 8: a group without the durability hook guards each source once and records its plain outcomes in one
+ // statement. Every other outcome (a replaced file, an unsafe path, an archived source) is unchanged.
+ test('without the durability hook, a group records its outcomes in one statement and one guard transaction per source', () => 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 });
+ await pauseGitEffects(engine, async () => { await seed(ctx('nested'), 3, 700); await seed(ctx('default'), 30); });
+ await release(engine);
+ const outcomeWrites: string[] = [];
+ let transactions = 0;
+ const executeRaw = engine.executeRaw, transaction = engine.transaction;
+ Object.assign(engine, {
+ executeRaw(this: BrainEngine, ...args: Parameters<BrainEngine['executeRaw']>) { if (/^UPDATE persistence_effects\b[\s\S]*outcome=/.test(args[0])) outcomeWrites.push(args[0]); return executeRaw.apply(this, args); },
+ transaction(this: BrainEngine, ...args: Parameters<BrainEngine['transaction']>) { transactions++; return transaction.apply(this, args); },
+ });
+ try { await pass(engine); } finally { Object.assign(engine, { executeRaw, transaction }); }
+ expect(await gitStates(engine)).toEqual({ committed: 33 });
+ expect(outcomeWrites).toHaveLength(1);
+ // Two guards (one per source) plus the pass's fixed claim transactions; one guard per effect made 37.
+ expect(transactions).toBeLessThanOrEqual(6);
+ }), 300_000);
+ test('without the durability hook, every effect of a mixed group keeps its own outcome', () => 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 });
+ await pauseGitEffects(engine, async () => { await seed(ctx('default'), 6); await seed(ctx('nested'), 2, 700); });
+ await effectSql(engine, `UPDATE persistence_effects SET data=jsonb_set(data,'{relative_path}','"../outside.md"')
+ WHERE id=(SELECT id FROM persistence_effects WHERE kind='git' ORDER BY id LIMIT 1 OFFSET 2)`);
+ writeFileSync(join(repo.root, 'notes', 'page-0004.md'), pageContent(4, ' Edited by hand.'));
+ await effectSql(engine, "UPDATE persistence_effects SET source_incarnation=gen_random_uuid() WHERE kind='git' AND source_id='nested'");
+ await release(engine);
+ await pass(engine);
+ const rows = await engine.executeRaw<{ slug: string; state: string; error_code: string | null; reason: string | null; git: string | null }>(`SELECT data->>'slug' AS slug,
+ state,error_code,outcome->>'reason' AS reason,outcome->>'git' AS git FROM persistence_effects WHERE kind='git' ORDER BY source_id,data->>'slug'`);
+ expect(rows.map(r => [r.slug, r.state, r.error_code, r.reason, r.git])).toEqual([
+ ['notes/page-0000', 'committed', null, 'durability_not_enabled', 'skipped'],
+ ['notes/page-0001', 'committed', null, 'durability_not_enabled', 'skipped'],
+ ['notes/page-0002', 'queued', 'source_changed', null, null],
+ ['notes/page-0003', 'committed', null, 'durability_not_enabled', 'skipped'],
+ ['notes/page-0004', 'committed', null, null, 'superseded'],
+ ['notes/page-0005', 'committed', null, 'durability_not_enabled', 'skipped'],
+ ['notes/page-0700', 'failed', 'source_changed', null, null],
+ ['notes/page-0701', 'failed', 'source_changed', null, null],
+ ]);
+ }), 300_000);
// Wave 7: the coalesced claim hoists its worktree-wide conditions into one InitPlan. This is the claim's
// predicate before that change, row by row; every state below must claim exactly the rows it selects.
test('the coalesced claim takes exactly the rows of the per-row reference predicate', () => withBrain(kind, async ({ engine, home, ctx }) => {