Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6712 PR 4b lane A): worktree-less writes of the incarnation are open work (shadow finding a)
garrytan729fb8358508
diff --git a/src/core/persistence/sync-pass-batch.ts b/src/core/persistence/sync-pass-batch.tsindex a01c7900bc..f331897ad2 100644--- a/src/core/persistence/sync-pass-batch.ts+++ b/src/core/persistence/sync-pass-batch.ts@@ -62,13 +62,16 @@ export function passRequestId(passId: string, path: string, level: string | null* The converged watermark a pass records (design v3.2 §2.2): the worktree's highest request `sequence`, and the requests* (`r:<id>`) and Git effects (`e:<id>`) still open, at most `cap` (null above it: no idle until a full round re-reads).*/-export async function readConvergedWatermark(tx: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, selfRequestId: string | null, cap: number):+export async function readConvergedWatermark(tx: Pick<BrainEngine, 'executeRaw'>, scope: { worktreeId: string; sourceId: string; incarnation: string }, selfRequestId: string | null, cap: number):Promise<{ request_hwm: string; open_at_stamp: string[] | null }> {- const [hwm] = await tx.executeRaw<{ hwm: string | null }>('SELECT max(sequence)::text AS hwm FROM persistence_requests WHERE worktree_id=$1::uuid', [worktreeId]);+ // The worktree's requests and the incarnation's worktree-less ones (writes admitted with sync.write_through=false).+ const [hwm] = await tx.executeRaw<{ hwm: string | null }>(`SELECT GREATEST((SELECT max(sequence) FROM persistence_requests WHERE worktree_id=$1::uuid),+ (SELECT max(sequence) FROM persistence_requests WHERE worktree_id IS NULL AND source_id=$2 AND source_incarnation=$3::uuid))::text AS hwm`, [scope.worktreeId, scope.sourceId, scope.incarnation]);const open = await tx.executeRaw<{ id: string }>(`(SELECT 'r:'||request_id::text AS id FROM persistence_requests- WHERE worktree_id=$1::uuid AND state IN ('queued','running','recovering') AND request_id IS DISTINCT FROM $2::uuid LIMIT $3)+ WHERE state IN ('queued','running','recovering') AND (worktree_id=$1::uuid OR worktree_id IS NULL AND source_id=$4 AND source_incarnation=$5::uuid)+ AND request_id IS DISTINCT FROM $2::uuid LIMIT $3)UNION ALL (SELECT 'e:'||e.id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id- WHERE r.worktree_id=$1::uuid AND e.kind='git' AND e.state IN ('queued','running') LIMIT $3)`, [worktreeId, selfRequestId, cap + 1]);+ WHERE r.worktree_id=$1::uuid AND e.kind='git' AND e.state IN ('queued','running') LIMIT $3)`, [scope.worktreeId, selfRequestId, cap + 1, scope.sourceId, scope.incarnation]);return { request_hwm: hwm?.hwm ?? '0', open_at_stamp: open.length > cap ? null : open.map(row => row.id) };}diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 63b5544bfe..3bd4fec5ff 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -375,7 +375,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): PrassertActive();await assertDrainLease(tx, sourceId);await tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]);- const watermark = await readConvergedWatermark(tx, context.binding.worktree_id, null, OPEN_AT_STAMP_CAP);+ const watermark = await readConvergedWatermark(tx, { worktreeId: context.binding.worktree_id, sourceId, incarnation }, null, OPEN_AT_STAMP_CAP);value.obligations.converged = { target: head, at, ...watermark, parser_fp: parserFp, pack, selection_fp: selectionFp,last_full_at: kind === 'full' || !converged ? at : converged.last_full_at, passes_since_full: kind === 'full' || !converged ? 0 : converged.passes_since_full + 1 };Object.assign(value.obligations, { not_converged_streak: 0, mismatch: {}, stuck_since: null });diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 842c9c1869..b6b2e281e2 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -164,9 +164,12 @@ async function readAttestations(exec: Exec, kind: 'postgres' | 'pglite', sourceI}/** `U_db`: open requests of the worktree (the `persistence_requests_pending` index) and pending Git effects of the source. */-async function readOpenWork(exec: Exec, sourceId: string, worktreeId: string): Promise<{ pageIds: Set<number>; origins: Set<string>; statements: number }> {+async function readOpenWork(exec: Exec, sourceId: string, incarnation: string, worktreeId: string): Promise<{ pageIds: Set<number>; origins: Set<string>; statements: number }> {+ // A write admitted with sync.write_through=false carries no worktree (page-mutations.ts), so the incarnation's+ // worktree-less requests are open work too.const [requests, effects] = await Promise.all([exec.executeRaw<{ page_id: number | null; source_path: string | null; path: string | null }>(`SELECT page_id, intent->>'sourcePath' AS source_path, intent->>'path' AS path- FROM persistence_requests WHERE worktree_id=$1 AND state IN ('queued','running','recovering') AND source_id=$2`, [worktreeId, sourceId]),+ FROM persistence_requests WHERE state IN ('queued','running','recovering') AND source_id=$2 AND (worktree_id=$1 OR worktree_id IS NULL AND source_incarnation=$3::uuid)`,+ [worktreeId, sourceId, incarnation]),exec.executeRaw<{ page_id: number | null; path: string | null }>(`SELECT r.page_id, e.data->>'relative_path' AS pathFROM persistence_requests r JOIN persistence_effects e ON e.request_id=r.idWHERE r.worktree_id=$1 AND r.source_id=$2 AND e.kind='git' AND e.state IN ('queued','running')`, [worktreeId, sourceId])]);@@ -300,7 +303,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st// Issued together, the snapshot's statements pipeline on its one connection (PGLite runs them in turn).timed('I⋈P', () => withRoundSnapshot(engine, async exec => {const [read, work, markers, passRow] = await Promise.all([timed('pages', () => readPages(exec, engineKind, sourceId, incarnation)),- timed('open_work', () => readOpenWork(exec, sourceId, context.binding.worktree_id)), timed('markers', () => readMarkers(exec, sourceId, incarnation)),+ timed('open_work', () => readOpenWork(exec, sourceId, incarnation, context.binding.worktree_id)), timed('markers', () => readMarkers(exec, sourceId, incarnation)),timed('pass_row', () => readPassRow(exec, sourceId, incarnation))]);return { pages: read.rows, open: work, markers, passRow, statements: read.statements + work.statements + 2 };})),@@ -548,12 +551,14 @@ export async function passIdleProbe(engine: Pick<BrainEngine, 'executeRaw'>, inpconst [probe] = await engine.executeRaw<{ pass_row: Record<string, unknown> | null; newer: boolean; pending: boolean; still_open: number | string }>(`WITH pass AS (SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND fingerprint=$2)SELECT (SELECT value FROM pass) AS pass_row,- EXISTS (SELECT 1 FROM persistence_requests WHERE sequence > COALESCE($3::bigint, ((SELECT value FROM pass)->'obligations'->'converged'->>'request_hwm')::bigint, 0) AND worktree_id = $4) AS newer,- EXISTS (SELECT 1 FROM persistence_requests WHERE worktree_id = $4 AND state IN ('queued','running','recovering')) AS pending,- (SELECT count(*) FROM persistence_requests WHERE worktree_id = $4 AND state IN ('queued','running','recovering') AND 'r:'||request_id::text = ANY($5::text[]))+ EXISTS (SELECT 1 FROM persistence_requests WHERE sequence > COALESCE($3::bigint, ((SELECT value FROM pass)->'obligations'->'converged'->>'request_hwm')::bigint, 0)+ AND (worktree_id = $4 OR worktree_id IS NULL AND source_id = $6 AND source_incarnation = $7::uuid)) AS newer,+ EXISTS (SELECT 1 FROM persistence_requests WHERE state IN ('queued','running','recovering') AND (worktree_id = $4 OR worktree_id IS NULL AND source_id = $6 AND source_incarnation = $7::uuid)) AS pending,+ (SELECT count(*) FROM persistence_requests WHERE state IN ('queued','running','recovering') AND (worktree_id = $4 OR worktree_id IS NULL AND source_id = $6 AND source_incarnation = $7::uuid)+ AND 'r:'||request_id::text = ANY($5::text[]))+ (SELECT count(*) FROM persistence_effects e JOIN persistence_requests r ON r.id = e.request_idWHERE r.worktree_id = $4 AND e.kind = 'git' AND e.state IN ('queued','running') AND 'e:'||e.id::text = ANY($5::text[])) AS still_open`,- [MANAGED_SYNC_PASS_OP, `${input.sourceId}:${input.incarnation}`, input.requestHwm, input.worktreeId, [...input.openAtStamp]]);+ [MANAGED_SYNC_PASS_OP, `${input.sourceId}:${input.incarnation}`, input.requestHwm, input.worktreeId, [...input.openAtStamp], input.sourceId, input.incarnation]);return { passRow: probe?.pass_row ?? null, newer: probe?.newer === true, pending: probe?.pending === true, stillOpen: Number(probe?.still_open ?? 0) };}diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 463e19e6bc..972bad244a 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -517,7 +517,7 @@ async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncInawait recordPassTail(tx, row.source_id, p.passId!, { changed: stamp.changed, extract: stamp.extract });for (const path of stamp.releasedHolds) await releaseHold(tx, path);if (stamp.retryTaken.length) await clearGitHoldRetryPaths(tx, row.source_id, stamp.incarnation, stamp.retryTaken);- const watermark = await readConvergedWatermark(tx, row.worktree_id!, row.request_id, OPEN_AT_STAMP_CAP);+ const watermark = await readConvergedWatermark(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, incarnation: row.source_incarnation }, row.request_id, OPEN_AT_STAMP_CAP);const value: ManagedSyncPassValue = structuredClone(pass.value);const at = new Date().toISOString(), prior = value.obligations.converged;value.obligations.converged = { target: p.target, at, ...watermark,diff --git a/test/sync-pass-rulings-6712.test.ts b/test/sync-pass-rulings-6712.test.tsindex 011f16efa2..92a47b93a4 100644--- a/test/sync-pass-rulings-6712.test.ts+++ b/test/sync-pass-rulings-6712.test.ts@@ -14,6 +14,8 @@* class by it (`by_action`).* - b5: under `--full` or an open episode, a legacy-marked path imports (v3.1 §2.7).* - b6: the convergence receipt counts #6885 legacy twin pairs (`legacy_twin_pairs`) with legacy-twins' read-only scan.+ * - shadow finding (a): a write queued with sync.write_through=false (no worktree) is open work, so the changed file it+ * would race is `in_flight`; in working mode a committed `git rm` of a synced file reads absent (`delete`).** Each test fails on capy/6712-pr4b (8cda2764b): there a baseline-equal legacy marker settles every page-less file, a* re-screen-due hold falls through to `matched` or `legacy_same`, results carry no `classAction`, the receipt has no@@ -29,7 +31,9 @@ import type { OperationContext } from '../src/core/ops/contract.ts';import { classifySyncPath, type SyncPathState } from '../src/core/persistence/sync-classify.ts';import { MANAGED_SYNC_PASS_OP, readShadowLevel, shadowConvergence, SYNC_ORIGIN_DELETED_OP } from '../src/core/persistence/sync-pass.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';-import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { preparePageAdmission, submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { admitWrite } from '../src/core/persistence/journal.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { managedBrain } from './helpers/managed-brain.ts';import { waitFor } from './helpers/wait-for.ts';@@ -141,4 +145,24 @@ describe('#6712 PR 4b classifier rulings (pglite)', () => {expect(Object.fromEntries((receipt!.samples.dirty ?? []).map(sample => [sample.path, sample.action]))).toEqual({ 'notes/a.md': 'none', 'notes/b.md': 'repair' });expect(receipt!.legacy_twin_pairs).toBe(1);}, { setup }), 180_000);++ test('finding (a): a put_page queued with write-through off makes the changed file in_flight', () => managedBrain(async ({ engine, ctx, root }) => {+ await engine.setConfig('sync.write_through', 'false');+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A committed change of notes/a.')); commit(root, 'change a');+ await disposePersistenceConsumer(engine);+ const current = await engine.readPageSnapshot('notes/a', { sourceId: 'default' });+ const prepared = await preparePageAdmission(ctx, { operation: 'put_page', params: { slug: 'notes/a', request_id: randomUUID(), expected_revision: current!.revision,+ content: note('notes/a', 'A queued agent edit.') } });+ const row = await admitWrite(engine, prepared.admission!);+ expect({ state: row.state, worktree: row.worktree_id ?? null }).toEqual({ state: 'queued', worktree: null });+ expect(await classOf(engine, 'notes/a.md')).toMatchObject({ cls: 'import', settled: false, inFlight: true });+ }, { setup }), 180_000);++ test('finding (a): in working mode a committed git rm of a synced file is a delete, not an import of unreadable bytes', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ git(root, 'rm', '-q', 'notes/b.md'); commit(root, 'remove b');+ const level = await readShadowLevel(engine, { sourceId: 'default', workingTree: true });+ expect(level!.paths.find(entry => entry.path === 'notes/b.md')?.result).toMatchObject({ cls: 'delete', action: 'delete' });+ }, { setup }), 180_000);});