Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(sync): #6712 PR 4b narrow a taken confirm round to the origins the pass wrote
garrytanfafe678e4749
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex ec40d429d1..cfb9b66c44 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -44,6 +44,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect// records are visited (`read`: ls-tree or ls-files; a synchronous hook), an `I⋈P` result in hand before the shared budget// decides whether it waits a turn, and the same result right before its rows are taken.| 'sync:level_chunk' | 'sync:level_result' | 'sync:level_take' | 'sync:closure_walk'+ // #6712 PR 4b: a taken confirm round about to patch the previous round's origin domain (sync-pass-narrow.ts); a hook that+ // throws makes it build the domain whole (`confirm.narrow: 'forced'`).+ | 'sync:level_narrow'// #6712 PR 4b (#6926): inside the round's last import's publication, before its folded stamp's checks (sync-pass-fold.ts); a hook// that throws models a failed check statement there: the stamp rolls back to its savepoint and the pass stamps by its checkpoint request.| 'sync:pass_fold'@@ -63,7 +66,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect*//** `writeId` is the write request row: rows of a caller-bound replay share one `requestId` (crash-robot per-request seams key on the row). */export interface FaultDetail { requestId?: string; writeId?: string; effectId?: string; sourceId?: string; operation?: string | null; signal?: AbortSignal; slug?: string; path?: string;- round?: number; read?: string; level?: { statements: number; confirm: { taken: boolean; reason: string | null; rows: number } | null; reused?: number } }+ round?: number; read?: string; level?: { statements: number; confirm: { taken: boolean; reason: string | null; rows: number; narrow?: string } | null; reused?: number;+ /** `sync:level_read`: the level and the input it was read with (sync-pass.ts `readShadowLevel`), for probes that read it again. */+ shadow?: unknown; input?: unknown } }/** Postgres returns `persistence_effects.id` (bigserial) as a BigInt; `faultPoint` hands hooks its decimal string (#6584). */export type FaultDetailInput = Omit<FaultDetail, 'effectId'> & { effectId?: string | number | bigint };type FaultHook = (point: FaultPoint, detail: FaultDetail) => Promise<void> | void;diff --git a/src/core/persistence/sync-pass-narrow.ts b/src/core/persistence/sync-pass-narrow.tsnew file mode 100644index 0000000000..92498400ee--- /dev/null+++ b/src/core/persistence/sync-pass-narrow.ts@@ -0,0 +1,201 @@+/**+ * #6712 PR 4b: a level's origin domain (the page claiming each origin and every claimant of a shared one, the domain,+ * the spelling twins and the attestation walk), built from every page, or patched at the origins a taken confirm round+ * re-read (sync-pass.ts `readShadowLevel`, `narrowGate`).+ *+ * A confirm round at the previous round's tree holds the previous round's `I⋈P` with the pages the pass wrote re-read into+ * their slots (a rewritten page in its own slot, a new page last; sync-pass.ts `confirmPages`). Only those slots changed,+ * so only the origins they named before and name now can claim differently: each is claimed again from its rows, in row+ * order, by `claimOrigins`' own rule, and the domain, the twins and the attestation walk are updated at those origins and+ * at the marker paths. What the patch leaves is what a full build at this round gives (the narrowing probe).+ */+import { resolveSlugForPath } from '../sync.ts';+import { isWindowsColonTarget } from './native-file-target.ts';+import type { GitTreeEntry } from './sync-git-stream.ts';+import type { PageTable } from './sync-pass.ts';+import type { LoopYield } from './sync-yield.ts';++/** What a committed-mode round leaves for the next round at the same tree (`PassLevelCache.domain`). */+export interface LevelDomainCache {+ treeKey: string;+ /** The `I⋈P` table it was built from: a confirm round re-reads into this same object. */+ table: PageTable;+ byOrigin: Map<string, number>; claimants: Map<string, number[]>;+ /** The domain, and the paths in it only a marker brought. */+ domain: Set<string>; markerOnly: string[];+ /** Claimed origins that count for no reconcilable page (a tombstone, or outside the level). */+ unreconciled: Set<string>;+ /** Domain paths that are not their own case and separator fold (spelling-twin candidates). */+ unfolded: Set<string>;+ /** The attestation walk: origins whose page needs the baseline tree, and whose page needs a proof read (`A`). */+ baselineWanted: Set<string>; unproven: Set<string>;+}++export interface DomainInput {+ pages: PageTable; tree: Map<string, GitTreeEntry>; keyOf: (row: number) => string; inLevel: (path: string) => boolean;+ /** Working mode's untracked and index paths (none in committed mode). */+ extra: Iterable<string>;+ markerPaths: readonly string[];+ isFile: (path: string) => boolean; originOf: (gitPath: string) => string; step: LoopYield;+ /** A taken confirm round at the cached tree: the cache and what the re-read replaced. */+ prior?: { cache: LevelDomainCache; changed: { rewritten: Array<{ slot: number; sourcePath: string; slug: string }>; from: number }; oldKey: (sourcePath: string, slug: string) => string };+}++export interface LevelDomain extends LevelDomainCache {+ twins: Set<string>; twinGroups: string[][];+ /** Patched: the origins claimed again and the marker paths of both rounds (what the classification looks at again). */+ touched: Set<string> | null;+}++const fold = (path: string) => path.replaceAll('\\', '/').toLowerCase();+const claimBeats = (pages: PageTable, row: number, win: number | undefined) =>+ win === undefined || (pages.deleted(win) && !pages.deleted(row)) || (pages.deleted(win) === pages.deleted(row) && Number(pages.id[row]) > Number(pages.id[win]));+/** A record naming the tree's blob keeps the tree's copy of its id: a converged 600k level holds one string per blob. */+const shareBlob = (pages: PageTable, row: number, tree: Map<string, GitTreeEntry>, key: string) => {+ const committed = pages.hasRecord(row) && tree.get(key);+ if (committed && pages.blobOid[row] === committed.oid) pages.blobOid[row] = committed.oid;+};++/**+ * The page claiming each origin (keyed by `keyOf`): the live one first, else the newest tombstone; and every page recording+ * an origin that more than one page records (#6517), in row order, so the level can name an ambiguous origin.+ */+async function claimOrigins(pages: PageTable, keyOf: (row: number) => string, tree: Map<string, GitTreeEntry>, step: LoopYield) {+ const byOrigin = new Map<string, number>(), claimants = new Map<string, number[]>();+ for (let row = 0; row < pages.length; row++) {+ if (step.due()) await step.pause();+ if (isWindowsColonTarget(pages.sourcePath[row]!)) continue;+ const key = keyOf(row);+ const prior = byOrigin.get(key);+ if (prior !== undefined) { const all = claimants.get(key); if (all) all.push(row); else claimants.set(key, [prior, row]); }+ if (claimBeats(pages, row, prior)) byOrigin.set(key, row);+ shareBlob(pages, row, tree, key);+ }+ return { byOrigin, claimants };+}++/** What the next round at `treeKey` patches (`PassLevelCache.domain`): the domain without this round's twins and touched origins. */+export function domainCache(domain: LevelDomain, treeKey: string): LevelDomainCache {+ const { twins: _twins, twinGroups: _groups, touched: _touched, ...cache } = domain;+ return { ...cache, treeKey };+}++export async function levelDomain(input: DomainInput): Promise<LevelDomain> {+ return input.prior ? patchedDomain(input, input.prior) : fullDomain(input);+}++async function fullDomain(input: DomainInput): Promise<LevelDomain> {+ const { pages, tree, inLevel, step } = input;+ const { byOrigin, claimants } = await claimOrigins(pages, input.keyOf, tree, step);+ const domain = new Set<string>(), unreconciled = new Set<string>(), markerOnly: string[] = [];+ for (const path of tree.keys()) { domain.add(path); if (step.due()) await step.pause(); }+ for (const path of input.extra) domain.add(path);+ for (const [path, i] of byOrigin) {+ if (step.due()) await step.pause();+ if (!inLevel(path)) { unreconciled.add(path); continue; }+ domain.add(path);+ if (pages.deleted(i)) unreconciled.add(path);+ }+ for (const path of input.markerPaths) if (inLevel(path) && !domain.has(path)) { domain.add(path); markerOnly.push(path); }+ const unfolded = new Set<string>();+ for (const path of domain) { if (step.due()) await step.pause(); if (fold(path) !== path) unfolded.add(path); }+ const cache = { treeKey: '', table: pages, byOrigin, claimants, domain, markerOnly, unreconciled, unfolded, baselineWanted: new Set<string>(), unproven: new Set<string>() };+ return { ...cache, ...await spellingTwins(input, cache), touched: null };+}++async function patchedDomain(input: DomainInput, prior: NonNullable<DomainInput['prior']>): Promise<LevelDomain> {+ const { pages, tree, inLevel } = input, { cache, changed } = prior, { byOrigin, claimants, domain } = cache;+ const slots = new Map<number, string | null>(), touched = new Set<string>();+ for (const row of changed.rewritten) if (!isWindowsColonTarget(row.sourcePath)) touched.add(prior.oldKey(row.sourcePath, row.slug));+ for (const row of changed.rewritten) slots.set(row.slot, null);+ for (let i = changed.from; i < pages.length; i++) slots.set(i, null);+ for (const slot of slots.keys()) if (!isWindowsColonTarget(pages.sourcePath[slot]!)) { const key = input.keyOf(slot); slots.set(slot, key); touched.add(key); }+ for (const key of touched) {+ const rows = (claimants.get(key) ?? (byOrigin.has(key) ? [byOrigin.get(key)!] : [])).filter(row => !slots.has(row));+ for (const [slot, now] of slots) if (now === key) rows.push(slot);+ rows.sort((a, b) => a - b);+ let win: number | undefined;+ for (const row of rows) if (claimBeats(pages, row, win)) win = row;+ if (win === undefined) byOrigin.delete(key); else byOrigin.set(key, win);+ if (rows.length > 1) claimants.set(key, rows); else claimants.delete(key);+ }+ for (const [slot, key] of slots) if (key !== null) shareBlob(pages, slot, tree, key);+ for (const path of cache.markerOnly) { domain.delete(path); touched.add(path); }+ for (const key of touched) {+ const at = byOrigin.get(key), claimed = at !== undefined && inLevel(key);+ if (tree.has(key) || claimed) domain.add(key); else domain.delete(key);+ if (at === undefined || (claimed && !pages.deleted(at))) cache.unreconciled.delete(key); else cache.unreconciled.add(key);+ }+ const markerOnly: string[] = [];+ for (const path of input.markerPaths) if (inLevel(path) && !domain.has(path)) { domain.add(path); markerOnly.push(path); }+ for (const path of markerOnly) touched.add(path);+ for (const path of touched) if (domain.has(path) && fold(path) !== path) cache.unfolded.add(path); else cache.unfolded.delete(path);+ const next = { ...cache, table: pages, markerOnly };+ return { ...next, ...await spellingTwins(input, next), touched };+}++/**+ * The attestation walk over the claimed origins (every one built in full, the touched ones patched): whose page needs the+ * baseline tree, and whose page needs a proof read (`A`); the rows to read, and whether the baseline tree is wanted.+ */+export async function walkAttestations(domain: LevelDomain, attest: (path: string, row: number) => { baseline: boolean; unproven: boolean }, step: LoopYield) {+ const keys: Iterable<string> = domain.touched ?? domain.byOrigin.keys();+ for (const key of keys) {+ if (step.due()) await step.pause();+ domain.baselineWanted.delete(key); domain.unproven.delete(key);+ const at = domain.byOrigin.get(key);+ if (at === undefined) continue;+ const verdict = attest(key, at);+ if (verdict.baseline) domain.baselineWanted.add(key);+ if (verdict.unproven) domain.unproven.add(key);+ }+ return { rows: [...domain.unproven].map(key => domain.byOrigin.get(key)!), wantBaseline: domain.baselineWanted.size > 0 };+}++/**+ * Spellings of one origin that differ only by case or separator. Files at L count (`isFile`), and so does a live page's+ * separator-spelled origin. Only a path that is not its own fold can bring a fold in (`unfolded`); the fold's spellings+ * are those paths and the fold itself. As discovery does, only spellings that name one page are twins: a live origin's page+ * slug, else the slug its path names.+ */+async function spellingTwins(input: DomainInput, domain: Pick<LevelDomainCache, 'byOrigin' | 'domain' | 'unfolded'>) {+ const { pages } = input;+ const live = (path: string) => { const at = domain.byOrigin.get(path); return at !== undefined && !pages.deleted(at) ? at : undefined; };+ const spelled = (path: string) => { const at = live(path); return input.isFile(path) || (at !== undefined && pages.sourcePath[at]!.includes('\\')); };+ const folds = new Set<string>();+ for (const path of domain.unfolded) { if (input.step.due()) await input.step.pause(); if (spelled(path)) folds.add(fold(path)); }+ const twins = new Set<string>(), twinGroups: string[][] = [];+ if (!folds.size) return { twins, twinGroups };+ const spellings = new Map<string, string[]>();+ for (const path of [...domain.unfolded, ...[...folds].filter(own => domain.domain.has(own))]) {+ const folded = fold(path);+ if (!folds.has(folded) || !spelled(path)) continue;+ const prior = spellings.get(folded);+ if (prior) prior.push(path); else spellings.set(folded, [path]);+ }+ for (const paths of spellings.values()) {+ if (paths.length < 2) continue;+ const slugOf = (path: string) => { const at = live(path); return at !== undefined ? pages.slug[at]! : resolveSlugForPath(input.originOf(path)); };+ const bySlug = new Map<string, string[]>();+ for (const path of paths) bySlug.set(slugOf(path), [...bySlug.get(slugOf(path)) ?? [], path]);+ for (const group of bySlug.values()) if (group.length > 1) { twinGroups.push(group); for (const path of group) twins.add(path); }+ }+ return { twins, twinGroups };+}++/**+ * A patched round's classification walk in the domain's sorted order: the previous round's entries, each kept as it is,+ * with the paths to classify again in their places: `again` within the domain, and each entry `keep` refuses. `again`+ * holds every path that may have left or joined the domain, so every other entry's path is still in it.+ */+export function narrowedWalk<T extends { path: string }>(prior: readonly T[], domain: Set<string>, again: Set<string>, keep: (entry: T) => boolean): Array<string | T> {+ const fresh = [...again].filter(path => domain.has(path)).sort(), walk: Array<string | T> = [];+ let j = 0;+ for (const entry of prior) {+ while (j < fresh.length && fresh[j]! < entry.path) walk.push(fresh[j++]!);+ if (fresh[j] === entry.path) { walk.push(fresh[j++]!); continue; }+ if (!again.has(entry.path)) walk.push(keep(entry) ? entry : entry.path);+ }+ while (j < fresh.length) walk.push(fresh[j++]!);+ return walk;+}diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 75ce629eac..989b30e4a8 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -754,10 +754,11 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr// The previous round's level is done with: dropped before the next one is read, so a large source holds one level, not two.lastLevel = null;await faultPoint('sync:round_start', { sourceId, round });- const level = await readShadowLevel(engine, { sourceId, context, workingTree: mode === 'working',+ const levelInput = { sourceId, context, workingTree: mode === 'working',pass: { noSchemaPack: processingOptions.noSchemaPack, episodeFullId: episode?.full_id ?? null, retryConsumed: round > 1 ? retryConsumed : undefined, exclude: opts.exclude, includeHidden: opts.includeHidden, strategy: opts.strategy, bootstrap: markersOwed(),- slugMode: value.obligations.slug_mode, cache: levelCache, passId, recorded: applied.recorded } });- await faultPoint('sync:level_read', { sourceId, round, level: level ? { statements: level.statements, confirm: level.confirm ?? null, reused: level.reused ?? 0 } : undefined });+ slugMode: value.obligations.slug_mode, cache: levelCache, passId, recorded: applied.recorded } };+ const level = await readShadowLevel(engine, levelInput);+ await faultPoint('sync:level_read', { sourceId, round, level: level ? { statements: level.statements, confirm: level.confirm ?? null, reused: level.reused ?? 0, shadow: level, input: levelInput } : undefined });assertActive();if (!level) throw new Error(`Source ${sourceId} became a company-brain source during its sync pass.`);// Each round reads the level at the current HEAD, and its batches freeze that commit (a commit landing mid-pass isdiff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 985cf68018..804ee6be7c 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -43,6 +43,7 @@ import { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP, type SyncSelection } fromimport { faultPoint } from './fault-points.ts';import { filterYielding, loopYield, sortYielding, turnYield, type LoopYield } from './sync-yield.ts';import { countsMatch, proveConfirm, readLevelMark, type ConfirmProof, type LevelMark } from './sync-pass-confirm.ts';+import { domainCache, levelDomain, narrowedWalk, walkAttestations, type LevelDomainCache } from './sync-pass-narrow.ts';export { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP };@@ -93,6 +94,8 @@ export interface PassLevelCache {pages?: { key: string; mark: LevelMark; table: PageTable };/** The last committed-mode round's classified paths, keyed by every level-wide input the classifier reads (`classifiedKey`). */classified?: { key: string; treeKey: string; paths: ShadowPath[] };+ /** The last committed-mode round's origin domain, which a taken confirm round at its tree patches (sync-pass-narrow.ts). */+ domain?: LevelDomainCache;}/**@@ -210,6 +213,15 @@ function matchedUnchanged(level: { pages: PageTable; tree: Map<string, GitTreeEn};}+/**+ * `matchedUnchanged`'s tests a narrowed round runs on every entry it keeps (sync-pass-narrow.ts `narrowedWalk`): the ones+ * on the entry and the round's open work and markers. The rest are tests on paths, which the round classifies again.+ */+function keptUnread(open: { pageIds: Set<number>; origins: Set<string> }, markers: Map<string, unknown>, originOf: (path: string) => string): (entry: ShadowPath) => boolean {+ return entry => entry instanceof MatchedPath && Object.isFrozen(entry.result) && entry.result.cls === 'matched' && entry.treeOid === entry.levelOid && !open.pageIds.has(entry.pageId!)+ && ((!markers.size && !open.origins.size) || (!markers.has(originOf(entry.path)) && !open.origins.has(originOf(entry.path))));+}+/** The origins (`keyOf`) whose page a confirm round re-read: a rewritten page's previous and current one, and each new page's. */function confirmChangedPaths(pages: PageTable, changed: { rewritten: Array<{ slot: number; sourcePath: string; slug: string }>; from: number }, keyOf: (sourcePath: string, slug: string) => string): Set<string> {const paths = new Set<string>();@@ -253,7 +265,9 @@ export interface ShadowLevel {timings_ms: Record<string, number>;statements: number;/** A round after a pass's first: whether it reused the previous round's `I⋈P` (`rows` re-read), or why it read it whole. */- confirm?: { taken: boolean; reason: string | null; rows: number };+ confirm?: { taken: boolean; reason: string | null; rows: number;+ /** A taken confirm round: `taken` when it patched the previous round's domain and classification, else why it built them whole. */+ narrow?: string };/** A taken confirm round: the paths whose previous-round classification it kept (`reusableMatched`). */reused?: number;}@@ -280,7 +294,7 @@ const PAGE_DELETED = 1, PAGE_RECORD = 2, PAGE_REVISION_NULL = 4, PAGE_PARSER_EXP* record field that differs from its usual value (origin = source_path, disk = blob, revision = the page's, the expected* parser) is kept only for the pages where it does; `row` rebuilds the `PageRow` the classifier reads.*/-class PageTable {+export class PageTable {readonly id: Array<number | string> = []; readonly slug: string[] = []; readonly sourcePath: string[] = []; readonly revision: string[] = [];readonly requestId: Array<string | null> = []; readonly bits: number[] = []; readonly blobOid: Array<string | undefined> = []; readonly fullEpisode: Array<string | null> = [];readonly origin = new Map<number, string>(); readonly diskBlobOid = new Map<number, string | null>(); readonly recordRevision = new Map<number, string>();@@ -594,7 +608,8 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst cache = input.pass?.cache;// The previous round's classification leaves the cache before anything can fail (only a complete round's is stored).let priorClassified = cache?.classified?.treeKey === treeKey ? cache.classified : undefined;- if (cache) cache.classified = undefined;+ const priorDomain = cache?.domain;+ if (cache) { cache.classified = undefined; cache.domain = undefined; }// The tree's ':' paths (#5032) are kept apart: they are refused, never part of the level.const eligibleTree = async (): Promise<{ tree: Map<string, GitTreeEntry>; colon: string[] }> => {if (cache?.tree?.key === treeKey) return cache.tree;@@ -647,22 +662,15 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst moved = new Set(held.moved.map(toGit));t = timer();- const pages = snapshot.pages;- const { byOrigin, claimants } = await claimOrigins(pages, i => gitPathOf(pageOrigin(pages.sourcePath[i]!, pages.slug[i]!)), tree, step);+ const pages = snapshot.pages, keyOf = (i: number) => gitPathOf(pageOrigin(pages.sourcePath[i]!, pages.slug[i]!));+ // A taken confirm round at the cached tree patches the previous round's domain at the origins the pass wrote (sync-pass-narrow.ts).+ const narrow = !snapshot.changed ? null : !priorDomain ? 'cache' : mode !== 'committed' || priorDomain.treeKey !== treeKey || priorDomain.table !== pages ? 'key' : process.platform === 'win32' ? 'platform'+ : colonRefused.size ? 'colon' : input.pass?.bootstrap ? 'bootstrap' : await faultPoint('sync:level_narrow', { sourceId }).then(() => 'taken', () => 'forced');+ const levelD = await levelDomain({ pages, tree, keyOf, inLevel, extra: [...untracked, ...(mode === 'working' ? [...index.keys()].filter(inLevel) : [])], markerPaths: [...markers.keys()].map(gitPathOf),+ isFile: path => tree.has(path) || (mode === 'working' && (untracked.has(path) || index.has(path))), originOf, step,+ ...(narrow === 'taken' ? { prior: { cache: priorDomain!, changed: snapshot.changed!, oldKey: (sourcePath: string, slug: string) => gitPathOf(pageOrigin(sourcePath, slug)) } } : {}) });+ const { byOrigin, claimants, domain, twins, twinGroups } = levelD, reconcilable = byOrigin.size - levelD.unreconciled.size;const rowAt = (path: string): PageRow | undefined => { const i = byOrigin.get(path); return i === undefined ? undefined : pages.row(i); };- const domain = new Set<string>();- for (const path of tree.keys()) { domain.add(path); if (step.due()) await step.pause(); }- for (const path of untracked) domain.add(path);- if (mode === 'working') for (const path of index.keys()) if (inLevel(path)) domain.add(path);- let reconcilable = 0;- for (const [path, i] of byOrigin) {- if (!inLevel(path)) continue;- domain.add(path);- if (!pages.deleted(i)) reconcilable++;- if (step.due()) await step.pause();- }- for (const origin of markers.keys()) { const path = gitPathOf(origin); if (inLevel(path)) domain.add(path); }- const { twins, twinGroups } = await spellingTwins(domain, rowAt, path => tree.has(path) || (mode === 'working' && (untracked.has(path) || index.has(path))), originOf, step);timings.domain = t();// Working mode rehashes every path (the full round's unconditional rehash); committed mode probes candidates only.@@ -675,15 +683,11 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st// `A` only matters where the file or the database moved (no row settles on `fileSame ∧ dbSame` with a proof): read it// for those pages alone, so a converged source reads none. The same walk finds whether any path needs the baseline tree.t = timer();- const unproven: number[] = [];- let wantBaseline = false;- for (const [path, i] of byOrigin) {- if (step.due()) await step.pause();+ const { rows: unproven, wantBaseline } = await walkAttestations(levelD, (path, i) => {const level = levelOf(path, probes.get(path)), deleted = pages.deleted(i), revision = pages.recordRevisionOf(i), names = pages.names(i, level);- if (!deleted && revision == null && level !== null && !names && inLevel(path)) wantBaseline = true;- if (pages.requestId[i] === null) continue;- if (deleted || level === null || !names || revision == null || String(revision) !== pages.revision[i]) unproven.push(i);- }+ return { baseline: !deleted && revision == null && level !== null && !names && inLevel(path),+ unproven: pages.requestId[i] !== null && (deleted || level === null || !names || revision == null || String(revision) !== pages.revision[i]) };+ }, step);const attestationStatements = unproven.length ? await readAttestations(engine, engineKind, sourceId, incarnation, pages, unproven) : 0;timings.A = t();@@ -774,10 +778,16 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst candidates: string[] = [], candidateAt: number[] = [];const settledBeforeDirtiness = new Set(['held', 'spelling', 'untracked', 'kept', 'delete', 'delete_drift', 'gone', 'deleted_same', 'deleted_edited', 'legacy_same', 'matched']);const shared = { mode, fullObligation: input.pass ? !!input.pass.episodeFullId : input.full === true };- for (const path of await sortYielding([...domain], step)) {+ // The cached claims stay whole for the next round. A narrowed round classifies again the paths whose entry `matchedUnchanged`+ // can fail on (`again`, and the entries `keptUnread` refuses); every other entry of the previous round stays as it is.+ const keepClaims = !!cache && mode === 'committed';+ const walk = narrow === 'taken' && reuse ? narrowedWalk(priorClassified!.paths, domain, new Set([...levelD.touched!, ...claimants.keys(), ...holdByGitPath.keys(), ...indexDelta?.keys() ?? [],+ ...twins, ...legacySpelling, ...[...pages.attested.keys()].map(keyOf)]), keptUnread(open, markers, originOf)) : await sortYielding([...domain], step);+ for (const item of walk) {if (step.due()) await step.pause();- const kept = reuse?.(path);- if (kept) { byOrigin.delete(path); paths.push(kept); reused++; continue; }+ if (typeof item !== 'string') { paths.push(item); reused++; continue; }+ const path = item, kept = reuse?.(path);+ if (kept) { if (!keepClaims) byOrigin.delete(path); paths.push(kept); reused++; continue; }const probe = probes.get(path);const { state, at, legacyPageless } = stateOf(path, mode === 'committed' && tree.has(path) ? 'clean' : null, probe);const result = sharedResult(classifySyncPath(state));@@ -790,7 +800,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stif (mode === 'committed' && tree.has(path) && (!settledBeforeDirtiness.has(result.cls) || staged)) { candidates.push(path); candidateAt.push(paths.length); }else {// The row's fields the level keeps are copied onto the entry; only a candidate's row is read again (its dirtiness re-classifies it).- byOrigin.delete(path);+ if (!keepClaims) byOrigin.delete(path);if (result.cls === 'matched' && !legacyPageless && !ambiguousOrigin && MatchedPath.fits(state, revision, shared)) {paths.push(new MatchedPath(path, pages.slug[at!]!, Number(pages.id[at!]), revision, result, state.tree, state.level!, state.dirty, state.record!.blobOids.length === 2, shared));continue;@@ -835,11 +845,15 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stretryRow: retry.size > 0, notConvergedStreak: 0, mismatchStreak: 0, requestNewer: false, openAtStampFinished: false, workingChange: false,rescreenDueHold: holds.some(hold => holdRescreenDue(hold, retry.has(hold.path))), full: input.full === true });timings.total = total();- if (cache && mode === 'committed') cache.classified = { key: classifiedKey, treeKey, paths };+ if (cache && mode === 'committed') {+ cache.classified = { key: classifiedKey, treeKey, paths };+ if (!colonRefused.size) cache.domain = domainCache(levelD, treeKey);+ }return { sourceId, incarnation, root, gitRoot, scope, slugMode, mode, head, baselineCommit, full: input.full === true, kind: kind.kind, kindBlockers: kind.blockers,heldRenames: holds.flatMap(hold => hold.meta.rename_from ? [{ path: toGit(hold.path), rename: hold.meta.rename_from }] : []),releasableHolds: holds.filter(hold => !domain.has(toGit(hold.path))).map(hold => hold.path),- paths, reconcilable, ...(colon.refusals.size ? { fileRefusals: [...colon.refusals.values()] } : {}), timings_ms: timings, statements: statements + attestationStatements + 3, ...(confirm ? { confirm } : {}), ...(reuse ? { reused } : {}), pack: pack?.identity ?? null,+ paths, reconcilable, ...(colon.refusals.size ? { fileRefusals: [...colon.refusals.values()] } : {}), timings_ms: timings, statements: statements + attestationStatements + 3,+ ...(confirm ? { confirm: narrow ? { ...confirm, narrow: narrow === 'taken' && !reuse ? 'classified' : narrow } : confirm } : {}), ...(reuse ? { reused } : {}), pack: pack?.identity ?? null,selection: { exclude: [...exclude].sort(), includeHidden: [...includeHidden].sort(), strategy, srcSubpath: scope || null, mode },rescreenDue: holds.filter(hold => holdRescreenDue(hold, retry.has(hold.path))).map(hold => toGit(hold.path)), workingCache: hashed?.cache ?? null };}@@ -991,32 +1005,6 @@ async function readLevelHolds(engine: BrainEngine, sourceId: string, incarnationreturn { holds, retry: new Set(retryPaths.filter(path => !retryConsumed?.has(path))), moved: [...basisMoved, ...driftMoved] };}-/**- * Spellings of one origin that differ only by case or separator (the domain holds each path once). Files at L count- * (`isFile`), and so does a live page's separator-spelled origin; a case-only respelling whose old file this sync removes- * is no refusal (discovery's one exception). As discovery does, only spellings that name one page are twins: a live- * origin's page slug, else the slug its path names.- */-/**- * The page claiming each origin (keyed by `keyOf`): the live one first, else the newest tombstone; and every page recording- * an origin that more than one page records (#6517), so the level can name an ambiguous origin. A record naming the tree's- * blob keeps the tree's copy of its id: a converged 600k level holds one string per blob.- */-async function claimOrigins(pages: PageTable, keyOf: (row: number) => string, tree: Map<string, GitTreeEntry>, step: LoopYield) {- const byOrigin = new Map<string, number>(), claimants = new Map<string, number[]>();- for (let row = 0; row < pages.length; row++) {- if (step.due()) await step.pause();- if (isWindowsColonTarget(pages.sourcePath[row]!)) continue;- const key = keyOf(row);- const prior = byOrigin.get(key);- if (prior !== undefined) { const all = claimants.get(key); if (all) all.push(row); else claimants.set(key, [prior, row]); }- if (prior === undefined || (pages.deleted(prior) && !pages.deleted(row)) || (pages.deleted(prior) === pages.deleted(row) && Number(pages.id[row]) > Number(pages.id[prior]))) byOrigin.set(key, row);- const committed = pages.bits[row]! & PAGE_RECORD && tree.get(key);- if (committed && pages.blobOid[row] === committed.oid) pages.blobOid[row] = committed.oid;- }- return { byOrigin, claimants };-}-/** One parser per importer kind (`syncImportParserFor`) for a whole level, not one object per path. */function parserByKind(schemaPack: string | null): (path: string) => SyncImportParser {const parsers = new Map<string, SyncImportParser>();@@ -1028,37 +1016,6 @@ function parserByKind(schemaPack: string | null): (path: string) => SyncImportPa};}-async function spellingTwins(domain: Set<string>, rowAt: (path: string) => PageRow | undefined, isFile: (path: string) => boolean, originOf: (gitPath: string) => string, step: LoopYield) {- const fold = (path: string) => path.replaceAll('\\', '/').toLowerCase();- const spelled = (path: string) => { const live = rowAt(path); return isFile(path) || !!(live && !live.deleted && live.source_path.includes('\\')); };- // Two spellings fold alike only when one is not its own fold, so the first walk keeps only those folds; the second- // groups, in the domain's order, the spellings of those folds (a level with none keeps no map of every path).- const folds = new Set<string>();- for (const path of domain) {- if (step.due()) await step.pause();- const folded = fold(path);- if (folded !== path && spelled(path)) folds.add(folded);- }- const twins = new Set<string>(), twinGroups: string[][] = [];- if (!folds.size) return { twins, twinGroups };- const spellings = new Map<string, string[]>();- for (const path of domain) {- if (step.due()) await step.pause();- const folded = fold(path);- if (!folds.has(folded) || !spelled(path)) continue;- const prior = spellings.get(folded);- if (prior) prior.push(path); else spellings.set(folded, [path]);- }- for (const paths of spellings.values()) {- if (paths.length < 2) continue;- const slugOf = (path: string) => { const live = rowAt(path); return live && !live.deleted ? live.slug : resolveSlugForPath(originOf(path)); };- const bySlug = new Map<string, string[]>();- for (const path of paths) bySlug.set(slugOf(path), [...bySlug.get(slugOf(path)) ?? [], path]);- for (const group of bySlug.values()) if (group.length > 1) { twinGroups.push(group); for (const path of group) twins.add(path); }- }- return { twins, twinGroups };-}-/*** Master refuses a spelling only among the files its sync claims (sync-discovery.ts:538-541): the live page's origin and the* page-less spellings that changed since the cursor. A page-less spelling unchanged since the baseline was never claimeddiff --git a/test/e2e/sync-pass-narrow-6712-postgres.test.ts b/test/e2e/sync-pass-narrow-6712-postgres.test.tsnew file mode 100644index 0000000000..a6bfb8c992--- /dev/null+++ b/test/e2e/sync-pass-narrow-6712-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../sync-pass-narrow-6712.test.ts'));diff --git a/test/sync-pass-confirm-6712.test.ts b/test/sync-pass-confirm-6712.test.tsindex 5d6bbc2cde..1ca5f53f32 100644--- a/test/sync-pass-confirm-6712.test.ts+++ b/test/sync-pass-confirm-6712.test.ts@@ -53,7 +53,7 @@ async function dbEdit(engine: BrainEngine, ctx: OperationContext, slug: string,{ timeoutMs: 30_000, label: `the database-only edit of ${slug} commits` });await engine.setConfig('sync.write_through', 'true');}-type Verdict = { round: number; confirm: { taken: boolean; reason: string | null; rows: number } | null };+type Verdict = { round: number; confirm: { taken: boolean; reason: string | null; rows: number; narrow?: string } | null };/** One sync with `between` run before round 2 reads its level; the rounds' confirm verdicts and the result. */async function pass(engine: BrainEngine, between: () => Promise<void> = async () => {}) {const verdicts: Verdict[] = [];@@ -82,11 +82,11 @@ for (const backend of testBackends()) {const changed = await pass(engine);expect({ status: changed.status, held: changed.held }).toEqual({ status: 'synced', held: [] });expect(changed.verdicts[0]).toEqual({ round: 1, confirm: null });- expect(round2(changed)).toEqual({ taken: true, reason: null, rows: 1 });+ expect(round2(changed)).toEqual({ taken: true, reason: null, rows: 1, narrow: 'taken' });expect(await bodyOf(engine, 'notes/a')).toContain('A committed change of notes/a.');edit(root, 'notes/d', 'A new file.'); commit(root, 'add d');const added = await pass(engine);- expect({ status: added.status, confirm: round2(added) }).toEqual({ status: 'synced', confirm: { taken: true, reason: null, rows: 1 } });+ expect({ status: added.status, confirm: round2(added) }).toEqual({ status: 'synced', confirm: { taken: true, reason: null, rows: 1, narrow: 'taken' } });expect(await bodyOf(engine, 'notes/d')).toContain('A new file.');expect((await performManagedSync(engine, OPTS)).pass).toBeUndefined();}), 180_000);@@ -133,7 +133,7 @@ for (const backend of testBackends()) {await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_IMPORT_PROVENANCE_OP, `default:${await incarnationOf(engine)}:${page!.id}`]);edit(root, 'notes/a', 'A committed change of notes/a.'); edit(root, 'notes/b', 'The second committed body.'); commit(root, 'change a and b');const run = await pass(engine);- expect(round2(run)).toEqual({ taken: true, reason: null, rows: 1 });+ expect(round2(run)).toEqual({ taken: true, reason: null, rows: 1, narrow: 'taken' });expect({ status: run.status, held: run.held }).toEqual({ status: 'synced', held: [['notes/b.md', 'file_drift']] });expect(await bodyOf(engine, 'notes/b')).toContain('DBONLYMARKER the agent edit.');expect(readFileSync(join(root, 'notes/b.md'), 'utf8')).toContain('The second committed body.');diff --git a/test/sync-pass-narrow-6712.test.ts b/test/sync-pass-narrow-6712.test.tsnew file mode 100644index 0000000000..03042ce761--- /dev/null+++ b/test/sync-pass-narrow-6712.test.ts@@ -0,0 +1,153 @@+/**+ * #6712 PR 4b fix 3, first part: a taken confirm round at the previous round's tree patches the previous round's origin+ * domain (claims, claimants, domain, spelling twins, the attestation walk) at the origins the pass wrote, and classifies+ * again only the paths whose kept entry could change (sync-pass-narrow.ts). Every other round reads in full, as before.+ *+ * Protects: on each case, every taken round after the first gives exactly the level a cacheless full read of the same+ * database and tree gives: each path's class, state (attestation `A`, spelling twin), page, revision and claimants, and+ * the level's reconcilable count, holds and kind. Cases: a round-1 edit, a rename that moves a page's origin (old and new)+ * and a new page, alone and beside tombstones at the rename's and the new page's origins, several live pages on one+ * origin (#6948), several tombstones, two spellings and a differing identity (GBRA-130); and the seeded mix. A round whose+ * seam refuses the patch (`sync:level_narrow`) builds the domain whole and says so (`narrow: 'forced'`), with the same level.+ *+ * PGLite here; Postgres through test/e2e/sync-pass-narrow-6712-postgres.test.ts.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+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 { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { readShadowLevel, type ShadowLevel } from '../src/core/persistence/sync-pass.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { mixSetup, seedMix } from '../scripts/bench/sync-convergence-seeded.ts';+import { dropOriginIndex } from './helpers/origin-index.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { 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, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+const note = (title: string, body = `The body of ${title}.`, front = '') => `---\ntype: concept\ntitle: ${title}\n${front}---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (const slug of ['a', 'b', 'c']) writeFileSync(join(root, `notes/${slug}.md`), note(`notes/${slug}`));+ writeFileSync(join(root, 'notes/Kept Doc.md'), note('Kept doc', 'A kept document.', 'id: kept-one\n'));+ commit(root, 'notes');+};++/** What the level hands the pass, path by path and level-wide. */+function project(level: ShadowLevel) {+ return {+ paths: level.paths.map(entry => ({ path: entry.path, slug: entry.slug, pageId: entry.pageId, revision: entry.revision, result: entry.result, state: entry.state,+ legacyPageless: entry.legacyPageless ?? null, ambiguousOrigin: entry.ambiguousOrigin ?? null })),+ reconcilable: level.reconcilable, releasableHolds: level.releasableHolds, heldRenames: level.heldRenames, rescreenDue: level.rescreenDue, kind: level.kind,+ kindBlockers: level.kindBlockers, fileRefusals: level.fileRefusals ?? null,+ };+}++type Compared = { round: number; narrow: string | undefined; same: boolean; paths: number };+/** A sync whose rounds after the first, when their confirm round is taken, are each compared with a cacheless full read. */+async function compared(engine: BrainEngine, { force = false } = {}) {+ const rounds: Compared[] = [], mismatches: unknown[] = [];+ installFaultHook(async (point, detail) => {+ if (point === 'sync:level_narrow' && force) throw new Error('a refused patch');+ if (point !== 'sync:level_read' || !detail.level?.confirm?.taken) return;+ const input = detail.level.input as Parameters<typeof readShadowLevel>[1];+ const narrowed = project(detail.level.shadow as ShadowLevel);+ const full = project((await readShadowLevel(engine, { ...input, pass: { ...input.pass!, cache: undefined, passId: undefined } }))!);+ const same = JSON.stringify(narrowed) === JSON.stringify(full);+ if (!same) mismatches.push({ round: detail.round, narrowed, full });+ rounds.push({ round: detail.round!, narrow: detail.level.confirm.narrow, same, paths: narrowed.paths.length });+ });+ try {+ const result = await performManagedSync(engine, OPTS);+ expect(mismatches).toEqual([]);+ return { status: result.status, rounds };+ } finally { installFaultHook(undefined); }+}+const narrowed = (run: { rounds: Compared[] }) => run.rounds.filter(round => round.narrow === 'taken');++/** A second live page recording notes/a.md (#6948), as legacy data left it. */+async function liveTwin(engine: BrainEngine) {+ await dropOriginIndex(engine);+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {+ await tx.putPage('notes/a-copy', { type: 'concept', title: 'Example', compiled_truth: 'A different body.', timeline: '', frontmatter: {}, content_hash: crypto.randomUUID() }, { sourceId: 'default' });+ await tx.executeRaw("UPDATE pages SET source_path='notes/a.md' WHERE source_id='default' AND slug='notes/a-copy'");+ }, TEST_WRITE_ATTRIBUTION));+}+/** Two deleted pages recording notes/twin.md (#6517). */+async function tombstoneTwins(engine: BrainEngine) {+ for (const slug of ['archive/twin-one', 'archive/twin-two']) await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {+ await tx.putPage(slug, { type: 'note', title: slug, compiled_truth: `Deleted ${slug}.`, timeline: '', frontmatter: {}, content_hash: `h-${slug}` }, { sourceId: 'default' });+ await tx.executeRaw("UPDATE pages SET source_path='notes/twin.md', deleted_at=now() WHERE source_id='default' AND slug=$1", [slug]);+ }, TEST_WRITE_ATTRIBUTION));+}++/** Deleted pages recording the origins round 1 would move a page onto and create a page at: round 1 holds both, beside its edit. */+async function tombstonedTargets(engine: BrainEngine) {+ for (const [slug, path] of [['archive/old-moved', 'notes/b-moved.md'], ['archive/old-new', 'notes/new.md']]) await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {+ await tx.putPage(slug!, { type: 'note', title: slug!, compiled_truth: `Deleted ${slug}.`, timeline: '', frontmatter: {}, content_hash: `h-${slug}` }, { sourceId: 'default' });+ await tx.executeRaw("UPDATE pages SET source_path=$2, deleted_at=now() WHERE source_id='default' AND slug=$1", [slug, path]);+ }, TEST_WRITE_ATTRIBUTION));+}++/**+ * Each case's arrangement after the first sync; round 1 also edits, renames and adds a page (`roundOneWrites`). `whole`:+ * no round of the case takes the confirm round, so it never narrows (several live pages on one origin: their page row is+ * rewritten during each pass's first round, which the confirm round reads as a foreign write), and the case shows only that.+ */+const CASES: Record<string, { arrange: (engine: BrainEngine, root: string) => Promise<void>; whole?: true }> = {+ moves: { arrange: async () => {} },+ tombstoned_targets: { arrange: engine => tombstonedTargets(engine) },+ several_live: { arrange: engine => liveTwin(engine), whole: true },+ several_tombstones: { arrange: async (engine, root) => { await tombstoneTwins(engine); writeFileSync(join(root, 'notes/twin.md'), note('notes/twin')); } },+ spelling: { arrange: async (_engine, root) => { writeFileSync(join(root, 'notes/Case.md'), note('Upper')); writeFileSync(join(root, 'notes/case.md'), note('Lower')); } },+ identity_differs: { arrange: async (_engine, root) => { git(root, 'rm', '-q', 'notes/Kept Doc.md'); writeFileSync(join(root, 'notes/kept-doc.md'), note('Another document', 'Another.', 'id: kept-two\n')); } },+};+const roundOneWrites = (root: string) => {+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'An edited body of notes/a.'));+ git(root, 'mv', 'notes/b.md', 'notes/b-moved.md');+ writeFileSync(join(root, 'notes/new.md'), note('notes/new'));+};++afterEach(() => installFaultHook(undefined));++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;+ const brain = (run: Parameters<typeof managedBrain>[0], seed: (b: { root: string }) => void = setup) => managedBrain(run, { ...(databaseUrl ? { databaseUrl } : {}), setup: seed });+ describe(`#6712 PR 4b round-2 narrowing (${backend})`, () => {+ for (const [name, { arrange, whole }] of Object.entries(CASES)) {+ test(`${name}: a narrowed round is the level a full read gives`, () => brain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await arrange(engine, root);+ roundOneWrites(root);+ commit(root, name);+ const run = await compared(engine);+ expect(run.status).toBe('synced');+ if (whole) expect(run.rounds).toEqual([]);+ else expect(narrowed(run).length).toBeGreaterThan(0);+ expect(run.rounds.every(round => round.same)).toBe(true);+ }), 240_000);+ }++ test('the seeded mix: each narrowed round is the level a full read gives', () => brain(async ({ engine, ctx, root }) => {+ await seedMix({ engine, ctx, root });+ const run = await compared(engine);+ expect(narrowed(run).length).toBeGreaterThan(0);+ expect(run.rounds.every(round => round.same)).toBe(true);+ }, mixSetup), 600_000);++ test('a refused patch builds the domain whole, says so in confirm, and gives the same level', () => brain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ roundOneWrites(root);+ commit(root, 'forced');+ const run = await compared(engine, { force: true });+ expect(run.status).toBe('synced');+ expect(run.rounds.length).toBeGreaterThan(0);+ expect(run.rounds.map(round => [round.narrow, round.same])).toEqual(run.rounds.map(() => ['forced', true]));+ }), 240_000);+ });+}