Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/capy/6712-pr4b' into capy/6712-pr4b-core

garrytanad65e0329ff1
diff --cc src/core/persistence/sync-pass-apply.ts
index a9e6103ae7,3cfd05731a..e613958c44
--- a/src/core/persistence/sync-pass-apply.ts
+++ b/src/core/persistence/sync-pass-apply.ts
@@@ -32,8 -32,9 +32,10 @@@ import { VERSION } from '../../version.
import type { BrainEngine } from '../engine.ts';
import { resolveSlugForPath } from '../sync.ts';
import { massReconcileAllowed, planReconcileDeletes } from '../sync-reconcile.ts';
+import { filterYielding, loopYield } from './sync-yield.ts';
import { admitKeepDbReconcile, freezeKeepDbReconcile, releaseMatchedDriftSkips } from '../repair/keep-db-policy.ts';
+
+ const KEEP_DB_CAPACITY_REFUSALS = new Set(['capacity', 'write_capacity_backpressure', 'queue_capacity', 'write_quota_exhausted', 'writer_busy', 'writer_pool_capacity']);
import type { SyncProcessingOptions } from './sync-authority.ts';
import type { SyncClassified } from './sync-classify.ts';
import { readOnlySameContentScreen } from './sync-convergence.ts';
diff --cc src/core/persistence/sync-pass.ts
index a014f87db4,9bd831e6ad..e3d0516f3a
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@@ -32,8 -34,8 +34,8 @@@ import { confirmedSyncDelta } from '../
import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, SYNC_IMPORT_PROVENANCE_OP, syncImportParserFor,
type GitHoldRecord, type SyncImportProvenance } from './sync-holds.ts';
import { movedDriftHolds, sameParser } from './sync-prescreen.ts';
- import { syncOriginPath } from './sync-origin.ts';
+ import { sameSyncOrigin, selectOriginClaimant, syncOriginPath } from './sync-origin.ts';
-import { hashWorkingLevel, probeDirtiness, readBlobs, readIndexLevel, readTreeLevel, workingChanged, type GitTreeEntry, type WorkingStatCache } from './sync-git-stream.ts';
+import { hashWorkingLevel, probeDirtiness, readBlobs, readIndexDelta, readIndexLevel, readTreeLevel, workingChanged, type GitIndexEntry, type GitTreeEntry, type WorkingStatCache } from './sync-git-stream.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';
@@@ -72,59 -69,13 +74,61 @@@ const POSTGRES_FETCH_ROWS = 25_000
const LEVEL_BLOB_MAX_BYTES = 8 * 1024 * 1024;
const SYNC_WRITE_KINDS = ['managed_sync_import', 'managed_sync_delete'];
+/** What one pass reuses between its rounds: a commit's tree never changes, so the next round at the same commit and selection reads it from here. */
- export interface PassLevelCache { tree?: { key: string; tree: Map<string, GitTreeEntry> } }
++export interface PassLevelCache { tree?: { key: string; tree: Map<string, GitTreeEntry>; colon: string[] } }
+
+/**
+ * Classifier results never change once made (a settle replaces the object), so equal ones are one object: a 600k-path
+ * level holds a handful instead of one per path. Bounded; a result past the bound stays its own.
+ */
+const SHARED_RESULTS = new Map<string, SyncClassified>();
+function sharedResult(result: SyncClassified): SyncClassified {
+ const key = JSON.stringify(result);
+ const shared = SHARED_RESULTS.get(key);
+ if (shared) return shared;
+ if (SHARED_RESULTS.size < 256) SHARED_RESULTS.set(key, Object.freeze(result) as SyncClassified);
+ return result;
+}
+
/** One classified path of the shadow level. */
export interface ShadowPath { path: string; slug: string | null; pageId: number | null; revision: string | null; state: SyncPathState; result: SyncClassified;
/** A page-less path unchanged since the baseline whose page a committed request deleted: the bootstrap writes it a `legacy` marker (`legacy_pageless`). */
- legacyPageless?: true }
+ legacyPageless?: true;
+ /** #6517 (`selectOriginClaimant`): several live pages, or no live page and several tombstones, record this origin. */
+ ambiguousOrigin?: { kind: 'several_live' | 'several_tombstones'; slugs: string[] } }
+/**
+ * A `matched` path whose state is the converged one (a live page whose record proves the level's blob and revision, nothing
+ * held, marked, owed or open): it keeps the few fields that vary and rebuilds the same `SyncPathState` on read. Most paths
+ * of a large converged source are these; a level of 600k holds them in about a fifth of a full entry's memory.
+ */
+class MatchedPath implements ShadowPath {
+ constructor(public path: string, public slug: string | null, public pageId: number | null, public revision: string, public result: SyncClassified,
+ private readonly treeOid: string | null, private readonly levelOid: string, private readonly dirty: SyncPathState['dirty'], private readonly diskRecorded: boolean,
+ private readonly shared: { mode: SyncPathState['mode']; fullObligation: boolean }) {}
+
+ /** Whether `state` is the one `state` would rebuild for a page at `revision`. */
+ static fits(state: SyncPathState, revision: string | null, shared: MatchedPath['shared']): revision is string {
+ return revision !== null && state.mode === shared.mode && state.fullObligation === shared.fullObligation && state.level !== null && state.present
+ && state.diskOid === null && state.levelSha256 === null && !state.published && state.attested === null && state.hold === null && state.marker === null
+ && state.baseline === null && !state.spelling && !state.episodeUnsatisfied && !state.keepDb && !state.openWork
+ && state.page?.live === true && state.page.revision === revision && state.page.originMatches
+ && state.record?.revision === revision && state.record.parserSame && state.record.blobOids.length <= 2 && state.record.blobOids.length > 0
+ && state.record.blobOids.every(oid => oid === state.level);
+ }
+
+ get state(): SyncPathState {
+ return { mode: this.shared.mode, tree: this.treeOid, level: this.levelOid, present: true, dirty: this.dirty, diskOid: null,
+ page: { live: true, revision: this.revision, originMatches: true }, record: { blobOids: this.diskRecorded ? [this.levelOid, this.levelOid] : [this.levelOid], revision: this.revision, parserSame: true },
+ attested: null, levelSha256: null, published: false, hold: null, marker: null, baseline: null, spelling: false, episodeUnsatisfied: false,
+ fullObligation: this.shared.fullObligation, keepDb: false, openWork: false };
+ }
+
+ set state(value: SyncPathState) {
+ Object.defineProperty(this, 'state', { value, writable: true, enumerable: true, configurable: true });
+ }
+}
+
export interface ShadowLevel {
sourceId: string; incarnation: string; root: string; gitRoot: string; scope: string; slugMode: 'git-root' | 'source-root';
mode: 'committed' | 'working'; head: string; baselineCommit: string | null; full: boolean;
@@@ -149,14 -102,10 +155,14 @@@
/** A page of the source with the import-record fields the classifier reads; `arm1` / `attested_hash` (`A`) are filled for the pages that need a proof. */
interface PageRow { id: number | string; slug: string; source_path: string; revision: string; deleted: boolean; request_id: string | null;
- record: (Pick<SyncImportProvenance, 'origin' | 'blob_oid' | 'disk_blob_oid' | 'revision' | 'parser'> & { full_episode?: string | null }) | null; arm1: boolean | null; attested_hash: string | null }
+ record: (Pick<SyncImportProvenance, 'origin' | 'blob_oid' | 'disk_blob_oid' | 'revision' | 'parser' | 'working'> & { full_episode?: string | null }) | null; arm1: boolean | null; attested_hash: string | null }
-const recordOids = (record: PageRow['record']): string[] =>
- record ? [record.blob_oid, record.disk_blob_oid].filter((oid): oid is string => typeof oid === 'string' && oid.length > 0) : [];
+/** The record's blob ids; one equal to `level` is `level`'s own string, so a converged page keeps one copy of its blob id. */
+const recordOids = (record: PageRow['record'], level?: string | null): string[] => {
+ const oids: string[] = [];
+ for (const oid of record ? [record.blob_oid, record.disk_blob_oid] : []) if (typeof oid === 'string' && oid.length > 0) oids.push(oid === level ? level : oid);
+ return oids;
+};
type Exec = Pick<BrainEngine, 'executeRaw'>;
@@@ -174,66 -123,27 +180,66 @@@ async function withRoundSnapshot<T>(eng
/**
* `I⋈P`: every page of the source with a recorded origin and the fields of its import record the classifier reads. Postgres
- * reads it as one set-based statement inside the round's snapshot (the planner hash-joins pages with their records; a
- * keyset with a per-row primary-key probe made the 61k read plan-bound, about 1.7 s of server time); PGLite reads bounded
- * keyset statements so writers interleave.
+ * plans it as one set-based statement inside the round's snapshot (the planner hash-joins pages with their records; a
+ * keyset with a per-row primary-key probe made the 61k read plan-bound, about 1.7 s of server time) and reads it through a
+ * cursor, `POSTGRES_FETCH_ROWS` at a time with the next fetch in flight: one result of 600k rows decoded in a single
+ * stretch of about a second and held every raw row at once. `cursor_tuple_fraction = 1` keeps the whole-result plan.
+ * PGLite reads bounded keyset statements so writers interleave.
*/
async function readPages(exec: Exec, kind: 'postgres' | 'pglite', sourceId: string, incarnation: string): Promise<{ rows: PageRow[]; statements: number }> {
+ // A record's fields usually repeat the page's (origin = source_path, disk = blob, revision = the page's), so those come back
+ // as a flag instead of a second copy of the string, and the parser as text parsed once per distinct value: a 600k-page
+ // read then holds about one string per field per page.
+ // The record's fields come out of its JSON once, in a subquery. On Postgres `OFFSET 0` keeps it unflattened, so the hash
+ // join builds over those few text columns instead of the whole record (600k: about 3.1 s of serial server time to 2.0 s);
+ // PGLite's keyset statements need it flattened, so each probes the record by primary key.
const select = `SELECT p.id, p.slug, p.source_path, p.knowledge_revision::text AS revision, p.deleted_at IS NOT NULL AS deleted,
- p.revision_write_request_id::text AS request_id,
- c.completed_keys IS NOT NULL AS has_record, c.completed_keys->0->>'origin' AS rec_origin, c.completed_keys->0->>'blob_oid' AS rec_blob_oid,
- c.completed_keys->0->>'disk_blob_oid' AS rec_disk_blob_oid, c.completed_keys->0->>'revision' AS rec_revision, c.completed_keys->0->'parser' AS rec_parser,
- c.completed_keys->0->>'full_episode' AS rec_full_episode, (c.completed_keys->0->'working')::text AS rec_working
- FROM pages p LEFT JOIN op_checkpoints c ON c.op=$2 AND c.fingerprint=$3||p.id::text
+ p.revision_write_request_id::text AS request_id, c.fingerprint IS NOT NULL AS has_record,
+ c.origin IS NOT DISTINCT FROM p.source_path AS rec_origin_same,
+ CASE WHEN c.origin IS DISTINCT FROM p.source_path THEN c.origin END AS rec_origin,
+ c.blob_oid AS rec_blob_oid,
+ c.disk_blob_oid IS NOT DISTINCT FROM c.blob_oid AS rec_disk_same,
+ CASE WHEN c.disk_blob_oid IS DISTINCT FROM c.blob_oid THEN c.disk_blob_oid END AS rec_disk_blob_oid,
+ c.revision IS NULL AS rec_revision_null,
+ NULLIF(c.revision, p.knowledge_revision::text) AS rec_revision,
- c.parser AS rec_parser, c.full_episode AS rec_full_episode
++ c.parser AS rec_parser, c.full_episode AS rec_full_episode, c.working AS rec_working
+ FROM pages p LEFT JOIN (SELECT fingerprint, completed_keys->0->>'origin' AS origin, completed_keys->0->>'blob_oid' AS blob_oid,
+ completed_keys->0->>'disk_blob_oid' AS disk_blob_oid, completed_keys->0->>'revision' AS revision,
- (completed_keys->0->'parser')::text AS parser, completed_keys->0->>'full_episode' AS full_episode
++ (completed_keys->0->'parser')::text AS parser, completed_keys->0->>'full_episode' AS full_episode, (completed_keys->0->'working')::text AS working
+ FROM op_checkpoints WHERE op=$2${kind === 'postgres' ? ' OFFSET 0' : ''}) c ON c.fingerprint=$3||p.id::text
WHERE p.source_id=$1 AND p.source_path IS NOT NULL`;
const params = [sourceId, SYNC_IMPORT_PROVENANCE_OP, `${sourceId}:${incarnation}:`];
- type Raw = Omit<PageRow, 'record' | 'arm1' | 'attested_hash'> & { has_record: boolean; rec_origin: string | null; rec_blob_oid: string | null;
- rec_disk_blob_oid: string | null; rec_revision: string | null; rec_parser: SyncImportProvenance['parser'] | null; rec_full_episode: string | null; rec_working: string | null };
+ type Raw = Omit<PageRow, 'record' | 'arm1' | 'attested_hash'> & { has_record: boolean; rec_origin_same: boolean; rec_origin: string | null; rec_blob_oid: string | null;
- rec_disk_same: boolean; rec_disk_blob_oid: string | null; rec_revision_null: boolean; rec_revision: string | null; rec_parser: string | null; rec_full_episode: string | null };
++ rec_disk_same: boolean; rec_disk_blob_oid: string | null; rec_revision_null: boolean; rec_revision: string | null; rec_parser: string | null; rec_full_episode: string | null; rec_working: string | null };
const rows: PageRow[] = [];
- const take = (page: Raw[]) => { for (const { has_record, rec_origin, rec_blob_oid, rec_disk_blob_oid, rec_revision, rec_parser, rec_full_episode, rec_working, ...row } of page) rows.push({ ...row, arm1: null, attested_hash: null,
- record: has_record ? { origin: rec_origin ?? '', blob_oid: rec_blob_oid ?? undefined, disk_blob_oid: rec_disk_blob_oid, revision: rec_revision ?? undefined, parser: rec_parser ?? undefined,
- full_episode: rec_full_episode, ...(rec_working === 'true' || rec_working === 'false' ? { working: rec_working === 'true' } : {}) } : null }); };
- if (kind === 'postgres') { take(await exec.executeRaw<Raw>(select, params)); return { rows, statements: 1 }; }
- let after = 0, statements = 0;
+ const parsers = new Map<string, SyncImportProvenance['parser'] | undefined>();
+ const parserOf = (text: string | null) => {
+ if (text === null) return undefined;
+ if (!parsers.has(text)) parsers.set(text, JSON.parse(text) ?? undefined);
+ return parsers.get(text);
+ };
+ const take = (page: Raw[]) => {
+ for (const raw of page) rows.push({ id: raw.id, slug: raw.slug, source_path: raw.source_path, revision: raw.revision, deleted: raw.deleted, request_id: raw.request_id,
+ arm1: null, attested_hash: null, record: raw.has_record ? { origin: raw.rec_origin_same ? raw.source_path : raw.rec_origin ?? '', blob_oid: raw.rec_blob_oid ?? undefined,
+ disk_blob_oid: raw.rec_disk_same ? raw.rec_blob_oid : raw.rec_disk_blob_oid, revision: raw.rec_revision_null ? undefined : raw.rec_revision ?? raw.revision,
- parser: parserOf(raw.rec_parser), full_episode: raw.rec_full_episode } : null });
++ parser: parserOf(raw.rec_parser), full_episode: raw.rec_full_episode, ...(raw.rec_working === 'true' || raw.rec_working === 'false' ? { working: raw.rec_working === 'true' } : {}) } : null });
+ };
+ let statements = 0;
+ if (kind === 'postgres') {
+ await exec.executeRaw('SET LOCAL cursor_tuple_fraction = 1');
+ await exec.executeRaw(`DECLARE sync_pass_pages NO SCROLL CURSOR FOR ${select}`, params);
+ statements += 2;
+ const fetch = () => { statements++; return exec.executeRaw<Raw>(`FETCH ${POSTGRES_FETCH_ROWS} FROM sync_pass_pages`); };
+ let next = fetch();
+ for (;;) {
+ const page = await next;
+ const more = page.length === POSTGRES_FETCH_ROWS;
+ if (more) next = fetch();
+ take(page);
+ if (!more) return { rows, statements };
+ }
+ }
+ let after = 0;
for (;;) {
statements++;
const page = await exec.executeRaw<Raw>(`${select} AND p.id>$4 ORDER BY p.id LIMIT ${PGLITE_KEYSET_ROWS}`, [...params, after]);
@@@ -380,14 -292,25 +388,26 @@@ export async function readShadowLevel(e
const includeHidden = [...new Set([...input.pass?.includeHidden ?? [], ...(settled(includeHiddenRead) ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))];
const keepDbPrefixes = (() => { try { return loadStorageConfig(root)?.keep_db ?? []; } catch { return []; } })();
const sourceRelative = (gitPath: string) => (scope ? gitPath.slice(scope.length + 1) : gitPath);
- // Pure per path and asked several times per path in a round, so each is computed once.
- const memo = <T>(fn: (path: string) => T) => { const seen = new Map<string, T>(); return (path: string): T => { let value = seen.get(path); if (value === undefined && !seen.has(path)) seen.set(path, value = fn(path)); return value as T; }; };
- const selected = memo((gitPath: string) => (!scope || gitPath.startsWith(`${scope}/`)) && !matchesAnyGlob(sourceRelative(gitPath), exclude)
- && !isReservedSkillBundlePath(slugMode === 'source-root' ? sourceRelative(gitPath) : gitPath) && isSyncable(gitPath, { strategy: strategy as 'markdown', includeHidden }));
+ // Eligibility of a path outside the cached tree (every path of the tree is eligible); origins validate per call: a
+ // 600k-path level keeps no per-path memo of either.
- const eligible = (gitPath: string) => (!scope || gitPath.startsWith(`${scope}/`)) && !matchesAnyGlob(sourceRelative(gitPath), exclude)
++ const selected = (gitPath: string) => (!scope || gitPath.startsWith(`${scope}/`)) && !matchesAnyGlob(sourceRelative(gitPath), exclude)
+ && !isReservedSkillBundlePath(slugMode === 'source-root' ? sourceRelative(gitPath) : gitPath) && isSyncable(gitPath, { strategy: strategy as 'markdown', includeHidden });
+ // #5032: a Windows-unstorable ':' path, and the other side of a rename touching one, take no part in the level.
+ let colonRefused = new Set<string>();
+ const eligible = (gitPath: string) => selected(gitPath) && !isWindowsColonTarget(gitPath) && !colonRefused.has(gitPath);
- const originPath = memo((path: string) => syncOriginPath(path));
- const originOf = memo((gitPath: string) => originPath(slugMode === 'source-root' && scope ? sourceRelative(gitPath) : gitPath));
- const gitPathOf = memo((origin: string) => { const o = originPath(origin); return slugMode === 'source-root' && scope ? `${scope}/${o}` : o; });
+ const originPath = (path: string) => syncOriginPath(path);
+ const originOf = (gitPath: string) => originPath(slugMode === 'source-root' && scope ? sourceRelative(gitPath) : gitPath);
+ const gitPathOf = (origin: string) => { const o = originPath(origin); return slugMode === 'source-root' && scope ? `${scope}/${o}` : o; };
+ // #5610: a source-root page whose stored origin is the legacy Git-root spelling (`<scope>/<origin>`) names `<origin>`, by
+ // the one rule discovery and preparation use (sameSyncOrigin; it refuses an origin that could name two files).
+ const originScope = { sourceId, root, scope, slugMode };
+ const pageOrigin = (row: Pick<PageRow, 'slug' | 'source_path'>): string => {
+ const recorded = originPath(row.source_path);
+ if (slugMode !== 'source-root' || !scope || !recorded.startsWith(`${scope}/`)) return recorded;
+ const stripped = recorded.slice(scope.length + 1);
+ return sameSyncOrigin(recorded, stripped, originScope, row.slug) ? stripped : recorded;
+ };
+ const step = loopYield();
t = timer();
const head = revParse(gitRoot, 'HEAD');
@@@ -398,29 -321,12 +418,31 @@@
const mode: 'committed' | 'working' = working ? 'working' : 'committed';
timings.rev_parse = t();
+ // A commit's tree never changes: the pass's next round at the same commit and selection reuses the eligible tree.
+ const treeKey = JSON.stringify([gitRoot, head, scope, slugMode, strategy, exclude, includeHidden]);
+ const cache = input.pass?.cache;
- const eligibleTree = async (): Promise<Map<string, GitTreeEntry>> => {
- if (cache?.tree?.key === treeKey) return cache.tree.tree;
++ // 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;
+ if (cache) cache.tree = undefined;
- const tree = new Map<string, GitTreeEntry>();
++ const tree = new Map<string, GitTreeEntry>(), colon: string[] = [];
+ for (const [path, entry] of await readTreeLevel(gitRoot, head, scope)) {
- if (eligible(path)) tree.set(path, entry);
++ if (isWindowsColonTarget(path)) colon.push(path);
++ else if (eligible(path)) tree.set(path, entry);
+ if (step.due()) await step.pause();
+ }
- if (cache) cache.tree = { key: treeKey, tree };
- return tree;
++ if (cache) cache.tree = { key: treeKey, tree, colon };
++ return { tree, colon };
+ };
// The Git level, the database snapshot and the holds are independent reads: they overlap, so each key times its own
// read and `reads` is the wall time of the three together.
const timed = async <T>(key: string, read: () => Promise<T>): Promise<T> => { const st = timer(); try { return await read(); } finally { timings[key] = st(); } };
t = timer();
const [gitLevel, snapshot, held] = await Promise.all([
- Promise.all([timed('T', () => readTreeLevel(gitRoot, head, scope)), timed('X', () => readIndexLevel(gitRoot)),
+ // Working mode reads the whole index (its paths join the domain); committed mode only where it differs from T, read
+ // after T so the two are never held whole together.
- Promise.all([timed('T', eligibleTree).then(async tree => ({ tree, indexDelta: mode === 'committed' ? await timed('X', () => readIndexDelta(gitRoot, tree)) : null })),
++ Promise.all([timed('T', eligibleTree).then(async ({ tree, colon }) => ({ tree, colon, indexDelta: mode === 'committed' ? await timed('X', () => readIndexDelta(gitRoot, tree)) : null })),
+ mode === 'working' ? timed('X', () => readIndexLevel(gitRoot)) : Promise.resolve(new Map<string, GitIndexEntry>()),
timed('U', async () => (mode === 'working' ? (await readUntracked(gitRoot, scope)).filter(eligible) : []))]),
// Issued together, the snapshot's statements pipeline on its one connection (PGLite runs them in turn).
timed('I⋈P', () => withRoundSnapshot(engine, async exec => {
@@@ -438,49 -344,32 +460,57 @@@
}),
]);
timings.reads = t();
- const [{ tree, indexDelta }, index, untrackedPaths] = gitLevel;
- const [treeAll, index, untrackedPaths] = gitLevel;
- const colon = await windowsColonRefusals(engine, { sourceId, gitRoot, from: context.source.last_commit, head, tree: treeAll, pages: snapshot.pages, selected,
++ const [{ tree: eligibleT, colon: colonTree, indexDelta }, index, untrackedPaths] = gitLevel;
++ const colon = await windowsColonRefusals(engine, { sourceId, gitRoot, from: context.source.last_commit, head, colonTree, pages: snapshot.pages, selected,
+ gitPathOf: origin => slugMode === 'source-root' && scope ? `${scope}/${origin}` : origin, sourcePathOf: gitPath => (slugMode === 'source-root' ? sourceRelative(gitPath) : gitPath) });
+ colonRefused = colon.paths;
- const tree = new Map<string, GitTreeEntry>([...treeAll].filter(([path]) => eligible(path)));
++ // A rename's other side refused with a ':' path leaves the level too (a copy: the cached tree is the commit's).
++ const tree = colonRefused.size ? new Map([...eligibleT].filter(([path]) => !colonRefused.has(path))) : eligibleT;
+ // Committed mode: the index entry of a tree path, its own where it differs from T, else T's at stage 0 (undefined: absent).
+ const indexed = (path: string): GitIndexEntry | undefined => {
+ if (!indexDelta) return index.get(path);
+ const delta = indexDelta.get(path);
+ if (delta !== undefined) return delta ?? undefined;
+ const committed = tree.get(path);
+ return committed ? { ...committed, stage: 0 } : undefined;
+ };
+ const inLevel = (path: string) => tree.has(path) || eligible(path);
const untracked = new Set(untrackedPaths);
- const { pages, open, markers, passRow, statements } = snapshot;
+ const { open, markers, passRow, statements } = snapshot;
const { holds, retry } = held;
const toGit = (holdPath: string) => (scope ? `${scope}/${holdPath}` : holdPath);
const holdByGitPath = new Map<string, GitHoldRecord>(holds.map(hold => [toGit(hold.path), hold]));
const moved = new Set(held.moved.map(toGit));
- // The page claiming each origin: the live one first, else the newest tombstone.
+ // The page claiming each origin: the live one first, else the newest tombstone. The rows leave the snapshot's result
+ // here (the driver's transaction keeps that object until its connection's next one), so only `byOrigin` holds them.
t = timer();
- const byOrigin = new Map<string, PageRow>();
++ // Every page recording an origin that more than one page records (#6517), so the level can name an ambiguous origin.
+ const byOrigin = new Map<string, PageRow>(), claimants = new Map<string, PageRow[]>();
- for (const row of pages) {
+ for (const row of snapshot.pages) {
- const key = gitPathOf(row.source_path);
++ if (step.due()) await step.pause();
+ if (isWindowsColonTarget(row.source_path)) continue;
+ const key = gitPathOf(pageOrigin(row));
- claimants.set(key, [...claimants.get(key) ?? [], row]);
const prior = byOrigin.get(key);
++ if (prior) { const all = claimants.get(key); if (all) all.push(row); else claimants.set(key, [prior, row]); }
if (!prior || (prior.deleted && !row.deleted) || (prior.deleted === row.deleted && Number(row.id) > Number(prior.id))) byOrigin.set(key, row);
- if (step.due()) await step.pause();
}
- const domain = new Set<string>([...tree.keys(), ...untracked, ...(mode === 'working' ? [...index.keys()].filter(eligible) : []), ...[...byOrigin.keys()].filter(eligible), ...[...markers.keys()].map(gitPathOf).filter(eligible)]);
+ snapshot.pages = [];
+ 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, row] of byOrigin) {
+ if (!inLevel(path)) continue;
+ domain.add(path);
+ if (!row.deleted) reconcilable++;
+ if (step.due()) await step.pause();
+ }
+ for (const origin of markers.keys()) { const path = gitPathOf(origin); if (inLevel(path)) domain.add(path); }
// Spellings of one origin that differ only by case or separator (the domain holds each path once).
const fold = (path: string) => path.replaceAll('\\', '/').toLowerCase();
- const spellings = new Map<string, string[]>();
+ const spellings = new Map<string, string | string[]>();
// Files at L count, 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).
for (const path of domain) {
@@@ -488,19 -376,18 +518,19 @@@
const live = byOrigin.get(path);
if (!tree.has(path) && !(mode === 'working' && (untracked.has(path) || index.has(path))) && !(live && !live.deleted && live.source_path.includes('\\'))) continue;
const folded = fold(path);
- spellings.set(folded, [...spellings.get(folded) ?? [], path]);
+ const prior = spellings.get(folded);
+ spellings.set(folded, prior === undefined ? path : typeof prior === 'string' ? [prior, path] : [...prior, path]);
}
// As discovery does, only spellings that name one page are twins: a live origin's page slug, else the slug its path names.
- const twins = new Set<string>();
+ const twins = new Set<string>(), twinGroups: string[][] = [];
for (const paths of spellings.values()) {
- if (paths.length < 2) continue;
+ if (typeof paths === 'string') continue;
const slugOf = (path: string) => { const live = byOrigin.get(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) for (const path of group) twins.add(path);
+ for (const group of bySlug.values()) if (group.length > 1) { twinGroups.push(group); for (const path of group) twins.add(path); }
}
- const reconcilable = [...byOrigin.entries()].filter(([path, row]) => !row.deleted && eligible(path)).length;
+ spellings.clear();
timings.domain = t();
// Working mode rehashes every path (the full round's unconditional rehash); committed mode probes candidates only.
@@@ -533,31 -416,43 +563,51 @@@
timings.A = t();
const baselineCommit = (context.source.last_commit && revParse(gitRoot, context.source.last_commit)) || null;
+ // The baseline tree, read once when a page needs it (no record revision; design §2.3) or the bootstrap's legacy walk does,
+ // so the classification itself never waits.
let baselineTree: Map<string, GitTreeEntry> | null | undefined;
- const baselineOf = async (path: string): Promise<string | null> => {
- if (!baselineCommit) return null;
- if (baselineTree === undefined) { const bt = timer(); baselineTree = await readTreeLevel(gitRoot, baselineCommit, scope).catch(() => null); timings.baseline = bt(); }
- return baselineTree?.get(path)?.oid ?? null;
+ const loadBaseline = async () => {
+ if (baselineTree !== undefined || !baselineCommit) return;
+ const bt = timer();
+ baselineTree = await readTreeLevel(gitRoot, baselineCommit, scope).catch(() => null);
+ timings.baseline = bt();
};
+ if (wantBaseline) await loadBaseline();
+ const baselineOf = (path: string): string | null => baselineTree?.get(path)?.oid ?? null;
+ // 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 claimed
+ // (#6865), so unless the claimed spellings still collide it settles as `legacy` and the others classify on their own.
+ const legacySpelling = new Set<string>();
+ for (const group of twinGroups) {
+ const unchanged: string[] = [];
+ for (const path of group) {
+ const live = byOrigin.get(path);
+ const level = levelOf(path, probes.get(path));
- if (!(live && !live.deleted) && level !== null && level === await baselineOf(path)) unchanged.push(path);
++ if ((live && !live.deleted) || level === null) continue;
++ await loadBaseline();
++ if (level === baselineOf(path)) unchanged.push(path);
+ }
+ if (group.length - unchanged.length > 1) continue;
+ for (const path of group) twins.delete(path);
+ for (const path of unchanged) legacySpelling.add(path);
+ }
const fp = (path: string) => syncImportParserFor(sourceRelative(path), pack?.identity ?? null);
- const stateOf = async (path: string, dirty: SyncPathState['dirty'], probe: { dp: string; rawOid: string | null; rawSha256: string | null } | undefined): Promise<{ state: SyncPathState; row?: PageRow; legacyPageless?: true }> => {
+ const stateOf = (path: string, dirty: SyncPathState['dirty'], probe: { dp: string; rawOid: string | null; rawSha256: string | null } | undefined): { state: SyncPathState; row?: PageRow; legacyPageless?: true } => {
const committed = tree.get(path) ?? null;
const row = byOrigin.get(path);
const level = levelOf(path, probe);
+ const origin = originOf(path);
// Presence decides only rows 4-6 (a level of absent); a committed path in T is not read here (Dp covers it).
- const presentNow = mode === 'working' ? level !== null : level === null ? readPresent(root, path, scope) : true;
const record = row?.record ?? null;
+ // #5459 (`keptWorkingTreePages`): a page whose import provenance is the pinned Git blob follows Git, so a lingering
+ // untracked copy of its file does not keep it.
+ const fromGit = record?.working === false || (record?.working === undefined && !!record?.blob_oid);
+ const presentNow = mode === 'working' ? level !== null : level === null ? !fromGit && readPresent(root, path, scope) : true;
- const recordBlobOids = recordOids(record);
+ const recordBlobOids = recordOids(record, level);
const attested = row && (row.arm1 || row.attested_hash) ? { hash: row.attested_hash ?? null, arm1: row.arm1 === true } : null;
const hold = holdByGitPath.get(path);
- const marker = markers.get(originOf(path)) ?? null;
+ const marker = markers.get(origin) ?? null;
const deletion = !row && !marker && level !== null ? legacyDeletions.get(path) : undefined;
const virtualMarker: SyncPathState['marker'] = deletion ? { kind: 'legacy', blobOids: [level!], deletion } : null;
const legacyPageless = deletion ? true as const : undefined;
@@@ -569,8 -464,8 +619,8 @@@
attested, levelSha256: probe?.rawSha256 ?? null,
published: !!attested?.hash && probe?.rawSha256 === attested.hash,
hold: hold ? { atLevel: holdAtLevel(hold, level, probe?.rawSha256 ?? null) && !moved.has(path), rescreenDue: holdRescreenDue(hold, retry.has(hold.path)), retried: retry.has(hold.path) } : null,
- marker: marker ?? virtualMarker, baseline: needsBaseline ? await baselineOf(path) : null,
+ marker: marker ?? virtualMarker, baseline: needsBaseline ? baselineOf(path) : null,
- spelling: twins.has(path),
+ spelling: legacySpelling.has(path) ? 'legacy' : twins.has(path),
episodeUnsatisfied: input.pass ? !!input.pass.episodeFullId && !!row && !row.deleted && record?.full_episode !== input.pass.episodeFullId
: input.full === true && !!row && !row.deleted,
fullObligation: input.pass ? !!input.pass.episodeFullId : input.full === true,
@@@ -603,27 -495,19 +653,30 @@@
t = timer();
const paths: ShadowPath[] = [];
- const candidates: string[] = [];
+ const candidates: string[] = [], candidateAt: number[] = [];
const settledBeforeDirtiness = new Set(['held', 'spelling', 'untracked', 'kept', 'delete', 'delete_drift', 'gone', 'deleted_same', 'deleted_edited', 'legacy_same', 'matched']);
- for (const path of [...domain].sort()) {
+ const shared = { mode, fullObligation: input.pass ? !!input.pass.episodeFullId : input.full === true };
+ for (const path of await sortYielding([...domain], step)) {
+ if (step.due()) await step.pause();
const probe = probes.get(path);
- const { state, row, legacyPageless } = await stateOf(path, mode === 'committed' && tree.has(path) ? 'clean' : null, probe);
- const result = classifySyncPath(state);
+ const { state, row, legacyPageless } = stateOf(path, mode === 'committed' && tree.has(path) ? 'clean' : null, probe);
+ const result = sharedResult(classifySyncPath(state));
// Rows 1-10 precede row 11 and `matched` settles either way, so only the rest are Dp candidates (design v3.2 §2.1).
- const staged = mode === 'committed' && tree.has(path) && (index.get(path)?.oid !== tree.get(path)!.oid || (index.get(path)?.stage ?? 0) !== 0);
- if (mode === 'committed' && tree.has(path) && (!settledBeforeDirtiness.has(result.cls) || staged)) candidates.push(path);
- const claimed = claimants.get(path) ?? [];
- const { ambiguous } = claimed.length > 1 ? selectOriginClaimant(claimed.map(page => ({ ...page, deleted_at: page.deleted ? true : null }))) : { ambiguous: null };
- const ambiguousOrigin = ambiguous ? { kind: ambiguous, slugs: claimed.filter(page => ambiguous === 'several_tombstones' || !page.deleted).map(page => page.slug) } : undefined;
- paths.push({ path, slug: row?.slug ?? null, pageId: row ? Number(row.id) : null, revision: row?.revision ?? null, state, result, ...(legacyPageless ? { legacyPageless } : {}), ...(ambiguousOrigin ? { ambiguousOrigin } : {}) });
+ const staged = mode === 'committed' && tree.has(path) && !!indexDelta?.has(path) && (indexed(path)?.oid !== tree.get(path)!.oid || (indexed(path)?.stage ?? 0) !== 0);
+ const revision = row?.revision ?? null;
++ const claimed = claimants.get(path);
++ const { ambiguous } = claimed ? selectOriginClaimant(claimed.map(page => ({ ...page, deleted_at: page.deleted ? true : null }))) : { ambiguous: null };
++ const ambiguousOrigin = ambiguous ? { kind: ambiguous, slugs: claimed!.filter(page => ambiguous === 'several_tombstones' || !page.deleted).map(page => page.slug) } : undefined;
+ if (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 (result.cls === 'matched' && !legacyPageless && MatchedPath.fits(state, revision, shared)) {
++ if (result.cls === 'matched' && !legacyPageless && !ambiguousOrigin && MatchedPath.fits(state, revision, shared)) {
+ paths.push(new MatchedPath(path, row!.slug, Number(row!.id), revision, result, state.tree, state.level!, state.dirty, state.record!.blobOids.length === 2, shared));
+ continue;
+ }
+ }
- paths.push({ path, slug: row?.slug ?? null, pageId: row ? Number(row.id) : null, revision, state, result, ...(legacyPageless ? { legacyPageless } : {}) });
++ paths.push({ path, slug: row?.slug ?? null, pageId: row ? Number(row.id) : null, revision, state, result, ...(legacyPageless ? { legacyPageless } : {}), ...(ambiguousOrigin ? { ambiguousOrigin } : {}) });
}
timings.classify = t();
if (candidates.length) {
@@@ -670,6 -552,29 +723,28 @@@
rescreenDue: holds.filter(hold => holdRescreenDue(hold, retry.has(hold.path))).map(hold => toGit(hold.path)), workingCache: hashed?.cache ?? null };
}
+ /**
+ * #5032, as discovery refuses them: on Windows a ':' path has no file. Each selected one gets a named refusal and leaves
+ * the level: a file at the target is skipped, a live page whose file left keeps its page, and a Git rename (last_commit to
+ * HEAD) touching one is refused on both sides, so the page keeps its identity until the change syncs from macOS or Linux.
+ * Off Windows, or with no ':' path, nothing is read.
+ */
-async function windowsColonRefusals(engine: BrainEngine, input: { sourceId: string; gitRoot: string; from: string | null; head: string; tree: Map<string, GitTreeEntry>;
++async function windowsColonRefusals(engine: BrainEngine, input: { sourceId: string; gitRoot: string; from: string | null; head: string; colonTree: string[];
+ pages: PageRow[]; selected: (gitPath: string) => boolean; gitPathOf: (origin: string) => string; sourcePathOf: (gitPath: string) => string }): Promise<{ refusals: Map<string, SyncFileRefusal>; paths: Set<string> }> {
+ const refusals = new Map<string, SyncFileRefusal>(), paths = new Set<string>();
- const colonTree = [...input.tree.keys()].filter(path => isWindowsColonTarget(path));
+ const colonPages = input.pages.filter(row => !row.deleted && isWindowsColonTarget(row.source_path)).map(row => input.gitPathOf(row.source_path.replaceAll('\\', '/')));
- if (!colonTree.length && !colonPages.length) return { refusals, paths };
++ if (!input.colonTree.length && !colonPages.length) return { refusals, paths };
+ const refuse = (path: string, message: string) => { paths.add(path); if (input.selected(path)) refusals.set(path, colonFileRefusal(input.sourceId, path, message)); };
+ const delta = input.from && input.from !== input.head ? await confirmedSyncDelta(engine, input.gitRoot, input.from, input.head, { sourceId: input.sourceId, sourcePathOf: input.sourcePathOf }) : null;
+ for (const rename of delta?.status === 'ok' ? delta.manifest.renamed : []) {
+ if (!isWindowsColonTarget(rename.from) && !isWindowsColonTarget(rename.to)) continue;
+ for (const path of [rename.from, rename.to]) refuse(path, COLON_REFUSAL_MESSAGES.rename(path, rename.from, rename.to));
+ }
- for (const path of colonTree) if (!paths.has(path)) refuse(path, COLON_REFUSAL_MESSAGES.import(path));
++ for (const path of input.colonTree) if (!paths.has(path)) refuse(path, COLON_REFUSAL_MESSAGES.import(path));
+ for (const path of colonPages) if (!paths.has(path)) refuse(path, COLON_REFUSAL_MESSAGES.delete(path));
+ return { refusals, paths };
+ }
+
/** `workingTreeFilePresent` (sync-discovery.ts) for a Git-root path: a file that exists, or one that cannot be read (fail closed). */
function readPresent(root: string, gitPath: string, scope: string): boolean {
const path = scope ? gitPath.slice(scope.length + 1) : gitPath;
diff --cc test/overwritten-edits-6712.test.ts
index 2e0da26947,62e43e0f25..99ea654610
--- a/test/overwritten-edits-6712.test.ts
+++ b/test/overwritten-edits-6712.test.ts
@@@ -1,13 -1,11 +1,12 @@@
/**
* #6712 follow-up: find and restore database edits an incremental managed sync silently overwrote.
*
- * The overwrite is seeded the way it happens on a released brain: a database-only `put_page` (`sync.write_through`
- * off), then a committed edit of the same file, then an incremental sync that publishes the file over the edit with no
- * hold. On a base without #6887 any page reproduces it. The live pass (#6712 PR 4b) holds a both-moved page whose import
- * record is missing or honest, so the seed rewrites the record to name the database edit's revision: a record that no
- * longer proves the page and that no classifier can tell from a true one. The pass then publishes the file over the
- * edit through a pass import (intent kind `managed_sync_import` with a `passId`), which is what the detector reads, and
- * these tests never depend on #6887.
+ * The overwrite is seeded as a released brain recorded it: a database-only `put_page` (`sync.write_through` off), a
+ * committed edit of the same file, and the history the cursor engine's incremental sync left when it published the file
+ * over the edit with no hold (its import receipt, the archived version, the import record and `last_commit`). #6712 PR 4b's
+ * pass no longer publishes over the edit, so the seed writes that history directly and these tests never depend on a
- * sync reproducing the bug; one row asserts the pass route's #6887 guarantee on the same scenario instead.
++ * sync reproducing the bug; one row asserts the pass route's #6887 guarantee on the same scenario instead, and one that
++ * the detector reads a pass import (intent kind `managed_sync_import` with a `passId`) that published over an edit.
*
* Protects:
* - a seeded overwrite is detected `high` (also after receipt compaction nulled every intent), and `repair
@@@ -134,6 -172,26 +173,47 @@@ for (const databaseUrl of process.env.D
expect((await doctor(engine)).status).toBe('ok');
}, { setup, databaseUrl }), 180_000);
+ test('#6887 on the pass route: a sync of the same scenario keeps the database edit and holds the file file_drift', () => managedBrain(async ({ engine, ctx, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ // The scenario the seed records, synced on #6712 PR 4b: a database-only edit, the page's import record gone (a page last
+ // imported before PR 0), and a committed edit of its file.
+ await engine.setConfig('sync.write_through', 'false');
+ await putPage(engine, ctx, 'notes/a', 'DBONLYMARKER the agent edit.');
+ await engine.setConfig('sync.write_through', 'true');
+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug='notes/a'");
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_IMPORT_PROVENANCE_OP, `default:${await incarnationOf(engine)}:${page!.id}`]);
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'The second committed body.'));
+ commit(root, 'edit notes/a');
+ const synced = await performManagedSync(engine, OPTS);
+ expect((synced.held ?? []).map(item => [item.path, item.code, item.slug])).toEqual([['notes/a.md', 'file_drift', 'notes/a']]);
+ expect(await bodyOf(engine, 'notes/a')).toContain('DBONLYMARKER the agent edit.');
+ expect(await bodyOf(engine, 'notes/a')).not.toContain('The second committed body.');
+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain('The second committed body.');
+ expect((await holdOf(engine, 'notes/a.md'))?.code).toBe('file_drift');
+ expect((await scanOverwrittenEdits(engine, 'default')).edits).toEqual([]);
+ }, { setup, databaseUrl }), 180_000);
+
++ test('the detector reads a pass import: one the pass published over a database edit (its record named the edit) is found', () => managedBrain(async ({ engine, ctx, root }) => {
++ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
++ // The pass holds a both-moved page whose record is honest (the row above), so the record is rewritten to name the
++ // database edit's revision: the pass then publishes the committed file over the edit through a pass import.
++ await engine.setConfig('sync.write_through', 'false');
++ await putPage(engine, ctx, 'notes/a', 'DBONLYMARKER the agent edit.');
++ await engine.setConfig('sync.write_through', 'true');
++ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug='notes/a'");
++ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys = jsonb_set(completed_keys, '{0,revision}', to_jsonb($3::text)) WHERE op=$1 AND fingerprint=$2",
++ [SYNC_IMPORT_PROVENANCE_OP, `default:${await incarnationOf(engine)}:${page!.id}`, await revisionOf(engine, 'notes/a')]);
++ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'The second committed body.'));
++ commit(root, 'edit notes/a');
++ await performManagedSync(engine, OPTS);
++ expect(await bodyOf(engine, 'notes/a')).toContain('The second committed body.');
++ const scan = await scanOverwrittenEdits(engine, 'default');
++ expect(scan.edits.map(edit => [edit.slug, edit.confidence, edit.db_operation])).toEqual([['notes/a', 'high', 'put_page']]);
++ const [imported] = await engine.executeRaw<{ kind: string; pass: boolean }>(
++ "SELECT intent->>'kind' AS kind, intent ? 'passId' AS pass FROM persistence_requests WHERE id::text=$1", [scan.edits[0]!.import_request_id]);
++ expect(imported).toEqual({ kind: 'managed_sync_import', pass: true });
++ }, { setup, databaseUrl }), 180_000);
++
test('a normal sync-written history is not flagged', () => managedBrain(async ({ engine, ctx, root }) => {
expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
await putPage(engine, ctx, 'notes/c', 'A write-through edit.');