Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): #6948 carry-over into the level pass: several live origin claimants hold that file origin_conflict (the rest syncs); legacy-twins merges through mergeTwinInto (#6712 PR 4b)

garrytan9407e91820f0
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 30e6b09606..279045f5b3 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -1003,6 +1003,7 @@ commands a person uses to decide it:
| `twin_slug_path_occupied` | A file sits at the twin's own slug path (`<twin-slug>.md`), which the twin's purge would compare or remove. Rename or remove it, sync, preview again. |
| `twin_has_withdrawals` | Claims were forgotten on the twin. Forget the same claims on the legacy page first, or retire the twin by hand. |
| `legacy_records_file_uri` | The legacy page records a file URI of its own; reconcile it first. |
+| `twin_evidence_conflicts` | The twin holds a link, relationship date, timeline entry or raw data row that the legacy page holds differently, so the merge would lose it. Make them agree, or retire the twin by hand, then preview again. |
The apply needs the user's consent: without `--yes` a terminal asks, and a
non-interactive run exits 3 (`ask_user`) with the consent payload and changes
@@ -1011,10 +1012,12 @@ the same in one transaction):
1. The legacy page records the file. It keeps its id, slug, links, timeline,
versions and aliases.
-2. The twin's links (both directions, without duplicating the legacy page's
- own; links between the two pages stay on the twin), timeline rows, slug
- aliases, facts other pages assert about it, raw data and attachments move
- to the legacy page. The twin's slug becomes an alias of the legacy page, so
+2. The twin merge `gbrain repair origin-twins` uses (#6948) moves the twin's
+ links in every role and their dated transitions (links between the two
+ pages stay on the twin), timeline rows, raw data, attachments, user-added
+ tags, slug aliases and facts other pages assert about it to the legacy page;
+ an exact duplicate of a legacy row is dropped, and a differing one makes the
+ pair a `twin_evidence_conflicts` decision. The twin's slug becomes an alias of the legacy page, so
`[[notes/foo-bar]]` and `gbrain get notes/foo-bar` keep resolving.
3. The twin's sync import record moves to the legacy page, so the next
`gbrain sync --source <id>` finds the file and the page unchanged: no new
@@ -1026,7 +1029,7 @@ the same in one transaction):
The legacy page keeps its slug: that is also the slug sync gives a never-forked
file whose legacy page it takes over (#6727), and the folded slug resolves to it
-through the alias. The twin's tags, chunks, versions and the facts and takes its
+through the alias. The twin's import-owned tags, chunks, versions and the facts and takes its
own body projects stay with the twin (the legacy page has the same ones, from
the same content). Restoring the twin brings back a page that records no file;
what moved stays on the legacy page.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 02f94dca1c..ad29e262f8 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -916,7 +916,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.296.0', text: 'After a parser or schema-pack change, a managed sync re-imports the pages whose file and page are unchanged but whose import record names the older parser (class `reparse`, which sync finishes by itself, with no hold), as the pre-pass prescreen did; the first pass after the change reads the whole source.' },
{ since: '0.60.296.0', text: 'An interrupted `gbrain sync --full` no longer ends with the run that started it: the next plain `gbrain sync` continues the re-import under the selection the `--full` started with, and there is no command to abandon it. A `--full` with a narrower selection (a CLI `--exclude`, say) finishes its own re-import and ends `synced` with status reason `selection_scoped`, without moving `last_commit`; the next plain sync then syncs the configured selection. A plain sync closes any open re-import, and stamps `chunker_version` only when the re-import covered the whole configured selection. To pause paid work, rely on the cost gate; to pause everything, set `sync.admission classify_only`.' },
{ since: '0.60.296.0', text: 'A managed sync pass that runs 4 rounds without the source settling (another writer keeps changing it) stops `not_converged`: outcome `resumable`, exit 0, everything it admitted stands, and `next` reruns the same sync. After 3 such passes in a row, `next` switches to a report: `gbrain sync status --source <id> --json` with `safe_to_loop: false` and `fix.next: report`, and a sync job ends needing an operator, so an agent loop stops instead of retrying. The count resets when a pass converges.' },
- { since: '0.60.296.0', text: 'New explicit repair `gbrain repair legacy-twins --source <id>` (#6885) merges the page pairs syncs before #6857 forked: a legacy page with no recorded file whose slug spells the file\'s name differently from today\'s slug rules, and the twin at today\'s slug that records the file. The read-only preview lists each pair (both pages\' ids, slugs and revisions, the file, whether the contents match) and lists as decisions, never merged, pairs whose contents differ, several legacy pages for one twin, and twins whose file is missing or drifted. `--apply --expect <hash> --yes` merges exactly the approved pairs: the legacy page takes over the file and keeps its id, links and history, the twin\'s links, timeline, aliases and the facts other pages state about it move over, its slug becomes an alias, and the twin is soft-deleted (its file untouched) and purged after 72 hours. It refuses off the owner host (`not_owner_host`), when the checkout cannot be read (`legacy_twins_storage_unknown`), and when the pairs are more than half of a source\'s file-backed pages (`legacy_twin_mass_merge_refused`, unless `GBRAIN_ALLOW_MASS_RECONCILE=1`). Nothing changes on upgrade; it runs only when named.' },
+ { since: '0.60.296.0', text: 'New explicit repair `gbrain repair legacy-twins --source <id>` (#6885) merges the page pairs syncs before #6857 forked: a legacy page with no recorded file whose slug spells the file\'s name differently from today\'s slug rules, and the twin at today\'s slug that records the file. The read-only preview lists each pair (both pages\' ids, slugs and revisions, the file, whether the contents match) and lists as decisions, never merged, pairs whose contents differ, several legacy pages for one twin, twins whose file is missing or drifted, and twins holding a link, relationship date, timeline entry or raw data row the legacy page holds differently (`twin_evidence_conflicts`). `--apply --expect <hash> --yes` merges exactly the approved pairs: the legacy page takes over the file and keeps its id, links and history, the twin\'s links and their dated transitions, timeline, raw data, user-added tags, aliases and the facts other pages state about it move over through the same twin merge as `gbrain repair origin-twins` (#6948), its slug becomes an alias, and the twin is soft-deleted (its file untouched) and purged after 72 hours. It refuses off the owner host (`not_owner_host`), when the checkout cannot be read (`legacy_twins_storage_unknown`), and when the pairs are more than half of a source\'s file-backed pages (`legacy_twin_mass_merge_refused`, unless `GBRAIN_ALLOW_MASS_RECONCILE=1`). Nothing changes on upgrade; it runs only when named.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.ts
index 4faa89009a..f2c2378360 100644
--- a/src/core/persistence/sync-pass-apply.ts
+++ b/src/core/persistence/sync-pass-apply.ts
@@ -10,7 +10,9 @@
* `sync-deletes-withheld` record (refreshed each pass) and settles those deletes `withheld`; imports and the stamp
* proceed and no per-page hold is written. A cleared trip deletes the record. Only `GBRAIN_ALLOW_MASS_RECONCILE=1` in the
* owner host's environment applies the deletes; a remote caller never does.
- * - **Holds** (rows 6, 9; §3.1 settle mismatch): `delete_drift` is a `file_drift` hold with side `deleted`, state
+ * - **Holds** (rows 6, 9; §3.1 settle mismatch; #6948): a path several live pages record as their origin is an
+ * `origin_conflict` hold of that path alone, with the shared verdict (origin-twins.ts) the sync-time heal acts on;
+ * `delete_drift` is a `file_drift` hold with side `deleted`, state
* `file_gone`; `deleted_edited` one with state `tombstone_edited` or `purged_differs` (purged holds carry the slug the
* marker names); a path that settled in three consecutive passes at one level without classifying settled is a
* `settle_mismatch` hold (`needs_human`). Each is written at level `L` under the drain lease, so it is `held` (row 1)
@@ -54,6 +56,10 @@ import type { SyncAdmission } from './sync-admission.ts';
import type { Action } from '../agent-output.ts';
import { slugUnderBoundPrefixes } from '../ops/context.ts';
import { syncOriginPath } from './sync-origin.ts';
+import { decideOriginTwins, readOriginClaimants, slugPathOccupied, type OriginConflict } from './origin-twins.ts';
+import { originConflictHold } from './sync-screen.ts';
+import { readSyncFile } from './sync-discovery.ts';
+import { frontmatterIdentity } from '../sync-rename-identity.ts';
/** Legacy pages the sweep screens per pass after the incarnation's first full round (design §2.7, [estimated]). */
export const PASS_LEGACY_SWEEP_MAX = 500;
@@ -66,7 +72,7 @@ const LEVEL_BLOB_MAX_BYTES = 8 * 1024 * 1024;
/** What a pass applied across its rounds (kept in memory; its counts go into the pass row's telemetry). */
export interface PassApplyState {
markersRetired: number;
- holds: { file_gone: number; tombstone_edited: number; purged_differs: number; settle_mismatch: number };
+ holds: { file_gone: number; tombstone_edited: number; purged_differs: number; settle_mismatch: number; origin_conflict: number };
settleMismatch: string[];
adopted: number;
swept: { screened: number; recorded: number };
@@ -78,6 +84,8 @@ export interface PassApplyState {
keepDb: { admitted: number; pending: number; paused: number; refused: Record<string, number> };
/** keep_db paths admitted in this pass: never admitted twice. */
keepDbTaken: string[];
+ /** #6948: paths this pass held `origin_conflict` (re-screen due, so a later round reads them again): held once per pass. */
+ originHeld: Set<string>;
matchedSlugs: Set<string>;
/** The newest round's classes and summary (design §9), after this module settled what it finished. */
classes: Record<string, { count: number; action: SyncClassAction }>;
@@ -90,8 +98,8 @@ export interface PassApplyState {
}
export function newPassApplyState(): PassApplyState {
- return { markersRetired: 0, holds: { file_gone: 0, tombstone_edited: 0, purged_differs: 0, settle_mismatch: 0 }, settleMismatch: [], adopted: 0,
- swept: { screened: 0, recorded: 0 }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], matchedSlugs: new Set(), classes: {}, summary: null, recorded: new Set() };
+ return { markersRetired: 0, holds: { file_gone: 0, tombstone_edited: 0, purged_differs: 0, settle_mismatch: 0, origin_conflict: 0 }, settleMismatch: [], adopted: 0,
+ swept: { screened: 0, recorded: 0 }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], originHeld: new Set(), matchedSlugs: new Set(), classes: {}, summary: null, recorded: new Set() };
}
export interface PassApplyInput {
@@ -138,7 +146,12 @@ export async function applyPassRound(engine: BrainEngine, level: ShadowLevel, in
}
}
await applyDeleteValve(engine, level, input, state);
- if (input.remote) { summarizeRound(level, state); return; }
+ if (input.remote) {
+ // #6948: a remote pass writes no hold, so a path several live pages claim is left as it is for the owner's pass to hold.
+ for (const entry of level.paths) if (entry.ambiguousOrigin?.kind === 'several_live' && !entry.result.settled && !entry.result.inFlight) settleAs(entry, { settled: true, action: 'none', classAction: 'repair' });
+ summarizeRound(level, state);
+ return;
+ }
await writePassHolds(engine, level, input, state);
await adoptRecords(engine, level, state);
await sweepLegacy(engine, level, input, state);
@@ -229,7 +242,7 @@ async function applyDeleteValve(engine: BrainEngine, level: ShadowLevel, input:
/** Rows 6 and 9 and the settle-mismatch streak (§3.1): holds at level `L`, written under the drain lease. */
async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {
- type Pending = { entry: ShadowPath; code: GitHoldCode; message: string; slug: string | null; meta: Partial<GitHoldMeta>; kind: keyof PassApplyState['holds'] };
+ type Pending = { entry: ShadowPath; code: GitHoldCode; message: string; slug: string | null; meta: Partial<GitHoldMeta>; kind: keyof PassApplyState['holds']; pageId?: null };
const pending: Pending[] = [];
// A held rename's origin waits for its destination's hold (#5988), whatever its page did meanwhile.
const heldRenameOrigins = new Set(level.heldRenames.map(held => syncOriginPath(held.rename.sourcePath)));
@@ -237,8 +250,17 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Pa
for (const entry of level.paths) {
if (step.due()) await step.pause();
const r = entry.result;
- if (r.settled || r.inFlight) continue;
- const { path } = passEntryPaths(level, entry.path);
+ if (r.inFlight) continue;
+ const { path, sourcePath } = passEntryPaths(level, entry.path);
+ // A level pass sees every claimed path, so a settled one (an unchanged file) is held too: the heal then resolves it.
+ if (entry.ambiguousOrigin?.kind === 'several_live' && r.cls !== 'spelling' && r.cls !== 'held') {
+ if (state.originHeld.has(entry.path)) { settleAs(entry, { cls: 'held', settled: true, action: 'none', classAction: 'repair' }); continue; }
+ const held = originConflictHold({ path, sourcePath, working: level.mode === 'working', action: entry.state.level === null ? 'delete' : 'import',
+ originConflict: await passOriginConflict(engine, level, entry, path, sourcePath) });
+ pending.push({ entry, code: 'origin_conflict', slug: held.slug, kind: 'origin_conflict', meta: held.meta, message: held.message, pageId: null });
+ continue;
+ }
+ if (r.settled) continue;
const streak = input.obligations.mismatch?.[entry.path];
if (streak && streak.streak >= SETTLE_MISMATCH_STREAK && streak.level === entry.state.level) {
pending.push({ entry, code: 'settle_mismatch', slug: entry.slug, kind: 'settle_mismatch', meta: { mismatch_streak: streak.streak },
@@ -262,7 +284,8 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Pa
await assertDrainLease(tx, level.sourceId);
for (const hold of pending) {
const { path, sourcePath } = passEntryPaths(level, hold.entry.path);
- await writeGitHold(tx, { source_id: level.sourceId, incarnation: level.incarnation, path, source_path: sourcePath, slug: hold.slug, page_id: hold.entry.state.page?.live ? hold.entry.pageId : null,
+ await writeGitHold(tx, { source_id: level.sourceId, incarnation: level.incarnation, path, source_path: sourcePath, slug: hold.slug,
+ page_id: hold.pageId !== undefined ? hold.pageId : hold.entry.state.page?.live ? hold.entry.pageId : null,
code: hold.code, message: hold.message, upstream_version: hold.entry.state.levelSha256, observed_at: input.observedAt, run_id: input.passId, mode: 'managed',
meta: { recovery_version: RECOVERY_VERSION, ...levelMeta(level, hold.entry), ...hold.meta } });
}
@@ -270,10 +293,28 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Pa
for (const hold of pending) {
state.holds[hold.kind]++;
if (hold.code === 'settle_mismatch') state.settleMismatch.push(passEntryPaths(level, hold.entry.path).path);
+ if (hold.code === 'origin_conflict') state.originHeld.add(hold.entry.path);
settleAs(hold.entry, { cls: 'held', settled: true, action: 'none', classAction: 'repair' });
}
}
+/**
+ * #6948, as discovery's `originConflictOf`: the live claimants' verdict inputs and the shared verdict, with the file's
+ * explicit id read at the path's level `L` (undefined, so the verdict holds `file_unreadable`, when there is no file or
+ * it cannot be read).
+ */
+async function passOriginConflict(engine: BrainEngine, level: ShadowLevel, entry: ShadowPath, path: string, sourcePath: string): Promise<OriginConflict> {
+ const claimants = await readOriginClaimants(engine, level.sourceId, entry.ambiguousOrigin!.ids);
+ const oid = entry.state.level;
+ const bytes = oid === null ? null : level.mode === 'working' ? readSyncFile(level.root, path)
+ : (await readBlobs(level.gitRoot, [oid], LEVEL_BLOB_MAX_BYTES).catch(() => new Map<string, Buffer>())).get(oid) ?? null;
+ let fileId: string | null | undefined;
+ try { fileId = bytes === null ? undefined : frontmatterIdentity(bytes.toString('utf8')).id; } catch { fileId = undefined; }
+ const verdict = decideOriginTwins({ sourcePath, claimants, fileId, slugPathOccupied: slugPathOccupied(level) });
+ return { canonical: verdict.canonical, claimants: verdict.verdict === 'resolve' ? [verdict.survivor, ...verdict.twins] : verdict.claimants,
+ ...(verdict.verdict === 'hold' ? { reason: verdict.reason } : {}) };
+}
+
/** One page's import-record write of a round: the record to store and the page revision it must still be at. */
interface RecordWrite { pageId: number; revision: string; record: Omit<SyncImportProvenance, 'recorded_at' | 'validated'> }
@@ -417,7 +458,7 @@ export async function finishPassApply(engine: BrainEngine, sourceId: string, sta
export function passApplyCounts(state: PassApplyState): Record<string, number> {
const refused = Object.values(state.keepDb.refused).reduce((a, b) => a + b, 0);
return { markers_retired: state.markersRetired, holds_file_gone: state.holds.file_gone, holds_tombstone_edited: state.holds.tombstone_edited,
- holds_purged_differs: state.holds.purged_differs, holds_settle_mismatch: state.holds.settle_mismatch, adopted: state.adopted, legacy_swept: state.swept.screened,
+ holds_purged_differs: state.holds.purged_differs, holds_settle_mismatch: state.holds.settle_mismatch, holds_origin_conflict: state.holds.origin_conflict, adopted: state.adopted, legacy_swept: state.swept.screened,
legacy_recorded: state.swept.recorded, deletes_withheld: state.withheldCount, keep_db_admitted: state.keepDb.admitted, keep_db_pending: state.keepDb.pending,
paused_keep_db: state.keepDb.paused, keep_db_refused: refused };
}
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index ee8c6ab90a..5fe3641e62 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -764,8 +764,9 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
await writeLegacyMarkers(engine, level);
value.obligations.legacy_markers_at = new Date().toISOString();
}
- // #6517, as discovery refuses a claim: several pages record the origin of a path this pass would act on (before any hold).
- const ambiguous = level.paths.find(entry => entry.ambiguousOrigin && !entry.result.settled && !entry.result.inFlight && entry.result.cls !== 'spelling');
+ // #6517, as discovery refuses a claim: several tombstones record the origin of a path this pass would act on (before any
+ // hold). Several live pages hold that path alone (#6948 `origin_conflict`, sync-pass-apply.ts) and the rest syncs.
+ const ambiguous = level.paths.find(entry => entry.ambiguousOrigin?.kind === 'several_tombstones' && !entry.result.settled && !entry.result.inFlight && entry.result.cls !== 'spelling');
if (ambiguous) {
await save('blocked', 'page_identity_changed');
throw ambiguousOriginRefusal(sourceId, entryPaths(level, ambiguous.path).sourcePath, ambiguous.ambiguousOrigin!.slugs.map(slug => ({ slug })), ambiguous.ambiguousOrigin!.kind);
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index 0e4cf62acf..1f62e8a829 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -129,7 +129,7 @@ export interface ShadowPath { path: string; slug: string | null; pageId: number
/** 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;
/** #6517 (`selectOriginClaimant`): several live pages, or no live page and several tombstones, record this origin. */
- ambiguousOrigin?: { kind: 'several_live' | 'several_tombstones'; slugs: string[] } }
+ ambiguousOrigin?: { kind: 'several_live' | 'several_tombstones'; slugs: string[]; ids: number[] } }
/**
* A `matched` path whose state is the converged one (a live page whose record proves the level's blob and revision, nothing
@@ -780,7 +780,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const revision = at === undefined ? null : pages.revision[at] ?? null;
const claimed = claimants.get(path);
const { ambiguous } = claimed ? selectOriginClaimant(claimed.map(page => ({ deleted_at: pages.deleted(page) ? true : null }))) : { ambiguous: null };
- const ambiguousOrigin = ambiguous ? { kind: ambiguous, slugs: claimed!.filter(page => ambiguous === 'several_tombstones' || !pages.deleted(page)).map(page => pages.slug[page]!) } : undefined;
+ const named = ambiguous ? claimed!.filter(page => ambiguous === 'several_tombstones' || !pages.deleted(page)) : [], ambiguousOrigin = ambiguous ? { kind: ambiguous, slugs: named.map(page => pages.slug[page]!), ids: named.map(page => Number(pages.id[page])) } : 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).
diff --git a/src/core/repair/legacy-twins.ts b/src/core/repair/legacy-twins.ts
index dcde8ead59..9991871303 100644
--- a/src/core/repair/legacy-twins.ts
+++ b/src/core/repair/legacy-twins.ts
@@ -10,22 +10,26 @@
* every pair with both ids, slugs and revisions, the recorded path and whether the two pages hold the same content,
* bound to the canonical owner it ran under; a pair it does not merge on its own is listed as a decision with the
* commands a person uses to decide (two-sided content, several legacy candidates for one twin, a twin whose file is
- * missing or differs from it, withdrawn claims on the twin, a file at the twin's slug path). `--apply --expect <hash>
+ * missing or differs from it, withdrawn claims on the twin, a file at the twin's slug path, a twin row the merge would
+ * lose). `--apply --expect <hash>
* --yes` merges exactly the approved pairs, one coordinated write per pair (`managed_maintenance_merge_legacy_twin`
* on the twin, holding the legacy page's key too; an unmanaged brain does the same in one maintenance transaction):
*
* 1. the legacy page records the file as its origin, keeping its id, slug, links, timeline, versions and aliases;
- * 2. the twin's links (both directions and as origin, deduplicated against the legacy page's own; links between
- * the pair stay), timeline rows, slug aliases, facts other pages assert about it, raw data rows the legacy page
- * lacks and file attachments move to the legacy page, and the twin's slug becomes a `slug_aliases` row for it;
+ * 2. the shared twin merge (#6948, persistence/twin-merge.ts `mergeTwinInto`, the one `gbrain repair origin-twins`
+ * uses) moves the twin's links in every role and their dated transitions (links between the pair stay), timeline
+ * rows, raw data, file attachments, user-added tags, slug aliases and facts other pages assert about it to the
+ * legacy page, and the twin's slug becomes a `slug_aliases` row for it. A twin row that would land on a legacy row
+ * saying something different is a decision (`twin_evidence_conflicts`), never dropped;
* 3. the twin's sync import record moves to the legacy page with its post-write revision, so the next sync sees
* the file and the page both unchanged (the classifier's `matched`) instead of an unproven drift;
* 4. the twin is soft-deleted as a shared origin: the file is untouched. Its tombstone forgets the file
- * (`source_path` and `source_uri` cleared), so the 72 h retention purge removes it database-only instead of
+ * (`source_path` and `source_uri` cleared, marked `origin_twin` so a restore writes no file), so the 72 h
+ * retention purge removes it database-only instead of
* refusing it forever as a page whose file another live page records; a pair whose twin slug path holds a
* file is a decision, so that purge has no file to compare or remove.
*
- * Kept on the twin (they go with it when it is purged, and come back if it is restored): its tags, chunks and
+ * Kept on the twin (they go with it when it is purged, and come back if it is restored): its import-owned tags, chunks and
* embeddings, page versions, the facts and takes its own body projects and its derived per-page state. Both pages
* hold the same content, so the legacy page already has the same projections.
*
@@ -46,8 +50,6 @@ import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import { isOpPageSlug } from '../ops/context.ts';
import { resolveSourceLocalFilePath } from '../markdown.ts';
import { slugifyPath } from '../sync.ts';
-import { noteBelief } from '../belief/ledger.ts';
-import { recordRenameAlias } from '../page-state/rename-alias.ts';
import { authorizeWrite } from '../persistence/authority.ts';
import { prepareCoreGuard } from '../persistence/core-guard.ts';
import { existingLocalHostId } from '../persistence/identity.ts';
@@ -56,7 +58,8 @@ import { maintenanceTransaction } from '../persistence/attribution.ts';
import { liveFileDrift } from '../persistence/drift-conflicts.ts';
import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
-import { readSyncImportProvenance, recordSyncImportProvenance, SYNC_IMPORT_PROVENANCE_OP } from '../persistence/sync-holds.ts';
+import { readSyncImportProvenance, recordSyncImportProvenance } from '../persistence/sync-holds.ts';
+import { mergeTwinInto, twinMergeConflicts } from '../persistence/twin-merge.ts';
import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';
import type { GhostOwner } from '../ghost-pages.ts';
import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
@@ -73,7 +76,7 @@ const DOCS = 'docs/guides/repair.md#legacy-twins';
export interface TwinPage { page_id: number; slug: string; revision: string }
export interface LegacyTwinPair { source_id: string; legacy: TwinPage; twin: TwinPage; path: string; import_record: boolean }
export type TwinDecisionReason = 'content_differs' | 'several_legacy' | 'file_missing' | 'file_drift' | 'file_unverified' | 'twin_slug_path_occupied'
- | 'legacy_records_file_uri' | 'twin_has_withdrawals' | 'twin_slug_unwritable';
+ | 'legacy_records_file_uri' | 'twin_has_withdrawals' | 'twin_slug_unwritable' | 'twin_evidence_conflicts';
export interface LegacyTwinDecision { source_id: string; reason: TwinDecisionReason; twin: TwinPage; legacy: TwinPage[]; path: string; commands: string[] }
interface ApprovedPair extends LegacyTwinPair { owner: GhostOwner; selection: string[] }
@@ -150,6 +153,7 @@ function decisionCommands(sourceId: string, reason: TwinDecisionReason, twin: Tw
case 'legacy_records_file_uri': return [...show, `The legacy page records a file URI of its own; decide which file it belongs to with gbrain sources reconcile ${sourceId} '${legacy[0]!.slug}' --brain host --preview.`];
case 'twin_has_withdrawals': return [...show, `Claims were forgotten on ${twin.slug}: forget the same claims on '${legacy[0]!.slug}' (gbrain forget), or soft-delete the twin by hand, then run ${preview}.`];
case 'twin_slug_unwritable': return show;
+ case 'twin_evidence_conflicts': return [...show, `The twin holds a link, relationship date, timeline entry or raw data row the legacy page holds differently, which the merge would lose: make them agree (or soft-delete the twin by hand), then run ${preview}.`];
}
}
@@ -166,7 +170,8 @@ async function pairVerdict(engine: BrainEngine, root: string, sourceId: string,
if (drift.reason !== 'agrees') return 'file_unverified';
if (existsSync(resolveSourceLocalFilePath(root, undefined, twin.slug, undefined) ?? join(root, `${twin.slug}.md`))) return 'twin_slug_path_occupied';
const [withdrawn] = await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1 AND subject=$2 LIMIT 1', [sourceId, twin.slug]);
- return withdrawn ? 'twin_has_withdrawals' : null;
+ if (withdrawn) return 'twin_has_withdrawals';
+ return (await twinMergeConflicts(engine, Number(only.id), Number(twin.id))).length ? 'twin_evidence_conflicts' : null;
}
export interface LegacyTwinScan { owner: GhostOwner; root: string; pairs: LegacyTwinPair[]; decisions: LegacyTwinDecision[]; file_backed: number; inspected: number; truncated: boolean }
@@ -342,53 +347,22 @@ async function pairLocked(tx: BrainEngine, pair: LegacyTwinPair): Promise<string
}
/**
- * The merge itself, inside the caller's transaction with both page keys held: the legacy page records the file,
- * the twin's references move to it, the twin is soft-deleted with its recorded origin cleared, and the twin's import
+ * The merge itself, inside the caller's transaction with both page keys held: the shared twin merge (#6948,
+ * persistence/twin-merge.ts) moves what other pages and the twin's own rows say about the twin to the legacy page and
+ * soft-deletes the twin with its recorded origin cleared; then the legacy page records the file and the twin's import
* record follows with the legacy page's post-write revision.
*/
async function applyTwinMerge(tx: BrainEngine, pair: LegacyTwinPair, incarnation: string): Promise<Record<string, unknown>> {
const { source_id: sourceId, legacy, twin } = pair;
const [twinRow] = await tx.executeRaw<{ source_uri: string | null }>('SELECT source_uri FROM pages WHERE id=$1', [twin.page_id]);
const record = await readSyncImportProvenance(tx, sourceId, incarnation, twin.page_id);
- await tx.executeRaw('UPDATE pages SET source_path=NULL, source_uri=NULL WHERE id=$1', [twin.page_id]);
+ const merged = await mergeTwinInto(tx, { sourceId, incarnation, survivor: legacy, twin });
await tx.executeRaw('UPDATE pages SET source_path=$2, source_uri=COALESCE(source_uri, $3) WHERE id=$1', [legacy.page_id, pair.path, twinRow?.source_uri ?? null]);
- const linkIds = (await tx.executeRaw<{ id: number }>('SELECT id FROM links WHERE (from_page_id=$1 AND to_page_id<>$2) OR (to_page_id=$1 AND from_page_id<>$2)',
- [twin.page_id, legacy.page_id])).map(row => Number(row.id));
- const statements: Array<[string, unknown[]]> = [
- [`DELETE FROM links s WHERE s.from_page_id=$1 AND s.to_page_id<>$2 AND EXISTS (SELECT 1 FROM links o WHERE o.from_page_id=$2 AND o.to_page_id=s.to_page_id
- AND o.link_type=s.link_type AND o.link_source IS NOT DISTINCT FROM s.link_source AND o.origin_page_id IS NOT DISTINCT FROM s.origin_page_id)`, [twin.page_id, legacy.page_id]],
- ['UPDATE links SET from_page_id=$2 WHERE from_page_id=$1 AND to_page_id<>$2', [twin.page_id, legacy.page_id]],
- [`DELETE FROM links s WHERE s.to_page_id=$1 AND s.from_page_id<>$2 AND EXISTS (SELECT 1 FROM links o WHERE o.to_page_id=$2 AND o.from_page_id=s.from_page_id
- AND o.link_type=s.link_type AND o.link_source IS NOT DISTINCT FROM s.link_source AND o.origin_page_id IS NOT DISTINCT FROM s.origin_page_id)`, [twin.page_id, legacy.page_id]],
- ['UPDATE links SET to_page_id=$2 WHERE to_page_id=$1 AND from_page_id<>$2', [twin.page_id, legacy.page_id]],
- [`DELETE FROM links s WHERE s.origin_page_id=$1 AND s.from_page_id<>$1 AND s.to_page_id<>$1 AND EXISTS (SELECT 1 FROM links o WHERE o.origin_page_id=$2
- AND o.from_page_id=s.from_page_id AND o.to_page_id=s.to_page_id AND o.link_type=s.link_type AND o.link_source IS NOT DISTINCT FROM s.link_source)`, [twin.page_id, legacy.page_id]],
- ['UPDATE links SET origin_page_id=$2 WHERE origin_page_id=$1 AND from_page_id<>$1 AND to_page_id<>$1', [twin.page_id, legacy.page_id]],
- [`DELETE FROM timeline_entries s WHERE s.page_id=$1 AND EXISTS (SELECT 1 FROM timeline_entries o WHERE o.page_id=$2 AND o.date=s.date
- AND md5(o.summary)=md5(s.summary) AND o.source=s.source)`, [twin.page_id, legacy.page_id]],
- ['UPDATE timeline_entries SET page_id=$2 WHERE page_id=$1', [twin.page_id, legacy.page_id]],
- ['DELETE FROM timeline_entries s WHERE s.event_page_id=$1 AND EXISTS (SELECT 1 FROM timeline_entries o WHERE o.event_page_id=$2 AND o.date=s.date)', [twin.page_id, legacy.page_id]],
- ['UPDATE timeline_entries SET event_page_id=$2 WHERE event_page_id=$1', [twin.page_id, legacy.page_id]],
- ['UPDATE raw_data r SET page_id=$2 WHERE r.page_id=$1 AND NOT EXISTS (SELECT 1 FROM raw_data o WHERE o.page_id=$2 AND o.source=r.source)', [twin.page_id, legacy.page_id]],
- ['UPDATE files SET page_id=$2, page_slug=$3 WHERE page_id=$1', [twin.page_id, legacy.page_id, legacy.slug]],
- [`UPDATE page_aliases a SET slug=$3 WHERE a.source_id=$1 AND a.slug=$2
- AND NOT EXISTS (SELECT 1 FROM page_aliases o WHERE o.source_id=$1 AND o.slug=$3 AND o.alias_norm=a.alias_norm AND o.origin=a.origin)`, [sourceId, twin.slug, legacy.slug]],
- ];
- for (const [sql, params] of statements) await tx.executeRaw(sql, params);
- const factIds = (await tx.executeRaw<{ id: number }>(`UPDATE facts SET entity_slug=$3 WHERE source_id=$1 AND entity_slug=$2
- AND source_markdown_slug IS DISTINCT FROM $2 RETURNING id`, [sourceId, twin.slug, legacy.slug])).map(row => Number(row.id));
- await recordRenameAlias(tx, sourceId, twin.slug, legacy.slug);
- const movedLinks = (await tx.executeRaw<{ id: number }>('SELECT id FROM links WHERE id=ANY($1::int[]) AND (from_page_id=$2 OR to_page_id=$2)', [linkIds, legacy.page_id])).map(row => Number(row.id));
- noteBelief({ kind: 'transferred', fromSlug: twin.slug, table: 'links', ids: movedLinks });
- noteBelief({ kind: 'transferred', fromSlug: twin.slug, table: 'facts', ids: factIds });
- await tx.createVersion(twin.slug, { sourceId });
- await tx.softDeletePage(twin.slug, { sourceId });
- await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_IMPORT_PROVENANCE_OP, `${sourceId}:${incarnation}:${twin.page_id}`]);
if (record) {
const [now] = await tx.executeRaw<{ revision: string }>('SELECT knowledge_revision::text AS revision FROM pages WHERE id=$1', [legacy.page_id]);
await recordSyncImportProvenance(tx, { ...record, page_id: legacy.page_id, revision: now!.revision });
}
- return { status: 'merged', legacy_slug: legacy.slug, twin_slug: twin.slug, source_id: sourceId, links_moved: movedLinks.length, facts_moved: factIds.length,
+ return { status: 'merged', legacy_slug: legacy.slug, twin_slug: twin.slug, source_id: sourceId, links_moved: merged.links_moved.length, facts_moved: merged.facts_moved.length,
import_record_moved: record !== null };
}
diff --git a/test/e2e/sync-pass-origin-twins-6948-postgres.test.ts b/test/e2e/sync-pass-origin-twins-6948-postgres.test.ts
new file mode 100644
index 0000000000..d043b410a5
--- /dev/null
+++ b/test/e2e/sync-pass-origin-twins-6948-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-pass-origin-twins-6948.test.ts'));
diff --git a/test/page-row-deleters-guard-6712.test.ts b/test/page-row-deleters-guard-6712.test.ts
index fbe3bfebb3..c0243e27d9 100644
--- a/test/page-row-deleters-guard-6712.test.ts
+++ b/test/page-row-deleters-guard-6712.test.ts
@@ -12,8 +12,13 @@ import { join } from 'node:path';
const ROOT = join(import.meta.dir, '..');
const PATTERN = /\.deletePages?\(|DELETE FROM pages\b/g;
+/** #6900: the segment-aware page delete (page-purge.ts); a call to it is a page-row deletion, its definition is not. */
+const SEGMENTS = /(?<!function )\bdeletePageWithSegments\(/g;
-/** The deleters a managed Git source reaches: each delete must follow `writeOriginDeletedMarker(` within three lines. */
+/**
+ * The deleters a managed Git source reaches (calls to `deletePageWithSegments` since #6900): each must follow
+ * `writeOriginDeletedMarker(` within three lines.
+ */
const MARKED: Record<string, number> = {
'src/core/persistence/page-purge.ts': 1, // delete_page --purge, manual and retention (the coordinator's purge transaction)
'src/core/belief/purge-mirror.ts': 1, // the restore-time purge replay
@@ -24,6 +29,7 @@ const REVIEWED: Record<string, { count: number; why: string }> = {
'src/core/pglite-engine.ts': { count: 2, why: 'engine methods forwarding to engine-sql/pages.ts' },
'src/core/postgres-engine.ts': { count: 2, why: 'engine methods forwarding to engine-sql/pages.ts' },
'src/core/engine-sql/pages.ts': { count: 3, why: 'the engine implementations themselves' },
+ 'src/core/persistence/page-purge.ts': { count: 1, why: 'inside deletePageWithSegments, whose callers are MARKED' },
'src/core/engine.ts': { count: 1, why: 'doc comment of deletePages' },
'src/core/engine-constants.ts': { count: 1, why: 'doc comment of the batch bound' },
'src/core/bootstrap/verify.ts': { count: 1, why: 'unmanaged brains only; a managed brain removes its probe pages through delete_page --purge' },
@@ -35,26 +41,28 @@ const REVIEWED: Record<string, { count: number; why: string }> = {
'src/core/google/sweep-shared.ts': { count: 1, why: 'Google connector sweep' },
};
-function scan(): Map<string, number[]> {
+function scan(pattern: RegExp): Map<string, number[]> {
const found = new Map<string, number[]>();
for (const path of new Bun.Glob('src/**/*.ts').scanSync({ cwd: ROOT })) {
const lines = readFileSync(join(ROOT, path), 'utf8').split('\n');
- lines.forEach((line, i) => { for (const _ of line.matchAll(PATTERN)) found.set(path, [...(found.get(path) ?? []), i]); });
+ lines.forEach((line, i) => { for (const _ of line.matchAll(pattern)) found.set(path, [...(found.get(path) ?? []), i]); });
}
return found;
}
test('no page-row deleter outside the reviewed callers', () => {
- const found = scan();
- const unexpected = [...found].filter(([path, hits]) => (MARKED[path] ?? REVIEWED[path]?.count) !== hits.length)
- .map(([path, hits]) => `${path}: ${hits.length} page-row deletion(s); expected ${MARKED[path] ?? REVIEWED[path]?.count ?? 0}`);
+ const raw = scan(PATTERN), segments = scan(SEGMENTS);
+ const unexpected = [...[...raw].filter(([path, hits]) => REVIEWED[path]?.count !== hits.length)
+ .map(([path, hits]) => `${path}: ${hits.length} page-row deletion(s); expected ${REVIEWED[path]?.count ?? 0}`),
+ ...[...segments].filter(([path, hits]) => MARKED[path] !== hits.length)
+ .map(([path, hits]) => `${path}: ${hits.length} deletePageWithSegments call(s); expected ${MARKED[path] ?? 0}`)];
expect(unexpected).toEqual([]);
- const stale = [...Object.keys(MARKED), ...Object.keys(REVIEWED)].filter(path => !found.has(path));
+ const stale = [...Object.keys(MARKED).filter(path => !segments.has(path)), ...Object.keys(REVIEWED).filter(path => !raw.has(path))];
expect(stale).toEqual([]);
});
test('the deleters a managed Git source reaches write the deletion marker right before the delete', () => {
- const found = scan();
+ const found = scan(SEGMENTS);
for (const [path, count] of Object.entries(MARKED)) {
const lines = readFileSync(join(ROOT, path), 'utf8').split('\n');
const hits = found.get(path) ?? [];
diff --git a/test/repair-legacy-twins-6885.test.ts b/test/repair-legacy-twins-6885.test.ts
index d81c65b850..731163b4d6 100644
--- a/test/repair-legacy-twins-6885.test.ts
+++ b/test/repair-legacy-twins-6885.test.ts
@@ -218,6 +218,19 @@ for (const backend of testBackends()) describe(`#6885 repair legacy-twins (${bac
expect((await pageRow(f.sourceId, f.ids.legacy))!.source_path).toBeNull();
}, { legacyBody: 'An edited legacy body that the file never had.\n' }), 180_000);
+ test('#6948 merge: a twin link the legacy page holds with other words is a decision twin_evidence_conflicts, never merged or dropped', () => fixture(async f => {
+ await raw(() => engine.executeRaw("INSERT INTO links(from_page_id, to_page_id, link_type, link_source, context) VALUES ($1,$3,'cites','manual','the twin says this'), ($2,$3,'cites','manual','the legacy page says that')",
+ [f.ids.twin, f.ids.legacy, f.ids.second]));
+ const preview = await repair(f.sourceId);
+ expect(preview.affected).toBe(0);
+ expect(preview.listing).toEqual([{ item: `${f.sourceId}:${TWIN}`, class: 'decision:twin_evidence_conflicts', detail: expect.stringContaining(`legacy ${LEGACY}`) }]);
+ const applied = await repair(f.sourceId, { apply: true, expect: preview.preview_hash });
+ expect(applied).toMatchObject({ applied: 0, failed: [] });
+ expect(await pageRow(f.sourceId, f.ids.twin)).toMatchObject({ deleted: false, source_path: FILE });
+ expect((await engine.executeRaw<{ context: string }>("SELECT context FROM links WHERE link_type='cites' AND to_page_id=$1 ORDER BY context", [f.ids.second])).map(row => row.context))
+ .toEqual(['the legacy page says that', 'the twin says this']);
+ }), 180_000);
+
test('a page that moved after the preview is skipped changed_since_preview; nothing changes', () => fixture(async f => {
const preview = await repair(f.sourceId);
expect(preview.affected).toBe(1);
diff --git a/test/sync-origin-markers-6712.test.ts b/test/sync-origin-markers-6712.test.ts
index 97625fb658..28ac60f38c 100644
--- a/test/sync-origin-markers-6712.test.ts
+++ b/test/sync-origin-markers-6712.test.ts
@@ -22,6 +22,7 @@ import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { replayPurges, type PurgeMirrorLine } from '../src/core/belief/purge-mirror.ts';
import { SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { dropOriginIndex } from './helpers/origin-index.ts';
import { managedBrain } from './helpers/managed-brain.ts';
const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
@@ -105,8 +106,12 @@ describe('#6712 PR 4b deletion markers (pglite)', () => {
expect((await purge(ctx, engine, 'notes/eta')).state).toBe('committed');
expect((await markers(engine)).has('notes/eta.md')).toBe(true);
// A live twin records delta's file; delta is soft-deleted (shared_origin) and purged: the twin owns the origin.
- await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.putPage('notes/delta-twin', { type: 'note', title: 'Twin', compiled_truth: 'A twin recording delta.',
- timeline: '', frontmatter: {}, content_hash: 'twin-delta', source_path: 'notes/delta.md' }, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));
+ // #6948: no writer records a held origin on a second page any more, so the twin's origin is set as legacy data left it.
+ await dropOriginIndex(engine);
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {
+ await tx.putPage('notes/delta-twin', { type: 'note', title: 'Twin', compiled_truth: 'A twin recording delta.', timeline: '', frontmatter: {}, content_hash: 'twin-delta' }, { sourceId: 'default' });
+ await tx.executeRaw("UPDATE pages SET source_path='notes/delta.md' WHERE source_id='default' AND slug='notes/delta-twin'");
+ }, TEST_WRITE_ATTRIBUTION));
expect((await mutate(ctx, engine, 'notes/delta')).state).toBe('committed');
expect((await purge(ctx, engine, 'notes/delta')).state).toBe('committed');
expect(await pageRow(engine, 'notes/delta')).toBeNull();
diff --git a/test/sync-pass-origin-twins-6948.test.ts b/test/sync-pass-origin-twins-6948.test.ts
new file mode 100644
index 0000000000..5c83fe2e63
--- /dev/null
+++ b/test/sync-pass-origin-twins-6948.test.ts
@@ -0,0 +1,91 @@
+/**
+ * #6712 PR 4b carry-over of #6948 (GBRA-129) into the level pass: a path several live pages record as their origin is
+ * held `origin_conflict` on its own, with the shared verdict (persistence/origin-twins.ts), and the rest of the source
+ * syncs. Before the carry-over the pass refused the whole source with `page_identity_changed`. The level pass sees every
+ * claimed path, so an unchanged file is held too; the hold is re-screened on every pass (the tick after it is not idle)
+ * and goes once one page records the file. The sync-time heal runs in `performSync`, so these runs (performManagedSync)
+ * show the pass's own hold. PGLite here; Postgres through test/e2e/sync-pass-origin-twins-6948-postgres.test.ts.
+ */
+import { 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 { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';
+import { MANAGED_SYNC_PASS_OP } from '../src/core/persistence/sync-pass-row.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { dropOriginIndex } from './helpers/origin-index.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.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 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');
+};
+
+const passRow = async (engine: BrainEngine) => (await engine.executeRaw<{ value: { telemetry: { kind: string; counts?: Record<string, number> } } }>(
+ "SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'source_id'='default'", [MANAGED_SYNC_PASS_OP]))[0]!.value;
+const originHolds = async (engine: BrainEngine) => ((await readGitSourceHolds(engine, { sourceIds: ['default'] }))[0]?.holds ?? []).filter(hold => hold.code === 'origin_conflict');
+const body = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ compiled_truth: string; deleted_at: string | null }>(
+ 'SELECT compiled_truth, deleted_at FROM pages WHERE source_id=$1 AND slug=$2', ['default', slug]))[0] ?? null;
+/** A second live page recording notes/a.md, as legacy data left it (the origin index is dropped: such a brain has it pending). */
+async function twin(engine: BrainEngine, slug: string, same: boolean): Promise<void> {
+ await dropOriginIndex(engine);
+ const [a] = await engine.executeRaw<{ compiled_truth: string; timeline: string | null; trust_tier: string }>(
+ "SELECT compiled_truth, timeline, trust_tier::text AS trust_tier FROM pages WHERE source_id='default' AND slug='notes/a'");
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {
+ await tx.executeRaw("SELECT set_config('gbrain.write_trust_tier', $1, true)", [a!.trust_tier]);
+ await tx.putPage(slug, { type: 'concept', title: 'Example', compiled_truth: same ? a!.compiled_truth : 'A different body.', timeline: a!.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=$1", [slug]);
+ }, TEST_WRITE_ATTRIBUTION));
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ const brain = (run: Parameters<typeof managedBrain>[0]) => managedBrain(run, { ...(databaseUrl ? { databaseUrl } : {}), setup });
+
+ describe(`#6712 PR 4b level pass: #6948 duplicate-origin twins (${backend})`, () => {
+ test('verified twins plus an unrelated edit: the pass holds only the twin-claimed file (no reason, so the heal resolves it) and syncs the rest', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await twin(engine, 'notes/a-copy', true);
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'An edited body of notes/a.'));
+ writeFileSync(join(root, 'notes/b.md'), note('notes/b', 'An edited body of notes/b.'));
+ commit(root, 'edit a and b');
+ const result = await performManagedSync(engine, OPTS);
+ expect(result.status).toBe('synced');
+ expect((await body(engine, 'notes/b'))!.compiled_truth).toContain('An edited body of notes/b.');
+ expect((await body(engine, 'notes/a'))!.compiled_truth).toContain('The committed body of notes/a.');
+ const held = await originHolds(engine);
+ expect(held.map(hold => [hold.path, hold.meta.reason ?? null, hold.meta.canonical_slug, (hold.meta.origin_claimants ?? []).map(page => page.slug)]))
+ .toEqual([['notes/a.md', null, 'notes/a', ['notes/a', 'notes/a-copy']]]);
+ expect((await passRow(engine)).telemetry.counts?.holds_origin_conflict).toBe(1);
+ expect((await body(engine, 'notes/a-copy'))!.deleted_at).toBeNull();
+ }), 180_000);
+
+ test('an unchanged file two differing pages claim is held with its reason on every pass (never idle meanwhile); once one page records it the hold goes', () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await twin(engine, 'notes/a-copy', false);
+ writeFileSync(join(root, 'notes/c.md'), note('notes/c', 'An edited body of notes/c.'));
+ commit(root, 'edit c');
+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');
+ expect((await body(engine, 'notes/c'))!.compiled_truth).toContain('An edited body of notes/c.');
+ const reasons = async () => (await originHolds(engine)).map(hold => [hold.path, hold.meta.reason ?? null]);
+ expect(await reasons()).toEqual([['notes/a.md', 'content_differs']]);
+ await performManagedSync(engine, OPTS);
+ expect((await passRow(engine)).telemetry.kind).not.toBe('idle');
+ expect(await reasons()).toEqual([['notes/a.md', 'content_differs']]);
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("UPDATE pages SET source_path=NULL WHERE source_id='default' AND slug='notes/a-copy'"), TEST_WRITE_ATTRIBUTION));
+ await performManagedSync(engine, OPTS);
+ expect(await reasons()).toEqual([]);
+ expect((await body(engine, 'notes/a'))!.compiled_truth).toContain('The committed body of notes/a.');
+ }), 180_000);
+ });
+}