Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: default-off sync.apply_held_deletions deletes a held committed deletion the page proves
garrytan091db673a651
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 58c20a4223..d927d97dda 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2309,6 +2309,27 @@ the only copy of that content. Recreate its file withkeep it. `gbrain repair ghost-pages` lists such a page apart the same way, andthe soft-delete itself refuses one (`refused`, `database_ahead_of_file`).+<a id="apply-held-deletions"></a>**Letting sync apply proven deletions (`sync.apply_held_deletions`, off by+default).** `gbrain config set sync.apply_held_deletions true` (or+`sync.apply_held_deletions.source.<id> true` for one source; a per-source value+wins) lets a managed sync delete a held `file_gone` page itself, and only when+every check passes: the file's provenance is `deleted_by_commit`, the page at+its current revision equals the file's last committed bytes (the blob in the+first parent of the newest deleting commit, compared the way sync compares a+file with a page before replacing it), and the page's revision is file-backed+by the test above. The deletion is an ordinary sync deletion: a soft delete+with the same restore window (`gbrain restore <slug> --force`), counted by the+mass-delete valve and the `sync.max_deletes` / `sync.max_delete_ratio` caps,+and its write request carries `heldDeletion` (the deleting commit and the blob)+as the page's receipt. Any other held page stays held, and its hold records why+(`meta.held_deletion.refused`: `content_differs`, `database_ahead_of_file`,+`not_deleted_by_commit` or `page_changed`) at the page's revision, so it is not+screened again until the page changes. A file deleted, committed again with+other bytes and deleted again is judged against its last committed bytes.+Turning the switch on makes the next sync read the whole source once; a sync+screens at most 200 held deletions, and the rest wait for a later sync that+reads the source (a new commit, or the daily full round).+`--provenance never_committed --prefer file` is refused: it would soft-deletethe only copy of each page. A database-only page is no longer screened againsta file; a file synced back at its old path binds it again. The apply re-checksdiff --git a/llms-full.txt b/llms-full.txtindex 6dcd0e7cfe..215f9399d6 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -7193,7 +7193,10 @@ indexed at such a path is kept (#1433). This is `sync.metafile_pages`:`typed` (the default) or `off`, which skips every meta file as before(`gbrain config set sync.metafile_pages off`). The first sync after the upgrade,or after setting it back to `typed`, imports the typed files already in the-tree once; it deletes or rewrites nothing else.+tree once; it deletes or rewrites nothing else. A meta file whose frontmatter+`slug:` names another page (`slug: projects/acme-example` in+`projects/acme-example/index.md`) stays skipped, since the slug conflicts with+its path; remove the `slug:` line to make it a page (#7341).A dot-directory you deliberately keep content in (say `.decisions/`) can bewaived back in with `--include-hidden '<glob>'` on `gbrain sync` — the globdiff --git a/src/commands/config.ts b/src/commands/config.tsindex 9e7d534379..7ea6b9cfa8 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -382,7 +382,7 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:if (await setLineGrammarConfig(engine, key, value)) return;if (key === 'sync.admission') return (await import('./config/sync-admission-value.ts')).setSyncAdmissionValue(engine, value);if (key === 'sync.metafile_pages') return (await import('./config/sync-metafile-pages-value.ts')).setMetafilePagesValue(engine, value);- if (/^sync\.max_delete(s|_ratio)(\.source\..+)?$/.test(key) || key === 'purge.retention_hours') {+ if (/^sync\.(max_delete(s|_ratio)|apply_held_deletions)(\.source\..+)?$/.test(key) || key === 'purge.retention_hours') {const err = (await import('../core/sync-reconcile.ts')).deleteSafetyConfigRefusal(key, value);if (err) { console.error(`[config] ${err}`); process.exit(1); }}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 60e7324422..4ccf2088ae 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1156,6 +1156,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.397.0', text: 'A `file_drift` hold (side `deleted`, state `file_gone`) for a missing file whose Git history read did not finish now carries `meta.reason` `origin_unknown` and says Git could not show whether a commit held the file, instead of `never_committed` and "Git never committed it". The page is still kept, and the `--held` preview still reads the whole history and names the provenance.' },// #7364 (GBRA-133 wave 3). `since` is restamped at the merge slot.{ since: '0.60.397.0', text: '`gbrain sources reconcile --apply` that commits and leaves the page and its canonical file agreeing now clears that file\'s `preparation_stalled` or `write_interrupted` sync hold (the write owner stalled, not the file), and its result names the cleared row (`cleared_hold`); a file that still differs keeps its hold. A page write refused for a held file now names the hold row it read in its message (`Hold row: source <id>, incarnation <uuid>.`), and `gbrain sources retry-held --json` reports the rows it read (`hold_rows`) and each held file\'s `fingerprint`, so a refusal naming a row the listing does not show can be told apart (#7364).' },+ // #7341 (GBRA-133 wave 3). `since` is restamped at the merge slot.+ { since: '0.60.397.0', text: 'A nested folder-scaffolding file (`index.md`, `README.md`, `log.md`, `schema.md`, `RESOLVER.md`) whose frontmatter `slug:` names another page, for example `slug: projects/acme-example` in `projects/acme-example/index.md`, is skipped by sync again, as before 0.60.337.0, even when it has `type:` or `title:`. Since then it was imported only to be held `frontmatter_slug_conflict`, so a folder of such hubs became one hold per file. The next sync releases those holds. One whose `slug:` is its own path slug, or that has none, is still a page; remove the `slug:` line to make a skipped one a page.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/config.ts b/src/core/config.tsindex 59ca651196..f0e6c86956 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1735,7 +1735,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['orphans.exclude_slugs','sync.cost_gate_min_usd','sync.admission', // #6712 PR 4b: normal | imports_only | classify_only, what a managed pass admits (persistence/sync-admission.ts)- 'sync.max_deletes', 'sync.max_delete_ratio', // #7130: absolute caps on one managed pass's deletes (sync-reconcile.ts); per source: <key>.source.<id>+ 'sync.max_deletes', 'sync.max_delete_ratio', 'sync.apply_held_deletions', // #7130 delete caps (sync-reconcile.ts), GBRA-133 held-deletion switch (persistence/sync-held-deletions.ts); per source: <key>.source.<id>'purge.retention_hours', // #7130: hours a soft-deleted page waits before the autopilot purge phase may purge it (default 72)'sync.federated_v2','sync.include_working_tree',@@ -1842,7 +1842,7 @@ export const KNOWN_CONFIG_KEY_PREFIXES: readonly string[] = ['minions.','pace.', // pace.mode + PACE_MODE_CONFIG_KEYS (src/core/pace-mode.ts)'decide.', // System One decide.* (validated by src/core/ai/decide/config.ts DECIDE_CONFIG_KEYS)- 'sync.max_deletes.source.', 'sync.max_delete_ratio.source.', // #7130: per-source delete caps (sync-reconcile.ts readSyncDeleteCaps)+ 'sync.max_deletes.source.', 'sync.max_delete_ratio.source.', 'sync.apply_held_deletions.source.', // #7130 per-source delete caps, GBRA-133 per-source held-deletion switch'connectors.', // chat-connectors: source_id, sync_floor_min, embed_kickoff_min_pages, doctor_stale_hours, <provider>.{auto_sync,last_sync_at,auth_error_at,watermark_iso} (no secrets — creds are file-plane)];diff --git a/src/core/persistence/sync-classify.ts b/src/core/persistence/sync-classify.tsindex 067d0779a6..7f607ad932 100644--- a/src/core/persistence/sync-classify.ts+++ b/src/core/persistence/sync-classify.ts@@ -100,6 +100,10 @@ export interface SyncClassified {pending?: 'keep_db';/** #6712 PR 4b: a write `sync.admission` pauses (`paused_keep_db`, §8). */paused?: 'keep_db';+ /** GBRA-133 (sync-held-deletions.ts): a held committed deletion `sync.apply_held_deletions` proved, deleted with this receipt. */+ heldDeletion?: { commit: string; blob_oid: string };+ /** GBRA-133: why that proof refused this held deletion; its hold records it at the page's revision. */+ heldDeletionRefused?: string;}const CLEAN = new Set<SyncDirtiness | null>(['clean', 'clean_eol', 'clean_lfs']);diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 0175d25dae..a9ba86d746 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -58,7 +58,9 @@ export interface SyncEntry { path: string; sourcePath: string; action: 'import'/** #6729 x #6727: the one legacy page carries an explicit frontmatter id that differs from the file's, so it is another document; held `legacy_slug_conflict` (`explicit_id_conflict`). */legacyIdVeto?: true;/** #6948: several live pages record this file as their origin; the freeze holds it `origin_conflict` (sync.holds=fail refuses). */- originConflict?: OriginConflict; }+ originConflict?: OriginConflict;+ /** GBRA-133: a held committed deletion `sync.apply_held_deletions` proved (sync-held-deletions.ts); its request carries the proof as the receipt. */+ heldDeletion?: { commit: string; blob_oid: string }; }/** Files that map to a slug another origin keeps; they are left out of the manifest until one is renamed. */export interface SyncSlugCollision { slug: string; kept: string; skipped: string[]; }/** #5032: a file sync skipped on this host with a named refusal, without failing the run. */diff --git a/src/core/persistence/sync-held-deletions.ts b/src/core/persistence/sync-held-deletions.tsnew file mode 100644index 0000000000..19df3c32b4--- /dev/null+++ b/src/core/persistence/sync-held-deletions.ts@@ -0,0 +1,128 @@+/**+ * GBRA-133 wave 3: `sync.apply_held_deletions` (default `false`; per source `sync.apply_held_deletions.source.<id>`). A+ * managed pass holds a live page whose file a commit deleted when nothing proves the page still holds what the file held+ * (no import record or attestation of its revision: sync-classify.ts `delete_drift`, state `file_gone`), and+ * `gbrain repair file-drift --held --provenance deleted_by_commit` is how a person resolves it. With the switch on, the pass+ * deletes such a page itself, and only when every one of these holds:+ *+ * - the newest commit of HEAD's history that deleted the file is known (`deleted_by_commit`, sync-origin-evidence.ts);+ * - the page, at the revision the level read, equals the file's last committed bytes (the blob that commit's first parent+ * held), by the canonical comparison the coordinator applies before it replaces a file (`fileMatchesSnapshot`);+ * - the page's revision is file-backed by the test `repair ghost-pages` applies (#7382, `ghostFileBacked`), so a page+ * written in the database after its file last held it is never deleted, even with equal content.+ *+ * The deletion is an ordinary `managed_sync_delete`: a soft delete with the restore window every sync delete has, under+ * the mass-delete valve and the #7130 caps, leaving a tombstone the automatic purge holds. Its request carries+ * `heldDeletion` (the deleting commit and the blob compared), which is the page's receipt. A page the proof refuses stays+ * held, and its hold records the refusal at that page revision (`held_deletion`), so a later pass screens it again only+ * after the page changes. A pass screens at most `PASS_HELD_DELETION_MAX` paths.+ */+import { promisify } from 'node:util';+import type { BrainEngine } from '../engine.ts';+import { execFile } from '../spawn.ts';+import { gitChildEnv } from '../git-env.ts';+import { ghostFileBacked } from '../repair/ghost-pages.ts';+import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';+import { fileMatchesSnapshot } from './page-prepare.ts';+import type { ManagedSyncContext } from './sync-discovery.ts';+import { readBlobs } from './sync-git-stream.ts';+import { readGitSourceHolds } from './sync-holds.ts';+import { readDeletionProvenance } from './sync-origin-evidence.ts';+import type { ShadowLevel, ShadowPath } from './sync-pass.ts';++const execFileAsync = promisify(execFile);++export const SYNC_APPLY_HELD_DELETIONS_KEY = 'sync.apply_held_deletions';+/** Held deletions one pass screens (git and database reads per path). */+export const PASS_HELD_DELETION_MAX = 200;+const BLOB_MAX_BYTES = 8 * 1024 * 1024;++/** The deleting commit and the blob the page was compared with: the receipt a held deletion's request carries. */+export interface HeldDeletionProof { commit: string; blob_oid: string }+/** Why the proof refused a held deletion. `provenance_unknown` and `blob_unreadable` are not recorded, so the next pass tries again. */+export type HeldDeletionRefusal = 'not_deleted_by_commit' | 'provenance_unknown' | 'blob_unreadable' | 'content_differs' | 'database_ahead_of_file' | 'page_changed';+const TRANSIENT: ReadonlySet<HeldDeletionRefusal> = new Set(['provenance_unknown', 'blob_unreadable']);++export interface HeldDeletionState { screened: Set<string>; applied: number; refused: number }+export const newHeldDeletionState = (): HeldDeletionState => ({ screened: new Set(), applied: 0, refused: 0 });++/** Whether the switch is on for `sourceId` (the per-source key wins over the brain-wide one; only `true` turns it on). */+export async function heldDeletionsEnabled(engine: { getConfig(key: string): Promise<string | null> }, sourceId: string): Promise<boolean> {+ const value = (await engine.getConfig(`${SYNC_APPLY_HELD_DELETIONS_KEY}.source.${sourceId}`)) ?? await engine.getConfig(SYNC_APPLY_HELD_DELETIONS_KEY);+ return value?.trim().toLowerCase() === 'true';+}++/**+ * Settles the round's held committed deletions the proof accepts as deletes (`heldDeletion` on the result) and marks+ * the ones it refuses (`heldDeletionRefused`), turning a settled hold back into a `delete_drift` so the pass records the+ * refusal on it. A no-op while the switch is off.+ */+export async function applyHeldDeletions(engine: BrainEngine, level: ShadowLevel, context: ManagedSyncContext, state: HeldDeletionState): Promise<void> {+ if (!await heldDeletionsEnabled(engine, level.sourceId)) return;+ const holdPath = (entry: ShadowPath) => level.scope ? entry.path.slice(level.scope.length + 1) : entry.path;+ const page = (entry: ShadowPath) => entry.slug !== null && entry.pageId !== null && entry.revision !== null && entry.state.page?.live === true;+ const fresh = level.paths.filter(entry => entry.result.cls === 'delete_drift' && entry.result.state === 'file_gone' && !entry.result.uncommitted && !entry.result.settled && !entry.result.inFlight && page(entry));+ const resting = level.paths.filter(entry => entry.result.cls === 'held' && entry.result.settled && entry.state.level === null && !entry.state.present && page(entry));+ let held: ShadowPath[] = [];+ if (resting.length) {+ const holds = new Map((await readGitSourceHolds(engine, { sourceIds: [level.sourceId] })).flatMap(source => source.incarnation === level.incarnation ? source.holds : []).map(hold => [hold.path, hold]));+ held = resting.filter(entry => {+ const hold = holds.get(holdPath(entry));+ return hold?.code === 'file_drift' && hold.meta.state === 'file_gone' && !hold.meta.reason && hold.meta.held_deletion?.page_revision !== entry.revision;+ });+ }+ const batch = [...fresh, ...held].filter(entry => !state.screened.has(entry.path)).slice(0, Math.max(0, PASS_HELD_DELETION_MAX - state.screened.size));+ if (!batch.length) return;+ for (const entry of batch) state.screened.add(entry.path);+ const verdicts = await proveHeldDeletions(engine, level, context, batch, holdPath);+ for (const entry of batch) {+ const verdict = verdicts.get(entry.path)!;+ if ('commit' in verdict) {+ state.applied++;+ entry.result = { ...entry.result, cls: 'delete', settled: false, inFlight: false, action: 'delete', classAction: 'owner', heldDeletion: verdict };+ continue;+ }+ state.refused++;+ entry.result = { ...entry.result, cls: 'delete_drift', settled: false, inFlight: false, action: 'hold', classAction: 'repair', side: 'deleted', state: 'file_gone',+ ...(TRANSIENT.has(verdict.refused) ? {} : { heldDeletionRefused: verdict.refused }) };+ }+}++async function proveHeldDeletions(engine: BrainEngine, level: ShadowLevel, context: ManagedSyncContext, batch: ShadowPath[], holdPath: (entry: ShadowPath) => string):+ Promise<Map<string, HeldDeletionProof | { refused: HeldDeletionRefusal }>> {+ const verdicts = new Map<string, HeldDeletionProof | { refused: HeldDeletionRefusal }>();+ const provenance = await readDeletionProvenance(level.gitRoot, batch.map(entry => entry.path));+ const parents = new Map<string, { commit: string; oid: string | null }>();+ for (const entry of batch) {+ const found = provenance.get(entry.path);+ if (found?.kind !== 'deleted_by_commit') { verdicts.set(entry.path, { refused: !found || found.kind === 'unknown' ? 'provenance_unknown' : 'not_deleted_by_commit' }); continue; }+ parents.set(entry.path, { commit: found.commit, oid: await lastCommittedBlob(level.gitRoot, found.commit, entry.path) });+ }+ const blobs = await readBlobs(level.gitRoot, [...new Set([...parents.values()].flatMap(parent => parent.oid ? [parent.oid] : []))], BLOB_MAX_BYTES).catch(() => new Map<string, Buffer>());+ const activePack = (await loadActivePackForEngine(engine, { remote: false, sourceId: level.sourceId }).catch(() => null))?.manifest;+ const owner = { host_id: context.binding.owner_host_id ?? '', worktree_id: context.binding.worktree_id, owner_epoch: String(context.binding.owner_epoch), source_incarnation: level.incarnation };+ for (const entry of batch) {+ const parent = parents.get(entry.path);+ if (!parent) continue;+ const bytes = parent.oid ? blobs.get(parent.oid) : undefined;+ if (!bytes) { verdicts.set(entry.path, { refused: 'blob_unreadable' }); continue; }+ const snapshot = await engine.readPageSnapshot(entry.slug!, { sourceId: level.sourceId });+ if (!snapshot || snapshot.revision !== entry.revision || Number(snapshot.page.id) !== entry.pageId) { verdicts.set(entry.path, { refused: 'page_changed' }); continue; }+ const sourcePath = level.slugMode === 'source-root' ? holdPath(entry) : entry.path;+ const same = await fileMatchesSnapshot(engine, entry.slug!, bytes.toString('utf8'), snapshot, sourcePath, activePack).catch(() => false);+ if (!same) { verdicts.set(entry.path, { refused: 'content_differs' }); continue; }+ const backed = await ghostFileBacked(engine, { source_id: level.sourceId, slug: entry.slug!, path: holdPath(entry), revision: entry.revision!, page_id: entry.pageId! }, owner);+ verdicts.set(entry.path, backed ? { commit: parent.commit, blob_oid: parent.oid! } : { refused: 'database_ahead_of_file' });+ }+ return verdicts;+}++/** The blob `path` held in the deleting commit's first parent: the file's last committed bytes. */+async function lastCommittedBlob(gitRoot: string, commit: string, path: string): Promise<string | null> {+ try {+ const { stdout } = await execFileAsync('git', ['-C', gitRoot, 'rev-parse', '--verify', '--quiet', `${commit}^1:${path}`], { env: gitChildEnv(), encoding: 'utf8', timeout: 60_000 });+ return stdout.trim() || null;+ } catch {+ return null;+ }+}diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 9217d05f37..2a59c219aa 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -180,6 +180,8 @@ export interface GitHoldMeta {write_failure?: PageWriteFailureMeta;/** #6278: the held entry is a deletion (the file is gone); discovery re-screens it on request or a gbrain change, not on its absence. */deleted?: true;+ /** GBRA-133 `file_drift` `file_gone`: `sync.apply_held_deletions` refused this deletion (sync-held-deletions.ts) while the page was at `page_revision`. */+ held_deletion?: { refused: string; page_revision: string };/*** #6712 dependency edge: the path of an earlier entry of the same sync, sharing this entry's slug or page id, that was* held in that sync; this entry waits on it with the same code, and discovery re-screens it once that hold is gone.diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.tsindex 268634cc59..c21e36b145 100644--- a/src/core/persistence/sync-pass-apply.ts+++ b/src/core/persistence/sync-pass-apply.ts@@ -61,6 +61,7 @@ import { decideOriginTwins, readOriginClaimants, slugPathOccupied, type OriginCoimport { originConflictHold } from './sync-screen.ts';import { readSyncFile } from './sync-discovery.ts';import { frontmatterIdentity } from '../sync-rename-identity.ts';+import { applyHeldDeletions, newHeldDeletionState, type HeldDeletionState } from './sync-held-deletions.ts';/** Legacy pages the sweep screens per pass after the incarnation's first full round (design §2.7, [estimated]). */export const PASS_LEGACY_SWEEP_MAX = 500;@@ -99,11 +100,13 @@ export interface PassApplyState {* page). The next round's confirm proof attributes those records to the pass.*/recorded: Set<number>;+ /** GBRA-133: the held committed deletions `sync.apply_held_deletions` screened this pass (sync-held-deletions.ts). */+ heldDeletions: HeldDeletionState;}export function newPassApplyState(): PassApplyState {return { markersRetired: 0, holds: { file_gone: 0, tombstone_edited: 0, purged_differs: 0, settle_mismatch: 0, origin_conflict: 0, page_identity_changed: 0, uncommitted: 0 }, settleMismatch: [], adopted: 0,- swept: { screened: 0, recorded: 0, paths: new Set() }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], originHeld: new Set(), matchedSlugs: new Set(), classes: {}, summary: null, recorded: new Set() };+ swept: { screened: 0, recorded: 0, paths: new Set() }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], originHeld: new Set(), matchedSlugs: new Set(), classes: {}, summary: null, recorded: new Set(), heldDeletions: newHeldDeletionState() };}export interface PassApplyInput {@@ -151,6 +154,7 @@ export async function applyPassRound(engine: BrainEngine, level: ShadowLevel, inif (!grantSees(level, entry, input.grantPrefixes) && !entry.result.settled) settleAs(entry, { settled: true, action: 'none', classAction: 'none' });}}+ if (!input.remote && input.admission === 'normal') await applyHeldDeletions(engine, level, input.context, state.heldDeletions);await applyDeleteValve(engine, level, input, state);if (input.remote) {// #6948: a remote pass writes no hold, so a path several live pages claim is left as it is for the owner's pass to hold.@@ -308,7 +312,8 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Papending.push({ entry, code: 'file_drift', slug: entry.slug, kind: 'uncommitted', meta: { side: 'deleted', state: 'file_gone', reason: r.uncommitted, ...(entry.revision ? { page_revision: entry.revision } : {}) },message: `${path}: the file is gone, but ${why}, so its absence is no evidence that page ${entry.slug} was deleted; sync held it and kept the page instead of deleting it (#7130); the rest of the source synced.` });} else if (r.cls === 'delete_drift') {- pending.push({ entry, code: 'file_drift', slug: entry.slug, kind: 'file_gone', meta: { side: 'deleted', state: 'file_gone', ...(entry.revision ? { page_revision: entry.revision } : {}) },+ pending.push({ entry, code: 'file_drift', slug: entry.slug, kind: 'file_gone', meta: { side: 'deleted', state: 'file_gone', ...(entry.revision ? { page_revision: entry.revision } : {}),+ ...(r.heldDeletionRefused && entry.revision ? { held_deletion: { refused: r.heldDeletionRefused, page_revision: entry.revision } } : {}) },message: `${path}: the file is gone, but page ${entry.slug} changed in the database since the file was last imported, so sync held the deletion instead of deleting the page; the rest of the source synced.` });} else if (r.cls === 'deleted_edited') {const purged = r.state === 'purged_differs';@@ -556,5 +561,5 @@ export function passApplyCounts(state: PassApplyState): Record<string, number> {return { markers_retired: state.markersRetired, holds_file_gone: state.holds.file_gone, holds_tombstone_edited: state.holds.tombstone_edited,holds_purged_differs: state.holds.purged_differs, holds_settle_mismatch: state.holds.settle_mismatch, holds_origin_conflict: state.holds.origin_conflict, holds_page_identity_changed: state.holds.page_identity_changed, holds_uncommitted: state.holds.uncommitted, adopted: state.adopted, legacy_swept: state.swept.screened,legacy_recorded: state.swept.recorded, deletes_withheld: state.withheldCount, keep_db_admitted: state.keepDb.admitted, keep_db_pending: state.keepDb.pending,- paused_keep_db: state.keepDb.paused, keep_db_refused: refused };+ paused_keep_db: state.keepDb.paused, keep_db_refused: refused, held_deletions_applied: state.heldDeletions.applied, held_deletions_refused: state.heldDeletions.refused };}diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 691effb27e..586a318b3d 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -52,6 +52,7 @@ import { withCoordinatedWrite } from './context.ts';import { pipelined } from '../page-state/transactions.ts';import { principalAttribution } from './attribution.ts';import { isCodeFilePath, readMetafilePagesMode, resolveSlugForPath } from '../sync.ts';+import { heldDeletionsEnabled } from './sync-held-deletions.ts';import { syncOriginPath } from './sync-origin.ts';import { databaseOnlyPageSql } from './unbound-pages.ts';import { originMarkerFingerprint } from './sync-markers.ts';@@ -152,7 +153,7 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Shawait faultPoint('sync:batch_entries', { sourceId: level.sourceId });const working = (entry: ShadowPath) => level.mode === 'working' && entry.state.level !== entry.state.tree;const deleteEntries = new Map<string, PassEntry>(deletes.map(entry => [entry.path, { ...entryPaths(level, entry.path), action: 'delete' as const, working: level.mode === 'working',- slug: entry.slug!, pageId: entry.pageId, revision: entry.revision, level: null }]));+ slug: entry.slug!, pageId: entry.pageId, revision: entry.revision, level: null, ...(entry.result.heldDeletion ? { heldDeletion: entry.result.heldDeletion } : {}) }]));const leaving = new Map(deletes.map(entry => [entry.path, entry]));const fresh = imports.filter(entry => !entry.state.page);// Same-blob twins per level, and the leaving pages per recorded blob, counted once: a scan per winner was quadratic.@@ -385,7 +386,9 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNull// GBRA-150: `sync.metafile_pages typed` widens the level's universe, so it joins the selection fingerprint (`off` keeps// the fingerprint an older pass stamped): the first pass after the upgrade or a flip reads the whole level once.const metafilePages = await readMetafilePagesMode(engine);- const selectionFp = digest(metafilePages === 'off' ? selection : { ...selection, metafile_pages: metafilePages }), parserFp = parserFingerprint();+ // GBRA-133: so does `sync.apply_held_deletions` when on (sync-held-deletions.ts): turning it on reads the level, and its held deletions, once.+ const heldDeletions = await heldDeletionsEnabled(engine, sourceId);+ const selectionFp = digest({ ...selection, ...(metafilePages === 'off' ? {} : { metafile_pages: metafilePages }), ...(heldDeletions ? { apply_held_deletions: true } : {}) }), parserFp = parserFingerprint();const obligations: ManagedSyncPassValue['obligations'] = prior ? structuredClone(prior.value.obligations): { baseline_commit: context.source.last_commit, mismatch: {}, not_converged_streak: 0, faults: {} };obligations.mismatch ??= {}; obligations.faults ??= {}; obligations.not_converged_streak ??= 0;diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 7fe9247f8a..68c5ae768d 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -85,6 +85,8 @@ export interface SyncIntent extends Record<string, unknown> {lineEndingOnly?: boolean;/** #5565: the deleted file is no page's origin; publication only re-proves that and commits a no-op. */unownedDeletion?: boolean;+ /** GBRA-133: a held committed deletion `sync.apply_held_deletions` proved: the deleting commit and the blob the page equals. */+ heldDeletion?: { commit: string; blob_oid: string };working?: boolean;renameFrom?: SyncRename;processingOptions?: SyncProcessingOptions;diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 120dd2168f..8e30b5fec3 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -480,7 +480,7 @@ async function freezeEntryOnce(engine: BrainEngine, cursor: Cursor, key: string,const passLevel = cursor.passId ? (entry as PassEntry | undefined)?.level ?? (entry ? null : cursor.target) : undefined;return remember(frozenSnapshot, { requestId: cursor.passId ? passRequestId(cursor.passId, entry?.path ?? slug, passLevel!) : randomUUID(), slug, pageId, ...(occupantRebound ? { rebound: true as const } : {}), intent: { kind: !entry ? 'managed_sync_checkpoint' : entry.action === 'import' ? 'managed_sync_import' : 'managed_sync_delete',expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly, ...(bodyRef ? { body_ref: bodyRef } : {}),- ...(entry?.unownedDeletion ? { unownedDeletion: true } : {}),+ ...(entry?.unownedDeletion ? { unownedDeletion: true } : {}), ...(entry?.heldDeletion ? { heldDeletion: entry.heldDeletion } : {}),...(entry?.renameFrom ? { renameFrom: entry.renameFrom } : {}),...(run.observedAt ? { holdObservedAt: run.observedAt } : {}), ...(blob ? { blobOid: blob.oid } : {}), ...(entry && run.embedDeferred ? { embedDeferred: true } : {}),...(!entry && cursor.releasedHolds?.length ? { releasedHolds: cursor.releasedHolds } : {}),diff --git a/src/core/sync-reconcile.ts b/src/core/sync-reconcile.tsindex 3b8a7c16b2..1c5c26d568 100644--- a/src/core/sync-reconcile.ts+++ b/src/core/sync-reconcile.ts@@ -49,6 +49,7 @@ export function parseSyncDeleteCap(key: typeof SYNC_MAX_DELETES_KEY | typeof SYN/** `gbrain config set`'s refusal of an invalid #7130 delete-safety value (null: valid). */export function deleteSafetyConfigRefusal(key: string, value: string): string | null {if (key === 'purge.retention_hours') return parsePurgeRetentionHours(value) === null ? `purge.retention_hours must be a whole number of hours, at least ${MIN_PURGE_RETENTION_HOURS}; nothing was written.` : null;+ if (key.startsWith('sync.apply_held_deletions')) return ['true', 'false'].includes(value.trim().toLowerCase()) ? null : `${key} must be true or false; nothing was written.`;const base = key.startsWith(SYNC_MAX_DELETES_KEY + '.') || key === SYNC_MAX_DELETES_KEY ? SYNC_MAX_DELETES_KEY : SYNC_MAX_DELETE_RATIO_KEY;if (parseSyncDeleteCap(base, value) !== null) return null;return base === SYNC_MAX_DELETES_KEY ? `${key} must be a whole number of pages, 0 or more; nothing was written.` : `${key} must be a number from 0 to 1 (a share of the source's file-backed pages); nothing was written.`;diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 2b01de4568..9930406b6b 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -422,6 +422,7 @@ test/sources-resolve-path.test.tstest/stats-health-source-scope.test.tstest/sync-absent-from-worktree-s27.test.tstest/sync-admission-6712.test.ts+test/sync-apply-held-deletions-gbra133.test.tstest/sync-capacity-preflight.test.tstest/sync-checkpoint-moved-6834.test.tstest/sync-discovery-legacy-origin-7130.test.ts@@ -449,6 +450,7 @@ test/sync-legacy-holds.test.tstest/sync-legacy-retry-actions-6696.test.tstest/sync-legacy-slug-adoption-6727.test.tstest/sync-legacy-sweep-resume-7189.test.ts+test/sync-metafile-foreign-slug-7341.test.tstest/sync-origin-live-wins-6517.test.tstest/sync-page-identity-hold-gbra130.test.tstest/sync-page-write-failed-gbra130.test.tsdiff --git a/test/sync-apply-held-deletions-gbra133.test.ts b/test/sync-apply-held-deletions-gbra133.test.tsnew file mode 100644index 0000000000..bea434bad0--- /dev/null+++ b/test/sync-apply-held-deletions-gbra133.test.ts@@ -0,0 +1,98 @@+/**+ * GBRA-133 wave 3: `sync.apply_held_deletions` (default off). A managed pass holds a live page whose file a commit deleted+ * when nothing proves the page still holds what the file held (an older import: no import record, no write request).+ * With the switch on, the pass deletes such a page itself only when the page equals the file's last committed blob and+ * its revision is file-backed by the #7382 test; every other held deletion stays held and its hold records why.+ * - a page equal to the deleted file's last committed bytes is soft-deleted by the pass, with a receipt (its+ * `managed_sync_delete` request names the deleting commit and the blob) and a restorable version;+ * - a page whose content differs from that blob is kept (`content_differs`);+ * - a page written in the database after the deleting commit is kept even with equal content (`database_ahead_of_file`);+ * - a path deleted, re-added with other bytes and deleted again is judged against the re-added bytes, its last+ * committed blob, so a page holding the first version is kept (`content_differs`);+ * - with the switch off nothing changes: all four stay held. A refused hold is not screened again while its page stays.+ * Before: no switch existed, so every proven held deletion waited for `gbrain repair file-drift`.+ * Real PGLite (and Postgres when DATABASE_URL is set), real managed syncs and real Git; older imports are modelled as+ * pages whose revision no import record or write request produced, last written an hour before the deleting commit.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const SLUGS = ['notes/a', 'notes/b', 'notes/c', 'notes/d'];++async function holds(engine: BrainEngine): Promise<Record<string, { code: string; meta: Record<string, any> }>> {+ const rows = await engine.executeRaw<{ record: { path: string; code: string; meta: Record<string, unknown> } }>("SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op='sync-hold'");+ return Object.fromEntries(rows.map(({ record }) => [record.path, record]));+}+const live = async (engine: BrainEngine) => (await engine.executeRaw<{ slug: string }>(+ "SELECT slug FROM pages WHERE source_id='default' AND deleted_at IS NULL AND slug LIKE 'notes/%' ORDER BY slug")).map(row => row.slug);++for (const backend of testBackends()) describe(`[${backend}] GBRA-133: sync.apply_held_deletions`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (const slug of SLUGS) writeFileSync(join(root, `${slug}.md`), note(slug, `The committed body of ${slug}.`));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'notes');+ };++ test('deletes only a page equal to its file\'s last committed blob, and keeps the rest held with the reason', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const coordinated = (sql: string, params: unknown[] = []) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));+ // Older imports: a revision no import record or sync request produced, last written an hour ago.+ await coordinated(`DELETE FROM op_checkpoints WHERE op='sync-import-provenance'+ AND completed_keys->0->>'page_id' IN (SELECT id::text FROM pages WHERE source_id='default' AND slug LIKE 'notes/%')`);+ for (const slug of SLUGS) await coordinated(`UPDATE pages SET knowledge_revision = $1::uuid, revision_write_request_id = NULL, updated_at = now() - interval '1 hour'+ WHERE source_id='default' AND slug=$2`, [randomUUID(), slug]);+ // notes/b moved on in the database (still before the deletion).+ await coordinated(`UPDATE pages SET compiled_truth = compiled_truth || ' Edited in the database.', knowledge_revision = $1::uuid WHERE source_id='default' AND slug='notes/b'`, [randomUUID()]);+ git(root, 'rm', '-q', ...SLUGS.map(slug => `${slug}.md`)); git(root, 'commit', '-qm', 'cull a, b, c and d');+ const cull = git(root, 'rev-parse', 'HEAD');+ const blobA = git(root, 'rev-parse', `${cull}^:notes/a.md`);+ // notes/d comes back with other bytes and is deleted again: its last committed blob is the second version.+ mkdirSync(join(root, 'notes'), { recursive: true });+ writeFileSync(join(root, 'notes/d.md'), note('notes/d', 'A second version of notes/d.'));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 're-add d');+ git(root, 'rm', '-q', 'notes/d.md'); git(root, 'commit', '-qm', 'cull d again');+ // notes/c is written in the database after the deleting commit, with the same content (a new revision, no write request).+ await coordinated(`UPDATE pages SET knowledge_revision = $1::uuid, updated_at = now() + interval '1 hour' WHERE source_id='default' AND slug='notes/c'`, [randomUUID()]);++ // Off (the default): every deletion is held, nothing is deleted.+ await performManagedSync(engine, OPTS);+ const off = await holds(engine);+ for (const slug of SLUGS) expect(off[`${slug}.md`]).toMatchObject({ code: 'file_drift', meta: { side: 'deleted', state: 'file_gone' } });+ for (const slug of SLUGS) expect(off[`${slug}.md`]!.meta.reason).toBeUndefined();+ expect(await live(engine)).toEqual(SLUGS);++ await engine.setConfig('sync.apply_held_deletions', 'true');+ await performManagedSync(engine, OPTS);+ expect(await live(engine)).toEqual(['notes/b', 'notes/c', 'notes/d']);+ const on = await holds(engine);+ expect(on['notes/a.md']).toBeUndefined();+ expect([on['notes/b.md']?.meta.held_deletion?.refused, on['notes/c.md']?.meta.held_deletion?.refused, on['notes/d.md']?.meta.held_deletion?.refused])+ .toEqual(['content_differs', 'database_ahead_of_file', 'content_differs']);+ // The receipt: an ordinary sync deletion of notes/a naming the deleting commit and the blob it equals, and a version to restore from.+ const receipts = await engine.executeRaw<{ slug: string; state: string; proof: { commit: string; blob_oid: string } }>(+ "SELECT slug, state, intent->'heldDeletion' AS proof FROM persistence_requests WHERE intent->>'kind'='managed_sync_delete' AND intent ? 'heldDeletion'");+ expect(receipts).toEqual([{ slug: 'notes/a', state: 'committed', proof: { commit: cull, blob_oid: blobA } }]);+ const [versions] = 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='default' AND p.slug='notes/a'");+ expect(versions!.n).toBeGreaterThan(0);++ // A refused hold is not screened again while its page stays at that revision.+ await performManagedSync(engine, { ...OPTS, full: true });+ expect(await live(engine)).toEqual(['notes/b', 'notes/c', 'notes/d']);+ const again = await holds(engine);+ for (const slug of ['notes/b', 'notes/c', 'notes/d']) expect(again[`${slug}.md`]!.meta.held_deletion).toEqual(on[`${slug}.md`]!.meta.held_deletion);+ }, { databaseUrl, setup }), 300_000);+});