Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(#6712 PR 4b lane M): shared-origin rule, helper and GC probes, page-row deleter lint, KEY_FILES entry

garrytan965e42eb18ce
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 7f7d4dd282..bb169c3440 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -21,6 +21,7 @@
- `src/core/persistence/sync-classify.ts` — the managed-sync level classifier (#6712 PR 4, design v3.2 §2.3): pure (no I/O), total, ordered, first match over one path's facts (`SyncPathState`: mode, `T[p]`, the level `L`, presence, `Dp`, the page and its import record, the attestation of its revision, hold, deletion marker, baseline blob, open work). Rows in order: `held`, `spelling`, `untracked`, `kept`, `delete`, `delete_drift`, `gone`, `deleted_same`, `deleted_edited`, `legacy_same`, `dirty`, `matched`, `adopt`, `reparse`, `db_ahead` (sub-labels `pending`/`db_only`/`unproven`; keep_db writes only `db_only` on a clean committed path; an open full obligation skips `db_only`/`unproven`), `import`, `legacy_unverified`, `keep_db`, `drift` (side `both` or `unknown`); then the overlay (unsettled with open work is `in_flight`). `syncClassAction` is the glossary tag (`none`, `owner`, `repair`); `syncPassKind` decides `idle`, `hold_only` or `full` from the converged state and every obligation. Tests: `test/sync-classify-6712.test.ts` (each row, and the cross product against a reference model built from the state space).
- `src/core/persistence/sync-pass.ts` — the read-only shadow of the level-triggered pass (#6712 PR 4a): `readShadowLevel` reads one managed source's level (`T` via `readTreeLevel`, `X`, working-mode untracked files, `Dp` for committed candidates only or every path in working mode, pages keyset on `pages.id` with the import record by a LATERAL primary-key probe and the revision's attestation in the same statement, holds and retry rows, open requests and pending Git effects, deletion markers) and classifies every path with `sync-classify.ts`; it writes and admits nothing. Postgres reads share one `REPEATABLE READ, READ ONLY` transaction; PGLite runs bounded 2,000-row statements. A company-brain source returns null (it keeps its frozen manifest). `shadowConvergence` wraps it in the receipt, `dryRunConvergence` backs `gbrain sync --dry-run --json`'s `convergence` (with the read-only screen), `statusConvergence` backs `sync status --detail` and doctor, and `idleTickProbe` times the idle tick's reads for the bench (`scripts/bench/sync-convergence.ts`). Tests: `test/sync-pass-shadow-6712.test.ts`.
- `src/core/persistence/sync-convergence.ts` — the convergence receipt (#6712 PR 4a, schema `convergence/1`, always `dry_run: true`): per-class `counts` and `classes` with action tags (`in_flight`, `keep_db_pending` beyond 200 per pass, and `deletes_withheld` when #2828's valve trips are classes too), predicted `decisions` by side after `readOnlySameContentScreen` (the dry run's `sameContentAtOrigin`: a screening request through `prepareManagedSyncMutation(..., { unsaved: true })`, at most 200 paths; equal content is `same_content_noops`, unscreened is `screen_unknown`), `would_hold`, `db_ahead` by prefix, `legacy_unverified`, `legacy_pageless`, `deletes` with the valve verdict and set hash, up to 20 samples per non-matched class, timings and statement count. `--redact-paths` replaces paths with sha256 prefixes and drops slugs.
+- `src/core/persistence/sync-markers.ts` — the deletion marker and the withheld mass-delete record of a managed Git source (#6712 PR 4b). `writeOriginDeletedMarker` runs in the transaction of every page-row deletion of a managed source (`page-purge.ts`, the purge-mirror replay; `test/page-row-deleters-guard-6712.test.ts` refuses any other deleter) and writes `sync-origin-deleted` (`<source>:<incarnation>:<origin>`, value `{kind:'deleted', blob_oids, page_id, slug}` from the import record) only when it can matter: the origin is in the `last_commit` tree (hardened `ls-tree`) or a file backs it on disk, no other live page records it, and the source is bound and not a company brain; an unreadable checkout counts as present. `retireOriginDeletedMarker` is compare-and-delete on the value read. `writeDeletesWithheld` / `readDeletesWithheld` / `clearDeletesWithheld` keep one `sync-deletes-withheld` record per incarnation (`{target, count, reconcilable, ratio, set_hash, samples≤20}`, `deleteSetHash`: sha256 over the sorted NUL-joined set). Seam: `purge:marker_written`.
- `src/commands/doctor/checks/managed-sync-convergence.ts` — doctor `managed_sync_convergence` (#6712 PR 4a, `deep` tier): the convergence shadow's counts for each managed source this host owns; always `ok` (informational), read-only. Tests: `test/doctor-managed-sync-convergence.test.ts`.
- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesQuery` (the paged same-name query and its binds, built per platform so every bound placeholder is referenced (#6659: an unreferenced bind failed every Windows `delete_page` with 42P18), 100 rows per batch below the source's highest page id, served by the v219 name indexes; `source_path` in any spelling or a `file:` URI; tombstones excluded) and `findLiveFileClaimants`, realpath deciding each candidate. In `page-prepare.ts`, a `delete_page` whose file another live page records (`prepareFileTarget` with `sharedOrigin`, before the byte comparison) owns no file: a soft delete publishes database-only with receipt `write_through.skipped: 'shared_origin'` and a warning ("hidden … does not erase", the `gbrain repair file-drift --source <id> --slug <survivor> --prefer file` that imports the kept file into the survivor; #6712 PR 1: sync holds a survivor that differs from the file `file_drift`, and that hold's fix leads with the same command), `validate` re-runs the census under the publication guards (`validateSharedOrigin`: the file moved or removed, or a different claimant set, refuses `source_changed` and never removes the file), and the surviving slug is named only when `slugDisclosable` (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). A purge of a shared-origin page refuses and names the soft delete. Tests: `test/page-prepare-shared-origin-6517.test.ts`, `test/sync-origin-live-wins-6517.test.ts`, `test/e2e/managed-sync-shared-origin-6517.test.ts`.
- `src/core/persistence/drift-conflicts.ts` — the `source_changed` / `file_database_drift` conflict pile (#6643). `auditDriftConflicts` groups conflict receipts by slug over a bounded window of request sequences (default 100,000, at most 1,000,000), paginated by slug with a `complete` flag; it backs `gbrain sources reconcile <source> --audit --conflicts` (`reconcile-audit.ts`) and MCP `list_write_conflicts` (`ops/persistence.ts`). The window ends at the source's own newest request (current incarnation, the `(source_incarnation, sequence)` index; a cursor never reads past it), and a source the caller may not read returns before anything is computed; the MCP op refuses an out-of-grant `source_id` through `resolveRequestedScope`. Remote callers get database-derived fields only, with source grant, slug fence and visibility filtered in the aggregating SQL; `liveFileDrift` (the `prepareFileTarget` comparison; reason `canonical_file_missing` for a live page whose canonical file is gone, `file_missing` for any other `source_changed`) and `driftClass` (the `reconcile-additive.ts` verdict) run only for a trusted local caller on the canonical owner, and such a row carries the compared file `path`. `submitMaintenance` (`prepared-maintenance.ts`, `maintenanceDriftRefusal`) refuses a drifted page before admission, and `synthesize_concepts` skips a drifted concept before spend, recording it in `dream.concepts.drift_skips` (per-entry atomic updates, released when the sides agree). Tests: `test/maintenance-file-drift-6643.test.ts` (PGLite; Postgres via `test/e2e/maintenance-file-drift-6643-postgres.test.ts`).
diff --git a/test/op-checkpoint-pass-rows-gc-6712.test.ts b/test/op-checkpoint-pass-rows-gc-6712.test.ts
new file mode 100644
index 0000000000..a12b7019cb
--- /dev/null
+++ b/test/op-checkpoint-pass-rows-gc-6712.test.ts
@@ -0,0 +1,31 @@
+/**
+ * #6712 PR 4b lane M (design v3.2 §3.4, eng-outside F9): the checkpoint GC keeps the managed-sync pass row, the
+ * deletion markers, the withheld mass-delete record and the cost reservations of a live source incarnation past the
+ * TTL, and collects the same rows of a retired incarnation. Real PGLite.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';
+import { SYNC_PASS_ROW_OPS } from '../src/core/persistence/sync-pass-row.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+test('GC keeps live-incarnation pass, marker, withheld and cost rows past the TTL and drops a retired incarnation\'s', async () => {
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ const live = source!.incarnation, retired = randomUUID();
+ const fingerprint = (op: string, incarnation: string) => op === 'sync-origin-deleted' ? `default:${incarnation}:notes/a.md`
+ : op === 'sync-pass-cost' ? `default:${incarnation}:episode:group` : `default:${incarnation}`;
+ for (const incarnation of [live, retired]) for (const op of SYNC_PASS_ROW_OPS) {
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now() - interval '30 days')`,
+ [op, fingerprint(op, incarnation), JSON.stringify({ source_id: 'default', incarnation })]);
+ }
+ expect(SYNC_PASS_ROW_OPS).toEqual(['managed-sync-pass', 'sync-origin-deleted', 'sync-deletes-withheld', 'sync-pass-cost']);
+ await purgeStaleCheckpoints(engine, 7);
+ const rows = await engine.executeRaw<{ op: string; incarnation: string }>(`SELECT op, completed_keys->0->>'incarnation' AS incarnation FROM op_checkpoints
+ WHERE op = ANY($1::text[]) ORDER BY op`, [[...SYNC_PASS_ROW_OPS]]);
+ expect(rows.filter(row => row.incarnation === live).map(row => row.op).sort()).toEqual([...SYNC_PASS_ROW_OPS].sort());
+ expect(rows.filter(row => row.incarnation === retired)).toEqual([]);
+}, 60_000);
diff --git a/test/page-row-deleters-guard-6712.test.ts b/test/page-row-deleters-guard-6712.test.ts
new file mode 100644
index 0000000000..fbe3bfebb3
--- /dev/null
+++ b/test/page-row-deleters-guard-6712.test.ts
@@ -0,0 +1,65 @@
+/**
+ * #6712 PR 4b lane M (design v3.2 §2.5, eng F7): every page-row deletion of a managed Git source writes its origin's
+ * deletion marker in the same transaction, so the classifier never reads a purged page's file as a new one. This lint
+ * refuses a new page-row deleter in src/ (`.deletePage(`, `.deletePages(`, raw `DELETE FROM pages`) that is not a
+ * reviewed caller below, and asserts the two deleters a managed source reaches call `writeOriginDeletedMarker` right
+ * before the delete. A new caller either goes through the helper (and joins MARKED) or names why a managed Git source
+ * never reaches it.
+ */
+import { expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+const ROOT = join(import.meta.dir, '..');
+const PATTERN = /\.deletePages?\(|DELETE FROM pages\b/g;
+
+/** The deleters a managed Git source reaches: each delete must follow `writeOriginDeletedMarker(` within three lines. */
+const MARKED: Record<string, number> = {
+ 'src/core/persistence/page-purge.ts': 1, // delete_page --purge, manual and retention (the coordinator's purge transaction)
+ 'src/core/belief/purge-mirror.ts': 1, // the restore-time purge replay
+};
+
+/** Reviewed callers a managed Git source never reaches, with the number of matches each file may hold. */
+const REVIEWED: Record<string, { count: number; why: string }> = {
+ 'src/core/pglite-engine.ts': { count: 2, why: 'engine methods forwarding to engine-sql/pages.ts' },
+ 'src/core/postgres-engine.ts': { count: 2, why: 'engine methods forwarding to engine-sql/pages.ts' },
+ 'src/core/engine-sql/pages.ts': { count: 3, why: 'the engine implementations themselves' },
+ 'src/core/engine.ts': { count: 1, why: 'doc comment of deletePages' },
+ 'src/core/engine-constants.ts': { count: 1, why: 'doc comment of the batch bound' },
+ 'src/core/bootstrap/verify.ts': { count: 1, why: 'unmanaged brains only; a managed brain removes its probe pages through delete_page --purge' },
+ 'src/core/transcripts/ingest.ts': { count: 1, why: 'unmanaged brains only; a managed brain deletes stale parts through the coordinator' },
+ 'src/core/persistence/purge-deleted.ts': { count: 1, why: 'unmanaged retention (expireRecordedTombstones); a managed brain purges through delete_page --purge' },
+ 'src/commands/migrate-engine.ts': { count: 1, why: 'engine migration copy, outside any source write' },
+ 'src/core/github-source.ts': { count: 2, why: 'GitHub connector source, not a managed Git checkout' },
+ 'src/core/google/google-source.ts': { count: 1, why: 'Google connector source' },
+ 'src/core/google/sweep-shared.ts': { count: 1, why: 'Google connector sweep' },
+};
+
+function scan(): Map<string, number[]> {
+ const found = new Map<string, number[]>();
+ for (const path of new Bun.Glob('src/**/*.ts').scanSync({ cwd: ROOT })) {
+ const lines = readFileSync(join(ROOT, path), 'utf8').split('\n');
+ lines.forEach((line, i) => { for (const _ of line.matchAll(PATTERN)) found.set(path, [...(found.get(path) ?? []), i]); });
+ }
+ return found;
+}
+
+test('no page-row deleter outside the reviewed callers', () => {
+ const found = scan();
+ const unexpected = [...found].filter(([path, hits]) => (MARKED[path] ?? REVIEWED[path]?.count) !== hits.length)
+ .map(([path, hits]) => `${path}: ${hits.length} page-row deletion(s); expected ${MARKED[path] ?? REVIEWED[path]?.count ?? 0}`);
+ expect(unexpected).toEqual([]);
+ const stale = [...Object.keys(MARKED), ...Object.keys(REVIEWED)].filter(path => !found.has(path));
+ expect(stale).toEqual([]);
+});
+
+test('the deleters a managed Git source reaches write the deletion marker right before the delete', () => {
+ const found = scan();
+ for (const [path, count] of Object.entries(MARKED)) {
+ const lines = readFileSync(join(ROOT, path), 'utf8').split('\n');
+ const hits = found.get(path) ?? [];
+ expect(hits).toHaveLength(count);
+ for (const line of hits) expect({ path, line: line + 1, marked: lines.slice(Math.max(0, line - 3), line).some(prior => prior.includes('writeOriginDeletedMarker(')) })
+ .toEqual({ path, line: line + 1, marked: true });
+ }
+});
diff --git a/test/sync-markers-6712.test.ts b/test/sync-markers-6712.test.ts
new file mode 100644
index 0000000000..85147d283a
--- /dev/null
+++ b/test/sync-markers-6712.test.ts
@@ -0,0 +1,83 @@
+/**
+ * #6712 PR 4b lane M (design v3.2 §2.5, §2.6): the marker and withheld-record helpers. Compare-and-delete retirement
+ * keeps a marker rewritten since it was read; the withheld record round-trips with its samples capped; the delete-set
+ * hash is order- and duplicate-free; the `purge:marker_written` seam fires after the marker insert of a purge. Real PGLite.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { clearDeletesWithheld, deleteSetHash, DELETES_WITHHELD_SAMPLES, readDeletesWithheld, readOriginDeletedMarker, retireOriginDeletedMarker,
+ writeDeletesWithheld } from '../src/core/persistence/sync-markers.ts';
+import { SYNC_ORIGIN_DELETED_OP } from '../src/core/persistence/sync-pass-row.ts';
+import { installFaultHook, type FaultDetail } from '../src/core/persistence/fault-points.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+describe('sync-markers helpers', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+ afterAll(async () => { await engine.disconnect(); });
+ const incarnation = randomUUID();
+ const insertMarker = (value: Record<string, unknown>) => engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,jsonb_build_array($3::text::jsonb))
+ ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys`, [SYNC_ORIGIN_DELETED_OP, `default:${incarnation}:notes/a.md`, JSON.stringify(value)]);
+
+ test('retireOriginDeletedMarker deletes only the value it read', async () => {
+ const read = { source_id: 'default', incarnation, kind: 'deleted', blob_oids: ['a'.repeat(40)], page_id: 1, slug: 'notes/a', at: '2026-10-01T00:00:00.000Z' };
+ await insertMarker(read);
+ expect(await readOriginDeletedMarker(engine, 'default', incarnation, 'notes/a.md')).toEqual(read as never);
+ const rewritten = { ...read, blob_oids: ['b'.repeat(40)], page_id: 2, at: '2026-10-02T00:00:00.000Z' };
+ await insertMarker(rewritten);
+ expect(await retireOriginDeletedMarker(engine, { sourceId: 'default', incarnation, origin: 'notes/a.md', expected: read })).toBe(false);
+ expect(await readOriginDeletedMarker(engine, 'default', incarnation, 'notes/a.md')).toEqual(rewritten as never);
+ expect(await retireOriginDeletedMarker(engine, { sourceId: 'default', incarnation, origin: 'notes/a.md', expected: { ...rewritten } })).toBe(true);
+ expect(await readOriginDeletedMarker(engine, 'default', incarnation, 'notes/a.md')).toBeNull();
+ expect(await retireOriginDeletedMarker(engine, { sourceId: 'default', incarnation, origin: 'notes/a.md', expected: rewritten })).toBe(false);
+ });
+
+ test('the withheld record is written, refreshed, read and cleared per incarnation, with at most 20 samples', async () => {
+ const paths = Array.from({ length: 30 }, (_, i) => `notes/n${String(i).padStart(2, '0')}.md`);
+ const input = { sourceId: 'default', incarnation, target: 'c'.repeat(40), count: 30, reconcilable: 40, ratio: 0.75, set_hash: deleteSetHash(paths), samples: paths };
+ const written = await writeDeletesWithheld(engine, input);
+ expect(written.samples).toHaveLength(DELETES_WITHHELD_SAMPLES);
+ expect(await readDeletesWithheld(engine, 'default', incarnation)).toEqual(written);
+ expect(await readDeletesWithheld(engine, 'default', randomUUID())).toBeNull();
+ const refreshed = await writeDeletesWithheld(engine, { ...input, count: 29, samples: paths.slice(1), set_hash: deleteSetHash(paths.slice(1)) });
+ expect(await readDeletesWithheld(engine, 'default', incarnation)).toEqual(refreshed);
+ expect(refreshed.source_id).toBe('default');
+ expect(refreshed.incarnation).toBe(incarnation);
+ expect(await clearDeletesWithheld(engine, 'default', incarnation)).toBe(true);
+ expect(await readDeletesWithheld(engine, 'default', incarnation)).toBeNull();
+ expect(await clearDeletesWithheld(engine, 'default', incarnation)).toBe(false);
+ });
+
+ test('deleteSetHash is sha256 over the sorted, NUL-joined set', () => {
+ const expected = createHash('sha256').update('a.md\0b/c.md\0z.md').digest('hex');
+ expect(deleteSetHash(['z.md', 'a.md', 'b/c.md'])).toBe(expected);
+ expect(deleteSetHash(['b/c.md', 'z.md', 'a.md', 'z.md'])).toBe(expected);
+ expect(deleteSetHash(['a.md', 'b/c.md'])).not.toBe(expected);
+ });
+});
+
+test('purge:marker_written fires after the marker insert of a managed purge, naming the origin', () => managedBrain(async ({ engine, ctx, root }) => {
+ expect((await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+ await engine.setConfig('sync.write_through', 'false');
+ const seen: Array<{ point: string; detail: FaultDetail }> = [];
+ installFaultHook((point, detail) => { if (point === 'purge:marker_written') seen.push({ point, detail }); });
+ try {
+ const snapshot = await engine.readPageSnapshot('notes/alpha', { sourceId: 'default' });
+ const result = await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: 'notes/alpha', purge: true, request_id: randomUUID(), expected_revision: snapshot!.revision }, waitMs: 30_000 });
+ expect(result.state).toBe('committed');
+ } finally { installFaultHook(undefined); }
+ expect(seen).toEqual([{ point: 'purge:marker_written', detail: { sourceId: 'default', slug: 'notes/alpha', path: 'notes/alpha.md' } }]);
+ void root;
+}, { setup: ({ root }) => {
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: 'ignore' });
+ git('init', '-q');
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ for (const name of ['alpha', 'beta']) writeFileSync(join(root, 'notes', name + '.md'), `---\ntitle: ${name}\n---\n\nSynthetic ${name}.\n`);
+ git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+} }), 120_000);