Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Fold a page whose file moved into the moved page instead of leaving it stale (GST-2584)
garrytan2b7763c5b38d
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex c8c394c722..25e6d0c8a3 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3174,6 +3174,16 @@ Reasons: `not_applied`, `still_behind`, `schema_unreadable`, `wedged`, `schema_b|---|---|---|---|---|---|---|| A configured model is not allowed under models strict mode. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### moved_pages_mass_fold_refused++<a id="moved_pages_mass_fold_refused"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain repair moved-pages refused to fold moved pages amounting to more than half of a source's file-backed pages; nothing was changed. | The sync mass-delete valve (#2828) applied to moved pages (GST-2584): that many moved pages at once almost always means a re-import under other paths or the wrong checkout, not a backlog. | Check the source and its checkout first. If folding these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1. | user | `repeat the read that failed` | 1 | no |++More: [docs/guides/repair.md#moved-pages](../../docs/guides/repair.md#moved-pages)+### movement_unknown<a id="movement_unknown"></a>diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 5d863a1734..f3448ef00b 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -221,6 +221,7 @@ work behind exits 0, so scripts should also check `results[].complete`.| `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync, or by a connector source on an older gbrain), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. || `file-drift` | `maintenance_write_drift` | Explicit-only, preview-bound. Resolves pages whose canonical file differs from the database copy (`source_changed` / `file_database_drift`) through canonical reconciliation, preferring the file or the database copy within reconcile's protections. `--all-drifted` refuses mixed drift classes unless `--class` keeps one; `--only`/`--skip` narrow by canonical file path glob. Opt-in `storage.keep_db` lets the owner host's resident consumer resolve drift under declared prefixes with the database copy. A page whose file is gone from the last commit: `--prefer database` recreates the file, `--prefer file` soft-deletes the page ([deleted canonical files](#deleted-canonical-files)). See [file drift](#file-drift). | Protected metadata, the tag union and protected takes or private fact rows, listed per page as `exceptions`; pages changed after the preview (`changed_since_preview`). || `ghost-pages` | `ghost_pages` | Explicit-only, preview-bound, destructive consent. Soft-deletes live pages whose canonical file is missing on the owner host (ghost pages: every write refuses `canonical_file_missing` and no sync can import a file that is not there), through `delete_page` bound to the previewed owner, path and revision. `--apply --expect <hash> --yes`. See [ghost pages](#ghost-pages). | Declared db_only and never-filed derived pages (never listed); a page whose file came back before the apply (`file_restored`); pages changed after the preview (`changed_since_preview`). |+| `moved-pages` | `ghost_pages` | Explicit-only, preview-bound, destructive consent. Folds a page left behind by a file that moved into the page the moved file imported as (GST-2584): when sync held the old page's deletion (`file_gone`), the new path imported as a fresh page. A page folds only on proof read from Git: its old path's last committed content is what one new path took at the move (or in that path's first commit), and the old page still holds it. Its links, relationship dates, timeline, raw data, files, user tags, aliases, facts and saved versions move to the moved page, its slug becomes an alias, its hold is cleared and it is soft-deleted (restorable for 72 h); no file is written. `--apply --expect <hash> --yes`. See [moved pages](#moved-pages). | Every other page whose file is gone, listed `held:<reason>`: `several_candidates`, `both_changed` (edited in the database after the move), `first_blob_differs`, `same_id_body_differs`, `evidence_conflicts`, `history_shallow`, `history_unknown`, `deletion_not_committed`, `not_moved`. || `uncommitted-deletions` | `uncommitted_sync_deletions` | Explicit-only, preview-bound, consent. Restores soft-deleted pages a managed sync removed before #7130 although Git never held their recorded file (`.gitignore` excludes it, or no commit holds it and it is not on the disk), one `restore_page` with `detach` each, published database-only: the page comes back live, forgets its recorded file, and no file is written. `--apply --expect <hash> --yes`. See [uncommitted deletions](#uncommitted-deletions). | Pages another writer deleted (listed, restored only with `--include-ambiguous`); tombstones whose file Git once committed or that is on the disk again; paths Git could not answer for (`unknown`); purged pages (only a backup brings them back). || `rows-behind` | `sync_rows_behind_checkpoint` | Explicit-only, preview-bound. Re-imports live pages of a managed source whose row holds an older version of its file than the sync checkpoint (`sources.last_commit`) says was imported, with no hold (#8071), from the file as committed at the checkpoint, through the managed file repair (no file is written). A file whose import is refused, or that is over the sync read bound, is held with that code instead. `--source <id>`, then `--apply --expect <hash>`. See [rows behind the checkpoint](#rows-behind). | Rows with no import record (`excluded:unproven`, joined with `--include-ambiguous`; one whose older version equals its committed file, so the database moved since, never joins: `excluded:database_moved`, nor one whose page and file both moved: `excluded:both_moved`), rows with an uncommitted working-tree edit (`excluded:worktree_differs`), rows whose import would keep page data the file does not carry (`excluded:import_overlay`); rows that moved after the preview (`changed_since_preview`). || `receipt-compaction` | `persistence_capacity` (terminal bytes) | Explicit-only, preview-bound, destructive consent. Compacts terminal write receipts now instead of on the idle maintenance tick (#6696): the intent and error message are dropped, the outcome, error code and detail stay, and the unused reservation returns to the receipt-bytes counters. `--older-than <72h\|30d>` is floored at the configured retention unless `--force`; committed receipts only unless `--include-failures`. No admission, so it runs at a full cap. See [receipt compaction](#receipt-compaction). | `failures_kept`: failed, conflict and cancelled receipts left without `--include-failures`. Receipts of a run whose sync cursor is still open, and the newest sync receipt of each worktree, are never listed. |@@ -1884,6 +1885,47 @@ origin; `CREATE UNIQUE INDEX CONCURRENTLY` on Postgres) only when the brain haschanges nothing and succeeds, and doctor's `origin_twins` check reports "Index pending". Once the last group isresolved, the repair's apply builds the index.+### Moved pages++Sync follows a file move when it happens. When the old page's deletion was held (a managed sync holds `file_gone` for a+page it cannot prove unchanged, including one with no import record), the new path imports as a fresh page and nothing+pairs the two again. Neither side of `repair file-drift` is right for that page: `--prefer file` soft-deletes it and drops+its links, facts, timeline and versions, and `--prefer database` writes a stale duplicate back at the old path. So the+file-drift preview lists such a page `moved_to`, resolves nothing for it, and names this repair instead:++```bash+gbrain repair moved-pages --source <id> [--slug <old-slug>] # preview, writes nothing+gbrain repair moved-pages --source <id> --apply --expect <hash> --yes # after the user agrees+```++A page folds only on two facts read from Git and the page, never on what the moved file holds today:++1. **The move.** The old path's last committed content (its blob at the parent of the commit that deleted it) is the+ content one new path took in that same commit, or in the first commit that holds the new path. A Git rename with the+ same content is the first case. Later edits to the moved file don't matter.+2. **The old page is untouched.** It still holds what that content imports (gbrain's own database-only artefacts, such+ as the grandfather `validate: false` stamp and a renamed pack type, count as unchanged).++Exactly one live page may descend from that content. The file name only explains a page with no candidate, because a+move can rename the file too, and a matching frontmatter `id` alone never pairs two pages. Every other page whose file+is gone is listed with why it is kept: `several_candidates`, `both_changed` (the old page was edited in the database+after the move: decide with the user), `first_blob_differs` (a page with the same file name started from other content),+`same_id_body_differs`, `evidence_conflicts` (a manual link or timeline entry that differs from the moved page's),+`history_shallow` (run `git fetch --unshallow` and preview again), `history_unknown`, `deletion_not_committed` and+`not_moved`.++The apply re-checks the proof and both pages under their keys, then folds each pair in one write (a coordinated+`managed_maintenance_fold_moved_page` maintenance write on a managed source, one maintenance transaction otherwise): the+old page's links in every role, relationship dates, timeline rows, raw data, attachments, user tags, free-text aliases,+facts other pages assert and saved versions move to the moved page, its slug becomes an alias (`get_page` and links+by the old slug reach the moved page), its `file_gone` hold is cleared, and it is marked `origin_twin` and soft-deleted.+No file is written. Each page gets a receipt (`moved_page_folded`) with the move commit, the blob and the restore+command: `gbrain restore <old-slug>` within 72 h brings back its own text as a database-only page, and the alias then+stops answering for it; references and versions moved to the moved page stay there. The apply refuses+[`moved_pages_mass_fold_refused`](error-codes.md#moved_pages_mass_fold_refused) when its folds would soft-delete more+than half of the source's file-backed pages, unless `GBRAIN_ALLOW_MASS_RECONCILE=1`. A source with no checkout (a+repo-less source) has no file that could move, so the preview lists nothing.+### Slug path mismatchDoctor's `slug_path_mismatch` check (#7305) counts live pages whose slug their recorded file path does not derive. The@@ -3472,6 +3514,9 @@ count. Read those lines before you agree to the apply.| `purged_differs` | Removes the file. | Imports the file as a new page. || `file_gone` | Recreates the file from the page. | Soft-deletes the page (the mass-delete valve applies). |+A `file_gone` page whose file moved is listed `moved_to <slug>` under either `--prefer` and resolved by neither: its+line names [`gbrain repair moved-pages`](#moved-pages), which folds it into the moved page.+`--prefer file` keeps the file's bytes: it adds only protected frontmatter keys thefile lacks and database-only timeline rows, and refuses[`file_wins_rewrite`](write-refusals.md#file_wins_rewrite) when the resultdiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 4fcc93e5c9..fe19c3dbfb 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -277,7 +277,7 @@ with each file and fix the ones that need no guessing."*| <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); 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`). A `file_gone` hold of a page with no import record says so (`meta.no_import_record`) instead of naming a database edit; when its file moved, `gbrain repair file-drift --held` lists the page `moved_to` and [`gbrain repair moved-pages`](repair.md#moved-pages) folds it into the moved page. 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 --git a/src/commands/repair.ts b/src/commands/repair.tsindex 421bdd65f4..bdc1b8513e 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -227,7 +227,7 @@ const VALUE_FLAGS = new Set(['--readers', '--slugs-file', '--rules', '--source',const KIND_FLAGS: Record<string, readonly string[]> = {'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],'--include-cross-entity': ['duplicate-facts'],- '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins', 'timeline-order', 'contact-rows', 'provenance', 'secret-spans', 'segmented-tiling', 'visibility'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift', 'visibility', 'private-labels'], '--since': ['file-drift', 'generations'],+ '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins', 'moved-pages', 'timeline-order', 'contact-rows', 'provenance', 'secret-spans', 'segmented-tiling', 'visibility'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift', 'visibility', 'private-labels'], '--since': ['file-drift', 'generations'],'--held': ['file-drift', 'generations'], '--side': ['file-drift'], '--state': ['file-drift'], '--cursor': ['file-drift'], '--provenance': ['file-drift'],'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],@@ -546,7 +546,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(olderThan ? ['--older-than', olderThan] : []), ...(includeFailures ? ['--include-failures'] : []), ...(force ? ['--force'] : []),...(afterPage !== undefined ? ['--after', String(afterPage)] : []), ...(day ? ['--day', day] : []),...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : []),- ...(kind === 'origin-twins' || kind === 'timeline-order' || kind === 'contact-rows' || kind === 'provenance' ? slugs.flatMap(slug => ['--slug', slug]) : []),+ ...(kind === 'origin-twins' || kind === 'moved-pages' || kind === 'timeline-order' || kind === 'contact-rows' || kind === 'provenance' ? slugs.flatMap(slug => ['--slug', slug]) : []),...(generations ? generationsSelectionArgv(generations) : []),...(kind === 'agent-session-facts' ? agentSessionFlagArgs({ cwdPrefixes, sessions, principal }) : []),...(kind === 'file-drift' ? [...slugs.flatMap(slug => ['--slug', slug]), ...requests.flatMap(id => ['--request', id]), ...(allDrifted ? ['--all-drifted'] : []),diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 13d106e7eb..f5afd4125d 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -372,6 +372,7 @@ export const CODES = {gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },ghost_mass_delete_refused: { class: 'consent', summary: "gbrain repair ghost-pages refused to soft-delete more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to ghost pages: that many missing canonical files almost always means the checkout is the wrong path, unmounted or half-cloned, not that the files were deleted.", docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Check the source checkout on its owner host first. If removing these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host, to check the checkout before anything is removed.", requires_exclusive: false } },notifier_stalled: { class: 'retryable', actor: 'agent', summary: "The commit notifier kept a source due through every retry tier (5 s, 15 s, 1 min, 5 min) without the sync making progress; it keeps retrying every 5 minutes.", why: "A commit-triggered sync failed or was refused the same way on every attempt, so the commit is still not searchable; the notifier block in gbrain sync status names the last error and the trace file with every attempt.", docs: 'docs/guides/on-commit-sync.md#notifier-stalled', suggestion: 'Run gbrain sync --source <id> --no-pull in the foreground to see the error, fix its cause, then read gbrain sync status --source <id> --json (the notifier block) to confirm the source is current.' },+ moved_pages_mass_fold_refused: { class: 'consent', summary: "gbrain repair moved-pages refused to fold moved pages amounting to more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to moved pages (GST-2584): that many moved pages at once almost always means a re-import under other paths or the wrong checkout, not a backlog.", docs: 'docs/guides/repair.md#moved-pages', suggestion: 'Check the source and its checkout first. If folding these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.' },origin_twin_mass_merge_refused: { class: 'consent', summary: "gbrain repair origin-twins refused to merge duplicate-origin twins amounting to more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to origin twins (#6948): that many twins at once almost always means a re-import under other slugs or the wrong checkout, not a backlog.", docs: 'docs/guides/repair.md#origin-twins', suggestion: 'Check the source and its checkout first. If merging these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.' },ghost_storage_unknown: { class: 'unavailable', summary: "Ghost pages of a source cannot be classified because its canonical checkout cannot be read reliably; nothing was listed or changed.", why: "A page is never reported or removed as a ghost while its file may only be unreadable: a missing or non-directory root (storage_unavailable), or a stat error, an invalid gbrain.yml or an inconclusive page check (ambiguous_storage), fails closed.", reasons: ['storage_unavailable', 'ambiguous_storage'], docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Inspect the source checkout on its owner host (writer status shows its root), fix it, then preview gbrain repair ghost-pages --source <id> again.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host.", requires_exclusive: false } },git_branch_unborn: { class: 'host_only', summary: "The canonical checkout's branch has no commit yet, so Git durability has nothing to build on.", why: "A Git effect commits on top of HEAD and pushes the branch; on an unborn branch (a fresh `init --git` root) there is no HEAD to commit on and no ref to push, so enabling durability would park every effect. The database is unaffected.", suggestion: 'Make the first commit on the branch on the brain host (git add -A && git commit -m "Initial brain"), then rerun gbrain sources writer git-durability <source> --enable.' },diff --git a/src/core/markdown.ts b/src/core/markdown.tsindex 71bf41a28f..ad36598407 100644--- a/src/core/markdown.ts+++ b/src/core/markdown.ts@@ -1093,7 +1093,7 @@ const GBRAIN_BASE_PATH_PREFIXES: ReadonlyArray<{ prefixes: string[]; type: PageT{ prefixes: ['/life/diary/'], type: 'diary' },];-function inferType(filePath?: string): PageType {+export function inferType(filePath?: string): PageType {return inferTypeWithPrefixes(filePath, GBRAIN_BASE_PATH_PREFIXES);}diff --git a/src/core/persistence/align-stored.ts b/src/core/persistence/align-stored.tsindex f3cb1c8434..cc7bb390da 100644--- a/src/core/persistence/align-stored.ts+++ b/src/core/persistence/align-stored.ts@@ -1,4 +1,4 @@-import { resolveParsedSubtype, type ParsedMarkdown } from '../markdown.ts';+import { inferType, resolveParsedSubtype, type ParsedMarkdown } from '../markdown.ts';/*** Aligns a canonical file's parse with what its import over `stored` keeps (#1035, #5521): a file without an explicit@@ -10,14 +10,14 @@ import { resolveParsedSubtype, type ParsedMarkdown } from '../markdown.ts';* read as written, so an explicit type there still wins.*/export function alignWithStored(parsed: ParsedMarkdown, stored: { type: string; frontmatter?: Record<string, unknown> | null }, inferred: boolean, retypeStamp = true): void {- if (!(retypeStamp && keepRetypeStamp(parsed, stored)) && (inferred || !parsed.typeExplicit)) parsed.type = stored.type as ParsedMarkdown['type'];+ if (!(retypeStamp && (keepRetypeStamp(parsed, stored) || keepPackRenamedType(parsed, stored))) && (inferred || !parsed.typeExplicit)) parsed.type = stored.type as ParsedMarkdown['type'];resolveParsedSubtype(parsed, stored);keepGrandfatherStamp(parsed.frontmatter, stored);}/** Sync's reading of a file over the stored page (sync-prepare.ts): the retype stamp, the subtype and the grandfather stamp kept as `alignWithStored` keeps them; an explicit file type is otherwise read as written. */export function keepStoredStamps(parsed: ParsedMarkdown, stored?: { type: string; frontmatter?: Record<string, unknown> | null } | null): void {- keepRetypeStamp(parsed, stored);+ if (!keepRetypeStamp(parsed, stored)) keepPackRenamedType(parsed, stored);resolveParsedSubtype(parsed, stored);keepGrandfatherStamp(parsed.frontmatter, stored);}@@ -38,6 +38,21 @@ export function keepRetypeStamp(parsed: ParsedMarkdown, stored?: { type: string;return true;}+/**+ * GST-2584: a page type gbrain itself named and later renamed. Before #6454 an import kept the reserved `type` key in the+ * stored frontmatter, and gbrain wrote that type into the file, with the name gbrain-base 1.0.0 infers from the path+ * (`writing/` is `writing`). A later pack infers another type for the same path and the column took it, so the file and the+ * stored copy still say the 1.0.0 name. A file whose explicit type is that name, equal to the stored copy and to what+ * gbrain-base 1.0.0 infers for its path, while the column says otherwise, is the page as renamed: it keeps the stored type.+ * Any other explicit type (a person's) is read as written. Returns whether the stored type was kept.+ */+export function keepPackRenamedType(parsed: ParsedMarkdown, stored?: { type: string; frontmatter?: Record<string, unknown> | null } | null): boolean {+ const copy = stored?.frontmatter?.type;+ if (!stored || parsed.typeExplicit !== true || typeof copy !== 'string' || parsed.type !== copy || parsed.type === stored.type || inferType(parsed.slug) !== parsed.type) return false;+ parsed.type = stored.type as ParsedMarkdown['type'];+ return true;+}+/*** #6429: the v0.13.1 grandfather stamped `validate: false` into the database; on an unmanaged brain that path never wrote* the file, so the file lacks a key the database carries. The mechanical stamp authors nothing (grandfather.ts): a filediff --git a/src/core/persistence/moved-pages.ts b/src/core/persistence/moved-pages.tsnew file mode 100644index 0000000000..e807fac595--- /dev/null+++ b/src/core/persistence/moved-pages.ts@@ -0,0 +1,135 @@+/**+ * GST-2584: whether a live page whose file is gone (a ghost, held `file_gone` on a managed source) is a file that moved,+ * and to which page. Sync follows a move only when it happens; when the old page's deletion was held, the new path+ * imported as a fresh page and nothing pairs the two again. `gbrain repair file-drift` lists such a page `moved_to`+ * and `gbrain repair moved-pages` folds it into the moved page; both read this one verdict.+ *+ * The proof that loses nothing is two facts, read from Git and the page, never from today's content of the moved file:+ * 1. the move: the old path's last committed blob (at the first parent of the commit that deleted it) is the blob a new+ * path took in that same commit, or the blob of the first commit that holds the new path. A Git rename with identical+ * content is the first case; later edits to the moved file do not matter;+ * 2. the stale side is untouched: the old page still holds what that blob imports (`fileMatchesSnapshot`, which reads+ * gbrain's own database-only artefacts as derived: `alignWithStored`). A page edited in the database after the move+ * is `both_changed`.+ * Exactly one live page of the source may descend from the blob; two or more are `several_candidates`. The file name+ * only explains a result with no candidate (a move can rename the file too), and a frontmatter `id` alone never pairs+ * two pages. A history too shallow to read the move, or one Git cannot answer, keeps the page held and says so.+ */+import { basename } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { syncGit } from './sync-discovery.ts';+import { readDeletionProvenance, type DeletionProvenance } from './sync-origin-evidence.ts';+import { fileMatchesSnapshot } from './page-prepare.ts';+import { twinMergeConflicts } from './twin-merge.ts';+import { literalPathspecs } from '../git-env.ts';++export interface MovedPageRef { page_id: number; slug: string; revision: string; path: string }+export type MovedEvidence = 'same_commit' | 'first_commit';+export const MOVED_HELD_REASONS = ['not_moved', 'several_candidates', 'both_changed', 'first_blob_differs', 'same_id_body_differs', 'evidence_conflicts',+ 'history_shallow', 'history_unknown', 'deletion_not_committed'] as const;+export type MovedHeldReason = typeof MOVED_HELD_REASONS[number];+export type MovedPageVerdict =+ | { verdict: 'moved'; survivor: MovedPageRef; old_blob: string; move_commit: string; evidence: MovedEvidence; evidence_commit: string; detail: string }+ | { verdict: 'held'; reason: MovedHeldReason; detail: string; candidates?: string[] };++const git = (root: string, args: string[]): string | null => { try { return syncGit(root, args); } catch { return null; } };+const shallow = (root: string) => git(root, ['rev-parse', '--is-shallow-repository'])?.trim() === 'true';+const short = (sha: string) => sha.slice(0, 12);++/** Paths (relative to `root`) that took `blob` in `commit` itself (added or changed to it there). */+function sameCommitPaths(root: string, commit: string, blob: string): string[] | null {+ const out = git(root, ['diff-tree', '-r', '--no-renames', '--no-commit-id', '--relative', '-z', `${commit}^`, commit]);+ if (out === null) return null;+ const fields = out.split('\0');+ const paths: string[] = [];+ for (let i = 0; i + 1 < fields.length; i += 2) {+ const [, , , next, status] = fields[i]!.split(' ');+ if (next === blob && status !== 'D') paths.push(fields[i + 1]!);+ }+ return paths;+}++/** Paths (relative to `root`) whose first commit in HEAD's history added them with `blob`, with that commit. */+function firstCommitPaths(root: string, blob: string): Map<string, string> | null {+ const out = git(root, ['log', '--no-renames', '--relative', '--raw', '--no-abbrev', '--format=commit %H', `--find-object=${blob}`, 'HEAD']);+ if (out === null) return null;+ const added = new Map<string, string>();+ let commit = '';+ for (const line of out.split('\n')) {+ if (line.startsWith('commit ')) { commit = line.slice(7).trim(); continue; }+ const match = /^:\d+ \d+ [0-9a-f]+ ([0-9a-f]+) A\t(.+)$/.exec(line);+ if (match && match[1] === blob && !match[2]!.startsWith('"')) added.set(match[2]!, commit);+ }+ const first = new Map<string, string>();+ for (const [path, commitOf] of added) {+ const history = git(root, ['log', '--no-renames', '--relative', '--diff-filter=A', '--format=%H', '--reverse', 'HEAD', '--', ...literalPathspecs([path])]);+ if (history === null) return null;+ if (history.split('\n').find(Boolean)?.trim() === commitOf) first.set(path, commitOf);+ }+ return first;+}++/** Of `paths`, those HEAD still holds (relative to `root`). */+function inHead(root: string, paths: string[]): Set<string> {+ if (!paths.length) return new Set();+ const out = git(root, ['ls-tree', '-r', '-z', '--name-only', 'HEAD', '--', ...literalPathspecs(paths)]);+ return new Set((out ?? '').split('\0').filter(Boolean));+}++/**+ * The verdict for one ghost page (`old`: its id, slug, revision and recorded path, relative to the source's canonical+ * root). `provenance` is the path's deletion provenance when the caller already read it (one history walk per window).+ */+export async function readMovedPage(engine: BrainEngine, input: { sourceId: string; root: string; old: MovedPageRef; provenance?: DeletionProvenance }): Promise<MovedPageVerdict> {+ const { sourceId, root, old } = input;+ const held = (reason: MovedHeldReason, detail: string, candidates?: string[]): MovedPageVerdict => ({ verdict: 'held', reason, detail, ...(candidates ? { candidates } : {}) });+ const deletion = input.provenance ?? (await readDeletionProvenance(root, [old.path])).get(old.path) ?? { kind: 'unknown' as const };+ if (deletion.kind !== 'deleted_by_commit') {+ if (shallow(root)) return held('history_shallow', `the checkout's history is shallow, so the commit that deleted ${old.path} cannot be read; fetch the full history (git fetch --unshallow) to check whether it moved`);+ if (deletion.kind === 'unknown') return held('history_unknown', `Git could not name the commit that deleted ${old.path}, so no move can be proven`);+ return held('deletion_not_committed', deletion.kind === 'never_committed' ? `no commit ever held ${old.path}, so there is no committed content to follow`+ : `HEAD still holds ${old.path}; only the working tree lost it, so it did not move in Git`);+ }+ const commit = deletion.commit;+ const blob = git(root, ['rev-parse', '--verify', '--quiet', `${commit}^:./${old.path}`])?.trim();+ if (!blob) return shallow(root) ? held('history_shallow', `the checkout's history is shallow, so ${old.path}'s content before commit ${short(commit)} cannot be read; fetch the full history (git fetch --unshallow) to check whether it moved`)+ : held('history_unknown', `Git could not read ${old.path} before commit ${short(commit)}, which deleted it`);+ const same = sameCommitPaths(root, commit, blob);+ const first = firstCommitPaths(root, blob);+ if (same === null || first === null) return held('history_unknown', `Git could not read which paths took ${old.path}'s content (blob ${short(blob)})`);+ const evidence = new Map<string, { evidence: MovedEvidence; commit: string }>();+ for (const [path, at] of first) if (path !== old.path) evidence.set(path, { evidence: 'first_commit', commit: at });+ for (const path of same) if (path !== old.path) evidence.set(path, { evidence: 'same_commit', commit });+ const present = inHead(root, [...evidence.keys()]);+ const rows = present.size ? await engine.executeRaw<{ id: number; slug: string; revision: string; source_path: string }>(`SELECT id, slug, knowledge_revision::text AS revision, source_path+ FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND id<>$2 AND source_path=ANY($3::text[]) ORDER BY id`, [sourceId, old.page_id, [...present]]) : [];+ if (rows.length > 1) return held('several_candidates', `${rows.length} live pages (${rows.map(row => row.slug).join(', ')}) started from ${old.path}'s last committed content (blob ${short(blob)}), so which one it moved to is a person's decision`,+ rows.map(row => row.slug));+ if (!rows.length) {+ const name = basename(old.path);+ const named = await engine.executeRaw<{ slug: string; source_path: string }>(`SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND id<>$2+ AND source_path IS NOT NULL AND (source_path=$3 OR right(source_path, length($3) + 1)='/' || $3) ORDER BY slug LIMIT 5`, [sourceId, old.page_id, name]);+ if (named.length) return held('first_blob_differs', `${named.map(row => row.source_path).join(', ')} has the same file name, but neither its first committed content nor its content in commit ${short(commit)} is ${old.path}'s last committed content (blob ${short(blob)}), so it is not proven to be the moved file`,+ named.map(row => row.slug));+ const [own] = await engine.executeRaw<{ id: string | null }>('SELECT frontmatter->>\'id\' AS id FROM pages WHERE id=$1', [old.page_id]);+ const twins = own?.id ? await engine.executeRaw<{ slug: string }>(`SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND id<>$2 AND frontmatter->>'id'=$3 ORDER BY slug LIMIT 5`,+ [sourceId, old.page_id, own.id]) : [];+ if (twins.length) return held('same_id_body_differs', `${twins.map(row => row.slug).join(', ')} has the same frontmatter id, but no page started from ${old.path}'s last committed content (blob ${short(blob)}), so the bodies differ and a fold would drop one side's edits`,+ twins.map(row => row.slug));+ return held('not_moved', `no live page of the source started from ${old.path}'s last committed content (blob ${short(blob)}), so commit ${short(commit)} deleted it rather than moving it`);+ }+ const row = rows[0]!;+ const survivor: MovedPageRef = { page_id: Number(row.id), slug: row.slug, revision: String(row.revision), path: row.source_path };+ const proof = evidence.get(row.source_path)!;+ const snapshot = await engine.readPageSnapshot(old.slug, { sourceId });+ const content = git(root, ['cat-file', 'blob', blob]);+ if (!snapshot || content === null) return held('history_unknown', `the page or blob ${short(blob)} could not be read`);+ if (!await fileMatchesSnapshot(engine, old.slug, content, snapshot, old.path).catch(() => false)) {+ return held('both_changed', `${old.path} moved to ${row.source_path} (blob ${short(blob)}), but page ${old.slug} changed in the database after the move, so a fold would drop its edit; decide with the user`, [row.slug]);+ }+ const conflicts = await twinMergeConflicts(engine, survivor.page_id, old.page_id);+ if (conflicts.length) return held('evidence_conflicts', `${old.path} moved to ${row.source_path}, but page ${old.slug} holds ${conflicts.map(c => c.detail).join('; ')}, which a fold would discard`, [row.slug]);+ return { verdict: 'moved', survivor, old_blob: blob, move_commit: commit, evidence: proof.evidence, evidence_commit: proof.commit,+ detail: `moved to ${row.slug}: ${proof.evidence === 'same_commit' ? `commit ${short(commit)} deleted ${old.path} and gave ${row.source_path} its content`+ : `${row.source_path}'s first commit ${short(proof.commit)} holds ${old.path}'s last committed content`} (blob ${short(blob)}), and page ${old.slug} still holds that content` };+}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex f0d7d9bd12..dda2bfea28 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -662,6 +662,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, coif (row.intent?.kind === 'managed_maintenance_file_drift_detach') return (await import('../repair/file-drift.ts')).prepareDriftDetach(engine, row);if (row.intent?.kind === 'managed_maintenance_merge_legacy_twin') return (await import('../repair/legacy-twins.ts')).prepareLegacyTwinMerge(engine, row, config);if (row.intent?.kind === 'managed_maintenance_resolve_origin_twin') return (await import('../repair/origin-twins.ts')).prepareOriginTwinResolve(engine, row, config);+ if (row.intent?.kind === 'managed_maintenance_fold_moved_page') return (await import('../repair/moved-pages.ts')).prepareMovedPageFold(engine, row, config);if (row.intent?.kind !== 'managed_maintenance_consolidate') throw opError('invalid_params', 'Unsupported maintenance request.',`Request ${row.request_id} for ${row.slug} in ${row.source_id} carries a maintenance kind this gbrain version does not publish (likely queued by a newer release); nothing changed. Upgrade gbrain on the brain host, and read the receipt before submitting anything new.`,{ fix: receiptFix(row) });diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 51ce5235d9..26986f67ac 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'atom-fence-rows' | 'extractor-facts' | 'unwithdrawn-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind' | 'facts-home' | 'private-labels' | 'lost-fence-rows';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'atom-fence-rows' | 'extractor-facts' | 'unwithdrawn-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'moved-pages' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind' | 'facts-home' | 'private-labels' | 'lost-fence-rows';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 4c7a40a885..ae103385d3 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -33,7 +33,7 @@* for a recommended merge or an undecidable pair, a paragraph for a person.*/import type { BrainEngine } from '../engine.ts';-import type { Action } from '../agent-output.ts';+import { shellQuote, type Action } from '../agent-output.ts';import type { ContentRefusal } from '../import-screen.ts';import { RECOVERY_VERSION, type InvalidFrontmatterReason } from '../markdown.ts';import { ORIGIN_TWINS_AUTO_RESOLVE_KEY, originTwinsPreviewArgv, type OriginConflictReason } from './origin-twins.ts';@@ -189,6 +189,8 @@ export interface GitHoldMeta {deleted?: true;/** GBRA-133 `file_drift` `file_gone`: `sync.apply_held_deletions` refused this deletion (sync-held-deletions.ts) while the page was at `page_revision`. */held_deletion?: { refused: string; page_revision: string };+ /** GST-2584 `file_drift` `file_gone`: the page has no import record of its revision, so sync cannot tell whether it changed in the database. */+ no_import_record?: true;/*** #6712 dependency edge: the path of an earlier entry of the same sync, sharing this entry's slug or page id, that was* held in that sync; this entry waits on it with the same code, and discovery re-screens it once that hold is gone.@@ -740,6 +742,11 @@ export function heldDriftPreviewArgv(sourceId: string, side: FileDriftSide, stat...(path ? ['--only', path] : []), '--prefer', prefer];}+/** GST-2584: the read-only preview of `gbrain repair moved-pages`, which folds a page whose file moved into the moved page. */+export function movedPagesPreviewArgv(sourceId: string, slug?: string | null): string[] {+ return ['gbrain', 'repair', 'moved-pages', '--source', sourceId, ...(slug ? ['--slug', slug] : [])];+}+/** #6712 PR 4b: the Decision for a `file_drift` hold whose one side is a deletion; each option names its action verb. */function deletedDriftFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'meta'> & Partial<Pick<GitHoldRecord, 'slug'>>, state: FileDriftDeletedState): Action {const source = record.source_id;@@ -759,8 +766,11 @@ function deletedDriftFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'met: uncommitted ? `${record.path} is gone, but Git never committed it${record.meta.reason === 'ignored' ? ' (.gitignore excludes it)' : ''}, so its absence is no evidence of a deletion and sync kept page ${slug} instead of deleting it (#7130). Put the file back and commit it (un-ignore it first) to keep the page file-backed. `: state === 'tombstone_edited' ? `Page ${slug} was deleted${revision} and ${record.path} then changed, so sync held the file instead of restoring the page or dropping the edit. `: state === 'purged_differs' ? `The page of ${record.path} was purged and the file differs from what the brain held, so sync held the file instead of importing it as a new page. `+ : record.meta.no_import_record ? `${record.path} is gone from the last commit, and page ${slug}${revision} has no import record that says whether it changed in the database since the file was imported, so sync held the deletion instead of removing it. `: `${record.path} is gone from the last commit but page ${slug} changed${revision}, so sync held the deletion instead of removing a page that changed. `;- const options = `This preview (writes nothing) shows --prefer database: ${fileDriftActionVerb('deleted', state, 'database')}; ${preview('file').join(' ')} previews --prefer file: `+ // GST-2584: a file that moved left its page behind; the --held preview lists it moved_to and names the fold.+ const moved = state === 'file_gone' ? `If the file moved, the preview lists the page moved_to <slug> and names ${shellQuote(movedPagesPreviewArgv(source, record.slug))}, which folds it into the moved page. ` : '';+ const options = `${moved}This preview (writes nothing) shows --prefer database: ${fileDriftActionVerb('deleted', state, 'database')}; ${preview('file').join(' ')} previews --prefer file: `+ `${fileDriftActionVerb('deleted', state, 'file')}. `;return { argv: preview('database'), consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/repair.md#deleted-canonical-files',why: `${what}${options}Decide with the user. ${FILE_DRIFT_APPLY_STEP} Then sync again. The rest of the source is not blocked.`,diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.tsindex a50ba39cd2..9560edf3c1 100644--- a/src/core/persistence/sync-pass-apply.ts+++ b/src/core/persistence/sync-pass-apply.ts@@ -317,9 +317,11 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Papending.push({ entry, code: 'file_drift', slug: entry.slug, kind: 'uncommitted', meta: { side: 'deleted', state: 'file_gone', reason: r.uncommitted, ...(entry.revision ? { page_revision: entry.revision } : {}) },message: `${path}: the file is gone, but ${why}, so its absence is no evidence that page ${entry.slug} was deleted; sync held it and kept the page instead of deleting it (#7130); the rest of the source synced.` });} else if (r.cls === 'delete_drift') {+ const unrecorded = entry.state.record?.revision == null;pending.push({ entry, code: 'file_drift', slug: entry.slug, kind: 'file_gone', meta: { side: 'deleted', state: 'file_gone', ...(entry.revision ? { page_revision: entry.revision } : {}),- ...(r.heldDeletionRefused && entry.revision ? { held_deletion: { refused: r.heldDeletionRefused, page_revision: entry.revision } } : {}) },- message: `${path}: the file is gone, but page ${entry.slug} changed in the database since the file was last imported, so sync held the deletion instead of deleting the page; the rest of the source synced.` });+ ...(r.heldDeletionRefused && entry.revision ? { held_deletion: { refused: r.heldDeletionRefused, page_revision: entry.revision } } : {}), ...(unrecorded ? { no_import_record: true as const } : {}) },+ message: unrecorded ? `${path}: the file is gone, and page ${entry.slug} has no import record that says whether it changed in the database since the file was imported, so sync held the deletion instead of deleting the page; the rest of the source synced.`+ : `${path}: the file is gone, but page ${entry.slug} changed in the database since the file was last imported, so sync held the deletion instead of deleting the page; the rest of the source synced.` });} else if (r.cls === 'deleted_edited') {const purged = r.state === 'purged_differs';const slug = purged ? (await readStoredMarker(engine, level, passEntryPaths(level, entry.path).sourcePath))?.slug ?? resolveSlugForPath(passEntryPaths(level, entry.path).sourcePath) ?? null : entry.slug;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 62b304b193..6c57744e8c 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -54,7 +54,7 @@ import type { GenerationsSelection } from '../generations/repair.ts';import type { PrivateLabelsLedger } from './private-labels.ts';import type { ReadersRequest } from './readers.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'access', 'private-labels'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'moved-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'access', 'private-labels'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.tsindex 6ecc8ca728..926792464d 100644--- a/src/core/repair/file-drift.ts+++ b/src/core/repair/file-drift.ts@@ -76,7 +76,8 @@ import { protectedReconcileKey, reconcileCanonical, RECONCILE_SCAN_KEYS, type Reimport { fileWinsContent } from '../persistence/file-wins-content.ts';import { ABSENT_FILE_HASH, canonicalDeletionState, missingFileRoute, readCanonicalFileText, readDeletedDriftTarget, readReconcileState, assertReconcileRevision, validateReconcileArtifact, type DeletedDriftChange, type DeletedDriftTarget, type ReconcileArtifact } from '../persistence/reconcile-state.ts';import { sourceDbOnlyVerdict } from '../persistence/source-storage.ts';-import { clearGitHold, readGitHold, fileDriftActionVerb, fileDriftSide, FILE_DRIFT_DELETED_STATES, FILE_DRIFT_SIDES, GIT_HOLD_OP, heldDriftPreviewArgv, requestGitHoldRetry, type FileDriftDeletedState, type FileDriftSide, type GitHoldRecord } from '../persistence/sync-holds.ts';+import { readMovedPage } from '../persistence/moved-pages.ts';+import { clearGitHold, movedPagesPreviewArgv, readGitHold, fileDriftActionVerb, fileDriftSide, FILE_DRIFT_DELETED_STATES, FILE_DRIFT_SIDES, GIT_HOLD_OP, heldDriftPreviewArgv, requestGitHoldRetry, type FileDriftDeletedState, type FileDriftSide, type GitHoldRecord } from '../persistence/sync-holds.ts';import { prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';import { maintenancePreflight, submitDatabaseMaintenanceIntent, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';import type { PreparedMutation } from '../persistence/coordinator.ts';@@ -567,6 +568,10 @@ async function fileGonePage(engine: BrainEngine, sourceId: string, slug: string,const root = join(binding!.local_path!, binding!.relative_path);const deletion = canonicalDeletionState(root, join(root, ...now.ghost.path.split('/')));if (deletion !== 'gone') return { skip: deletion === 'in_head' ? 'deletion_uncommitted' : 'unknown_deletion_state', detail: missingFileRoute(sourceId, slug, now.ghost.path, deletion) };+ // GST-2584: a file that moved left this page behind; neither side of this repair carries it, the fold does.+ const deletedBy = target?.provenance ?? (await readDeletionProvenance(root, [now.ghost.path])).get(now.ghost.path) ?? { kind: 'unknown' as const };+ const moved = await readMovedPage(engine, { sourceId, root, old: { page_id: now.ghost.page_id, slug, revision: now.ghost.revision, path: now.ghost.path }, provenance: deletedBy });+ if (moved.verdict === 'moved') return { skip: 'moved_to', detail: `${moved.detail}; nothing is written for it here. Fold it into ${moved.survivor.slug} instead (its alias, links, facts, timeline and saved versions carried, the old page soft-deleted and restorable): ${shellQuote(movedPagesPreviewArgv(sourceId, slug))}` };if (opts.prefer === 'file' && sourceDbOnlyVerdict(root, slug) === 'unknown') return { skip: 'storage_invalid',detail: `gbrain.yml's storage section is invalid or ambiguous about db_only, so whether ${slug} is database-only is unknown and --prefer file would delete it (#8007): run gbrain storage status, fix gbrain.yml, commit it, then sync source ${sourceId} again` };if (opts.provenance === 'never_committed' && target?.provenance?.kind === 'never_committed') {@@ -577,7 +582,6 @@ async function fileGonePage(engine: BrainEngine, sourceId: string, slug: string,if (opts.prefer === 'file') return { page: { slug, prefer: 'file', exceptions: [], soft_delete: { ghost: now.ghost, owner: now.owner } },detail: `soft-deletes the page: its file ${now.ghost.path} is gone from the last commit (purged after ${GHOST_PURGE_FUSE_HOURS} h; gbrain restore ${slug} --force undoes it until then)` };// GST-2579: recreating the file undoes the commit that deleted it; in bulk the deletion is kept, an exact --slug names the commit and needs consent.- const deletedBy = target?.provenance ?? (await readDeletionProvenance(root, [now.ghost.path])).get(now.ghost.path) ?? { kind: 'unknown' as const };const undone: UnimportedFile | null = deletedBy.kind === 'never_committed' ? null : { path: now.ghost.path, reason: 'unimported_delete',commit: deletedBy.kind === 'deleted_by_commit' ? { sha: deletedBy.commit, author: deletedBy.author, date: deletedBy.date } : null };if (undone && !opts.slugs?.length) return { skip: 'kept_newer_delete', detail: `kept the deletion, nothing is written for it: recreating the file would undo ${unimportedFileText(undone)}. `diff --git a/src/core/repair/moved-pages.ts b/src/core/repair/moved-pages.tsnew file mode 100644index 0000000000..4fefd1743d--- /dev/null+++ b/src/core/repair/moved-pages.ts@@ -0,0 +1,255 @@+/**+ * `gbrain repair moved-pages --source <id> [--slug <old-slug>]...` (GST-2584): fold a page left behind by a file that moved+ * into the page the moved file imported as.+ *+ * Sync follows a move only when it happens. When the old page's deletion was held (a managed source holds `file_gone`+ * for a page it cannot prove unchanged), the new path imports as a fresh page and nothing pairs the two again; neither+ * side of `repair file-drift` carries the old page (`--prefer file` drops its links, facts, timeline and versions,+ * `--prefer database` writes a stale duplicate back). This repair pairs them on proof read from Git+ * (persistence/moved-pages.ts): the old path's last committed content is the moved file's content at the move, and the old+ * page still holds it. Exactly one page may descend from it; anything else is listed with its reason and kept.+ *+ * Explicit-only, preview-bound, trusted local CLI on the source's owner host. `--apply --expect <hash> --yes` folds exactly+ * the previewed pairs, one coordinated maintenance write per pair (`managed_maintenance_fold_moved_page`; an unmanaged+ * brain does the same in one maintenance transaction), re-checking the proof and both pages under their keys:+ * `mergeTwinInto` moves links in every role, relationship dates, timeline, raw data, files, user tags, aliases and facts+ * to the moved page, records the old slug as an alias and soft-deletes the old page (database-only, restorable for+ * ${MOVED_PAGES_PURGE_FUSE_HOURS} h); its saved versions move too, and its `file_gone` hold is cleared. No file is written.+ * A repo-less brain has no file that could move, so the preview lists nothing.+ */+import type { BrainEngine } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import type { PreparedMutation } from '../persistence/coordinator.ts';+import type { WriteRequest } from '../persistence/model.ts';+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';+import { shellQuote } from '../agent-output.ts';+import { authorizeWrite } from '../persistence/authority.ts';+import { prepareCoreGuard } from '../persistence/core-guard.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';+import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { mergeTwinInto } from '../persistence/twin-merge.ts';+import { readMovedPage, type MovedEvidence, type MovedHeldReason, type MovedPageRef } from '../persistence/moved-pages.ts';+import { readDeletionProvenance } from '../persistence/sync-origin-evidence.ts';+import { clearGitHold, movedPagesPreviewArgv } from '../persistence/sync-holds.ts';+import { ghostPageNow, scanGhostSource, sourceContext, type GhostOwner } from '../ghost-pages.ts';+import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';+import { ghostScanRefusal, GHOST_PURGE_FUSE_HOURS, GHOST_REPAIR_LIMIT } from './ghost-pages.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';++export const MOVED_PAGES_INTENT = 'managed_maintenance_fold_moved_page';+export const MOVED_PAGES_PURGE_FUSE_HOURS = GHOST_PURGE_FUSE_HOURS;+const DOCS = 'docs/guides/repair.md#moved-pages';++/** One coordinated write: the old page folds into the page its file moved to. */+export interface MovedPair { source_id: string; old: MovedPageRef; survivor: MovedPageRef; old_blob: string; move_commit: string; evidence: MovedEvidence; evidence_commit: string; observed_at: string }+interface HeldPage { source_id: string; slug: string; path: string; reason: MovedHeldReason; detail: string; candidates?: string[] }+interface ApprovedPair extends MovedPair { owner: GhostOwner; selection: string[] }+interface PairItem extends RepairItem { pair: MovedPair; owner: GhostOwner; hash: string; last: boolean }++const previewArgv = (sourceId: string) => [...movedPagesPreviewArgv(sourceId), '--json'];+const previewFix = (sourceId: string) => readFix('Previews the pages of the source whose file moved again; writes nothing.', { argv: previewArgv(sourceId) });+const sameOwner = (a: GhostOwner | undefined, b: GhostOwner) => !!a && a.host_id === b.host_id && a.worktree_id === b.worktree_id+ && a.owner_epoch === b.owner_epoch && a.source_incarnation === b.source_incarnation;++/** The consent payload of `--apply --expect <hash>` (registry `consentText`). */+export const MOVED_PAGES_CONSENT_TEXT = {+ what: 'Fold each previewed page whose file moved into the page the moved file imported as',+ why: 'Each old page was left behind when its file moved while its deletion was held; Git shows the moved file started from exactly what the old page still holds, so folding it loses no edit.',+ risk: `The old page's links in every role, relationship dates, timeline, raw data, files, user tags, aliases, facts and saved versions move to the moved page, its slug becomes an alias, its hold is cleared, and it is soft-deleted and purged ${MOVED_PAGES_PURGE_FUSE_HOURS} h later; gbrain restore brings back its text as a database-only page until then, and moved references stay on the moved page. No file is written.`,+ user_message: `Fold the previewed pages whose file moved into their moved pages? Each old page is soft-deleted and purged after ${MOVED_PAGES_PURGE_FUSE_HOURS} h`,+};++function hashParts(scope: RepairScope, slugs: string[] | undefined, owner: GhostOwner, pairs: MovedPair[], held: HeldPage[]) {+ return { kind: 'moved-pages-v1', brain_id: scope.brain_id, selection: { source_ids: scope.source_ids, slugs: slugs ?? null }, owner,+ pairs: pairs.map(({ observed_at: _observedAt, ...pair }) => pair), held: held.map(page => ({ slug: page.slug, reason: page.reason })) };+}++function item(pair: MovedPair, owner: GhostOwner, hash: string, last: boolean): PairItem {+ return { cursor: { phase: 1, id: pair.old.page_id }, source_id: pair.source_id, slug: pair.old.slug, chars: 0, action: 'fold:moved_page', pair, owner, hash, last };+}++const pairLine = (p: MovedPair) => `${p.old.slug} (id ${p.old.page_id}, revision ${p.old.revision}) folds into ${p.survivor.slug} (id ${p.survivor.page_id}): ${p.old.path} moved to ${p.survivor.path} `+ + `(${p.evidence === 'same_commit' ? `commit ${p.move_commit.slice(0, 12)}` : `first commit ${p.evidence_commit.slice(0, 12)} of ${p.survivor.path}`}, blob ${p.old_blob.slice(0, 12)})`;++export const movedPagesRepair: RepairHandler = {+ kind: 'moved-pages',+ embeds: false,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ if (opts?.remote === true) throw trustedCliRequired('gbrain repair moved-pages runs only from the trusted local CLI on the brain host.');+ if (scope.source_ids.length !== 1) {+ throw opError('invalid_params', 'gbrain repair moved-pages needs --source <id>.',+ 'Moved files are read from each source\'s own canonical checkout; name one source, e.g. gbrain repair moved-pages --source default.',+ { fix: readFix('Lists the registered sources.', { argv: ['gbrain', 'sources', 'list', '--json'] }), docs: DOCS });+ }+ const sourceId = scope.source_ids[0]!;+ const command = shellQuote(movedPagesPreviewArgv(sourceId));+ const slugs = opts?.slugs?.length ? [...new Set(opts.slugs)].sort() : undefined;+ const scan = await scanGhostSource(engine, sourceId);+ if (scan.status === 'not_applicable' && scan.reason === 'not_applicable') {+ const hash = previewHash({ kind: 'moved-pages-v1', brain_id: scope.brain_id, selection: { source_ids: scope.source_ids, slugs: slugs ?? null }, empty: true });+ return { items: [], preview_hash: opts?.expect ?? hash, residuals: { moved: 0 },+ warnings: [`Source ${sourceId} has no canonical checkout bound (a repo-less source), so no file of it can have moved; nothing to fold.`] };+ }+ const refusal = ghostScanRefusal(scan);+ if (refusal) throw refusal;+ const owner = scan.owner!, root = scan.root!;+ const ghosts = scan.ghosts.filter(ghost => !slugs || slugs.includes(ghost.slug)).slice(0, GHOST_REPAIR_LIMIT);+ const provenance = await readDeletionProvenance(root, ghosts.map(ghost => ghost.path));+ const observedAt = new Date().toISOString();+ const pairs: MovedPair[] = [], held: HeldPage[] = [];+ for (const ghost of ghosts) {+ const old: MovedPageRef = { page_id: ghost.page_id, slug: ghost.slug, revision: ghost.revision, path: ghost.path };+ const verdict = await readMovedPage(engine, { sourceId, root, old, provenance: provenance.get(ghost.path) ?? { kind: 'unknown' } });+ if (verdict.verdict === 'moved') pairs.push({ source_id: sourceId, old, survivor: verdict.survivor, old_blob: verdict.old_blob, move_commit: verdict.move_commit,+ evidence: verdict.evidence, evidence_commit: verdict.evidence_commit, observed_at: observedAt });+ else held.push({ source_id: sourceId, slug: ghost.slug, path: ghost.path, reason: verdict.reason, detail: verdict.detail, ...(verdict.candidates ? { candidates: verdict.candidates } : {}) });+ }+ const missing = slugs?.filter(slug => !ghosts.some(ghost => ghost.slug === slug)) ?? [];+ const mass = scan.file_backed > MASS_RECONCILE_MIN_PAGES && pairs.length > scan.file_backed * MASS_RECONCILE_RATIO;+ if (!opts?.apply) {+ const hash = previewHash(hashParts(scope, slugs, owner, pairs, held));+ if (pairs.length) await saveApprovedSet<ApprovedPair>(engine, { command: 'moved-pages', hash }, pairs.map(pair => ({ ...pair, owner, selection: scope.source_ids })));+ const warnings = [+ ...(missing.length ? [`Not a live page whose file is gone in source ${sourceId}, so nothing to fold: ${missing.join(', ')}.`] : []),+ ...(mass ? [`${pairs.length} fold(s) against ${scan.file_backed} file-backed page(s) (more than ${Math.round(MASS_RECONCILE_RATIO * 100)}%): the apply refuses unless GBRAIN_ALLOW_MASS_RECONCILE=1; check the source first.`] : []),+ ...(scan.ghosts.length > ghosts.length && !slugs ? [`More pages whose file is gone may exist past the first ${GHOST_REPAIR_LIMIT} listed; apply this set, then preview again.`] : []),+ ...(held.length ? [`${held.length} page(s) whose file is gone are not proven moved and are never folded by this apply; each lists why.`] : []),+ ...(pairs.length ? [MOVED_PAGES_CONSENT_TEXT.risk] : []),+ ...(!scan.ghosts.length ? [`Source ${sourceId} has no live page whose file is gone; nothing to fold.`] : []),+ ];+ return { warnings, items: pairs.map((pair, index) => item(pair, owner, hash, index === pairs.length - 1)), preview_hash: hash,+ residuals: { held: held.length, ...Object.fromEntries([...new Set(held.map(page => page.reason))].map(reason => [reason, held.filter(page => page.reason === reason).length])) },+ listing: [...pairs.map(pair => ({ item: `${pair.source_id}:${pair.old.slug}`, class: 'moved_to', detail: pairLine(pair) })),+ ...held.map(page => ({ item: `${page.source_id}:${page.slug}`, class: `held:${page.reason}`, detail: page.detail }))],+ details: { pairs, held, mass_fold: mass, purge_fuse_hours: MOVED_PAGES_PURGE_FUSE_HOURS, docs: DOCS } };+ }+ if (!opts.expect) {+ throw opError('invalid_params', 'gbrain repair moved-pages --apply folds only the set a preview printed.',+ `Preview first: ${command} — then, after the user agrees, run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`, { fix: previewFix(sourceId), docs: DOCS });+ }+ const approved = await loadApprovedSet<ApprovedPair>(engine, { command: 'moved-pages', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash(hashParts(scope, slugs, owner, [], held)) });+ if (approved.items.some(pair => JSON.stringify(pair.selection) !== JSON.stringify(scope.source_ids) || !sameOwner(owner, pair.owner))) throw previewChangedError(opts.expect, command);+ if (scan.file_backed > MASS_RECONCILE_MIN_PAGES && approved.items.length > scan.file_backed * MASS_RECONCILE_RATIO && !massReconcileAllowed()) {+ throw opError('moved_pages_mass_fold_refused', `Refusing to fold ${approved.items.length} moved page(s) of source ${sourceId}: that soft-deletes more than ${Math.round(MASS_RECONCILE_RATIO * 100)}% of its ${scan.file_backed} file-backed page(s).`,+ 'That many moved pages at once almost always means a re-import under other paths or the wrong checkout, not a backlog; nothing was changed. If it is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.',+ { fix: previewFix(sourceId), docs: DOCS });+ }+ const items = approved.items.map(({ selection: _selection, owner: pairOwner, ...pair }, index) => item(pair, pairOwner, opts.expect!, index === approved.items.length - 1));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { pair, owner, hash, last } = entry as PairItem;+ const outcome = await foldMovedPage(ctx, pair, owner,+ () => repairRequestId(ctx, 'moved-pages', { source_id: pair.source_id, slug: pair.old.slug }, `fold:${pair.survivor.revision}:${pair.old.revision}`));+ if (last) await clearApprovedSet(ctx.engine, { command: 'moved-pages', hash });+ return outcome;+ },+ render(details) {+ const held = (details.held as HeldPage[] | undefined) ?? [];+ return [...held.map(page => ` kept ${page.slug} (${page.reason}): ${page.detail}`),+ ` each folded page: soft-deleted, purged after ${details.purge_fuse_hours} h; guide: ${details.docs}`];+ },+};++const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });++/** Whether the pair is still the approved one and still proven moved; otherwise why not. */+export async function movedPairNow(engine: BrainEngine, pair: MovedPair, owner: GhostOwner | null): Promise<string | null> {+ const now = await ghostPageNow(engine, pair.source_id, pair.old.slug);+ if (!now.ghost) return `${pair.old.slug} is no longer a live page whose file is gone (${now.reason})`;+ if (owner && !sameOwner(now.owner, owner)) return 'the source\'s canonical owner changed since the preview';+ if (now.ghost.page_id !== pair.old.page_id || now.ghost.revision !== pair.old.revision || now.ghost.path !== pair.old.path) return `${pair.old.slug} has a new revision or recorded path`;+ const [survivor] = await engine.executeRaw<{ slug: string; revision: string; source_path: string | null }>(`SELECT slug, knowledge_revision::text AS revision, source_path FROM pages+ WHERE source_id=$1 AND id=$2 AND deleted_at IS NULL`, [pair.source_id, pair.survivor.page_id]);+ if (!survivor) return `${pair.survivor.slug} was deleted or purged`;+ if (survivor.slug !== pair.survivor.slug || String(survivor.revision) !== pair.survivor.revision || survivor.source_path !== pair.survivor.path) return `${pair.survivor.slug} has a new revision, slug or recorded path`;+ const context = await sourceContext(engine, pair.source_id);+ if (!context.ok) return 'the source\'s canonical checkout cannot be read';+ const verdict = await readMovedPage(engine, { sourceId: pair.source_id, root: context.root, old: pair.old });+ if (verdict.verdict !== 'moved') return `it is not proven moved any more (${verdict.reason}: ${verdict.detail})`;+ return verdict.survivor.page_id === pair.survivor.page_id && verdict.old_blob === pair.old_blob ? null : 'another page is now the moved one';+}++/** Under both page keys: why the locked pair is no longer the approved one, or null. */+async function pairLocked(tx: BrainEngine, pair: MovedPair): Promise<string | null> {+ const rows = await tx.executeRaw<{ id: number; slug: string; revision: string; source_path: string | null }>(`SELECT id, slug, knowledge_revision::text AS revision, source_path FROM pages+ WHERE source_id=$1 AND id=ANY($2::int[]) AND deleted_at IS NULL`, [pair.source_id, [pair.old.page_id, pair.survivor.page_id]]);+ for (const page of [pair.old, pair.survivor]) {+ const row = rows.find(candidate => Number(candidate.id) === page.page_id);+ if (!row || row.slug !== page.slug || String(row.revision) !== page.revision || row.source_path !== page.path) return `${page.slug} changed`;+ }+ return null;+}++/** The write itself, inside the caller's transaction with both page keys held. */+async function applyFold(tx: BrainEngine, pair: MovedPair, incarnation: string): Promise<Record<string, unknown>> {+ const merged = await mergeTwinInto(tx, { sourceId: pair.source_id, incarnation, survivor: { page_id: pair.survivor.page_id, slug: pair.survivor.slug },+ twin: { page_id: pair.old.page_id, slug: pair.old.slug } });+ const versions = await tx.executeRaw('UPDATE page_versions SET page_id=$2 WHERE page_id=$1 RETURNING id', [pair.old.page_id, pair.survivor.page_id]);+ const holdCleared = await clearGitHold(tx, { sourceId: pair.source_id, incarnation, path: pair.old.path, observedAt: pair.observed_at });+ const restore = ['gbrain', 'restore', pair.old.slug, '--source-id', pair.source_id];+ return { status: 'moved_page_folded', source_id: pair.source_id, old_slug: pair.old.slug, old_path: pair.old.path, survivor_slug: pair.survivor.slug, survivor_path: pair.survivor.path,+ move_commit: pair.move_commit, old_blob: pair.old_blob, evidence: pair.evidence, links_moved: merged.links_moved.length, link_ids: merged.links_moved, facts_moved: merged.facts_moved.length,+ transitions_moved: merged.transitions_moved, tags_moved: merged.tags_moved, versions_moved: versions.length, deduplicated: merged.deduplicated, hold_cleared: holdCleared, restore_argv: restore,+ restore_note: `${restore.join(' ')} brings back ${pair.old.slug}'s own text as a database-only page within ${MOVED_PAGES_PURGE_FUSE_HOURS} h; references and versions moved to ${pair.survivor.slug} stay there.` };+}++/** Folds one pair; a managed brain submits it under `requestId()`. Returns the receipt fields on success. */+export async function foldMovedPage(ctx: OperationContext, pair: MovedPair, owner: GhostOwner | null, requestId: () => Promise<string>): Promise<RepairItemOutcome> {+ const engine = ctx.engine;+ const moved = await movedPairNow(engine, pair, owner);+ if (moved) return changed(moved);+ if (await managedPersistenceEnabled(engine)) {+ const authority = (await maintenancePreflight(engine, pair.source_id))!;+ try {+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, pair.old.slug, { kind: MOVED_PAGES_INTENT, expected_revision: pair.old.revision, pair, owner }, await requestId());+ return { applied: true, outcome: 'folded', detail: receipt };+ } catch (error) {+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed', 'source_changed'].includes(error.code)) return changed(error.message);+ throw error;+ }+ }+ const result = await maintenanceTransaction(engine, async tx => {+ await tx.lockPageKeys([{ sourceId: pair.source_id, slug: pair.survivor.slug }, { sourceId: pair.source_id, slug: pair.old.slug }].sort((a, b) => a.slug.localeCompare(b.slug)));+ const reason = await pairLocked(tx, pair);+ if (reason) return { reason };+ const [source] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [pair.source_id]);+ return { receipt: await applyFold(tx, pair, source!.incarnation) };+ });+ return 'reason' in result ? changed(result.reason!) : { applied: true, outcome: 'folded', detail: result.receipt };+}++/**+ * Preparer for `managed_maintenance_fold_moved_page`, a request on the old page that also holds the moved page's key:+ * re-checks the proof and both pages, publishes no file (the old file is gone, the moved file stays as it is), and+ * re-checks both pages under the locks.+ */+export async function prepareMovedPageFold(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {+ const pair = row.intent!.pair as MovedPair | undefined;+ const owner = (row.intent!.owner as GhostOwner | null | undefined) ?? null;+ if (row.authority.remote || !pair || pair.old?.slug !== row.slug || pair.source_id !== row.source_id || pair.old.page_id !== Number(row.page_id) || !pair.survivor) {+ throw opError('invalid_params', 'The moved-page fold intent does not name its pages.',+ `Request ${row.request_id} for ${row.slug} in source ${row.source_id} does not name the pair it folds, so nothing changed. Preview the repair again.`, { fix: previewFix(row.source_id) });+ }+ const refuse = (reason: string) => opError('revision_conflict', 'The moved-page pair changed since it was read.',+ `Pages ${row.slug} and ${pair.survivor.slug} in source ${row.source_id} changed (${reason}), so request ${row.request_id} folded nothing. Preview the repair again.`, { fix: previewFix(row.source_id) });+ const moved = await movedPairNow(engine, pair, owner);+ if (moved) throw refuse(moved);+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);+ const core = await prepareCoreGuard(engine, { row, snapshot: await engine.readPageSnapshot(row.slug, { sourceId: row.source_id }), incoming: null });+ const prepared: PreparedMutation = { observedRevision: pair.old.revision, additionalPageKeys: [{ sourceId: row.source_id, slug: pair.survivor.slug }],+ ...(core ? { exclusiveSources: core.exclusiveSources } : {}),+ databaseOnlyReason: 'origin_twin',+ validate: async tx => {+ await authorizeWrite(tx, row.authority, 'submit_job', row.slug);+ const locked = await pairLocked(tx, pair);+ if (locked) throw refuse(locked);+ prepared.databaseOnlyWarning = `${row.slug} is folded into ${pair.survivor.slug} and hidden; ${pair.survivor.path} is untouched, and ${row.slug} resolves to ${pair.survivor.slug} as an alias.`;+ },+ apply: async tx => applyFold(tx, pair, row.source_incarnation) };+ return prepared;+}diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 78fce2ce41..ab342863de 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -80,6 +80,7 @@ import { stuckRecoveryRepair } from './stuck-recovery.ts';import { ghostPagesRepair, GHOST_CONSENT_TEXT, GHOST_CONSEQUENCES, GHOST_PURGE_FUSE_HOURS } from './ghost-pages.ts';import { legacyTwinsRepair, LEGACY_TWINS_CONSENT_TEXT, LEGACY_TWINS_PURGE_FUSE_HOURS } from './legacy-twins.ts';import { originTwinsRepair, ORIGIN_TWINS_CONSENT_TEXT, ORIGIN_TWINS_PURGE_FUSE_HOURS } from './origin-twins.ts';+import { movedPagesRepair, MOVED_PAGES_CONSENT_TEXT, MOVED_PAGES_PURGE_FUSE_HOURS } from './moved-pages.ts';import { receiptCompactionRepair } from './receipt-compaction.ts';import { aliasesRepair } from './aliases.ts';import { renameIdentityRepair, RENAME_IDENTITY_CONSENT_TEXT } from './rename-identity.ts';@@ -514,6 +515,17 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'the source\'s file-backed pages unless GBRAIN_ALLOW_MASS_RECONCILE=1. Once no source has a group, --apply builds the pages_live_origin_key index. '+ 'Preview-bound: --apply --expect <hash> --yes resolves exactly the previewed set. Runs only when named.',},+ 'moved-pages': {+ handler: movedPagesRepair, embeds: 'none', checks: ['ghost_pages'], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: MOVED_PAGES_CONSENT_TEXT,+ summary: 'Fold a page left behind by a file that moved into the page the moved file imported as (GST-2584): sync follows a move only when it happens, so when the old '+ + 'page\'s deletion was held (file_gone) the new path imports as a fresh page and the old one stays. Needs --source; refused off the canonical owner host. A page is '+ + 'folded only on proof read from Git: its old path\'s last committed content is the content a new path took in the commit that deleted it (or that path\'s first '+ + 'commit), exactly one live page descends from it, and the old page still holds it. Its links in every role, relationship dates, timeline, raw data, files, user '+ + `tags, aliases, facts and saved versions move to the moved page, its slug becomes an alias, its hold is cleared, and it is soft-deleted and purged after ${MOVED_PAGES_PURGE_FUSE_HOURS} h; `+ + 'no file is written. Any other page whose file is gone is listed with why it is kept (several candidates, a database edit after the move, a shallow history). '+ + 'Preview-bound: --apply --expect <hash> --yes folds exactly the previewed set. Runs only when named.',+ },'receipt-compaction': {handler: receiptCompactionRepair, embeds: 'none', checks: ['persistence_capacity'], explicit_only: true, preview_bound: true, consent: 'destructive',consentText: {diff --git a/test/moved-pages-gst2584.test.ts b/test/moved-pages-gst2584.test.tsnew file mode 100644index 0000000000..5c85eb706a--- /dev/null+++ b/test/moved-pages-gst2584.test.ts@@ -0,0 +1,265 @@+/**+ * GST-2584: a file that moved while its old page's deletion was held left a stale page at the old slug, and no repair+ * folded it into the moved page.+ * - `repair file-drift --held` lists such a page moved_to <slug> and prints the fold, never the recreate;+ * - `repair moved-pages` folds it on proof read from Git (the old path's last committed content is what the new path took+ * at the move, or its first commit, and the old page still holds it): alias, links in every role, timeline and saved+ * versions carried, the hold cleared, the old page soft-deleted and restorable, a receipt per page, no file written;+ * - kept, with the reason: two candidates, a near-equal body, a first commit that differs, a database edit after the+ * move, a frontmatter id alone, a shallow history;+ * - gbrain's own database-only artefacts are derived, not a page-side edit: a file naming the type gbrain-base 1.0.0 gave+ * its path, equal to the stored `type` copy, while the column took a later pack's type; and the grandfather stamp;+ * - the file_gone hold says when the page simply has no import record.+ * Real PGLite (and Postgres when DATABASE_URL is set), a managed worktree with real Git commits; no seams.+ */+import { expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { operationsByName } from '../src/core/operations.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { fileMatchesSnapshot } from '../src/core/persistence/page-prepare.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { testBackends } from './helpers/test-backends.ts';++const SYNC = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const logger = { info() {}, warn() {}, error() {} };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const ALPHA = '---\ntitle: Alpha\n---\n\nThe alpha body, kept word for word through the move.\n';+const BETA = '---\ntitle: Beta\n---\n\nBeta points at [[notes/alpha]].\n';+const setup = (files: Record<string, string>) => ({ root }: { root: string }) => {+ git(root, 'init', '-q'); git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]'); git(root, 'config', 'commit.gpgsign', 'false');+ for (const [path, content] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); }+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'first');+};+const opts = (backend: string, files: Record<string, string> = { 'notes/alpha.md': ALPHA, 'notes/beta.md': BETA }) =>+ ({ ...(backend === 'postgres' ? { databaseUrl: process.env.DATABASE_URL } : {}), setup: setup(files) });++const cli = async <T>(engine: BrainEngine, run: () => Promise<T>) => withVerifiedLocalRegistration(engine, await registerLocalWriter(engine, 'cli'), run);+const runner = async (engine: BrainEngine, kind: 'moved-pages' | 'file-drift', options: Record<string, unknown>) => cli(engine, async () =>+ (await repairRunner(engine, { apply: options.expect !== undefined, logger })).run(kind, await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', ...options }));+const raw = (engine: BrainEngine, sql: string, params: unknown[] = []) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));+const page = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ id: number; deleted: boolean; source_path: string | null; type: string }>(+ "SELECT id, deleted_at IS NOT NULL AS deleted, source_path, type FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0];+const holds = async (engine: BrainEngine) => (await engine.executeRaw<{ path: string; message: string; meta: Record<string, unknown> }>(+ "SELECT completed_keys->0->>'path' AS path, completed_keys->0->>'message' AS message, completed_keys->0->'meta' AS meta FROM op_checkpoints WHERE op='sync-hold' ORDER BY 1"));++/**+ * Syncs the first commit, then edits notes/alpha in the database only (sync's import record no longer matches it), runs+ * `move` in the checkout and syncs again: the move imports as a fresh page and the old page's deletion is held+ * file_gone, as sync does it. With `revert`, the database edit is then taken back, so the old page holds its file again.+ */+async function movedAway(engine: BrainEngine, root: string, move: () => void, revert = true): Promise<void> {+ await registerLocalWriter(engine, 'cli');+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');+ const [before] = await engine.executeRaw<{ timeline: string }>("SELECT timeline FROM pages WHERE source_id='default' AND slug='notes/alpha'");+ await raw(engine, "UPDATE pages SET timeline='An edit only the database holds.', knowledge_revision=gen_random_uuid() WHERE source_id='default' AND slug='notes/alpha'");+ move();+ await performManagedSync(engine, SYNC);+ expect((await holds(engine)).map(hold => hold.path)).toContain('notes/alpha.md');+ if (revert) await raw(engine, "UPDATE pages SET timeline=$1, knowledge_revision=gen_random_uuid() WHERE source_id='default' AND slug='notes/alpha'", [before!.timeline]);+}+const mv = (root: string, to: string) => () => { mkdirSync(join(root, to, '..'), { recursive: true }); git(root, 'mv', 'notes/alpha.md', to); git(root, 'commit', '-qm', 'move'); };++async function repairCli(engine: BrainEngine, args: string[]): Promise<{ out: string; exitCode: number | string | undefined }> {+ const lines: string[] = [];+ const { log, error } = console;+ const stdout = process.stdout.write.bind(process.stdout);+ const previous = process.exitCode;+ process.exitCode = 0;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ console.error = () => {};+ process.stdout.write = ((chunk: string | Uint8Array) => { lines.push(String(chunk)); return true; }) as typeof process.stdout.write;+ try { await runRepairCommand(engine, [...args, '--json']); return { out: lines.join('\n'), exitCode: process.exitCode }; }+ finally { console.log = log; console.error = error; process.stdout.write = stdout; process.exitCode = previous ?? 0; _resetCliExitVerdictForTests(); }+}++const listed = (plan: { listing?: Array<{ item: string; class: string; detail?: string }> }, slug: string) => plan.listing!.find(entry => entry.item === `default:${slug}`);++for (const backend of testBackends()) {+ test(`${backend}: a move whose old page's deletion was held folds into the moved page: preview, consent, links, versions, hold, alias, search and restore`, () => managedBrain(async ({ engine, ctx, root }) => {+ await movedAway(engine, root, mv(root, 'notes/archive/alpha.md'));+ const moveCommit = git(root, 'rev-parse', 'HEAD');+ const old = (await page(engine, 'notes/alpha'))!, moved = (await page(engine, 'notes/archive/alpha'))!;+ expect(moved.deleted).toBe(false);+ // A database-only link from another page, to the old page: a relationship only the database holds.+ await cli(engine, () => operationsByName.add_link!.handler(ctx, { from: 'notes/beta', to: 'notes/alpha', link_type: 'advises', request_id: randomUUID() }));+ const versionsBefore = Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_versions WHERE page_id=$1', [old.id]))[0]!.n);++ // file-drift lists it moved_to and prints the fold, not the recreate.+ const drift = await runner(engine, 'file-drift', { held: true, side: 'deleted', state: 'file_gone', prefer: 'database' });+ expect(drift.affected).toBe(0);+ expect(listed(drift, 'notes/alpha')).toMatchObject({ class: 'moved_to', detail: expect.stringContaining('gbrain repair moved-pages --source default --slug notes/alpha') });+ expect(String(listed(drift, 'notes/alpha')!.detail)).not.toContain('recreates');++ const preview = JSON.parse((await repairCli(engine, ['moved-pages', '--source', 'default'])).out).results[0];+ expect(preview.affected).toBe(1);+ expect(preview.listing).toContainEqual(expect.objectContaining({ item: 'default:notes/alpha', class: 'moved_to', detail: expect.stringContaining(`commit ${moveCommit.slice(0, 12)}`) }));+ expect(preview.details.pairs[0]).toMatchObject({ old: { slug: 'notes/alpha', path: 'notes/alpha.md' }, survivor: { slug: 'notes/archive/alpha', path: 'notes/archive/alpha.md' }, evidence: 'same_commit', move_commit: moveCommit });+ expect(preview.apply_command).toEndWith(' --yes');+ const apply = ['moved-pages', '--source', 'default', '--apply', '--expect', preview.preview_hash];+ expect((await repairCli(engine, apply)).exitCode).toBe(3);+ expect((await page(engine, 'notes/alpha'))!.deleted).toBe(false);+ const applied = JSON.parse((await repairCli(engine, [...apply, '--yes'])).out).results[0];+ expect(applied.outcomes).toEqual({ folded: 1 });++ expect(await page(engine, 'notes/alpha')).toMatchObject({ deleted: true, source_path: null });+ expect(existsSync(join(root, 'notes/alpha.md'))).toBe(false);+ expect(readFileSync(join(root, 'notes/archive/alpha.md'), 'utf8')).toBe(ALPHA);+ expect(git(root, 'status', '--porcelain', '--', 'notes/alpha.md', 'notes/archive')).toBe('');+ expect((await holds(engine)).map(hold => hold.path)).not.toContain('notes/alpha.md');+ const links = await engine.executeRaw<{ link_type: string; from: string }>(`SELECT l.link_type, f.slug AS from FROM links l JOIN pages f ON f.id=l.from_page_id+ WHERE l.to_page_id=$1 ORDER BY 1`, [moved.id]);+ expect(links).toContainEqual({ link_type: 'advises', from: 'notes/beta' });+ expect(await engine.executeRaw('SELECT 1 FROM links WHERE to_page_id=$1 OR from_page_id=$1', [old.id])).toEqual([]);+ const versionsAfter = Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_versions WHERE page_id=$1', [moved.id]))[0]!.n);+ expect(versionsAfter).toBeGreaterThan(versionsBefore);+ expect(await engine.executeRaw('SELECT 1 FROM page_versions WHERE page_id=$1', [old.id])).toEqual([]);+ expect(await engine.executeRaw("SELECT canonical_slug FROM slug_aliases WHERE source_id='default' AND alias_slug='notes/alpha'")).toEqual([{ canonical_slug: 'notes/archive/alpha' }]);++ // The old slug resolves to the moved page, and a search finds only the moved page.+ const got = await cli(engine, () => operationsByName.get_page!.handler(ctx, { slug: 'notes/alpha' })) as Record<string, unknown>;+ expect(got.slug).toBe('notes/archive/alpha');+ const hits = await cli(engine, () => operationsByName.search!.handler(ctx, { query: 'kept word for word' })) as Array<{ slug: string }>;+ expect(hits.map(hit => hit.slug)).toContain('notes/archive/alpha');+ expect(hits.map(hit => hit.slug)).not.toContain('notes/alpha');++ // A sync afterwards has nothing left to hold.+ await performManagedSync(engine, SYNC);+ expect(await holds(engine)).toEqual([]);++ // gbrain restore brings the old page back within the window, database-only; the alias stops answering for it.+ const [deleted] = await engine.executeRaw<{ revision: string }>("SELECT knowledge_revision::text AS revision FROM pages WHERE source_id='default' AND slug='notes/alpha'");+ await cli(engine, () => operationsByName.restore_page!.handler(ctx, { slug: 'notes/alpha', expected_revision: deleted!.revision, request_id: randomUUID() }));+ expect(await page(engine, 'notes/alpha')).toMatchObject({ deleted: false, source_path: null });+ const back = await cli(engine, () => operationsByName.get_page!.handler(ctx, { slug: 'notes/alpha' })) as Record<string, unknown>;+ expect(back.slug).toBe('notes/alpha');+ expect(existsSync(join(root, 'notes/alpha.md'))).toBe(false);+ }, opts(backend)), 240_000);++ test(`${backend}: an equal body moved to another top folder under another file name, and then edited there, still folds`, () => managedBrain(async ({ engine, root }) => {+ await movedAway(engine, root, () => { mkdirSync(join(root, 'archive'), { recursive: true }); git(root, 'mv', 'notes/alpha.md', 'archive/first-letter.md'); git(root, 'commit', '-qm', 'move');+ writeFileSync(join(root, 'archive/first-letter.md'), `${ALPHA}\nA later edit at the new path.\n`); git(root, 'commit', '-qam', 'edit after the move'); });+ const preview = await runner(engine, 'moved-pages', {});+ expect(listed(preview, 'notes/alpha')).toMatchObject({ class: 'moved_to' });+ expect(preview.details!.pairs).toEqual([expect.objectContaining({ survivor: expect.objectContaining({ slug: 'archive/first-letter' }), evidence: 'same_commit' })]);+ expect((await runner(engine, 'moved-pages', { expect: preview.preview_hash })).outcomes).toEqual({ folded: 1 });+ expect((await page(engine, 'notes/alpha'))!.deleted).toBe(true);+ expect(readFileSync(join(root, 'archive/first-letter.md'), 'utf8')).toContain('A later edit at the new path.');+ }, opts(backend)), 240_000);++ test(`${backend}: a copy committed separately and the old file deleted later folds on the copy's first commit`, () => managedBrain(async ({ engine, root }) => {+ await movedAway(engine, root, () => { mkdirSync(join(root, 'archive'), { recursive: true }); writeFileSync(join(root, 'archive/alpha.md'), ALPHA); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'copy');+ git(root, 'rm', '-q', 'notes/alpha.md'); git(root, 'commit', '-qm', 'delete the old one'); });+ const preview = await runner(engine, 'moved-pages', {});+ expect(preview.details!.pairs).toEqual([expect.objectContaining({ survivor: expect.objectContaining({ slug: 'archive/alpha' }), evidence: 'first_commit' })]);+ }, opts(backend)), 240_000);++ test(`${backend}: a page edited in the database after the move stays held as both changed`, () => managedBrain(async ({ engine, root }) => {+ await movedAway(engine, root, mv(root, 'archive/alpha.md'), false);+ const preview = await runner(engine, 'moved-pages', {});+ expect(preview.affected).toBe(0);+ expect(listed(preview, 'notes/alpha')).toMatchObject({ class: 'held:both_changed' });+ const drift = await runner(engine, 'file-drift', { held: true, side: 'deleted', state: 'file_gone', prefer: 'database' });+ expect(listed(drift, 'notes/alpha')!.class).not.toBe('moved_to');+ }, opts(backend)), 240_000);++ test(`${backend}: a near-equal body at the new path (its first commit differs) stays held, named by its file name`, () => managedBrain(async ({ engine, root }) => {+ await movedAway(engine, root, () => { mkdirSync(join(root, 'archive'), { recursive: true }); git(root, 'rm', '-q', 'notes/alpha.md');+ writeFileSync(join(root, 'archive/alpha.md'), ALPHA.replace('word for word', 'word for word,')); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'move and touch'); });+ const preview = await runner(engine, 'moved-pages', {});+ expect(preview.affected).toBe(0);+ expect(listed(preview, 'notes/alpha')).toMatchObject({ class: 'held:first_blob_differs', detail: expect.stringContaining('archive/alpha.md has the same file name') });+ expect((await page(engine, 'notes/alpha'))!.deleted).toBe(false);+ }, opts(backend)), 240_000);++ test(`${backend}: two pages started from the old file's content stay held (several candidates)`, () => managedBrain(async ({ engine, root }) => {+ await movedAway(engine, root, () => { for (const dir of ['archive', 'other']) { mkdirSync(join(root, dir), { recursive: true }); writeFileSync(join(root, dir, 'alpha.md'), ALPHA); }+ git(root, 'rm', '-q', 'notes/alpha.md'); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'split'); });+ const preview = await runner(engine, 'moved-pages', {});+ expect(preview.affected).toBe(0);+ expect(listed(preview, 'notes/alpha')).toMatchObject({ class: 'held:several_candidates' });+ expect(preview.details!.held).toEqual([expect.objectContaining({ candidates: ['archive/alpha', 'other/alpha'] })]);+ }, opts(backend)), 240_000);++ test(`${backend}: a frontmatter id shared with a page whose body differs never folds`, () => managedBrain(async ({ engine, root }) => {+ const WITH_ID = '---\ntitle: Alpha\nid: alpha-id\n---\n\nThe alpha body, kept word for word through the move.\n';+ await movedAway(engine, root, () => { mkdirSync(join(root, 'elsewhere'), { recursive: true }); git(root, 'rm', '-q', 'notes/alpha.md');+ writeFileSync(join(root, 'elsewhere/renamed.md'), WITH_ID.replace('kept word for word', 'rewritten')); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'rewrite elsewhere'); });+ const preview = await runner(engine, 'moved-pages', {});+ expect(preview.affected).toBe(0);+ expect(listed(preview, 'notes/alpha')).toMatchObject({ class: 'held:same_id_body_differs' });+ }, opts(backend, { 'notes/alpha.md': '---\ntitle: Alpha\nid: alpha-id\n---\n\nThe alpha body, kept word for word through the move.\n', 'notes/beta.md': BETA })), 240_000);++ test(`${backend}: a history too shallow to read the move keeps the page held and says so`, () => managedBrain(async ({ engine, root }) => {+ await movedAway(engine, root, mv(root, 'archive/alpha.md'));+ writeFileSync(join(root, '.git/shallow'), `${git(root, 'rev-parse', 'HEAD')}\n`);+ const preview = await runner(engine, 'moved-pages', {});+ expect(preview.affected).toBe(0);+ expect(listed(preview, 'notes/alpha')).toMatchObject({ class: 'held:history_shallow', detail: expect.stringContaining('git fetch --unshallow') });+ }, opts(backend)), 240_000);++ test(`${backend}: a source with no checkout (repo-less) lists nothing to fold`, () => managedBrain(async ({ engine }) => {+ const plan = await cli(engine, async () => (await repairRunner(engine, { apply: false, logger })).run('moved-pages', await resolveRepairScope(engine, 'dbonly'), { explicit: true, sourceFlag: 'dbonly' }));+ expect(plan.affected).toBe(0);+ expect(plan.warnings!.join(' ')).toContain('no canonical checkout');+ }, { ...opts(backend), setup: async (brain: { engine: BrainEngine; root: string }) => {+ setup({ 'notes/alpha.md': ALPHA })(brain);+ await brain.engine.executeRaw("INSERT INTO sources (id, name) VALUES ('dbonly', 'dbonly') ON CONFLICT DO NOTHING");+ } }), 240_000);++ test(`${backend}: a file_gone hold of a page with no import record says so instead of naming a database edit`, () => managedBrain(async ({ engine, root }) => {+ await registerLocalWriter(engine, 'cli');+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-import-provenance'");+ await raw(engine, "UPDATE pages SET timeline='An edit only the database holds.', knowledge_revision=gen_random_uuid() WHERE source_id='default' AND slug='notes/alpha'");+ git(root, 'rm', '-q', 'notes/alpha.md'); git(root, 'commit', '-qm', 'delete');+ await performManagedSync(engine, SYNC);+ const [hold] = (await holds(engine)).filter(entry => entry.path === 'notes/alpha.md');+ expect(hold!.message).toContain('has no import record');+ expect(hold!.message).not.toContain('changed in the database since the file was last imported');+ expect(hold!.meta).toMatchObject({ side: 'deleted', state: 'file_gone', no_import_record: true });+ }, opts(backend)), 240_000);++ test(`${backend}: a file naming the type gbrain-base 1.0.0 gave its path, equal to the stored copy, is not drift when the column took a later pack's type`, () => managedBrain(async ({ engine, root }) => {+ await registerLocalWriter(engine, 'cli');+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');+ expect((await page(engine, 'writing/essay'))!.type).toBe('writing');+ // What an older gbrain left: the reserved type copy in the stored frontmatter, and a column a later pack retyped.+ await raw(engine, `UPDATE pages SET type='media', frontmatter=frontmatter || '{"type":"writing","validate":false}'::jsonb, knowledge_revision=gen_random_uuid() WHERE source_id='default' AND slug='writing/essay'`);+ const snapshot = (await engine.readPageSnapshot('writing/essay', { sourceId: 'default' }))!;+ const file = readFileSync(join(root, 'writing/essay.md'), 'utf8');+ expect(await fileMatchesSnapshot(engine, 'writing/essay', file, snapshot, 'writing/essay.md')).toBe(true);+ // A person's explicit type is still read as written, and so is the old name under a path gbrain-base 1.0.0 types otherwise.+ expect(await fileMatchesSnapshot(engine, 'writing/essay', file.replace('type: writing', 'type: guide'), snapshot, 'writing/essay.md')).toBe(false);+ expect(await fileMatchesSnapshot(engine, 'notes/essay', file, { ...snapshot, page: { ...snapshot.page, slug: 'notes/essay' } }, 'notes/essay.md')).toBe(false);+ // The import keeps the retyped column instead of reading the old name back into it.+ writeFileSync(join(root, 'writing/essay.md'), `${file}\nA later line.\n`); git(root, 'commit', '-qam', 'edit');+ await performManagedSync(engine, SYNC);+ expect((await engine.readPageSnapshot('writing/essay', { sourceId: 'default' }))?.page.compiled_truth).toContain('A later line.');+ expect((await page(engine, 'writing/essay'))!.type).toBe('media');++ }, opts(backend, { 'writing/essay.md': '---\ntype: writing\ntitle: Essay\n---\n\nAn essay gbrain wrote out.\n', 'notes/beta.md': BETA })), 240_000);++ test(`${backend}: a moved page carrying the type rename and the grandfather stamp folds`, () => managedBrain(async ({ engine, root }) => {+ await registerLocalWriter(engine, 'cli');+ expect((await performManagedSync(engine, SYNC)).status).toBe('first_sync');+ await raw(engine, `UPDATE pages SET type='media', frontmatter=frontmatter || '{"type":"writing","validate":false}'::jsonb, knowledge_revision=gen_random_uuid() WHERE source_id='default' AND slug='writing/essay'`);+ mkdirSync(join(root, 'archive'), { recursive: true }); git(root, 'mv', 'writing/essay.md', 'archive/essay.md'); git(root, 'commit', '-qm', 'move');+ await performManagedSync(engine, SYNC);+ expect((await holds(engine)).map(hold => hold.path)).toContain('writing/essay.md');+ const preview = await runner(engine, 'moved-pages', {});+ expect(listed(preview, 'writing/essay')).toMatchObject({ class: 'moved_to' });+ expect((await runner(engine, 'moved-pages', { expect: preview.preview_hash })).outcomes).toEqual({ folded: 1 });+ }, opts(backend, { 'writing/essay.md': '---\ntype: writing\ntitle: Essay\n---\n\nAn essay gbrain wrote out.\n', 'notes/beta.md': BETA })), 240_000);+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 5ca64ca05e..b5251de15d 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -341,6 +341,7 @@ test/migration-persistence-foreground-committed-index.test.tstest/migration-persistence-request-id-index.test.tstest/migration-persistence-request-slug-index.test.tstest/mirror-readonly-write-through-7098.test.ts+test/moved-pages-gst2584.test.tstest/notifier-passed-freshness-marker-7941.test.tstest/notifier-retry-unwatched-gst2515.test.tstest/on-commit-embedding.serial.test.tsdiff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 214b9a1ba5..f79f716544 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'private-labels'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'moved-pages', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'facts-home', 'private-labels'];// GBRA-161: the generations preview carries its ledger kind and the restore window, so the printed command runs as is.const PREVIEW = (kind: RepairKind): string => kind === 'generations' ? 'gbrain repair generations --kind atom --since 30d' : `gbrain repair ${kind}`;let engine: PGLiteEngine;