Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): GBRA-130 A-17/B-3/B-4: hold one file page_identity_changed instead of stopping the source (#6712 PR 4b)

garrytan8de5620c4026
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 7d04b735f6..ce5c2c143c 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -135,6 +135,7 @@ Every hold and error has three fields, from one table
| `file_unreadable` | page | none | yes | always: only a change to the checkout makes the file readable |
| `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 |
| `origin_conflict_decision` | page | none | yes | always: the pages differ, their ids conflict or none is the page the path names |
+| `page_identity_decision` | page | none | yes | always: only a person decides which page the file is |
| `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/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index c796e548fb..88573c1b55 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -206,6 +206,7 @@ with each file and fix the ones that need no guessing."*
| <a id="write_gate_rejected"></a>`write_gate_rejected` | The source is untrusted, the file reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request), and the operator set `write_gate.external_mode` to `reject`, so the file is never imported and always visible. Managed sync holds it when it freezes the file (#6712 PR 2; before, the refusal came at preparation and blocked the rest of the source); an owner allow rule (`gbrain trust allow`) covering the source and the file's path admits it at freeze exactly as at preparation. The hold is `needs_human`, and every sync re-screens it, so the setting switched or an allow rule added clears it on the next sync. | Tell the user; whether to edit the file or switch `write_gate.external_mode` back to `quarantine` is their decision. |
| <a id="legacy_slug_conflict"></a><a id="legacy_slug_conflict-explicit_id_conflict"></a>`legacy_slug_conflict` (`explicit_id_conflict`) | The file has no page at its slug, and several live pages an older gbrain imported before the current slug fold (a space, an emoji, an accent or a trailing dash in the slug; no recorded file) fold to that slug (#6727). Exactly one such page is taken over by the file: the next sync imports into it (same page id, links, timeline and aliases) and records the file as its origin, instead of creating a second page. With several, sync cannot tell which page is the file's, so it holds the file and the rest of the source syncs. It holds the file the same way when the one match has a slug sync cannot write as it stands (capital letters, from a gbrain that predates lowercase slugs; the importer lowercases), rather than creating a second page beside it. With reason `explicit_id_conflict` (#6729), the one match carries an explicit frontmatter `id` that differs from the file's, so it is a different document and is not taken over. With `sync.holds=fail` the run stops with `page_identity_changed`. Twins an older sync already created are not merged by this. | Ask the user which page is the file's (`gbrain sync status --source <source> --json` names every candidate slug). Remove each other one with `gbrain delete --source <source> -- '<slug>'` (soft delete, recoverable for 72 h), or rename the file if none of them is its page; with one match under a slug with capitals, which no command can address yet, keep the file held or rename it to a name that folds to another slug (it then imports as a new page beside the old one, which keeps its links). For `explicit_id_conflict`: give the file the page's `id` if it is the same document; otherwise rename the file or delete the old page. Then `gbrain sync --source <source> --no-pull`. The hold re-screens on every sync. |
| <a id="origin_conflict"></a><a id="origin_conflict-no_canonical_claimant"></a><a id="origin_conflict-content_differs"></a><a id="origin_conflict-file_unreadable"></a><a id="origin_conflict-explicit_id_conflict"></a><a id="origin_conflict-visibility_differs"></a><a id="origin_conflict-trust_tier_differs"></a><a id="origin_conflict-twin_has_withdrawals"></a><a id="origin_conflict-twin_slug_path_occupied"></a><a id="origin_conflict-twin_evidence_conflicts"></a>`origin_conflict` (`no_canonical_claimant`, `content_differs`, `file_unreadable`, `explicit_id_conflict`, `visibility_differs`, `trust_tier_differs`, `twin_has_withdrawals`, `twin_slug_path_occupied`, `twin_evidence_conflicts`) | Several live pages of the source record this file as their origin (duplicate-origin twins, #6948). Sync used to stop the whole source with `page_identity_changed`; now only this file is held and the rest of the source syncs. With no reason the pages are verified duplicates: the page the path names (`meta.canonical_slug`), one inline body, a readable file, no conflicting frontmatter ids, one visibility and trust tier, no slug-keyed fact withdrawals or purges, no file at a twin's own slug path and no link, relationship date, timeline entry or raw payload the merge would lose. Right after that managed sync, the heal merges each other page into the canonical one (links, relationship dates, timeline, raw data, user tags, aliases and facts move; its slug becomes an alias; it is soft-deleted without touching the file, restorable for 72 h) and the next sync imports the file. A reason means a person decides: `no_canonical_claimant` (no page, or not exactly one, is the page the path names), `content_differs` (the bodies differ, or one cannot be read), `file_unreadable`, `explicit_id_conflict` (different frontmatter `id`s), `visibility_differs`, `trust_tier_differs` (a merge never raises or lowers a tier), `twin_has_withdrawals`, `twin_slug_path_occupied`, `twin_evidence_conflicts`. With `sync.holds=fail` the run stops with `page_identity_changed`. | `gbrain repair origin-twins --source <source>` (read-only) lists every group with its pages, revisions and verdict. Verified groups: let the next sync heal them, or apply the preview now. A decision: read each page (`gbrain get --source <source> -- '<slug>'`), then either `gbrain repair origin-twins --source <source> --slug '<kept-slug>'` (the others forget the file and stay live; nothing is deleted) or soft-delete the others with `gbrain delete`. Then `gbrain sync --source <source> --no-pull`. The heal's kill switch is `gbrain config set sync.origin_twins.auto_resolve false`. The hold re-screens on every sync. Guide: [origin twins](repair.md#origin-twins). |
+| <a id="page_identity_changed-held"></a><a id="page_identity_changed-several_tombstones"></a><a id="page_identity_changed-spelling"></a><a id="page_identity_changed-identity_differs"></a>`page_identity_changed` (`several_tombstones`, `spelling`, `identity_differs`) held | Managed sync cannot decide which page this file is (GBRA-130). `several_tombstones`: several soft-deleted pages record the file as their origin (`meta.identity_slugs`), so reviving one would be a guess. `spelling`: two files differ only by letter case or separator (`notes/Case.md` and `notes/case.md`), which another platform treats as one file (`meta.identity_paths`); both are held. `identity_differs`: the file maps to a page whose own file is gone, but its frontmatter `id` differs from the page's (`meta.identity_ids`), so it is another document and must not inherit that page's facts, links and history (#6729); the page keeps its slug, id and body, and the deletion of its old file waits with the hold. A sync pass used to stop the whole source with `page_identity_changed`; now only these files are held and the rest of the source syncs. A dry run (and a company source's plan) still refuses the source as before, and a remote sync leaves the files for the owner's sync to hold. The hold needs a person (`sync status` names it `page_identity_decision`) and re-screens on every sync. | `several_tombstones`: restore the page that is this file's (`gbrain restore '<slug>' --source-id <source>`; a live page wins over deleted ones) or purge the others. `spelling`: keep one spelling, rename or remove the others and commit. `identity_differs`: give the file the page's `id` if it is the same document, or rename it so its slug differs, and commit. Then `gbrain sync --source <source> --no-pull`. |
| <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. |
| <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. |
| <a id="file_drift"></a>`file_drift` | Managed sync would have imported a file over a database version of its page that sync never saw (#6712). Every import records its provenance (the bytes left on disk, the page revision it wrote, the parser); a page that moved since that record (a database-only write, write-through off) while its file did not change, or, in a tree walk (first sync, `--full`, an unreachable checkpoint), a page whose file and revision both moved or that has no usable record (an upgraded brain: none, a pre-PR 0 record, a partial one), is imported only when the import changes nothing, a sync request wrote its current revision, or its writer's write-through wrote that revision to the file. Otherwise the file is held, the page keeps the database version and the rest of the source syncs. The hold names `sides` (`database`, `both`, `unknown`) and the database request that wrote the page when there was one; a hold the live pass writes also names its Decision, `side` (`both`, `unknown`, `deleted`) and, for a deleted side, `state` (`tombstone_edited`, `purged_differs`, `file_gone`). Pages under `storage.keep_db` prefixes whose file is clean in committed mode are not held: the pass writes the database copy back to the file (at most 200 per pass, the rest the next pass); an uncommitted edit there is held. Holds of this code never escalate; with `sync.holds=fail` the run stops with `file_drift` instead of holding. | `gbrain sources status <source>` names the page. Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file), decide with the user, apply it with the plan hash, then `gbrain sync --source <source> --no-pull`. Held pages of one Decision resolve together with [`--held --side <side> [--state <state>]`](repair.md#file-drift-held). A changed file or page revision re-screens the hold by itself. |
diff --git a/llms-full.txt b/llms-full.txt
index 4ca2a3c94f..d819745ca3 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7540,6 +7540,7 @@ Every hold and error has three fields, from one table
| `file_unreadable` | page | none | yes | always: only a change to the checkout makes the file readable |
| `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 |
| `origin_conflict_decision` | page | none | yes | always: the pages differ, their ids conflict or none is the page the path names |
+| `page_identity_decision` | page | none | yes | always: only a person decides which page the file is |
| `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/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index ad29e262f8..aa75546208 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -917,6 +917,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.296.0', text: 'An interrupted `gbrain sync --full` no longer ends with the run that started it: the next plain `gbrain sync` continues the re-import under the selection the `--full` started with, and there is no command to abandon it. A `--full` with a narrower selection (a CLI `--exclude`, say) finishes its own re-import and ends `synced` with status reason `selection_scoped`, without moving `last_commit`; the next plain sync then syncs the configured selection. A plain sync closes any open re-import, and stamps `chunker_version` only when the re-import covered the whole configured selection. To pause paid work, rely on the cost gate; to pause everything, set `sync.admission classify_only`.' },
{ since: '0.60.296.0', text: 'A managed sync pass that runs 4 rounds without the source settling (another writer keeps changing it) stops `not_converged`: outcome `resumable`, exit 0, everything it admitted stands, and `next` reruns the same sync. After 3 such passes in a row, `next` switches to a report: `gbrain sync status --source <id> --json` with `safe_to_loop: false` and `fix.next: report`, and a sync job ends needing an operator, so an agent loop stops instead of retrying. The count resets when a pass converges.' },
{ since: '0.60.296.0', text: 'New explicit repair `gbrain repair legacy-twins --source <id>` (#6885) merges the page pairs syncs before #6857 forked: a legacy page with no recorded file whose slug spells the file\'s name differently from today\'s slug rules, and the twin at today\'s slug that records the file. The read-only preview lists each pair (both pages\' ids, slugs and revisions, the file, whether the contents match) and lists as decisions, never merged, pairs whose contents differ, several legacy pages for one twin, twins whose file is missing or drifted, and twins holding a link, relationship date, timeline entry or raw data row the legacy page holds differently (`twin_evidence_conflicts`). `--apply --expect <hash> --yes` merges exactly the approved pairs: the legacy page takes over the file and keeps its id, links and history, the twin\'s links and their dated transitions, timeline, raw data, user-added tags, aliases and the facts other pages state about it move over through the same twin merge as `gbrain repair origin-twins` (#6948), its slug becomes an alias, and the twin is soft-deleted (its file untouched) and purged after 72 hours. It refuses off the owner host (`not_owner_host`), when the checkout cannot be read (`legacy_twins_storage_unknown`), and when the pairs are more than half of a source\'s file-backed pages (`legacy_twin_mass_merge_refused`, unless `GBRAIN_ALLOW_MASS_RECONCILE=1`). Nothing changes on upgrade; it runs only when named.' },
+ { since: '0.60.296.0', text: 'A managed sync of a non-company source that cannot decide which page a file is no longer stops the whole source with `page_identity_changed`: the file alone is held `page_identity_changed` (it needs a person; `meta.reason` names why) and the rest of the source syncs. `several_tombstones`: several deleted pages record the file as their origin; `spelling`: files differing only by letter case or separator (both are held); `identity_differs`: a file whose frontmatter id differs from the page at its slug, which keeps its id, body and slug while its old file\'s deletion waits. A dry run (and a company source) still refuses the source as before, so `gbrain sync --dry-run` reports a refusal where the sync itself holds one file; a remote sync leaves such files for the owner\'s sync to hold.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.ts
index 3f46240031..30bbc25a92 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', origin_conflict: 'conflict', origin_conflict_decision: 'conflict',
+ concurrent_write: 'conflict', revision_conflict: 'conflict', page_identity_changed: 'conflict', legacy_slug_conflict: 'conflict', origin_conflict: 'conflict', origin_conflict_decision: 'conflict', page_identity_decision: 'conflict',
settle_mismatch: 'defect', page_write_failed: 'defect',
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',
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index e158a08c70..89c79ea956 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -90,6 +90,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
// #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.' },
+ // GBRA-130 A-17/B-3/B-4: a held `page_identity_changed` path (sync-status.ts holdVerdict): several tombstones, a spelling twin or a takeover whose ids differ.
+ { code: 'page_identity_decision', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only a person decides which page the file is',
+ human_reason: 'Sync cannot decide which page this file is (several deleted pages record it, another spelling of it collides, or its frontmatter id differs from the page at its slug) and never guesses; a person restores or purges the deleted pages, keeps one spelling, or fixes the id or the file name, commits, then runs gbrain sync --source <source> --no-pull.' },
// 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 50de34b594..4baaf4a05d 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -76,7 +76,9 @@ export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regre
/** GBRA-130 A-6: the path's write failed the same unclassifiable way (an owner exception, an unplaced refusal) on repeated attempts. */
| 'page_write_failed'
/** GBRA-130 A-7: a file sync cannot read as a regular file inside its root (a symlink, a non-regular file, a permission error). */
- | 'file_unreadable';
+ | 'file_unreadable'
+ /** GBRA-130 A-17/B-3/B-4: a path whose page identity sync cannot decide (several tombstones, a spelling twin, a takeover whose ids differ). */
+ | 'page_identity_changed';
/** GBRA-130 A-6: the fault a `page_write_failed` hold stands for (identifiers and classes only, never content). */
export interface PageWriteFailureMeta { code: string; origin: string | null; error_class: string | null; errno: string | null; request_id: string; attempts: number; gbrain_version: string }
/** #6278: what the owner recorded about a preparation it gave up on (step names and vocabulary only, never content). */
@@ -91,7 +93,9 @@ 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 | OriginConflictReason;
+export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | 'explicit_id_conflict' | FenceReason | OriginConflictReason | PageIdentityHoldReason;
+/** GBRA-130: why a `page_identity_changed` hold's path has no page sync may write (A-17, B-3, B-4). */
+export type PageIdentityHoldReason = 'several_tombstones' | 'spelling' | 'identity_differs';
/** #6712 PR 4b: the sides a `file_drift` Decision can be about, and the states of a deleted side (design v3.2 §4). */
export const FILE_DRIFT_SIDES = ['both', 'unknown', 'deleted'] as const;
export type FileDriftSide = typeof FILE_DRIFT_SIDES[number];
@@ -165,6 +169,12 @@ export interface GitHoldMeta {
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;
+ /** GBRA-130 `page_identity_changed`: the pages involved (the tombstones recording the origin, or the page whose slug a file would take over). */
+ identity_slugs?: string[];
+ /** GBRA-130 `page_identity_changed` (`spelling`): the other spellings of the origin, in the source's path form. */
+ identity_paths?: string[];
+ /** GBRA-130 `page_identity_changed` (`identity_differs`): the frontmatter ids of the page and of the file. */
+ identity_ids?: { page: string; file: string };
}
/** #6188: why the last fence repair left a hold in place, and when the maintenance run tries it again (null: it does not). */
@@ -529,10 +539,11 @@ export async function holdBasisMoved(engine: Pick<BrainEngine, 'executeRaw'>, so
* 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. #6948: and an
- * `origin_conflict` hold, which rests on the twin pages the heal, the repair or a person removes.
+ * `origin_conflict` hold, which rests on the twin pages the heal, the repair or a person removes. GBRA-130: and a `page_identity_changed`
+ * hold, which rests on pages (tombstones, a page at the slug) or spellings a person changes.
*/
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', 'origin_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', 'page_identity_changed'].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())
@@ -778,6 +789,23 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'user', requires_exclusive: false,
user_message: `gbrain refuses ${record.path}, whose exact bytes imported under an earlier version. This is a gbrain bug: report it with the gbrain version, the file and the code, then upgrade or pin the last good version.`,
why: 'The same bytes imported before, so only gbrain changed; sync holds the file under GBRAIN_SYNC_PARSER_REGRESSION=hold.' };
+ case 'page_identity_changed': {
+ const slugs = record.meta.identity_slugs ?? [], paths = record.meta.identity_paths ?? [], ids = record.meta.identity_ids;
+ 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 its page identity is decided (this hold is re-screened on every sync); the file then imports.` };
+ const user_message = record.meta.reason === 'several_tombstones'
+ ? `Deleted pages ${slugs.map(slug => JSON.stringify(slug)).join(', ')} all record ${record.path} as their origin, so sync cannot tell which one the file is and held only this file; the rest of the source keeps syncing. `
+ + `Restore the page that is this file's (gbrain restore '<slug>' --source-id ${source}; a live page wins over the deleted ones) or purge the others, then run gbrain sync --source ${source} --no-pull.`
+ : record.meta.reason === 'spelling'
+ ? `${record.path} and ${paths.length ? paths.join(', ') : 'another file'} differ only by letter case or separator, which another platform treats as one file, so sync held them rather than guess which is the page's; the rest of the source keeps syncing. `
+ + `Keep one spelling, rename or remove the others and commit, then run gbrain sync --source ${source} --no-pull.`
+ : `${record.path} maps to page ${JSON.stringify(slugs[0] ?? record.slug ?? '')}, whose file is gone, but its frontmatter id ${JSON.stringify(ids?.file ?? '')} differs from the page's id ${JSON.stringify(ids?.page ?? '')}, so it is a different document and sync held it rather than give it that page's facts, links and history; the rest of the source keeps syncing. `
+ + `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 --source ${source} --no-pull.`;
+ return { argv: verify.argv, consent: [], actor: 'user', requires_exclusive: false, docs: gitHoldDocs(record.code, record.meta.reason), user_message,
+ why: 'Which page a file is cannot be decided when several deleted pages record it, when spellings another platform folds together collide, or when the ids say it is another document; sync never guesses a page identity.',
+ then, verify };
+ }
case 'legacy_slug_conflict': {
const slugs = record.meta.legacy_slugs ?? [];
const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.ts
index f2c2378360..a8206a8812 100644
--- a/src/core/persistence/sync-pass-apply.ts
+++ b/src/core/persistence/sync-pass-apply.ts
@@ -72,7 +72,7 @@ const LEVEL_BLOB_MAX_BYTES = 8 * 1024 * 1024;
/** What a pass applied across its rounds (kept in memory; its counts go into the pass row's telemetry). */
export interface PassApplyState {
markersRetired: number;
- holds: { file_gone: number; tombstone_edited: number; purged_differs: number; settle_mismatch: number; origin_conflict: number };
+ holds: { file_gone: number; tombstone_edited: number; purged_differs: number; settle_mismatch: number; origin_conflict: number; page_identity_changed: number };
settleMismatch: string[];
adopted: number;
swept: { screened: number; recorded: number };
@@ -84,7 +84,7 @@ export interface PassApplyState {
keepDb: { admitted: number; pending: number; paused: number; refused: Record<string, number> };
/** keep_db paths admitted in this pass: never admitted twice. */
keepDbTaken: string[];
- /** #6948: paths this pass held `origin_conflict` (re-screen due, so a later round reads them again): held once per pass. */
+ /** #6948: paths this pass held `origin_conflict` (GBRA-130: or `page_identity_changed`; re-screen due, so a later round reads them again): held once per pass. */
originHeld: Set<string>;
matchedSlugs: Set<string>;
/** The newest round's classes and summary (design §9), after this module settled what it finished. */
@@ -98,7 +98,7 @@ export interface PassApplyState {
}
export function newPassApplyState(): PassApplyState {
- return { markersRetired: 0, holds: { file_gone: 0, tombstone_edited: 0, purged_differs: 0, settle_mismatch: 0, origin_conflict: 0 }, settleMismatch: [], adopted: 0,
+ return { markersRetired: 0, holds: { file_gone: 0, tombstone_edited: 0, purged_differs: 0, settle_mismatch: 0, origin_conflict: 0, page_identity_changed: 0 }, settleMismatch: [], adopted: 0,
swept: { screened: 0, recorded: 0 }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], originHeld: new Set(), matchedSlugs: new Set(), classes: {}, summary: null, recorded: new Set() };
}
@@ -148,7 +148,8 @@ export async function applyPassRound(engine: BrainEngine, level: ShadowLevel, in
await applyDeleteValve(engine, level, input, state);
if (input.remote) {
// #6948: a remote pass writes no hold, so a path several live pages claim is left as it is for the owner's pass to hold.
- for (const entry of level.paths) if (entry.ambiguousOrigin?.kind === 'several_live' && !entry.result.settled && !entry.result.inFlight) settleAs(entry, { settled: true, action: 'none', classAction: 'repair' });
+ // GBRA-130: so is a path several tombstones record, and a spelling twin (A-17, B-3).
+ for (const entry of level.paths) if ((entry.ambiguousOrigin || entry.result.cls === 'spelling') && !entry.result.settled && !entry.result.inFlight) settleAs(entry, { settled: true, action: 'none', classAction: 'repair' });
summarizeRound(level, state);
return;
}
@@ -242,8 +243,8 @@ async function applyDeleteValve(engine: BrainEngine, level: ShadowLevel, input:
/** Rows 6 and 9 and the settle-mismatch streak (§3.1): holds at level `L`, written under the drain lease. */
async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {
- type Pending = { entry: ShadowPath; code: GitHoldCode; message: string; slug: string | null; meta: Partial<GitHoldMeta>; kind: keyof PassApplyState['holds']; pageId?: null };
- const pending: Pending[] = [];
+ const pending: PendingHold[] = [];
+ let spellings: Map<string, string[]> | undefined;
// A held rename's origin waits for its destination's hold (#5988), whatever its page did meanwhile.
const heldRenameOrigins = new Set(level.heldRenames.map(held => syncOriginPath(held.rename.sourcePath)));
const step = loopYield();
@@ -261,6 +262,19 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Pa
continue;
}
if (r.settled) continue;
+ // GBRA-130 A-17 / B-3: a path whose page identity sync cannot decide is held alone; discovery (a dry run, a company plan) still refuses.
+ const identity = r.cls === 'spelling' ? 'spelling' as const : entry.ambiguousOrigin?.kind === 'several_tombstones' ? 'several_tombstones' as const : null;
+ if (identity) {
+ if (state.originHeld.has(entry.path)) { settleAs(entry, { cls: 'held', settled: true, action: 'none', classAction: 'repair' }); continue; }
+ const others = identity === 'spelling' ? ((spellings ??= spellingGroups(level)).get(spellingKey(sourcePath)) ?? []).filter(other => other !== sourcePath) : [];
+ pending.push(identity === 'spelling'
+ ? { entry, code: 'page_identity_changed', kind: 'page_identity_changed', slug: entry.slug ?? resolveSlugForPath(sourcePath) ?? null, meta: { reason: 'spelling', identity_paths: others },
+ message: `${path} and ${others.join(', ') || 'another file'} differ only by letter case or separator, which another platform treats as one file, so sync held them instead of guessing which is the page's; the rest of the source synced.` }
+ : { entry, code: 'page_identity_changed', kind: 'page_identity_changed', slug: entry.slug ?? entry.ambiguousOrigin!.slugs[0] ?? null, pageId: null,
+ meta: { reason: 'several_tombstones', identity_slugs: entry.ambiguousOrigin!.slugs },
+ message: `Deleted pages ${entry.ambiguousOrigin!.slugs.join(', ')} all record ${path} as their origin, so sync held this file instead of guessing which page it is; the rest of the source synced.` });
+ continue;
+ }
const streak = input.obligations.mismatch?.[entry.path];
if (streak && streak.streak >= SETTLE_MISMATCH_STREAK && streak.level === entry.state.level) {
pending.push({ entry, code: 'settle_mismatch', slug: entry.slug, kind: 'settle_mismatch', meta: { mismatch_streak: streak.streak },
@@ -279,6 +293,34 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Pa
: `${path}: page ${slug} was deleted in the database, and the file changed since, so sync held the file instead of reviving the page; the rest of the source synced.` });
}
}
+ await writeHolds(engine, level, input, state, pending);
+}
+
+/**
+ * GBRA-130 B-4: holds the imports `batchEntries` found would take over a page at their slug whose frontmatter id differs
+ * from the file's (another document), in the same shape as `writePassHolds`; discovery (a dry run, a company plan) still refuses.
+ */
+export async function holdPassIdentities(engine: BrainEngine, level: ShadowLevel, input: Pick<PassApplyInput, 'passId' | 'observedAt'>, state: PassApplyState,
+ items: ReadonlyArray<{ entry: ShadowPath; slug: string; ids: { page: string; file: string } }>): Promise<void> {
+ await writeHolds(engine, level, input, state, items.map(({ entry, slug, ids }) => ({ entry, code: 'page_identity_changed' as const, kind: 'page_identity_changed' as const, slug, pageId: null,
+ meta: { reason: 'identity_differs' as const, identity_slugs: [slug], identity_ids: ids },
+ message: `${passEntryPaths(level, entry.path).path} maps to page ${slug}, whose file is gone, but its frontmatter id '${ids.file}' differs from the page's id '${ids.page}', so it is a different document; sync held it and kept the page instead of giving the file that page's facts, links and history; the rest of the source synced.` })));
+}
+
+type PendingHold = { entry: ShadowPath; code: GitHoldCode; message: string; slug: string | null; meta: Partial<GitHoldMeta>; kind: keyof PassApplyState['holds']; pageId?: null };
+const spellingKey = (sourcePath: string) => sourcePath.replaceAll('\\', '/').toLowerCase();
+/** The level's spelling twins by their folded spelling (only built when a round has one). */
+function spellingGroups(level: ShadowLevel): Map<string, string[]> {
+ const groups = new Map<string, string[]>();
+ for (const entry of level.paths) if (entry.result.cls === 'spelling') {
+ const { sourcePath } = passEntryPaths(level, entry.path);
+ groups.set(spellingKey(sourcePath), [...groups.get(spellingKey(sourcePath)) ?? [], sourcePath]);
+ }
+ return groups;
+}
+
+/** Writes the round's holds at level `L` under the drain lease, counts them and settles their paths `held`. */
+async function writeHolds(engine: BrainEngine, level: ShadowLevel, input: Pick<PassApplyInput, 'passId' | 'observedAt'>, state: PassApplyState, pending: PendingHold[]): Promise<void> {
if (!pending.length) return;
await engine.transaction(async tx => {
await assertDrainLease(tx, level.sourceId);
@@ -293,7 +335,7 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Pa
for (const hold of pending) {
state.holds[hold.kind]++;
if (hold.code === 'settle_mismatch') state.settleMismatch.push(passEntryPaths(level, hold.entry.path).path);
- if (hold.code === 'origin_conflict') state.originHeld.add(hold.entry.path);
+ if (hold.code === 'origin_conflict' || hold.code === 'page_identity_changed') state.originHeld.add(hold.entry.path);
settleAs(hold.entry, { cls: 'held', settled: true, action: 'none', classAction: 'repair' });
}
}
@@ -458,7 +500,7 @@ export async function finishPassApply(engine: BrainEngine, sourceId: string, sta
export function passApplyCounts(state: PassApplyState): Record<string, number> {
const refused = Object.values(state.keepDb.refused).reduce((a, b) => a + b, 0);
return { markers_retired: state.markersRetired, holds_file_gone: state.holds.file_gone, holds_tombstone_edited: state.holds.tombstone_edited,
- holds_purged_differs: state.holds.purged_differs, holds_settle_mismatch: state.holds.settle_mismatch, holds_origin_conflict: state.holds.origin_conflict, adopted: state.adopted, legacy_swept: state.swept.screened,
+ holds_purged_differs: state.holds.purged_differs, holds_settle_mismatch: state.holds.settle_mismatch, holds_origin_conflict: state.holds.origin_conflict, holds_page_identity_changed: state.holds.page_identity_changed, adopted: state.adopted, legacy_swept: state.swept.screened,
legacy_recorded: state.swept.recorded, deletes_withheld: state.withheldCount, keep_db_admitted: state.keepDb.admitted, keep_db_pending: state.keepDb.pending,
paused_keep_db: state.keepDb.paused, keep_db_refused: refused };
}
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 5fe3641e62..04dd50886f 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -14,7 +14,6 @@
* converging stop `resumable` (`not_converged`).
*/
import { randomUUID } from 'node:crypto';
-import { opError } from '../ops/contract.ts';
import { confirmedSyncDelta, confirmRenameIdentities, explicitIdVeto } from '../sync-rename-identity.ts';
import { buildDetachedWorkingTreeManifest } from '../sync-delta.ts';
import type { DowngradedRename, SyncManifest } from '../sync.ts';
@@ -25,7 +24,7 @@ import { getWriteRequestById } from './journal.ts';
import type { WriteRequest } from './model.ts';
import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';
import { recordedStop, replaysUnchangedRefusal } from './sync-stop-class.ts';
-import { adoptLegacyPage, ambiguousOriginRefusal, assertTakeoverIdentity, incomingId, syncExcludePatterns, syncGit, type LegacyIdentity, type ManagedSyncContext, type SyncDiscovery, type SyncEntry, type SyncFileRefusal, type SyncSlugCollision } from './sync-discovery.ts';
+import { adoptLegacyPage, incomingId, syncExcludePatterns, syncGit, type LegacyIdentity, type ManagedSyncContext, type SyncDiscovery, type SyncEntry, type SyncFileRefusal, type SyncSlugCollision } from './sync-discovery.ts';
import { assertSyncDispatchActive, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
import { recordPassFenceTrend, type PassStamp, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';
import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP, writePassRow, type ManagedSyncPassValue, type PassEpisode,
@@ -56,7 +55,7 @@ import { databaseOnlyPageSql } from './unbound-pages.ts';
import { originMarkerFingerprint } from './sync-markers.ts';
import { SYNC_SLICE_OP } from './sync-slices.ts';
import { passResumeArgs } from './sync-pass-readers.ts';
-import { applyPassRound, finishPassApply, newPassApplyState, passApplyCounts, remoteReconcile } from './sync-pass-apply.ts';
+import { applyPassRound, finishPassApply, holdPassIdentities, newPassApplyState, passApplyCounts, remoteReconcile } from './sync-pass-apply.ts';
import { passCostDecision, passEpisodeClosure, readReservedUsd, registerPassCost, unregisterPassCost } from './sync-pass-episode.ts';
import { currentEmbeddingPricePerMTok } from '../embedding.ts';
import { SIZE_STATE_SAMPLE, type SyncSizeStates } from '../page-embedding-budget.ts';
@@ -144,7 +143,8 @@ function entryPaths(level: ShadowLevel, gitPath: string): { path: string; source
* page moves to the new slug). Deletes first, then imports.
*/
async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: ShadowPath[], imports: ShadowPath[]):
- Promise<{ entries: PassEntry[]; collisions: SyncSlugCollision[]; skipped: ShadowPath[]; downgrades: DowngradedRename[] }> {
+ Promise<{ entries: PassEntry[]; collisions: SyncSlugCollision[]; skipped: ShadowPath[]; downgrades: DowngradedRename[];
+ identity: Array<{ entry: ShadowPath; origin: ShadowPath | null; slug: string; ids: { page: string; file: string } }> }> {
const working = (entry: ShadowPath) => level.mode === 'working' && entry.state.level !== entry.state.tree;
const deleteEntries = new Map<string, PassEntry>(deletes.map(entry => [entry.path, { ...entryPaths(level, entry.path), action: 'delete' as const, working: level.mode === 'working',
slug: entry.slug!, pageId: entry.pageId, revision: entry.revision, level: null }]));
@@ -176,7 +176,7 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh
const bothDrift = imports.filter(entry => entry.result.cls === 'drift' && entry.result.side === 'both' && entry.pageId !== null);
const baselineRecords = await readSyncImportProvenances(engine, level.sourceId, level.incarnation, bothDrift.map(entry => entry.pageId!));
const driftBaseline = (entry: ShadowPath) => entry.result.side === 'both' && entry.pageId !== null ? baselineRecords.get(entry.pageId)?.disk_blob_oid ?? undefined : undefined;
- const entries: PassEntry[] = [], collisions: SyncSlugCollision[] = [], skipped: ShadowPath[] = [];
+ const entries: PassEntry[] = [], collisions: SyncSlugCollision[] = [], skipped: ShadowPath[] = [], identity: Array<{ entry: ShadowPath; origin: ShadowPath | null; slug: string; ids: { page: string; file: string } }> = [];
const claims = new Map<string, ShadowPath[]>();
for (const entry of imports) {
const paths = entryPaths(level, entry.path);
@@ -217,8 +217,14 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh
const paths = entryPaths(level, winner.path);
const base = { ...paths, action: 'import' as const, working: working(winner), level: winner.state.level, slug, ...legacySlugs.get(winner.path) };
if (holder) {
- // #6729: a file whose frontmatter id differs from the page's is another document; it inherits nothing (refused before any write).
- assertTakeoverIdentity(discovery, named(winner), holder);
+ // #6729: a file whose frontmatter id differs from the page's is another document; it inherits nothing. GBRA-130 B-4: it is
+ // held alone and the page keeps its slug (its origin's deletion waits with it); discovery still refuses the source.
+ const incoming = holder.fm_id ? incomingId(discovery, named(winner)) : null;
+ if (explicitIdVeto(incoming, holder.fm_id)) {
+ identity.push({ entry: winner, origin: deletes.find(entry => entry.path === holderPath) ?? null, slug, ids: { page: holder.fm_id!, file: incoming! } });
+ if (holderPath !== null) deleteEntries.delete(holderPath);
+ continue;
+ }
// A live page at the slug with no recorded origin (written straight to the database, or by an older gbrain) attests
// neither side: the import is guarded as drift of unknown side, so the freeze imports it only as a proven no-op and
// otherwise holds file_drift (as discovery's tree walk guards it, sync-prescreen.ts). A page written while the source was
@@ -255,7 +261,7 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh
}
entries.push({ ...base, pageId: null, revision: null });
}
- return { entries: [...deleteEntries.values(), ...entries.sort((a, b) => a.path.localeCompare(b.path))], collisions, skipped, downgrades };
+ return { entries: [...deleteEntries.values(), ...entries.sort((a, b) => a.path.localeCompare(b.path))], collisions, skipped, downgrades, identity };
}
/**
@@ -454,9 +460,9 @@ async function triageRound(level: ShadowLevel, input: { S: Map<string, string>;
if (r.settled) continue;
if (r.inFlight) { inFlight.push(entry); continue; }
if (S.has(settledKey(entry.path, entry.state.level))) {
- // A hold this pass wrote or re-screened at L, or a slug collision it skipped, is that path's fate here, even when
- // its code re-screens every pass or the skipped twin still classifies as an import.
- if (entry.state.hold?.atLevel || S.get(settledKey(entry.path, entry.state.level)) === 'collision'
+ // A hold this pass wrote or re-screened at L, a slug collision it skipped, or the origin deletion an identity hold keeps
+ // (GBRA-130 B-4) is that path's fate here, even when its code re-screens every pass or the skipped twin still classifies as an import.
+ if (entry.state.hold?.atLevel || ['collision', 'identity_origin'].includes(S.get(settledKey(entry.path, entry.state.level))!)
|| legacyWaived.has(settledKey(entryPaths(level, entry.path).path, entry.state.level))) continue;
// Design §3.1: admitted at most once more per (path, level) in this pass, then counted as a settle mismatch.
const again = settledKey(entry.path, entry.state.level);
@@ -764,13 +770,6 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
await writeLegacyMarkers(engine, level);
value.obligations.legacy_markers_at = new Date().toISOString();
}
- // #6517, as discovery refuses a claim: several tombstones record the origin of a path this pass would act on (before any
- // hold). Several live pages hold that path alone (#6948 `origin_conflict`, sync-pass-apply.ts) and the rest syncs.
- const ambiguous = level.paths.find(entry => entry.ambiguousOrigin?.kind === 'several_tombstones' && !entry.result.settled && !entry.result.inFlight && entry.result.cls !== 'spelling');
- if (ambiguous) {
- await save('blocked', 'page_identity_changed');
- throw ambiguousOriginRefusal(sourceId, entryPaths(level, ambiguous.path).sourcePath, ambiguous.ambiguousOrigin!.slugs.map(slug => ({ slug })), ambiguous.ambiguousOrigin!.kind);
- }
await applyPassRound(engine, level, { passId, observedAt: startedAt, remote, admission, fullRound: kind === 'full', obligations: value.obligations, context, processingOptions,
grantPrefixes: remote ? authority.writer.slugPrefixes : null }, applied);
assertActive();
@@ -778,13 +777,6 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (!remote) value.obligations.deletes_withheld = applied.withheld?.set_hash ?? null;
const { deletes, imports, inFlight, mismatch, owed } = await triageRound(level, { S, legacyWaived, readmitted, admission, remote, counts });
lastMismatch = mismatch;
- // Origins that differ only by case or separator spelling may be one file on another platform: refuse rather than guess, as discovery does.
- const spelled = owed.filter(entry => entry.result.cls === 'spelling').map(entry => entryPaths(level, entry.path).sourcePath);
- if (spelled.length) {
- await save('blocked', 'page_identity_changed');
- throw opError('page_identity_changed', 'Sync origins for one slug differ only by case or separator spelling.',
- `Files in ${sourceId} differ only by case or separator spelling (${spelled.slice(0, 3).join(', ')}); nothing was written. Keep one spelling, rename or remove the others and commit, then run gbrain sync --no-pull --source ${sourceId}.`);
- }
const candidates = deletes.length + imports.length;
if (round === 1) candidatesFirst = candidates + inFlight.length + owed.length;
value.telemetry.candidates = candidatesFirst;
@@ -835,6 +827,11 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
throw error;
});
collisions.push(...built.collisions);
+ if (!remote && built.identity.length) await holdPassIdentities(engine, level, { passId, observedAt: startedAt }, applied, built.identity);
+ for (const { entry, origin } of built.identity) {
+ S.set(settledKey(entry.path, entry.state.level), 'held');
+ if (origin) S.set(settledKey(origin.path, origin.state.level), 'identity_origin');
+ }
identityDowngrades.push(...built.downgrades.filter(pair => !identityDowngrades.some(seen => seen.from === pair.from && seen.to === pair.to)));
for (const entry of [...built.skipped, ...built.collisions.flatMap(c => c.skipped.map(sourcePath => imports.find(i => entryPaths(level, i.path).sourcePath === sourcePath)!))].filter(Boolean)) {
S.set(settledKey(entry.path, entry.state.level), 'collision'); counts.collisions++;
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index cebcaf04a8..8c00b1df59 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -219,6 +219,7 @@ export function holdVerdict(record: GitHoldRecord, auto: FenceAutoRepair | undef
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 });
+ if (record.code === 'page_identity_changed') return classifySyncFault({ code: record.code, detail: 'page_identity_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/test/behavior-change-notice-6712-block.test.ts b/test/behavior-change-notice-6712-block.test.ts
index c527620ee1..1964939d8e 100644
--- a/test/behavior-change-notice-6712-block.test.ts
+++ b/test/behavior-change-notice-6712-block.test.ts
@@ -12,7 +12,7 @@ import { join } from 'node:path';
import { BEHAVIOR_CHANGES, compareReleases } from '../src/core/behavior-change-notice.ts';
const MARKER = '// #6712 PR 4b (the level-triggered sync pass';
-const ROWS = 23;
+const ROWS = 24;
const NOTICE_CAP = 2_000;
/** The array literal's row lines in order, and where the block's rows start and how many there are. */
diff --git a/test/persistence-managed-lifecycle.test.ts b/test/persistence-managed-lifecycle.test.ts
index 197a8cecf8..29b6ef2b9c 100644
--- a/test/persistence-managed-lifecycle.test.ts
+++ b/test/persistence-managed-lifecycle.test.ts
@@ -151,9 +151,14 @@ test('a file that replaces its vanished origin at the same slug takes over the p
test('two new files whose paths differ only by case are refused rather than guessed', async () => withEnv({ GBRAIN_HOME: home }, async () => {
for (const engine of engines) {
- const f = await fixture(engine, { 'notes/Case.md': note('Upper', 'Upper case spelling.'), 'notes/case.md': note('Lower', 'Lower case spelling.') });
- await expect(performManagedSync(engine, { sourceId: f.id, noPull: true })).rejects.toMatchObject({ code: 'page_identity_changed' });
+ const f = await fixture(engine, { 'notes/Case.md': note('Upper', 'Upper case spelling.'), 'notes/case.md': note('Lower', 'Lower case spelling.'), 'notes/other.md': note('Other', 'An unrelated note.') });
+ // GBRA-130 B-3 (was: the sync refused page_identity_changed): each spelling is held alone, nothing is imported at either
+ // spelling or their slug, and the rest of the source imports.
+ const result = await performManagedSync(engine, { sourceId: f.id, noPull: true });
+ expect(result.held?.map(hold => [hold.path, hold.code, hold.reason]).sort()).toEqual([['notes/Case.md', 'page_identity_changed', 'spelling'], ['notes/case.md', 'page_identity_changed', 'spelling']]);
expect(await engine.getPage('notes/case', { sourceId: f.id })).toBeNull();
+ expect(await engine.getPage('notes/other', { sourceId: f.id })).not.toBeNull();
+ expect(await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND intent->>'path' IN ('notes/Case.md','notes/case.md')", [f.id])).toEqual([]);
}
}), 180_000);
diff --git a/test/persistence-sync-origin-native.test.ts b/test/persistence-sync-origin-native.test.ts
index a0b8de2f80..9cda89a794 100644
--- a/test/persistence-sync-origin-native.test.ts
+++ b/test/persistence-sync-origin-native.test.ts
@@ -236,8 +236,15 @@ check('native historical separator identity preserves the original page or refus
expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);
} else {
await expect(performManagedSync(engine, { ...f.opts, dryRun: true })).rejects.toMatchObject({ code: 'page_identity_changed' });
- await expect(performManagedSync(engine, f.opts)).rejects.toMatchObject({ code: 'page_identity_changed' });
- expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ // GBRA-130 B-3 (was: the pass refused page_identity_changed): both spellings are held, neither is imported or deleted,
+ // and an unrelated file in the same sync imports.
+ writeFileSync(join(f.root, 'notes/other.md'), 'An unrelated synthetic note.\n');
+ execFileSync('git', ['-C', f.root, 'add', 'notes/other.md']);
+ execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Add an unrelated note']);
+ const result = await performManagedSync(engine, f.opts);
+ expect(result.held?.map(hold => [hold.path, hold.code, hold.reason]).sort()).toEqual([['notes/example.md', 'page_identity_changed', 'spelling'], ['notes\\example.md', 'page_identity_changed', 'spelling']]);
+ expect(await engine.executeRaw("SELECT intent->>'path' AS path FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' <> 'managed_sync_checkpoint' ORDER BY path", [f.id])).toEqual([{ path: 'notes/other.md' }]);
+ expect(await engine.getPage('notes/other', { sourceId: f.id })).not.toBeNull();
expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
}
expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
@@ -248,13 +255,16 @@ check('native historical separator identity preserves the original page or refus
check('native Windows historical alias cannot become a delete plus replacement identity', async engine => {
if (process.platform !== 'win32') {
const literal = 'notes\\example.md', literalSlug = resolveSlugForPath(literal);
- const f = await fixture(engine, literal, literalSlug, { [literal]: content, 'notes/example.md': content.replace('stable', 'separate') });
+ const f = await fixture(engine, literal, literalSlug, { [literal]: content, 'notes/example.md': content.replace('stable', 'separate'), 'notes/other.md': 'An unrelated synthetic note.\n' });
const history = await engine.getVersions(f.slug, { sourceId: f.id });
await expect(performManagedSync(engine, { ...f.opts, dryRun: true })).rejects.toMatchObject({ code: 'page_identity_changed' });
- await expect(performManagedSync(engine, f.opts)).rejects.toMatchObject({ code: 'page_identity_changed' });
+ // GBRA-130 B-3 (was: the pass refused page_identity_changed): both spellings are held, the page is neither deleted nor
+ // replaced, and an unrelated file in the same sync imports.
+ const result = await performManagedSync(engine, f.opts);
+ expect(result.held?.map(hold => [hold.path, hold.code, hold.reason]).sort()).toEqual([['notes/example.md', 'page_identity_changed', 'spelling'], ['notes\\example.md', 'page_identity_changed', 'spelling']]);
expect((await engine.getPage(literalSlug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
- expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1', [f.id])).toHaveLength(1);
- expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ expect((await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1', [f.id])).map(row => row.slug).sort()).toEqual([literalSlug, 'notes/other'].sort());
+ expect(await engine.executeRaw("SELECT intent->>'path' AS path FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' <> 'managed_sync_checkpoint' ORDER BY path", [f.id])).toEqual([{ path: 'notes/other.md' }]);
expect(readFileSync(join(f.root, literal), 'utf8')).toBe(content);
expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toContain('separate');
expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
@@ -302,9 +312,15 @@ for (const alias of [false, true]) check(`native historical ${alias ? 'alias' :
expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);
expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);
if (process.platform !== 'win32' && !alias) {
- await expect(performManagedSync(engine, opts)).rejects.toMatchObject({ code: 'page_identity_changed' });
- expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
- expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);
+ // GBRA-130 B-3 (was: the pass refused page_identity_changed): both spellings are held, neither is imported or deleted,
+ // and the unrelated notes/untouched.md imports.
+ const result = await performManagedSync(engine, opts);
+ expect(result).toMatchObject({ status: 'synced', fromCommit: f.head, toCommit: target, deleted: 0, filesImported: 1 });
+ expect(result.held?.map(hold => [hold.path, hold.code, hold.reason]).sort()).toEqual([['notes/example.md', 'page_identity_changed', 'spelling'], ['notes\\example.md', 'page_identity_changed', 'spelling']]);
+ expect(await engine.executeRaw("SELECT intent->>'path' AS path FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' <> 'managed_sync_checkpoint' ORDER BY path", [f.id])).toEqual([{ path: 'notes/untouched.md' }]);
+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);
+ expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);
+ expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(target);
} else {
// #6712 PR 4b: the first pass reads the whole level, so the unchanged notes/untouched.md, which has no page yet, is
// imported beside the changed file (the cursor's incremental delta saw only the change). The historical origin's page
@@ -439,7 +455,7 @@ check('an explicit working-tree deletion of a page no sync import recorded is he
});
check('native case aliases refuse rather than merge distinct origins', async engine => {
- const f = await fixture(engine, 'Notes/example.md', 'notes/example', { 'Notes/example.md': content });
+ const f = await fixture(engine, 'Notes/example.md', 'notes/example', { 'Notes/example.md': content, 'other.md': 'An unrelated synthetic note.\n' });
const object = execFileSync('git', ['-C', f.root, 'rev-parse', 'HEAD:Notes/example.md'], { encoding: 'utf8' }).trim();
execFileSync('git', ['-C', f.root, '-c', 'core.ignorecase=false', 'update-index', '--add', '--cacheinfo', `100644,${object},notes/example.md`]);
execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Add case-distinct tree entry']);
@@ -447,9 +463,15 @@ check('native case aliases refuse rather than merge distinct origins', async eng
mkdirSync(join(f.root, 'notes'), { recursive: true });
writeFileSync(join(f.root, 'notes/example.md'), content);
}
- await expect(performManagedSync(engine, f.opts)).rejects.toMatchObject({ code: 'page_identity_changed' });
+ // GBRA-130 B-3 (was: the pass refused page_identity_changed): the case spellings are held, neither is imported or
+ // deleted, and an unrelated file in the same sync imports.
+ const result = await performManagedSync(engine, f.opts);
+ const held = result.held?.map(hold => [hold.path, hold.code, hold.reason]).sort();
+ if (process.platform === 'linux') expect(held).toEqual([['Notes/example.md', 'page_identity_changed', 'spelling'], ['notes/example.md', 'page_identity_changed', 'spelling']]);
+ else for (const hold of held ?? []) expect(hold).toEqual([expect.stringMatching(/^[Nn]otes\/example\.md$/), 'page_identity_changed', 'spelling']);
+ expect(held?.length).toBeGreaterThan(0);
expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
- expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
+ expect(await engine.executeRaw("SELECT intent->>'path' AS path FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' <> 'managed_sync_checkpoint' ORDER BY path", [f.id])).toEqual([{ path: 'other.md' }]);
expect(readFileSync(join(f.root, 'Notes/example.md'), 'utf8')).toBe(content);
expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toBe(content);
});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 58bfb13c92..9d9ab1afb7 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -313,6 +313,7 @@ test/sync-legacy-holds.test.ts
test/sync-legacy-retry-actions-6696.test.ts
test/sync-legacy-slug-adoption-6727.test.ts
test/sync-origin-live-wins-6517.test.ts
+test/sync-page-identity-hold-gbra130.test.ts
test/sync-page-write-failed-gbra130.test.ts
test/sync-pass-cost-grouping-gbra130.test.ts
test/sync-pass-dirty-after-freeze-gbra130.test.ts
diff --git a/test/sync-inexact-rename-6729.test.ts b/test/sync-inexact-rename-6729.test.ts
index 268d35ae9b..51548cb8f7 100644
--- a/test/sync-inexact-rename-6729.test.ts
+++ b/test/sync-inexact-rename-6729.test.ts
@@ -383,8 +383,18 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,
if (mode === 'classic') continue;
// Managed discovery's same-slug takeover: only a conflicting explicit id vetoes it, before anything is written.
git(s.root, 'mv', 'notes/Id Doc.md', 'notes/id-doc.md'); write(s.root, 'notes/id-doc.md', doc('id: id-doc-two-6729\ntitle: Id doc', 'Another document.\n'));
+ write(s.root, 'notes/unrelated-6729.md', doc('title: Unrelated 6729'));
commit(s.root, 'respell with a different id');
- await expect(s.sync()).rejects.toMatchObject({ code: 'page_identity_changed', detail: 'rename_identity_conflict' });
+ // GBRA-130 B-4 (was: the sync refused page_identity_changed / rename_identity_conflict): the file alone is held and the page keeps
+ // its slug, id and body; the rest of the source syncs.
+ const held = await s.sync();
+ expect(held.held?.map(hold => [hold.path, hold.code, hold.reason])).toEqual([['notes/id-doc.md', 'page_identity_changed', 'identity_differs']]);
+ expect(await pageRow(s.id, 'notes/unrelated-6729')).toMatchObject({ deleted_at: null });
+ expect((await engine.executeRaw<{ id: string }>("SELECT frontmatter->>'id' AS id FROM pages WHERE source_id=$1 AND slug=$2", [s.id, 'notes/id-doc']))[0]?.id).toBe('id-doc-one-6729');
+ expect((await engine.executeRaw<{ compiled_truth: string }>("SELECT compiled_truth FROM pages WHERE source_id=$1 AND slug=$2", [s.id, 'notes/id-doc']))[0]?.compiled_truth).not.toContain('Another document');
+ expect((await pageRow(s.id, 'notes/id-doc'))).toMatchObject({ id: idDoc.id, deleted_at: null });
+ // The origin's deletion waits with the hold on the next pass too.
+ expect((await s.sync()).held?.map(hold => [hold.path, hold.reason])).toEqual([['notes/id-doc.md', 'identity_differs']]);
expect((await pageRow(s.id, 'notes/id-doc'))).toMatchObject({ id: idDoc.id, deleted_at: null });
}
}), 240_000);
@@ -455,8 +465,18 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,
const one = (await pageRow(s.id, 'notes/foo-bar'))!;
git(s.root, 'rm', '-q', 'notes/Foo Bar.md');
write(s.root, 'notes/foo-bar.md', doc('id: doc-two-6729\ntitle: Document two', 'A different document.\n'));
+ write(s.root, 'notes/unrelated-6729.md', doc('title: Unrelated 6729'));
commit(s.root, 'replace with a different document at the same slug');
- await expect(s.sync()).rejects.toMatchObject({ code: 'page_identity_changed', detail: 'rename_identity_conflict' });
+ // GBRA-130 B-4 (was: the sync refused page_identity_changed / rename_identity_conflict): the file alone is held and the page keeps
+ // its slug, id and body; the rest of the source syncs.
+ const held = await s.sync();
+ expect(held.held?.map(hold => [hold.path, hold.code, hold.reason])).toEqual([['notes/foo-bar.md', 'page_identity_changed', 'identity_differs']]);
+ expect(await pageRow(s.id, 'notes/unrelated-6729')).toMatchObject({ deleted_at: null });
+ expect((await engine.executeRaw<{ id: string }>("SELECT frontmatter->>'id' AS id FROM pages WHERE source_id=$1 AND slug=$2", [s.id, 'notes/foo-bar']))[0]?.id).toBe('doc-one-6729');
+ expect((await engine.executeRaw<{ compiled_truth: string }>("SELECT compiled_truth FROM pages WHERE source_id=$1 AND slug=$2", [s.id, 'notes/foo-bar']))[0]?.compiled_truth).not.toContain('A different document');
+ expect(await pageRow(s.id, 'notes/foo-bar')).toMatchObject({ id: one.id, deleted_at: null });
+ expect((await s.sync()).held?.map(hold => [hold.path, hold.reason])).toEqual([['notes/foo-bar.md', 'identity_differs']]);
+ expect(await pageRow(s.id, 'notes/foo-bar')).toMatchObject({ id: one.id, deleted_at: null });
expect((await pageRow(s.id, 'notes/foo-bar'))).toMatchObject({ id: one.id, deleted_at: null });
}), 180_000);
});
diff --git a/test/sync-page-identity-hold-gbra130.test.ts b/test/sync-page-identity-hold-gbra130.test.ts
new file mode 100644
index 0000000000..fbd9c123c8
--- /dev/null
+++ b/test/sync-page-identity-hold-gbra130.test.ts
@@ -0,0 +1,102 @@
+/**
+ * GBRA-130 A-17/B-3/B-4 (#6712 PR 4b): a managed sync pass that could not decide which page one file is stopped the whole
+ * source. Several tombstones recording the file's origin (#6517, A-17), two spellings another platform folds into one
+ * file (B-3), or a file whose frontmatter id differs from the page holding its slug (#6729, B-4) each threw
+ * page_identity_changed out of the pass, so every other file in the source waited behind it on every later sync.
+ *
+ * Protects (red before: the sync rejects page_identity_changed and notes/other.md never imports): the file alone is held
+ * page_identity_changed with meta.reason several_tombstones / spelling / identity_differs, needs a person
+ * (sync status page_identity_decision), nothing is imported, revived or deleted at its slug, the unrelated file imports,
+ * and a later sync holds it again without stopping. A dry run still refuses the source, as discovery does. Runs on PGLite
+ * and, with DATABASE_URL, on Postgres.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readGitHold } from '../src/core/persistence/sync-holds.ts';
+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const note = (title: string, front = '') => `---\ntype: concept\ntitle: ${title}\n${front}---\n\nThe body of ${title}.\n`;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes/seed.md'), note('notes/seed'));
+ writeFileSync(join(root, 'notes/Kept Doc.md'), note('Kept doc', 'id: kept-one\n'));
+ commit(root, 'seed');
+};
+const rows = (engine: BrainEngine, slug: string) => engine.executeRaw<{ id: number; deleted_at: string | null; compiled_truth: string; source_path: string | null }>(
+ "SELECT id, deleted_at, compiled_truth, source_path FROM pages WHERE source_id='default' AND slug=$1 ORDER BY id", [slug]);
+const requests = async (engine: BrainEngine) => (await engine.executeRaw<{ path: string }>(
+ "SELECT intent->>'path' AS path FROM persistence_requests WHERE source_id='default' AND intent->>'path' IS NOT NULL ORDER BY sequence")).map(row => row.path);
+const incarnation = async (engine: BrainEngine) => (await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'"))[0]!.incarnation;
+
+for (const backend of testBackends()) describe(`[${backend}] GBRA-130 A-17/B-3/B-4: one file whose page identity is undecidable`, () => {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ async function heldAlone(engine: BrainEngine, root: string, paths: string[], reason: string) {
+ const before = await requests(engine);
+ // A dry run keeps discovery's refusal (it reads the source as a company plan does), and writes nothing.
+ await expect(performManagedSync(engine, { ...OPTS, dryRun: true })).rejects.toMatchObject({ code: 'page_identity_changed' });
+ expect(await requests(engine)).toEqual(before);
+ const first = await performManagedSync(engine, OPTS);
+ expect(first.status).toBe('synced');
+ expect(first.held?.map(hold => [hold.path, hold.code, hold.reason]).sort()).toEqual(paths.map(path => [path, 'page_identity_changed', reason]).sort());
+ expect((await requests(engine)).filter(path => !before.includes(path))).toEqual(['notes/other.md']);
+ expect(await rows(engine, 'notes/other')).toMatchObject([{ deleted_at: null }]);
+ for (const path of paths) expect(await readGitHold(engine, 'default', await incarnation(engine), path)).toMatchObject({ code: 'page_identity_changed', meta: { reason } });
+ const status = await readSyncStatus(engine, 'default', { detail: false });
+ for (const path of paths) expect(status.holds.find(hold => hold.path === path)).toMatchObject({ code: 'page_identity_changed', needs_human: true, safe_actions: ['none'] });
+ expect(status.needs_human).toBe(true);
+ // A later sync re-screens the held paths (holdRescreenDue) and holds them again, and is not stopped by them.
+ writeFileSync(join(root, 'notes/later.md'), note('notes/later'));
+ commit(root, 'later');
+ const again = await performManagedSync(engine, OPTS);
+ expect(again).toMatchObject({ status: 'synced', holds_outstanding: paths.length });
+ for (const path of paths) expect(await readGitHold(engine, 'default', await incarnation(engine), path)).toMatchObject({ code: 'page_identity_changed', meta: { reason } });
+ expect(await rows(engine, 'notes/later')).toMatchObject([{ deleted_at: null }]);
+ }
+
+ test('several_tombstones: a file two deleted pages record is held, neither is revived, the rest imports', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ for (const slug of ['archive/twin-one', 'archive/twin-two']) await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {
+ await tx.putPage(slug, { type: 'note', title: slug, compiled_truth: `Deleted ${slug}.`, timeline: '', frontmatter: {}, content_hash: `h-${slug}` }, { sourceId: 'default' });
+ await tx.executeRaw("UPDATE pages SET source_path='notes/twin.md', deleted_at=now() WHERE source_id='default' AND slug=$1", [slug]);
+ }, TEST_WRITE_ATTRIBUTION));
+ writeFileSync(join(root, 'notes/twin.md'), note('notes/twin'));
+ writeFileSync(join(root, 'notes/other.md'), note('notes/other'));
+ commit(root, 'twin and other');
+ await heldAlone(engine, root, ['notes/twin.md'], 'several_tombstones');
+ expect(await rows(engine, 'notes/twin')).toEqual([]);
+ for (const slug of ['archive/twin-one', 'archive/twin-two']) expect((await rows(engine, slug))[0]?.deleted_at).not.toBeNull();
+ }, { databaseUrl, setup }), 240_000);
+
+ test('spelling: two files differing only by case are both held, nothing is imported at their slug, the rest imports', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/Case.md'), note('Upper'));
+ writeFileSync(join(root, 'notes/case.md'), note('Lower'));
+ writeFileSync(join(root, 'notes/other.md'), note('notes/other'));
+ commit(root, 'two spellings and other');
+ await heldAlone(engine, root, ['notes/Case.md', 'notes/case.md'], 'spelling');
+ expect(await rows(engine, 'notes/case')).toEqual([]);
+ }, { databaseUrl, setup }), 240_000);
+
+ test('identity_differs: a file whose id differs from the page at its slug is held, the page keeps its id and body, the rest imports', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ const [kept] = await rows(engine, 'notes/kept-doc');
+ expect(kept).toMatchObject({ source_path: 'notes/Kept Doc.md', deleted_at: null });
+ git(root, 'rm', '-q', 'notes/Kept Doc.md');
+ writeFileSync(join(root, 'notes/kept-doc.md'), note('Another document', 'id: kept-two\n'));
+ writeFileSync(join(root, 'notes/other.md'), note('notes/other'));
+ commit(root, 'replace kept with another document');
+ await heldAlone(engine, root, ['notes/kept-doc.md'], 'identity_differs');
+ expect(await rows(engine, 'notes/kept-doc')).toEqual([kept]);
+ }, { databaseUrl, setup }), 240_000);
+});