Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): hold duplicate-origin twins per file and heal verified duplicates (#6948)

garrytane5a48af50584
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 77387eba59..9070d53703 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2380,6 +2380,16 @@ Reasons: `not_owner_host`, `not_applicable`.
More: [docs/guides/repair.md#ghost-pages](../../docs/guides/repair.md#ghost-pages)
+### origin_twin_mass_merge_refused
+
+<a id="origin_twin_mass_merge_refused"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| gbrain repair origin-twins refused to merge duplicate-origin twins amounting to more than half of a source's file-backed pages; nothing was changed. | The sync mass-delete valve (#2828) applied to origin twins (#6948): that many twins at once almost always means a re-import under other slugs or the wrong checkout, not a backlog. | Check the source and its checkout first. If merging these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1. | user | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/repair.md#origin-twins](../../docs/guides/repair.md#origin-twins)
+
### overlapping_path
<a id="overlapping_path"></a>
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index cb3aed9e37..a20d536fb5 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -122,6 +122,7 @@ Every hold and error has three fields, from one table
| `purged_content` | page | none | yes | always: only the owner clears a purge tombstone |
| `write_gate_rejected` | page | none | yes | always: write_gate.external_mode=reject is the user's setting |
| `legacy_slug_conflict` | page | none | yes | always: only a person decides which legacy page the file takes over |
+| `origin_conflict` | page | repair | no | the hold carries a reason (the pages differ, ids conflict or none is the page the path names), or the heal is off |
| `revision_conflict` | page | retry | no | the same path fails again after a rerun |
| `page_identity_changed` | page | retry | no | the same path fails again after a rerun |
| `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun |
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 0c7379fd03..14e7589c37 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -398,6 +398,7 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:
}
if (key.startsWith('loops.')) (await import('./config/loops-values.ts')).refuseInvalidLoopsConfigValue(key, value);
if (key === 'sync.slug_conflicts.auto_remove') { const err = (await import('../core/repair/slug-autoheal.ts')).slugAutoRemoveValueRefusal(value); if (err) { console.error(`[config] ${err}`); process.exit(1); } }
+ if (key === 'sync.origin_twins.auto_resolve') { const err = (await import('../core/repair/origin-twins-heal.ts')).originAutoResolveValueRefusal(value); if (err) { console.error(`[config] ${err}`); process.exit(1); } }
if (key.startsWith('search.')) (await import('./config/keyword-timeout-value.ts')).refuseInvalidKeywordTimeoutValue(key, value);
if (key === 'persistence.max_claim_ms') {
const { validateMaxClaimConfigValue } = await import('../core/persistence/claim-phase.ts');
diff --git a/src/commands/doctor/checks/origin-twins.ts b/src/commands/doctor/checks/origin-twins.ts
new file mode 100644
index 0000000000..655920ead4
--- /dev/null
+++ b/src/commands/doctor/checks/origin-twins.ts
@@ -0,0 +1,40 @@
+/**
+ * #6948 `origin_twins`: live pages of one source recording the same file (duplicate-origin twins), which sync holds
+ * `origin_conflict`, and the state of the `pages_live_origin_key` index that makes a new twin unwritable. With the
+ * index present no twin can exist, so nothing else is read. Without it the check counts groups per source (one
+ * grouped read over live file-backed pages): twins name the read-only `gbrain repair origin-twins --source <id>`
+ * preview; no twins name its apply, which builds the index ("index pending").
+ */
+import type { Check } from '../../doctor.ts';
+import { agentFix, checkError } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { originIndexState, originTwinCounts, originTwinsRepairCommand, ORIGIN_INDEX } from '../../../core/persistence/origin-index.ts';
+
+const DOCS = 'docs/guides/repair.md#origin-twins';
+
+async function runOriginTwins(ctx: DoctorContext): Promise<Check[]> {
+ try {
+ const engine = connectedEngine(ctx);
+ const index = await originIndexState(engine);
+ if (index === 'present') return [{ name: 'origin_twins', status: 'ok', details: { index, docs: DOCS }, message: `${ORIGIN_INDEX.name} is present: no two live pages can record one file.` }];
+ const sources = await originTwinCounts(engine);
+ if (sources.length) {
+ const first = sources[0]!.source_id;
+ return [{ name: 'origin_twins', status: 'warn', details: { index, sources, docs: DOCS },
+ message: `Index pending: ${sources.map(s => `source ${s.source_id} has ${s.groups} file(s) recorded by several live pages (${s.twins} extra page(s))`).join('; ')}. `
+ + `Sync holds each such file origin_conflict and imports the rest. Preview the fix with ${originTwinsRepairCommand(first)} (writes nothing); its apply builds ${ORIGIN_INDEX.name} once no source has a group.`,
+ fix: agentFix(['gbrain', 'repair', 'origin-twins', '--source', first, '--json'],
+ 'Read-only preview: lists each duplicate-origin group with its pages, revisions and verdict, and prints the apply command with its hash. Apply only after the user agrees (merged twins are soft-deleted; their file stays).',
+ 'origin_twins', { docs: DOCS }) }];
+ }
+ const [source] = await engine.executeRaw<{ id: string }>("SELECT id FROM sources ORDER BY (id = 'default') DESC, id LIMIT 1");
+ return [{ name: 'origin_twins', status: 'warn', details: { index, sources: [], docs: DOCS },
+ message: `Index pending: no duplicate-origin twins remain, but ${ORIGIN_INDEX.name} is ${index}. Build it with ${originTwinsRepairCommand(source?.id ?? 'default')} --apply --expect <hash from its preview> --yes (online; writes no page).`,
+ fix: agentFix(['gbrain', 'repair', 'origin-twins', '--source', source?.id ?? 'default', '--json'],
+ 'Read-only preview of an empty set; its printed apply command builds the index online and changes no page.', 'origin_twins', { docs: DOCS }) }];
+ } catch (error) {
+ return [checkError('origin_twins', 'check for duplicate-origin twins and the origin index', error, { details: { index: 'unknown', docs: DOCS } })];
+ }
+}
+
+export const originTwinsEntry: DoctorEntry = { name: 'origin_twins', emits: ['origin_twins'], run: runOriginTwins };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index b7da5c8557..8bf1164402 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -117,6 +117,7 @@ import { behaviorChangesEntry } from './checks/behavior-changes.ts';
import { fenceIntegrityEntry } from './checks/fence-integrity.ts';
import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';
import { ghostPagesEntry } from './checks/ghost-pages.ts';
+import { originTwinsEntry } from './checks/origin-twins.ts';
import { renameIdentityDowngradesEntry } from './checks/rename-identity-downgrades.ts';
import { unindexedFilesEntry } from './checks/unindexed-files.ts';
import { purgeParkedPagesEntry } from './checks/purge-parks.ts';
@@ -247,6 +248,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
atomHeldFailedEntry,
extractionInputTruncatedEntry,
ghostPagesEntry,
+ originTwinsEntry,
renameIdentityDowngradesEntry,
purgeParkedPagesEntry,
missingRecordedFilesEntry,
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 72d02ef10d..c26495280d 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -140,7 +140,7 @@ const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--ski
/** Flags only some kinds accept, with the kinds that do. */
const KIND_FLAGS: Record<string, readonly string[]> = {
'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'rename-identity'],
- '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],
+ '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],
'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],
};
@@ -362,7 +362,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
const preview = ['gbrain', 'repair', kind, ...(source ? ['--source', source] : []), ...only.flatMap(path => ['--only', path]), ...skip.flatMap(path => ['--skip', path]),
...(includeAmbiguous ? ['--include-ambiguous'] : []), ...(requestId ? ['--request-id', requestId] : []),
...(olderThan ? ['--older-than', olderThan] : []), ...(includeFailures ? ['--include-failures'] : []), ...(force ? ['--force'] : []),
- ...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : [])];
+ ...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : []),
+ ...(kind === 'origin-twins' ? slugs.flatMap(slug => ['--slug', slug]) : [])];
const custom = repairSpec(kind as RepairKind).consentText;
const text = custom ? { ...custom, why: `Preview ${expect}: ${custom.why}`, user_message: `${custom.user_message} (preview ${expect.slice(0, 12)}${keep ? `, keep ${keep}` : ''})` } : {
what: `Rewrite the previewed ${kind} changes on disk and import them`,
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 6f6d2c7b16..7b2e902114 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -37,6 +37,8 @@ export interface SyncResult {
replayedRemembers?: import('../core/repair/failed-writes.ts').ImportReplayReport;
/** #6712 PR 2 (L4): live pages whose canonical file is gone (ghost pages), counted after a managed sync with the read-only repair preview; sync never deletes them. */
ghostPages?: import('../core/persistence/sync-ghosts.ts').SyncGhostPages; /** #6865: stray slug: lines naming no page this sync removed (repair/slug-autoheal.ts). */ slug_lines_removed?: import('../core/repair/slug-autoheal.ts').SlugHealReport;
+ /** #6948: held duplicate-origin files whose verified twins this sync merged, or why it left them (repair/origin-twins-heal.ts). */
+ origin_twins_resolved?: import('../core/repair/origin-twins-heal.ts').OriginHealReport;
/** #6722: pages this run left large or embed_skip (chunked, keyword-searchable) and their embedding state. */ size_states?: import('../core/page-embedding-budget.ts').SyncSizeStates;
status: 'up_to_date' | 'synced' | 'first_sync' | 'dry_run' | 'blocked_by_failures' | 'partial';
fromCommit: string | null;
diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.ts
index 1d85afbb5f..c727c8703e 100644
--- a/src/commands/sync/perform.ts
+++ b/src/commands/sync/perform.ts
@@ -151,7 +151,8 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promi
if (outer.dryRun) return work(undefined);
const { withSyncTail } = await import('../../core/persistence/sync-tail.ts');
try {
- return await (await import('../../core/repair/slug-autoheal.ts')).healAfterManagedSync(engine, outer, await withSyncTail(engine, sourceId, await withDrainLease(engine, sourceId, {
+ const { healOriginTwinsAfterManagedSync } = await import('../../core/repair/origin-twins-heal.ts');
+ return await healOriginTwinsAfterManagedSync(engine, outer, await (await import('../../core/repair/slug-autoheal.ts')).healAfterManagedSync(engine, outer, await withSyncTail(engine, sourceId, await withDrainLease(engine, sourceId, {
holder: outer.drainHolder ?? { kind: 'cli', id: null }, remote: currentSubmissionAuthority()?.kind === 'remote_generic',
...(outer.followDrainLease ? { follow: { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs } } : {}),
tty: process.stderr.isTTY === true,
@@ -162,7 +163,7 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promi
? `[sync] source ${sourceId} is being drained by ${who}; following it until it finishes or this run's budget ends (one drainer per source; it resumes the same cursor). Ctrl-C stops following and leaves it running.`
: `[sync] following ${who}: ${done}.`);
},
- }, work), { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs }));
+ }, work), { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs })));
} catch (err) {
if (err instanceof LockUnavailableError && err.lockId === lockKey) throw new SyncLockBusyError(await formatLockBusyMessage(engine, lockKey), lockKey);
throw err;
diff --git a/src/core/config.ts b/src/core/config.ts
index 8e95073510..94c85f5979 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1746,6 +1746,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// restores fail-closed blocking. Detail, escalation and the parser-regression
// stop are tuned by GBRAIN_SYNC_* env since #6712 PR 2 (RETIRED_SYNC_KEYS).
'sync.holds', 'sync.slug_conflicts.auto_remove', // #6865: sync-time removal of a stray slug: line naming no page (repair/slug-autoheal.ts); default on
+ 'sync.origin_twins.auto_resolve', // #6948: sync-time merge of verified duplicate-origin twins (repair/origin-twins-heal.ts); default on
'fences.normalize', // #6188: inline Tier 1 fence normalization (fence-repair/config.ts); default on
'fences.repair.enabled', 'fences.repair.llm', // #6188: the fence_repair cycle phase and its Tier 3 model step (fence-repair/config.ts); default on
'fences.repair.max_usd_per_page', 'fences.repair.max_usd_per_day', // #6188: Tier 3 fence repair caps; 0 = no model spend
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 12b6461dc6..36c0f447fb 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -201,6 +201,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'undeclared_db_only_pages',
// #6696 B5: live pages whose canonical file is missing on the owner host (doctor/checks/ghost-pages.ts).
'ghost_pages',
+ // #6948: files recorded by several live pages (origin twins) and the pages_live_origin_key index (doctor/checks/origin-twins.ts).
+ 'origin_twins',
// #6729: inexact renames whose identity sync did not keep, until the pair gets a disposition (doctor/checks/rename-identity-downgrades.ts).
'rename_identity_downgrades',
// #6609: live pages of a classic checkout whose recorded file a full sync would not find (doctor/checks/missing-recorded-files.ts).
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 59c8c74b57..f40067ddce 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -175,7 +175,7 @@ export async function putPage(
import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename),
chunker_version = ${trustedSql(bodyWriteChunkVersion('EXCLUDED.compiled_truth', 'EXCLUDED.timeline'))},
source_path = COALESCE(EXCLUDED.source_path, pages.source_path),
- database_only_reason = CASE WHEN EXCLUDED.source_path IS NOT NULL AND pages.database_only_reason = 'detached' THEN NULL ELSE pages.database_only_reason END,
+ database_only_reason = CASE WHEN EXCLUDED.source_path IS NOT NULL AND pages.database_only_reason IN ('detached', 'origin_twin') THEN NULL ELSE pages.database_only_reason END,
source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind),
source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri),
ingested_via = COALESCE(EXCLUDED.ingested_via, pages.ingested_via),
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index f7a58783a9..b3dbdc592c 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -271,6 +271,7 @@ export const CODES = {
full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },
gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },
ghost_mass_delete_refused: { class: 'consent', summary: "gbrain repair ghost-pages refused to soft-delete more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to ghost pages: that many missing canonical files almost always means the checkout is the wrong path, unmounted or half-cloned, not that the files were deleted.", docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Check the source checkout on its owner host first. If removing these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host, to check the checkout before anything is removed.", requires_exclusive: false } },
+ origin_twin_mass_merge_refused: { class: 'consent', summary: "gbrain repair origin-twins refused to merge duplicate-origin twins amounting to more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to origin twins (#6948): that many twins at once almost always means a re-import under other slugs or the wrong checkout, not a backlog.", docs: 'docs/guides/repair.md#origin-twins', suggestion: 'Check the source and its checkout first. If merging these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.' },
ghost_storage_unknown: { class: 'unavailable', summary: "Ghost pages of a source cannot be classified because its canonical checkout cannot be read reliably; nothing was listed or changed.", why: "A page is never reported or removed as a ghost while its file may only be unreadable: a missing or non-directory root (storage_unavailable), or a stat error, an invalid gbrain.yml or an inconclusive page check (ambiguous_storage), fails closed.", reasons: ['storage_unavailable', 'ambiguous_storage'], docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Inspect the source checkout on its owner host (writer status shows its root), fix it, then preview gbrain repair ghost-pages --source <id> again.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host.", requires_exclusive: false } },
git_branch_unborn: { class: 'host_only', summary: "The canonical checkout's branch has no commit yet, so Git durability has nothing to build on.", why: "A Git effect commits on top of HEAD and pushes the branch; on an unborn branch (a fresh `init --git` root) there is no HEAD to commit on and no ref to push, so enabling durability would park every effect. The database is unaffected.", suggestion: 'Make the first commit on the branch on the brain host (git add -A && git commit -m "Initial brain"), then rerun gbrain sources writer git-durability <source> --enable.' },
// wave 18b (GBRA-106) #5182: activation warns per source whose Git effects it would leave skipped.
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 2d26ca529a..a06b264ada 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -61,7 +61,7 @@ interface PreparedMutationBase {
contentUnchanged?: boolean;
deferEmbedding?: boolean;
/** Why a page write bound to a worktree publishes no file (receipt `write_through.skipped`). */
- databaseOnlyReason?: 'db_only' | 'unbound_source' | 'mirror_read_only' | 'sync_excluded' | 'shared_origin';
+ databaseOnlyReason?: 'db_only' | 'unbound_source' | 'mirror_read_only' | 'sync_excluded' | 'shared_origin' | 'origin_twin';
/** #6517: the receipt's `write_through.warning` for a database-only publication, set by `validate` under the publication guards. */
databaseOnlyWarning?: string;
/**
diff --git a/src/core/persistence/origin-index.ts b/src/core/persistence/origin-index.ts
new file mode 100644
index 0000000000..74ba43730d
--- /dev/null
+++ b/src/core/persistence/origin-index.ts
@@ -0,0 +1,59 @@
+/**
+ * #6948: the database invariant behind origin twins: one live page per recorded origin, a partial unique index
+ * `pages_live_origin_key` on (source_id, source_path) over live pages that record a file. It is built online only
+ * when the brain holds no live twins (the migration, or `gbrain repair origin-twins --apply` once the last group is
+ * resolved); with twins it is left pending and doctor names the repair, so no upgrade fails or rewrites data.
+ * The index covers the stored spelling; the legacy `<scope>/<origin>` spelling of a scoped source-root source is
+ * refused by the writer guard and reported by doctor and the repair.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { buildIndexOnline, type OnlineIndexOutcome } from '../schema-migrations/helpers.ts';
+
+export const ORIGIN_INDEX = {
+ name: 'pages_live_origin_key',
+ table: 'pages',
+ sql: 'CREATE UNIQUE INDEX IF NOT EXISTS pages_live_origin_key ON pages (source_id, source_path) WHERE deleted_at IS NULL AND source_path IS NOT NULL',
+};
+
+/** Live twin groups (same stored origin) per source, at most `limit` sources. */
+export async function originTwinCounts(engine: Pick<BrainEngine, 'executeRaw'>, limit = 50): Promise<Array<{ source_id: string; groups: number; twins: number }>> {
+ const rows = await engine.executeRaw<{ source_id: string; groups: number; twins: number }>(`SELECT source_id, count(*)::int AS groups, (sum(n) - count(*))::int AS twins
+ FROM (SELECT source_id, count(*) AS n FROM pages WHERE deleted_at IS NULL AND source_path IS NOT NULL GROUP BY source_id, source_path HAVING count(*) > 1) g
+ GROUP BY source_id ORDER BY source_id LIMIT ${Math.max(1, Math.floor(limit))}`);
+ return rows.map(row => ({ source_id: row.source_id, groups: Number(row.groups), twins: Number(row.twins) }));
+}
+
+export type OriginIndexState = 'present' | 'missing' | 'invalid';
+
+export async function originIndexState(engine: Pick<BrainEngine, 'executeRaw' | 'kind'>): Promise<OriginIndexState> {
+ if (engine.kind !== 'postgres') {
+ const [row] = await engine.executeRaw<{ present: boolean }>('SELECT to_regclass($1) IS NOT NULL AS present', [ORIGIN_INDEX.name]);
+ return row?.present ? 'present' : 'missing';
+ }
+ const [row] = await engine.executeRaw<{ valid: boolean }>('SELECT indisvalid AS valid FROM pg_index WHERE indexrelid = to_regclass($1)', [ORIGIN_INDEX.name]);
+ return !row ? 'missing' : row.valid ? 'present' : 'invalid';
+}
+
+export const originTwinsRepairCommand = (sourceId: string) => `gbrain repair origin-twins --source ${sourceId}`;
+
+export type OriginIndexOutcome = { state: Exclude<OnlineIndexOutcome, 'building'> | 'building' } | { state: 'pending'; sources: Array<{ source_id: string; groups: number; twins: number }> };
+
+/**
+ * Builds the index when no live twins exist (online, CONCURRENTLY on Postgres); otherwise writes nothing and returns
+ * the sources that still hold twins. A twin written between the check and a concurrent build fails the build: the
+ * INVALID remnant (which would still enforce uniqueness) is dropped and the index stays pending. Never throws for twins.
+ */
+export async function buildOriginIndexIfClean(engine: BrainEngine, version: number, notice?: (line: string) => void): Promise<OriginIndexOutcome> {
+ if (await originIndexState(engine) === 'present') return { state: 'present' };
+ const sources = await originTwinCounts(engine);
+ if (sources.length) return { state: 'pending', sources };
+ try {
+ return { state: await buildIndexOnline(engine, version, ORIGIN_INDEX, { notice, rebuild: 'gbrain repair origin-twins --source <id> --apply' }) };
+ } catch (error) {
+ const again = await originTwinCounts(engine);
+ if (!again.length) throw error;
+ if (engine.kind === 'postgres') await engine.withReservedConnection(conn => conn.executeRaw(`DROP INDEX CONCURRENTLY IF EXISTS ${ORIGIN_INDEX.name}`), { selfContained: true });
+ else await engine.executeRaw(`DROP INDEX IF EXISTS ${ORIGIN_INDEX.name}`);
+ return { state: 'pending', sources: again };
+ }
+}
diff --git a/src/core/persistence/origin-twins.ts b/src/core/persistence/origin-twins.ts
new file mode 100644
index 0000000000..3212b48bda
--- /dev/null
+++ b/src/core/persistence/origin-twins.ts
@@ -0,0 +1,108 @@
+/**
+ * #6948: duplicate-origin twins. Two or more live pages of one source recording the same origin (`source_id`,
+ * `source_path`) used to make managed sync refuse the whole source. This module holds the one rule that decides what
+ * happens to such a group, shared by sync discovery (src/core/persistence/sync-discovery.ts), the sync-time heal and
+ * `gbrain repair origin-twins`, so the three never disagree.
+ *
+ * A group resolves on its own only when the claimants are positively verified duplicates: exactly one claimant's slug is
+ * the slug the file's path gives (`resolveSlugForPath`, the canonical page), every claimant holds the same inline body
+ * (`compiled_truth` and `timeline`; frontmatter may differ, a segmented body is unknown), the file is present and its frontmatter readable, no two explicit frontmatter ids among the file and
+ * the claimants differ, all claimants share one visibility and one trust tier, no twin has slug-keyed fact withdrawals or purges, and no
+ * twin has a file of its own at its slug path. Anything else is a decision for a
+ * person, and sync holds only that file (`origin_conflict`). Missing evidence never counts as agreement.
+ */
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { resolveSlugForPath } from '../sync.ts';
+import { explicitIdVeto } from '../sync-rename-identity.ts';
+import type { BrainEngine } from '../engine.ts';
+import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+
+/** The kill switch for the sync-time auto-resolve (default on), modelled on `sync.slug_conflicts.auto_remove`. */
+export const ORIGIN_TWINS_AUTO_RESOLVE_KEY = 'sync.origin_twins.auto_resolve';
+
+/** `pages.database_only_reason` of a page that gave its origin up to a duplicate: it never writes or removes a file again (restore, purge). */
+export const ORIGIN_TWIN_REASON = 'origin_twin';
+
+/** Whether a page carries the `origin_twin` marker (file-target preparation honours it). */
+export async function isOriginTwinPage(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string): Promise<boolean> {
+ const [row] = await engine.executeRaw<{ database_only_reason: string | null }>('SELECT database_only_reason FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ return row?.database_only_reason === ORIGIN_TWIN_REASON;
+}
+
+/** The read-only preview of every twin group of a source (`gbrain repair origin-twins`). */
+export const originTwinsPreviewArgv = (sourceId: string) => ['gbrain', 'repair', 'origin-twins', '--source', sourceId];
+
+/** One live page recording the origin. */
+export interface OriginClaimant { id: number; slug: string; revision: string; body_hash: string | null; fm_id: string | null;
+ /** Remote readers cannot see the page (the read-side private rule). */
+ private: boolean;
+ /** Fact withdrawals or purges are keyed to the page's slug: moving its facts could bring a forgotten claim back. */
+ restricted: boolean;
+ /** The page's memory trust tier; a merge never raises or lowers one, so differing tiers hold. */
+ trust_tier: string | null }
+
+/**
+ * The verdict inputs of live pages, by id: the inline body digest (`compiled_truth` and `timeline`; NULL for a segmented
+ * body, so unknown never matches), the explicit frontmatter id, privacy and slug-keyed withdrawals or purges.
+ */
+export async function readOriginClaimants(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, ids: readonly number[]): Promise<OriginClaimant[]> {
+ const rows = await engine.executeRaw<{ id: number; slug: string; revision: string; body_hash: string | null; fm_id: string | null; private: boolean; restricted: boolean; trust_tier: string | null }>(
+ `SELECT p.id, p.slug, p.knowledge_revision::text AS revision,
+ CASE WHEN p.compiled_truth IS NULL THEN NULL ELSE md5(p.compiled_truth) || md5(COALESCE(p.timeline, '')) END AS body_hash,
+ p.frontmatter->>'id' AS fm_id, p.trust_tier::text AS trust_tier, (${privatePagesFilterFragment('p')}) AS private,
+ (EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=p.source_id AND w.subject=p.slug)
+ OR EXISTS (SELECT 1 FROM fact_purges f WHERE f.source_id=p.source_id AND f.subject=p.slug)) AS restricted
+ FROM pages p WHERE p.source_id=$1 AND p.id=ANY($2::bigint[]) AND p.deleted_at IS NULL ORDER BY p.id`, [sourceId, [...ids]]);
+ return rows.map(row => ({ id: Number(row.id), slug: row.slug, revision: String(row.revision), body_hash: row.body_hash, fm_id: row.fm_id,
+ private: row.private === true, restricted: row.restricted === true, trust_tier: row.trust_tier ?? null }));
+}
+
+export type OriginConflictReason = 'no_canonical_claimant' | 'content_differs' | 'file_unreadable' | 'explicit_id_conflict' | 'visibility_differs'
+ | 'trust_tier_differs' | 'twin_has_withdrawals' | 'twin_slug_path_occupied'
+ /** A twin holds a link, relationship date, timeline entry or raw payload its survivor holds differently (persistence/twin-merge.ts). */
+ | 'twin_evidence_conflicts';
+
+export type OriginTwinVerdict =
+ | { verdict: 'resolve'; canonical: string; survivor: OriginClaimant; twins: OriginClaimant[] }
+ | { verdict: 'hold'; canonical: string; reason: OriginConflictReason; claimants: OriginClaimant[] };
+
+export interface OriginTwinInput {
+ /** The origin, in the form sync records it. */
+ sourcePath: string;
+ /** Every live page recording the origin (two or more). */
+ claimants: readonly OriginClaimant[];
+ /** The file's explicit frontmatter id (null: it has none); undefined when the file is missing or cannot be read. */
+ fileId: string | null | undefined;
+ /** Whether a file exists at a claimant's own slug path (it would be another document's page); omitted means none. */
+ slugPathOccupied?: (slug: string) => boolean;
+}
+
+/** What discovery records on an entry several live pages claim; the freeze holds it `origin_conflict`. No `reason`: the group resolves on its own. */
+export interface OriginConflict { canonical: string; claimants: OriginClaimant[]; reason?: OriginConflictReason }
+
+/** Whether a Markdown file exists at a page's own slug path in the source's checkout (origin form: under the slug root). */
+export function slugPathOccupied(context: { root: string; gitRoot: string; slugMode: 'git-root' | 'source-root' }): (slug: string) => boolean {
+ const base = context.slugMode === 'source-root' ? context.root : context.gitRoot;
+ return slug => ['.md', '.mdx'].some(ext => existsSync(join(base, `${slug}${ext}`)));
+}
+
+/** The verdict for one group of live pages recording one origin. Pure: callers read the rows and the file. */
+export function decideOriginTwins(input: OriginTwinInput): OriginTwinVerdict {
+ const canonical = resolveSlugForPath(input.sourcePath);
+ const claimants = [...input.claimants].sort((a, b) => Number(a.id) - Number(b.id));
+ const hold = (reason: OriginConflictReason): OriginTwinVerdict => ({ verdict: 'hold', canonical, reason, claimants });
+ const survivors = claimants.filter(page => page.slug === canonical);
+ if (survivors.length !== 1) return hold('no_canonical_claimant');
+ const survivor = survivors[0]!;
+ const twins = claimants.filter(page => page !== survivor);
+ if (survivor.body_hash === null || twins.some(page => page.body_hash !== survivor.body_hash)) return hold('content_differs');
+ if (input.fileId === undefined) return hold('file_unreadable');
+ const ids = [input.fileId, ...claimants.map(page => page.fm_id)];
+ if (ids.some(a => ids.some(b => explicitIdVeto(a, b)))) return hold('explicit_id_conflict');
+ if (twins.some(page => page.private !== survivor.private)) return hold('visibility_differs');
+ if (twins.some(page => page.trust_tier !== survivor.trust_tier)) return hold('trust_tier_differs');
+ if (twins.some(page => page.restricted)) return hold('twin_has_withdrawals');
+ if (twins.some(page => input.slugPathOccupied?.(page.slug))) return hold('twin_slug_path_occupied');
+ return { verdict: 'resolve', canonical, survivor, twins };
+}
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 1d5a656602..43b3800269 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -41,6 +41,7 @@ import type { PreparedContentImport } from './prepared-import.ts';
import type { PreparedMutation } from './coordinator.ts';
import type { SqlEngine, WriteRequest } from './model.ts';
import { isUnboundSourcePage } from './unbound-source.ts';
+import { isOriginTwinPage } from './origin-twins.ts';
import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';
import { materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';
import { pipelined } from '../page-state/transactions.ts';
@@ -265,6 +266,9 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
// every state (live, tombstone, restore, revert, delete, purge); any file at
// its derived path is not its canonical file and is neither written nor removed.
if (snapshot && !snapshot.page.source_path && await isUnboundSourcePage(engine, row.source_id, row.slug)) return undefined;
+ // #6948: a page that gave its file up to a duplicate it was merged into never writes or removes a file again (restore,
+ // edit, purge); any file at its slug path is another page's.
+ if (snapshot && !snapshot.page.source_path && await isOriginTwinPage(engine, row.source_id, row.slug)) return undefined;
const binding = await getWorktreeBinding(engine, row.source_id, hostId);
if (!binding?.local_path) throw opError('owner_unavailable', 'The canonical worktree is unavailable on this host.',
`This host does not hold source ${row.source_id}'s canonical worktree (or it has no local path), so the file of ${row.slug} was not written. Inspect the owner before resubmitting; the write publishes on the host that owns the source.`,
@@ -383,7 +387,8 @@ async function heldFileRefusal(engine: BrainEngine, row: Pick<WriteRequest, 'sou
* Receipt reason for a page write that publishes no file. Invariant: for a
* bound row, prepareFileTarget returns no target only for a live declared
* db_only page whose file is absent, a page of a read-only mirror source
- * (#5409), or a page written while its source was unbound (#5254) in any state; every other case returns a target or throws.
+ * (#5409), a page written while its source was unbound (#5254) in any state, or a page merged into its duplicate (#6948);
+ * every other case returns a target or throws.
*/
export function databaseOnlyPublication(row: Pick<WriteRequest, 'worktree_id'>, file: PreparedMutation['file']): Pick<PreparedMutation, 'databaseOnlyReason'> {
return row.worktree_id && !file ? { databaseOnlyReason: 'db_only' } : {};
@@ -393,6 +398,7 @@ async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest,
if (reason.databaseOnlyReason && (await sourceMirrorReadOnly(engine, row.source_id) || await isMirrorOnlyPage(engine, row.source_id, row.slug))) {
return { databaseOnlyReason: 'mirror_read_only' };
}
+ if (reason.databaseOnlyReason && await isOriginTwinPage(engine, row.source_id, row.slug)) return { databaseOnlyReason: 'origin_twin' };
return reason.databaseOnlyReason && await isUnboundSourcePage(engine, row.source_id, row.slug) ? { databaseOnlyReason: 'unbound_source' } : reason;
}
@@ -471,6 +477,14 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,
}
// #6511: the purge's journal sweep runs here, under the preparation budget, never inside the 5 s publication transaction.
const preparedPurge: PreparedPagePurge | null = purge ? await preparePagePurge(engine, row, snapshot, clock) : null;
+ // #6948: a page merged into its duplicate holds that page's body, so an owner purge would tombstone the survivor's content.
+ if (preparedPurge && !preparedPurge.retention && await isOriginTwinPage(engine, row.source_id, row.slug)) {
+ const error = pageRefusal('source_changed', 'The page was merged into a duplicate that holds the same content, so a purge (which tombstones its content source-wide) was refused and nothing was removed, tombstoned or redacted. '
+ + 'The 72 h retention purge removes it database-only; to erase the content itself, purge the page it was merged into.', row,
+ `${row.slug} of source ${row.source_id} was merged into a duplicate page (gbrain repair origin-twins).`, pageFix(row.source_id, row.slug));
+ error.detail = 'origin_twin';
+ throw error;
+ }
const prepared: PreparedMutation = { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file),
// W1: a purge bumps sources.purge_epoch, so it holds the source row exclusively from the start (retention bumps nothing, #26);
// the derived rows' and cascaded links' streams are locked with the page.
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 4c5c00ce84..ce35407e29 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -203,7 +203,7 @@ export function maintenanceDriftRefusal(sourceId: string, slug: string): Operati
* retirement, which exists to soft-delete pages whose canonical file is gone): a missing canonical file publishes, so it is no ghost.
*/
export const PUBLISHES_WITHOUT_FILE: ReadonlySet<string> = new Set(['managed_maintenance_chronicle_event', 'managed_maintenance_chronicle_retire', 'managed_maintenance_retire_stale_atoms',
- 'managed_maintenance_retire_ghost_page']);
+ 'managed_maintenance_retire_ghost_page', 'managed_maintenance_resolve_origin_twin']);
/** #6696 (A12): `source_changed` / `canonical_file_missing` before admission: the page's recorded file is gone; never a new request. */
export function maintenanceGhostRefusal(sourceId: string, slug: string): OperationError {
@@ -533,6 +533,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, co
}
if (row.intent?.kind === 'managed_maintenance_retire_stale_atoms') return (await import('../repair/stale-atoms.ts')).prepareStaleAtomRetirement(engine, row, config);
if (row.intent?.kind === 'managed_maintenance_retire_ghost_page') return (await import('../repair/ghost-pages.ts')).prepareGhostPageRetirement(engine, row, config);
+ if (row.intent?.kind === 'managed_maintenance_resolve_origin_twin') return (await import('../repair/origin-twins.ts')).prepareOriginTwinResolve(engine, row, config);
if (row.intent?.kind !== 'managed_maintenance_consolidate') throw opError('invalid_params', 'Unsupported maintenance request.',
`Request ${row.request_id} for ${row.slug} in ${row.source_id} carries a maintenance kind this gbrain version does not publish (likely queued by a newer release); nothing changed. Upgrade gbrain on the brain host, and read the receipt before submitting anything new.`,
{ fix: receiptFix(row) });
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index b75339bd10..3934a3d0fb 100644
--- a/src/core/persistence/preview-approval.ts
+++ b/src/core/persistence/preview-approval.ts
@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';
/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
export const APPROVAL_MAX_AGE_DAYS = 7;
-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'missing-tables';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'missing-tables';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.ts
index 727bcb8595..29857301ee 100644
--- a/src/core/persistence/public-category.ts
+++ b/src/core/persistence/public-category.ts
@@ -34,7 +34,7 @@ export const PUBLIC_BY_TERMINAL: Readonly<Record<TerminalCategory, PublicCategor
/** Fault codes (holds, run stops, receipts) by name; a test pins that every `SYNC_FAULT_TABLE` code is here. */
export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {
worktree_dirty: 'drift', file_drift: 'drift', source_changed: 'drift', pinned_git_worktree_conflict: 'drift',
- concurrent_write: 'conflict', revision_conflict: 'conflict', page_identity_changed: 'conflict', legacy_slug_conflict: 'conflict',
+ concurrent_write: 'conflict', revision_conflict: 'conflict', page_identity_changed: 'conflict', legacy_slug_conflict: 'conflict', origin_conflict: 'conflict',
invalid_fence: 'content_refused', invalid_frontmatter: 'content_refused', frontmatter_slug_conflict: 'content_refused', rename_held: 'content_refused',
file_too_large: 'content_refused', content_rejected: 'content_refused', managed_image_sync_unsupported: 'content_refused',
purged_content: 'content_refused', write_gate_rejected: 'content_refused',
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index cbb9e86ffd..0a35d66817 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -163,7 +163,7 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
}
// The page has a canonical origin (adopted above, or already recorded, #6536): drop the #5254 database-only classification.
await tx.executeRaw(`UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL
- AND database_only_reason='unbound_source' AND source_path IS NOT NULL`, [row.source_id, row.slug]);
+ AND database_only_reason IN ('unbound_source', 'origin_twin') AND source_path IS NOT NULL`, [row.source_id, row.slug]);
if (!ready.noop) { await prepared.project!(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }
const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id });
const scanStateTransferred = final ? await transferLegacyAtomPageState(tx, state.snapshot, final) : false;
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index 6eb2651d35..290ba6cdb1 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -13,6 +13,7 @@ import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from
import { absentCanonicalPath, findLiveFileClaimants, recordedReconcilePath, type FileClaimTarget } from './file-claims.ts';
import { wholeBodySnapshot } from './segmented-apply.ts';
import { sharedOriginExit } from './sync-origin.ts';
+import { originTwinsPreviewArgv } from './origin-twins.ts';
export { fileClaimCandidatesQuery } from './file-claims.ts';
import { localHostId } from './identity.ts';
import { isDatabaseOnlyPage, slugDerivedOrigin } from './unbound-pages.ts';
@@ -135,7 +136,10 @@ async function assertSoleFileClaim(engine: BrainEngine, target: FileClaimTarget)
const [claimant] = await findLiveFileClaimants(engine, target);
if (claimant) throw opError('source_changed', 'Several pages claim the recorded canonical file.',
`Nothing changed. Pages ${target.slug} and ${claimant.slug} in '${target.sourceId}' both record the same file, so reconcile cannot tell which owns it; decide with the user which page owns the file before reconciling either. `
- + sharedOriginExit(target.sourceId, [target.slug, claimant.slug]) + ' Then preview again.');
+ + sharedOriginExit(target.sourceId, [target.slug, claimant.slug]) + ' Then preview again.',
+ // #6948 (B-15): the read-only group listing names the page that keeps the file and the exact command for each other one.
+ { detail: 'shared_origin', fix: readFix(`Lists the duplicate-origin group of ${target.slug} and ${claimant.slug} with the page its path names and the command that resolves each other page; writes nothing.`,
+ { argv: originTwinsPreviewArgv(target.sourceId) }) });
}
/**
* #6394: `adoptSlugPath` lets a live page with no recorded origin and no database-only marker reconcile against the file
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index d8ed778a4c..571c013473 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -25,6 +25,7 @@ import { currentCompanyBrainSync } from '../company-brain/profile.ts';
import type { CompanyBrainPlan } from '../company-brain/types.ts';
import { assertDistinctSyncOrigins, legacySyncOrigin, sameSyncOrigin, selectOriginClaimant, sharedOriginExit, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive } from './sync-authority.ts';
+import { decideOriginTwins, readOriginClaimants, slugPathOccupied, type OriginConflict } from './origin-twins.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, readSyncImportProvenances } from './sync-holds.ts';
import { readBlobContents, readTreeBlobs, SYNC_READ_BOUND } from './sync-blobs.ts';
@@ -51,7 +52,9 @@ export interface SyncEntry { path: string; sourcePath: string; action: 'import'
/** #6727: live pages with no recorded origin whose slugs fold to this file's slug, several or one the importer cannot write; the freeze holds it `legacy_slug_conflict`. */
legacySlugs?: string[];
/** #6729 x #6727: the one legacy page carries an explicit frontmatter id that differs from the file's, so it is another document; held `legacy_slug_conflict` (`explicit_id_conflict`). */
- legacyIdVeto?: true; }
+ legacyIdVeto?: true;
+ /** #6948: several live pages record this file as their origin; the freeze holds it `origin_conflict` (sync.holds=fail refuses). */
+ originConflict?: OriginConflict; }
/** Files that map to a slug another origin keeps; they are left out of the manifest until one is renamed. */
export interface SyncSlugCollision { slug: string; kept: string; skipped: string[]; }
/** #5032: a file sync skipped on this host with a named refusal, without failing the run. */
@@ -506,7 +509,13 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
...(legacy ? byPath.get(legacy) ?? [] : []).filter(page => sameSyncOrigin(page.source_path!, entry.sourcePath, originScope, page.slug))];
// #6517: one origin rule (sync-origin.ts): a live page wins over tombstones; several live pages, or several tombstones, refuse.
const { winner: origin, ambiguous } = selectOriginClaimant(claimants);
- if (ambiguous) throw ambiguousOriginRefusal(sourceId, entry.sourcePath, ambiguous === 'several_live' ? claimants.filter(page => page.deleted_at == null) : claimants, ambiguous);
+ if (ambiguous === 'several_live') {
+ // #6948: twin claimants hold this file (`origin_conflict`) instead of refusing the source; the freeze holds it, the heal resolves the safe case.
+ entry.originConflict = await originConflictOf(engine, discovered, entry, claimants.filter(page => page.deleted_at == null));
+ Object.assign(entry, { slug: entry.originConflict.canonical, pageId: null, revision: null });
+ continue;
+ }
+ if (ambiguous) throw ambiguousOriginRefusal(sourceId, entry.sourcePath, claimants, ambiguous);
let slug = entry.slug ?? origin?.slug ?? resolveSlugForPath(entry.sourcePath);
if (!slug && entry.action === 'import') slug = parseMarkdown(readSyncContent(discovered, entry), '').slug;
if (!slug) throw opError('invalid_params', 'The imported file has no usable page slug.',
@@ -608,7 +617,7 @@ const legacyByFold = new WeakMap<LegacyIdentity[], Promise<Map<string, string[]>
async function foldLegacyPages(engine: BrainEngine, identities: LegacyIdentity[]): Promise<Map<string, string[]>> {
const candidates = identities.filter(page => page.deleted_at == null && page.source_path == null && slugifyPath(page.slug) !== page.slug);
const databaseOnly = new Set(candidates.length ? (await engine.executeRaw<{ id: number }>(
- `SELECT p.id FROM pages p WHERE p.id=ANY($1::bigint[]) AND ${databaseOnlyPageSql('p')}`, [candidates.map(page => Number(page.id))])).map(row => Number(row.id)) : []);
+ `SELECT p.id FROM pages p WHERE p.id=ANY($1::bigint[]) AND (${databaseOnlyPageSql('p')} OR p.database_only_reason IS NOT DISTINCT FROM 'origin_twin')`, [candidates.map(page => Number(page.id))])).map(row => Number(row.id)) : []);
return candidates.filter(page => !databaseOnly.has(Number(page.id)))
.reduce((map, page) => map.set(slugifyPath(page.slug), [...map.get(slugifyPath(page.slug)) ?? [], page.slug]), new Map<string, string[]>());
}
@@ -651,11 +660,27 @@ function assertTakeoverIdentity(discovery: SyncDiscovery, winner: SyncEntry, hol
+ `Give the file the page's id if it is the same document, or rename it so its slug differs, commit, then run gbrain sync --no-pull --source ${discovery.sourceId}.`,
{ detail: 'rename_identity_conflict' });
}
+/** #6948: the frontmatter id of the file an entry imports (null: none), or undefined when it cannot be read: unreadable is never agreement. */
+function readableId(discovery: SyncDiscovery, entry: SyncEntry): string | null | undefined {
+ try { return frontmatterIdentity(readSyncContent(discovery, entry)).id; } catch { return undefined; }
+}
/** #6729: the frontmatter id of the file an entry imports (null when it has none or cannot be read). */
function incomingId(discovery: SyncDiscovery, entry: SyncEntry): string | null {
try { return frontmatterIdentity(readSyncContent(discovery, entry)).id; } catch { return null; }
}
-/** #6517: several live pages (the soft-delete exit is named) or several tombstones record one imported origin. */
+/**
+ * #6948: the conflict record of an entry several live pages claim: the claimants (with the verdict inputs, read only on
+ * this path) and the shared verdict (origin-twins.ts), which the freeze turns into an
+ * `origin_conflict` hold of this file alone.
+ */
+async function originConflictOf(engine: BrainEngine, discovery: SyncDiscovery, entry: SyncEntry, live: Array<{ id: number }>): Promise<OriginConflict> {
+ const claimants = await readOriginClaimants(engine, discovery.sourceId, live.map(page => Number(page.id)));
+ const verdict = decideOriginTwins({ sourcePath: entry.sourcePath, claimants, fileId: entry.action === 'import' ? readableId(discovery, entry) : undefined,
+ slugPathOccupied: slugPathOccupied(discovery) });
+ return { canonical: verdict.canonical, claimants: verdict.verdict === 'resolve' ? [verdict.survivor, ...verdict.twins] : verdict.claimants,
+ ...(verdict.verdict === 'hold' ? { reason: verdict.reason } : {}) };
+}
+/** #6517: several tombstones record one imported origin (several live pages are an `origin_conflict` hold, #6948). */
function ambiguousOriginRefusal(sourceId: string, sourcePath: string, named: Array<{ slug: string }>, ambiguous: 'several_live' | 'several_tombstones'): OperationError {
return opError('page_identity_changed', 'Several pages claim the same imported origin.',
`Pages ${named.map(page => page.slug).join(', ')} in ${sourceId} all record ${sourcePath} as their origin; nothing was written. `
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index d3f71d733c..440f308900 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -75,6 +75,12 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
// #6727: pages an older gbrain imported without recording their file fold to the file's slug, several or one sync cannot write; a person decides.
{ code: 'legacy_slug_conflict', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only a person decides which legacy page the file takes over',
human_reason: 'Pages an older gbrain imported without recording their file match this file and sync cannot pick one to import into; a person keeps the one that is its page and removes the others (gbrain delete --source <source> -- <slug>), or renames the file, then syncs.' },
+ // #6948: several live pages record the file as their origin; the sync-time heal resolves verified duplicates, a person decides the rest.
+ { code: 'origin_conflict', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the hold carries a reason (the pages differ, ids conflict or none is the page the path names), or the heal is off',
+ human_reason: 'Several live pages record this file as their origin and sync cannot prove they are one document; a person keeps the page that is the file\'s and soft-deletes the others (gbrain repair origin-twins --source <source> lists them with the commands), then syncs.' },
+ // #6948: an `origin_conflict` hold whose verdict carries a reason (sync-status.ts holdVerdict): nothing resolves it without a person.
+ { code: 'origin_conflict_decision', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: the pages differ, their ids conflict or none is the page the path names',
+ human_reason: 'Several live pages record this file as their origin and sync cannot prove they are one document; a person keeps the page that is the file\'s and soft-deletes the others (gbrain repair origin-twins --source <source> lists them with the commands), then syncs.' },
// Older releases recorded these as run failures; a rerun on this release holds the page instead.
{ code: 'revision_conflict', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
{ code: 'page_identity_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index d4392aad8c..bae5942e23 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -36,6 +36,7 @@ import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import type { ContentRefusal } from '../import-screen.ts';
import { RECOVERY_VERSION, type InvalidFrontmatterReason } from '../markdown.ts';
+import { ORIGIN_TWINS_AUTO_RESOLVE_KEY, originTwinsPreviewArgv, type OriginConflictReason } from './origin-twins.ts';
import { FENCE_REASONS, type FenceMessageLocation } from '../fence-repair/reasons.ts';
import type { FenceReason, FenceTier, GateLetter } from '../fence-repair/types.ts';
import { FENCE_VERSION } from '../fence-repair/refusal.ts';
@@ -69,7 +70,7 @@ export const GIT_HOLD_ESCALATE_MIN_SCREENED = 40;
type Exec = Pick<BrainEngine, 'executeRaw'>;
export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty' | 'file_drift'
- | 'legacy_slug_conflict';
+ | 'legacy_slug_conflict' | 'origin_conflict';
/** #6278: what the owner recorded about a preparation it gave up on (step names and vocabulary only, never content). */
export interface PreparationStallMeta {
request_id: string;
@@ -82,7 +83,7 @@ export interface PreparationStallMeta {
/** The `gbrain sync` arguments that resume the cursor with its stored options (after `sources retry-held`). */
sync_argv: string[];
}
-export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | 'explicit_id_conflict' | FenceReason;
+export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | 'explicit_id_conflict' | FenceReason | OriginConflictReason;
export interface GitHoldMeta {
reason?: GitHoldReason;
@@ -135,6 +136,10 @@ export interface GitHoldMeta {
blocked_on?: string;
/** #6727 `legacy_slug_conflict`: the live pages without a recorded origin whose slugs fold to the file's slug. */
legacy_slugs?: string[];
+ /** #6948 `origin_conflict`: the live pages recording the file as their origin, by id (no `reason`: the sync-time heal resolves it). */
+ origin_claimants?: Array<{ id: number; slug: string; revision: string }>;
+ /** #6948 `origin_conflict`: the slug the file's path gives (the page that keeps the origin). */
+ canonical_slug?: string;
}
/** #6188: why the last fence repair left a hold in place, and when the maintenance run tries it again (null: it does not). */
@@ -495,10 +500,11 @@ export async function holdBasisMoved(engine: Pick<BrainEngine, 'executeRaw'>, so
* re-screens whenever multimodal embedding is on, since managed sync then
* imports the image instead of holding it. #6712 PR 2: a `content_rejected`, `write_gate_rejected` or
* `purged_content` hold rests on a setting, an allow rule or a tombstone its fix lets the user change, so it
- * re-screens on every sync too. #6727: so does a `legacy_slug_conflict` hold, which rests on the legacy pages a person removes.
+ * re-screens on every sync too. #6727: so does a `legacy_slug_conflict` hold, which rests on the legacy pages a person removes. #6948: and an
+ * `origin_conflict` hold, which rests on the twin pages the heal, the repair or a person removes.
*/
export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, retried: boolean): boolean {
- return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression', 'content_rejected', 'write_gate_rejected', 'purged_content', 'legacy_slug_conflict'].includes(record.code)
+ return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression', 'content_rejected', 'write_gate_rejected', 'purged_content', 'legacy_slug_conflict', 'origin_conflict'].includes(record.code)
// #6712: a transient hold (the write owner stalled, not the file) is retried by every sync until it has been held HOLD_ATTEMPTS_NEEDS_HUMAN times.
|| (record.code === 'preparation_stalled' && (record.meta.attempts ?? 1) < HOLD_ATTEMPTS_NEEDS_HUMAN)
|| (record.code === 'managed_image_sync_unsupported' && isMultimodalEnabled())
@@ -700,6 +706,27 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
why: `Re-screens ${record.path} after the other pages are removed (this hold is re-screened on every sync).` },
verify };
}
+ case 'origin_conflict': {
+ const claimants = record.meta.origin_claimants ?? [];
+ const canonical = record.meta.canonical_slug ?? '<slug>';
+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ const then: Action = { argv: ['gbrain', 'sync', '--source', source, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Re-screens ${record.path} once one page records it (this hold is re-screened on every sync); the file then imports into that page.` };
+ const named = claimants.map(page => page.slug).join(', ');
+ if (!record.meta.reason) {
+ return { argv: originTwinsPreviewArgv(source), consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#origin_conflict',
+ why: `Pages ${named} all record ${record.path} as their origin and hold the same content, and ${canonical} is the page its path names, so the next managed sync resolves them by itself `
+ + `(${ORIGIN_TWINS_AUTO_RESOLVE_KEY}, on by default): each other page's links move to ${canonical}, its slug becomes an alias of ${canonical}, and it is soft-deleted without touching the file (restorable for 72 h). `
+ + `This preview writes nothing; its apply does the same now. The rest of the source is not blocked.`, then, verify };
+ }
+ const keep = claimants.find(page => page.slug === canonical);
+ const soft = claimants.filter(page => page !== keep).map(page => `gbrain delete --source-id ${source} --expected-revision ${page.revision} -- '${page.slug}'`);
+ return { argv: ['gbrain', 'get', '--source', source, '--', claimants[0]?.slug ?? canonical], consent: [], actor: 'user', requires_exclusive: false, docs: `docs/guides/write-refusals.md#origin_conflict-${record.meta.reason}`,
+ user_message: `Pages ${named} all record ${record.path} as their origin, and sync cannot prove they are one document (${record.meta.reason}), so it held only this file; the rest of the source keeps syncing. `
+ + `Read each page (gbrain get --source ${source} -- '<slug>'), pick the one that is this file's page and soft-delete each other one (the file stays, restorable for 72 h)`
+ + (soft.length ? `, for example: ${soft.join('; ')}` : '') + `; then run gbrain sync --source ${source} --no-pull. gbrain repair origin-twins --source ${source} lists the group and its commands.`,
+ why: 'Which page owns a file cannot be decided when the pages differ, carry different frontmatter ids, or none is the page the path names; sync never deletes a page it cannot prove is a duplicate.', then, verify };
+ }
case 'rename_held':
return repair(true, `The page that ${record.path} renames changed after the rename was recorded, so it was not moved; the preview proposes re-binding the rename to the current page for approval.`);
case 'frontmatter_slug_conflict':
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index a8cb0fdc0d..81e66bb1e0 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -18,7 +18,7 @@ import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext,
import { CHECKPOINT_MOVED_MESSAGE, checkpointRevival } from './sync-slug-mode.ts';
import { managedCursorKey, resolveManagedCursor } from './sync-cursor-key.ts';
import { isImageFilePath, isMultimodalEnabled } from '../sync.ts';
-import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';
+import { assertSyncPageOrigin, sameSyncOrigin, sharedOriginExit, syncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';
import { streamedSyncBodyRef, type SyncBodyRef } from './sync-streamed.ts';
@@ -47,7 +47,7 @@ import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';
import { isContentRefusal } from '../import-screen.ts';
import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';
import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
-import { driftBaselineContent, dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, streamedRefusalHold, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
+import { driftBaselineContent, dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, originConflictHold, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, streamedRefusalHold, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
import { frozenImageIntent, sameImageBytes } from './sync-image.ts';
import { fenceReceiptLocation } from '../fence-repair/refusal.ts';
import { managedSyncWriteDiagnostic, writeWaitOf } from './sync-write-diagnostic.ts';
@@ -353,6 +353,10 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
// are on; `sync.holds=fail` and company-brain cursors keep the refusals.
const holdsOn = !!run.screen && !cursor.companyPlan;
if (entry.legacySlugs?.length && !holdsOn) throw syncRunRefusal('page_identity_changed', 'Legacy pages sync cannot import into match the imported file.', retry, `${entry.path} imports as page ${entry.slug}, but pages ${entry.legacySlugs.join(', ')} of source ${cursor.sourceId}, imported from a file of that name, record no file (sync.holds=fail); keep the file's page, remove the others, then sync again.`);
+ if (entry.originConflict) {
+ if (!holdsOn) throw syncRunRefusal('page_identity_changed', 'Several pages claim the same imported origin.', retry, `Pages ${entry.originConflict.claimants.map(page => page.slug).join(', ')} of source ${cursor.sourceId} all record ${entry.path} as their origin (sync.holds=fail); ${sharedOriginExit(cursor.sourceId, entry.originConflict.claimants.map(page => page.slug))} Then sync again.`);
+ return { hold: originConflictHold(entry) };
+ }
const [occupant, snapshot] = await Promise.all([alreadyImportedAtOrigin(engine, cursor, entry, originScope).catch(error => {
if (!holdsOn || !(error instanceof OperationError) || error.code !== 'page_identity_changed') throw error;
return { originFault: error };
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index f7f1159099..099702684b 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -186,6 +186,22 @@ export function managedImageHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' |
message: `${entry.path} is an image, and managed sync imports images only with GBRAIN_EMBEDDING_MULTIMODAL=true (multimodal embedding is off on this install); the rest of the source synced.` }, content, blob);
}
+/**
+ * #6948: the hold of a file (an import or a deletion) several live pages record as their origin. Only this file waits:
+ * the rest of the source syncs. With no `reason` the pages are verified duplicates and the sync-time heal resolves them;
+ * a reason is a decision for a person. Re-screened on every sync, so the file imports once one page records it.
+ */
+export function originConflictHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld' | 'action' | 'originConflict'>): HeldEntry {
+ const conflict = entry.originConflict!;
+ const named = conflict.claimants.map(page => page.slug).join(', ');
+ const why = conflict.reason ? `sync cannot prove they are one document (${conflict.reason}), so a person decides which page keeps it`
+ : `they hold the same body and ${conflict.canonical} is the page its path names, so the sync-time heal keeps ${conflict.canonical} and soft-deletes the others (the file stays)`;
+ const held = heldEntry(entry, conflict.canonical, null, { code: 'origin_conflict', ...(conflict.reason ? { reason: conflict.reason } : {}),
+ message: `Pages ${named} all record ${entry.path} as their origin; ${why}. Only this file is held; the rest of the source synced.` }, null, null);
+ return { ...held, meta: { ...held.meta, origin_claimants: conflict.claimants.map(({ id, slug, revision }) => ({ id, slug, revision })), canonical_slug: conflict.canonical,
+ ...(entry.action === 'delete' ? { deleted: true as const } : {}) } };
+}
+
/** #5988: the hold of a file over the sync read bound, whose content is never read (#6529: shared with the image freeze). */
/** Wave B: the hold for a file its streamed preparation refused, by the receipt's content-refusal code and message. */
export function streamedRefusalHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null,
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 424ecbfe24..a0ced65ddd 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -209,6 +209,7 @@ async function retiredCursorStands(engine: BrainEngine, sourceId: string, incarn
export function holdVerdict(record: GitHoldRecord, auto: FenceAutoRepair | undefined, now = Date.now()): SyncFaultVerdict {
const escalation = holdEscalation(record, now);
const content = record.meta.content_repair ? { content_repair: { ...record.meta.content_repair, path: record.path, slug: record.slug } } : {};
+ if (record.code === 'origin_conflict' && record.meta.reason) return classifySyncFault({ code: record.code, detail: 'origin_conflict_decision', ...escalation });
const disposition = contentHoldDisposition(record, auto);
if (disposition.action !== 'listed' || disposition.state === 'owner') return classifySyncFault({ code: record.code, ...escalation, ...content });
const verdict = classifySyncFault({ code: record.code, ...escalation, detail: disposition.reason, ...content });
diff --git a/src/core/persistence/twin-merge.ts b/src/core/persistence/twin-merge.ts
new file mode 100644
index 0000000000..8aca80a71d
--- /dev/null
+++ b/src/core/persistence/twin-merge.ts
@@ -0,0 +1,138 @@
+/**
+ * One merge primitive for a duplicate page ("twin") that a surviving page replaces, used by `gbrain repair origin-twins`
+ * and the sync-time heal (#6948). It runs inside the caller's write with both page keys held and moves what other pages
+ * and the twin's own rows say about the twin to the survivor:
+ *
+ * 1. links in every role (from, to, origin) and dated link transitions, so manual and custom relationships the twin
+ * holds database-only survive it; links and transitions between the pair stay on the twin. The temporal
+ * relationship state of every touched key is recomputed;
+ * 2. timeline rows and timeline events that name the twin, raw data, file attachments, user-added tags (a survivor tag
+ * the import owns becomes user-added when the twin's was), free-text page aliases and facts other pages assert
+ * about the twin;
+ * 3. the twin's slug becomes a `slug_aliases` row for the survivor, so links written against it keep resolving;
+ * 4. the twin forgets its recorded file (`source_path`, `source_uri` cleared, marked `origin_twin`) and is soft-deleted:
+ * the file stays, the 72 h retention purge removes the twin database-only, and a restored twin writes or removes
+ * no file, so a restore can never claim the survivor's file again;
+ * 5. the twin's sync import record is dropped: it describes what the file imported into the twin.
+ *
+ * A row that lands on a survivor row with the same unique key is dropped only when it says the same thing (same payload)
+ * or is re-derived from page bodies (body and frontmatter links, their transitions). Anything else is distinct evidence
+ * the merge would lose, so `twinMergeConflicts` lists it and the merge refuses before writing (the group needs a person).
+ *
+ * Kept on the twin (they go with it when it is purged and come back if it is restored): its import-owned tags, chunks,
+ * embeddings, page versions and the projections of its own body. A page version of the twin is written first.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { opError } from '../ops/contract.ts';
+import { noteBelief } from '../belief/ledger.ts';
+import { recordRenameAlias } from '../page-state/rename-alias.ts';
+import { refreshRelationships, type RelationshipKey } from '../link-relationships.ts';
+import { SYNC_IMPORT_PROVENANCE_OP } from './sync-holds.ts';
+import { ORIGIN_TWIN_REASON } from './origin-twins.ts';
+
+/** Link provenances re-derived from page bodies and frontmatter: a survivor with the same body re-derives each one. */
+export const DERIVED_LINK_SOURCES = ['markdown', 'frontmatter', 'mentions', 'wikilink-resolved'];
+/** Transition producers re-derived from page bodies; `explicit` and `manual` are stated by a person. */
+const DERIVED_TRANSITION_PRODUCERS = ['timeline', 'frontmatter', 'inline', 'dream'];
+
+export interface TwinMergePage { page_id: number; slug: string }
+export interface TwinMergeResult { links_moved: number[]; facts_moved: number[]; transitions_moved: number; tags_moved: string[]; deduplicated: number }
+export interface TwinMergeConflict { table: 'links' | 'link_transitions' | 'timeline_entries' | 'raw_data'; id: number; detail: string }
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+
+const PAIR = 'NOT (from_page_id IN ($1::int, $2::int) AND to_page_id IN ($1::int, $2::int))';
+const MAP = (col: string) => `CASE WHEN ${col}=$1::int THEN $2::int ELSE ${col} END`;
+const TOUCHES = 'from_page_id IN ($1::int, $2::int) OR to_page_id IN ($1::int, $2::int) OR origin_page_id IN ($1::int, $2::int)';
+const MOVING = '(from_page_id=$1::int OR to_page_id=$1::int OR origin_page_id IS NOT DISTINCT FROM $1::int)';
+
+/** Moving rows of the twin that land on another row's unique key, with whether every such row says the same thing. */
+const LINK_LOSERS = `WITH m AS (
+ SELECT id, link_type, link_source, context, origin_field, link_kind, resolution_type, assertion_tense, ${MOVING} AS moving,
+ ${MAP('from_page_id')} AS f, ${MAP('to_page_id')} AS t, ${MAP('origin_page_id')} AS o
+ FROM links WHERE (${TOUCHES}) AND ${PAIR})
+ SELECT s.id, s.link_source, bool_and(s.context=k.context AND s.origin_field IS NOT DISTINCT FROM k.origin_field AND s.link_kind IS NOT DISTINCT FROM k.link_kind
+ AND s.resolution_type IS NOT DISTINCT FROM k.resolution_type AND s.assertion_tense IS NOT DISTINCT FROM k.assertion_tense) AS same
+ FROM m s JOIN m k ON s.moving AND k.id<>s.id AND k.f=s.f AND k.t=s.t AND k.link_type=s.link_type
+ AND k.link_source IS NOT DISTINCT FROM s.link_source AND k.o IS NOT DISTINCT FROM s.o AND (NOT k.moving OR k.id<s.id)
+ GROUP BY s.id, s.link_source`;
+
+const TRANSITION_LOSERS = `WITH m AS (
+ SELECT id, link_type, kind, occurred_on, producer, date_precision, ${MOVING} AS moving,
+ ${MAP('from_page_id')} AS f, ${MAP('to_page_id')} AS t, ${MAP('origin_page_id')} AS o
+ FROM link_transitions WHERE (${TOUCHES}) AND ${PAIR})
+ SELECT s.id, s.producer, bool_and(s.date_precision=k.date_precision) AS same
+ FROM m s JOIN m k ON s.moving AND k.id<>s.id AND k.f=s.f AND k.t=s.t AND k.link_type=s.link_type AND k.kind=s.kind
+ AND k.occurred_on=s.occurred_on AND k.producer=s.producer AND k.o IS NOT DISTINCT FROM s.o AND (NOT k.moving OR k.id<s.id)
+ GROUP BY s.id, s.producer`;
+
+/** Rows of the twin whose move would discard distinct evidence; empty when the merge loses nothing. Read-only. */
+export async function twinMergeConflicts(exec: Exec, survivorId: number, twinId: number): Promise<TwinMergeConflict[]> {
+ const params = [twinId, survivorId];
+ const links = (await exec.executeRaw<{ id: number; link_source: string | null; same: boolean }>(LINK_LOSERS, params))
+ .filter(row => !row.same && !DERIVED_LINK_SOURCES.includes(row.link_source ?? ''))
+ .map(row => ({ table: 'links' as const, id: Number(row.id), detail: `a ${row.link_source ?? 'legacy'} link whose context or metadata differs from the survivor's` }));
+ const transitions = (await exec.executeRaw<{ id: number; producer: string; same: boolean }>(TRANSITION_LOSERS, params))
+ .filter(row => !row.same && !DERIVED_TRANSITION_PRODUCERS.includes(row.producer))
+ .map(row => ({ table: 'link_transitions' as const, id: Number(row.id), detail: `a ${row.producer} relationship date whose precision differs from the survivor's` }));
+ const timeline = (await exec.executeRaw<{ id: number }>(`SELECT s.id FROM timeline_entries s JOIN timeline_entries o ON o.page_id=$2::int AND o.date=s.date
+ AND md5(o.summary)=md5(s.summary) AND o.source=s.source WHERE s.page_id=$1::int AND o.detail<>s.detail`, params))
+ .map(row => ({ table: 'timeline_entries' as const, id: Number(row.id), detail: 'a timeline entry whose detail differs from the survivor\'s' }));
+ const raw = (await exec.executeRaw<{ id: number; source: string }>(`SELECT s.id, s.source FROM raw_data s JOIN raw_data o ON o.page_id=$2::int AND o.source=s.source
+ WHERE s.page_id=$1::int AND o.data IS DISTINCT FROM s.data`, params))
+ .map(row => ({ table: 'raw_data' as const, id: Number(row.id), detail: `raw data of source ${row.source} that differs from the survivor's` }));
+ return [...links, ...transitions, ...timeline, ...raw];
+}
+
+async function relationshipKeys(exec: Exec, table: 'links' | 'link_transitions', pageIds: number[]): Promise<RelationshipKey[]> {
+ return (await exec.executeRaw<RelationshipKey>(`SELECT DISTINCT from_page_id, to_page_id, link_type FROM ${table}
+ WHERE from_page_id=ANY($1::int[]) OR to_page_id=ANY($1::int[])`, [pageIds])).map(row => ({ from_page_id: Number(row.from_page_id), to_page_id: Number(row.to_page_id), link_type: row.link_type }));
+}
+
+export async function mergeTwinInto(tx: BrainEngine, input: { sourceId: string; incarnation: string; survivor: TwinMergePage; twin: TwinMergePage }): Promise<TwinMergeResult> {
+ const { sourceId, survivor, twin } = input;
+ const params = [twin.page_id, survivor.page_id];
+ const conflicts = await twinMergeConflicts(tx, survivor.page_id, twin.page_id);
+ if (conflicts.length) {
+ throw opError('revision_conflict', 'The duplicate page holds evidence its survivor does not, so the merge was refused.',
+ `Merging ${twin.slug} into ${survivor.slug} in source ${sourceId} would discard ${conflicts.map(c => `${c.detail} (${c.table} ${c.id})`).join('; ')}. Nothing changed; the group needs a person (gbrain repair origin-twins --source ${sourceId}).`,
+ { reason: 'twin_evidence_conflicts' });
+ }
+ await tx.createVersion(twin.slug, { sourceId });
+ await tx.executeRaw('UPDATE pages SET source_path=NULL, source_uri=NULL, database_only_reason=$2 WHERE id=$1', [twin.page_id, ORIGIN_TWIN_REASON]);
+ const before = [...await relationshipKeys(tx, 'links', [twin.page_id]), ...await relationshipKeys(tx, 'link_transitions', [twin.page_id])];
+ const linkLosers = (await tx.executeRaw<{ id: number }>(LINK_LOSERS, params)).map(row => Number(row.id));
+ const transitionLosers = (await tx.executeRaw<{ id: number }>(TRANSITION_LOSERS, params)).map(row => Number(row.id));
+ if (linkLosers.length) await tx.executeRaw('DELETE FROM links WHERE id=ANY($1::int[])', [linkLosers]);
+ if (transitionLosers.length) await tx.executeRaw('DELETE FROM link_transitions WHERE id=ANY($1::bigint[])', [transitionLosers]);
+ const movedLinks = (await tx.executeRaw<{ id: number }>(`UPDATE links SET from_page_id=${MAP('from_page_id')}, to_page_id=${MAP('to_page_id')}, origin_page_id=${MAP('origin_page_id')}
+ WHERE ${MOVING} AND ${PAIR} RETURNING id`, params)).map(row => Number(row.id));
+ const movedTransitions = await tx.executeRaw(`UPDATE link_transitions SET from_page_id=${MAP('from_page_id')}, to_page_id=${MAP('to_page_id')}, origin_page_id=${MAP('origin_page_id')}
+ WHERE ${MOVING} AND ${PAIR} RETURNING id`, params);
+ const statements: Array<[string, unknown[]]> = [
+ [`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)`, params],
+ ['UPDATE timeline_entries SET page_id=$2 WHERE page_id=$1', params],
+ ['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)', params],
+ ['UPDATE timeline_entries SET event_page_id=$2 WHERE event_page_id=$1', params],
+ ['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)', params],
+ [`UPDATE tags o SET tag_source='added' WHERE o.page_id=$2 AND o.tag_source='frontmatter'
+ AND EXISTS (SELECT 1 FROM tags s WHERE s.page_id=$1 AND s.tag=o.tag AND s.tag_source='added')`, params],
+ ['UPDATE files SET page_id=$2, page_slug=$3 WHERE page_id=$1', [...params, survivor.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, survivor.slug]],
+ ];
+ for (const [sql, values] of statements) await tx.executeRaw(sql, values);
+ const tagsMoved = (await tx.executeRaw<{ tag: string }>(`UPDATE tags s SET page_id=$2 WHERE s.page_id=$1 AND s.tag_source IS DISTINCT FROM 'frontmatter'
+ AND NOT EXISTS (SELECT 1 FROM tags o WHERE o.page_id=$2 AND o.tag=s.tag) RETURNING tag`, params)).map(row => row.tag);
+ 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, survivor.slug])).map(row => Number(row.id));
+ await recordRenameAlias(tx, sourceId, twin.slug, survivor.slug);
+ const after = [...await relationshipKeys(tx, 'links', [survivor.page_id]), ...await relationshipKeys(tx, 'link_transitions', [survivor.page_id])];
+ await refreshRelationships(tx, [...before, ...after]);
+ noteBelief({ kind: 'transferred', fromSlug: twin.slug, table: 'links', ids: movedLinks });
+ noteBelief({ kind: 'transferred', fromSlug: twin.slug, table: 'facts', ids: factIds });
+ await tx.softDeletePage(twin.slug, { sourceId });
+ await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_IMPORT_PROVENANCE_OP, `${sourceId}:${input.incarnation}:${twin.page_id}`]);
+ return { links_moved: movedLinks, facts_moved: factIds, transitions_moved: movedTransitions.length, tags_moved: tagsMoved, deduplicated: linkLosers.length + transitionLosers.length };
+}
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 4f316511e7..0c71199781 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -37,7 +37,7 @@ import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';
import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'missing-tables'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/origin-twins-heal.ts b/src/core/repair/origin-twins-heal.ts
new file mode 100644
index 0000000000..0da4fffd70
--- /dev/null
+++ b/src/core/repair/origin-twins-heal.ts
@@ -0,0 +1,156 @@
+/**
+ * #6948: the sync-time heal of duplicate-origin twins. A file several live pages record as their origin is held by sync
+ * (`origin_conflict`); when they are verified duplicates (persistence/origin-twins.ts: the canonical page by path, one
+ * inline body, readable file, compatible ids, one visibility and trust tier, no slug-keyed withdrawals, no file at a
+ * twin's own slug path), nothing is ambiguous. So right after a managed sync of a source finishes and releases its drain
+ * lease, this re-reads each such hold's group from the database and the file at the last synced commit, re-runs the
+ * verdict, and merges each twin into the canonical page through the same coordinated write `gbrain repair origin-twins`
+ * applies (`resolveOriginTwin`). Each resolved file is scheduled for re-screen, so the next sync imports it.
+ *
+ * Guards, as #6865's slug heal (slug-autoheal.ts): skipped on dry runs and non-ok results, under remote submission
+ * authority, while the source has an unfinished sync cursor, and when `sync.origin_twins.auto_resolve` is false;
+ * bounded (`ORIGIN_HEAL_MAX_FILES`, `ORIGIN_HEAL_BUDGET_MS` or the caller's deadline). Mass valve: when the planned
+ * twin deletions are over half of the source's file-backed pages, nothing is merged and the repair preview is named.
+ * The heal never builds the index. Nothing here runs at upgrade; a failure never fails the sync.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { OperationContext } from '../ops/contract.ts';
+import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
+import { serr } from '../console-prefix.ts';
+import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
+import { readGitSourceHolds } from '../persistence/sync-holds.ts';
+import { ORIGIN_TWINS_AUTO_RESOLVE_KEY, originTwinsPreviewArgv, readOriginClaimants } from '../persistence/origin-twins.ts';
+import { syncOriginPath } from '../persistence/sync-origin.ts';
+import { groupPairs, massTwins, originGroupVerdict, originOwnerContext, resolveOriginTwin, type OriginTwinGroup } from './origin-twins.ts';
+import { repairRequestId } from './core.ts';
+
+export const ORIGIN_HEAL_BUDGET_MS = 60_000;
+export const ORIGIN_HEAL_MAX_FILES = 200;
+/** Twin pages the heal soft-deletes per source in any 24 h (merges by the repair count too); past it the repair preview is named. */
+export const ORIGIN_HEAL_DAILY_MAX = 1000;
+const FALSE = /^(false|0|off|no)$/i;
+const TRUE = /^(true|1|on|yes)$/i;
+const OK_STATUSES: ReadonlyArray<SyncResult['status']> = ['synced', 'first_sync', 'up_to_date'];
+
+/** `gbrain config set` refusal text for a value that is not a boolean; null when it is one. */
+export function originAutoResolveValueRefusal(value: string): string | null {
+ return TRUE.test(value.trim()) || FALSE.test(value.trim()) ? null : `${ORIGIN_TWINS_AUTO_RESOLVE_KEY} must be true or false (got "${value}"). Nothing was written.`;
+}
+
+export interface OriginHealReport {
+ /** Held files whose twins were merged into the canonical page; each imports on the next sync. */
+ resolved: number;
+ /** Twin pages soft-deleted by those merges. */
+ twins_merged: number;
+ pending: number;
+ failed: number;
+ left_by_reason: Record<string, number>;
+ /** Up to 20 resolved files. */
+ resolved_paths: string[];
+ /** One receipt per merged twin (slugs, moved counts, dropped frontmatter, restore argv), up to 20. */
+ receipts: Array<Record<string, unknown>>;
+ skipped?: 'disabled' | 'remote_authority' | 'sync_unfinished' | 'not_owner_host' | 'mass_valve' | 'daily_cap';
+ notice: string;
+ preview_argv: string[];
+ opt_out_argv: string[];
+}
+
+async function unfinishedCursor(engine: BrainEngine, sourceId: string): Promise<boolean> {
+ const rows = await engine.executeRaw(`SELECT 1 FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'
+ AND completed_keys->0->>'sourceId'=$1 LIMIT 1`, [sourceId]);
+ return rows.length > 0;
+}
+
+function skipReason(skipped: NonNullable<OriginHealReport['skipped']>): string {
+ if (skipped === 'disabled') return `${ORIGIN_TWINS_AUTO_RESOLVE_KEY} is false`;
+ if (skipped === 'remote_authority') return 'this sync runs under a remote job or agent';
+ if (skipped === 'sync_unfinished') return 'the source still has an unfinished sync cursor';
+ if (skipped === 'mass_valve') return "the twins are over half of the source's file-backed pages";
+ if (skipped === 'daily_cap') return `the heal already merged ${ORIGIN_HEAL_DAILY_MAX} twin page(s) of this source in the last 24 h`;
+ return 'this host does not own the source checkout';
+}
+
+function noticeOf(sourceId: string, r: Omit<OriginHealReport, 'notice' | 'preview_argv' | 'opt_out_argv'>): string {
+ const preview = originTwinsPreviewArgv(sourceId).join(' ');
+ if (r.skipped) return `[sync] ${r.pending} file(s) of source ${sourceId} are recorded by several live pages; sync left them held because ${skipReason(r.skipped)}. Preview the fix with ${preview} (read-only).`;
+ const left = Object.values(r.left_by_reason).reduce((a, b) => a + b, 0);
+ const more = r.pending ? `; ${r.pending} more wait for the next sync` : '';
+ const failed = r.failed ? `; ${r.failed} failed (${preview} shows why)` : '';
+ const person = left ? `; ${left} held file(s) need a person (${preview})` : '';
+ return `[sync] resolved ${r.resolved} file(s) of source ${sourceId} recorded by duplicate pages: ${r.twins_merged} twin page(s) merged into the page each path names `
+ + `(links moved, slug kept as an alias, soft-deleted without touching the file; restorable for 72 h)${more}${failed}${person}. Opt out: gbrain config set ${ORIGIN_TWINS_AUTO_RESOLVE_KEY} false.`;
+}
+
+/** The post-sync heal of one managed source; returns the result with the report. Never throws. */
+export async function healOriginTwinsAfterManagedSync(engine: BrainEngine, outer: SyncOpts, result: SyncResult, now: () => number = Date.now): Promise<SyncResult> {
+ if (outer.dryRun || !OK_STATUSES.includes(result.status)) return result;
+ const sourceId = outer.sourceId ?? 'default';
+ try {
+ const holds = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.code === 'origin_conflict');
+ if (!holds.length) return result;
+ const base = { resolved: 0, twins_merged: 0, pending: holds.length, failed: 0, left_by_reason: {} as Record<string, number>, resolved_paths: [] as string[], receipts: [] as Array<Record<string, unknown>> };
+ const authority = currentSubmissionAuthority();
+ const skip: OriginHealReport['skipped'] = FALSE.test(String(await engine.getConfig(ORIGIN_TWINS_AUTO_RESOLVE_KEY) ?? '').trim()) ? 'disabled'
+ : authority && authority.kind !== 'application' ? 'remote_authority' : await unfinishedCursor(engine, sourceId) ? 'sync_unfinished' : undefined;
+ const context = skip ? null : await originOwnerContext(engine, sourceId);
+ if (skip || !context?.ok) return withReport(result, sourceId, { ...base, skipped: skip ?? 'not_owner_host' });
+ const groups: Array<{ path: string; group: OriginTwinGroup }> = [];
+ for (const hold of [...holds].sort((a, b) => a.path.localeCompare(b.path)).slice(0, ORIGIN_HEAL_MAX_FILES)) {
+ const origin = syncOriginPath(hold.source_path ?? hold.path);
+ const live = await engine.executeRaw<{ id: number; source_path: string }>('SELECT id, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND id=ANY($2::bigint[])',
+ [sourceId, (hold.meta.origin_claimants ?? []).map(page => page.id)]);
+ const claimants = await readOriginClaimants(engine, sourceId, live.map(row => Number(row.id)));
+ const verdict = claimants.length > 1 ? await originGroupVerdict(engine, context, origin, claimants) : null;
+ if (!verdict || verdict.verdict !== 'resolve') {
+ const reason = verdict && verdict.verdict === 'hold' ? verdict.reason : 'no_longer_twins';
+ base.left_by_reason[reason] = (base.left_by_reason[reason] ?? 0) + 1;
+ base.pending--;
+ continue;
+ }
+ const pathOf = new Map(live.map(row => [Number(row.id), row.source_path]));
+ groups.push({ path: hold.path, group: { source_id: sourceId, source_path: origin, canonical: verdict.canonical, reason: null,
+ claimants: [verdict.survivor, ...verdict.twins].map(page => ({ page_id: page.id, slug: page.slug, revision: page.revision, source_path: pathOf.get(page.id)! })) } });
+ }
+ const [counted] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);
+ if (massTwins(groups.reduce((n, entry) => n + entry.group.claimants.length - 1, 0), Number(counted?.n ?? 0))) return withReport(result, sourceId, { ...base, skipped: 'mass_valve' });
+ const [today] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND database_only_reason='origin_twin'
+ AND deleted_at > now() - interval '24 hours'`, [sourceId]);
+ let budget = ORIGIN_HEAL_DAILY_MAX - Number(today?.n ?? 0);
+ if (budget <= 0) return withReport(result, sourceId, { ...base, skipped: 'daily_cap' });
+ const { loadConfig } = await import('../config.ts');
+ const ctx = { engine, config: loadConfig() ?? { engine: engine.kind }, logger: { info: () => {}, warn: (m: string) => serr(m), error: (m: string) => serr(m) },
+ remote: false, dryRun: false, sourceId } as unknown as OperationContext;
+ const deadline = Math.min(now() + ORIGIN_HEAL_BUDGET_MS, outer.deadlineAtMs ?? Infinity);
+ const healed: string[] = [];
+ for (const { path, group } of groups) {
+ if (now() >= deadline || outer.signal?.aborted || budget < group.claimants.length - 1) break;
+ base.pending--;
+ budget -= group.claimants.length - 1;
+ let all = true;
+ for (const pair of groupPairs(group)) {
+ try {
+ const outcome = await resolveOriginTwin(ctx, pair, context.owner,
+ () => repairRequestId(ctx, 'origin-twins', { source_id: sourceId, slug: pair.twin.slug }, `merge:${pair.survivor.revision}:${pair.twin.revision}`));
+ if (!outcome.applied) { all = false; base.left_by_reason[outcome.outcome] = (base.left_by_reason[outcome.outcome] ?? 0) + 1; break; }
+ base.twins_merged++;
+ if (base.receipts.length < 20 && outcome.detail) base.receipts.push(outcome.detail);
+ } catch (error) {
+ all = false; base.failed++;
+ serr(`[sync] could not resolve the duplicate pages of ${path}: ${error instanceof Error ? error.message : String(error)}`);
+ break;
+ }
+ }
+ if (all) { healed.push(path); base.resolved++; }
+ }
+ return withReport(result, sourceId, { ...base, resolved_paths: healed.slice(0, 20) });
+ } catch (error) {
+ serr(`[sync] the duplicate-origin heal of source ${sourceId} did not run (${error instanceof Error ? error.message : String(error)}); gbrain repair origin-twins --source ${sourceId} resolves them.`);
+ return result;
+ }
+}
+
+function withReport(result: SyncResult, sourceId: string, report: Omit<OriginHealReport, 'notice' | 'preview_argv' | 'opt_out_argv'>): SyncResult {
+ const notice = noticeOf(sourceId, report);
+ if (report.resolved || report.failed || report.skipped === 'mass_valve' || report.skipped === 'remote_authority') serr(notice);
+ return { ...result, origin_twins_resolved: { ...report, notice, preview_argv: originTwinsPreviewArgv(sourceId), opt_out_argv: ['gbrain', 'config', 'set', ORIGIN_TWINS_AUTO_RESOLVE_KEY, 'false'] } };
+}
diff --git a/src/core/repair/origin-twins.ts b/src/core/repair/origin-twins.ts
new file mode 100644
index 0000000000..926e22ee8c
--- /dev/null
+++ b/src/core/repair/origin-twins.ts
@@ -0,0 +1,390 @@
+/**
+ * `gbrain repair origin-twins --source <id>` (#6948): resolve live pages that record the same origin (`source_path`).
+ *
+ * Explicit-only, preview-bound, trusted local CLI on the source's owner host. The preview lists every twin group of the
+ * source (the stored spelling, and the legacy `<scope>/<origin>` spelling of a scoped source-root source), each with
+ * the shared verdict (`decideOriginTwins`, persistence/origin-twins.ts): verified duplicates are `resolve` items, any
+ * other group is a decision listed with its reason and the commands a person uses. `--apply --expect <hash> --yes`
+ * resolves exactly the approved items, one coordinated write per twin (`managed_maintenance_resolve_origin_twin`; an
+ * unmanaged brain does the same in one maintenance transaction):
+ *
+ * - `merge` (verified duplicates, also what the sync-time heal runs): `mergeTwinInto` re-points what other pages say
+ * about the twin to the survivor, records the twin's slug as an alias, clears its origin, marks it database-only
+ * (`origin_twin`, so a restore writes no file and the purge removes none) and soft-deletes it;
+ * - `detach` (a person's `--slug <keep>` choice on a held group): the other claimants forget the file and are marked
+ * `origin_twin`; they stay live with their content, links and history, so nothing is lost.
+ *
+ * Re-checked under both page keys (ids, slugs, revisions, both still claimants, a merge's verdict still `resolve`);
+ * a moved pair is skipped `changed_since_preview`. Refused off the owner host, and when the planned twins are over
+ * half of the source's file-backed pages (`GBRAIN_ALLOW_MASS_RECONCILE=1` overrides). Once no group is left in the
+ * brain, the apply builds `pages_live_origin_key` (persistence/origin-index.ts).
+ */
+import { readFileSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { realpathSync } from 'node:fs';
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
+import { authorizeWrite } from '../persistence/authority.ts';
+import { prepareCoreGuard } from '../persistence/core-guard.ts';
+import { existingLocalHostId } from '../persistence/identity.ts';
+import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { decideOriginTwins, ORIGIN_TWIN_REASON, readOriginClaimants, slugPathOccupied, type OriginClaimant, type OriginConflictReason, type OriginTwinVerdict } from '../persistence/origin-twins.ts';
+import { mergeTwinInto, twinMergeConflicts } from '../persistence/twin-merge.ts';
+import { buildOriginIndexIfClean, originTwinsRepairCommand } from '../persistence/origin-index.ts';
+import { legacySyncOrigin, sameSyncOrigin, syncOriginPath, type SyncOriginScope } from '../persistence/sync-origin.ts';
+import { frontmatterIdentity } from '../sync-rename-identity.ts';
+import { scannerSlugRootMode } from '../write-through.ts';
+import { syncGit } from '../persistence/sync-discovery.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';
+
+export const ORIGIN_TWINS_INTENT = 'managed_maintenance_resolve_origin_twin';
+/** Groups one preview lists; a larger set is applied in rounds (preview, apply, preview again). */
+export const ORIGIN_TWINS_LIMIT = 1000;
+export const ORIGIN_TWINS_PURGE_FUSE_HOURS = 72;
+/** The migration that builds the index; the repair builds it the same way once the brain is clean. */
+const ORIGIN_INDEX_MIGRATION = 257;
+const DOCS = 'docs/guides/repair.md#origin-twins';
+
+export interface TwinPage { page_id: number; slug: string; revision: string }
+export type OriginTwinMode = 'merge' | 'detach';
+/** One coordinated write: the twin gives up the origin to the survivor. */
+export interface OriginTwinPair { source_id: string; source_path: string; twin_path: string; survivor: TwinPage; twin: TwinPage; mode: OriginTwinMode }
+export interface OriginTwinGroup { source_id: string; source_path: string; canonical: string; claimants: Array<TwinPage & { source_path: string }>; reason: OriginConflictReason | null }
+
+interface ApprovedPair extends OriginTwinPair { owner: GhostOwner; selection: string[] }
+interface PairItem extends RepairItem { pair: OriginTwinPair; owner: GhostOwner; hash: string; last: boolean }
+type OwnerContext = { ok: true; root: string; gitRoot: string; scope: SyncOriginScope; owner: GhostOwner; commit: string | null } | { ok: false; reason: 'not_applicable' | 'not_owner_host' };
+
+const previewFix = (sourceId: string) => readFix('Previews the duplicate-origin groups of the source again; writes nothing.', { argv: ['gbrain', 'repair', 'origin-twins', '--source', sourceId, '--json'] });
+
+/** The consent payload of `--apply --expect <hash>` (registry `consentText`). */
+export const ORIGIN_TWINS_CONSENT_TEXT = {
+ what: 'Resolve each previewed duplicate-origin group: the canonical page keeps the file; each other page gives it up',
+ why: 'Several live pages record the same file, which held that file out of every sync; the preview listed each group with its pages, revisions and verdict.',
+ risk: `A merged twin's inbound links, aliases, tags and facts others assert move to the surviving page, its slug becomes an alias, and it is soft-deleted (the file stays) and purged ${ORIGIN_TWINS_PURGE_FUSE_HOURS} h later; gbrain restore brings back its text as a database-only page, and moved references stay on the survivor. A detached page only forgets the file and stays live.`,
+ user_message: `Resolve the previewed duplicate-origin groups? Merged twins are soft-deleted (the file stays) and purged after ${ORIGIN_TWINS_PURGE_FUSE_HOURS} h`,
+};
+
+/** The sync mass-delete valve (#2828) over planned twin deletions (pages, not groups). */
+export function massTwins(twins: number, fileBacked: number): boolean {
+ return fileBacked > MASS_RECONCILE_MIN_PAGES && twins > fileBacked * MASS_RECONCILE_RATIO;
+}
+
+const sameOwner = (a: GhostOwner | undefined, b: GhostOwner) => !!a && a.host_id === b.host_id && a.worktree_id === b.worktree_id
+ && a.owner_epoch === b.owner_epoch && a.source_incarnation === b.source_incarnation;
+
+export async function originOwnerContext(engine: BrainEngine, sourceId: string): Promise<OwnerContext> {
+ const hostId = existingLocalHostId();
+ const binding = await getWorktreeBinding(engine, sourceId, hostId);
+ if (!binding) return { ok: false, reason: 'not_applicable' };
+ if (!hostId || !binding.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') return { ok: false, reason: 'not_owner_host' };
+ const root = join(binding.local_path, binding.relative_path);
+ let gitRoot: string;
+ try { gitRoot = syncGit(root, ['rev-parse', '--show-toplevel']).trim(); } catch { return { ok: false, reason: 'not_owner_host' }; }
+ const slugMode = await scannerSlugRootMode(engine, sourceId, root);
+ const scope = relative(realpathSync.native(gitRoot), realpathSync.native(root)).split('\\').join('/');
+ const [source] = await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]);
+ return { ok: true, root, gitRoot, scope: { sourceId, root, scope, slugMode }, commit: source?.last_commit ?? null,
+ owner: { host_id: hostId, worktree_id: binding.worktree_id, owner_epoch: String(binding.owner_epoch), source_incarnation: binding.source_incarnation } };
+}
+
+function ownerRefusal(sourceId: string, reason: 'not_applicable' | 'not_owner_host'): OperationError {
+ return opError('not_owner_host', `Duplicate-origin groups of source ${sourceId} can only be checked and resolved on its canonical owner host.`,
+ reason === 'not_applicable' ? `Source ${sourceId} has no canonical checkout bound, so its files cannot be read; nothing was listed or changed.`
+ : `This host does not own source ${sourceId}'s active canonical worktree; nothing was listed or changed. Run ${originTwinsRepairCommand(sourceId)} on the owner host (writer status names it).`,
+ { reason, fix: readFix('Shows the source\'s canonical binding and owner host, read-only.', { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }), docs: DOCS });
+}
+
+/** The file's explicit frontmatter id at the last synced commit (the bytes sync screened), else the working tree; undefined when unreadable. */
+export function originFileId(context: Extract<OwnerContext, { ok: true }>, origin: string): string | null | undefined {
+ const gitPath = context.scope.slugMode === 'source-root' && context.scope.scope ? `${context.scope.scope}/${origin}` : origin;
+ try {
+ const bytes = context.commit ? syncGit(context.gitRoot, ['show', `${context.commit}:${gitPath}`]) : readFileSync(join(context.gitRoot, gitPath), 'utf8');
+ return frontmatterIdentity(bytes).id;
+ } catch { return undefined; }
+}
+
+/**
+ * The verdict of one group of live claimants of an origin: `decideOriginTwins` over the rows and the file, then, for a
+ * group it would resolve, whether any twin holds evidence the merge would lose (`twin_evidence_conflicts`).
+ */
+export async function originGroupVerdict(engine: BrainEngine, context: Extract<OwnerContext, { ok: true }>, origin: string, claimants: OriginClaimant[]): Promise<OriginTwinVerdict> {
+ const verdict = decideOriginTwins({ sourcePath: origin, claimants, fileId: originFileId(context, origin),
+ slugPathOccupied: slugPathOccupied({ root: context.root, gitRoot: context.gitRoot, slugMode: context.scope.slugMode }) });
+ if (verdict.verdict !== 'resolve') return verdict;
+ for (const twin of verdict.twins) {
+ if ((await twinMergeConflicts(engine, verdict.survivor.id, twin.id)).length) {
+ return { verdict: 'hold', canonical: verdict.canonical, reason: 'twin_evidence_conflicts', claimants: [verdict.survivor, ...verdict.twins].sort((a, b) => a.id - b.id) };
+ }
+ }
+ return verdict;
+}
+
+export interface OriginTwinScan { owner: GhostOwner; groups: OriginTwinGroup[]; file_backed: number; truncated: boolean; context: Extract<OwnerContext, { ok: true }> }
+
+/** Every live twin group of one source (stored spelling and legacy spelling), at most `ORIGIN_TWINS_LIMIT`. */
+export async function scanOriginTwins(engine: BrainEngine, sourceId: string): Promise<OriginTwinScan> {
+ const context = await originOwnerContext(engine, sourceId);
+ if (!context.ok) throw ownerRefusal(sourceId, context.reason);
+ const byOrigin = new Map<string, Array<{ id: number; source_path: string }>>();
+ const exact = await engine.executeRaw<{ source_path: string; ids: number[]; paths: string[] }>(`SELECT source_path, array_agg(id ORDER BY id) AS ids, array_agg(source_path ORDER BY id) AS paths
+ FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL GROUP BY source_path HAVING count(*) > 1 ORDER BY source_path LIMIT ${ORIGIN_TWINS_LIMIT + 1}`, [sourceId]);
+ for (const row of exact) byOrigin.set(row.source_path, row.ids.map((id, i) => ({ id: Number(id), source_path: row.paths[i]! })));
+ const legacyPrefix = legacySyncOrigin(context.scope, 'x') ? `${context.scope.scope}/` : null;
+ if (legacyPrefix) {
+ const pairs = await engine.executeRaw<{ legacy_id: number; legacy_path: string; legacy_slug: string; origin: string }>(`SELECT l.id AS legacy_id, l.source_path AS legacy_path, l.slug AS legacy_slug, o.source_path AS origin
+ FROM pages l JOIN pages o ON o.source_id=l.source_id AND l.source_path = $2 || o.source_path
+ WHERE l.source_id=$1 AND l.deleted_at IS NULL AND o.deleted_at IS NULL AND l.id <> o.id LIMIT ${ORIGIN_TWINS_LIMIT + 1}`, [sourceId, legacyPrefix]);
+ for (const pair of pairs) {
+ let same = false;
+ try { same = sameSyncOrigin(pair.legacy_path, pair.origin, context.scope, pair.legacy_slug); } catch { same = true; }
+ if (!same) continue;
+ const group = byOrigin.get(pair.origin) ?? (await engine.executeRaw<{ id: number; source_path: string }>(
+ 'SELECT id, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path=$2 ORDER BY id', [sourceId, pair.origin])).map(row => ({ id: Number(row.id), source_path: row.source_path }));
+ if (!group.some(page => page.id === Number(pair.legacy_id))) group.push({ id: Number(pair.legacy_id), source_path: pair.legacy_path });
+ byOrigin.set(pair.origin, group);
+ }
+ }
+ const truncated = byOrigin.size > ORIGIN_TWINS_LIMIT;
+ const groups: OriginTwinGroup[] = [];
+ for (const [origin, pages] of [...byOrigin].sort(([a], [b]) => a.localeCompare(b)).slice(0, ORIGIN_TWINS_LIMIT)) {
+ const claimants = await readOriginClaimants(engine, sourceId, pages.map(page => page.id));
+ if (claimants.length < 2) continue;
+ const pathOf = new Map(pages.map(page => [page.id, page.source_path]));
+ const listed = claimants.map(page => ({ page_id: page.id, slug: page.slug, revision: page.revision, source_path: pathOf.get(page.id)! }));
+ let confined: string;
+ try { confined = syncOriginPath(origin); } catch {
+ groups.push({ source_id: sourceId, source_path: origin, canonical: '', reason: 'no_canonical_claimant', claimants: listed });
+ continue;
+ }
+ const verdict = await originGroupVerdict(engine, context, confined, claimants);
+ groups.push({ source_id: sourceId, source_path: origin, canonical: verdict.canonical, reason: verdict.verdict === 'resolve' ? null : verdict.reason, claimants: listed });
+ }
+ const [counted] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);
+ return { owner: context.owner, groups, file_backed: Number(counted?.n ?? 0), truncated, context };
+}
+
+/** The writes a group needs: every non-survivor gives the origin to `keep` (the canonical page for a verified group). */
+export function groupPairs(group: OriginTwinGroup, keep?: string): OriginTwinPair[] {
+ const survivor = group.claimants.find(page => page.slug === (keep ?? group.canonical));
+ if (!survivor || (!keep && group.reason)) return [];
+ const mode: OriginTwinMode = group.reason ? 'detach' : 'merge';
+ return group.claimants.filter(page => page !== survivor).map(twin => ({ source_id: group.source_id, source_path: group.source_path, twin_path: twin.source_path,
+ survivor: { page_id: survivor.page_id, slug: survivor.slug, revision: survivor.revision }, twin: { page_id: twin.page_id, slug: twin.slug, revision: twin.revision }, mode }));
+}
+
+function decisionCommands(group: OriginTwinGroup): string[] {
+ return [...group.claimants.map(page => `gbrain get --source ${group.source_id} -- '${page.slug}'`),
+ `Pick the page that is ${group.source_path}'s, then: ${originTwinsRepairCommand(group.source_id)} --slug '<kept-slug>' (the others forget the file and stay live; nothing is deleted)`];
+}
+
+function hashParts(scope: RepairScope, owner: GhostOwner, pairs: OriginTwinPair[], groups: OriginTwinGroup[]) {
+ return { kind: 'origin-twins-v1', brain_id: scope.brain_id, selection: { source_ids: scope.source_ids }, owner, pairs, decisions: groups.filter(group => group.reason) };
+}
+
+function item(pair: OriginTwinPair, owner: GhostOwner, hash: string, last: boolean): PairItem {
+ return { cursor: { phase: 1, id: pair.twin.page_id }, source_id: pair.source_id, slug: pair.twin.slug, chars: 0, action: `${pair.mode}:origin_twin`, pair, owner, hash, last };
+}
+
+const pairLine = (p: OriginTwinPair) => p.mode === 'merge'
+ ? `${p.survivor.slug} (id ${p.survivor.page_id}) keeps ${p.source_path}; twin ${p.twin.slug} (id ${p.twin.page_id}, revision ${p.twin.revision}) holds the same body and is merged into it`
+ : `${p.survivor.slug} (id ${p.survivor.page_id}) keeps ${p.source_path}; ${p.twin.slug} (id ${p.twin.page_id}) forgets the file and stays live`;
+
+export const originTwinsRepair: RepairHandler = {
+ kind: 'origin-twins',
+ embeds: false,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ if (opts?.remote === true) throw trustedCliRequired('gbrain repair origin-twins runs only from the trusted local CLI on the brain host.');
+ if (scope.source_ids.length !== 1) {
+ throw opError('invalid_params', 'gbrain repair origin-twins needs --source <id>.',
+ 'Duplicate-origin groups are checked on each source\'s own canonical owner host; name one source, e.g. gbrain repair origin-twins --source default.',
+ { fix: readFix('Lists the registered sources.', { argv: ['gbrain', 'sources', 'list', '--json'] }), docs: DOCS });
+ }
+ const sourceId = scope.source_ids[0]!;
+ const command = originTwinsRepairCommand(sourceId);
+ const keep = opts?.slugs?.length ? opts.slugs : undefined;
+ if (keep && keep.length !== 1) throw opError('invalid_params', 'gbrain repair origin-twins --slug names the one page that keeps a file.', `Name one slug per run: ${command} --slug '<kept-slug>'.`, { fix: previewFix(sourceId), docs: DOCS });
+ const scan = await scanOriginTwins(engine, sourceId);
+ const chosen = keep ? scan.groups.filter(group => group.claimants.some(page => page.slug === keep[0])) : scan.groups;
+ const pairs = chosen.flatMap(group => groupPairs(group, keep?.[0]));
+ const mass = massTwins(pairs.filter(pair => pair.mode === 'merge').length, scan.file_backed);
+ if (!opts?.apply) {
+ const hash = previewHash(hashParts(scope, scan.owner, pairs, scan.groups));
+ if (pairs.length) await saveApprovedSet<ApprovedPair>(engine, { command: 'origin-twins', hash }, pairs.map(pair => ({ ...pair, owner: scan.owner, selection: scope.source_ids })));
+ const decisions = scan.groups.filter(group => group.reason && !keep);
+ const warnings = [
+ ...(keep && !chosen.length ? [`No duplicate-origin group of source ${sourceId} has a page ${keep[0]}.`] : []),
+ ...(mass ? [`${pairs.length} twin(s) against ${scan.file_backed} file-backed page(s) (more than ${Math.round(MASS_RECONCILE_RATIO * 100)}%): the apply refuses unless GBRAIN_ALLOW_MASS_RECONCILE=1; check the source first.`] : []),
+ ...(scan.truncated ? [`More groups may exist past the first ${ORIGIN_TWINS_LIMIT} listed; apply this set, then preview again.`] : []),
+ ...(decisions.length ? [`${decisions.length} group(s) need a person's decision and are never resolved by this apply; each lists the commands to decide it.`] : []),
+ ...(pairs.some(pair => pair.mode === 'merge') ? [ORIGIN_TWINS_CONSENT_TEXT.risk] : []),
+ ...(!scan.groups.length ? ['No duplicate-origin group in this source; --apply builds the pages_live_origin_key index once no source has one.'] : []),
+ ];
+ return { warnings, items: pairs.map((pair, index) => item(pair, scan.owner, hash, index === pairs.length - 1)), preview_hash: hash,
+ residuals: { groups: scan.groups.length, decisions: decisions.length, file_backed: scan.file_backed },
+ listing: [...pairs.map(pair => ({ item: `${pair.source_id}:${pair.twin.slug}`, class: pair.mode, detail: pairLine(pair) })),
+ ...decisions.map(group => ({ item: `${group.source_id}:${group.source_path}`, class: `decision:${group.reason}`,
+ detail: `${group.claimants.map(page => `${page.slug} (id ${page.page_id}, revision ${page.revision})`).join(', ')} record ${group.source_path}` }))],
+ details: { decisions: decisions.map(group => ({ ...group, commands: decisionCommands(group) })), mass_merge: mass, truncated: scan.truncated, purge_fuse_hours: ORIGIN_TWINS_PURGE_FUSE_HOURS, docs: DOCS } };
+ }
+ if (!opts.expect) {
+ throw opError('invalid_params', 'gbrain repair origin-twins --apply resolves only the set a preview printed.',
+ `Preview first: ${command} — then, after the user agrees, run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`, { fix: previewFix(sourceId), docs: DOCS });
+ }
+ const approved = await loadApprovedSet<ApprovedPair>(engine, { command: 'origin-twins', hash: opts.expect, previewCommand: command,
+ emptyHash: async () => previewHash(hashParts(scope, scan.owner, [], scan.groups)) });
+ if (approved.items.some(pair => JSON.stringify(pair.selection) !== JSON.stringify(scope.source_ids) || !sameOwner(scan.owner, pair.owner))) throw previewChangedError(opts.expect, command);
+ if (massTwins(approved.items.filter(pair => pair.mode === 'merge').length, scan.file_backed) && !massReconcileAllowed()) {
+ throw opError('origin_twin_mass_merge_refused', `Refusing to merge ${approved.items.length} duplicate-origin twin(s) of source ${sourceId}: that soft-deletes more than ${Math.round(MASS_RECONCILE_RATIO * 100)}% of its ${scan.file_backed} file-backed page(s).`,
+ 'That many twins at once almost always means a re-import under another slug or the wrong checkout, not a backlog; nothing was changed. If it is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.',
+ { fix: previewFix(sourceId), docs: DOCS });
+ }
+ if (!approved.items.length) {
+ const built = await buildOriginIndexIfClean(engine, ORIGIN_INDEX_MIGRATION);
+ return { items: [], preview_hash: opts.expect, residuals: { index_present: built.state === 'present' ? 1 : 0 }, warnings: built.state === 'pending'
+ ? [`pages_live_origin_key stays pending: ${built.sources.map(s => `source ${s.source_id} still has ${s.groups} group(s)`).join(', ')}.`] : [`pages_live_origin_key: ${built.state}.`] };
+ }
+ const items = approved.items.map(({ selection: _selection, owner, ...pair }, index) => item(pair, owner, opts.expect!, index === approved.items.length - 1));
+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { pair, owner, hash, last } = entry as PairItem;
+ const outcome = await resolveOriginTwin(ctx, pair, owner,
+ () => repairRequestId(ctx, 'origin-twins', { source_id: pair.source_id, slug: pair.twin.slug }, `${pair.mode}:${pair.survivor.revision}:${pair.twin.revision}`));
+ if (last) {
+ await clearApprovedSet(ctx.engine, { command: 'origin-twins', hash });
+ const built = await buildOriginIndexIfClean(ctx.engine, ORIGIN_INDEX_MIGRATION);
+ ctx.logger.info(built.state === 'pending' ? `pages_live_origin_key stays pending: ${built.sources.map(s => `source ${s.source_id} still has ${s.groups} group(s)`).join(', ')}` : `pages_live_origin_key: ${built.state}`);
+ }
+ return outcome;
+ },
+ render(details) {
+ const decisions = (details.decisions as Array<OriginTwinGroup & { commands: string[] }> | undefined) ?? [];
+ return [...decisions.flatMap(group => [` decision ${group.reason}: ${group.claimants.map(page => page.slug).join(', ')} record ${group.source_path}`,
+ ...group.commands.map(command => ` ${command}`)]),
+ ` each merged twin: soft-deleted (its file stays), purged after ${details.purge_fuse_hours} h; guide: ${details.docs}`];
+ },
+};
+
+const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });
+
+/** Whether the pair is still the approved one (and, for a merge, still verified duplicates); otherwise why not. */
+export async function originPairNow(engine: BrainEngine, pair: OriginTwinPair, owner: GhostOwner | null): Promise<string | null> {
+ const context = await originOwnerContext(engine, pair.source_id);
+ if (!context.ok || (owner && !sameOwner(context.owner, owner))) return 'the source\'s canonical owner changed since the preview';
+ const rows = await engine.executeRaw<{ id: number; slug: string; revision: string; source_path: string | null }>(`SELECT id, slug, knowledge_revision::text AS revision, source_path FROM pages
+ WHERE source_id=$1 AND id=ANY($2::bigint[]) AND deleted_at IS NULL`, [pair.source_id, [pair.survivor.page_id, pair.twin.page_id]]);
+ const survivor = rows.find(row => Number(row.id) === pair.survivor.page_id), twin = rows.find(row => Number(row.id) === pair.twin.page_id);
+ if (!survivor || !twin) return 'one of the two pages was deleted or purged';
+ if (survivor.slug !== pair.survivor.slug || twin.slug !== pair.twin.slug) return 'one of the two pages was renamed';
+ if (String(survivor.revision) !== pair.survivor.revision || String(twin.revision) !== pair.twin.revision) return 'one of the two pages has a new revision';
+ if (survivor.source_path == null || twin.source_path !== pair.twin_path) return 'a recorded origin changed';
+ if (pair.mode === 'detach') return null;
+ const live = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path=ANY($2::text[])',
+ [pair.source_id, [...new Set([pair.source_path, pair.twin_path, survivor.source_path])]]);
+ const verdict = await originGroupVerdict(engine, context, syncOriginPath(pair.source_path), await readOriginClaimants(engine, pair.source_id, live.map(row => Number(row.id))));
+ if (verdict.verdict !== 'resolve') return `the group needs a decision now (${verdict.reason})`;
+ return verdict.survivor.id === pair.survivor.page_id ? null : 'another page is now canonical';
+}
+
+/** Resolves one pair; a managed brain submits it under `requestId()`. Returns the receipt fields on success. */
+export async function resolveOriginTwin(ctx: OperationContext, pair: OriginTwinPair, owner: GhostOwner | null, requestId: () => Promise<string>): Promise<RepairItemOutcome> {
+ const engine = ctx.engine;
+ const moved = await originPairNow(engine, pair, owner);
+ if (moved) return changed(moved);
+ if (await managedPersistenceEnabled(engine)) {
+ const authority = (await maintenancePreflight(engine, pair.source_id))!;
+ try {
+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, pair.twin.slug, { kind: ORIGIN_TWINS_INTENT, expected_revision: pair.twin.revision, pair, owner }, await requestId());
+ return { applied: true, outcome: pair.mode === 'merge' ? 'merged' : 'detached', detail: receipt };
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed', 'source_changed'].includes(error.code)) return changed(error.message);
+ throw error;
+ }
+ }
+ const result = await maintenanceTransaction(engine, async tx => {
+ await tx.lockPageKeys([{ sourceId: pair.source_id, slug: pair.survivor.slug }, { sourceId: pair.source_id, slug: pair.twin.slug }].sort((a, b) => a.slug.localeCompare(b.slug)));
+ const reason = await pairLocked(tx, pair);
+ if (reason) return { reason };
+ const [source] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [pair.source_id]);
+ return { receipt: await applyOriginTwin(tx, pair, source!.incarnation) };
+ });
+ return 'reason' in result ? changed(result.reason!) : { applied: true, outcome: pair.mode === 'merge' ? 'merged' : 'detached', detail: result.receipt };
+}
+
+/** Under the page keys: why the locked pair is no longer the approved one, or null. */
+async function pairLocked(tx: BrainEngine, pair: OriginTwinPair): Promise<string | null> {
+ const survivor = await tx.readPageSnapshot(pair.survivor.slug, { sourceId: pair.source_id });
+ const twin = await tx.readPageSnapshot(pair.twin.slug, { sourceId: pair.source_id });
+ if (!survivor || Number(survivor.page.id) !== pair.survivor.page_id || survivor.revision !== pair.survivor.revision || survivor.page.source_path == null) return 'the surviving page changed';
+ if (!twin || Number(twin.page.id) !== pair.twin.page_id || twin.revision !== pair.twin.revision || twin.page.source_path !== pair.twin_path) return 'the twin changed';
+ return null;
+}
+
+const DROPPED_VALUE_MAX = 1000;
+/** Keys of the twin's frontmatter the survivor lacks or holds differently, with the twin's values (listed in the receipt). */
+async function droppedFrontmatter(tx: BrainEngine, pair: OriginTwinPair): Promise<Record<string, unknown>> {
+ const rows = await tx.executeRaw<{ id: number; frontmatter: Record<string, unknown> | string | null }>('SELECT id, frontmatter FROM pages WHERE id=ANY($1::bigint[])', [[pair.survivor.page_id, pair.twin.page_id]]);
+ const of = (id: number) => { const raw = rows.find(row => Number(row.id) === id)?.frontmatter; return (typeof raw === 'string' ? JSON.parse(raw) : raw ?? {}) as Record<string, unknown>; };
+ const survivor = of(pair.survivor.page_id), twin = of(pair.twin.page_id);
+ return Object.fromEntries(Object.entries(twin).filter(([key, value]) => JSON.stringify(survivor[key]) !== JSON.stringify(value))
+ .map(([key, value]) => { const text = JSON.stringify(value) ?? 'null'; return [key, text.length > DROPPED_VALUE_MAX ? `${text.slice(0, DROPPED_VALUE_MAX)}… (truncated; the twin's page version holds it)` : value]; }));
+}
+
+/** The write itself, inside the caller's transaction with both page keys held. */
+async function applyOriginTwin(tx: BrainEngine, pair: OriginTwinPair, incarnation: string): Promise<Record<string, unknown>> {
+ const restore = ['gbrain', 'restore', pair.twin.slug, '--source-id', pair.source_id];
+ const base = { source_id: pair.source_id, source_path: pair.source_path, survivor_slug: pair.survivor.slug, twin_slug: pair.twin.slug };
+ if (pair.mode === 'detach') {
+ await tx.executeRaw('UPDATE pages SET source_path=NULL, source_uri=NULL, database_only_reason=$2 WHERE id=$1', [pair.twin.page_id, ORIGIN_TWIN_REASON]);
+ return { status: 'origin_twin_detached', ...base };
+ }
+ const dropped = await droppedFrontmatter(tx, pair);
+ const merged = await mergeTwinInto(tx, { sourceId: pair.source_id, incarnation, survivor: { page_id: pair.survivor.page_id, slug: pair.survivor.slug }, twin: { page_id: pair.twin.page_id, slug: pair.twin.slug } });
+ return { status: 'origin_twin_resolved', ...base, links_moved: merged.links_moved.length, link_ids: merged.links_moved, facts_moved: merged.facts_moved.length,
+ transitions_moved: merged.transitions_moved, tags_moved: merged.tags_moved, deduplicated: merged.deduplicated, dropped_frontmatter: dropped, restore_argv: restore,
+ restore_note: `${restore.join(' ')} brings back ${pair.twin.slug}'s own text as a database-only page within ${ORIGIN_TWINS_PURGE_FUSE_HOURS} h; references moved to ${pair.survivor.slug} stay there. `
+ + `${pair.survivor.slug}'s frontmatter comes from ${pair.source_path}, so each key in dropped_frontmatter (the twin's value) is kept only in the twin's page version; `
+ + 'its free-text aliases answer for the survivor until the file is next imported. Add any of them to the file to keep them.' };
+}
+
+/**
+ * Preparer for `managed_maintenance_resolve_origin_twin`, a request on the twin that also holds the survivor's key:
+ * re-checks the pair, publishes no file (the file stays the survivor's), and re-checks both pages under the locks.
+ */
+export async function prepareOriginTwinResolve(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {
+ const pair = row.intent!.pair as OriginTwinPair | undefined;
+ const owner = (row.intent!.owner as GhostOwner | null | undefined) ?? null;
+ if (!pair || pair.twin.slug !== row.slug || pair.source_id !== row.source_id || pair.twin.page_id !== Number(row.page_id) || !['merge', 'detach'].includes(pair.mode)) {
+ throw opError('invalid_params', 'The origin twin intent does not name its pages.',
+ `Request ${row.request_id} for ${row.slug} in source ${row.source_id} does not name the pair it resolves, so nothing changed. Preview the repair again.`, { fix: previewFix(row.source_id) });
+ }
+ const refuse = (reason: string) => opError('revision_conflict', 'The duplicate-origin pair changed since it was read.',
+ `Pages ${pair.survivor.slug} and ${row.slug} in source ${row.source_id} changed (${reason}), so request ${row.request_id} resolved nothing. Preview the repair again.`, { fix: previewFix(row.source_id) });
+ const moved = await originPairNow(engine, pair, owner);
+ if (moved) throw refuse(moved);
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ const core = await prepareCoreGuard(engine, { row, snapshot: await engine.readPageSnapshot(row.slug, { sourceId: row.source_id }), incoming: null });
+ const prepared: PreparedMutation = { observedRevision: pair.twin.revision, additionalPageKeys: [{ sourceId: row.source_id, slug: pair.survivor.slug }],
+ ...(core ? { exclusiveSources: core.exclusiveSources } : {}),
+ databaseOnlyReason: 'shared_origin',
+ validate: async tx => {
+ await authorizeWrite(tx, row.authority, 'submit_job', row.slug);
+ const locked = await pairLocked(tx, pair);
+ if (locked) throw refuse(locked);
+ prepared.databaseOnlyWarning = pair.mode === 'merge'
+ ? `Twin ${row.slug} is hidden; ${pair.source_path} is untouched and stays ${pair.survivor.slug}'s, which takes its inbound references; ${row.slug} resolves to it as an alias.`
+ : `${row.slug} no longer records ${pair.source_path}, which stays ${pair.survivor.slug}'s; ${row.slug} stays live as a database-only page.`;
+ },
+ apply: async tx => applyOriginTwin(tx, pair, row.source_incarnation) };
+ return prepared;
+}
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 62c7e76789..a6fe120778 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -66,6 +66,7 @@ import { frontmatterKeysRepair } from './frontmatter-keys.ts';
import { fileDriftRepair } from './file-drift.ts';
import { stuckRecoveryRepair } from './stuck-recovery.ts';
import { ghostPagesRepair, GHOST_CONSENT_TEXT, GHOST_CONSEQUENCES, GHOST_PURGE_FUSE_HOURS } from './ghost-pages.ts';
+import { originTwinsRepair, ORIGIN_TWINS_CONSENT_TEXT, ORIGIN_TWINS_PURGE_FUSE_HOURS } from './origin-twins.ts';
import { receiptCompactionRepair } from './receipt-compaction.ts';
import { aliasesRepair } from './aliases.ts';
import { renameIdentityRepair, RENAME_IDENTITY_CONSENT_TEXT } from './rename-identity.ts';
@@ -336,6 +337,18 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'rechecking each file is still absent (a restored file keeps its page and asks for a new preview). Refused when ghosts are over half of the source\'s '
+ `file-backed pages unless GBRAIN_ALLOW_MASS_RECONCILE=1. Purged after ${GHOST_PURGE_FUSE_HOURS} h; ${GHOST_CONSEQUENCES.undo} Runs only when named.`,
},
+ 'origin-twins': {
+ handler: originTwinsRepair, embeds: 'none', checks: ['origin_twins'], explicit_only: true, preview_bound: true, consent: 'destructive',
+ consentText: ORIGIN_TWINS_CONSENT_TEXT,
+ summary: 'Resolve duplicate-origin twins (#6948): several live pages of one source recording the same file, which sync holds origin_conflict. Needs --source; '
+ + 'refused off the canonical owner host. A group whose pages are verified duplicates (the page the path names, one body, readable file, compatible ids, one '
+ + 'visibility and trust tier, no slug-keyed withdrawals, no file at a twin\'s slug path, no evidence the merge would lose) is merged: links, relationship dates, '
+ + 'timeline, raw data, user tags, aliases and facts move to the canonical page, the twin\'s slug becomes an alias, and the twin is soft-deleted (the file stays) '
+ + `and purged after ${ORIGIN_TWINS_PURGE_FUSE_HOURS} h; the receipt lists the twin\'s frontmatter keys the survivor lacks and the restore command. Any other group is listed with the `
+ + 'commands to decide it; --slug <kept-slug> then only detaches the other pages (they forget the file and stay live). Refused when merges are over half of '
+ + 'the source\'s file-backed pages unless GBRAIN_ALLOW_MASS_RECONCILE=1. Once no source has a group, --apply builds the pages_live_origin_key index. '
+ + 'Preview-bound: --apply --expect <hash> --yes resolves exactly the previewed set. Runs only when named.',
+ },
'receipt-compaction': {
handler: receiptCompactionRepair, embeds: 'none', checks: ['persistence_capacity'], explicit_only: true, preview_bound: true, consent: 'destructive',
consentText: {
diff --git a/src/core/schema-migrations/helpers.ts b/src/core/schema-migrations/helpers.ts
index 56562fae8e..300c9d7a17 100644
--- a/src/core/schema-migrations/helpers.ts
+++ b/src/core/schema-migrations/helpers.ts
@@ -76,7 +76,7 @@ export type OnlineIndexOutcome = 'present' | 'created' | 'rebuilt' | 'building';
* `CREATE INDEX IF NOT EXISTS`. Postgres leaves a valid index alone, reports
* one another session is still building, drops an INVALID leftover of an
* interrupted concurrent build, then runs `CREATE INDEX CONCURRENTLY IF NOT
- * EXISTS` on a dedicated connection under the session's startup timeouts, then
+ * EXISTS` (`CREATE UNIQUE INDEX CONCURRENTLY` for a unique one) on a dedicated connection under the session's startup timeouts, then
* confirms the index is valid. Callers build one index at a time;
* a lock timeout leaves an INVALID index that the next call drops and rebuilds.
* After a create or rebuild, `analyzeAfterIndexBuild` refreshes the table's
@@ -110,7 +110,7 @@ export async function buildIndexOnline(
// No session SET: a reservation can fall back to a transaction-pooled connection, where a SET or RESET
// reaches another client's backend. The build runs under the session's startup timeouts; one that times
// out leaves an INVALID index, which the next call drops and rebuilds.
- await engine.withReservedConnection(conn => conn.executeRaw(index.sql.replace('CREATE INDEX', 'CREATE INDEX CONCURRENTLY')), { selfContained: true });
+ await engine.withReservedConnection(conn => conn.executeRaw(index.sql.replace(/CREATE (UNIQUE )?INDEX/, 'CREATE $1INDEX CONCURRENTLY')), { selfContained: true });
// IF NOT EXISTS also skips an INVALID index a concurrent caller's failed build left behind.
const [built] = await engine.executeRaw<{ valid: boolean }>('SELECT indisvalid AS valid FROM pg_index WHERE indexrelid = to_regclass($1)', [index.name]);
if (!built?.valid) {
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index f656de705e..d769ca9622 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 256;
+export const LATEST_SCHEMA_VERSION = 257;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index ebe402e5cf..ccd93a7b68 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -257,6 +257,7 @@ import { v253 } from './v253-page-view-digests.ts';
import { v254 } from './v254-segment-reader-marks.ts';
import { v255 } from './v255-page-body-staging-texts.ts';
import { v256 } from './v256-chunk-retirement-index.ts';
+import { v257 } from './v257-pages-live-origin-key.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -512,4 +513,5 @@ export const MIGRATIONS: Migration[] = [
v254,
v255,
v256,
+ v257,
];
diff --git a/src/core/schema-migrations/v257-pages-live-origin-key.ts b/src/core/schema-migrations/v257-pages-live-origin-key.ts
new file mode 100644
index 0000000000..f3c4eda42b
--- /dev/null
+++ b/src/core/schema-migrations/v257-pages-live-origin-key.ts
@@ -0,0 +1,32 @@
+import type { Migration } from './types.ts';
+import { migrationNotice } from './helpers.ts';
+import { buildOriginIndexIfClean, originTwinsRepairCommand } from '../persistence/origin-index.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// #6948: one live page per recorded origin. The partial unique index
+// pages_live_origin_key (source_id, source_path) over live pages that record a
+// file makes a second live claim on an origin fail inside the writer's own
+// transaction, so a duplicate-origin twin can no longer be written. It is
+// built online (CONCURRENTLY on Postgres, inline on PGLite) only when the
+// brain holds no live twins. With twins, nothing is written or repaired here
+// (repairs are preview-first operator steps, never upgrade steps): the
+// migration prints `gbrain repair origin-twins --source <id>` for each source
+// and succeeds; that repair builds the index once the last group is resolved,
+// and doctor's origin_twins check reports "index pending" until then. Not in
+// schema.sql: the schema replay on every initSchema would fail on a brain with
+// twins. Fresh installs run this migration and get the index.
+export const v257: Migration = {
+ version: 257,
+ name: 'pages_live_origin_key',
+ idempotent: true,
+ transaction: false,
+ sql: '',
+ handler: async engine => {
+ const outcome = await buildOriginIndexIfClean(engine, 257, migrationNotice);
+ if (outcome.state !== 'pending') return;
+ migrationNotice(` pages_live_origin_key deferred: ${outcome.sources.map(s => `source ${s.source_id} has ${s.groups} duplicate-origin group(s)`).join(', ')}. `
+ + `Nothing was changed. Preview the fix with ${outcome.sources.map(s => originTwinsRepairCommand(s.source_id)).join(' ; ')} (writes nothing); its apply builds the index.\n`);
+ },
+};
diff --git a/test/e2e/origin-twins-6948.test.ts b/test/e2e/origin-twins-6948.test.ts
new file mode 100644
index 0000000000..cbfd29d9d4
--- /dev/null
+++ b/test/e2e/origin-twins-6948.test.ts
@@ -0,0 +1,268 @@
+/**
+ * #6948: duplicate-origin twins no longer abort a source's managed sync. Through the public sync entry point
+ * (`performSync`): only the twin file is held `origin_conflict`, the rest of the source syncs, and the sync-time heal
+ * merges verified duplicates into the page the path names (links moved, slug kept as an alias, the twin soft-deleted
+ * without touching the file, an `origin_twin_resolved` receipt with the restore command). Anything else stays a per-file
+ * hold a person decides (`gbrain repair origin-twins` lists it; `--slug` only detaches). The kill switch, three
+ * claimants, a tombstone beside a live claimant, deletion and dry runs, the merged twin's restore and purge, and the
+ * `pages_live_origin_key` migration with and without twins. Master threw `page_identity_changed` for the whole source.
+ *
+ * PGLite and, with DATABASE_URL, Postgres. Synthetic content only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../../src/core/operations.ts';
+import { OperationError } from '../../src/core/ops/contract.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { performSync } from '../../src/commands/sync/perform.ts';
+import { readGitSourceHolds } from '../../src/core/persistence/sync-holds.ts';
+import { holdVerdict } from '../../src/core/persistence/sync-status.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { originIndexState } from '../../src/core/persistence/origin-index.ts';
+import { v257 } from '../../src/core/schema-migrations/v257-pages-live-origin-key.ts';
+import { originTwinsEntry } from '../../src/commands/doctor/checks/origin-twins.ts';
+import { runRepairCommand } from '../../src/commands/repair.ts';
+import { _resetCliExitVerdictForTests } from '../../src/core/cli-force-exit.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const op = (name: string) => operations.find(o => o.name === name)!;
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message = 'synthetic content') => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };
+const note = (body: string, extra = '') => `---\ntitle: Example\n${extra}---\n${body}\n`;
+
+async function capture(fn: () => Promise<void>): Promise<string> {
+ let printed = '';
+ const original = console.log, write = process.stdout.write;
+ console.log = (...parts: unknown[]) => { printed += `${parts.map(String).join(' ')}\n`; };
+ process.stdout.write = ((chunk: string | Uint8Array) => { printed += String(chunk); return true; }) as typeof process.stdout.write;
+ try { await fn(); } finally { console.log = original; process.stdout.write = write; }
+ return printed;
+}
+
+for (const backend of testBackends()) describe(`[${backend}] #6948 duplicate-origin twins in managed sync`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), `gbrain-6948-e2e-${backend}-`));
+ const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, GBRAIN_INTERACTIVE: '0', CI: '1' };
+ const sync = (opts: Record<string, unknown>) => withEnv(env, () => performSync(engine, opts as Parameters<typeof performSync>[1]));
+ const row = async (sourceId: string, slug: string) => (await engine.executeRaw<{ id: number; deleted_at: string | null; compiled_truth: string; source_path: string | null; database_only_reason: string | null }>(
+ 'SELECT id,deleted_at,compiled_truth,source_path,database_only_reason FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0] ?? null;
+ const holds = async (sourceId: string) => (await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? [];
+ const write = (sourceId: string, fn: (tx: BrainEngine) => Promise<unknown>) => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+ const context = (sourceId: string): OperationContext => ({ engine, config: { engine: backend, embedding_disabled: true } as never, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId });
+
+ /** A managed git source: `alpha.md` synced into page `alpha`, `beta.md` into `beta`, plus extra live pages recording alpha.md. */
+ async function source(twins: Array<{ slug: string; same?: boolean; frontmatter?: Record<string, unknown> }>) {
+ const id = `ot-${randomUUID().replace(/-/g, '').slice(0, 12)}`, root = join(home, id);
+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');
+ writeFileSync(join(root, 'alpha.md'), note('Alpha, version one.'));
+ writeFileSync(join(root, 'beta.md'), note('Beta, version one.'));
+ commit(root);
+ await withEnv(env, async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ });
+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };
+ expect((await sync(opts)).status).toBe('first_sync');
+ const alpha = (await engine.executeRaw<{ compiled_truth: string; timeline: string; trust_tier: string }>('SELECT compiled_truth, timeline, trust_tier FROM pages WHERE source_id=$1 AND slug=$2', [id, 'alpha']))[0]!;
+ for (const twin of twins) {
+ // A twin sync imported under another slug carries the tier sync gave its file.
+ await write(id, async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.write_trust_tier', $1, true)", [alpha.trust_tier]);
+ await tx.putPage(twin.slug, { type: 'note', title: 'Example', compiled_truth: twin.same === false ? 'A different body.' : alpha.compiled_truth,
+ timeline: alpha.timeline ?? '', frontmatter: twin.frontmatter ?? {}, content_hash: randomUUID(), source_path: 'alpha.md' }, { sourceId: id });
+ });
+ }
+ return { id, root, opts };
+ }
+
+ beforeAll(async () => {
+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }
+ // Twins exist only on brains written before this release, whose index is pending.
+ await engine.executeRaw('DROP INDEX IF EXISTS pages_live_origin_key');
+ }, 120_000);
+ afterAll(async () => {
+ await withEnv(env, async () => { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); });
+ await engine.disconnect(); await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+ }, 60_000);
+
+ test('contract: verified twins plus an unrelated edit sync without refusing; the heal merges the twin and the next sync imports the file', async () => {
+ const f = await source([{ slug: 'alpha-copy', frontmatter: { aliases: ['Alpha Example'], tags: ['from-twin'], confirmed_by: 'alice-example' } }]);
+ await write(f.id, async tx => {
+ const [beta, twin] = await Promise.all(['beta', 'alpha-copy'].map(async slug => Number((await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [f.id, slug]))[0]!.id)));
+ await tx.executeRaw("INSERT INTO links (from_page_id,to_page_id,link_type,link_source,context) VALUES ($1,$2,'cites','manual','beta cites the copy')", [beta, twin]);
+ });
+ writeFileSync(join(f.root, 'alpha.md'), note('Alpha, version two.'));
+ writeFileSync(join(f.root, 'beta.md'), note('Beta, version two.'));
+ commit(f.root, 'edit both');
+ const result = await sync(f.opts);
+ expect(result.status).toBe('synced');
+ expect((await row(f.id, 'beta'))!.compiled_truth).toContain('version two');
+ const heal = result.origin_twins_resolved!;
+ expect(heal).toMatchObject({ resolved: 1, twins_merged: 1, failed: 0, resolved_paths: ['alpha.md'] });
+ const receipt = heal.receipts[0] as Record<string, any>;
+ expect(receipt).toMatchObject({ status: 'origin_twin_resolved', survivor_slug: 'alpha', twin_slug: 'alpha-copy', links_moved: 1,
+ restore_argv: ['gbrain', 'restore', 'alpha-copy', '--source-id', f.id] });
+ expect(receipt.dropped_frontmatter).toEqual({ aliases: ['Alpha Example'], tags: ['from-twin'], confirmed_by: 'alice-example' });
+ const twin = (await row(f.id, 'alpha-copy'))!;
+ expect(twin.deleted_at).not.toBeNull();
+ expect(twin).toMatchObject({ source_path: null, database_only_reason: 'origin_twin' });
+ expect(readFileSync(join(f.root, 'alpha.md'), 'utf8')).toBe(note('Alpha, version two.'));
+ expect(existsSync(join(f.root, 'alpha-copy.md'))).toBe(false);
+ const alphaId = (await row(f.id, 'alpha'))!.id;
+ expect(await engine.executeRaw('SELECT context FROM links WHERE to_page_id=$1', [alphaId])).toEqual([{ context: 'beta cites the copy' }]);
+ // The next sync re-screens the hold and imports the file into the survivor.
+ const next = await sync(f.opts);
+ expect(next.status).not.toBe('blocked_by_failures');
+ expect((await row(f.id, 'alpha'))!.compiled_truth).toContain('version two');
+ expect((await holds(f.id)).filter(h => h.code === 'origin_conflict')).toEqual([]);
+ // gbrain get alpha-copy resolves to the survivor through the alias.
+ const resolved = await engine.executeRaw<{ canonical_slug: string }>('SELECT canonical_slug FROM slug_aliases WHERE source_id=$1 AND alias_slug=$2', [f.id, 'alpha-copy']);
+ expect(resolved).toEqual([{ canonical_slug: 'alpha' }]);
+ }, 180_000);
+
+ test('a merged twin restores as a database-only page (no file written) and an owner purge is refused', async () => {
+ const f = await source([{ slug: 'alpha-copy' }]);
+ expect((await sync({ ...f.opts, full: true })).origin_twins_resolved).toMatchObject({ resolved: 1 });
+ const gone = (await engine.readPageSnapshot('alpha-copy', { sourceId: f.id, includeDeleted: true }))!;
+ const restored = await withEnv(env, () => op('restore_page').handler(context(f.id), { slug: 'alpha-copy', source_id: f.id, request_id: randomUUID(), expected_revision: gone.revision })) as Record<string, any>;
+ expect(restored.state ?? 'committed').toBe('committed');
+ expect((await row(f.id, 'alpha-copy'))).toMatchObject({ deleted_at: null, source_path: null, database_only_reason: 'origin_twin' });
+ expect(existsSync(join(f.root, 'alpha-copy.md'))).toBe(false);
+ const snapshot = (await engine.readPageSnapshot('alpha-copy', { sourceId: f.id }))!;
+ const purge = await withEnv(env, () => op('delete_page').handler(context(f.id), { slug: 'alpha-copy', source_id: f.id, request_id: randomUUID(), expected_revision: snapshot.revision, purge: true }))
+ .then(() => null, error => error as OperationError);
+ expect(purge?.code).toBe('source_changed');
+ expect(purge?.message).toContain('merged into a duplicate that holds the same content');
+ expect((await row(f.id, 'alpha'))!.deleted_at).toBeNull();
+ }, 180_000);
+
+ test('three verified claimants merge into the canonical page in one sync', async () => {
+ const f = await source([{ slug: 'alpha-copy' }, { slug: 'archive/alpha' }]);
+ const result = await sync({ ...f.opts, full: true });
+ expect(result.origin_twins_resolved).toMatchObject({ resolved: 1, twins_merged: 2 });
+ for (const slug of ['alpha-copy', 'archive/alpha']) expect((await row(f.id, slug))!.deleted_at).not.toBeNull();
+ expect((await row(f.id, 'alpha'))).toMatchObject({ deleted_at: null, source_path: 'alpha.md' });
+ }, 180_000);
+
+ test('the kill switch off: the twin file stays held, the rest syncs, sync status lists the hold and nothing is deleted', async () => {
+ const f = await source([{ slug: 'alpha-copy' }]);
+ await engine.setConfig('sync.origin_twins.auto_resolve', 'false');
+ try {
+ writeFileSync(join(f.root, 'beta.md'), note('Beta, version two.')); commit(f.root, 'edit beta');
+ const result = await sync({ ...f.opts, full: true });
+ expect(result.status).toBe('synced');
+ expect((await row(f.id, 'beta'))!.compiled_truth).toContain('version two');
+ expect(result.origin_twins_resolved).toMatchObject({ skipped: 'disabled', resolved: 0 });
+ expect((await row(f.id, 'alpha-copy'))!.deleted_at).toBeNull();
+ const held = (await holds(f.id)).filter(h => h.code === 'origin_conflict');
+ expect(held.map(h => [h.path, h.meta.reason ?? null, h.meta.canonical_slug])).toEqual([['alpha.md', null, 'alpha']]);
+ expect(holdVerdict(held[0]!, undefined).needs_human).toBe(false);
+ } finally { await engine.setConfig('sync.origin_twins.auto_resolve', 'true'); }
+ }, 180_000);
+
+ test('twins whose bodies differ are a decision: held with the reason, never merged; --slug only detaches, then the file imports', async () => {
+ const f = await source([{ slug: 'alpha-copy', same: false }]);
+ writeFileSync(join(f.root, 'alpha.md'), note('Alpha, version two.')); commit(f.root, 'edit alpha');
+ const result = await sync(f.opts);
+ expect(result.status).toBe('synced');
+ expect(result.origin_twins_resolved).toMatchObject({ resolved: 0, left_by_reason: { content_differs: 1 } });
+ const held = (await holds(f.id)).find(h => h.code === 'origin_conflict')!;
+ expect(held.meta.reason).toBe('content_differs');
+ expect(holdVerdict(held, undefined)).toMatchObject({ needs_human: true });
+ expect((await row(f.id, 'alpha-copy'))!.deleted_at).toBeNull();
+ _resetCliExitVerdictForTests();
+ const preview = JSON.parse(await withEnv(env, () => capture(() => runRepairCommand(engine, ['origin-twins', '--source', f.id, '--json'])))).results[0];
+ expect(preview.details.decisions.map((g: { reason: string }) => g.reason)).toEqual(['content_differs']);
+ expect(preview.listing.map((l: { class: string }) => l.class)).toEqual(['decision:content_differs']);
+ const keep = JSON.parse(await withEnv(env, () => capture(() => runRepairCommand(engine, ['origin-twins', '--source', f.id, '--slug', 'alpha', '--json'])))).results[0];
+ expect(keep.listing.map((l: { class: string }) => l.class)).toEqual(['detach']);
+ const applied = JSON.parse(await withEnv(env, () => capture(() => runRepairCommand(engine, ['origin-twins', '--source', f.id, '--slug', 'alpha', '--apply', '--expect', keep.preview_hash, '--yes', '--json'])))).results[0];
+ expect(applied).toMatchObject({ applied: 1, failed: [] });
+ expect((await row(f.id, 'alpha-copy'))).toMatchObject({ deleted_at: null, source_path: null, database_only_reason: 'origin_twin', compiled_truth: 'A different body.' });
+ await sync(f.opts);
+ expect((await row(f.id, 'alpha'))!.compiled_truth).toContain('version two');
+ expect((await holds(f.id)).filter(h => h.code === 'origin_conflict')).toEqual([]);
+ }, 180_000);
+
+ test('trust tiers that differ hold trust_tier_differs; a merge never raises a tier', async () => {
+ const f = await source([{ slug: 'alpha-copy' }]);
+ await write(f.id, async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.write_trust_tier', 'unknown', true)");
+ await tx.executeRaw("UPDATE pages SET trust_tier='unknown', title='Lowered' WHERE source_id=$1 AND slug='alpha-copy'", [f.id]);
+ });
+ expect((await engine.executeRaw<{ t: string }>("SELECT trust_tier AS t FROM pages WHERE source_id=$1 AND slug IN ('alpha','alpha-copy') ORDER BY slug", [f.id])).map(r => r.t)[0])
+ .not.toBe((await engine.executeRaw<{ t: string }>("SELECT trust_tier AS t FROM pages WHERE source_id=$1 AND slug='alpha-copy'", [f.id]))[0]!.t);
+ const result = await sync({ ...f.opts, full: true });
+ expect(result.origin_twins_resolved).toMatchObject({ resolved: 0, left_by_reason: { trust_tier_differs: 1 } });
+ expect((await row(f.id, 'alpha-copy'))!.deleted_at).toBeNull();
+ }, 180_000);
+
+ test('a live claimant beside a tombstone is no conflict; deleting a twin-held file and a dry run never refuse the source', async () => {
+ const f = await source([{ slug: 'alpha-copy' }]);
+ await write(f.id, tx => tx.executeRaw('UPDATE pages SET deleted_at=now() WHERE source_id=$1 AND slug=$2', [f.id, 'alpha-copy']));
+ writeFileSync(join(f.root, 'alpha.md'), note('Alpha, version two.')); commit(f.root, 'edit alpha');
+ expect((await sync(f.opts)).status).toBe('synced');
+ expect((await row(f.id, 'alpha'))!.compiled_truth).toContain('version two');
+ const g = await source([{ slug: 'alpha-copy' }]);
+ rmSync(join(g.root, 'alpha.md')); commit(g.root, 'remove alpha');
+ const dry = await sync({ ...g.opts, dryRun: true });
+ expect(dry.status).toBe('dry_run');
+ expect((await row(g.id, 'alpha-copy'))!.deleted_at).toBeNull();
+ await engine.setConfig('sync.origin_twins.auto_resolve', 'false');
+ try {
+ const deleted = await sync(g.opts);
+ expect(deleted.status).toBe('synced');
+ expect((await holds(g.id)).filter(h => h.code === 'origin_conflict').map(h => h.path)).toEqual(['alpha.md']);
+ expect((await row(g.id, 'alpha'))!.deleted_at).toBeNull();
+ } finally { await engine.setConfig('sync.origin_twins.auto_resolve', 'true'); }
+ }, 180_000);
+
+ test('the migration with twins writes nothing and leaves the index pending (doctor says so); the repair apply then builds it', async () => {
+ const f = await source([{ slug: 'alpha-copy' }]);
+ const pages = async () => (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE deleted_at IS NULL'))[0]!.n;
+ const before = await pages();
+ await v257.handler!(engine);
+ expect(await originIndexState(engine)).toBe('missing');
+ expect(await pages()).toBe(before);
+ const pending = (await originTwinsEntry.run({ engine } as never))[0]!;
+ expect(pending).toMatchObject({ name: 'origin_twins', status: 'warn' });
+ expect(pending.message).toContain('Index pending');
+ expect(pending.message).toContain(`source ${f.id} has 1 file(s) recorded by several live pages`);
+ expect(pending.message).toContain('Preview the fix with gbrain repair origin-twins --source ');
+ // Resolve every source's twins with the repair (earlier tests left groups only where a person decides; resolve them by keeping alpha).
+ const sources = await engine.executeRaw<{ source_id: string }>(`SELECT DISTINCT source_id FROM pages WHERE deleted_at IS NULL AND source_path IS NOT NULL
+ GROUP BY source_id, source_path HAVING count(*) > 1`);
+ for (const { source_id } of sources) {
+ for (const args of [[], ['--slug', 'alpha']]) {
+ const preview = JSON.parse(await withEnv(env, () => capture(() => runRepairCommand(engine, ['origin-twins', '--source', source_id, ...args, '--json'])))).results[0];
+ if (!preview.listing?.some((l: { class: string }) => !l.class.startsWith('decision'))) continue;
+ await withEnv(env, () => capture(() => runRepairCommand(engine, ['origin-twins', '--source', source_id, ...args, '--apply', '--expect', preview.preview_hash, '--yes', '--json'])));
+ }
+ }
+ expect(await originIndexState(engine)).toBe('present');
+ expect((await originTwinsEntry.run({ engine } as never))[0]).toMatchObject({ status: 'ok' });
+ // With the index present, a second live claim on an origin is refused by the database.
+ const refused = await write(f.id, tx => tx.putPage('alpha-third', { type: 'note', title: 'x', compiled_truth: 'x', timeline: '', frontmatter: {}, content_hash: 'x', source_path: 'alpha.md' }, { sourceId: f.id }))
+ .then(() => 'written', () => 'refused');
+ expect(refused).toBe('refused');
+ // The migration on a clean brain builds it (and is idempotent).
+ await v257.handler!(engine);
+ expect(await originIndexState(engine)).toBe('present');
+ }, 300_000);
+});
diff --git a/test/origin-twins-6948.test.ts b/test/origin-twins-6948.test.ts
new file mode 100644
index 0000000000..1cee4d4d59
--- /dev/null
+++ b/test/origin-twins-6948.test.ts
@@ -0,0 +1,201 @@
+/**
+ * #6948: duplicate-origin twins. `decideOriginTwins` (the one rule discovery, the sync-time heal and
+ * `gbrain repair origin-twins` share) over every pathological group shape, and the merge primitive
+ * (`mergeTwinInto`, `twinMergeConflicts`) on a real database: what moves to the survivor, what is deduplicated, and
+ * the distinct evidence that refuses the merge before any write. PGLite and, with DATABASE_URL, Postgres.
+ * Synthetic content only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { decideOriginTwins, readOriginClaimants, type OriginClaimant } from '../src/core/persistence/origin-twins.ts';
+import { mergeTwinInto, twinMergeConflicts } from '../src/core/persistence/twin-merge.ts';
+import { syncOriginPath } from '../src/core/persistence/sync-origin.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const page = (id: number, slug: string, over: Partial<OriginClaimant> = {}): OriginClaimant =>
+ ({ id, slug, revision: '1', body_hash: 'same', fm_id: null, private: false, restricted: false, trust_tier: 'owner', ...over });
+const decide = (sourcePath: string, claimants: OriginClaimant[], fileId: string | null | undefined = null, occupied: string[] = []) =>
+ decideOriginTwins({ sourcePath, claimants, fileId, slugPathOccupied: slug => occupied.includes(slug) });
+const reason = (v: ReturnType<typeof decide>) => v.verdict === 'hold' ? v.reason : 'resolve';
+
+describe('#6948 decideOriginTwins: every pathological group', () => {
+ test('two verified duplicates resolve: the page the path names survives, the other is its twin', () => {
+ const v = decide('notes/note-example.md', [page(7, 'notes/note-example-copy'), page(3, 'notes/note-example')]);
+ expect(v).toMatchObject({ verdict: 'resolve', canonical: 'notes/note-example', survivor: { id: 3 } });
+ expect(v.verdict === 'resolve' && v.twins.map(t => t.id)).toEqual([7]);
+ });
+ test('three and more live claimants resolve together when all are duplicates, and hold together when one differs', () => {
+ const three = [page(1, 'notes/note-example'), page(2, 'notes/note-example-2'), page(3, 'notes/note-example-3'), page(4, 'archive/note-example')];
+ const v = decide('notes/note-example.md', three);
+ expect(v.verdict === 'resolve' && v.twins.map(t => t.id)).toEqual([2, 3, 4]);
+ expect(reason(decide('notes/note-example.md', [...three.slice(0, 3), page(4, 'archive/note-example', { body_hash: 'other' })]))).toBe('content_differs');
+ });
+ test('canonical ties: no claimant is the page the path names, or the same slug twice, hold no_canonical_claimant', () => {
+ expect(reason(decide('notes/note-example.md', [page(1, 'notes/a'), page(2, 'notes/b')]))).toBe('no_canonical_claimant');
+ expect(reason(decide('notes/note-example.md', [page(1, 'notes/note-example'), page(2, 'notes/note-example')]))).toBe('no_canonical_claimant');
+ });
+ test('claimants differing in content hold content_differs, and a body that cannot be read (segmented) never matches', () => {
+ expect(reason(decide('notes/note-example.md', [page(1, 'notes/note-example'), page(2, 'x/y', { body_hash: 'other' })]))).toBe('content_differs');
+ expect(reason(decide('notes/note-example.md', [page(1, 'notes/note-example', { body_hash: null }), page(2, 'x/y', { body_hash: null })]))).toBe('content_differs');
+ });
+ test('claimants (or the file) carrying different frontmatter ids hold explicit_id_conflict; one shared id resolves', () => {
+ expect(reason(decide('notes/note-example.md', [page(1, 'notes/note-example', { fm_id: 'id-a' }), page(2, 'x/y', { fm_id: 'id-b' })]))).toBe('explicit_id_conflict');
+ expect(reason(decide('notes/note-example.md', [page(1, 'notes/note-example'), page(2, 'x/y')], 'id-file'))).toBe('resolve');
+ expect(reason(decide('notes/note-example.md', [page(1, 'notes/note-example', { fm_id: 'id-a' }), page(2, 'x/y')], 'id-b'))).toBe('explicit_id_conflict');
+ expect(reason(decide('notes/note-example.md', [page(1, 'notes/note-example', { fm_id: 'id-a' }), page(2, 'x/y', { fm_id: 'id-a' })], 'id-a'))).toBe('resolve');
+ });
+ test('missing evidence never counts as agreement: an unreadable file holds file_unreadable', () => {
+ expect(reason(decideOriginTwins({ sourcePath: 'notes/note-example.md', claimants: [page(1, 'notes/note-example'), page(2, 'x/y')], fileId: undefined }))).toBe('file_unreadable');
+ });
+ test('visibility, trust tier, slug-keyed withdrawals and a file at a twin\'s own slug path each hold', () => {
+ const pair = (over: Partial<OriginClaimant>) => [page(1, 'notes/note-example'), page(2, 'x/y', over)];
+ expect(reason(decide('notes/note-example.md', pair({ private: true })))).toBe('visibility_differs');
+ expect(reason(decide('notes/note-example.md', pair({ trust_tier: 'untrusted' })))).toBe('trust_tier_differs');
+ expect(reason(decide('notes/note-example.md', [page(1, 'notes/note-example', { trust_tier: 'untrusted' }), page(2, 'x/y')]))).toBe('trust_tier_differs');
+ expect(reason(decide('notes/note-example.md', pair({ restricted: true })))).toBe('twin_has_withdrawals');
+ expect(reason(decide('notes/note-example.md', pair({}), null, ['x/y']))).toBe('twin_slug_path_occupied');
+ });
+ test('path spellings: case and Unicode normalization fold to one canonical page; ./ and a trailing slash are not stored origins', () => {
+ const pair = [page(1, 'notes/note-example'), page(2, 'x/y')];
+ expect(decide('Notes/Note-Example.md', pair)).toMatchObject({ verdict: 'resolve', canonical: 'notes/note-example' });
+ const cafe = [page(1, 'notes/cafe'), page(2, 'x/y')];
+ expect(decide('notes/cafe\u0301.md', cafe)).toMatchObject({ verdict: 'resolve', canonical: 'notes/cafe' });
+ expect(decide('notes/caf\u00e9.md', cafe)).toMatchObject({ verdict: 'resolve', canonical: 'notes/cafe' });
+ expect(decide('./notes/note-example.md', pair)).toMatchObject({ verdict: 'resolve', canonical: 'notes/note-example' });
+ // A trailing slash names no Markdown file: no claimant is its page, so a person decides.
+ expect(reason(decide('notes/note-example.md/', pair))).toBe('no_canonical_claimant');
+ for (const spelled of ['./notes/note-example.md', 'notes/note-example.md/', 'notes//note-example.md']) expect(() => syncOriginPath(spelled)).toThrow();
+ });
+});
+
+for (const backend of testBackends()) describe(`[${backend}] #6948 mergeTwinInto and twinMergeConflicts`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ const sourceId = 'default';
+ const write = <T>(fn: (tx: BrainEngine) => Promise<T>) => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+ const id = async (slug: string) => Number((await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0]!.id);
+ async function put(slug: string, opts: { body?: string; sourcePath?: string | null; frontmatter?: Record<string, unknown> } = {}) {
+ await write(tx => tx.putPage(slug, { type: 'note', title: slug, compiled_truth: opts.body ?? 'One shared body.', timeline: '', frontmatter: opts.frontmatter ?? {},
+ content_hash: randomUUID(), ...(opts.sourcePath ? { source_path: opts.sourcePath } : {}) }, { sourceId }));
+ return id(slug);
+ }
+ /** A survivor and a twin recording one origin with one body, and a third page. */
+ async function trio() {
+ const tag = randomUUID().slice(0, 8);
+ const origin = `notes/note-${tag}.md`;
+ const survivor = await put(`notes/note-${tag}`, { sourcePath: origin });
+ const twin = await put(`notes/note-${tag}-copy`, { sourcePath: origin });
+ const third = await put(`people/alice-example-${tag}`, { body: 'Alice, a person.' });
+ return { tag, origin, survivor: { page_id: survivor, slug: `notes/note-${tag}` }, twin: { page_id: twin, slug: `notes/note-${tag}-copy` }, third };
+ }
+ const link = (from: number, to: number, type: string, source: string | null, context = '', origin: number | null = null) =>
+ write(tx => tx.executeRaw('INSERT INTO links (from_page_id,to_page_id,link_type,link_source,context,origin_page_id) VALUES ($1,$2,$3,$4,$5,$6)', [from, to, type, source, context, origin]));
+ const merge = (t: Awaited<ReturnType<typeof trio>>) => write(async tx => {
+ const [source] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ return mergeTwinInto(tx, { sourceId, incarnation: source!.incarnation, survivor: t.survivor, twin: t.twin });
+ });
+
+ beforeAll(async () => {
+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }
+ // A brain that already holds twins (written before this release): the index is pending, so twins can be seeded.
+ await engine.executeRaw('DROP INDEX IF EXISTS pages_live_origin_key');
+ }, 120_000);
+ afterAll(async () => { await engine.disconnect(); await closePostgres?.(); }, 60_000);
+
+ test('a twin with inbound links, manual and custom outgoing relationships, aliases, timeline, raw data and tags: everything moves or is an exact duplicate', async () => {
+ const t = await trio();
+ // Inbound: a body link from the third page to both (derived, re-derived from that body: deduplicated), and a manual one to the twin only.
+ await link(t.third, t.twin.page_id, '', 'markdown', 'see [[twin]]');
+ await link(t.third, t.survivor.page_id, '', 'markdown', 'see [[survivor]]');
+ await link(t.third, t.twin.page_id, 'mentions_manually', 'manual', 'a person said so');
+ // Outgoing relationships the twin holds database-only (add_link): manual and a custom provenance.
+ await link(t.twin.page_id, t.third, 'works_with', 'manual', 'manual context');
+ await link(t.twin.page_id, t.third, 'advises', 'acme-example', 'custom context');
+ await write(tx => tx.executeRaw(`INSERT INTO link_transitions (source_id,from_page_id,to_page_id,link_type,kind,occurred_on,producer,origin_page_id)
+ VALUES ($1,$2,$3,'works_at','start','2024-01-01','explicit',$2)`, [sourceId, t.twin.page_id, t.third]));
+ await write(async tx => {
+ await tx.executeRaw("INSERT INTO page_aliases (source_id,alias_norm,slug,origin) VALUES ($1,$2,$3,'frontmatter')", [sourceId, `note alias ${t.tag}`, t.twin.slug]);
+ await tx.executeRaw("INSERT INTO timeline_entries (page_id,date,summary,source) VALUES ($1,'2024-02-02','Shared entry','') , ($2,'2024-02-02','Shared entry','') , ($1,'2024-03-03','Only on the twin','manual')", [t.twin.page_id, t.survivor.page_id]);
+ await tx.executeRaw("INSERT INTO raw_data (page_id,source,data) VALUES ($1,'crm','{\"k\":1}'), ($1,'web','{\"same\":true}'), ($2,'web','{\"same\":true}')", [t.twin.page_id, t.survivor.page_id]);
+ await tx.executeRaw("INSERT INTO tags (page_id,tag,tag_source) VALUES ($1,'alpha','added'), ($1,'shared','added'), ($2,'shared','frontmatter'), ($1,'fm-only','frontmatter')", [t.twin.page_id, t.survivor.page_id]);
+ });
+ expect(await twinMergeConflicts(engine, t.survivor.page_id, t.twin.page_id)).toEqual([]);
+ const result = await merge(t);
+ expect(result.links_moved.length).toBe(3);
+ expect(result.transitions_moved).toBe(1);
+ expect(result.tags_moved).toEqual(['alpha']);
+ const out = await engine.executeRaw<{ link_type: string; link_source: string; context: string }>('SELECT link_type, link_source, context FROM links WHERE from_page_id=$1 AND to_page_id=$2 ORDER BY link_type', [t.survivor.page_id, t.third]);
+ expect(out).toEqual([{ link_type: 'advises', link_source: 'acme-example', context: 'custom context' }, { link_type: 'works_with', link_source: 'manual', context: 'manual context' }]);
+ const inbound = await engine.executeRaw<{ link_source: string; context: string }>('SELECT link_source, context FROM links WHERE from_page_id=$1 AND to_page_id=$2 ORDER BY link_source', [t.third, t.survivor.page_id]);
+ expect(inbound).toEqual([{ link_source: 'manual', context: 'a person said so' }, { link_source: 'markdown', context: 'see [[survivor]]' }]);
+ expect(await engine.executeRaw('SELECT 1 FROM links WHERE from_page_id=$1 OR to_page_id=$1', [t.twin.page_id])).toEqual([]);
+ expect(await engine.executeRaw<{ from_page_id: number }>('SELECT from_page_id FROM link_transitions WHERE to_page_id=$1', [t.third])).toEqual([{ from_page_id: t.survivor.page_id }]);
+ expect((await engine.executeRaw<{ slug: string }>('SELECT slug FROM page_aliases WHERE source_id=$1 AND alias_norm=$2', [sourceId, `note alias ${t.tag}`])).map(r => r.slug)).toEqual([t.survivor.slug]);
+ expect(await engine.executeRaw<{ canonical_slug: string }>('SELECT canonical_slug FROM slug_aliases WHERE source_id=$1 AND alias_slug=$2', [sourceId, t.twin.slug])).toEqual([{ canonical_slug: t.survivor.slug }]);
+ expect((await engine.executeRaw<{ summary: string }>('SELECT summary FROM timeline_entries WHERE page_id=$1 ORDER BY date', [t.survivor.page_id])).map(r => r.summary)).toEqual(['Shared entry', 'Only on the twin']);
+ expect((await engine.executeRaw<{ source: string }>('SELECT source FROM raw_data WHERE page_id=$1 ORDER BY source', [t.survivor.page_id])).map(r => r.source)).toEqual(['crm', 'web']);
+ const tags = await engine.executeRaw<{ page_id: number; tag: string; tag_source: string }>('SELECT page_id, tag, tag_source FROM tags WHERE page_id=ANY($1::int[]) ORDER BY page_id, tag', [[t.survivor.page_id, t.twin.page_id]]);
+ expect(tags.map(r => [Number(r.page_id) === t.survivor.page_id ? 'survivor' : 'twin', r.tag, r.tag_source]))
+ .toEqual([['survivor', 'alpha', 'added'], ['survivor', 'shared', 'added'], ['twin', 'fm-only', 'frontmatter'], ['twin', 'shared', 'added']].sort((a, b) => (a[0] + a[1]).localeCompare(b[0] + b[1])));
+ const [gone] = await engine.executeRaw<{ deleted_at: string | null; source_path: string | null; database_only_reason: string | null }>('SELECT deleted_at, source_path, database_only_reason FROM pages WHERE id=$1', [t.twin.page_id]);
+ expect(gone!.deleted_at).not.toBeNull();
+ expect(gone).toMatchObject({ source_path: null, database_only_reason: 'origin_twin' });
+ expect((await engine.executeRaw<{ source_path: string }>('SELECT source_path FROM pages WHERE id=$1', [t.survivor.page_id]))[0]!.source_path).toBe(t.origin);
+ });
+
+ test('distinct evidence on the same unique key refuses the merge before any write: link context, raw payload, timeline detail, relationship date precision', async () => {
+ const cases: Array<[string, (t: Awaited<ReturnType<typeof trio>>) => Promise<unknown>]> = [
+ ['links', async t => { await link(t.third, t.twin.page_id, 'knows', 'manual', 'context A'); await link(t.third, t.survivor.page_id, 'knows', 'manual', 'context B'); }],
+ ['raw_data', t => write(tx => tx.executeRaw("INSERT INTO raw_data (page_id,source,data) VALUES ($1,'crm','{\"v\":1}'), ($2,'crm','{\"v\":2}')", [t.twin.page_id, t.survivor.page_id]))],
+ ['timeline_entries', t => write(tx => tx.executeRaw("INSERT INTO timeline_entries (page_id,date,summary,source,detail) VALUES ($1,'2024-02-02','Met','', 'detail A'), ($2,'2024-02-02','Met','', 'detail B')", [t.twin.page_id, t.survivor.page_id]))],
+ ['link_transitions', t => write(tx => tx.executeRaw(`INSERT INTO link_transitions (source_id,from_page_id,to_page_id,link_type,kind,occurred_on,producer,origin_page_id,date_precision)
+ VALUES ($1,$2,$4,'works_at','start','2024-01-01','manual',NULL,'day'), ($1,$3,$4,'works_at','start','2024-01-01','manual',NULL,'year')`, [sourceId, t.twin.page_id, t.survivor.page_id, t.third]))],
+ ];
+ for (const [table, seed] of cases) {
+ const t = await trio();
+ await seed(t);
+ const conflicts = await twinMergeConflicts(engine, t.survivor.page_id, t.twin.page_id);
+ expect(conflicts.map(c => c.table)).toEqual([table as never]);
+ const error = await merge(t).then(() => null, e => e as OperationError);
+ expect(error).toBeInstanceOf(OperationError);
+ expect(error).toMatchObject({ code: 'revision_conflict', reason: 'twin_evidence_conflicts' });
+ const [twin] = await engine.executeRaw<{ deleted_at: string | null; source_path: string | null }>('SELECT deleted_at, source_path FROM pages WHERE id=$1', [t.twin.page_id]);
+ expect(twin).toEqual({ deleted_at: null, source_path: t.origin });
+ }
+ });
+
+ test('a derived link whose context differs is re-derived from the survivor\'s body: deduplicated, not a conflict; exact duplicates are idempotent', async () => {
+ const t = await trio();
+ await link(t.twin.page_id, t.third, '', 'markdown', 'body context A', t.twin.page_id);
+ await link(t.survivor.page_id, t.third, '', 'markdown', 'body context B', t.survivor.page_id);
+ await link(t.third, t.twin.page_id, 'knows', 'manual', 'same');
+ await link(t.third, t.survivor.page_id, 'knows', 'manual', 'same');
+ expect(await twinMergeConflicts(engine, t.survivor.page_id, t.twin.page_id)).toEqual([]);
+ const result = await merge(t);
+ expect(result.deduplicated).toBe(2);
+ expect((await engine.executeRaw('SELECT 1 FROM links WHERE from_page_id=$1 AND to_page_id=$2', [t.survivor.page_id, t.third])).length).toBe(1);
+ expect((await engine.executeRaw('SELECT 1 FROM links WHERE from_page_id=$1 AND to_page_id=$2', [t.third, t.survivor.page_id])).length).toBe(1);
+ });
+
+ test('readOriginClaimants reads the verdict inputs: one digest per body, the frontmatter id, the trust tier and slug-keyed withdrawals', async () => {
+ const t = await trio();
+ const differs = await put(`notes/other-${t.tag}`, { body: 'A different body.', sourcePath: t.origin, frontmatter: { id: 'id-x' } });
+ await write(tx => tx.executeRaw("INSERT INTO fact_withdrawals (source_id,visibility,subject,fact_hash) VALUES ($1,'private',$2,'h')", [sourceId, t.twin.slug]));
+ const rows = await readOriginClaimants(engine, sourceId, [t.survivor.page_id, t.twin.page_id, differs]);
+ expect(rows.map(r => r.id)).toEqual([t.survivor.page_id, t.twin.page_id, differs].sort((a, b) => a - b));
+ const by = new Map(rows.map(r => [r.id, r]));
+ expect(by.get(t.survivor.page_id)!.body_hash).toBe(by.get(t.twin.page_id)!.body_hash);
+ expect(by.get(differs)!.body_hash).not.toBe(by.get(t.survivor.page_id)!.body_hash);
+ expect(by.get(differs)!.fm_id).toBe('id-x');
+ expect(by.get(t.twin.page_id)!.restricted).toBe(true);
+ expect(by.get(t.survivor.page_id)!.restricted).toBe(false);
+ expect(reason(decideOriginTwins({ sourcePath: t.origin, claimants: rows.filter(r => r.id !== differs), fileId: null }))).toBe('twin_has_withdrawals');
+ });
+});