Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): a never-published page's delete no longer fails closed on a missing file (#5336)
time-attack4d682fa1f7dd
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 6b4b4992f8..a4937a53c5 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -14,7 +14,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/onboarding.ts` + `legacy-locks.ts` + `physical-root-recovery.ts` — read-only source onboarding states; exact same-host dead-lock cleanup under explicit activation opt-in; and state-bound same-owner root repair using a durable manifest and token-verified temporary stamp. `physical-root.ts` `restampPhysicalRoot` handles a filesystem device id that changed while the owner token, brain, worktree, root, inode and a non-zero birth time still match (macOS can renumber `st_dev` across reboots): under the caller's outside-root native lock, one transaction verifies owner host, brain and host binding and rewrites the recorded self-transfer copies and retained topology staging identities (each only while it still names the old device); after commit the stamp and the reservation's initial device are rewritten and the event is logged, so an interruption between the two leaves a device-only change the next locked acquisition finishes. Ownership markers inside a retained topology clone stage are not re-stamped; an interrupted clone recovery that spans a device renumbering still needs source recovery. `assertPhysicalRoot` stays read-only; zero birth time or any other difference keeps the refusal. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.-- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests.+- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests.- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. `__setMaintenanceWriteWaitForTests` replaces the base wait. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.Atom completion admits replacement and revision-pinned stale-atom deletion children together.Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex b68222cb5f..0c378b6715 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -130,7 +130,7 @@ export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, bytreturn 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; 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 } = {}): Promise<PreparedMutation['file']> {if (!row.worktree_id) return undefined;// #5409: a read-only mirror's checkout belongs to its Git remote; nothing is written or removed there.if (await sourceMirrorReadOnly(engine, row.source_id)) return undefined;@@ -167,6 +167,7 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ// canonical file publishes to the database only; a recorded file that went// missing still refuses below.if (publishesDatabaseOnly(root, row.slug, snapshot)) return undefined;+ if (options.deleting === true && content === null && !snapshot.page.source_path && !capturedPath) return undefined;throw new OperationError('source_changed', 'The canonical file was removed outside coordinated publication.','Import the local deletion or recover the canonical file before editing this page.');}@@ -269,7 +270,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest// 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, activePack, remote: row.authority.remote });+ 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 => {if (purge) {await tx.deletePage(row.slug, source);diff --git a/test/persistence-captured-file-target.test.ts b/test/persistence-captured-file-target.test.tsindex 871fb2736f..da258a7ded 100644--- a/test/persistence-captured-file-target.test.ts+++ b/test/persistence-captured-file-target.test.ts@@ -1,5 +1,5 @@import { afterAll, beforeAll, expect, test } from 'bun:test';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { dirname, join } from 'node:path';import { tmpdir } from 'node:os';import { pathToFileURL } from 'node:url';@@ -16,7 +16,8 @@ const sourceId = 'captured-target';beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({}); await engine.initSchema();- home = mkdtempSync(join(tmpdir(), 'gbrain-captured-target-'));+ // realpath: macOS tmpdir lives under /var -> /private/var; targets are compared post-realpath.+ home = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-captured-target-')));root = join(home, 'source'); mkdirSync(root);await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);worktreeId = (await claimWorktree(engine, sourceId, root)).worktree_id;@@ -74,3 +75,76 @@ test('captured file still requires bytes matching the coherent page snapshot', aawait expect(prepareFileTarget(engine, row, snapshot, 'Replacement')).rejects.toMatchObject({ code: 'source_changed' });expect(readFileSync(file, 'utf8')).toBe('Uncoordinated local edit');});++async function neverFiled(slug: string, body: string) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body }, { sourceId });+ await engine.executeRaw('UPDATE pages SET source_uri=NULL,source_path=NULL WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ return { snapshot: (await engine.readPageSnapshot(slug, { sourceId }))!, row: { source_id: sourceId, worktree_id: worktreeId, slug } };+}++test('deleting a live page that never recorded a canonical artifact does not fail closed on a missing file', async () => {+ // Subagent-sandbox and other database-only publications admit with no+ // worktree, so no .md is ever written and source_path stays null. A later+ // CLI delete_page (write-through authority, worktree bound) must treat the+ // absent file as "nothing to unlink" and plan no file at all.+ const slug = 'wiki/agents/42/notes/scratch/db-only';+ const { row, snapshot } = await neverFiled(slug, 'Sandbox content');+ expect(await prepareFileTarget(engine, row, snapshot, null, undefined, { deleting: true })).toBeUndefined();+});++test('a page with no recorded file path whose file is missing still refuses edits; only its deletion proceeds', async () => {+ // Pre-v0.32.7 rows have a NULL source_path even though their file existed,+ // so a missing file may be a real uncoordinated removal. An edit must not+ // silently recreate it; a delete has nothing to resurrect.+ const slug = 'notes/legacy-null-source-path';+ const { row, snapshot } = await neverFiled(slug, 'Legacy row');+ const file = join(root, `${slug}.md`);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));+ rmSync(file);+ await expect(prepareFileTarget(engine, row, snapshot, 'Forced edit')).rejects.toMatchObject({ code: 'source_changed' });+ await expect(prepareFileTarget(engine, row, snapshot, null)).rejects.toMatchObject({ code: 'source_changed' });+ expect(await prepareFileTarget(engine, row, snapshot, null, undefined, { deleting: true })).toBeUndefined();+});++test('a live page whose recorded source_path artifact is missing still fails closed, including on delete', async () => {+ const slug = 'notes/recorded-then-removed';+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Was on disk' }, { sourceId });+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE source_id=$2 AND slug=$3', [`${slug}.md`, sourceId, slug]);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const row = { source_id: sourceId, worktree_id: worktreeId, slug };+ await expect(prepareFileTarget(engine, row, snapshot, 'Replacement')).rejects.toMatchObject({ code: 'source_changed' });+ await expect(prepareFileTarget(engine, row, snapshot, null, undefined, { deleting: true })).rejects.toMatchObject({ code: 'source_changed' });+});++test('a live page recorded only through a captured file URI still fails closed when that file is missing', async () => {+ // #5622 captured files record their artifact in source_uri, not source_path.+ const slug = 'notes/captured-gone';+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Captured, then removed' }, { sourceId });+ await engine.executeRaw('UPDATE pages SET source_uri=$1,source_path=NULL WHERE source_id=$2 AND slug=$3',+ [pathToFileURL(join(root, 'notes', 'Captured Gone.md')).href, sourceId, slug]);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const row = { source_id: sourceId, worktree_id: worktreeId, slug };+ await expect(prepareFileTarget(engine, row, snapshot, null, undefined, { deleting: true })).rejects.toMatchObject({ code: 'source_changed' });+ await expect(prepareFileTarget(engine, row, snapshot, 'Replacement')).rejects.toMatchObject({ code: 'source_changed' });+});++test('a declared db_only page stays database-only even when never published', async () => {+ // Composition invariant: the gbrain.yml declaration must win over the+ // never-published delete fall-through. notes/db-only/ is not a derive-phase+ // prefix, so only the declaration can make this page database-only.+ writeFileSync(join(root, 'gbrain.yml'), 'storage:\n db_only:\n - notes/db-only/\n');+ try {+ const { row, snapshot } = await neverFiled('notes/db-only/declared-never-published', 'Database-only by declaration');+ expect(await prepareFileTarget(engine, row, snapshot, null, undefined, { deleting: true })).toBeUndefined();+ expect(await prepareFileTarget(engine, row, snapshot, 'Content change')).toBeUndefined();+ } finally {+ rmSync(join(root, 'gbrain.yml'), { force: true });+ }+});++test('an undeclared never-filed derive-phase page stays database-only (atoms/ precedence)', async () => {+ const { row, snapshot } = await neverFiled('atoms/derived-never-published', 'Derived output');+ expect(await prepareFileTarget(engine, row, snapshot, null, undefined, { deleting: true })).toBeUndefined();+ expect(await prepareFileTarget(engine, row, snapshot, 'Content change')).toBeUndefined();+});diff --git a/test/persistence-never-published-delete.test.ts b/test/persistence-never-published-delete.test.tsnew file mode 100644index 0000000000..c1507b2e03--- /dev/null+++ b/test/persistence-never-published-delete.test.ts@@ -0,0 +1,73 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';++// #5336: a subagent-sandbox page is published to the database only and never+// gets a canonical file. A trusted local delete of it must not fail closed as+// if the file had been removed outside gbrain, and its receipt must not claim+// a file or Git effect it did not perform; a trusted edit keeps refusing.+let engine: PGLiteEngine;+let home: string;+let root: string;+const sourceId = 'never-published';+const quiet = { info() {}, warn() {}, error() {} };+const cli = (): OperationContext => ({ engine, sourceId, remote: false, dryRun: false, config: { engine: 'pglite' }, logger: quiet });+const sandbox = (): OperationContext => ({ ...cli(), remote: true, viaSubagent: true, subagentId: 42 });+const submit = (ctx: OperationContext, operation: string, params: Record<string, unknown>) =>+ withEnv({ GBRAIN_HOME: home }, () => submitPageMutation(ctx, { operation, params: { request_id: randomUUID(), ...params }, waitMs: 30_000 }));++beforeAll(async () => {+ home = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-never-published-')));+ root = join(home, 'source'); mkdirSync(root);+ engine = new PGLiteEngine();+ await withEnv({ GBRAIN_HOME: home }, async () => { await engine.connect({}); await engine.initSchema(); });+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+}, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });+ rmSync(home, { recursive: true, force: true });+});++test('a trusted delete of a never-published sandbox page soft-deletes it; a trusted edit still refuses', async () => {+ const deleted = 'wiki/agents/42/notes/delete-me';+ const edited = 'wiki/agents/42/notes/edit-me';+ for (const slug of [deleted, edited]) {+ const put = await submit(sandbox(), 'put_page', { slug, content: '---\ntitle: Sandbox note\ntype: note\n---\nSandbox body.\n' });+ expect(put.state).toBe('committed');+ expect(put.persistence).toEqual({ mode: 'database' });+ expect(existsSync(join(root, `${slug}.md`))).toBe(false);+ }++ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('never-published-other','never-published-other') ON CONFLICT DO NOTHING");+ await engine.putPage(deleted, { type: 'note', title: 'Other source', compiled_truth: 'Other source body.' }, { sourceId: 'never-published-other' });+ const versionsBefore = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2`, [sourceId, deleted]);+ const disk = () => readdirSync(home, { recursive: true }).map(String).filter(entry => !entry.includes('.gbrain')).sort();+ const diskBefore = disk();++ const result = await submit(cli(), 'delete_page', { slug: deleted, force: true });+ expect(result.state).toBe('committed');+ expect(result.persistence).toEqual({ mode: 'database' });+ expect(result.write_through).toMatchObject({ written: false });+ const effects = await engine.executeRaw<{ kind: string }>(`SELECT e.kind FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id+ WHERE r.request_id=$1::uuid`, [result.request_id]);+ expect(effects.map(effect => effect.kind)).not.toContain('git');+ expect(await engine.readPageSnapshot(deleted, { sourceId })).toBeNull();+ expect((await engine.readPageSnapshot(deleted, { sourceId, includeDeleted: true }))?.page.deleted_at).not.toBeNull();+ const versionsAfter = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2`, [sourceId, deleted]);+ expect(versionsAfter[0]!.n).toBe(versionsBefore[0]!.n + 1);+ expect((await engine.readPageSnapshot(deleted, { sourceId: 'never-published-other' }))?.page.compiled_truth).toBe('Other source body.');+ expect(existsSync(join(root, `${deleted}.md`))).toBe(false);+ expect(disk()).toEqual(diskBefore);++ await expect(submit(cli(), 'put_page', { slug: edited, content: '---\ntitle: Sandbox note\ntype: note\n---\nTrusted edit.\n', force: true }))+ .rejects.toMatchObject({ code: 'source_changed' });+ expect(existsSync(join(root, `${edited}.md`))).toBe(false);+ expect((await engine.readPageSnapshot(edited, { sourceId }))?.page.compiled_truth).toContain('Sandbox body.');+}, 120_000);