Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(purge): a sync-excluded tombstone's purge is database-only and keeps the user's file (#6368)

time-attack676e01d3b7d0
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index 3fc2e5e780..4eae7d3d4b 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -14,6 +14,6 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.
- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included) / `findRequestsForSlugs`, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome.
- `src/core/persistence/purged-intent.ts` — `intentCarriesPurgedContent`: `completeWrite` (journal.ts) nulls the intent of any terminal request whose content (`fact`, `claim`, page fence rows, or the page's content hash) matches a subject-scoped purge tombstone, and of any refusal coded `purged_content`; a write refused for another reason, or committed as a no-op after the overlay dropped purged rows, keeps no copy. Only content-bearing intents are checked, and whether the source holds any tombstone is selected by completeWrite's terminal statement itself (`PURGE_PRESENCE_COLUMNS`), so the hook adds no statement to a write on a source without tombstones (#6007 budget). `purged_content` is a write error code, so receipts and the frozen verb path (wire `invalid_params`, canonical `purged_content`) keep it typed.
-- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, redacts finished intents for the slug, then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts`.
+- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, redacts finished intents for the slug, then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts`. #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged.
- `src/core/ops/purge.ts` — `purge_fact`, `list_page_purges`, `unpurge_page`: admin scope, `cliOnly` (every MCP route gets `trusted_local_only`). The resident owner runs them only for its verified local CLI registration (`LOCAL_CLI_OWNER_OPERATIONS` in `persistence/ipc.ts`, checked in `persistence/provider.ts`).
- `src/commands/forget-purge.ts` + `src/commands/pages-purges.ts` — the CLI fronts. `runForgetPurge` always runs the dry run, then a typed token on a terminal or `--yes` plus `--request-id` without one; `--match` lists ids, `--status` polls completion; `PURGE_FAMILY_HELP` is the purge-family table shown by `gbrain forget --help`. `gbrain pages purges list` and `gbrain pages unpurge <slug>` run the page-tombstone ops as the trusted CLI.
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 623fe8fee3..a025fe63a2 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -51,7 +51,7 @@ interface PreparedMutationBase {
contentUnchanged?: boolean;
deferEmbedding?: boolean;
/** Why a page write bound to a worktree publishes no file (receipt `write_through.skipped`). */
- databaseOnlyReason?: 'db_only' | 'unbound_source' | 'mirror_read_only';
+ databaseOnlyReason?: 'db_only' | 'unbound_source' | 'mirror_read_only' | 'sync_excluded';
/**
* Must perform only transaction-composable database work. `preimage` (#5984)
* is the publisher's read of the page under its page guard, after the revision
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index b28df78fb2..286d25be6a 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -4,6 +4,8 @@ import { boundedReads } from './bounded-reads.ts';
import { isQuarantined, quarantineOutcome } from '../quarantine.ts';
import { existsSync, readFileSync } from 'node:fs';
import { join, relative, sep } from 'node:path';
+import { matchesAnyGlob } from '../sync.ts';
+import { syncExcludePatterns } from './sync-discovery.ts';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page, PageVersion } from '../types.ts';
@@ -144,7 +146,9 @@ export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, byt
return digest(actual) === digest(canonical(snapshot.page, snapshot.tags));
}
export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, snapshot: PageSnapshot | null,
- content: string | null, hostId?: string, options: { allowMissing?: boolean; deleting?: boolean; capture?: { path: string; hash: string }; activePack?: ParseOpts['activePack']; remote?: boolean } = {}): Promise<PreparedMutation['file']> {
+ content: string | null, hostId?: string, options: { allowMissing?: boolean; deleting?: boolean; capture?: { path: string; hash: string }; activePack?: ParseOpts['activePack']; remote?: boolean;
+ /** #6368: a tombstone purge whose file matches these sync.exclude globs (relative to the source root) owns no file. */
+ excludeTombstone?: { patterns: string[]; onExcluded: (path: string) => void } } = {}): Promise<PreparedMutation['file']> {
if (!row.worktree_id) return undefined;
// #6212: a legacy slug (admitted only to delete or restore its existing row) never owns a file: its recorded
// source_uri or source_path may name the file of another page, such as the one sync now slugs it to.
@@ -174,6 +178,10 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
if (!isWriteTargetContained(path, root)) throw opError('source_changed', 'The canonical file target is outside its registered source.',
`The file of ${row.slug} resolves outside source ${row.source_id}'s registered root (a symlinked directory or a moved checkout), so nothing was written. Inspect the owner before resubmitting; how to repair the checkout is the user's decision.`,
{ fix: ownerStatusFix(row.source_id) });
+ if (options.excludeTombstone && snapshot?.page.deleted_at) {
+ const rel = relative(root, path).split(sep).join('/');
+ if (matchesAnyGlob(rel, options.excludeTombstone.patterns)) { options.excludeTombstone.onExcluded(rel); return undefined; }
+ }
const before = existsSync(path) ? readFileSync(path) : null;
if (!before && snapshot && !snapshot.page.deleted_at && !options.allowMissing) {
// A declared db_only page has no canonical file by design and publishes to
@@ -307,8 +315,17 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ
// Tombstones still own their recorded artifact. Purge always attempts its
// removal before the guarded hard-delete and receipt commit; failure rolls
// back to the prior row, and replay survives the eventual absence of that row.
- const file = await prepareFileTarget(engine, row, snapshot, null, undefined, { allowMissing: purge || options.allowMissingFile, deleting: true, activePack, remote: row.authority.remote });
- return { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file), apply: async tx => {
+ // #6368: a tombstone whose file is under sync.exclude does not own that file (sync never reads it again), so its
+ // purge is database-only: the file is neither compared nor removed. The exclusion is checked again at publication.
+ let excludedPath: string | null = null;
+ const exclude = purge && snapshot.page.deleted_at != null ? await syncExcludePatterns(engine) : [];
+ const file = await prepareFileTarget(engine, row, snapshot, null, undefined, { allowMissing: purge || options.allowMissingFile, deleting: true, activePack, remote: row.authority.remote,
+ ...(exclude.length ? { excludeTombstone: { patterns: exclude, onExcluded: (path: string) => { excludedPath = path; } } } : {}) });
+ return { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file), ...(excludedPath !== null ? { databaseOnlyReason: 'sync_excluded' as const } : {}), apply: async tx => {
+ if (purge && excludedPath !== null) {
+ if (!matchesAnyGlob(excludedPath, await syncExcludePatterns(tx))) throw pageRefusal('source_changed', 'sync.exclude changed while the purge was prepared.', row,
+ `${excludedPath} was excluded from sync when the purge of ${row.slug} was prepared and is not any more, so nothing was purged. Run the purge again; it re-reads the exclusion.`, pageFix(row.source_id, row.slug));
+ }
if (purge) return purgePageInTransaction(tx, row, snapshot);
if (!noop) { await tx.createVersion(row.slug, source); await tx.softDeletePage(row.slug, source); }
return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop,
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 13ec5b41ce..762b08c214 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -47,6 +47,11 @@ export interface SyncDiscovery { binding: WorktreeBinding; root: string; gitRoot
retryTaken?: string[]; }
export interface ManagedSyncContext { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;
source: { last_commit: string | null; config: Record<string, unknown> }; }
+/** The persisted `sync.exclude` globs (plus a run's `--exclude`), as discovery matches them against a path relative to the source root. */
+export async function syncExcludePatterns(engine: Pick<BrainEngine, 'getConfig'>, extra: readonly string[] = []): Promise<string[]> {
+ return [...extra, ...(await engine.getConfig('sync.exclude') ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)]
+ .map(v => v.endsWith('/') ? `${v}**` : v);
+}
export function syncGit(root: string, args: string[]): string {
return execFileSync('git', ['-c', 'core.quotepath=false', '-C', root, ...args],
{ encoding: 'utf8', timeout: 30_000, maxBuffer: 32 * 1024 ** 2, stdio: ['ignore', 'pipe', 'pipe'] });
@@ -181,8 +186,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
slugPrefix: probe.slice(0, -2), dryRun: true }) : 'git-root';
const sourcePath = (path: string) => slugMode === 'source-root' && scope ? path.slice(scope.length + 1) : path;
const originScope: SyncOriginScope = { sourceId, root, scope, slugMode };
- const exclude = [...(opts.exclude ?? []), ...(await engine.getConfig('sync.exclude') ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)]
- .map(v => v.endsWith('/') ? `${v}**` : v);
+ const exclude = await syncExcludePatterns(engine, opts.exclude);
const includeHidden = [...new Set([...(opts.includeHidden ?? []), ...(await engine.getConfig('sync.include_hidden') ?? '')
.split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))];
// Reserved skillpack paths belong to the shared skill publisher; the managed importer always refuses them.
diff --git a/test/page-snapshot-alias-plan.test.ts b/test/page-snapshot-alias-plan.test.ts
index 94915070c5..55d19ef3a7 100644
--- a/test/page-snapshot-alias-plan.test.ts
+++ b/test/page-snapshot-alias-plan.test.ts
@@ -80,7 +80,7 @@ for (const kind of testBackends()) {
['fetch exact hit across sources', 'people/bob-example', { resolveAlias: true, requireUnambiguous: true, sourceIds: ['default', 'alt'] }],
['fetch exact hit in one source', 'people/bob-example', { resolveAlias: true, requireUnambiguous: true, sourceId: 'default' }],
['private exact with preserveExactIdentity', 'people/private-example', { resolveAlias: true, excludePrivate: true, preserveExactIdentity: true, sourceIds: ['default', 'alt'] }],
- ] as const)('%s visits fewer than 100 pages rows per statement', async (_name, slug, opts) => {
+ ] as Array<[string, string, NonNullable<Parameters<typeof readPageSnapshot>[2]>]>)('%s visits fewer than 100 pages rows per statement', async (_name, slug, opts) => {
const { counts } = await visits(slug, opts);
expect(counts.length).toBeGreaterThan(0);
for (const count of counts) expect(count).toBeLessThan(100);
diff --git a/test/pages-purge-artifact.test.ts b/test/pages-purge-artifact.test.ts
index 295362fc27..048a5b54c7 100644
--- a/test/pages-purge-artifact.test.ts
+++ b/test/pages-purge-artifact.test.ts
@@ -16,6 +16,12 @@ import { importFromContent } from '../src/core/import-file.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
import { withEnv } from './helpers/with-env.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
let engine: PGLiteEngine;
let tmpRoot: string;
@@ -173,3 +179,64 @@ describe('managed purge artifact and receipt boundaries', () => {
expect(readFileSync(join(file, 'keep'), 'utf8')).toBe('preserved directory contents');
});
});
+
+// #6368: a tombstone whose file is under sync.exclude does not own that file; its purge is database-only.
+describe('managed purge of a sync-excluded tombstone (#6368)', () => {
+ for (const edited of [false, true]) {
+ test(`excluded tombstone with an ${edited ? 'edited' : 'unchanged'} file purges database-only and keeps the file`, async () => {
+ const file = await seedPageWithFile();
+ await engine.softDeletePage(SLUG, { sourceId: 'default' });
+ await engine.setConfig('sync.exclude', 'secrets/');
+ if (edited) writeFileSync(file, 'A local edit the user keeps.');
+ const bytes = readFileSync(file, 'utf8');
+ const result = await purge();
+ expect(result).toMatchObject({ status: 'purged', state: 'committed', write_through: { written: false, skipped: 'sync_excluded' } });
+ expect(await rowState()).toBe('absent');
+ expect(existsSync(file)).toBe(true);
+ expect(readFileSync(file, 'utf8')).toBe(bytes);
+ });
+ }
+ test('a glob exclusion relative to the source root also applies; a non-excluded tombstone keeps the artifact contract', async () => {
+ const file = await seedPageWithFile();
+ await engine.softDeletePage(SLUG, { sourceId: 'default' });
+ await engine.setConfig('sync.exclude', 'other/**, **/leaked-*.md');
+ expect((await purge())).toMatchObject({ status: 'purged', write_through: { skipped: 'sync_excluded' } });
+ expect(existsSync(file)).toBe(true);
+ });
+ test('a non-excluded tombstone with an edited file still refuses', async () => {
+ const file = await seedPageWithFile();
+ await engine.softDeletePage(SLUG, { sourceId: 'default' });
+ await engine.setConfig('sync.exclude', 'other/');
+ writeFileSync(file, 'Unknown local edit must survive.');
+ expect((await failure(await parameters({ purge: true }), 'conflict')).code).toBe('source_changed');
+ expect(readFileSync(file, 'utf8')).toBe('Unknown local edit must survive.');
+ });
+ test('a live page under an excluded path keeps the artifact contract', async () => {
+ const live = await seedPageWithFile();
+ await engine.setConfig('sync.exclude', 'secrets/');
+ expect(await purge()).toMatchObject({ status: 'purged', write_through: { written: true } });
+ expect(existsSync(live)).toBe(false);
+ });
+ test('an exclusion removed between preparation and publication refuses the purge and keeps the file', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const file = await seedPageWithFile();
+ await engine.softDeletePage(SLUG, { sourceId: 'default' });
+ await engine.setConfig('sync.exclude', 'secrets/');
+ await putPage.handler(context(), { slug: 'notes/bootstrap-writer', content: CONTENT, request_id: randomUUID() });
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default', includeDeleted: true }))!;
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const authority = await submissionAuthority(context(), 'delete_page', 'default', source!.incarnation, SLUG);
+ const binding = (await getWorktreeBinding(engine, 'default'))!;
+ const intent = { purge: true, expected_revision: snapshot.revision };
+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'delete_page', sourceId: 'default', sourceIncarnation: source!.incarnation,
+ slug: SLUG, pageId: snapshot.page.id, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation, requestId: randomUUID(), callerIntent: intent, intent });
+ const row = (await claimNextWrite(engine, localHostId()))!;
+ const prepared = await preparePageMutation(engine, row, context().config);
+ expect(prepared.databaseOnlyReason).toBe('sync_excluded');
+ await engine.setConfig('sync.exclude', '');
+ const settled = await publishMutation(engine, row, prepared);
+ expect(settled.state).not.toBe('committed');
+ expect(settled.error_code).toBe('source_changed');
+ expect(await rowState()).toBe('tombstone');
+ expect(readFileSync(file, 'utf8')).toBe(CONTENT);
+ }));
+});