Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6712 PR 4b lane A): classifier rulings b1, b2, b4, b5, b6 (Q3 = A)
garrytan6ed54afb1c27
diff --git a/src/core/persistence/sync-classify.ts b/src/core/persistence/sync-classify.tsindex d26f253228..99563e04c0 100644--- a/src/core/persistence/sync-classify.ts+++ b/src/core/persistence/sync-classify.ts@@ -46,14 +46,19 @@ export interface SyncPathState {published: boolean;/** An active hold at `p`: whether it is at level `L` in its own domain, re-screen due, or in the retry set. */hold: { atLevel: boolean; rescreenDue: boolean; retried: boolean } | null;- /** A deletion marker at the origin: `deleted` (with the blob ids it held) or `legacy` (the baseline blob). */- marker: { kind: 'deleted' | 'legacy'; blobOids: readonly string[] } | null;+ /**+ * A deletion marker at the origin: `deleted` (with the blob ids it held) or `legacy` (the baseline blob of a page deleted+ * before PR 4; `deletion` is the committed deleting request that proves it, and a legacy marker without one settles nothing).+ */+ marker: { kind: 'deleted' | 'legacy'; blobOids: readonly string[]; deletion?: string | null } | null;/** `T[p]` at the pass row's `baseline_commit` (null: absent there, or no baseline). */baseline: string | null;/** Another live origin differs from `p` only by case or separator. */spelling: boolean;/** An open full episode has not re-imported this page yet. */episodeUnsatisfied: boolean;+ /** `--full` or an open episode: every path, page-less ones included, owes a re-import (v3.1 §2.7). */+ fullObligation?: boolean;/** Under a `storage.keep_db` prefix, on a source that is not mirror-read-only. */keepDb: boolean;/** Open work on the page or path (a queued/running/recovering request, a pending Git effect). */@@ -66,6 +71,10 @@ export interface SyncClassified {/** The overlay: an unsettled class whose page has open work is `in_flight` (skipped this round, blocks the stamp). */inFlight: boolean;action: SyncPathAction;+ /** Who finishes this path (per path, not per class): a settled `dirty` path is `none`, an unsettled one `repair`; a re-screen-due hold is `owner`. */+ classAction: SyncClassAction;+ /** `held`: the hold is re-screen due (or no longer at its level), so the pass re-runs it. */+ rescreenDue?: true;/** `db_ahead`: `pending` (attested), `db_only` (moved off a recorded revision), `unproven` (no record revision). */sub?: 'pending' | 'db_only' | 'unproven';/** `drift` and `delete_drift`: the hold's side. `deleted_edited`: its state. */@@ -91,15 +100,32 @@ export function syncClassAction(cls: SyncClass | 'in_flight' | 'keep_db_pending'}}-/** Rows 1-19 of v3.2 §2.3, tried in order; the first match wins. */-function firstMatch(s: SyncPathState): Omit<SyncClassified, 'inFlight'> {+type Matched = Omit<SyncClassified, 'inFlight' | 'classAction'>;++/**+ * Rows 1-19 of v3.2 §2.3, tried in order; the first match wins. Garry's Q3 = A invariant: a settled path is matched, held or+ * in a class whose action says who finishes it. So a path with a hold row never settles in a later row (b2): unless the hold+ * is at its level and not re-screen due, the pass re-runs it (`held`, `rescreenDue`).+ */+function firstMatch(s: SyncPathState): Matched {+ if (s.hold && s.hold.atLevel && !s.hold.rescreenDue && !s.hold.retried) return { cls: 'held', settled: true, action: 'none' };+ const rest = afterHold(s);+ // The re-run is the import the hold refused, where an import is what the level would get anyway (`import`) or changes+ // nothing (`matched`). A level that needs another action (a drift side, a delete proof, a reparse) keeps that class, so+ // its guard still applies; one that settles any other way (database ahead, a deleted page, an uncommitted edit, a legacy+ // page) must not be imported over, so the hold stands.+ if (s.hold && s.level !== null && (rest.cls === 'matched' || rest.cls === 'import')) return { cls: 'held', settled: false, action: 'import', rescreenDue: true };+ if (s.hold && rest.settled) return { cls: 'held', settled: true, action: 'none' };+ return rest;+}++function afterHold(s: SyncPathState): Matched {const live = s.page?.live === true;const tombstone = s.page !== null && !s.page.live;const fileSame = s.level !== null && !!s.record && s.record.blobOids.includes(s.level);const dbSame = !!s.page && !!s.record && s.record.revision !== null && s.record.revision === s.page.revision;const proof = dbSame || s.attested !== null;const obligation = !s.record?.parserSame || !s.page?.originMatches || s.episodeUnsatisfied;- if (s.hold && s.hold.atLevel && !s.hold.rescreenDue && !s.hold.retried) return { cls: 'held', settled: true, action: 'none' };if (s.spelling) return { cls: 'spelling', settled: false, action: 'refuse' };if (s.mode === 'committed' && s.tree === null && !live) return { cls: 'untracked', settled: true, action: 'none' };if (live && s.level === null) {@@ -112,7 +138,7 @@ function firstMatch(s: SyncPathState): Omit<SyncClassified, 'inFlight'> {const deletedMarker = s.marker?.kind === 'deleted' ? s.marker : null;if ((tombstone && fileSame) || (deletedMarker && s.level !== null && deletedMarker.blobOids.includes(s.level))) return { cls: 'deleted_same', settled: true, action: 'none' };if ((tombstone || deletedMarker) && !s.published) return { cls: 'deleted_edited', settled: false, action: 'hold', side: 'deleted', state: tombstone ? 'tombstone_edited' : 'purged_differs' };- if (s.marker?.kind === 'legacy' && s.level !== null && s.marker.blobOids.includes(s.level)) return { cls: 'legacy_same', settled: true, action: 'none' };+ if (s.marker?.kind === 'legacy' && s.marker.deletion && !s.fullObligation && s.level !== null && s.marker.blobOids.includes(s.level)) return { cls: 'legacy_same', settled: true, action: 'none' };}if (s.mode === 'committed' && s.tree !== null && !CLEAN.has(s.dirty)) {const absorbed = (s.tree !== null && !!s.record && s.record.blobOids.includes(s.tree)) || (s.diskOid !== null && !!s.record && s.record.blobOids.includes(s.diskOid));@@ -141,7 +167,9 @@ function firstMatch(s: SyncPathState): Omit<SyncClassified, 'inFlight'> {/** The class of one path (v3.2 §2.3), with the open-work overlay applied. */export function classifySyncPath(s: SyncPathState): SyncClassified {const match = firstMatch(s);- return { ...match, inFlight: !match.settled && s.openWork };+ const inFlight = !match.settled && s.openWork;+ const classAction: SyncClassAction = inFlight || match.rescreenDue ? 'owner' : match.cls === 'dirty' ? (match.settled ? 'none' : 'repair') : syncClassAction(match.cls);+ return { ...match, inFlight, classAction };}/** Why a pass is not idle (v3.2 §2.2); empty = idle. A hold-only round runs when `rescreen_due_hold` is the only reason. */diff --git a/src/core/persistence/sync-convergence.ts b/src/core/persistence/sync-convergence.tsindex 6d31ad1083..38040152d6 100644--- a/src/core/persistence/sync-convergence.ts+++ b/src/core/persistence/sync-convergence.ts@@ -3,8 +3,12 @@* (`gbrain sync --dry-run --json`'s `convergence`), `sync status --detail`'s `convergence` and doctor's counts share.* Built from the shadow level (sync-pass.ts); every value is a prediction (`dry_run: true`), nothing is admitted.*- * - `classes`: `{<class>: {count, action}}` with `action ∈ none | owner | repair` (the glossary, sync-classify.ts- * `syncClassAction`); `in_flight`, `keep_db_pending` and `deletes_withheld` are classes here too.+ * - `classes`: `{<class>: {count, action, by_action}}` with `action ∈ none | owner | repair`. The action is per path+ * (sync-classify.ts `classAction`: a settled `dirty` path is `none`, an unsettled one `repair`), so `by_action` counts the+ * class's paths by it and `action` is the most demanding one present; `in_flight`, `keep_db_pending` and+ * `deletes_withheld` are classes here too.+ * - `legacy_twin_pairs`: the #6885 forked pairs `gbrain repair legacy-twins` would list (its read-only scan, bounded by+ * `LEGACY_TWINS_LIMIT`); null when this host cannot scan the source. Dry runs and status only, never an idle tick.* - `decisions`: the `file_drift` holds the pass would write, by side, after the read-only `sameContentAtOrigin` screen* of each drift path (a dry run only, at most `SCREEN_CAP` paths): equal content is a `same_content_noops` settle, an* unscreened path is counted in `screen_unknown`, never as a decision.@@ -40,7 +44,8 @@ export interface ConvergenceReceipt {mode: ShadowLevel['mode']; target: string; baseline_commit: string | null; converged_at: null; round: 1; full: boolean;candidates: number; settled: number; remaining: number; in_flight: number; eta_seconds: null; eta_reason: 'shadow';counts: Partial<Record<ConvergenceClassKey, number>>;- classes: Partial<Record<ConvergenceClassKey, { count: number; action: SyncClassAction }>>;+ classes: Partial<Record<ConvergenceClassKey, { count: number; action: SyncClassAction; by_action: Partial<Record<SyncClassAction, number>> }>>;+ legacy_twin_pairs: number | null;decisions: { both: number; unknown: number; deleted: number };same_content_noops: number; screen_unknown: number; screen_skipped?: 'not_a_dry_run' | 'screen_unavailable';would_hold: number;@@ -60,7 +65,7 @@ const redact = (path: string) => `sha256:${createHash('sha256').update(path).digfunction reasonOf(entry: ShadowPath): string {const { state, result } = entry;switch (result.cls) {- case 'held': return 'held at this level';+ case 'held': return result.rescreenDue ? 'held; re-screen due' : 'held at this level';case 'spelling': return 'origins differ only by case or separator';case 'delete': return 'file gone from the tree; the page has no database-only change';case 'delete_drift': return 'file gone from the tree; the page changed in the database';@@ -78,9 +83,9 @@ function reasonOf(entry: ShadowPath): string {}/** The receipt of one shadow level. `screen` runs only for dry runs; status and doctor pass `false`. */-export async function buildConvergenceReceipt(_engine: BrainEngine, level: ShadowLevel, opts: { redactPaths: boolean; sampleCap: number; screen: ConvergenceScreen | false }): Promise<ConvergenceReceipt> {+export async function buildConvergenceReceipt(engine: BrainEngine, level: ShadowLevel, opts: { redactPaths: boolean; sampleCap: number; screen: ConvergenceScreen | false }): Promise<ConvergenceReceipt> {const started = performance.now();- const keyed: Array<{ entry: ShadowPath; key: ConvergenceClassKey }> = [];+ const keyed: Array<{ entry: ShadowPath; key: ConvergenceClassKey; action: SyncClassAction }> = [];let keepDbSeen = 0;const deletes = level.paths.filter(entry => entry.result.cls === 'delete' && !entry.result.inFlight);const ratio = level.reconcilable ? deletes.length / level.reconcilable : 0;@@ -93,11 +98,18 @@ export async function buildConvergenceReceipt(_engine: BrainEngine, level: Shadoif (keepDbSeen > KEEP_DB_PASS_CAP) key = 'keep_db_pending';}if (key === 'delete' && verdict === 'withheld') key = 'deletes_withheld';- keyed.push({ entry, key });+ keyed.push({ entry, key, action: key === 'keep_db_pending' || key === 'deletes_withheld' ? syncClassAction(key) : entry.result.classAction });}const counts: ConvergenceReceipt['counts'] = {};- for (const { key } of keyed) counts[key] = (counts[key] ?? 0) + 1;- const classes: ConvergenceReceipt['classes'] = Object.fromEntries(Object.entries(counts).map(([key, count]) => [key, { count, action: syncClassAction(key as ConvergenceClassKey) }]));+ const classes: ConvergenceReceipt['classes'] = {};+ const RANK: Record<SyncClassAction, number> = { none: 0, owner: 1, repair: 2 };+ for (const { key, action } of keyed) {+ counts[key] = (counts[key] ?? 0) + 1;+ const entry = classes[key] ?? (classes[key] = { count: 0, action, by_action: {} });+ entry.count++;+ entry.by_action[action] = (entry.by_action[action] ?? 0) + 1;+ if (RANK[action] > RANK[entry.action]) entry.action = action;+ }const drift = keyed.filter(({ key }) => key === 'drift').map(({ entry }) => entry);let screened = new Map<string, 'same' | 'differs' | 'unknown'>();@@ -131,11 +143,11 @@ export async function buildConvergenceReceipt(_engine: BrainEngine, level: Shadoconst show = (path: string) => (opts.redactPaths ? redact(path) : path);const samples: ConvergenceReceipt['samples'] = {};- for (const { entry, key } of keyed) {+ for (const { entry, key, action } of keyed) {if (key === 'matched') continue;const list = samples[key] ?? (samples[key] = []);if (list.length >= opts.sampleCap) continue;- list.push({ path: show(entry.path), ...(opts.redactPaths || !entry.slug ? {} : { slug: entry.slug }), reason: reasonOf(entry), action: syncClassAction(key) });+ list.push({ path: show(entry.path), ...(opts.redactPaths || !entry.slug ? {} : { slug: entry.slug }), reason: reasonOf(entry), action });}const sortedDeletes = deletes.map(entry => entry.path).sort();const setHash = sortedDeletes.length ? sha256(sortedDeletes.join('\0')) : null;@@ -144,6 +156,10 @@ export async function buildConvergenceReceipt(_engine: BrainEngine, level: Shadoconst inFlight = counts.in_flight ?? 0;const candidates = level.paths.length - settled - inFlight;const keepDbAdmitted = Math.min(keepDbSeen, KEEP_DB_PASS_CAP);+ const twinsStarted = performance.now();+ const { scanLegacyTwins } = await import('../repair/legacy-twins.ts');+ const twins = await scanLegacyTwins(engine, level.sourceId).then(scan => scan.pairs.length + scan.decisions.length, () => null);+ const twinsMs = Math.round((performance.now() - twinsStarted) * 10) / 10;return {schema: 'convergence/1', dry_run: true, source_id: level.sourceId, pass_id: null, kind: level.kind, kind_blockers: level.kindBlockers, mode: level.mode,target: level.head, baseline_commit: level.baselineCommit, converged_at: null, round: 1, full: level.full,@@ -152,11 +168,11 @@ export async function buildConvergenceReceipt(_engine: BrainEngine, level: Shadowould_hold: decisions.both + decisions.unknown + decisions.deleted + unknown + dirtyHolds,keep_db_admitted: keepDbAdmitted, keep_db_pending: counts.keep_db_pending ?? 0, keep_db_authorized: keepDbAdmitted,db_ahead: dbAhead, db_ahead_by_prefix: dbAhead.by_prefix, full_skipped_db_ahead: fullSkipped,- legacy_unverified: counts.legacy_unverified ?? 0, legacy_pageless: level.paths.filter(entry => entry.legacyPageless && entry.result.cls === 'legacy_same').length,+ legacy_twin_pairs: twins, legacy_unverified: counts.legacy_unverified ?? 0, legacy_pageless: level.paths.filter(entry => entry.legacyPageless && entry.result.cls === 'legacy_same').length,deletes: { count: deletes.length, reconcilable: level.reconcilable, ratio: Math.round(ratio * 1000) / 1000, verdict, set_hash: setHash, samples: deleteSamples },deletes_withheld: verdict === 'withheld' ? { count: deletes.length, ratio: Math.round(ratio * 1000) / 1000, set_hash: setHash, samples: deleteSamples } : null,samples, settle_mismatch: [], episode: null, admission: null, last_full_at: null, redacted: opts.redactPaths,- duration_ms: Math.round(level.timings_ms.total ?? 0), timings_ms: { ...level.timings_ms, screen: screenMs, receipt: Math.round((performance.now() - started) * 10) / 10 },+ duration_ms: Math.round(level.timings_ms.total ?? 0), timings_ms: { ...level.timings_ms, screen: screenMs, legacy_twins: twinsMs, receipt: Math.round((performance.now() - started) * 10) / 10 },statements: level.statements,};}diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 4242748723..63b5544bfe 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -175,11 +175,11 @@ async function awaitInFlight(engine: BrainEngine, level: ShadowLevel, inFlight:}}-/** Design §2.7: the incarnation's first pass writes a `legacy` marker for each page-less path whose level is its baseline blob. */+/** Design §2.7 (b1): the incarnation's first pass writes a `legacy` marker, with its deletion proof, for each page-less path deleted before PR 4. */async function writeLegacyMarkers(engine: BrainEngine, level: ShadowLevel): Promise<number> {const rows = level.paths.filter(entry => entry.legacyPageless && entry.state.level).map(entry => ({fingerprint: originMarkerFingerprint(level.sourceId, level.incarnation, entryPaths(level, entry.path).sourcePath),- value: { source_id: level.sourceId, incarnation: level.incarnation, kind: 'legacy', blob_oids: [entry.state.level], at: new Date().toISOString() } }));+ value: { source_id: level.sourceId, incarnation: level.incarnation, kind: 'legacy', blob_oids: [entry.state.level], deletion: entry.state.marker?.deletion ?? null, at: new Date().toISOString() } }));if (!rows.length) return 0;await engine.transaction(async tx => {await assertDrainLease(tx, level.sourceId);diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 23e9e7aa79..842c9c1869 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -51,8 +51,9 @@ export interface PassLevelInput {includeHidden?: readonly string[];strategy?: string;/**- * The incarnation's first pass (no pass row yet): a page-less path whose level equals its baseline blob reads a virtual- * `legacy` marker, which the pass then writes (design §2.7). After it, only stored markers count.+ * The incarnation's first pass (no pass row yet): a page-less path whose level equals its baseline blob and whose slug a+ * committed deletion names reads a virtual `legacy` marker, which the pass then writes (design §2.7, b1). After it, only+ * stored markers count.*/bootstrap?: boolean;}@@ -64,7 +65,7 @@ const SYNC_WRITE_KINDS = ['managed_sync_import', 'managed_sync_delete'];/** 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 whose file is unchanged since the baseline: PR 4b's bootstrap writes it a `legacy` marker (`legacy_pageless`). */+ /** 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 }export interface ShadowLevel {@@ -177,15 +178,29 @@ async function readOpenWork(exec: Exec, sourceId: string, worktreeId: string): P}/** Deletion markers of the incarnation (a primary-key range read); none exist before PR 4b. */-async function readMarkers(exec: Exec, sourceId: string, incarnation: string): Promise<Map<string, { kind: 'deleted' | 'legacy'; blobOids: string[] }>> {+async function readMarkers(exec: Exec, sourceId: string, incarnation: string): Promise<Map<string, { kind: 'deleted' | 'legacy'; blobOids: string[]; deletion: string | null }>> {const prefix = `${sourceId}:${incarnation}:`;// `starts_with`, not a range: under a linguistic collation (en_US) a `< prefix || U+FFFF` bound matches nothing.- const rows = await exec.executeRaw<{ fingerprint: string; value: { kind?: string; blob_oids?: unknown } | null }>(+ const rows = await exec.executeRaw<{ fingerprint: string; value: { kind?: string; blob_oids?: unknown; deletion?: unknown } | null }>('SELECT fingerprint, completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND starts_with(fingerprint, $2)',[SYNC_ORIGIN_DELETED_OP, prefix]);return new Map(rows.map(row => [syncOriginPath(row.fingerprint.slice(prefix.length)), {kind: row.value?.kind === 'legacy' ? 'legacy' as const : 'deleted' as const,- blobOids: Array.isArray(row.value?.blob_oids) ? (row.value!.blob_oids as unknown[]).filter((oid): oid is string => typeof oid === 'string') : [] }]));+ blobOids: Array.isArray(row.value?.blob_oids) ? (row.value!.blob_oids as unknown[]).filter((oid): oid is string => typeof oid === 'string') : [],+ deletion: typeof row.value?.deletion === 'string' ? row.value.deletion : null }]));+}++/**+ * Design §2.7 with the parent's b1 ruling: a page-less path unchanged since the baseline is a page deleted before PR 4 only+ * when a committed deleting request of this incarnation names the slug its path imports to (the newest one is the proof). A+ * file sync refused before it ever had a page has none, so it imports.+ */+async function readLegacyDeletions(exec: Exec, sourceId: string, incarnation: string, slugs: string[]): Promise<Map<string, string>> {+ if (!slugs.length) return new Map();+ const rows = await exec.executeRaw<{ slug: string; id: string }>(`SELECT DISTINCT ON (slug) slug, id::text AS id FROM persistence_requests+ WHERE source_id=$1 AND source_incarnation=$2::uuid AND state='committed' AND slug=ANY($3::text[])+ AND (operation='delete_page' OR intent->>'kind'='managed_sync_delete') ORDER BY slug, sequence DESC`, [sourceId, incarnation, slugs]);+ return new Map(rows.map(row => [row.slug, row.id]));}/** The pass row of the incarnation (PR 4b writes it); null in PR 4a. */@@ -371,9 +386,9 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst 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;- let virtualMarker: SyncPathState['marker'] = null;- let legacyPageless: true | undefined;- if (!row && !marker && level !== null && (!input.pass || input.pass.bootstrap) && level === await baselineOf(path)) { virtualMarker = { kind: 'legacy', blobOids: [level] }; legacyPageless = true; }+ 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;const needsBaseline = row && !row.deleted && (record?.revision == null) && level !== null && !recordBlobOids.includes(level);const state: SyncPathState = {mode, tree: committed?.oid ?? null, level, present: presentNow, dirty, diskOid: probe?.rawOid ?? null,@@ -386,12 +401,31 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stspelling: (spellings.get(fold(path)) ?? 0) > 1,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,keepDb: !mirror && keepDbPrefixes.length > 0 && !!row && isKeepDbSlug(row.slug, keepDbPrefixes),openWork: !!row && open.pageIds.has(Number(row.id)) || open.origins.has(originOf(path)),};return { state, ...(row ? { row } : {}), ...(legacyPageless ? { legacyPageless } : {}) };};+ // Bootstrap (the incarnation's first pass; for a read-only level, no pass row yet): page-less paths at their baseline blob+ // whose slug a committed deletion names get a `legacy` marker (§2.7, b1).+ t = timer();+ const legacyDeletions = new Map<string, string>();+ if (baselineCommit && (input.pass ? input.pass.bootstrap === true : !passRow)) {+ const pageless: Array<{ path: string; slug: string }> = [];+ for (const path of domain) {+ if (byOrigin.has(path) || markers.has(originOf(path))) continue;+ const level = levelOf(path, probes.get(path));+ if (level === null || level !== await baselineOf(path)) continue;+ const slug = resolveSlugForPath(originOf(path));+ if (slug) pageless.push({ path, slug });+ }+ const bySlug = await readLegacyDeletions(engine, sourceId, incarnation, [...new Set(pageless.map(entry => entry.slug))]);+ for (const { path, slug } of pageless) { const id = bySlug.get(slug); if (id) legacyDeletions.set(path, id); }+ timings.legacy = t();+ }+t = timer();const paths: ShadowPath[] = [];const candidates: string[] = [];@@ -439,7 +473,6 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst kind = syncPassKind({ converged: null, head, parserFp: '', pack: pack?.identity ?? null, selectionFp: '', now: Date.now(), openEpisode: input.full === true, owedTail: false,retryRow: 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 });- void passRow;timings.total = total();return { sourceId, incarnation, root, gitRoot, scope, slugMode, mode, head, baselineCommit, full: input.full === true, kind: kind.kind, kindBlockers: kind.blockers,paths, reconcilable, timings_ms: timings, statements: statements + attestationStatements + 3, pack: pack?.identity ?? null,diff --git a/test/sync-classify-6712.test.ts b/test/sync-classify-6712.test.tsindex b979444046..cb78158ed4 100644--- a/test/sync-classify-6712.test.ts+++ b/test/sync-classify-6712.test.ts@@ -10,6 +10,10 @@* The reference model below is written from the state space (page state × level × dirtiness, then the* fileSame × dbSame × proof regions the totality argument names), not from the row list, so the ordered first-match* table in sync-classify.ts and this decision tree must agree on every input.+ *+ * #6712 PR 4b rulings (Garry's Q3 = A: a settled path is matched, held, or in an action-tagged class): a legacy marker+ * settles only with a recorded deletion and never under a full obligation (b1, b5); a path with a hold never settles in+ * another class (b2).*/import { describe, expect, test } from 'bun:test';import fc from 'fast-check';@@ -21,6 +25,15 @@ const CLEAN: ReadonlySet<SyncDirtiness | null> = new Set(['clean', 'clean_eol',/** The reference model: page state first, then level, then dirtiness, then the fileSame × dbSame × proof regions. */function reference(s: SyncPathState): SyncClass {if (s.hold && s.hold.atLevel && !s.hold.rescreenDue && !s.hold.retried) return 'held';+ const rest = referenceAfterHold(s);+ if (!s.hold) return rest;+ if (s.level !== null && (rest === 'matched' || rest === 'import')) return 'held';+ const live = s.page?.live === true;+ const dirtySettled = (s.tree !== null && !!s.record?.blobOids.includes(s.tree)) || (s.diskOid !== null && !!s.record?.blobOids.includes(s.diskOid)) || s.published || (s.dirty === 'deleted' && !live);+ return SETTLED.has(rest) || (rest === 'dirty' && dirtySettled) ? 'held' : rest;+}++function referenceAfterHold(s: SyncPathState): SyncClass {if (s.spelling) return 'spelling';const absorbed = new Set(s.record?.blobOids ?? []);const fileSame = s.level !== null && absorbed.has(s.level);@@ -36,7 +49,7 @@ function reference(s: SyncPathState): SyncClass {if ((state === 'tombstone' && fileSame) || markerHolds) return 'deleted_same';const deletedEvidence = state === 'tombstone' || s.marker?.kind === 'deleted';if (deletedEvidence && !s.published) return 'deleted_edited';- if (s.marker?.kind === 'legacy' && s.marker.blobOids.includes(s.level)) return 'legacy_same';+ if (s.marker?.kind === 'legacy' && s.marker.deletion && !s.fullObligation && s.marker.blobOids.includes(s.level)) return 'legacy_same';return dirtyCommitted ? dirtyClass() : 'import';}if (s.level === null && s.mode === 'committed' && s.present) return 'kept';@@ -68,7 +81,9 @@ const at = (patch: Partial<SyncPathState>) => ({ ...base, ...patch });describe('rows (v3.2 §2.3)', () => {const cases: Array<[string, Partial<SyncPathState>, SyncClass, boolean]> = [['1 held at its level', { hold: { atLevel: true, rescreenDue: false, retried: false }, level: 'B', tree: 'B' }, 'held', true],- ['1 a re-screen-due hold does not settle', { hold: { atLevel: true, rescreenDue: true, retried: false } }, 'matched', true],+ ['1 a re-screen-due hold does not settle: the pass re-runs it', { hold: { atLevel: true, rescreenDue: true, retried: false } }, 'held', false],+ ['1 a re-screen-due hold on a page-less file is held, not imported or legacy (b2)', { hold: { atLevel: true, rescreenDue: true, retried: false }, page: null, record: null }, 'held', false],+ ['1 a hold over a database-ahead level stands (never imported over)', { hold: { atLevel: false, rescreenDue: false, retried: false }, page: { live: true, revision: 'R2', originMatches: true } }, 'held', true],['2 spelling', { spelling: true }, 'spelling', false],['3 untracked: committed, not in T, no live page', { tree: null, level: null, page: null, record: null }, 'untracked', true],['4 kept: live, committed, absent from T, file present', { tree: null, level: null, present: true, dirty: null }, 'kept', true],@@ -79,7 +94,9 @@ describe('rows (v3.2 §2.3)', () => {['8 deleted_same (marker)', { page: null, record: null, marker: { kind: 'deleted', blobOids: ['A'] } }, 'deleted_same', true],['9 deleted_edited (tombstone)', { tree: 'B', level: 'B', page: { live: false, revision: 'R1', originMatches: true } }, 'deleted_edited', false],['9 deleted_edited (marker without OIDs, fail closed)', { page: null, record: null, marker: { kind: 'deleted', blobOids: [] } }, 'deleted_edited', false],- ['10 legacy_same', { page: null, record: null, marker: { kind: 'legacy', blobOids: ['A'] } }, 'legacy_same', true],+ ['10 legacy_same: a marker that records a deletion', { page: null, record: null, marker: { kind: 'legacy', blobOids: ['A'], deletion: 'req-1' } }, 'legacy_same', true],+ ['10 a baseline-equal legacy marker without a deletion settles nothing (b1)', { page: null, record: null, marker: { kind: 'legacy', blobOids: ['A'] } }, 'import', false],+ ['10 a legacy-marked path under a full obligation imports (b5)', { page: null, record: null, marker: { kind: 'legacy', blobOids: ['A'], deletion: 'req-1' }, fullObligation: true }, 'import', false],['10 a legacy-marked file that changed imports', { tree: 'B', level: 'B', page: null, record: null, marker: { kind: 'legacy', blobOids: ['A'] } }, 'import', false],['11 dirty, absorbed', { dirty: 'modified', diskOid: 'C' }, 'dirty', true],['11 dirty, not absorbed', { tree: 'B', level: 'B', dirty: 'modified', diskOid: 'C' }, 'dirty', false],@@ -150,9 +167,9 @@ const stateArb: fc.Arbitrary<SyncPathState> = fc.record({published: fc.boolean(),hold: fc.constantFrom<SyncPathState['hold']>(null, { atLevel: true, rescreenDue: false, retried: false }, { atLevel: false, rescreenDue: false, retried: false },{ atLevel: true, rescreenDue: true, retried: false }, { atLevel: true, rescreenDue: false, retried: true }),- marker: fc.constantFrom<SyncPathState['marker']>(null, { kind: 'deleted', blobOids: ['A'] }, { kind: 'deleted', blobOids: [] }, { kind: 'legacy', blobOids: ['A'] }),+ marker: fc.constantFrom<SyncPathState['marker']>(null, { kind: 'deleted', blobOids: ['A'] }, { kind: 'deleted', blobOids: [] }, { kind: 'legacy', blobOids: ['A'] }, { kind: 'legacy', blobOids: ['A'], deletion: 'req-1' }),baseline: fc.constantFrom<string | null>(null, 'A', 'B'),- spelling: fc.boolean(), episodeUnsatisfied: fc.boolean(), keepDb: fc.boolean(), openWork: fc.boolean(),+ spelling: fc.boolean(), episodeUnsatisfied: fc.boolean(), fullObligation: fc.boolean(), keepDb: fc.boolean(), openWork: fc.boolean(),}).map(({ working, ...raw }) => {// Consistency the pass guarantees: committed L = T[p] and Dp only for T paths; working L = the bytes, present ⇔ L.const level = raw.mode === 'committed' ? raw.tree : working;@@ -168,7 +185,8 @@ describe('P0 properties', () => {expect(a).toEqual(b);expect(SYNC_CLASSES).toContain(a.cls);expect(a.cls).toBe(reference(s));- if (a.cls !== 'dirty' && a.cls !== 'spelling') expect(a.settled).toBe(SETTLED.has(a.cls));+ if (a.cls !== 'dirty' && a.cls !== 'spelling' && a.cls !== 'held') expect(a.settled).toBe(SETTLED.has(a.cls));+ if (a.cls === 'held') expect(a.settled).toBe(!a.rescreenDue);expect(a.inFlight).toBe(!a.settled && s.openWork);}), { numRuns: 60_000, seed: 6712 });});@@ -181,11 +199,11 @@ describe('P0 properties', () => {for (const page of [null, { live: true, revision: 'R1', originMatches: true }, { live: true, revision: 'R2', originMatches: true }, { live: false, revision: 'R1', originMatches: true }])for (const record of [null, { blobOids: ['A'], revision: null, parserSame: true }, { blobOids: ['A'], revision: 'R1', parserSame: true }, { blobOids: ['A'], revision: 'R1', parserSame: false }])for (const attested of [null, { hash: sha('A'), arm1: false }, { hash: null, arm1: true }])- for (const marker of [null, { kind: 'deleted' as const, blobOids: ['A'] }, { kind: 'legacy' as const, blobOids: ['A'] }])- for (const published of [false, true]) for (const baseline of [null, 'A']) for (const keepDb of [false, true]) for (const episodeUnsatisfied of [false, true]) {+ for (const marker of [null, { kind: 'deleted' as const, blobOids: ['A'] }, { kind: 'legacy' as const, blobOids: ['A'] }, { kind: 'legacy' as const, blobOids: ['A'], deletion: 'req-1' }])+ for (const published of [false, true]) for (const baseline of [null, 'A']) for (const keepDb of [false, true]) for (const episodeUnsatisfied of [false, true]) for (const fullObligation of [false, true]) {const level = mode === 'committed' ? tree : working;const s: SyncPathState = { mode, tree, level, present, dirty, diskOid: 'C', page, record, attested, levelSha256: sha(level), published, hold: null, marker, baseline,- spelling: false, episodeUnsatisfied, keepDb, openWork: false };+ spelling: false, episodeUnsatisfied, fullObligation, keepDb, openWork: false };const got = classifySyncPath(s);if (got.cls !== reference(s)) throw new Error(`mismatch ${got.cls} vs ${reference(s)} for ${JSON.stringify(s)}`);n++;diff --git a/test/sync-pass-rulings-6712.test.ts b/test/sync-pass-rulings-6712.test.tsnew file mode 100644index 0000000000..011f16efa2--- /dev/null+++ b/test/sync-pass-rulings-6712.test.ts@@ -0,0 +1,144 @@+/**+ * #6712 PR 4b lane A: the parent's classifier rulings after the seeded shadow validation (Garry's Q3 = A invariant: a+ * settled path is matched, held, or in a class whose action says who finishes it).+ *+ * Protects:+ * - b1: a legacy marker settles a page-less path only when it records a deletion. A committed file with no page, no hold+ * and no committed deletion of its slug imports (on the bootstrap pass too), so a file refused before it ever had a page+ * (#6865, #6875 gate 2) is not reported synced; a page deleted before PR 4 (a committed delete_page of its slug) stays+ * `legacy_same`, and the bootstrap pass writes its marker with the deleting request as proof.+ * - b2: a path with a hold row never settles in another class: a re-screen-due hold (frontmatter_slug_conflict,+ * legacy_slug_conflict) is `held` with `rescreenDue` and the pass re-runs it; a hold over a level that must not be+ * imported over (database ahead) stands as a settled `held`.+ * - b4: the action is per path: a settled `dirty` path is `none`, an unsettled one `repair`; the receipt counts each+ * class by it (`by_action`).+ * - b5: under `--full` or an open episode, a legacy-marked path imports (v3.1 §2.7).+ * - b6: the convergence receipt counts #6885 legacy twin pairs (`legacy_twin_pairs`) with legacy-twins' read-only scan.+ *+ * Each test fails on capy/6712-pr4b (8cda2764b): there a baseline-equal legacy marker settles every page-less file, a+ * re-screen-due hold falls through to `matched` or `legacy_same`, results carry no `classAction`, the receipt has no+ * `by_action` or `legacy_twin_pairs`, and `--full` keeps legacy-marked paths `legacy_same`.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { classifySyncPath, type SyncPathState } from '../src/core/persistence/sync-classify.ts';+import { MANAGED_SYNC_PASS_OP, readShadowLevel, shadowConvergence, SYNC_ORIGIN_DELETED_OP } from '../src/core/persistence/sync-pass.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { waitFor } from './helpers/wait-for.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: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };++const base: SyncPathState = { mode: 'committed', tree: 'A', level: 'A', present: true, dirty: 'clean', diskOid: 'A',+ page: { live: true, revision: 'R1', originMatches: true }, record: { blobOids: ['A'], revision: 'R1', parserSame: true },+ attested: null, levelSha256: 'sha-A', published: false, hold: null, marker: null, baseline: 'A', spelling: false, episodeUnsatisfied: false, keepDb: false, openWork: false };+const at = (patch: Partial<SyncPathState>): SyncPathState => ({ ...base, ...patch });+const pageless = { page: null, record: null } as const;++/** Raw rows as an older gbrain left them: managed persistence off around the write. */+async function raw<T>(engine: BrainEngine, fn: () => Promise<T>): Promise<T> {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+}+async function deletePage(engine: BrainEngine, ctx: OperationContext, slug: string): Promise<string> {+ const requestId = randomUUID();+ const current = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug, request_id: requestId, expected_revision: current!.revision } });+ await waitFor(async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.state === 'committed',+ { timeoutMs: 20_000, label: `the delete_page of ${slug} commits` });+ return (await engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]!.id;+}+const classOf = async (engine: BrainEngine, path: string, full = false) => {+ const level = await readShadowLevel(engine, { sourceId: 'default', full });+ return level!.paths.find(entry => entry.path === path)?.result;+};+const liveSlugs = async (engine: BrainEngine) => (await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id='default' AND deleted_at IS NULL ORDER BY slug")).map(row => row.slug);++describe('#6712 PR 4b classifier rulings (pure)', () => {+ test('b1: a baseline-equal legacy marker without a recorded deletion settles nothing; the page-less file imports (owner)', () => {+ expect(classifySyncPath(at({ ...pageless, marker: { kind: 'legacy', blobOids: ['A'] } }))).toMatchObject({ cls: 'import', settled: false, action: 'import', classAction: 'owner' });+ expect(classifySyncPath(at({ ...pageless, marker: { kind: 'legacy', blobOids: ['A'], deletion: 'req-1' } }))).toMatchObject({ cls: 'legacy_same', settled: true, classAction: 'none' });+ expect(classifySyncPath(at({ ...pageless }))).toMatchObject({ cls: 'import', settled: false });+ });++ test('b2: a re-screen-due hold is held and re-run, never settled in a later row; a hold over a database-ahead level stands', () => {+ for (const hold of [{ atLevel: true, rescreenDue: true, retried: false }, { atLevel: true, rescreenDue: false, retried: true }, { atLevel: false, rescreenDue: false, retried: false }]) {+ expect(classifySyncPath(at({ hold }))).toMatchObject({ cls: 'held', settled: false, action: 'import', rescreenDue: true, classAction: 'owner' });+ expect(classifySyncPath(at({ ...pageless, hold }))).toMatchObject({ cls: 'held', settled: false, action: 'import', rescreenDue: true, classAction: 'owner' });+ }+ const dbAhead = at({ hold: { atLevel: true, rescreenDue: true, retried: false }, page: { live: true, revision: 'R2', originMatches: true } });+ expect(classifySyncPath(dbAhead)).toMatchObject({ cls: 'held', settled: true, action: 'none', classAction: 'repair' });+ const drift = at({ hold: { atLevel: true, rescreenDue: true, retried: false }, tree: 'B', level: 'B', page: { live: true, revision: 'R2', originMatches: true } });+ expect(classifySyncPath(drift)).toMatchObject({ cls: 'drift', settled: false, action: 'hold', side: 'both' });+ });++ test('b4: the action is per path: a settled dirty path is none, an unsettled one repair', () => {+ expect(classifySyncPath(at({ dirty: 'modified', diskOid: 'C' }))).toMatchObject({ cls: 'dirty', settled: true, classAction: 'none' });+ expect(classifySyncPath(at({ tree: 'B', level: 'B', dirty: 'staged', diskOid: 'C', published: true }))).toMatchObject({ cls: 'dirty', settled: true, classAction: 'none' });+ expect(classifySyncPath(at({ tree: 'B', level: 'B', dirty: 'modified', diskOid: 'C' }))).toMatchObject({ cls: 'dirty', settled: false, classAction: 'repair' });+ expect(classifySyncPath(at({ tree: 'B', level: 'B', openWork: true }))).toMatchObject({ cls: 'import', inFlight: true, classAction: 'owner' });+ });++ test('b5: under --full or an open episode a legacy-marked path imports', () => {+ expect(classifySyncPath(at({ ...pageless, marker: { kind: 'legacy', blobOids: ['A'], deletion: 'req-1' }, fullObligation: true }))).toMatchObject({ cls: 'import', settled: false, classAction: 'owner' });+ });+});++describe('#6712 PR 4b classifier rulings (pglite)', () => {+ 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}`, `The committed body of notes/${slug}.`));+ commit(root, 'notes');+ };++ test('b1/b5: a page-less file with no deletion imports on the bootstrap pass; a page deleted before PR 4 stays legacy_same (marker with proof) but imports under --full', () => managedBrain(async ({ engine, ctx }) => {+ await engine.setConfig('sync.write_through', 'false');+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ // An older gbrain's state: notes/b never got a page (refused once); notes/c was deleted by delete_page and its+ // tombstone purged before PR 4 (no deleted marker). No pass row and no markers yet.+ const deletion = await deletePage(engine, ctx, 'notes/c');+ await raw(engine, () => engine.executeRaw("DELETE FROM pages WHERE source_id='default' AND slug IN ('notes/b','notes/c')"));+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op IN ($1,$2)', [MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP]);++ expect(await classOf(engine, 'notes/b.md')).toMatchObject({ cls: 'import', settled: false, action: 'import' });+ expect(await classOf(engine, 'notes/c.md')).toMatchObject({ cls: 'legacy_same', settled: true });+ expect(await classOf(engine, 'notes/c.md', true)).toMatchObject({ cls: 'import', settled: false, action: 'import' });++ const result = await performManagedSync(engine, OPTS);+ expect(result.status).not.toBe('blocked_by_failures');+ expect(await liveSlugs(engine)).toEqual(['notes/a', 'notes/b']);+ const markers = await engine.executeRaw<{ fingerprint: string; value: { kind: string; deletion: string | null } }>(+ 'SELECT fingerprint, completed_keys->0 AS value FROM op_checkpoints WHERE op=$1', [SYNC_ORIGIN_DELETED_OP]);+ expect(markers.map(row => ({ path: row.fingerprint.split(':').pop(), kind: row.value.kind, deletion: row.value.deletion }))).toEqual([{ path: 'notes/c.md', kind: 'legacy', deletion }]);+ expect(await classOf(engine, 'notes/c.md')).toMatchObject({ cls: 'legacy_same', settled: true });+ }, { setup }), 180_000);++ test('b4/b6: the receipt counts dirty paths by their own action and the source\'s legacy twin pairs', () => managedBrain(async ({ engine, root }) => {+ writeFileSync(join(root, 'notes/Foo Bar.md'), note('Foo Bar', 'A synthetic observation about Foo Bar.')); commit(root, 'twin file');+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ // #6885: an older gbrain left a legacy page with no recorded origin at the unfolded slug, beside sync's twin.+ await raw(engine, () => engine.executeRaw(`INSERT INTO pages(source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash)+ SELECT source_id, 'notes/foo bar', type, title, compiled_truth, timeline, frontmatter, content_hash FROM pages WHERE source_id='default' AND slug='notes/foo-bar'`));+ // notes/a: a committed change whose working copy is back at the synced bytes (dirty, absorbed: settled, none);+ // notes/b: a committed change under a different uncommitted one (dirty, not absorbed: repair).+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A committed change of notes/a.'));+ writeFileSync(join(root, 'notes/b.md'), note('notes/b', 'A committed change of notes/b.'));+ commit(root, 'changes');+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'The committed body of notes/a.'));+ writeFileSync(join(root, 'notes/b.md'), note('notes/b', 'An uncommitted edit of notes/b.'));++ const receipt = await shadowConvergence(engine, { sourceId: 'default' });+ expect(receipt!.classes.dirty).toEqual({ count: 2, action: 'repair', by_action: { none: 1, repair: 1 } });+ expect(Object.fromEntries((receipt!.samples.dirty ?? []).map(sample => [sample.path, sample.action]))).toEqual({ 'notes/a.md': 'none', 'notes/b.md': 'repair' });+ expect(receipt!.legacy_twin_pairs).toBe(1);+ }, { setup }), 180_000);+});