Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): never-committed origins are not deletion evidence; absolute delete caps (#7130) [wip]
garrytanc54f60bdb3c8
diff --git a/src/commands/config.ts b/src/commands/config.tsindex 41d0d6f2e6..9b4ab7dd0c 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -380,6 +380,10 @@ const setLineGrammarConfig = async (engine: BrainEngine, key: string, value: strasync function setConfigWithDecideHooks(engine: BrainEngine, key: string, value: string, force = false): Promise<void> {if (await setLineGrammarConfig(engine, key, value)) return;if (key === 'sync.admission') return (await import('./config/sync-admission-value.ts')).setSyncAdmissionValue(engine, value);+ if (/^sync\.max_delete(s|_ratio)(\.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); }+ }if (key.startsWith('decide.')) {const { validateDecideConfigValue } = await import('../core/ai/decide/config.ts');const err = validateDecideConfigValue(key, value);diff --git a/src/core/config.ts b/src/core/config.tsindex 8c86e9d9a7..8feeaa2910 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1725,6 +1725,8 @@ 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>+ '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',// #5984: managed Postgres sync publishes pages in bulk groups (on by default; each page keeps its own request).@@ -1827,6 +1829,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)'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/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 2280bf736a..2cdec2586f 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -72,6 +72,7 @@ import { preparePageAdvisories, remoteLinkHint, pageNoopAdvisories, timelineRowsimport { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { colonSlugWindowsRefusal, isWindowsColonTarget, nativeFileTarget } from './native-file-target.ts';import { isSourceDbOnlySlug } from './source-storage.ts';+import { gitIgnoresUntracked } from './sync-origin-evidence.ts';import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { DERIVE_PHASE_DB_ONLY_DEFAULTS } from '../storage-config.ts';import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';@@ -293,6 +294,10 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequif (!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) });+ // #7130: a canonical file under a path the checkout's .gitignore excludes would never be committed, so the page would be+ // file-backed by a file no history holds (and a later sync could read its absence as a deletion). The write publishes+ // to the database only and binds no file; a declared db_only page keeps its cache file as before.+ if (!isSourceDbOnlySlug(root, row.slug, 'not_db_only') && await gitIgnoresUntracked(root, relative(root, path).split(sep).join('/'))) return undefined;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; }diff --git a/src/core/persistence/sync-classify.ts b/src/core/persistence/sync-classify.tsindex 12342c43de..3a46907def 100644--- a/src/core/persistence/sync-classify.ts+++ b/src/core/persistence/sync-classify.ts@@ -66,6 +66,11 @@ export interface SyncPathState {keepDb: boolean;/** Open work on the page or path (a queued/running/recovering request, a pending Git effect). */openWork: boolean;+ /**+ * #7130 (sync-origin-evidence.ts): for a live page whose file is absent, whether Git ever committed the file. Read only+ * for those paths; undefined until read. Anything but `committed` is no deletion evidence, so the page is held.+ */+ originEvidence?: 'committed' | 'never_committed' | 'ignored' | 'unknown';}export interface SyncClassified {@@ -83,6 +88,8 @@ export interface SyncClassified {/** `drift` and `delete_drift`: the hold's side. `deleted_edited`: its state. */side?: 'both' | 'unknown' | 'deleted';state?: 'tombstone_edited' | 'purged_differs' | 'file_gone';+ /** #7130: a `delete_drift` whose file Git never committed (`never_committed`, also when that could not be read) or `.gitignore` excludes. */+ uncommitted?: 'never_committed' | 'ignored';/** `db_ahead` `db_only` under keep_db: also gets the DB-wins write. */keepDbWrite?: true;/** `db_ahead` `db_only`/`unproven` under an open full obligation: excluded and counted (`full_skipped_db_ahead`). */@@ -139,8 +146,11 @@ function afterHold(s: SyncPathState): Matched {if (s.mode === 'committed' && s.tree === null && !live) return { cls: 'untracked', settled: true, action: 'none' };if (live && s.level === null) {if (s.mode === 'committed' && s.present) return { cls: 'kept', settled: true, action: 'none' };- if (!s.present) return proof ? { cls: 'delete', settled: false, action: 'delete' }- : { cls: 'delete_drift', settled: false, action: 'hold', side: 'deleted', state: 'file_gone' };+ if (!s.present) {+ if (s.originEvidence && s.originEvidence !== 'committed') return { cls: 'delete_drift', settled: false, action: 'hold', side: 'deleted', state: 'file_gone',+ uncommitted: s.originEvidence === 'ignored' ? 'ignored' : 'never_committed' };+ return proof ? { cls: 'delete', settled: false, action: 'delete' } : { cls: 'delete_drift', settled: false, action: 'hold', side: 'deleted', state: 'file_gone' };+ }}if (!live && s.level === null) return { cls: 'gone', settled: true, action: 'none' };if (!live) {diff --git a/src/core/persistence/sync-convergence.ts b/src/core/persistence/sync-convergence.tsindex fbf17b8066..de30932e30 100644--- a/src/core/persistence/sync-convergence.ts+++ b/src/core/persistence/sync-convergence.ts@@ -19,7 +19,7 @@*/import { createHash, randomUUID } from 'node:crypto';import type { BrainEngine } from '../engine.ts';-import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';+import { massReconcileAllowed, readSyncDeleteCaps, syncDeleteTrip, type SyncDeleteCaps, type SyncDeleteTrip } from '../sync-reconcile.ts';import { syncClassAction, type SyncClass, type SyncClassAction } from './sync-classify.ts';import { readBlobs } from './sync-git-stream.ts';import type { ShadowLevel, ShadowPath } from './sync-pass.ts';@@ -59,7 +59,7 @@ export interface ConvergenceReceipt {db_ahead_by_prefix: Record<string, number>; full_skipped_db_ahead: number;legacy_unverified: number; legacy_pageless: number;deletes: { count: number; reconcilable: number; ratio: number; verdict: 'apply' | 'withheld' | 'allowed_by_env'; set_hash: string | null; samples: string[] };- deletes_withheld: { count: number; ratio: number; set_hash: string | null; samples: string[] } | null;+ deletes_withheld: { count: number; ratio: number; set_hash: string | null; samples: string[]; trip?: SyncDeleteTrip; caps?: SyncDeleteCaps } | null;samples: Partial<Record<ConvergenceClassKey, ConvergenceSample[]>>;settle_mismatch: string[]; episode: null; admission: null; last_full_at: null;redacted: boolean; duration_ms: number; timings_ms: Record<string, number>; statements: number;@@ -94,7 +94,10 @@ export async function buildConvergenceReceipt(engine: BrainEngine, level: Shadowlet keepDbSeen = 0;const deletes = level.paths.filter(entry => entry.result.cls === 'delete' && !entry.result.inFlight);const ratio = level.reconcilable ? deletes.length / level.reconcilable : 0;- const tripped = level.reconcilable > MASS_RECONCILE_MIN_PAGES && deletes.length > level.reconcilable * MASS_RECONCILE_RATIO;+ // #7130: the same limits the pass applies (sync-pass-apply.ts): the 50% valve and the absolute caps.+ const caps = deletes.length ? await readSyncDeleteCaps(engine, level.sourceId) : null;+ const trip = caps ? syncDeleteTrip(deletes.length, level.reconcilable, caps) : null;+ const tripped = trip !== null;const verdict = !tripped ? 'apply' : massReconcileAllowed() ? 'allowed_by_env' : 'withheld';for (const entry of level.paths) {let key: ConvergenceClassKey = entry.result.inFlight ? 'in_flight' : entry.result.cls;@@ -175,7 +178,7 @@ export async function buildConvergenceReceipt(engine: BrainEngine, level: Shadowdb_ahead: dbAhead, db_ahead_by_prefix: dbAhead.by_prefix, full_skipped_db_ahead: fullSkipped,legacy_twin_pairs: twins, legacy_unverified: counts.legacy_unverified ?? 0, legacy_pageless: level.paths.filter(entry => entry.legacyPageless && entry.result.cls === 'legacy_same').length,deletes: { count: deletes.length, reconcilable: level.reconcilable, ratio: Math.round(ratio * 1000) / 1000, verdict, set_hash: setHash, samples: deleteSamples },- deletes_withheld: verdict === 'withheld' ? { count: deletes.length, ratio: Math.round(ratio * 1000) / 1000, set_hash: setHash, samples: deleteSamples } : null,+ deletes_withheld: verdict === 'withheld' ? { count: deletes.length, ratio: Math.round(ratio * 1000) / 1000, set_hash: setHash, samples: deleteSamples, trip: trip!, caps: caps! } : null,samples, settle_mismatch: [], episode: null, admission: null, last_full_at: null, redacted: opts.redactPaths,duration_ms: Math.round(level.timings_ms.total ?? 0), timings_ms: { ...level.timings_ms, screen: screenMs, legacy_twins: twinsMs, receipt: Math.round((performance.now() - started) * 10) / 10 },statements: level.statements,diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 1c8917dbd6..52575622ed 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -31,6 +31,7 @@ import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, readSyncImportProvenances } from './sync-holds.ts';import { readBlobContents, readTreeBlobs, SYNC_READ_BOUND } from './sync-blobs.ts';import { gitChildEnv } from '../git-env.ts';+import { readOriginEvidence } from './sync-origin-evidence.ts';import { movedDriftHolds, prescreenSyncEntries, type SyncDriftSide } from './sync-prescreen.ts';import { sliceEntries, type SyncSliceCursor, type SyncSliceState } from './sync-slices.ts';@@ -73,6 +74,8 @@ export interface SyncDiscovery { binding: WorktreeBinding; root: string; gitRootstagedHead?: string;/** #5459 (P4.5): live pages the tree walk left alone because their file is in the working tree and their import provenance is the working tree or unknown. */workingTreeKept?: string[];+ /** #7130: live pages whose file is absent but Git never committed it (or `.gitignore` excludes it): kept, never deleted. */+ uncommittedKept?: string[];/** #6349 (P4.4): this discovery is one path slice of its target; the checkpoint records it instead of advancing `last_commit` until `done`. */slice?: SyncSliceState;/** #6729: inexact Git renames split into a delete plus an add (origin form); recorded after the run commits. */@@ -348,6 +351,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cconst renamedFrom = new Map<string, { from: string; identityHead?: string }>();let workingTreeKept: string[] | undefined;let treeAbsent: Array<{ id: number; gitPath: string }> = [];+ // #7130: deletions no Git change names (a tree walk's absent pages, a re-screened held deletion) need a commit that held the file.+ const unproven = new Set<string>();const discoveredAt = new Date().toISOString();// #5988: active holds are re-screened when their file changed, left, or a newer reader may import it.const holds = company ? [] : (await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds.filter(hold => hold.incarnation === incarnation) ?? [];@@ -418,7 +423,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cif (treeAbsent.length) {// A path the selected working tree already decided (an import or a deletion above) is not re-judged.const kept = await keptWorkingTreePages(engine, { sourceId, incarnation, root, nativeRoot, nativeGitRoot }, treeAbsent.filter(page => !entries.has(page.gitPath)));- for (const page of treeAbsent) if (!entries.has(page.gitPath) && !kept.has(page.gitPath)) put(page.gitPath, 'delete');+ for (const page of treeAbsent) if (!entries.has(page.gitPath) && !kept.has(page.gitPath)) { put(page.gitPath, 'delete'); unproven.add(page.gitPath); }if (kept.size) workingTreeKept = [...kept];}// #6278 (B7): every scheduled path is consumed by this discovery: it is screened as an entry (the file changed in Git),@@ -451,8 +456,16 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c}if (!changed) continue;put(gitPath, present ? 'import' : 'delete', workingHold);+ if (!present) unproven.add(gitPath);}}+ let uncommittedKept: string[] | undefined;+ const unprovenDeletes = [...unproven].filter(path => entries.get(path)?.action === 'delete');+ if (unprovenDeletes.length && !company) {+ const evidence = await readOriginEvidence(gitRoot, [target, source.last_commit], unprovenDeletes);+ uncommittedKept = unprovenDeletes.filter(path => evidence.get(path) !== 'committed');+ for (const path of uncommittedKept) entries.delete(path);+ }if (company) {entries.clear();renamedFrom.clear();@@ -495,7 +508,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c}const discovered: SyncDiscovery = { discoveredAt, ...(released.length ? { releasedHolds: released } : {}), ...(retryTaken.length ? { retryTaken } : {}),...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}), ...(stage ? { stagedHead: stage.head } : {}),- ...(workingTreeKept ? { workingTreeKept } : {}), ...(company ? {} : identityDowngradesOf([delta?.status === 'ok' ? delta.manifest : null, working ? dirty : null], eligible, sourcePath)) };+ ...(workingTreeKept ? { workingTreeKept } : {}), ...(uncommittedKept?.length ? { uncommittedKept } : {}), ...(company ? {} : identityDowngradesOf([delta?.status === 'ok' ? delta.manifest : null, working ? dirty : null], eligible, sourcePath)) };// Freeze all logical identities in one database statement, before yielding// between pages. A later interactive edit must conflict with this scan.const identities = await engine.executeRaw<{ id: number; slug: string; source_path: string | null; knowledge_revision: string; deleted_at: Date | string | null; fm_id: string | null }>(diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 57ff04688d..38244c00d2 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -117,7 +117,7 @@ export interface PreparationStallMeta {}export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | 'explicit_id_conflict' | FenceReason | OriginConflictReason | PageIdentityHoldReason| 'symlink_in_repo' | 'symlink_outside_root' | 'symlink_dangling' | 'symlink_loop' | 'permission_denied' | 'not_regular_file' | 'skip_worktree' | 'deleted_locally'- | 'not_utf8' | 'control_character';+ | 'not_utf8' | 'control_character' | 'never_committed' | 'ignored';/** GBRA-130: why a `page_identity_changed` hold's path has no page sync may write (A-17, B-3, B-4). */export type PageIdentityHoldReason = 'several_tombstones' | 'spelling' | 'identity_differs';/** #6712 PR 4b: the sides a `file_drift` Decision can be about, and the states of a deleted side (design v3.2 §4). */@@ -680,7 +680,9 @@ function deletedDriftFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'metconst revision = record.meta.page_revision ? ` (revision ${record.meta.page_revision})` : '';const preview = (prefer: 'database' | 'file') => heldDriftPreviewArgv(source, 'deleted', state, prefer, record.path);const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };- const what = state === 'tombstone_edited' ? `Page ${slug} was deleted${revision} and ${record.path} then changed, so sync held the file instead of restoring the page or dropping the edit. `+ const uncommitted = state === 'file_gone' && (record.meta.reason === 'never_committed' || record.meta.reason === 'ignored');+ const what = uncommitted ? `${record.path} is gone, but Git never committed it${record.meta.reason === 'ignored' ? ' (.gitignore excludes it)' : ''}, so its absence is no evidence of a deletion and sync kept page ${slug} instead of deleting it (#7130). Put the file back and commit it (un-ignore it first) to keep the page file-backed. `+ : state === 'tombstone_edited' ? `Page ${slug} was deleted${revision} and ${record.path} then changed, so sync held the file instead of restoring the page or dropping the edit. `: state === 'purged_differs' ? `The page of ${record.path} was purged and the file differs from what the brain held, so sync held the file instead of importing it as a new page. `: `${record.path} is gone from the last commit but page ${slug} changed${revision}, so sync held the deletion instead of removing a page that changed. `;const options = `This preview (writes nothing) shows --prefer database: ${fileDriftActionVerb('deleted', state, 'database')}; ${preview('file').join(' ')} previews --prefer file: `diff --git a/src/core/persistence/sync-markers.ts b/src/core/persistence/sync-markers.tsindex 817271415e..d71d191089 100644--- a/src/core/persistence/sync-markers.ts+++ b/src/core/persistence/sync-markers.ts@@ -24,6 +24,7 @@ import { getWorktreeBinding, managedPersistenceEnabled } from './ownership.ts';import { readSyncFile } from './sync-discovery.ts';import { readSyncImportProvenance } from './sync-holds.ts';import { syncOriginPath } from './sync-origin.ts';+import type { SyncDeleteCaps, SyncDeleteTrip } from '../sync-reconcile.ts';import { SYNC_DELETES_WITHHELD_OP, SYNC_ORIGIN_DELETED_OP, passFingerprint } from './sync-pass-row.ts';type Exec = Pick<BrainEngine, 'executeRaw'>;@@ -137,6 +138,9 @@ export interface DeletesWithheld {/** `deleteSetHash` of the withheld paths: the record matches a later trip only while the set is the same. */set_hash: string;samples: string[];+ /** #7130: the limit the set went over (absent on a record written before the caps: the 50% valve). */+ trip?: SyncDeleteTrip;+ caps?: SyncDeleteCaps;at: string;}@@ -147,9 +151,9 @@ export function deleteSetHash(paths: Iterable<string>): string {/** Writes (or refreshes) the source's withheld mass-delete record inside `tx`; keeps the first `DELETES_WITHHELD_SAMPLES` samples. */export async function writeDeletesWithheld(tx: Exec, input: { sourceId: string; incarnation: string; target: string; count: number; reconcilable: number; ratio: number;- set_hash: string; samples: readonly string[] }): Promise<DeletesWithheld> {+ set_hash: string; samples: readonly string[]; trip?: SyncDeleteTrip; caps?: SyncDeleteCaps }): Promise<DeletesWithheld> {const value: DeletesWithheld = { source_id: input.sourceId, incarnation: input.incarnation, target: input.target, count: input.count, reconcilable: input.reconcilable,- ratio: input.ratio, set_hash: input.set_hash, samples: input.samples.slice(0, DELETES_WITHHELD_SAMPLES), at: new Date().toISOString() };+ ratio: input.ratio, set_hash: input.set_hash, samples: input.samples.slice(0, DELETES_WITHHELD_SAMPLES), ...(input.trip ? { trip: input.trip } : {}), ...(input.caps ? { caps: input.caps } : {}), at: new Date().toISOString() };await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now())ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now()`,[SYNC_DELETES_WITHHELD_OP, passFingerprint(input.sourceId, input.incarnation), JSON.stringify(value)]);diff --git a/src/core/persistence/sync-origin-evidence.ts b/src/core/persistence/sync-origin-evidence.tsnew file mode 100644index 0000000000..186bbfd1f3--- /dev/null+++ b/src/core/persistence/sync-origin-evidence.ts@@ -0,0 +1,69 @@+/**+ * #7130: whether a missing file is evidence that its page was deleted. A managed sync deletes a live page whose recorded+ * file is absent from the pinned tree and the disk only when Git once committed that file: then its absence is a removal+ * the history records, and the page's bytes stay recoverable from the commit that held them. A file Git never committed+ * (an agent's write-through that landed in a directory `.gitignore` excludes, a copy removed before any commit) left no+ * history, so its absence proves nothing and the page may hold the only copy of its content: sync holds it instead.+ *+ * Both reads are bounded Git plumbing over the candidate paths alone. A read that fails or times out answers `unknown`+ * for every path it covered, which the classifier treats like a missing commit (fail closed: hold, never delete).+ */+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { gitChildEnv } from '../git-env.ts';++const execFileAsync = promisify(execFile);++/** `committed`: some commit of the history holds the path. `never_committed`: none does. `ignored`: `.gitignore` excludes it. `unknown`: a read failed. */+export type OriginEvidence = 'committed' | 'never_committed' | 'ignored' | 'unknown';++/** Paths per Git invocation (argument-list bound). */+const BATCH = 500;+const GIT_TIMEOUT_MS = 120_000;+const GIT_MAX_BUFFER = 64 * 1024 ** 2;++async function git(gitRoot: string, args: string[]): Promise<{ code: number; stdout: string }> {+ try {+ const { stdout } = await execFileAsync('git', ['-c', 'core.quotepath=false', '--literal-pathspecs', '-C', gitRoot, ...args],+ { env: gitChildEnv(), encoding: 'utf8', timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER });+ return { code: 0, stdout };+ } catch (error) {+ const e = error as { code?: unknown; stdout?: unknown; killed?: boolean };+ return { code: typeof e.code === 'number' && !e.killed ? e.code : -1, stdout: typeof e.stdout === 'string' ? e.stdout : '' };+ }+}++/**+ * #7130 (write-through): whether the Git work tree around `root` ignores `relativePath` and does not track it, so a+ * file written there would never be committed. False outside a work tree or when Git cannot answer (the write keeps its+ * old behavior then; sync's own evidence read still fails closed).+ */+export async function gitIgnoresUntracked(root: string, relativePath: string): Promise<boolean> {+ return (await git(root, ['check-ignore', '-q', '--', relativePath])).code === 0;+}++/**+ * The evidence for each Git-root-relative path in `gitPaths`, read in the work tree at `gitRoot`. `commits` are the+ * history tips to search (the pinned target and the pass's baseline); a path any commit reachable from one of them+ * touched was committed. `.gitignore` is read as the checkout has it now.+ */+export async function readOriginEvidence(gitRoot: string, commits: ReadonlyArray<string | null | undefined>, gitPaths: readonly string[]): Promise<Map<string, OriginEvidence>> {+ const evidence = new Map<string, OriginEvidence>();+ const tips = [...new Set(commits.filter((commit): commit is string => typeof commit === 'string' && commit.length > 0))];+ const paths = [...new Set(gitPaths)];+ for (let i = 0; i < paths.length; i += BATCH) {+ const batch = paths.slice(i, i + BATCH);+ const touched = tips.length ? await git(gitRoot, ['log', ...tips, '--format=', '--name-only', '--no-renames', '-z', '--', ...batch]) : { code: 0, stdout: '' };+ const committed = new Set(touched.stdout.split('\0').map(path => path.trim()).filter(Boolean));+ const ignoredRead = await git(gitRoot, ['check-ignore', '--no-index', '-z', '--', ...batch]);+ const ignored = new Set(ignoredRead.stdout.split('\0').filter(Boolean));+ // check-ignore exits 1 when no path is ignored; anything else but 0 is a failed read.+ const ignoreKnown = ignoredRead.code === 0 || ignoredRead.code === 1;+ for (const path of batch) {+ if (touched.code !== 0 || !ignoreKnown) evidence.set(path, 'unknown');+ else if (ignored.has(path)) evidence.set(path, 'ignored');+ else evidence.set(path, committed.has(path) ? 'committed' : 'never_committed');+ }+ }+ return evidence;+}diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.tsindex 35ed65aa11..5b2b5a2c27 100644--- a/src/core/persistence/sync-pass-apply.ts+++ b/src/core/persistence/sync-pass-apply.ts@@ -33,7 +33,7 @@import { VERSION } from '../../version.ts';import type { BrainEngine } from '../engine.ts';import { resolveSlugForPath } from '../sync.ts';-import { massReconcileAllowed, planReconcileDeletes } from '../sync-reconcile.ts';+import { massReconcileAllowed, planReconcileDeletes, readSyncDeleteCaps, syncDeleteTrip } from '../sync-reconcile.ts';import { filterYielding, loopYield } from './sync-yield.ts';import { admitKeepDbReconcile, driftSkippedSlugs, freezeKeepDbReconcile, releaseMatchedDriftSkips } from '../repair/keep-db-policy.ts';@@ -75,7 +75,7 @@ const LEVEL_BLOB_MAX_BYTES = 8 * 1024 * 1024;/** What a pass applied across its rounds (kept in memory; its counts go into the pass row's telemetry). */export interface PassApplyState {markersRetired: number;- holds: { file_gone: number; tombstone_edited: number; purged_differs: number; settle_mismatch: number; origin_conflict: number; page_identity_changed: number };+ holds: { file_gone: number; tombstone_edited: number; purged_differs: number; settle_mismatch: number; origin_conflict: number; page_identity_changed: number; uncommitted: number };settleMismatch: string[];adopted: number;swept: { screened: number; recorded: number };@@ -101,7 +101,7 @@ export interface PassApplyState {}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 }, settleMismatch: [], adopted: 0,+ 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 }, 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() };}@@ -242,7 +242,10 @@ async function applyDeleteValve(engine: BrainEngine, level: ShadowLevel, input:const live = await filterYielding(level.paths, entry => (isCompactMatched(entry) || entry.state.page?.live === true) && !!entry.slug);return planReconcileDeletes(live.map(entry => ({ slug: entry.slug!, source_path: entry.path })), live.filter(entry => !deleting.has(entry.path)).map(entry => entry.path), () => true);})() : null;- const tripped = !!plan?.massDelete && (input.remote || !massReconcileAllowed());+ // #7130: the absolute caps (sync.max_deletes, sync.max_delete_ratio) withhold too, below the 50% valve.+ const caps = plan ? await readSyncDeleteCaps(engine, level.sourceId) : null;+ const trip = plan && caps ? (plan.massDelete ? 'mass_ratio' as const : syncDeleteTrip(deletes.length, plan.reconcilableCount, caps)) : null;+ const tripped = trip !== null && (input.remote || !massReconcileAllowed());state.withheldCount = tripped ? deletes.length : 0;if (tripped) {for (const entry of deletes) settleAs(entry, { settled: true, action: 'none', withheld: true });@@ -251,7 +254,7 @@ async function applyDeleteValve(engine: BrainEngine, level: ShadowLevel, input:await engine.transaction(async tx => {await assertDrainLease(tx, level.sourceId);state.withheld = await writeDeletesWithheld(tx, { sourceId: level.sourceId, incarnation: level.incarnation, target: level.head, count: deletes.length,- reconcilable: plan!.reconcilableCount, ratio: plan!.reconcilableCount ? deletes.length / plan!.reconcilableCount : 1, set_hash: deleteSetHash(paths), samples: paths });+ reconcilable: plan!.reconcilableCount, ratio: plan!.reconcilableCount ? deletes.length / plan!.reconcilableCount : 1, set_hash: deleteSetHash(paths), samples: paths, trip: trip!, caps: caps! });});return;}@@ -301,7 +304,11 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Pacontinue;}if (r.cls === 'delete_drift' && heldRenameOrigins.has(syncOriginPath(passEntryPaths(level, entry.path).sourcePath))) continue;- if (r.cls === 'delete_drift') {+ if (r.cls === 'delete_drift' && r.uncommitted) {+ const why = r.uncommitted === 'ignored' ? '.gitignore excludes it, so Git never kept it' : 'no commit in its history holds it (or Git could not show one)';+ pending.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 } : {}) },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') {@@ -532,7 +539,7 @@ export async function finishPassApply(engine: BrainEngine, sourceId: string, staexport function passApplyCounts(state: PassApplyState): Record<string, number> {const refused = Object.values(state.keepDb.refused).reduce((a, b) => a + b, 0);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, adopted: state.adopted, legacy_swept: state.swept.screened,+ 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 };}diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.tsindex d9bf41851e..666a8be82e 100644--- a/src/core/persistence/sync-pass-status.ts+++ b/src/core/persistence/sync-pass-status.ts@@ -81,8 +81,9 @@ export function passStatusNext(sourceId: string, reason: PassStatusReason, row:why: `The last ${row.value.obligations.not_converged_streak} passes of ${sourceId} ended not converged; another sync will not change that. Report what doctor shows with the gbrain version (read-only).` }: { ...sync, why: 'The last pass ran out of rounds before every path settled; the same sync continues from the current level.' };case 'deletes_withheld':- return { argv: ['gbrain', 'sync', '--source', sourceId, '--dry-run', '--json'], consent: [], actor: 'user', requires_exclusive: false, verify,- user_message: `Sync of ${sourceId} withheld a mass delete (more than half of its file-backed pages). If the checkout is the wrong one or incomplete, restore it and sync again; if the deletion is intended, run GBRAIN_ALLOW_MASS_RECONCILE=1 gbrain sync --source ${sourceId} on the brain host.`,+ // #7130: deleting pages is the user's decision, never an agent's: next is ask_user whatever the actor.+ return { ask_user: true, argv: ['gbrain', 'sync', '--source', sourceId, '--dry-run', '--json'], consent: [], actor: 'user', requires_exclusive: false, verify,+ user_message: `Sync of ${sourceId} withheld a bulk delete (over half of its file-backed pages, or over sync.max_deletes / sync.max_delete_ratio); nothing was deleted. Review the withheld set in the dry run. If the checkout is the wrong one or incomplete, restore it and sync again; if the deletion is intended, run GBRAIN_ALLOW_MASS_RECONCILE=1 gbrain sync --source ${sourceId} on the brain host.`,why: 'The dry run lists the withheld set and its hash (read-only); everything else of the source is synced.' };case 'admission_paused':return { argv: ['gbrain', 'config', 'set', 'sync.admission', 'normal'], consent: [], actor: 'user', requires_exclusive: false, verify,diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 9da787cec7..ccefb17de8 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -36,6 +36,7 @@ import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHoimport { movedDriftHolds, sameParser } from './sync-prescreen.ts';import { sameSyncOrigin, selectOriginClaimant, syncOriginPath } from './sync-origin.ts';import { hashWorkingLevel, probeDirtiness, readBlobs, readIndexDelta, readIndexLevel, readTreeLevel, workingChanged, type GitIndexEntry, type GitTreeEntry, type WorkingStatCache } from './sync-git-stream.ts';+import { readOriginEvidence } from './sync-origin-evidence.ts';import { classifySyncPath, syncPassKind, type SyncClassified, type SyncIdleBlocker, type SyncPathState } from './sync-classify.ts';import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceReceipt, type ConvergenceScreen } from './sync-convergence.ts';import { readManagedMode } from './ownership.ts';@@ -834,6 +835,18 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: sttimings.classify += t();}+ // #7130: an absent file is deletion evidence only when Git once committed it (sync-origin-evidence.ts), read for those paths alone.+ const absent = await filterYielding(paths, entry => (entry.result.cls === 'delete' || entry.result.cls === 'delete_drift') && entry.state.originEvidence === undefined, step);+ if (absent.length) {+ t = timer();+ const evidence = await readOriginEvidence(gitRoot, [head, baselineCommit], absent.map(entry => entry.path));+ for (const entry of absent) {+ const state = { ...entry.state, originEvidence: evidence.get(entry.path) ?? 'unknown' as const };+ Object.assign(entry, { state, result: classifySyncPath(state) });+ }+ timings.origin = t();+ }+// Adoption by hash needs the level's bytes: committed mode reads the blobs of the candidates that could adopt.const needBytes = await filterYielding(paths, entry => !['matched', 'held', 'dirty'].includes(entry.result.cls) && entry.state.levelSha256 === null && entry.state.level !== null&& entry.state.attested?.hash && entry.state.page?.live, step);diff --git a/src/core/sync-reconcile.ts b/src/core/sync-reconcile.tsindex bb429c4d56..5c15832ad2 100644--- a/src/core/sync-reconcile.ts+++ b/src/core/sync-reconcile.ts@@ -17,6 +17,81 @@ import { gitChildEnv } from './git-env.ts';export const MASS_RECONCILE_RATIO = 0.5;export const MASS_RECONCILE_MIN_PAGES = 20;+/**+ * #7130: absolute caps on what one managed sync pass deletes, on top of the 50% valve, which a large source never trips+ * (19,325 deletes were 4% of a 478k-page source). A pass over either cap withholds its deletes like the valve does.+ * `sync.max_deletes` (default 500) is a count; `sync.max_delete_ratio` (default 0.01) a share of the source's file-backed+ * pages, applied only to a pass deleting more than `SYNC_DELETE_RATIO_FLOOR` pages so that a small brain's ordinary+ * deletion of a folder is not withheld. A source overrides either with `sync.max_deletes.source.<id>` /+ * `sync.max_delete_ratio.source.<id>`.+ */+export const DEFAULT_SYNC_MAX_DELETES = 500;+export const DEFAULT_SYNC_MAX_DELETE_RATIO = 0.01;+export const SYNC_DELETE_RATIO_FLOOR = 50;+export const SYNC_MAX_DELETES_KEY = 'sync.max_deletes';+export const SYNC_MAX_DELETE_RATIO_KEY = 'sync.max_delete_ratio';++export interface SyncDeleteCaps { maxDeletes: number; maxDeleteRatio: number }+/** Which limit a pass's deletes went over: the #2828 valve (`mass_ratio`), or a #7130 cap. */+export type SyncDeleteTrip = 'mass_ratio' | 'max_deletes' | 'max_delete_ratio';++/** A stored cap value, or null when it is unset or not a valid value (the default then applies). */+export function parseSyncDeleteCap(key: typeof SYNC_MAX_DELETES_KEY | typeof SYNC_MAX_DELETE_RATIO_KEY, raw: string | null | undefined): number | null {+ const text = raw?.trim();+ if (!text) return null;+ const value = Number(text);+ if (!Number.isFinite(value) || value < 0) return null;+ if (key === SYNC_MAX_DELETES_KEY) return Number.isInteger(value) ? value : null;+ return value <= 1 ? value : null;+}++/** `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;+ 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.`;+}++/**+ * #7130: how long a soft-deleted page waits before the autopilot purge phase may purge it (`purge.retention_hours`,+ * default 72, at least 24). The manual `gbrain pages purge-deleted` takes its own `--older-than`.+ */+export const DEFAULT_PURGE_RETENTION_HOURS = 72;+export const MIN_PURGE_RETENTION_HOURS = 24;+export function parsePurgeRetentionHours(raw: string | null | undefined): number | null {+ const text = raw?.trim();+ if (!text) return null;+ const value = Number(text);+ return Number.isInteger(value) && value >= MIN_PURGE_RETENTION_HOURS ? value : null;+}+export async function readPurgeRetentionHours(engine: { getConfig(key: string): Promise<string | null> }): Promise<number> {+ return parsePurgeRetentionHours(await engine.getConfig('purge.retention_hours')) ?? DEFAULT_PURGE_RETENTION_HOURS;+}++/** The caps in effect for `sourceId`: its own key, else the brain's, else the default. */+export async function readSyncDeleteCaps(engine: { getConfig(key: string): Promise<string | null> }, sourceId: string): Promise<SyncDeleteCaps> {+ const read = async (key: typeof SYNC_MAX_DELETES_KEY | typeof SYNC_MAX_DELETE_RATIO_KEY, fallback: number) =>+ parseSyncDeleteCap(key, await engine.getConfig(`${key}.source.${sourceId}`)) ?? parseSyncDeleteCap(key, await engine.getConfig(key)) ?? fallback;+ return { maxDeletes: await read(SYNC_MAX_DELETES_KEY, DEFAULT_SYNC_MAX_DELETES), maxDeleteRatio: await read(SYNC_MAX_DELETE_RATIO_KEY, DEFAULT_SYNC_MAX_DELETE_RATIO) };+}++/** The limit `deletes` deletions out of `reconcilable` file-backed pages go over, or null. */+export function syncDeleteTrip(deletes: number, reconcilable: number, caps: SyncDeleteCaps): SyncDeleteTrip | null {+ if (deletes <= 0) return null;+ if (reconcilable > MASS_RECONCILE_MIN_PAGES && deletes > reconcilable * MASS_RECONCILE_RATIO) return 'mass_ratio';+ if (deletes > caps.maxDeletes) return 'max_deletes';+ if (deletes > SYNC_DELETE_RATIO_FLOOR && deletes > reconcilable * caps.maxDeleteRatio) return 'max_delete_ratio';+ return null;+}++/** What a trip means, in the words status and the dry run use. */+export function syncDeleteTripText(trip: SyncDeleteTrip, caps: SyncDeleteCaps): string {+ if (trip === 'mass_ratio') return `more than ${Math.round(MASS_RECONCILE_RATIO * 100)}% of its file-backed pages`;+ if (trip === 'max_deletes') return `more than sync.max_deletes (${caps.maxDeletes}) pages`;+ return `more than sync.max_delete_ratio (${caps.maxDeleteRatio}) of its file-backed pages`;+}+/*** Normalize path separators so a page whose stored `source_path` was written* with a different separator than the local OS's `path.relative` produces (e.g.