Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/sync-stops-holding-pages
garrytand98cfe54d71d
diff --cc docs/architecture/key-files/canonical-reconciliation-continued.mdindex 62d45a4f24,0bef6982e6..95f4bc7b82--- a/docs/architecture/key-files/canonical-reconciliation-continued.md+++ b/docs/architecture/key-files/canonical-reconciliation-continued.md@@@ -7,4 -7,4 +7,5 @@@ Current behavior and load-bearing invar- `src/commands/doctor/checks/rows-behind.ts` — doctor `sync_rows_behind_checkpoint` (BRAIN, after `sync_overwritten_db_edits`): per source counts and first slugs from `scanRowsBehind`; `warn` on `behind` rows with the read-only `gbrain repair rows-behind --source <id> --json` preview as the fix; `unknown` (info) when the `GBRAIN_DOCTOR_ROWS_BEHIND_TIMEOUT_MS` budget (default 10 s) stopped a scan or a checkout is unreadable; not applicable (ok) off the owner host and on repo-less brains.- `src/core/repair/rows-behind.ts` — `gbrain repair rows-behind --source <id>`: explicit-only, preview-bound (`--apply --expect <hash>`, `--include-ambiguous` adds rows with no import record). `reimport` submits the committed bytes through `submitManagedFileRepair`; `hold:<code>` writes the hold sync would have written (`writeGitHold`). Refused off the owner host (`not_owner_host`). Never runs on upgrade. Tests: `test/rows-behind-checkpoint-8071.test.ts` (PGLite and Postgres via `test/e2e/rows-behind-checkpoint-8071-postgres.test.ts`).- GST-2201, a file that comes back after sync deleted its page: `readShadowLevel` (`sync-pass.ts`) reads whether a tombstone is sync-made (`syncDeleteOrigin`, `sync-delete-tombstones.ts`) into `page.syncDeleted`, and `sync-classify.ts` classifies such a path `import` ahead of `deleted_same` / `deleted_edited` (uncommitted bytes take `dirty`; an old hold on it re-runs). The selection fingerprint carries `sync_deleted_restore`, so the first pass after the upgrade reads the whole level once. `originCommitted` (`sync-markers.ts`) says whether a page's file is in the tree at the source's `last_commit` or at HEAD (false off a managed checkout or for a company-brain source; an unreadable checkout counts as committed). A retention purge (`page-prepare.ts`) of a tombstone whose file is committed defers a sync-made tombstone (`revision_conflict`) and purges any other database-only (`databaseOnlyReason: committed_file`), so the file stays. Tests: `test/sync-restored-file-purge.test.ts` (PGLite and Postgres), `test/sync-classify-6712.test.ts`.+- `src/core/repair/file-drift-compare.ts` — GST-2568: `gbrain repair file-drift` with a selection and no `--prefer` (`compareSelection` in file-drift.ts) compares each page with its file through `comparePage` and writes nothing: `driftDifference` over the `reconcileCanonical` readings names what differs, `newerSide` compares the file's last commit at HEAD (`fileCommitEvidence`) with the page's `updated_at` (unknown with uncommitted bytes, a missing time or the same second), and the verdict is `release_hold`, `no_drift`, `prefer_file`, `needs_human` (a newer page, a page whose file is gone, a deleted page whose file differs) or `unknown`. A `--prefer file` preview reads `readDriftEvidence` first and lists a page newer than its file `kept_newer_page` (`newerPageParagraph`) unless `--slug` names it, which adds a warning instead. `linesNotCarried` counts the overwritten side's lines the result does not carry; `prepareDriftPage` renders both with `serializePageToMarkdown` and stores `lost_lines` on each page, which the listing, a total warning and `details.lost_lines_total` report. Test: `test/file-drift-normalisation-gst2568.test.ts`.+ - `src/core/persistence/unimported-file.ts` — GST-2579: `unimportedFile(engine, state)` reports a page file whose bytes are neither in sync's import record (`raw_sha256`/`disk_sha256`) nor a git effect gbrain wrote for a revision the page has held (live `knowledge_revision` or a `page_versions` row), with the last commit that touched it (`lastCommitOf` in `pending-import.ts`); no import record counts as newer. `discardedFilePaths` names the decided paths whose result drops the file's value. `repair/file-drift.ts` skips such pages in bulk (`kept_newer_file`; a recreate over another writer's delete is `kept_newer_delete`), names the commit for `--slug`, and `fileDriftConsentText` lists them in the consent the registry's `consent: 'destructive'` asks for. `reconcile.ts` refuses a preview, and an admitted apply (the `guard` on `admitReconcileArtifact`; keep_db passes none), whose result takes the database over such a file (`unimportedFileRefusal`, `source_changed` / `unimported_file_edit`). Test: `test/db-wins-unimported-gst2579.test.ts`.diff --cc docs/guides/write-refusals.mdindex 7da441e67d,59c5334843..174153c537--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@@ -276,7 -276,7 +276,7 @@@ with each file and fix the ones that ne| <a id="rename_identity_unreadable"></a>`rename_identity_unreadable` | Classic sync (GBRA-133 S-51): a file added in the same sync that removed or renamed another has a title or frontmatter `id` the database refused to compare (SQLSTATE 22021 or 22P05), so sync could not tell whether it is that page renamed. The new file is held and the old page keeps its id, links, facts and timeline; the rest of the source keeps syncing. A NUL byte or an unpaired surrogate in a title or id never reaches the database: sync treats such a value as absent and the pair takes the ordinary unconfirmed-rename path. | Remove the characters the database cannot store from the file title and `id`, commit, then `gbrain sync --source <source> --no-pull`. The pair is decided again when the file changes or on `gbrain sources retry-held <source>`. || <a id="rename_reconcile_failed"></a>`rename_reconcile_failed` | Classic sync (GBRA-133 S-67): a rename fell back to importing the new file, and removing the page of the old name then failed with an unexpected error (the hold records its class and code, never its message). The old page was kept and may duplicate the new one; the rest of the source keeps syncing. A transient database error and the reconcile's own "staleness unprovable" verdict still record the `<rename:…>` marker, which a later run converges. | Ask the user before `gbrain sync --source <source> --full --no-pull`: the full walk removes pages whose file is gone after checking each one (it re-reads the whole source). Or remove the old page with `gbrain delete --source <source> -- <slug>` (recoverable for 72 h). || <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. [Compare it first](repair.md#file-drift-compare) with `gbrain repair file-drift --source <source> --slug <slug>` (no `--prefer`: it names the newer side and writes nothing). 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. |-| <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); the preview names any file edit sync never imported that the database copy would overwrite. Decide with the user; the apply asks for their consent (exit 3) and takes `--yes` only after they agree ([newer file changes](repair.md#file-drift-newer)), 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. |++| <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. [Compare it first](repair.md#file-drift-compare) with `gbrain repair file-drift --source <source> --slug <slug>` (no `--prefer`: it names the newer side and writes nothing). Preview `gbrain repair file-drift --source <source> --slug <slug> --prefer database` (keep the database copy, rewrite the file) or `--prefer file` (import the file); the preview names any file edit sync never imported that the database copy would overwrite. Decide with the user; the apply asks for their consent (exit 3) and takes `--yes` only after they agree ([newer file changes](repair.md#file-drift-newer)), 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. || <a id="file_wins_rewrite"></a>`file_wins_rewrite` | `gbrain repair file-drift --prefer file` keeps the canonical file's bytes and adds only the protected parts reconcile keeps from the database: protected frontmatter keys the file lacks (inserted before the closing `---`) and database-only timeline rows (appended to the file's timeline, with a `<!-- timeline -->` line above a bare `## Timeline` heading so they stay in it). When the resolved page also differs in anything else (a value, a tag, the title, the body), keeping the file would mean re-rendering all of it, so the preview refuses the page and nothing is written. A database-only timeline row dated before the file's own rows sorts in among them rather than after them, so it refuses too. A file-wins apply accepted before this rule existed refuses the same way when it is prepared, and writes nothing. | Show the user the page's differences. Commit them into the file through the door (`gbrain git commit-push`) and preview again, or preview `--prefer database` if the database copy should win. || <a id="frontmatter_alias_limit"></a>`frontmatter_alias_limit` | A file whose exact bytes an older gbrain imported and validated nests YAML aliases in its frontmatter that expand past the size limit (#7018). This release refuses them on purpose, so only that file is held (its page keeps the last imported version) and the rest of the source syncs; it is never a parser regression. | Reduce the alias nesting in the frontmatter (or write the values out), or remove the file, then commit and `gbrain sync --source <source> --no-pull`. The hold re-screens when the file changes. Before 4b such a file stopped the source as `sync_parser_regression`; the workaround there was `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs. || <a id="visibility_noncanonical"></a>`visibility_noncanonical` | The file's frontmatter asks for `visibility: private` in a spelling page privacy does not read: another case (`Visibility: private`, `visibility: Private`), a block scalar, a list, a flow mapping or a merge key. Page privacy reads only the exact lowercase key and value, so importing it would store a world-readable page its author believes is private. Git sync (classic and managed) holds the file and the rest of the source syncs; `gbrain import` (with or without a Git checkout) refuses it and imports the rest. An existing page keeps its last imported version. Company-brain connects and syncs, and the GitHub and Google connectors on a database-only source, hold it the same way (#7880); `gbrain repair url-clone-fences` lists a clone file whose HEAD asks for it this way under this code; apply restores the file from HEAD with its fence rows kept database-only, so the clone can pull, but does not import HEAD and reports `held` (#7897). `put_page`, `edit_page`, `capture`, `ingest_capture`, `brainstorm --save` and `sources reconcile` refuse the same request as [`visibility_not_applied`](#visibility_not_applied). Doctor `git_held_files` counts the held files and the stored pages that ask for private this way (`details.visibility_noncanonical`). | Write `visibility: private` on its own frontmatter line (lowercase key and value), commit, and run `gbrain sync --source <source> --no-pull` (or import the file again). The hold re-screens when the file changes; no frontmatter repair rewrites a privacy request. For a stored page doctor names, rewrite its frontmatter the same way with `put_page` or by editing its file. |diff --cc src/core/repair/file-drift.tsindex f2838a21d7,f332164003..9bc874f985--- a/src/core/repair/file-drift.ts+++ b/src/core/repair/file-drift.ts@@@ -91,10 -91,9 +91,11 @@@ import { prepareReconcileResult } fromimport { canonicalOriginPage, originConflictMessage, originTwinsFix } from '../persistence/origin-guard.ts';import { assertReconcileOutputPath, assertReconcileSize } from '../persistence/reconcile-backup.ts';import { authorizeReconcile, runReconcileApply } from '../persistence/reconcile.ts';+ import { discardedFilePaths, unimportedFile, unimportedFileText, type UnimportedFile } from '../persistence/unimported-file.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { recordsNoFileOrigin } from '../persistence/unbound-pages.ts';+import { comparedListing, comparePage, linesNotCarried, newerPageParagraph, readDriftEvidence, type ComparedPage } from './file-drift-compare.ts';+import { serializePageToMarkdown } from '../markdown.ts';import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';export type DriftSide = 'file' | 'database';@@@ -108,8 -107,8 +109,10 @@@ export interface ArtifactPage { slug: sfile_gone?: true;/** GBRA-133: file wins appends protected keys or timeline rows to the canonical file (`fileWinsContent`). */file_appended?: true;+ /** How many lines of the side the repair overwrites the result does not carry (`linesNotCarried`, both sides rendered alike). */- lost_lines: number }++ lost_lines: number;+ /** GST-2579: database wins writes over a file edit gbrain never imported or wrote; only an exact --slug selection keeps such a page, and its apply needs consent. */+ discards?: UnimportedFile }/** #6712 wave: a page whose canonical file is gone from the last commit, resolved `--prefer file`: soft-delete exactly that page. */export interface SoftDeletePage { slug: string; prefer: 'file'; exceptions: DriftException[]; soft_delete: { ghost: GhostPage; owner: GhostOwner } }/**@@@ -542,10 -526,8 +546,10 @@@ export async function prepareDriftPage(if (error instanceof OperationError && !error.fix) error.fix = readFix(`gbrain wrote a reconcile preview of ${slug} that its own apply refuses, so nothing was approved or written; report it with the output of gbrain doctor --json (the command in fix).`, { argv: ['gbrain', 'doctor', '--json'] });throw error;}- return { slug, prefer, adopt_slug_path: adopt, exceptions: driftExceptions(prepared.result, prefer === 'file' ? file : database), result: prepared.result, preview,+ const rendered = (page: ParsedPage) => serializePageToMarkdown({ ...state.snapshot.page, ...page }, page.tags);+ const lost_lines = opts.fileGone ? 0 : linesNotCarried(rendered(prefer === 'database' ? file : database), rendered(prepared.result));+ return { slug, prefer, adopt_slug_path: adopt, exceptions: driftExceptions(prepared.result, prefer === 'file' ? file : database), result: prepared.result, preview, lost_lines,- ...(opts.fileGone ? { file_gone: true as const } : {}), ...(appends ? { file_appended: true as const } : {}) };+ ...(opts.fileGone ? { file_gone: true as const } : {}), ...(appends ? { file_appended: true as const } : {}), ...(discards ? { discards } : {}) };}/**@@@ -748,46 -737,31 +759,71 @@@ function item(page: ApprovedPage, indexreturn { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0, action: `prefer_${prefer}`, page, hash, last };}+/**+ * GST-2568: the selection compared with no winner named (file-drift-compare.ts): per page what differs, which side is newer+ * and what a repair would do. Reads only; it prints no apply command, and a held selection is windowed as a preview is.+ */+async function compareSelection(engine: BrainEngine, sourceId: string, opts: RepairPlanOptions): Promise<RepairPlan> {+ const held = opts.held ? await selectHeld(engine, sourceId, opts) : null;+ const selected = held ? null : await selectSlugs(engine, sourceId, opts);+ const targets: { slug: string | null; hold?: GitHoldRecord }[] = held ? [...held.legacy.map(hold => ({ slug: hold.slug, hold })), ...held.targets.slice(0, HELD_WINDOW_PAGES).map(target => ({ slug: target.hold.slug, hold: target.hold }))]+ : selected!.slugs.map(slug => ({ slug }));+ const residuals: Record<string, number> = { ...(held?.notSelected || selected?.notSelected ? { not_selected: held?.notSelected ?? selected!.notSelected } : {}), ...(held?.before ? { before_cursor: held.before } : {}) };+ const count = (key: string) => { residuals[key] = (residuals[key] ?? 0) + 1; };+ const listing: NonNullable<RepairPlan['listing']> = [];+ for (const row of selected?.unknown ?? []) { count(`unknown_${row.reason}`); listing.push({ item: `${sourceId}:${row.slug}`, class: 'unknown', detail: unknownDriftDetail(sourceId, row) }); }+ const assessmentAt = new Date().toISOString();+ const windowEnd = Math.min(Date.now() + HELD_WINDOW_BUDGET_MS, opts.deadline ?? Infinity);+ const pages: ComparedPage[] = [];+ let windowed = 0;+ opts.progress?.start('repair.file_drift.compare', targets.length);+ if (targets.length) await asLocalCli(engine, async () => {+ for (const target of targets) {+ if (held && pages.length && Date.now() >= windowEnd) break;+ opts.progress?.tick(1, target.slug ?? target.hold?.path);+ if (target.hold && fileDriftSide(target.hold.meta)) windowed++;+ pages.push(await comparePage(engine, sourceId, target, assessmentAt));+ }+ });+ opts.progress?.finish();+ for (const page of pages) { count(page.would); listing.push(comparedListing(page)); }+ const remaining = held ? held.targets.length - windowed : 0;+ const nextCursor = remaining > 0 && windowed > 0 ? heldCursor(held!.targets[windowed - 1]!.hold.path) : undefined;+ if (remaining > 0) residuals.after_window = remaining;+ const filesNewer = pages.filter(page => page.would === 'prefer_file').length;+ const next = [...(filesNewer ? [`Preview the file side for the ${filesNewer} page(s) whose file is newer: ${previewCommand(sourceId, { ...opts, prefer: 'file' })} (pages newer than their file are left held, kept_newer_page)`] : []),+ ...(nextCursor ? [`Compare the next window: ${shellQuote(compareArgv(sourceId, { ...opts, cursor: nextCursor }).slice(0, -1))}`] : [])];+ return { items: [], residuals, listing, details: { compare: true, writes: 'none',+ pages: pages.map(({ item: _item, ...page }) => page), ...(next.length ? { next_actions: next } : {}),+ ...(held ? { window: { previewed: windowed, remaining, complete: remaining === 0, ...(nextCursor ? { next_cursor: nextCursor } : {}) } } : {}),+ evidence: 'newer compares the file\'s last commit time at HEAD with the page\'s updated_at; unknown when the file has uncommitted bytes or either time is missing.' } };+}++ /**+ * GST-2579: the consent wording of a file-drift apply, naming every file edit sync never imported that the previewed+ * database-wins resolutions overwrite (the artifact's `discards`).+ */+ export function fileDriftConsentText(hash: string, sourceId: string | undefined): { what: string; why: string; risk: string; user_message: string } {+ let discards: UnimportedFile[] = [];+ let removals: string[] = [];+ try {+ const pages = [...readArtifact(hash, `gbrain repair file-drift --source ${sourceId ?? '<source>'}`).values()];+ discards = pages.flatMap(page => 'discards' in page && page.discards ? [page.discards] : []);+ removals = pages.flatMap(page => 'remove_file' in page ? [page.remove_file.path] : []);+ } catch { /* the apply itself refuses a missing or changed artifact */ }+ const list = (items: string[]) => items.slice(0, 10).join('; ') + (items.length > 10 ? `; and ${items.length - 10} more (listed in the preview)` : '');+ const named = list(discards.map(unimportedFileText));+ const removing = removals.length ? ` It also removes ${removals.length} file(s) that changed after their page was deleted, and the page does not hold what they say: ${list(removals)}.` : '';+ return {+ what: 'Apply the previewed file-drift resolutions: each listed page takes the preferred side, so either the canonical file is rewritten from the database copy or the page is replaced from the file.',+ why: `The preview ${hash} listed each page and the side that wins it${discards.length ? `, and the file edits sync never imported that the database copy overwrites (${discards.length})` : ''}${removals.length ? `, and the files it removes (${removals.length})` : ''}.`,+ risk: 'The losing side is replaced: a file rewrite is a new commit (git revert brings the edit back) and reconcile keeps a private backup of the replaced copy; a removed file comes back with git revert only when it was committed; a page that changed since the preview is skipped.',+ user_message: (discards.length+ ? `Apply the previewed file-drift repair? It overwrites file edits sync never imported with the database copy: ${named}.`+ : 'Apply the previewed file-drift repair? Each listed page takes the side the preview showed, and the other copy is replaced.') + removing,+ };+ }+export const fileDriftRepair: RepairHandler = {kind: 'file-drift',outcomeItemsLimit: 1000,@@@ -903,21 -874,18 +939,28 @@@listing.push({ item: `${sourceId}:${slug}`, class: live.still_present === false ? 'no_drift' : 'unknown', detail: live.reason });continue;}+ // GST-2568: Git stays the parent, but a page edited after its file's last commit is never dropped file-wins in bulk;+ // an explicit --slug still resolves it, with the warning naming the edit it drops.+ if (opts.prefer === 'file') {+ const evidence = await readDriftEvidence(engine, sourceId, slug, assessmentAt);+ if (evidence.newer === 'database' && evidence.differs !== 'none') {+ if (!opts.slugs?.length) { count('kept_newer_page'); listing.push({ item: `${sourceId}:${slug}`, class: 'kept_newer_page', detail: newerPageParagraph(sourceId, slug, evidence) }); continue; }+ newerPages.push(`${slug}: ${newerPageParagraph(sourceId, slug, evidence).replace('it stays held for a person', '--prefer file named for it drops that edit')}`);+ }+ }const page = await prepareDriftPage(engine, sourceId, slug, opts.prefer, assessmentAt);if (classes.has(slug)) page.class = classes.get(slug);+ // GST-2579: in bulk a newer file is kept (its hold stays); only an exact --slug selection may discard it, named here and in the consent.+ if (page.discards && !opts.slugs?.length) {+ count('kept_newer_file');+ listing.push({ item: `${sourceId}:${slug}`, class: 'kept_newer_file', detail: `kept the file, nothing is written for it: it holds ${unimportedFileText(page.discards)}. `+ + `Import it with --prefer file, or, if the user decides to discard that edit, preview the page alone: gbrain repair file-drift --source ${sourceId} --slug ${slug} --prefer database` });+ continue;+ }pages.push(page);listing.push({ item: `${sourceId}:${slug}`, class: `prefer_${opts.prefer}`,- detail: `${page.exceptions.length ? `kept: ${[...new Set(page.exceptions.map(e => e.reason))].join(', ')}` : 'exactly the preferred side'}${page.adopt_slug_path ? '; adopts the file at its slug path' : ''}`- detail: `${page.discards ? `discards ${unimportedFileText(page.discards)}; ` : ''}${page.exceptions.length ? `kept: ${[...new Set(page.exceptions.map(e => e.reason))].join(', ')}` : 'exactly the preferred side'}${page.adopt_slug_path ? '; adopts the file at its slug path' : ''}` });++ detail: `${page.discards ? `discards ${unimportedFileText(page.discards)}; ` : ''}${page.exceptions.length ? `kept: ${[...new Set(page.exceptions.map(e => e.reason))].join(', ')}` : 'exactly the preferred side'}${page.adopt_slug_path ? '; adopts the file at its slug path' : ''}`+ + (page.lost_lines ? `; drops ${page.lost_lines} line(s) the ${opts.prefer === 'database' ? 'file' : 'page'} holds` : '') });} catch (error) {if (!(error instanceof OperationError) || ['owner_unavailable', 'writer_registration_required'].includes(error.code)) throw error;count(`refused_${error.code}`);@@@ -942,12 -910,13 +985,17 @@@const appended = pages.flatMap(page => 'preview' in page && page.file_appended ? [page.preview.preconditions.relative_path] : []);// #6712 PR 4b: a removed file is gone only once its deletion is committed; without Git durability the next sync finds the committed file held again.const removed = pages.flatMap(page => 'remove_file' in page ? [page.remove_file.path] : []);+ const removalWarning = removed.length ? [`The apply removes ${removed.length} file(s) that changed after their page was deleted; the deleted page does not hold what they say: ${removed.slice(0, 10).join(' ')}${removed.length > 10 ? ` and ${removed.length - 10} more` : ''}`] : [];let warnings: string[] = nextCommand ? [`This preview covered ${previewed} of the ${held!.targets.length} selected held pages${opts.cursor ? ' after its cursor' : ''} (one window stops at ${HELD_WINDOW_PAGES} pages or ${HELD_WINDOW_BUDGET_MS / 1000} s); its hash and apply command cover only these. `+ `After applying this window (or deciding not to), preview the next one: ${nextCommand}`] : [];+ const discarded = pages.flatMap(page => 'preview' in page && page.discards ? [page.discards] : []);+ if (discarded.length) warnings.unshift(`This apply writes the database copy over ${discarded.length} file change(s) sync never imported, and needs the user's consent: ${discarded.map(unimportedFileText).join('; ')}. `+ + 'Each write is a new commit, so git revert brings the change back; reconcile also keeps the replaced bytes in its private backup.');+ warnings.push(...removalWarning);+ if (newerPages.length) warnings.unshift(`The apply drops a database edit newer than its file for ${newerPages.length} page(s): ${newerPages.join(' ')}`);+ const losing = pages.flatMap(page => 'preview' in page && page.lost_lines ? [page] : []);+ const lostLines = losing.reduce((sum, page) => sum + page.lost_lines, 0);+ if (lostLines) warnings.push(`The apply drops ${lostLines} line(s) the ${opts.prefer === 'database' ? 'files' : 'pages'} it overwrites hold and the result does not carry, across ${losing.length} page(s); details.pages[].lost_lines counts each. Read them before agreeing.`);const releases = pages.filter(page => 'release_hold' in page).length;if (releases) warnings.push(`The apply only schedules a re-screen of ${releases} held file(s) whose page and file agree; the next sync (gbrain sync --source ${sourceId}) releases each that still agrees.`);let undoneBySync: { recreated: number; removed: number } | null = null;@@@ -987,7 -955,7 +1035,7 @@@: 'import_file' in page ? { slug: page.slug, action: 'import_file', state: page.import_file.state, path: page.import_file.path, verb: fileDriftActionVerb('deleted', page.import_file.state, 'file'), exceptions: page.exceptions, result_digest: page.import_file.result_digest }: { slug: page.slug, ...(page.file_gone ? { action: 'recreate_file' } : {}), ...(page.class ? { class: page.class } : {}),verb: page.file_gone ? fileDriftActionVerb('deleted', 'file_gone', 'database') : fileDriftActionVerb('both', undefined, page.prefer),- adopt_slug_path: page.adopt_slug_path, exceptions: page.exceptions, result_digest: page.preview.result_digest, lost_lines: page.lost_lines }),- adopt_slug_path: page.adopt_slug_path, exceptions: page.exceptions, result_digest: page.preview.result_digest, ...(page.discards ? { discards: page.discards } : {}) }),++ adopt_slug_path: page.adopt_slug_path, exceptions: page.exceptions, result_digest: page.preview.result_digest, lost_lines: page.lost_lines, ...(page.discards ? { discards: page.discards } : {}) }),...(provenanceOf.get(page.slug) ? { provenance: provenanceOf.get(page.slug) } : {}) })),protections: 'Protected metadata stays as the database holds it, tags are the union of both sides, and protected takes and private fact rows are kept; exceptions lists each page\'s.' } };},diff --cc test/repair-file-drift-origin-twin-gbra108.test.tsindex eeb84093e5,da8d9e47a9..4c63cca806--- a/test/repair-file-drift-origin-twin-gbra108.test.ts+++ b/test/repair-file-drift-origin-twin-gbra108.test.ts@@@ -77,7 -77,9 +77,9 @@@ test('a held origin twin is listed by tconst planned = await preview(engine, 'database');expect(planned.residuals).toEqual({});expect(planned.affected).toBe(1);- expect(planned.listing).toEqual([{ item: `default:${SLUG}`, class: 'prefer_database', detail: 'exactly the preferred side; adopts the file at its slug path; drops 1 line(s) the file holds' }]);+ // GST-2579: the external commit was never imported, so the listing names the commit the repair discards.+ expect(planned.listing).toEqual([{ item: `default:${SLUG}`, class: 'prefer_database',- detail: expect.stringMatching(new RegExp(`^discards commit ${git(root, 'rev-parse', 'HEAD').slice(0, 12)} by Example on \\S+ to ${PATH}, which sync never recorded importing; exactly the preferred side; adopts the file at its slug path$`)) }]);++ detail: expect.stringMatching(new RegExp(`^discards commit ${git(root, 'rev-parse', 'HEAD').slice(0, 12)} by Example on \\S+ to ${PATH}, which sync never recorded importing; exactly the preferred side; adopts the file at its slug path; drops 1 line\\(s\\) the file holds$`)) }]);expect((await preview(engine, 'database', planned.preview_hash!)).outcomes).toEqual({ repaired: 1 });await settleManagedGitEffects(engine);git(root, 'commit', '-qam', 'commit the repaired file');