Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(purge): managed sync holds a stale purged page as purged_content (prefetched tombstones in the pure screen)

garrytanc68c78ad36d3
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 55b9ea3ecb..bb16b6c124 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -151,6 +151,7 @@ with each file and fix the ones that need no guessing."*
| <a id="file_too_large"></a>`file_too_large` | Over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read). The limit is fixed. | Split the file into smaller files and commit, or leave it out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`. The next `gbrain sync --source <source> --no-pull` clears the hold. |
| <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | With multimodal embedding on (`embedding_multimodal` / `GBRAIN_EMBEDDING_MULTIMODAL`), sync admits image files, but managed sync has no image importer yet. Each image import is held instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken; keeping them held is fine. To stop holding images, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`) or turn multimodal embedding off; either clears the holds on the next `gbrain sync --source <source> --no-pull`. A held image is re-screened when it changes and on `gbrain sources retry-held <source>`. |
| <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. |
+| <a id="purged_content"></a>`purged_content` | The file (or written content) has the content hash of a page the owner purged with `gbrain delete <slug> --purge`, under any slug, or carries a purged claim the database refuses. Purge leaves a text-free tombstone so a stale file, re-sync or revert cannot bring the content back. | Delete or edit the file and commit; an edited file imports normally. Only if the purge was a mistake, the owner lists tombstones with `gbrain pages purges list` and clears one with `gbrain pages unpurge <slug>` on the brain host. See [expire versus purge](memory-boundaries.md#purge). |
| <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. |
| <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. A conflict no such request explains still blocks with `revision_conflict`. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. |
| <a id="parser_regression"></a>`parser_regression` | With `sync.parser_regression=hold`, a file whose exact bytes imported under an earlier gbrain is now refused. This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. |
diff --git a/src/core/import-screen.ts b/src/core/import-screen.ts
index 0dcd5ec7fe..ce6c221f07 100644
--- a/src/core/import-screen.ts
+++ b/src/core/import-screen.ts
@@ -15,6 +15,7 @@ import { withQuarantineOverride } from './quarantine-override.ts';
import { loadOperatorLiterals } from './content-sanity-literals.ts';
import { classifyImportHold, contentSizeHold, parseMarkdown, type ContentHold, type ParseOpts, type ParsedMarkdown } from './markdown.ts';
import { isCodeFilePath } from './sync.ts';
+import { contentHash } from './utils.ts';
import { opError, type OperationError } from './ops/contract.ts';
import type { Action } from './agent-output.ts';
import { fenceFixText, fenceLocationFromMessage, fenceRefusal } from './fence-repair/refusal.ts';
@@ -80,7 +81,7 @@ export function assessImportSanity(page: Pick<ParsedMarkdown, 'compiled_truth' |
* with its location-only `fence`.
*/
export interface ContentRefusal extends Omit<ContentHold, 'code' | 'reason'> {
- code: ContentHold['code'] | 'content_rejected' | 'invalid_fence';
+ code: ContentHold['code'] | 'content_rejected' | 'invalid_fence' | 'purged_content';
reason?: ContentHold['reason'] | FenceReason;
fence?: FenceMessageLocation;
/** #6188 (D18): every issue that blocks the write, location and class only. */
@@ -137,6 +138,8 @@ export interface ImportScreenInput {
fences?: 'coordinated' | 'lenient';
/** #6188: `fences.normalize`; false treats a fixable fence as residual. Default true. */
normalize?: boolean;
+ /** #5575: the source's page purge tombstones (content hash -> purged slug), prefetched by the caller. */
+ purgedPages?: ReadonlyMap<string, string>;
}
export type ImportScreenResult =
@@ -158,6 +161,9 @@ export function screenImportContent(input: ImportScreenInput): ImportScreenResul
const parsed = parseMarkdown(input.content, input.path, { validate: true, ...(input.activePack ? { activePack: input.activePack } : {}) });
const hold = classifyImportHold(parsed, { expectedSlug: input.expectedSlug, slugExempt: input.slugExempt, slugConflictMessage: input.slugConflictMessage });
if (hold) return { status: 'refused', refusal: hold };
+ const purgedAs = input.purgedPages?.size ? input.purgedPages.get(contentHash(parsed)) : undefined;
+ if (purgedAs !== undefined) return { status: 'refused', refusal: { code: 'purged_content',
+ message: `${input.path} carries the content of page ${purgedAs}, which the owner purged; it was not imported.` } };
let fences: FenceScreen | undefined;
if (input.fences) {
const before = { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline ?? '' };
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index d22772cdc6..52899b3657 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -373,6 +373,11 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
return { argv: ['gbrain', 'config', 'get', 'sync.exclude'], consent: [], actor: 'agent', requires_exclusive: false,
why: `The size limit is fixed. Split ${record.path} into smaller files and commit, or leave it out of the source: read the current sync.exclude list, then run gbrain config set sync.exclude '<current list>,${record.path}'. The next gbrain sync --source ${source} --no-pull clears the hold.`,
verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };
+ case 'purged_content':
+ return { argv: ['gbrain', 'pages', 'purges', 'list', '--source', source], consent: [], actor: 'user', requires_exclusive: false,
+ user_message: `${record.path} carries the content of a page the owner purged, so sync holds it. Delete or edit the file and commit; or, only if the purge was a mistake, clear it with gbrain pages unpurge <slug> --source ${source} on the brain host.`,
+ why: 'Purged content stays out of the brain until the owner clears its tombstone; editing the file (a new content hash) imports normally.',
+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };
case 'content_rejected':
return { argv: ['gbrain', 'config', 'get', 'content_sanity'], consent: [], actor: 'user', requires_exclusive: false,
user_message: `${record.path} was rejected by the content-sanity gate because junk_disposition is reject. Remove the matched junk from the file, or decide whether to switch junk_disposition back to quarantine.`,
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index ef6da2f984..ba228822ff 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -37,6 +37,7 @@ import { checkpointRetryCommand, findIncompleteSyncReceipt } from './checkpoint-
import { frontmatterSlugConflictMessage } from './verb-errors.ts';
import { CHUNKER_VERSION } from '../chunkers/code.ts';
import { clearGitHold, countGitHolds, recordSyncImportProvenance } from './sync-holds.ts';
+import { readPagePurgeTombstones } from './page-purge.ts';
import { fenceWhere } from '../fence-repair/refusal.ts';
import { fencesNormalizeEnabled } from '../fence-repair/config.ts';
import { describeFixes } from '../fence-repair/report.ts';
@@ -136,6 +137,7 @@ function syncContentRefusal(refusal: ContentRefusal, row: WriteRequest, p: SyncI
: refusal.code === 'frontmatter_slug_conflict' ? 'Correct the frontmatter `slug:` in the file and commit the change.'
: refusal.code === 'file_too_large' ? `${p.sourcePath} is over the import size limit; split it into smaller files or add it to sync.exclude, then commit.`
: refusal.code === 'content_rejected' ? `The content-sanity gate rejects ${p.sourcePath} under junk_disposition=reject; remove the matched junk and commit.`
+ : refusal.code === 'purged_content' ? `${p.sourcePath} still carries purged content; delete or edit the file and commit, or the owner clears the tombstone with gbrain pages unpurge.`
: `Fix ${where} (one line per key, the whole value quoted) and commit the change; gbrain repair frontmatter --source ${row.source_id} previews the exact line fix and writes it only after the preview hash is approved.`;
const error = syncPublicationRefusal(refusal.code, refusal.message, row, p, cause, false, {
...(refusal.code === 'content_rejected' ? {} : { legacy_error: 'invalid_params' }),
@@ -155,6 +157,8 @@ export interface SyncImportScreenInput {
activePack?: ParseOpts['activePack']; companyApproval?: boolean; sanity?: ImportSanityConfig;
/** #6188: `fences.normalize`; false holds a fixable fence like any other. Default true. */
normalize?: boolean;
+ /** #5575: page purge tombstones of the source; a matching file is held as `purged_content`. */
+ purgedPages?: ReadonlyMap<string, string>;
}
/**
@@ -182,6 +186,7 @@ export function screenSyncImport(input: SyncImportScreenInput): { screen: Import
slugExempt: declared => snapshot?.page.source_path != null && syncOriginPath(snapshot.page.source_path) === syncOriginPath(sourcePath) && declared === snapshot.page.slug,
slugConflictMessage: (found, expected) => frontmatterSlugConflictMessage(sourcePath, found, expected),
...(input.sanity ? { sanity: input.sanity } : {}),
+ ...(input.purgedPages ? { purgedPages: input.purgedPages } : {}),
...(newerWorkingTree ? { published: () => {
const working = input.renamed ? null : readSyncFile(input.root, input.path);
return !!working && sha256(working) === input.rawHash && sameCanonicalImport(base!, parseMarkdown(working.toString('utf8'), `${slug}.md`, { activePack }));
@@ -396,7 +401,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
`Page ${renamed.slug}, which this file was renamed from, changed or was deleted after the sync was admitted.`);
}
const { screen, parsedInput, newerWorkingTree } = await settledSyncScreen(engine, { content: p.content, rawHash: p.rawHash, lineEndingOnly: p.lineEndingOnly === true,
- slug: row.slug, sourcePath: p.sourcePath, path: p.path, root, snapshot, base, renamed: !!renamed, activePack, companyApproval: !!p.companyApproval });
+ slug: row.slug, sourcePath: p.sourcePath, path: p.path, root, snapshot, base, renamed: !!renamed, activePack, companyApproval: !!p.companyApproval,
+ purgedPages: await readPagePurgeTombstones(engine, row.source_id) });
if (screen.status === 'published') return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate,
apply: async tx => { await releaseHold(tx); return { status: 'skipped', slug: row.slug, source_id: row.source_id, chunks: 0, noop: true, imported_file: true }; } };
if (screen.status === 'refused') throw syncContentRefusal(screen.refusal, row, p);
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index 28092d188b..70ca40de1e 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -25,6 +25,7 @@ import { isImageFilePath, resolveSlugForPath } from '../sync.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
import { VERSION } from '../../version.ts';
import { sha256 } from './digest.ts';
+import { readPagePurgeTombstones } from './page-purge.ts';
import { readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry } from './sync-discovery.ts';
import { readBlobContents, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
import { screenSyncImport, type SyncImportScreenInput } from './sync-prepare.ts';
@@ -96,6 +97,14 @@ export function managedImageHold(entry: SyncEntry, content: string | null, blob:
message: `${entry.path} is an image, which managed sync does not import yet; the rest of the source synced.` }, content, blob);
}
+const purgeTombstonesByRun = new WeakMap<SyncScreenRun, Promise<Map<string, string>>>();
+/** #5575: one tombstone read per sync run; a run screens one source. */
+function runPurgeTombstones(engine: BrainEngine, run: SyncScreenRun, sourceId: string): Promise<Map<string, string>> {
+ let read = purgeTombstonesByRun.get(run);
+ if (!read) { read = readPagePurgeTombstones(engine, sourceId); purgeTombstonesByRun.set(run, read); }
+ return read;
+}
+
export interface FrozenImportScreen {
cursor: Pick<SyncDiscovery, 'sourceId' | 'incarnation' | 'root'>;
entry: SyncEntry; slug: string; pageId: number | null; snapshot: Snapshot;
@@ -126,7 +135,8 @@ export async function screenFrozenImport(engine: BrainEngine, input: FrozenImpor
const moved = entry.renameFrom && entry.renameFrom.slug !== slug ? entry.renameFrom : undefined;
const base = moved ? await engine.readPageSnapshot(moved.slug, { sourceId: input.cursor.sourceId, includeDeleted: true }) : snapshot;
const screenInput: SyncImportScreenInput = { content, rawHash: input.rawHash, lineEndingOnly: input.lineEndingOnly, slug, sourcePath: entry.sourcePath, path: entry.path,
- root: input.cursor.root, snapshot, base, renamed: !!moved, activePack: run.activePack, sanity: run.sanity };
+ root: input.cursor.root, snapshot, base, renamed: !!moved, activePack: run.activePack, sanity: run.sanity,
+ purgedPages: await runPurgeTombstones(engine, run, input.cursor.sourceId) };
let { screen } = screenSyncImport(screenInput);
// #6188: a fence Tier 1 rewrites is admitted (publication writes the normalized file back); with fences.normalize=false it is held.
if (screenNormalized(screen) && !await run.normalize()) ({ screen } = screenSyncImport({ ...screenInput, normalize: false }));
diff --git a/test/page-purge.test.ts b/test/page-purge.test.ts
index 209ab34dd1..a92d3dc01d 100644
--- a/test/page-purge.test.ts
+++ b/test/page-purge.test.ts
@@ -20,6 +20,8 @@ import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { withEnv } from './helpers/with-env.ts';
+import { screenImportContent } from '../src/core/import-screen.ts';
+import { readPagePurgeTombstones } from '../src/core/persistence/page-purge.ts';
let engine: PGLiteEngine;
let storageDir: string;
@@ -92,6 +94,9 @@ describe('page purge', () => {
await runExtractFacts(engine, { slugs: [SLUG] });
await purgePage();
expect(await errorText(importFromContent(engine, SLUG, CONTENT, { noEmbed: true, sourceId: 'default' }))).toContain('purged_content');
+ // The prefetched tombstones match the stale file's own bytes, so sync holds it at screen time.
+ const screen = screenImportContent({ content: CONTENT, path: `${SLUG}.md`, purgedPages: await readPagePurgeTombstones(engine, 'default') });
+ expect(screen.status === 'refused' && screen.refusal.code).toBe('purged_content');
expect(await errorText(importFromContent(engine, 'notes/renamed-copy', CONTENT, { noEmbed: true, sourceId: 'default' }))).toContain('purged_content');
expect(await errorText(call('put_page', { slug: SLUG, content: CONTENT, request_id: randomUUID() }))).toContain('purged_content');
await importFromContent(engine, 'notes/edited', CONTENT.replace('AKIA-EXAMPLE-NOT-REAL', 'rotated'), { noEmbed: true, sourceId: 'default' });
diff --git a/test/purge-import-screen.test.ts b/test/purge-import-screen.test.ts
new file mode 100644
index 0000000000..82a12eb59e
--- /dev/null
+++ b/test/purge-import-screen.test.ts
@@ -0,0 +1,41 @@
+/**
+ * #5575 CEO-8: the pure import screen refuses content whose content hash
+ * matches a prefetched page purge tombstone (managed sync then holds the file
+ * as `purged_content`, with the owner's fix); edited content and an empty
+ * tombstone map pass. No database.
+ */
+import { describe, expect, test } from 'bun:test';
+import { screenImportContent } from '../src/core/import-screen.ts';
+import { screenSyncImport } from '../src/core/persistence/sync-prepare.ts';
+import { gitHoldFix } from '../src/core/persistence/sync-holds.ts';
+import { parseMarkdown } from '../src/core/markdown.ts';
+import { contentHash } from '../src/core/utils.ts';
+
+const CONTENT = '---\ntitle: Leaked key\ntype: note\n---\n# Leaked key\n\nThe key is AKIA-EXAMPLE-NOT-REAL.\n';
+
+describe('purged-page import screen', () => {
+ const hash = contentHash(parseMarkdown(CONTENT, 'notes/leaked-key.md', { validate: true }));
+ const tombstones = new Map([[hash, 'notes/leaked-key']]);
+
+ test('matching content is refused under any slug; edited content and no tombstones pass', () => {
+ for (const path of ['notes/leaked-key.md', 'archive/renamed.md']) {
+ const screen = screenImportContent({ content: CONTENT, path, purgedPages: tombstones });
+ expect(screen.status).toBe('refused');
+ if (screen.status === 'refused') {
+ expect(screen.refusal.code).toBe('purged_content');
+ expect(screen.refusal.message).not.toContain('AKIA');
+ }
+ }
+ expect(screenImportContent({ content: CONTENT.replace('AKIA-EXAMPLE-NOT-REAL', 'rotated'), path: 'notes/leaked-key.md', purgedPages: tombstones }).status).toBe('importable');
+ expect(screenImportContent({ content: CONTENT, path: 'notes/leaked-key.md' }).status).toBe('importable');
+ });
+
+ test('the managed sync screen holds it and the hold names the owner fix', () => {
+ const { screen } = screenSyncImport({ content: CONTENT, rawHash: null, lineEndingOnly: false, slug: 'notes/leaked-key', sourcePath: 'notes/leaked-key.md',
+ path: 'notes/leaked-key.md', root: '/nonexistent', snapshot: null, base: null, renamed: false, purgedPages: tombstones });
+ expect(screen.status === 'refused' && screen.refusal.code).toBe('purged_content');
+ const fix = gitHoldFix({ source_id: 'default', path: 'notes/leaked-key.md', code: 'purged_content', meta: { recovery_version: 1 } as never });
+ expect(fix.argv).toEqual(['gbrain', 'pages', 'purges', 'list', '--source', 'default']);
+ expect(fix.actor).toBe('user');
+ });
+});