Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(#6712 PR 4b lane B): pass apply round (holds, valve, adoption, sweep, keep_db, marker retirement)

garrytan8be75dd201ca
diff --git a/src/core/persistence/sync-classify.ts b/src/core/persistence/sync-classify.ts
index 99563e04c0..fdfc421526 100644
--- a/src/core/persistence/sync-classify.ts
+++ b/src/core/persistence/sync-classify.ts
@@ -84,6 +84,12 @@ export interface SyncClassified {
keepDbWrite?: true;
/** `db_ahead` `db_only`/`unproven` under an open full obligation: excluded and counted (`full_skipped_db_ahead`). */
fullSkipped?: true;
+ /** #6712 PR 4b (sync-pass-apply.ts): a delete the mass-delete valve withheld (design §2.6); settled while the trip lasts. */
+ withheld?: true;
+ /** #6712 PR 4b: a keep_db write over the pass cap (`keep_db_pending`, §4), settled and taken first next pass. */
+ pending?: 'keep_db';
+ /** #6712 PR 4b: a write `sync.admission` pauses (`paused_keep_db`, §8). */
+ paused?: 'keep_db';
}
const CLEAN = new Set<SyncDirtiness | null>(['clean', 'clean_eol', 'clean_lfs']);
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 10ab3fa521..a3bee59a8e 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -74,6 +74,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
// #6727: pages an older gbrain imported without recording their file fold to the file's slug, several or one sync cannot write; a person decides.
{ code: 'legacy_slug_conflict', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only a person decides which legacy page the file takes over',
human_reason: 'Pages an older gbrain imported without recording their file match this file and sync cannot pick one to import into; a person keeps the one that is its page and removes the others (gbrain delete --source <source> -- <slug>), or renames the file, then syncs.' },
+ // #6712 PR 4b (design v3.2 §3.1): a live pass settled the path three passes in a row and it never classified settled; a gbrain bug or an environment fault, never a loop.
+ { code: 'settle_mismatch', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: the pass cannot tell why the path does not settle',
+ human_reason: 'Sync settled this file three passes in a row but it never read settled afterwards; read gbrain doctor --json and gbrain sources writer status <source> (read-only), fix what they name, then run gbrain sources retry-held <source> to re-test it.' },
// Older releases recorded these as run failures; a rerun on this release holds the page instead.
{ code: 'revision_conflict', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
{ code: 'page_identity_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 508bacd0e5..626d21943e 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -69,7 +69,9 @@ export const GIT_HOLD_ESCALATE_MIN_SCREENED = 40;
type Exec = Pick<BrainEngine, 'executeRaw'>;
export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty' | 'file_drift'
- | 'legacy_slug_conflict';
+ | 'legacy_slug_conflict'
+ /** #6712 PR 4b (design v3.2 §3.1): a path a live pass settled in three consecutive passes at one level that never classified settled. */
+ | 'settle_mismatch';
/** #6278: what the owner recorded about a preparation it gave up on (step names and vocabulary only, never content). */
export interface PreparationStallMeta {
request_id: string;
@@ -148,6 +150,8 @@ export interface GitHoldMeta {
blocked_on?: string;
/** #6727 `legacy_slug_conflict`: the live pages without a recorded origin whose slugs fold to the file's slug. */
legacy_slugs?: string[];
+ /** #6712 PR 4b `settle_mismatch`: the consecutive passes that settled the path at this level without it classifying settled. */
+ mismatch_streak?: number;
}
/** #6188: why the last fence repair left a hold in place, and when the maintenance run tries it again (null: it does not). */
@@ -749,6 +753,17 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
why: `Re-screens ${record.path} after the other pages are removed (this hold is re-screened on every sync).` },
verify };
}
+ case 'settle_mismatch': {
+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#settle_mismatch',
+ why: `Sync settled ${record.path} at the same level in ${record.meta.mismatch_streak ?? 3} passes in a row, but the next round never classified it settled, so sync held it instead of re-importing it every pass; the rest of the source synced. `
+ + `Doctor (read-only) names a broken writer, a stuck effect or a damaged record; gbrain sources writer status ${source} --json (read-only) shows the write owner. Report what they show with the gbrain version. Once the cause is fixed, retry-held re-tests the file.`,
+ then: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', source, '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: 'Shows the write owner, its gbrain version and any write still stuck (read-only).',
+ then: { argv: ['gbrain', 'sources', 'retry-held', source], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Schedules ${record.path} for a re-test on the next sync of ${source}; a mismatch that comes back is held again after three passes.` } },
+ verify };
+ }
case 'rename_held':
return repair(true, `The page that ${record.path} renames changed after the rename was recorded, so it was not moved; the preview proposes re-binding the rename to the current page for approval.`);
case 'frontmatter_slug_conflict':
diff --git a/src/core/persistence/sync-page-fault.ts b/src/core/persistence/sync-page-fault.ts
index 1e1525302f..350a0c561d 100644
--- a/src/core/persistence/sync-page-fault.ts
+++ b/src/core/persistence/sync-page-fault.ts
@@ -149,7 +149,7 @@ export function fileDriftHold(entry: HoldEntry, slug: string, pageId: number | n
: 'there is no import record to tell which side changed';
return base(entry, slug, pageId, 'file_drift',
`${entry.path}: ${by} since the file was last imported and ${file}, so sync held the import instead of overwriting the database version; the rest of the source synced.`,
- intent.content ?? null, intent.blobOid, { sides: observed.sides, ...(observed.revision ? { page_revision: observed.revision } : {}),
+ intent.content ?? null, intent.blobOid, { sides: observed.sides, ...(observed.sides !== 'database' ? { side: observed.sides } : {}), ...(observed.revision ? { page_revision: observed.revision } : {}),
...(observed.proof ? { competing_request_id: observed.proof.request_id, competing_operation: observed.proof.operation } : {}),
...(observed.sharedOrigin ? { shared_origin: true as const } : {}) });
}
diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.ts
new file mode 100644
index 0000000000..d2c051f000
--- /dev/null
+++ b/src/core/persistence/sync-pass-apply.ts
@@ -0,0 +1,321 @@
+/**
+ * #6712 PR 4b (design v3.2 §2.3 rows 6, 9, 13, 15, 17-19; §2.5; §2.6; §2.7; §3.1; §4): what a live pass does with a classified
+ * round besides admitting imports and deletes (sync-pass-run.ts). `applyPassRound` runs once per round, after the level is
+ * read and before the round's candidates are partitioned, and settles in place the paths it finishes:
+ *
+ * - **Marker retirement** (§2.5, full rounds): a deletion marker is retired by compare-and-delete when its origin is
+ * independently absent from the pinned `T` and from disk, whatever the mode, or a live page claims the origin again. An
+ * untracked copy in committed mode keeps it, and a working-mode `L = absent` alone retires nothing.
+ * - **The mass-delete valve** (§2.6): the round's deletes go through #2828's `planReconcileDeletes`. A trip writes one
+ * `sync-deletes-withheld` record (refreshed each pass) and settles those deletes `withheld`; imports and the stamp
+ * proceed and no per-page hold is written. A cleared trip deletes the record. Only `GBRAIN_ALLOW_MASS_RECONCILE=1` in the
+ * owner host's environment applies the deletes; a remote caller never does.
+ * - **Holds** (rows 6, 9; §3.1 settle mismatch): `delete_drift` is a `file_drift` hold with side `deleted`, state
+ * `file_gone`; `deleted_edited` one with state `tombstone_edited` or `purged_differs` (purged holds carry the slug the
+ * marker names); a path that settled in three consecutive passes at one level without classifying settled is a
+ * `settle_mismatch` hold (`needs_human`). Each is written at level `L` under the drain lease, so it is `held` (row 1)
+ * and the rest of the source stamps. Row 11's unsettled `dirty` and row 19's `drift` are held by the batch freeze
+ * (sync-run.ts: the publication screen's `worktree_dirty`, the `sameContentAtOrigin` no-op or `file_drift`).
+ * - **Adoption** (row 13): one fenced, batched record write `{blob_oid, disk_blob_oid, revision}` per round, keeping
+ * `r.parser`; arm 1 adopts by revision alone on `fileSame` with no record revision.
+ * - **The legacy sweep** (§2.7): `legacy_unverified` pages run the read-only `sameContentAtOrigin` screen (every page in
+ * the incarnation's first full round, then at most `PASS_LEGACY_SWEEP_MAX` per pass); an equal page gets a record
+ * `{blob_oid, disk_blob_oid, revision, parser: fp}` and is `matched`, so a later edit imports with no Decision.
+ * - **keep_db** (rows 15, 18; §4): a clean committed keep_db path is frozen to the bytes of `T[p]` and admitted as a
+ * DB-wins reconcile of the pass (keep-db-policy.ts) under the drain lease, at most `PASS_KEEP_DB_MAX` per pass; the
+ * rest are `keep_db_pending` (settled, owned by sync, taken first next pass). An admitted path is `in_flight` until its
+ * Git effect writes, then row 11 settles it `published` and row 13 adopts it after the commit. A refused one is row 19.
+ *
+ * A remote caller (`remote: true`) writes nothing here: no hold, marker, record, withheld record or keep_db write.
+ */
+import { VERSION } from '../../version.ts';
+import type { BrainEngine } from '../engine.ts';
+import { resolveSlugForPath } from '../sync.ts';
+import { massReconcileAllowed, planReconcileDeletes } from '../sync-reconcile.ts';
+import { admitKeepDbReconcile, freezeKeepDbReconcile, releaseMatchedDriftSkips } from '../repair/keep-db-policy.ts';
+import type { SyncProcessingOptions } from './sync-authority.ts';
+import type { SyncClassified } from './sync-classify.ts';
+import { readOnlySameContentScreen } from './sync-convergence.ts';
+import type { ManagedSyncContext } from './sync-discovery.ts';
+import { sha256 } from './digest.ts';
+import { readBlobs } from './sync-git-stream.ts';
+import { RECOVERY_VERSION } from '../markdown.ts';
+import { readSyncImportProvenances, recordSyncImportProvenances, syncImportParserFor, writeGitHold,
+ type GitHoldCode, type GitHoldMeta, type SyncImportProvenance } from './sync-holds.ts';
+import { assertDrainLease } from './sync-lease.ts';
+import { clearDeletesWithheld, deleteSetHash, readDeletesWithheld, readOriginDeletedMarker, retireOriginDeletedMarker, writeDeletesWithheld, type DeletesWithheld } from './sync-markers.ts';
+import type { ShadowLevel, ShadowPath } from './sync-pass.ts';
+import { SETTLE_MISMATCH_STREAK, type ManagedSyncPassValue } from './sync-pass-row.ts';
+import type { SyncAdmission } from './sync-admission.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;
+/** keep_db DB-wins writes a pass admits (design §4, [estimated]). */
+export const PASS_KEEP_DB_MAX = 200;
+/** The bootstrap Decision gate (design §2.7, [estimated]): file_drift Decisions per 10,000 pages. */
+export const BOOTSTRAP_DECISIONS_PER_10K = 5;
+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 };
+ settleMismatch: string[];
+ adopted: number;
+ swept: { screened: number; recorded: number };
+ /** The first full round of the incarnation swept every legacy page (the pass records it in `obligations.legacy_sweep`). */
+ sweptAll: boolean;
+ withheld: DeletesWithheld | null;
+ /** Deletes the valve withheld in the newest round. */
+ withheldCount: number;
+ keepDb: { admitted: number; pending: number; paused: number; refused: Record<string, number> };
+ /** keep_db paths admitted in this pass: never admitted twice. */
+ keepDbTaken: string[];
+ matchedSlugs: string[];
+}
+
+export function newPassApplyState(): PassApplyState {
+ return { markersRetired: 0, holds: { file_gone: 0, tombstone_edited: 0, purged_differs: 0, settle_mismatch: 0 }, settleMismatch: [], adopted: 0,
+ swept: { screened: 0, recorded: 0 }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], matchedSlugs: [] };
+}
+
+export interface PassApplyInput {
+ passId: string;
+ observedAt: string;
+ remote: boolean;
+ admission: SyncAdmission;
+ /** The round reads every path (a full pass); marker retirement runs only then. */
+ fullRound: boolean;
+ /** The pass row's obligations as pinned (`mismatch`, `legacy_sweep`). */
+ obligations: ManagedSyncPassValue['obligations'];
+ context: ManagedSyncContext;
+ processingOptions: SyncProcessingOptions;
+ /** Test seam: the read-only same-content screen (default `readOnlySameContentScreen`). */
+ screen?: (level: ShadowLevel, paths: ShadowPath[]) => Promise<Map<string, 'same' | 'differs' | 'unknown'>>;
+}
+
+/** The source-relative path (`SyncEntry.path`, the hold key) and the recorded origin of a level path. */
+export function passEntryPaths(level: Pick<ShadowLevel, 'scope' | 'slugMode'>, gitPath: string): { path: string; sourcePath: string } {
+ const path = level.scope ? gitPath.slice(level.scope.length + 1) : gitPath;
+ return { path, sourcePath: level.slugMode === 'source-root' && level.scope ? path : gitPath };
+}
+
+const settleAs = (entry: ShadowPath, patch: Partial<SyncClassified>) => { entry.result = { ...entry.result, inFlight: false, ...patch }; };
+
+/** The hold meta that pins a hold to the path's level `L` in its own domain (sync-pass.ts `holdAtLevel`). */
+function levelMeta(level: ShadowLevel, entry: ShadowPath): Partial<GitHoldMeta> {
+ if (entry.state.level === null) return { deleted: true };
+ if (level.mode === 'working') return { working: true, ...(entry.state.levelSha256 ? { working_hash: entry.state.levelSha256 } : {}) };
+ return { blob_oid: entry.state.level };
+}
+
+/** Runs the round's settle-side work (module header) and settles the paths it finished in `level.paths`. */
+export async function applyPassRound(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {
+ if (input.fullRound && !input.remote) await retireMarkers(engine, level, state);
+ await applyDeleteValve(engine, level, input, state);
+ if (input.remote) return;
+ await writePassHolds(engine, level, input, state);
+ await adoptRecords(engine, level, state);
+ await sweepLegacy(engine, level, input, state);
+ await admitKeepDb(engine, level, input, state);
+ for (const entry of level.paths) if (entry.result.cls === 'matched' && entry.slug) state.matchedSlugs.push(entry.slug);
+}
+
+/** Design §2.5: retire markers whose origin left both `T` and the disk, or that a live page claims again (compare-and-delete). */
+async function retireMarkers(engine: BrainEngine, level: ShadowLevel, state: PassApplyState): Promise<void> {
+ const retire = level.paths.filter(entry => entry.state.marker && !entry.legacyPageless
+ && ((entry.state.tree === null && !entry.state.present) || entry.state.page?.live === true));
+ if (!retire.length) return;
+ await engine.transaction(async tx => {
+ await assertDrainLease(tx, level.sourceId);
+ for (const entry of retire) {
+ const { sourcePath } = passEntryPaths(level, entry.path);
+ const stored = await readStoredMarker(tx, level, sourcePath);
+ if (!stored) continue;
+ const blobOids = Array.isArray(stored.blob_oids) ? stored.blob_oids : [];
+ if ((stored.kind === 'legacy' ? 'legacy' : 'deleted') !== entry.state.marker!.kind || blobOids.join('\0') !== entry.state.marker!.blobOids.join('\0')) continue;
+ if (await retireOriginDeletedMarker(tx, { sourceId: level.sourceId, incarnation: level.incarnation, origin: sourcePath, expected: stored })) state.markersRetired++;
+ }
+ });
+}
+
+async function readStoredMarker(exec: Pick<BrainEngine, 'executeRaw'>, level: ShadowLevel, origin: string): Promise<{ kind?: string; blob_oids?: string[]; slug?: string } | null> {
+ return await readOriginDeletedMarker(exec, level.sourceId, level.incarnation, origin) as { kind?: string; blob_oids?: string[]; slug?: string } | null;
+}
+
+/** Design §2.6: the round's deletes through #2828's valve; a trip withholds them all under one source-level record. */
+async function applyDeleteValve(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {
+ const deletes = level.paths.filter(entry => entry.result.action === 'delete' && !entry.result.settled && !entry.result.inFlight);
+ const deleting = new Set(deletes.map(entry => entry.path));
+ const live = level.paths.filter(entry => entry.state.page?.live === true && entry.slug);
+ const plan = planReconcileDeletes(live.map(entry => ({ slug: entry.slug!, source_path: entry.path })), live.filter(entry => !deleting.has(entry.path)).map(entry => entry.path), () => true);
+ const tripped = deletes.length > 0 && plan.massDelete && (input.remote || !massReconcileAllowed());
+ state.withheldCount = tripped ? deletes.length : 0;
+ if (tripped) {
+ for (const entry of deletes) settleAs(entry, { settled: true, action: 'none', withheld: true });
+ if (input.remote) return;
+ const paths = deletes.map(entry => passEntryPaths(level, entry.path).path).sort();
+ 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 });
+ });
+ return;
+ }
+ if (input.remote || !await readDeletesWithheld(engine, level.sourceId, level.incarnation)) return;
+ await engine.transaction(async tx => { await assertDrainLease(tx, level.sourceId); await clearDeletesWithheld(tx, level.sourceId, level.incarnation); });
+ state.withheld = null;
+}
+
+/** Rows 6 and 9 and the settle-mismatch streak (§3.1): holds at level `L`, written under the drain lease. */
+async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {
+ type Pending = { entry: ShadowPath; code: GitHoldCode; message: string; slug: string | null; meta: Partial<GitHoldMeta>; kind: keyof PassApplyState['holds'] };
+ const pending: Pending[] = [];
+ for (const entry of level.paths) {
+ const r = entry.result;
+ if (r.settled || r.inFlight) continue;
+ const { path } = passEntryPaths(level, entry.path);
+ const streak = input.obligations.mismatch?.[entry.path];
+ if (streak && streak.streak >= SETTLE_MISMATCH_STREAK && streak.level === entry.state.level) {
+ pending.push({ entry, code: 'settle_mismatch', slug: entry.slug, kind: 'settle_mismatch', meta: { mismatch_streak: streak.streak },
+ message: `${path}: sync settled this file at the same level in ${streak.streak} passes in a row, but the next round never classified it settled, so sync held it instead of re-importing it every pass; the rest of the source synced.` });
+ continue;
+ }
+ 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') {
+ const purged = r.state === 'purged_differs';
+ const slug = purged ? (await readStoredMarker(engine, level, passEntryPaths(level, entry.path).sourcePath))?.slug ?? resolveSlugForPath(passEntryPaths(level, entry.path).sourcePath) ?? null : entry.slug;
+ pending.push({ entry, code: 'file_drift', slug, kind: purged ? 'purged_differs' : 'tombstone_edited', meta: { side: 'deleted', state: purged ? 'purged_differs' : 'tombstone_edited' },
+ message: purged ? `${path}: page ${slug ?? path} was purged, and the file differs from the bytes it held, so sync held the file instead of importing it as a new page; the rest of the source synced.`
+ : `${path}: page ${slug} was deleted in the database, and the file changed since, so sync held the file instead of reviving the page; the rest of the source synced.` });
+ }
+ }
+ if (!pending.length) return;
+ await engine.transaction(async tx => {
+ await assertDrainLease(tx, level.sourceId);
+ for (const hold of pending) {
+ const { path, sourcePath } = passEntryPaths(level, hold.entry.path);
+ await writeGitHold(tx, { source_id: level.sourceId, incarnation: level.incarnation, path, source_path: sourcePath, slug: hold.slug, page_id: hold.entry.state.page?.live ? hold.entry.pageId : null,
+ code: hold.code, message: hold.message, upstream_version: hold.entry.state.levelSha256, observed_at: input.observedAt, run_id: input.passId, mode: 'managed',
+ meta: { recovery_version: RECOVERY_VERSION, ...levelMeta(level, hold.entry), ...hold.meta } });
+ }
+ });
+ for (const hold of pending) {
+ state.holds[hold.kind]++;
+ if (hold.code === 'settle_mismatch') state.settleMismatch.push(passEntryPaths(level, hold.entry.path).path);
+ settleAs(hold.entry, { cls: 'held', settled: true, action: 'none', classAction: 'repair' });
+ }
+}
+
+/** One page's import-record write of a round: the record to store and the page revision it must still be at. */
+interface RecordWrite { pageId: number; revision: string; record: Omit<SyncImportProvenance, 'recorded_at' | 'validated'> }
+
+/** The batched, fenced record write: a page whose revision moved since the round read it is left alone. Returns the pages written. */
+async function writeRecords(engine: BrainEngine, level: ShadowLevel, writes: RecordWrite[]): Promise<Set<number>> {
+ if (!writes.length) return new Set();
+ return engine.transaction(async tx => {
+ await assertDrainLease(tx, level.sourceId);
+ const rows = await tx.executeRaw<{ id: number | string; revision: string }>('SELECT id, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND id=ANY($2::int[]) FOR SHARE',
+ [level.sourceId, writes.map(write => write.pageId)]);
+ const current = new Map(rows.map(row => [Number(row.id), row.revision]));
+ const fenced = writes.filter(write => current.get(write.pageId) === write.revision);
+ await recordSyncImportProvenances(tx, fenced.map(write => write.record));
+ return new Set(fenced.map(write => write.pageId));
+ });
+}
+
+/** Row 13: adopt the level into the page's record, keeping `r.parser` (arm 1: revision only, on `fileSame`). */
+async function adoptRecords(engine: BrainEngine, level: ShadowLevel, state: PassApplyState): Promise<void> {
+ const adopt = level.paths.filter(entry => entry.result.cls === 'adopt' && entry.pageId !== null && entry.revision !== null && entry.state.level !== null);
+ if (!adopt.length) return;
+ const records = await readSyncImportProvenances(engine, level.sourceId, level.incarnation, adopt.map(entry => entry.pageId!));
+ const writes = adopt.map((entry): RecordWrite => {
+ const prior = records.get(entry.pageId!);
+ const { sourcePath } = passEntryPaths(level, entry.path);
+ const base: Omit<SyncImportProvenance, 'recorded_at' | 'validated'> = prior ? (({ recorded_at: _r, validated: _v, ...rest }) => rest)(prior)
+ : { source_id: level.sourceId, incarnation: level.incarnation, page_id: entry.pageId!, origin: sourcePath, raw_sha256: entry.state.levelSha256 ?? '', gbrain_version: VERSION, working: level.mode === 'working' };
+ return { pageId: entry.pageId!, revision: entry.revision!, record: { ...base, blob_oid: entry.state.level!, disk_blob_oid: entry.state.diskOid ?? prior?.disk_blob_oid ?? entry.state.level!, revision: entry.revision! } };
+ });
+ state.adopted += (await writeRecords(engine, level, writes)).size;
+}
+
+/** Design §2.7: the bounded read-only legacy sweep; an equal page gets a record and is `matched`. */
+async function sweepLegacy(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {
+ const legacy = level.paths.filter(entry => entry.result.cls === 'legacy_unverified' && entry.pageId !== null && entry.revision !== null && entry.state.level !== null && entry.slug);
+ if (!legacy.length) return;
+ const sweepAll = input.fullRound && !input.obligations.legacy_sweep?.first_full_at;
+ const budget = sweepAll ? legacy.length : Math.max(0, PASS_LEGACY_SWEEP_MAX - state.swept.screened);
+ const batch = legacy.slice(0, budget);
+ if (!batch.length) return;
+ const screen = input.screen ?? readOnlySameContentScreen(engine, input.context, input.processingOptions);
+ const verdicts = await screen(level, batch);
+ state.swept.screened += batch.length;
+ if (sweepAll) state.sweptAll = true;
+ const same = batch.filter(entry => verdicts.get(entry.path) === 'same');
+ if (!same.length) return;
+ const blobs = level.mode === 'committed' ? await readBlobs(level.gitRoot, [...new Set(same.map(entry => entry.state.level!))], LEVEL_BLOB_MAX_BYTES) : new Map<string, Buffer>();
+ const writes = same.flatMap((entry): RecordWrite[] => {
+ const { path, sourcePath } = passEntryPaths(level, entry.path);
+ const bytes = blobs.get(entry.state.level!);
+ const raw = entry.state.levelSha256 ?? (bytes ? sha256(bytes) : null);
+ if (!raw) return [];
+ return [{ pageId: entry.pageId!, revision: entry.revision!, record: { source_id: level.sourceId, incarnation: level.incarnation, page_id: entry.pageId!, origin: sourcePath, raw_sha256: raw,
+ blob_oid: entry.state.level!, disk_blob_oid: entry.state.diskOid ?? entry.state.level!, revision: entry.revision!, parser: syncImportParserFor(path, level.pack), gbrain_version: VERSION,
+ working: level.mode === 'working' } }];
+ });
+ const written = await writeRecords(engine, level, writes);
+ state.swept.recorded += written.size;
+ for (const entry of same) if (written.has(entry.pageId!)) settleAs(entry, { cls: 'matched', settled: true, action: 'none', classAction: 'none' });
+}
+
+/** Rows 15 and 18 under keep_db (§4): freeze to `T[p]`'s bytes and admit the DB-wins reconcile of the pass, bounded per pass. */
+async function admitKeepDb(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {
+ const taken = new Set(state.keepDbTaken);
+ const want = level.paths.filter(entry => !entry.result.inFlight && !taken.has(entry.path) && entry.pageId !== null && entry.revision !== null && entry.slug && entry.state.level !== null
+ && ((entry.result.cls === 'keep_db' && !entry.result.settled) || (entry.result.cls === 'db_ahead' && entry.result.keepDbWrite === true)));
+ if (!want.length) return;
+ if (input.admission !== 'normal') {
+ for (const entry of want) { state.keepDb.paused++; settleAs(entry, { settled: true, action: 'none', paused: 'keep_db' }); }
+ return;
+ }
+ const room = Math.max(0, PASS_KEEP_DB_MAX - state.keepDb.admitted);
+ const now = want.slice(0, room), later = want.slice(room);
+ for (const entry of later) { state.keepDb.pending++; settleAs(entry, { settled: true, action: 'none', pending: 'keep_db' }); }
+ if (!now.length) return;
+ const blobs = await readBlobs(level.gitRoot, [...new Set(now.map(entry => entry.state.level!))], LEVEL_BLOB_MAX_BYTES);
+ for (const entry of now) {
+ const bytes = blobs.get(entry.state.level!);
+ const refuse = (reason: string) => {
+ state.keepDb.refused[reason] = (state.keepDb.refused[reason] ?? 0) + 1;
+ if (entry.result.cls === 'keep_db') settleAs(entry, { cls: 'drift', settled: false, action: 'hold', side: entry.state.record?.revision != null ? 'both' : 'unknown', classAction: 'repair' });
+ };
+ if (!bytes) { refuse('bytes_unreadable'); continue; }
+ const frozen = await freezeKeepDbReconcile(engine, { sourceId: level.sourceId, slug: entry.slug!, pageId: entry.pageId!, revision: entry.revision!, path: passEntryPaths(level, entry.path).path,
+ frozenBytes: bytes, classified: entry.result, mode: entry.state.mode, dirty: entry.state.dirty });
+ if ('refused' in frozen) { refuse(frozen.refused); continue; }
+ const admitted = await admitKeepDbReconcile(engine, frozen.artifact, { passId: input.passId, remote: false, inTx: tx => assertDrainLease(tx, level.sourceId) });
+ if ('refused' in admitted) {
+ if (admitted.refused === 'admission_paused') { state.keepDb.paused++; settleAs(entry, { settled: true, action: 'none', paused: 'keep_db' }); continue; }
+ refuse(admitted.refused); continue;
+ }
+ state.keepDb.admitted++;
+ state.keepDbTaken.push(entry.path);
+ settleAs(entry, { settled: false, inFlight: true, action: 'keep_db' });
+ }
+}
+
+/** Once per pass: release the concept drift skips of pages the pass classified `matched` (§4). */
+export async function finishPassApply(engine: BrainEngine, sourceId: string, state: PassApplyState): Promise<number> {
+ return state.matchedSlugs.length ? releaseMatchedDriftSkips(engine, sourceId, state.matchedSlugs) : 0;
+}
+
+/** The pass row's telemetry counts of what the rounds applied. */
+export 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, 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-row.ts b/src/core/persistence/sync-pass-row.ts
index 7a36baceea..4a6b62c659 100644
--- a/src/core/persistence/sync-pass-row.ts
+++ b/src/core/persistence/sync-pass-row.ts
@@ -65,6 +65,8 @@ export interface ManagedSyncPassValue {
/** When the current run of unhealthy endings (`blocked`, `not_converged`) began; kept across them, cleared at `synced`/`up_to_date`. The §3.7 readers age a stuck source from it. */
stuck_since?: string | null;
faults: Record<string, { level: string | null; class: string; attempts: number }>;
+ /** #6712 PR 4b (design §2.7): when the incarnation's first full round swept every `legacy_unverified` page; later passes sweep at most 500. */
+ legacy_sweep?: { first_full_at: string };
};
telemetry: {
pass_id: string;
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 63b5544bfe..b89ed8c2f0 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -40,6 +40,7 @@ import { resolveSlugForPath } from '../sync.ts';
import { syncOriginPath } from './sync-origin.ts';
import { originMarkerFingerprint } from './sync-markers.ts';
import { passResumeArgs } from './sync-pass-readers.ts';
+import { applyPassRound, finishPassApply, newPassApplyState, passApplyCounts } from './sync-pass-apply.ts';
/** Rounds a pass runs before it stops `not_converged` (design §3.1). */
export const PASS_MAX_ROUNDS = 4;
@@ -283,10 +284,12 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
let lastMismatch: ShadowPath[] = [];
let lastLevel: ShadowLevel | null = null;
const rememberLevel = () => { if (lastLevel?.workingCache) rememberWorkingStatCache(cacheKey, lastLevel.workingCache); };
+ const applied = newPassApplyState();
+ const readmitted = new Set<string>();
const save = async (outcome: PassOutcome, stopReason: string | null) => {
const ended = outcome !== 'open';
- value.telemetry = { ...value.telemetry, outcome, stop_reason: stopReason, settled: S.size, counts: { ...counts },
+ value.telemetry = { ...value.telemetry, outcome, stop_reason: stopReason, settled: S.size, counts: { ...counts, ...passApplyCounts(applied) },
...(ended ? { ended_at: new Date().toISOString(), duration_ms: Date.now() - started } : {}) };
if (outcome === 'blocked' || stopReason === 'not_converged') value.obligations.stuck_since ??= new Date().toISOString();
await engine.transaction(async tx => { await assertDrainLease(tx, sourceId); await writePassRow(tx, value); });
@@ -336,6 +339,9 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
lastLevel = level;
value.telemetry.timings_ms = level.timings_ms;
if (bootstrap && round === 1) await writeLegacyMarkers(engine, level);
+ await applyPassRound(engine, level, { passId, observedAt: startedAt, remote, admission, fullRound: kind === 'full', obligations: value.obligations, context, processingOptions }, applied);
+ assertActive();
+ if (applied.sweptAll && !value.obligations.legacy_sweep) value.obligations.legacy_sweep = { first_full_at: new Date().toISOString() };
const deletes: ShadowPath[] = [], imports: ShadowPath[] = [], inFlight: ShadowPath[] = [], mismatch: ShadowPath[] = [], owed: ShadowPath[] = [];
lastMismatch = mismatch;
for (const entry of level.paths) {
@@ -345,7 +351,10 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (S.has(settledKey(entry.path, entry.state.level))) {
// A hold this pass wrote or re-screened at L is that path's fate here, even when its code re-screens every pass.
if (entry.state.hold?.atLevel) continue;
- mismatch.push(entry); continue;
+ // Design §3.1: admitted at most once more per (path, level) in this pass, then counted as a settle mismatch.
+ const again = settledKey(entry.path, entry.state.level);
+ if (readmitted.has(again)) { mismatch.push(entry); continue; }
+ readmitted.add(again);
}
if (r.action === 'delete') {
if (admission !== 'normal') { S.set(settledKey(entry.path, entry.state.level), 'paused_deletes'); counts.pausedDeletes++; continue; }
@@ -379,11 +388,12 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
value.obligations.converged = { target: head, at, ...watermark, parser_fp: parserFp, pack, selection_fp: selectionFp,
last_full_at: kind === 'full' || !converged ? at : converged.last_full_at, passes_since_full: kind === 'full' || !converged ? 0 : converged.passes_since_full + 1 };
Object.assign(value.obligations, { not_converged_streak: 0, mismatch: {}, stuck_since: null });
- value.telemetry = { ...value.telemetry, outcome: 'up_to_date', ended_at: at, remaining: 0, duration_ms: Date.now() - started, counts: { ...counts } };
+ value.telemetry = { ...value.telemetry, outcome: 'up_to_date', ended_at: at, remaining: 0, duration_ms: Date.now() - started, counts: { ...counts, ...passApplyCounts(applied) } };
await writePassRow(tx, value);
}, principalAttribution(authority.writer.principal)));
rememberLevel();
await clearPassFailures(engine, sourceId, incarnation);
+ await finishPassApply(engine, sourceId, applied);
return { ...result('up_to_date'), fromCommit: remote ? null : head };
}
const closesEpisode = !!episode && configured;
@@ -396,6 +406,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
value.telemetry = { ...value.telemetry, outcome: 'synced', stop_reason: configured ? null : 'selection_scoped', remaining: 0 };
rememberLevel();
await clearPassFailures(engine, sourceId, incarnation);
+ await finishPassApply(engine, sourceId, applied);
return result(configured && context.source.last_commit === null ? 'first_sync' : 'synced', configured ? undefined : 'selection_scoped');
}
const built = await batchEntries(engine, level, deletes, imports);