Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
G8a: unknown-side drift with a differing row is a discard; reclassify is one transaction
garrytan3154a38355c5
diff --git a/docs/designs/GIT_CANONICAL_MEMORY.md b/docs/designs/GIT_CANONICAL_MEMORY.mdindex 7a44c25b23..3eb54c2cab 100644--- a/docs/designs/GIT_CANONICAL_MEMORY.md+++ b/docs/designs/GIT_CANONICAL_MEMORY.md@@ -78,12 +78,12 @@ G8a ships it as `gbrain sources canonical <source-id> --to git|mixed [--dry-run| Category | What the apply does ||---|---|-| adopt (`database_ahead`, `undeclared_database_only`, `worktree_only`) | Writes the page's export view to its file and commits it through the door, up to 200 pages per commit. The worktree writer lock is taken per group and dropped between groups. No row changes: the bytes read back `equal`, and the strict pass after them rewrites none of those rows. |+| adopt (`database_ahead`, `undeclared_database_only`, `worktree_only`) | Writes the page's export view to its file and commits it through the door, up to 200 pages per commit. The worktree writer lock is taken per group and dropped between groups. No row changes: the bytes read back `equal`, and the strict pass after them rewrites none of those rows. A page with no import record whose row differs from HEAD counts as `database_ahead`, so it is adopted before the strict import could overwrite it. || declared | Nothing. A page under an ignored path is `git_ignored` and never gets a file or a Git effect. |-| git wins | The strict pass indexes the committed blob: Git moved and the database did not, Git deleted a page the database had not edited, a held deletion, or a held `file_drift` whose side is unknown. |+| git wins | The strict pass indexes the committed blob: Git moved and the database did not, Git deleted a page the database had not edited, a held deletion, or a held `file_drift` whose side is unknown and whose row already equals the committed file. || holds | Cleared, so Git's verdict runs over them. |-| parked effects | Retried once, or, for targets Git ignores, the page is stamped `git_ignored` (declared) and the target stays parked as a record. |-| discard | Refused: `git_conversion_blocked` names each category (both sides moved, a both-sides drift hold, a database edit Git deleted, an uncommitted working-tree edit that differs from HEAD and the export, an ignored target, unparseable, unsafe path, segmented page, export mismatch, or a row a strict pass would overwrite unplanned). There is no override. |+| parked effects | Retried once, or, for targets Git ignores, the page is stamped `git_ignored` (declared) in the same transaction that marks each parked target `declared: git_ignored`; the target stays as a record and the next preview no longer lists it. |+| discard | Refused: `git_conversion_blocked` names each category (both sides moved, a both-sides drift hold, an unknown-side drift hold whose row differs from the committed file, a database edit Git deleted, an uncommitted working-tree edit that differs from HEAD and the export, an ignored target (a fail-closed fallback when the ignore rules cannot be read), unparseable, unsafe path, segmented page, export mismatch, or a row a strict pass would overwrite unplanned). There is no override. |`--apply --expect <hash>` re-plans and refuses `preview_changed` on any difference, adopts group by group (a crash leaves the source mixed and the rerun preview lists only what is left), clears the holds, settles the parked effects, runs the full strict-equivalent pass, then sets `canonical: git` in the transaction that records the conversion. Writes can land between that pass and the flag, so it runs one genuine strict pass and previews again: the conversion is complete only when nothing is left; otherwise it reports `git_conversion_incomplete` with what remains and the source stays strict, because Git wins. `--to mixed` removes the flag and changes nothing else; Git keeps every door commit.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex b87e94f2c7..193d112eb3 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1677,7 +1677,7 @@ More: [docs/guides/repair.md#ghost-pages](../../docs/guides/repair.md#ghost-page|---|---|---|---|---|---|---|| Converting a source to git-canonical would discard database content or cannot place it, so the apply wrote nothing. | gbrain sources canonical --to git applies only when every database row will be in Git or in a declared database-only class afterwards. The preview counts what would be lost or cannot be placed by category (detail lists them): both_moved and held_drift_both, a page Git and the database both changed; deleted_in_git, a page Git deleted that the database edited since; uncommitted_edit, a working-tree edit the adoption would overwrite; ignored_target, a page whose file Git ignores without a declared class; unparseable and unsafe_path, a committed file or path sync cannot read; segmented_page, a segmented page conversion does not adopt yet; export_mismatch, a page whose export does not read back equal; git_overwrites_database, a page version a strict pass would replace that nothing accepted. There is no override. | Relay the categories and their paths (the --dry-run preview lists them) and ask the user how each should be resolved; preview again afterwards. | user | `repeat the read that failed` | 1 | no |-Reasons: `both_moved`, `held_drift_both`, `deleted_in_git`, `uncommitted_edit`, `ignored_target`, `unparseable`, `unsafe_path`, `segmented_page`, `export_mismatch`, `git_overwrites_database`.+Reasons: `both_moved`, `held_drift_both`, `held_drift_unknown_differs`, `deleted_in_git`, `uncommitted_edit`, `ignored_target`, `unparseable`, `unsafe_path`, `segmented_page`, `export_mismatch`, `git_overwrites_database`.More: [docs/designs/GIT_CANONICAL_MEMORY.md#conversion](../../docs/designs/GIT_CANONICAL_MEMORY.md#conversion)diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 9ec1d6fa80..52b181d924 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -329,7 +329,7 @@ export const CODES = {git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },git_unavailable: { class: 'retryable', summary: "A git command did not complete." },git_object_missing: { class: 'caller', summary: "A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone.", why: "An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#git_object_missing', suggestion: 'Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then sync again; every sync re-tests the hold.' },- git_conversion_blocked: { class: 'consent', actor: 'user', summary: "Converting a source to git-canonical would discard database content or cannot place it, so the apply wrote nothing.", reasons: ['both_moved', 'held_drift_both', 'deleted_in_git', 'uncommitted_edit', 'ignored_target', 'unparseable', 'unsafe_path', 'segmented_page', 'export_mismatch', 'git_overwrites_database'], why: "gbrain sources canonical --to git applies only when every database row will be in Git or in a declared database-only class afterwards. The preview counts what would be lost or cannot be placed by category (detail lists them): both_moved and held_drift_both, a page Git and the database both changed; deleted_in_git, a page Git deleted that the database edited since; uncommitted_edit, a working-tree edit the adoption would overwrite; ignored_target, a page whose file Git ignores without a declared class; unparseable and unsafe_path, a committed file or path sync cannot read; segmented_page, a segmented page conversion does not adopt yet; export_mismatch, a page whose export does not read back equal; git_overwrites_database, a page version a strict pass would replace that nothing accepted. There is no override.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Relay the categories and their paths (the --dry-run preview lists them) and ask the user how each should be resolved; preview again afterwards.' },+ git_conversion_blocked: { class: 'consent', actor: 'user', summary: "Converting a source to git-canonical would discard database content or cannot place it, so the apply wrote nothing.", reasons: ['both_moved', 'held_drift_both', 'held_drift_unknown_differs', 'deleted_in_git', 'uncommitted_edit', 'ignored_target', 'unparseable', 'unsafe_path', 'segmented_page', 'export_mismatch', 'git_overwrites_database'], why: "gbrain sources canonical --to git applies only when every database row will be in Git or in a declared database-only class afterwards. The preview counts what would be lost or cannot be placed by category (detail lists them): both_moved and held_drift_both, a page Git and the database both changed; deleted_in_git, a page Git deleted that the database edited since; uncommitted_edit, a working-tree edit the adoption would overwrite; ignored_target, a page whose file Git ignores without a declared class; unparseable and unsafe_path, a committed file or path sync cannot read; segmented_page, a segmented page conversion does not adopt yet; export_mismatch, a page whose export does not read back equal; git_overwrites_database, a page version a strict pass would replace that nothing accepted. There is no override.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Relay the categories and their paths (the --dry-run preview lists them) and ask the user how each should be resolved; preview again afterwards.' },git_conversion_incomplete: { class: 'retryable', summary: "A git-canonical conversion stopped because its strict pass did not finish, or finished with work left after the flag was set.", why: "The conversion runs a full strict-equivalent pass before it sets canonical: git, and one genuine strict pass after. A pass that ends partial, blocked or deferred stops the conversion where it is: before the flag the source stays as it was, after it the source stays strict (Git wins) and the plan lists what is left.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Wait until gbrain sync status --source <id> --json shows the source idle, then preview again with gbrain sources canonical <id> --to git --dry-run and apply the new hash.' },git_home_required: { class: 'caller', summary: "A git-canonical source would store content in the database without a file in Git; nothing was written.", reasons: ['no_file_form', 'declared_target', 'facts_lane'], why: "On a source with canonical: git, page content reaches the database only after Git commits its file. The declared database-only classes (private, alias-private and lineage-private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores, detached pages and origin twins) are the only exceptions. no_file_form: the write has no file and is in no declared class; declared_target: a publication would commit a file for a declared page; facts_lane: a writer with no file form yet.", docs: 'docs/guides/write-refusals.md#git_home_required', suggestion: 'Ask the user which git home to configure (a path Git tracks, or a storage.db_only directory in gbrain.yml), then submit the write again with a new request_id.' },git_private_commit_refused: { class: 'caller', summary: "A git-canonical source refused to commit the file of a private, alias-private or lineage-private page; nothing was written and HEAD is unchanged.", reasons: ['private', 'alias_private', 'lineage_private'], why: "Private pages of a source with canonical: git are database-only: their bytes never enter Git history. A page turning private is published as the door commit that removes its file, never as a commit of its bytes.", docs: 'docs/guides/write-refusals.md#git_private_commit_refused', suggestion: 'The page stays database-only. Write it through put_page (which publishes a private page without a file), or remove visibility: private if it belongs in Git, then submit again with a new request_id.' },diff --git a/src/core/persistence/git-conversion.ts b/src/core/persistence/git-conversion.tsindex 5d283f32c3..aa0d5b12cf 100644--- a/src/core/persistence/git-conversion.ts+++ b/src/core/persistence/git-conversion.ts@@ -11,12 +11,14 @@* and commits it with commitThroughDoor, one commit per group of CONVERSION_GROUP_MAX pages, under the worktree writer* lock, which is dropped between groups. No row changes: the database already holds those bytes.* - declared: database-only on purpose; nothing is written and nothing deleted.- * - git_wins: Git's verdict replaces the row and loses nothing the operator has not accepted (Git moved and the- * database did not; Git deleted a page sync had not indexed yet; a held deletion; a held file_drift whose side is- * unknown). The strict-equivalent pass applies it.+ * - git_wins: Git's verdict replaces the row and loses nothing (Git moved and the database did not; Git deleted a page+ * the database had not edited; a held deletion; a held file_drift whose side is unknown and whose row already equals+ * the committed file). The strict-equivalent pass applies it. An unknown-side drift whose row differs from the file+ * would lose that edit, so it is a discard (held_drift_unknown_differs).* - holds: cleared, so that pass runs Git's verdict over them (a hold at its level would settle the path).* - parked Git effects: retried (retry-effects' one authorized attempt), or reclassified when Git ignores the target- * (the page is stamped git_ignored, G7a's declared class, and the target stays parked as a record).+ * (in one transaction the page is stamped git_ignored, G7a's declared class, and each target stays parked as a record+ * marked `declared: git_ignored`, so the next plan no longer lists it).* - discard: database content that would be neither in Git after the apply nor declared, by category. The apply* refuses (git_conversion_blocked, naming the categories) unless it is zero; there is no override.* The preview hash binds HEAD, the source incarnation and every planned item with its revision.@@ -51,6 +53,7 @@ import { readDeletionProvenance } from './sync-origin-evidence.ts';import { retryParkedEffects } from './effect-retry.ts';import { runPersistenceEffects } from './effects.ts';import { faultPoint } from './fault-points.ts';+import { declarePersistenceProtocol } from './protocol.ts';import { previewChangedError, previewHash } from './preview-approval.ts';import { sha256 } from './digest.ts';@@ -65,7 +68,7 @@ export type AdoptState = typeof ADOPT_STATES[number];export const GIT_WINS_REASONS = ['git_ahead', 'deleted_by_commit', 'held_deletion', 'held_drift_unknown'] as const;export type GitWinsReason = typeof GIT_WINS_REASONS[number];/** Database content the apply would discard or cannot place, by why: each must be zero before the apply runs. */-export const DISCARD_CATEGORIES = ['both_moved', 'held_drift_both', 'deleted_in_git', 'uncommitted_edit', 'ignored_target', 'unparseable', 'unsafe_path',+export const DISCARD_CATEGORIES = ['both_moved', 'held_drift_both', 'held_drift_unknown_differs', 'deleted_in_git', 'uncommitted_edit', 'ignored_target', 'unparseable', 'unsafe_path','segmented_page', 'export_mismatch', 'git_overwrites_database'] as const;export type DiscardCategory = typeof DISCARD_CATEGORIES[number];@@ -146,6 +149,7 @@ export async function planGitConversion(engine: BrainEngine, sourceId: string):for (const hold of holds) {tally(preview.holds, hold.side ? `${hold.code}:${hold.side}` : hold.code, hold.path);if (hold.action === 'blocked') discard('held_drift_both', hold.path);+ else if (hold.side === 'unknown' && equal.has(hold.path)) gitWins('held_drift_unknown', hold.path);}const noFile = pages.filter(page => page.state === 'undeclared_database_only' && page.path !== null);@@ -161,12 +165,12 @@ export async function planGitConversion(engine: BrainEngine, sourceId: string):case 'unparseable': discard('unparseable', path); continue;case 'unsafe_path': discard('unsafe_path', path); continue;case 'git_ahead':- if (side === 'unknown') gitWins('held_drift_unknown', path);+ if (side === 'unknown') discard('held_drift_unknown_differs', path);else if (page.databaseAlsoMoved && side !== 'both') discard('both_moved', path);else if (!page.databaseAlsoMoved) gitWins('git_ahead', path);continue;case 'database_ahead':- if (side === 'unknown') { gitWins('held_drift_unknown', path); continue; }+ if (side === 'unknown') { discard('held_drift_unknown_differs', path); continue; }if (side === 'both') continue;candidates.push({ page, state: 'database_ahead' });continue;@@ -206,7 +210,7 @@ function emptyPreview(sourceId: string, context: ManagedSyncContext, census: Gitparked_effects: { count: 0, retry: 0, reclassify: 0, by_code: {} }, index: { imports: 0, deletes: 0 }, discard: counted(DISCARD_CATEGORIES), remaining: 0, preview_hash: '', apply: [] };}-/** A hold's fate: a held deletion or an unknown-side drift goes to Git, a both-sides drift is database content Git would discard, the rest re-screen. */+/** A hold's fate: a held deletion or an unknown-side drift goes to Git (planGitConversion discards the drift when its row differs), a both-sides drift is database content Git would discard, the rest re-screen. */function holdItem(hold: GitHoldRecord): HoldItem {const side = hold.code === 'file_drift' ? fileDriftSide(hold.meta) ?? null : null;const action = side === 'both' ? 'blocked' : side === 'unknown' || side === 'deleted' ? 'git_wins' : 'rescreen';@@ -225,6 +229,8 @@ async function planAdoption(engine: BrainEngine, sourceId: string, root: string,const withdrawals = await readExportWithdrawals(engine, sourceId);for (const { page, state } of candidates) {const path = page.path!;+ // Fail-closed fallback: an ignored path with no file is already declared git_ignored by the census, and Git commits a+ // tracked file whatever its ignore rules say, so this fires only when reading the ignore rules fails (ignored is null).if (!ignored || ignored.has(path)) { discard('ignored_target', path); continue; }if (page.segmented) { discard('segmented_page', path); continue; }const snapshot = await readExportPage(engine, { ...page, source_id: sourceId }, withdrawals);@@ -248,7 +254,8 @@ function diskBytes(path: string): Buffer | null {async function readParked(engine: BrainEngine, sourceId: string): Promise<ParkedItem[]> {const rows = await engine.executeRaw<{ effect: string; request: string; kind: string; parked: Array<{ slug?: string; error_code: string }> }>(`SELECT e.id::text AS effect, r.request_id::text AS request, e.kind, e.data->'parked' AS parked FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id- WHERE e.source_id=$1 AND jsonb_typeof(e.data->'parked')='array' AND jsonb_array_length(e.data->'parked')>0 ORDER BY e.id`, [sourceId]);+ WHERE e.source_id=$1 AND jsonb_typeof(e.data->'parked')='array' AND EXISTS (SELECT 1 FROM jsonb_array_elements(e.data->'parked') p WHERE p->>'declared' IS NULL)+ ORDER BY e.id`, [sourceId]);return rows.map(row => {const parked = typeof row.parked === 'string' ? JSON.parse(row.parked) as typeof row.parked : row.parked;const codes = parked.map(target => target.error_code);@@ -377,7 +384,13 @@ async function settleParked(engine: BrainEngine, sourceId: string, parked: Parkelet retried = 0, reclassified = 0;for (const item of parked) {if (item.action === 'reclassify') {- await engine.executeRaw(`UPDATE pages SET database_only_reason='git_ignored' WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL AND database_only_reason IS NULL`, [sourceId, item.slugs]);+ // Metadata only (G7a has no standalone declare helper): the page's declared class and the parked record change together.+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw('SELECT id FROM persistence_effects WHERE id=$1 FOR UPDATE', [item.effect]);+ await tx.executeRaw(`UPDATE pages SET database_only_reason='git_ignored' WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL AND database_only_reason IS NULL`, [sourceId, item.slugs]);+ await tx.executeRaw(`UPDATE persistence_effects SET data=jsonb_set(data,'{parked}',(SELECT jsonb_agg(p||'{"declared":"git_ignored"}'::jsonb) FROM jsonb_array_elements(data->'parked') p)),updated_at=now() WHERE id=$1`, [item.effect]);+ });reclassified++;continue;}diff --git a/test/git-canonical-conversion-g8a.test.ts b/test/git-canonical-conversion-g8a.test.tsindex 902523ea27..8dba644763 100644--- a/test/git-canonical-conversion-g8a.test.ts+++ b/test/git-canonical-conversion-g8a.test.ts@@ -79,7 +79,7 @@ async function parkIgnoredEffect(engine: BrainEngine, slug: string, code = 'git_});}-const SLUGS = ['notes/same', 'notes/ahead', 'notes/gitmoved', 'notes/drift', 'notes/removed'];+const SLUGS = ['notes/same', 'notes/ahead', 'notes/gitmoved', 'notes/drift', 'notes/removed', 'notes/legacy'];const setup = ({ root }: { root: string }) => {mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');// The door commits with the repository's own identity: CI runners have no global one.@@ -97,26 +97,36 @@ const bulkSetup = ({ root }: { root: string }) => {git(root, 'add', '-A'); git(root, 'commit', '-qm', 'bulk');};+/** The page loses its sync import record, as a page imported before records were written has none. */+async function dropImportRecord(engine: BrainEngine, slug: string): Promise<void> {+ const [row] = await engine.executeRaw<{ id: string }>("SELECT id::text FROM pages WHERE source_id='default' AND slug=$1", [slug]);+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-import-provenance' AND fingerprint LIKE $1", [`default:%:${row!.id}`]);+}++const DRIFT_COMMITTED = 'The committed edit of notes/drift.';/**- * Every category on one non-strict source: notes/ahead and notes/dbonly hold content Git lacks (adopt); notes/secret is- * private and scratch/ignored is under an ignored path whose Git effect parked (declared, reclassified); notes/gitmoved got- * a commit sync has not read (git wins); notes/removed was deleted in Git after a database edit and notes/drift moved on- * both sides without an import record (held, Git wins).+ * Every category on one non-strict source: notes/ahead and notes/dbonly hold content Git lacks, and notes/legacy has no+ * import record and a database edit (adopt); notes/secret is private and scratch/ignored is under an ignored path whose+ * Git effect parked (declared, reclassified); notes/gitmoved got a commit sync has not read (git wins); notes/removed was+ * deleted in Git after a database edit (held deletion, Git wins); notes/drift moved on both sides without an import record+ * (held, side unknown); a later database write that matches the commit (`driftMatches`) leaves the hold with nothing to+ * lose, so Git wins; otherwise the database edit would be discarded.*/-async function mixedSource(brain: ManagedBrain): Promise<void> {+async function mixedSource(brain: ManagedBrain, driftMatches = true): Promise<void> {const { engine, root } = brain;expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');- for (const slug of ['notes/ahead', 'notes/drift', 'notes/removed']) await databaseOnlyEdit(engine, slug, `Written to the database alone: ${slug}.`);- writeFileSync(join(root, 'notes/drift.md'), note('notes/drift', 'The committed edit of notes/drift.'));+ for (const slug of ['notes/ahead', 'notes/drift', 'notes/removed', 'notes/legacy']) await databaseOnlyEdit(engine, slug, `Written to the database alone: ${slug}.`);+ writeFileSync(join(root, 'notes/drift.md'), note('notes/drift', DRIFT_COMMITTED));git(root, 'rm', '-q', 'notes/removed.md'); git(root, 'commit', '-qam', 'edit drift, remove removed');- const [drift] = await engine.executeRaw<{ id: string }>("SELECT id::text FROM pages WHERE slug='notes/drift'");- await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-import-provenance' AND fingerprint LIKE $1", [`default:%:${drift!.id}`]);+ await dropImportRecord(engine, 'notes/drift');+ await dropImportRecord(engine, 'notes/legacy');await databaseOnlyPage(brain, 'notes/dbonly', note('notes/dbonly', 'Only in the database.'));await databaseOnlyPage(brain, 'notes/secret', note('notes/secret', 'A private note.', 'visibility: private\n'));await putPage.handler(brain.ctx, { slug: 'scratch/ignored', content: note('scratch/ignored', 'Under an ignored path.'), wait_ms: 30_000 });await parkIgnoredEffect(engine, 'scratch/ignored');await performManagedSync(engine, OPTS);expect(await holds(engine)).toEqual(['notes/drift.md file_drift', 'notes/removed.md file_drift']);+ if (driftMatches) await databaseOnlyEdit(engine, 'notes/drift', DRIFT_COMMITTED);writeFileSync(join(root, 'notes/gitmoved.md'), note('notes/gitmoved', 'The committed edit of notes/gitmoved.'));git(root, 'commit', '-qam', 'edit gitmoved');}@@ -130,25 +140,31 @@ for (const backend of testBackends()) describe(`[${backend}] G8a: sources canoniconst base = git(root, 'rev-parse', 'HEAD');const before = await revisions(engine);const { preview } = await planGitConversion(engine, 'default');- expect(preview).toMatchObject({ strict: false, adopt: { count: 2, groups: 1, by: { database_ahead: 1, undeclared_database_only: 1, worktree_only: 0 } },+ expect(preview).toMatchObject({ strict: false, adopt: { count: 3, groups: 1, by: { database_ahead: 2, undeclared_database_only: 1, worktree_only: 0 } },declared: { count: 2, by: { private: 1, git_ignored: 1 } }, git_wins: { count: 3, by: { git_ahead: 1, held_deletion: 1, held_drift_unknown: 1, deleted_by_commit: 0 } },holds: { count: 2, by: { 'file_drift:unknown': 1, 'file_drift:deleted': 1 } }, parked_effects: { count: 1, retry: 0, reclassify: 1 }, discard: { count: 0 } });- expect(preview.adopt.sample.sort()).toEqual(['notes/ahead.md', 'notes/dbonly.md']);+ expect(preview.adopt.sample.sort()).toEqual(['notes/ahead.md', 'notes/dbonly.md', 'notes/legacy.md']);+ expect(preview.git_wins.sample.sort()).toEqual(['notes/drift.md', 'notes/gitmoved.md', 'notes/removed.md']);expect(await strict(engine)).toBe(false);expect(git(root, 'rev-parse', 'HEAD')).toBe(base);const result = await applyGitConversion(engine, 'default', preview.preview_hash, PROCESSING);- expect(result).toMatchObject({ status: 'converted', committed: { groups: 1, pages: 2 }, holds_cleared: 2, parked: { reclassified: 1 }, after: { remaining: 0, strict: true } });+ expect(result).toMatchObject({ status: 'converted', committed: { groups: 1, pages: 3 }, holds_cleared: 2, parked: { reclassified: 1 },+ after: { remaining: 0, strict: true, parked_effects: { count: 0 } } });expect(await strict(engine)).toBe(true);- expect(conversionCommits(root, base)).toEqual([{ subject: 'gbrain: persist 2 canonical memory updates', paths: ['notes/ahead.md', 'notes/dbonly.md'] }]);+ expect(conversionCommits(root, base)).toEqual([{ subject: 'gbrain: persist 3 canonical memory updates', paths: ['notes/ahead.md', 'notes/dbonly.md', 'notes/legacy.md'] }]);expect(git(root, 'status', '--porcelain')).toBe('');expect(readFileSync(join(root, 'notes/ahead.md'), 'utf8')).toContain('Written to the database alone: notes/ahead.');const after = await revisions(engine);expect(after['notes/ahead']).toBe(before['notes/ahead']);expect(after['notes/dbonly']).toBe(before['notes/dbonly']);+ // A page with no import record is adopted into Git before the strict import runs, so its database body is committed, never overwritten.+ expect(readFileSync(join(root, 'notes/legacy.md'), 'utf8')).toContain('Written to the database alone: notes/legacy.');+ expect(after['notes/legacy']).toBe(before['notes/legacy']);+ expect((await page(engine, 'notes/legacy'))!.body).toContain('Written to the database alone: notes/legacy.');expect(after['notes/same']).toBe(before['notes/same']);expect((await page(engine, 'notes/gitmoved'))!.body).toContain('The committed edit of notes/gitmoved.');- expect((await page(engine, 'notes/drift'))!.body).toContain('The committed edit of notes/drift.');+ expect((await page(engine, 'notes/drift'))!.body).toContain(DRIFT_COMMITTED);expect((await page(engine, 'notes/removed'))!.deleted).toBe(true);expect((await page(engine, 'notes/secret'))!.deleted).toBe(false);// The page under an ignored path stays database-only (declared git_ignored): no file is written, no git_target_ignored round trip.@@ -169,6 +185,19 @@ for (const backend of testBackends()) describe(`[${backend}] G8a: sources canoniexpect((await planGitConversion(engine, 'default')).preview).toMatchObject({ strict: true, remaining: 0 });}, { databaseUrl, setup }), 240_000);+ test('an unknown-side drift whose database body differs from the committed file is a discard, refused by path', () => managedBrain(async brain => {+ const { engine, root } = brain;+ await mixedSource(brain, false);+ const base = git(root, 'rev-parse', 'HEAD');+ const { preview } = await planGitConversion(engine, 'default');+ expect(preview).toMatchObject({ git_wins: { by: { held_drift_unknown: 0 } }, discard: { count: 1, by: { held_drift_unknown_differs: 1 }, sample: ['notes/drift.md'] } });+ await expect(applyGitConversion(engine, 'default', preview.preview_hash, PROCESSING)).rejects.toMatchObject({ code: 'git_conversion_blocked', detail: 'held_drift_unknown_differs' });+ expect(git(root, 'rev-parse', 'HEAD')).toBe(base);+ expect(await strict(engine)).toBe(false);+ expect(await holds(engine)).toEqual(['notes/drift.md file_drift', 'notes/removed.md file_drift']);+ expect((await page(engine, 'notes/drift'))!.body).toContain('Written to the database alone: notes/drift.');+ }, { databaseUrl, setup }), 240_000);+test('a stale hash refuses preview_changed and writes nothing', () => managedBrain(async brain => {const { engine, root } = brain;expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');