Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(purge): remove a purged page's aliases; add repair aliases for leftovers (#6619)

time-attack6a5043679dbf
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index a0270e6d38..02d7294950 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -13,6 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id, and `file_database_drift` (W4.11) when its last replay attempt was refused `source_changed` and the page has not been written since (`lastFailedAttempt`; the detail and an apply's `file_database_drift` outcome name `gbrain sources reconcile <source> <slug> --preview`; `test/repair-failed-writes-drift-w411.test.ts`); owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969). The superseded / already-written / duplicate rule lives in `persistence/terminal-classify.ts`, shared with the #6650 terminal-failure readers.
- `src/core/repair/ontology-facts.ts` — `gbrain repair ontology-facts` (#6264), explicit-only and preview-bound (`--apply --expect <hash>`). `classifyOntologyFacts` (read-only; also doctor `ontology_facts_fenced`) takes ontology rows (`dimension IS NOT NULL`) carrying the pre-fix fence step's signature, a `row_num` or a `source_markdown_slug` that differs from `source` (`mergeOntologyFact` writes them equal and never sets `row_num`), and classes each `fenced` or `retired`, or excluded as `withdrawn` (`fact_withdrawals`), `consolidated` or `duplicate` (restoring would collide with the ontology dedup key). The apply sets `row_num` NULL, `source_markdown_slug = source` and `expired_at` NULL in one statement that rechecks row number, page, expiry and the dedup key (`changed_since_preview` otherwise), through `coordinatedDatabaseWrite('ontology_propose')` on the entity and page keys on a managed brain or one maintenance transaction otherwise; the withdrawal trigger re-expires a claim forgotten after the preview (`withdrawn`). Page text is never rewritten. Tests: `test/ontology-fence-sweep.test.ts`.
- `src/core/repair/timeline-comments.ts` — `gbrain repair timeline-comments` (#6184), explicit-only. The plan lists pages with timeline rows whose source, summary or detail carries `<!--`/`-->` or whose body has a materialized bullet carrying markup (`dropCommentBullets`), with residuals `comment_only_rows`, `comment_bearing_rows`, `pages_with_comment_bullets`. Apply: one revision-bound `put_page` per page dropping those generated bullets (user-written bullets are left), then one transaction under the page lock (`withCoordinatedWrite` with maintenance attribution on managed brains) that deletes comment-only rows and rewrites the rest to their stripped tuple, or deletes them when the page already has it. Idempotent. `timeline.ts` warns `timeline_comment_markup` naming this kind while such rows exist.
+- `src/core/repair/aliases.ts` — `gbrain repair aliases` (#6619), explicit-only, projection publication, wired to doctor `dangling_aliases`. One item per (source, target slug) whose alias rows (`page_aliases.slug`, `slug_aliases.canonical_slug`) point at a slug with no page row at all; apply rechecks that under the page key lock and deletes both tables' rows for it, inside `withCoordinatedWrite` on a managed brain (both tables carry the managed writer guard). Aliases of soft-deleted pages are the `soft_deleted_target` residual; rename redirects (`alias_slug` = the missing slug) are never touched. Exports `ORPHANED_ALIAS_COUNTS_SQL` / `SOFT_DELETED_ALIAS_COUNT_SQL`, which `checkDanglingAliases` (`src/core/onboard/checks.ts`) reports apart, naming `repairPreviewCommand('aliases', {source})` per source instead of raw SQL. Test: `test/purge-aliases-6619.test.ts`.
- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` (a correlated, table-qualified `NOT EXISTS`, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; `test/e2e/repair-orphan-children-plan-postgres.test.ts`) are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).
- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a host that may not write the source is skipped with the owner condition as its reason (`host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`; `owner_unavailable` is the fallback; the skip's detail carries `why`, the read-only fix and `retryable`), a candidate a write in flight or an unfinished sync's frozen manifest still names is `sync_in_progress` (#6278: checked at plan, at apply and again at the write's admission in `file-repair.ts`; the rest of the source repairs while the sync runs, and a held path is not busy); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.
- `src/core/repair/content-lane.ts` — the content-repair lane (#6377). `CONTENT_REPAIR_KINDS` is the ordered list of repair kinds that clear managed-sync content holds (today `fences`; the GBRA-72 integration appends `slug-conflicts`), read by `gbrain repair content` (`src/commands/repair-content.ts`), the `content_repair` cycle phase and `gbrain sync unblock --apply`, so a new kind plugs in with one entry. `CONTENT_REPAIR_HOLD_KINDS` maps a hold code to the kind that clears it (`invalid_fence` → `fences`; `frontmatter_slug_conflict` → `null` until Lane B's kind lands, which keeps the surfaces' refusal text). `runContentLane(engine, scope, { apply, kinds?, only, skip, expect?, noLlm, maxLlmUsd, deadline, registry? })` has no rule logic: it runs each kind through `repairRunner` in order, passing the run's paid allowance minus what earlier kinds spent (read from each result's `cost.llm_usd`; the daily ledger is `FENCE_REPAIR_LEDGER` for every kind) and one absolute deadline (a `time_budget` stop ends the pass; any other stop lets the next kind run), and returns per-kind results, each kind's own `preview_hash` (no combined hash: `--expect` is one hash per kind in lane order, `parseContentLaneExpect` refuses a wrong count with `invalid_params` before any kind runs), the lane's spend and remaining allowance, and `apply_command` (`contentLaneArgv`). A preview plans every kind before any mutation; `--apply --expect` binds each kind to its approved set; a bare apply runs each kind's own plan-and-apply (`changed_since_read` binding, held reasons recorded on the holds). `contentHoldDisposition(record, auto)` reads a hold's stored repair state (`fenceHoldStatus` for a fence hold; `meta.content_repair.action` for a slug-conflict hold, read loosely) and says whether an unattended surface may run the kind (`repair`), must list it (`listed`: `needs_human` for a manual reason or a recommended merge, `paid`, `owner`) or has no kind for it (`unsupported`). Output is counts, codes, hashes and paths only. Tests: `test/cycle-content-repair.test.ts` (stub kinds), `test/repair-content.test.ts` (the real `fences` kind through the CLI).
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index a7faedc090..b61eee4500 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -13,7 +13,7 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.
- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included; the fact purge's planning read) / `findRequestsForSlugs` (index-served by `persistence_requests_slug_intent`), the page purge's preparation-time journal census `sweepRequestsCarrying` (#6511: a keyset walk of the source's journal in `JOURNAL_SWEEP_CHUNK_ROWS` chunks, every needle in raw and JSON-escaped form against intent, outcome, error detail and message, compacted rows included, the purge's own row excluded, stopped by the claim clock between chunks and at `JOURNAL_SWEEP_MATCH_CAP`; returns the carrying ids, the ids pending at the scan, the `sequence` ceiling as text and `complete`) with `recheckRequestsCarrying` for the publication's bounded re-check of the tail past the ceiling and of the rows that were pending, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome.
- `src/core/persistence/purged-intent.ts` — `intentCarriesPurgedContent`: `completeWrite` (journal.ts) nulls the intent of any terminal request whose content (`fact`, `claim`, page fence rows, or the page's content hash) matches a subject-scoped purge tombstone, and of any refusal coded `purged_content`; a write refused for another reason, or committed as a no-op after the overlay dropped purged rows, keeps no copy. Only content-bearing intents are checked, and whether the source holds any tombstone is selected by completeWrite's terminal statement itself (`PURGE_PRESENCE_COLUMNS`), so the hook adds no statement to a write on a source without tombstones (#6007 budget). `purged_content` is a write error code, so receipts and the frozen verb path (wire `invalid_params`, canonical `purged_content`) keep it typed.
-- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, redacts finished intents for the slug and the carrying ids the preparation sweep found plus the publication's tail and pending re-check (#6511: `preparePagePurge` runs `readPurgeClaims` and `sweepRequestsCarrying` under the preparation budget at steps `purge_claims` / `purge_journal_sweep`, so the O(journal) substring scan is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go through `lookup`, which maps a 57014 to the terminal, non-retryable `purge_lookup_timeout` naming `gbrain repair request-indexes` only when `persistence_requests_slug_intent` is missing or INVALID; the receipt's `journal_sweep` reports `ceiling`, `scanned`, `tail`, `pending_rechecked` and `complete`), then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts` and `test/page-purge-journal-timeout-6511.test.ts` (both engines; seams `purge:*` in `fault-points.ts`). #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged.
+- `src/core/persistence/page-purge.ts` — `purgePageInTransaction`, called by the `delete_page purge:true` apply in `page-prepare.ts`: records in `page_purges` the content hash of the page and of every retained version (up to 1000), each as imported and as purge-overlaid, so an older version is refused too; drops the decide rows, trust proposals, gate holds (by slug) and gate receipts naming the page or its rows and clears legacy `query_cache`; tombstones and deletes facts filed on the page, tombstones its takes, deletes take proposals, open loops, core notices and `files` rows, the page's `page_aliases` and the `slug_aliases` redirects whose `canonical_slug` is the page (#6619; a redirect from this slug to another page stays; counted in `removed` and checked by slug in the receipt), redacts finished intents for the slug and the carrying ids the preparation sweep found plus the publication's tail and pending re-check (#6511: `preparePagePurge` runs `readPurgeClaims` and `sweepRequestsCarrying` under the preparation budget at steps `purge_claims` / `purge_journal_sweep`, so the O(journal) substring scan is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout; the lookups that stay inside the transaction go through `lookup`, which maps a 57014 to the terminal, non-retryable `purge_lookup_timeout` naming `gbrain repair request-indexes` only when `persistence_requests_slug_intent` is missing or INVALID; the receipt's `journal_sweep` reports `ceiling`, `scanned`, `tail`, `pending_rechecked` and `complete`), then deletes the page (FK cascades). `PURGE_RESIDUALS` names what stays out of reach. `finishPagePurge` deletes stored blobs after commit, lists any left by storage path, and attaches `receipt`, the store-by-store receipt from `verifyPagePurge` (same shape as the fact receipt: residuals first, every swept inventory store, other pages' prose naming a purged claim as `source_prose`); the page's claims used as needles live only in process memory, and a same-id replay returns the result built when the purge ran. `residuals` stays the prose string. `readPagePurgeTombstones` feeds `screenImportContent({ purgedPages })` from managed sync's freeze-time screen (`sync-screen.ts`, one read per run) and publication (`sync-prepare.ts`), which hold a matching file as `purged_content`; direct imports and `put_page` hit the pages guard instead; `listPagePurges` / `unpurgePage` (also clears the fact and take tombstones of the same request) back the owner-only ops. Pinned by `test/page-purge.test.ts` and `test/page-purge-journal-timeout-6511.test.ts` (both engines; seams `purge:*` in `fault-points.ts`). #6368: a purge of a tombstone whose file matches `sync.exclude` (discovery's globs via `syncExcludePatterns` in `sync-discovery.ts`, matched relative to the source root) owns no file: `prepareFileTarget`'s `excludeTombstone` option returns no target, the purge is database-only and the receipt says `write_through.skipped: 'sync_excluded'`; the file is neither compared nor removed (an unchanged excluded file used to be deleted, an edited one refused forever). The apply re-reads the exclusion inside the publication transaction and refuses `source_changed` if it was removed meanwhile. Live-page purges and soft deletes are unchanged.
- `src/core/ops/purge.ts` — `purge_fact`, `list_page_purges`, `unpurge_page`: admin scope, `cliOnly` (every MCP route gets `trusted_local_only`). The resident owner runs them only for its verified local CLI registration (`LOCAL_CLI_OWNER_OPERATIONS` in `persistence/ipc.ts`, checked in `persistence/provider.ts`).
- `src/commands/forget-purge.ts` + `src/commands/pages-purges.ts` — the CLI fronts. `runForgetPurge` always runs the dry run, then a typed token on a terminal or `--yes` plus `--request-id` without one; `--match` lists ids, `--status` polls completion; `PURGE_FAMILY_HELP` is the purge-family table shown by `gbrain forget --help`. `gbrain pages purges list` and `gbrain pages unpurge <slug>` run the page-tombstone ops as the trusted CLI.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 679655b5ad..de0c7373a4 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -145,6 +145,7 @@ work behind exits 0, so scripts should also check `results[].complete`.
| `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. 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`). |
| `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. |
+| `aliases` | `dangling_aliases` (orphaned rows) | Explicit-only. Deletes free-text page aliases and slug redirects whose target page has no row at all (a page purged before purge removed its aliases, #6619, or a hard-deleted page), each target rechecked under its page lock; a coordinated maintenance write on a managed brain. A redirect from an old name of a page that still exists is never touched. See [aliases](#aliases). | `soft_deleted_target`: aliases of a soft-deleted page, kept for `gbrain restore` and removed when the page is purged. |
Timeline rows that an earlier version of a page produced and its current text
no longer has are removals, not history, so `timeline` neither counts nor
@@ -586,6 +587,32 @@ A page whose keys a write cleared between preview and apply is counted
`already_clean`. Nested user keys with the same names (`metadata.title`) are
never touched; only the four top-level keys are.
+### Aliases
+
+<a id="aliases"></a>
+Doctor `dangling_aliases` counts alias rows whose target page is gone. Two
+kinds are reported apart:
+
+- **Orphaned:** the target slug has no page row at all, usually a page purged
+ before purge removed its aliases (#6619). A free-text alias can still resolve
+ a name to that missing page. Preview per source, then apply:
+
+ ```bash
+ gbrain repair aliases --source <id>
+ gbrain repair aliases --source <id> --apply
+ ```
+
+ The apply deletes `page_aliases` rows whose `slug` is the missing page and
+ `slug_aliases` rows whose `canonical_slug` is the missing page. A redirect
+ whose old name happens to be the missing slug but points at a live page (a
+ rename) is kept.
+- **Soft-deleted target:** the page is in its restore window. Its aliases are
+ kept so `gbrain restore` brings them back; purging the page removes them.
+ Nothing needs running.
+
+Both alias tables carry the managed writer guard, so deleting rows with raw SQL
+fails on a managed brain; use the repair.
+
### Orphan children
**Say to your agent:** *"gbrain fails with `unexpected chunk number` or
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index f1752febf0..9c6a47f5a0 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -103,7 +103,7 @@ const ROWS: readonly Row[] = [
['op_checkpoint_paths', 'out_of_scope', 'no_memory_text', 'op fingerprint path'],
['op_checkpoints', 'out_of_scope', 'no_memory_text', 'op fingerprint completed_keys'],
['open_loops', 'swept', 'open_loops', 'source_id dedup_key loop_type counterparty_slug counterparty_source_id counterparty_email summary evidence thread_id page_slug status detector closed_by'],
- ['page_aliases', 'out_of_scope', 'probed_reported', 'source_id alias_norm slug origin alias_text', 'alias_text'],
+ ['page_aliases', 'swept', 'page_aliases', 'source_id alias_norm slug origin alias_text'],
['page_embedding_budget', 'out_of_scope', 'no_memory_text', 'state reason embedding_signature'],
['page_extraction_state', 'out_of_scope', 'no_memory_text', 'pipeline watermark_sha256 input_truncated'],
['page_facts_reconcile', 'out_of_scope', 'no_memory_text', 'outcome'],
diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.ts
index 772bd0628b..6c5d2412ee 100644
--- a/src/core/facts/purge-verify.ts
+++ b/src/core/facts/purge-verify.ts
@@ -317,6 +317,8 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: st
await keyed('facts', 'SELECT 1 FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [src, slug]);
for (const table of ['take_proposals', 'open_loops']) await keyed(table, `SELECT 1 FROM ${table} WHERE source_id=$1 AND page_slug=$2`, [src, slug]);
await keyed('core_edit_notices', 'SELECT 1 FROM core_edit_notices WHERE source_id=$1 AND slug=$2', [src, slug]);
+ await keyed('page_aliases', 'SELECT 1 FROM page_aliases WHERE source_id=$1 AND slug=$2', [src, slug]);
+ await keyed('slug_aliases', 'SELECT 1 FROM slug_aliases WHERE source_id=$1 AND canonical_slug=$2', [src, slug]);
await keyed('files', 'SELECT 1 FROM files WHERE page_slug=$2 AND (source_id=$1 OR source_id IS NULL)', [src, slug]);
await keyed('write_gate_holds', 'SELECT 1 FROM write_gate_holds WHERE source_id=$1 AND slug=$2', [src, slug]);
await keyed('query_cache', 'SELECT 1 FROM query_cache WHERE $1::text IS NOT NULL', [src]);
diff --git a/src/core/onboard/checks.ts b/src/core/onboard/checks.ts
index 280c4e1f20..12c6afc6b0 100644
--- a/src/core/onboard/checks.ts
+++ b/src/core/onboard/checks.ts
@@ -26,6 +26,8 @@ import { embeddingEnablement, type ReadinessState } from '../readiness.ts';
import { embeddingsDisabled } from '../embedding-disabled.ts';
import { loadConfig } from '../config.ts';
import { MIN_ENTITY_PAGES_FOR_COVERAGE } from '../types.ts';
+import { ORPHANED_ALIAS_COUNTS_SQL, SOFT_DELETED_ALIAS_COUNT_SQL } from '../repair/aliases.ts';
+import { repairPreviewCommand } from '../repair/registry.ts';
/** Shared shape returned by all four checks. */
export interface OnboardCheckResult {
@@ -695,59 +697,57 @@ export async function checkTypeProliferation(
/**
* dangling_aliases (F12): surfaces both slug_aliases redirects and
- * page_aliases free-text names whose target page no longer exists.
- * Source-scoped JOINs prevent cross-source false-positive deletion.
+ * page_aliases free-text names whose target page is gone or soft-deleted.
+ * Source-scoped JOINs prevent cross-source false positives.
*
- * v0.42 ships surface-only (no auto-GC RemediationStep). v0.43+ may add
- * `cleanup-dangling-aliases` as an auto_apply handler once detection is
- * confirmed clean in production.
+ * #6619: the two cases are reported apart. Aliases whose target has no page
+ * row (purged or hard-deleted) are cleared by `gbrain repair aliases`, named
+ * per source; aliases of a soft-deleted page are kept for `gbrain restore`
+ * and removed when that page is purged, so nothing is offered for them. The
+ * alias tables carry the managed writer guard, so raw SQL is never offered.
*
- * Defensive: pre-v105 brains don't have slug_aliases yet — returns ok
- * via the `isUndefinedTableError` fallthrough inherent in safeCount's
- * catch-all (returns 0 on any SQL error).
+ * Defensive: pre-v105 brains don't have slug_aliases yet; a failed read
+ * counts nothing (ok).
*/
export async function checkDanglingAliases(
engine: BrainEngine,
): Promise<OnboardCheckResult> {
- const slugAliases = await safeCount(
- engine,
- `SELECT COUNT(*) AS count FROM slug_aliases sa
- LEFT JOIN pages p
- ON p.slug = sa.canonical_slug
- AND p.source_id = sa.source_id
- AND p.deleted_at IS NULL
- WHERE p.id IS NULL`,
- );
- const pageAliases = await safeCount(
- engine,
- `SELECT COUNT(*) AS count FROM page_aliases pa
- LEFT JOIN pages p
- ON p.slug = pa.slug
- AND p.source_id = pa.source_id
- AND p.deleted_at IS NULL
- WHERE p.id IS NULL`,
- );
+ let orphaned: Array<{ source_id: string; slug_redirects: number; page_aliases: number }> = [];
+ let soft = { slug_redirects: 0, page_aliases: 0 };
+ try {
+ orphaned = await engine.executeRaw(ORPHANED_ALIAS_COUNTS_SQL);
+ const [row] = await engine.executeRaw<typeof soft>(SOFT_DELETED_ALIAS_COUNT_SQL);
+ if (row) soft = row;
+ } catch { /* pre-v105 brain or unreadable alias tables: nothing to report */ }
+ const slugAliases = orphaned.reduce((sum, row) => sum + Number(row.slug_redirects), 0) + Number(soft.slug_redirects);
+ const pageAliases = orphaned.reduce((sum, row) => sum + Number(row.page_aliases), 0) + Number(soft.page_aliases);
const n = slugAliases + pageAliases;
- if (n > 0) {
+ if (n === 0) {
return {
- check: {
- name: 'dangling_aliases',
- status: 'warn',
- message:
- `${n} alias rows point at missing/deleted pages ` +
- `(${slugAliases} slug redirects; ${pageAliases} free-text page aliases). ` +
- `Safe GC (source-scoped): ` +
- `\`DELETE FROM slug_aliases sa WHERE NOT EXISTS (SELECT 1 FROM pages p ` +
- `WHERE p.slug = sa.canonical_slug AND p.source_id = sa.source_id ` +
- `AND p.deleted_at IS NULL); DELETE FROM page_aliases pa WHERE NOT EXISTS ` +
- `(SELECT 1 FROM pages p WHERE p.slug = pa.slug ` +
- `AND p.source_id = pa.source_id AND p.deleted_at IS NULL);\``,
- },
- remediations: [], // v0.42: surface-only; auto-GC v0.43+
+ check: { name: 'dangling_aliases', status: 'ok', message: 'No dangling aliases' },
+ remediations: [],
};
}
+ const commands = orphaned.map(row => repairPreviewCommand('aliases', { source: row.source_id }));
+ const softTotal = Number(soft.slug_redirects) + Number(soft.page_aliases);
+ const orphanedText = orphaned.length
+ ? `${n - softTotal} point at pages that no longer exist (${orphaned.map(row => `${row.source_id}: ${Number(row.slug_redirects) + Number(row.page_aliases)}`).join(', ')}); `
+ + `preview their cleanup with ${commands.join('; ')}, then run the --apply command it prints. `
+ : '';
+ const softText = softTotal
+ ? `${softTotal} belong to soft-deleted pages and are kept for gbrain restore; purging the page removes them, so nothing needs running for those.`
+ : '';
return {
- check: { name: 'dangling_aliases', status: 'ok', message: 'No dangling aliases' },
+ check: {
+ name: 'dangling_aliases',
+ status: 'warn',
+ message:
+ `${n} alias rows point at missing/deleted pages ` +
+ `(${slugAliases} slug redirects; ${pageAliases} free-text page aliases). ${orphanedText}${softText}`.trimEnd(),
+ details: { orphaned, soft_deleted: soft },
+ ...(orphaned.length ? { fix: { argv: commands[0]!.split(' '), consent: [], actor: 'agent' as const, requires_exclusive: false,
+ why: 'Lists the orphaned alias rows of that source without changing anything; its output prints the apply command.' } } : {}),
+ },
remediations: [],
};
}
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index f4d4722db8..5ba3f2a286 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -161,6 +161,9 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,
removed.take_proposals = await count('DELETE FROM take_proposals WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);
removed.open_loops = await count('DELETE FROM open_loops WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);
removed.core_edit_notices = await count('DELETE FROM core_edit_notices WHERE source_id=$1 AND slug=$2 RETURNING 1', [sourceId, slug]);
+ // #6619: the page's free-text aliases and the redirects that resolve to it; a redirect from this slug to another page stays.
+ removed.page_aliases = await count('DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2 RETURNING 1', [sourceId, slug]);
+ removed.slug_aliases = await count('DELETE FROM slug_aliases WHERE source_id=$1 AND canonical_slug=$2 RETURNING 1', [sourceId, slug]);
// #6511 [R2]: the preparation sweep's targets, plus the tail past its ceiling and the rows pending at scan time, re-tested here.
const lookup = <T>(point: PurgeLookupPoint, fn: () => Promise<T>) => journalLookup(row, point, prepared.slugIndex, fn);
const recheck = await lookup('tail_recheck', () => recheckRequestsCarrying(tx, sourceId, needles, prepared.sweep,
diff --git a/src/core/repair/aliases.ts b/src/core/repair/aliases.ts
new file mode 100644
index 0000000000..7e48771085
--- /dev/null
+++ b/src/core/repair/aliases.ts
@@ -0,0 +1,69 @@
+/**
+ * `gbrain repair aliases` (#6619): delete alias rows whose target page has no
+ * row at all (purged or hard-deleted), the ones doctor `dangling_aliases`
+ * reports as orphaned. A free-text alias (`page_aliases.slug`) or a slug
+ * redirect (`slug_aliases.canonical_slug`) pointing at such a slug can still
+ * resolve a name to a page that no longer exists. Rows whose target is
+ * soft-deleted are left alone: `gbrain restore` inside the 72-hour window
+ * still needs them, and a purge removes them with the page. A redirect whose
+ * alias_slug is the missing slug (an old name of a page that still exists)
+ * is a rename redirect and is never touched.
+ *
+ * One item per (source, target slug). Applying it rechecks, under the page key
+ * lock, that the slug still has no page row, then deletes both alias tables'
+ * rows for it; on a managed brain the delete runs as a coordinated
+ * maintenance write (the alias tables carry the managed writer guard).
+ * Explicit-only, bookkeeping only, no journal admission.
+ */
+import { maintenanceAttribution } from '../persistence/attribution.ts';
+import { withCoordinatedWrite } from '../persistence/context.ts';
+import { readManagedMode } from '../persistence/managed-mode.ts';
+import { afterCursor, type RepairHandler, type RepairItem } from './core.ts';
+
+const MISSING = (alias: string, column: string) => `NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id=${alias}.source_id AND p.slug=${alias}.${column})`;
+const SOFT_DELETED = (alias: string, column: string) =>
+ `EXISTS (SELECT 1 FROM pages p WHERE p.source_id=${alias}.source_id AND p.slug=${alias}.${column} AND p.deleted_at IS NOT NULL)`;
+
+/** Alias rows (both tables) whose target page row is absent, per source; and those whose target is soft-deleted. */
+export const ORPHANED_ALIAS_COUNTS_SQL = `SELECT source_id,sum(slug_redirects)::int AS slug_redirects,sum(page_aliases)::int AS page_aliases FROM (
+ SELECT sa.source_id,1 AS slug_redirects,0 AS page_aliases FROM slug_aliases sa WHERE ${MISSING('sa', 'canonical_slug')}
+ UNION ALL SELECT pa.source_id,0,1 FROM page_aliases pa WHERE ${MISSING('pa', 'slug')}) o GROUP BY source_id ORDER BY source_id`;
+export const SOFT_DELETED_ALIAS_COUNT_SQL = `SELECT
+ (SELECT count(*)::int FROM slug_aliases sa WHERE ${SOFT_DELETED('sa', 'canonical_slug')}) AS slug_redirects,
+ (SELECT count(*)::int FROM page_aliases pa WHERE ${SOFT_DELETED('pa', 'slug')}) AS page_aliases`;
+
+export const aliasesRepair: RepairHandler = {
+ kind: 'aliases',
+ publication: 'projection',
+ embeds: false,
+ async plan(engine, scope, after) {
+ const rows = await engine.executeRaw<{ source_id: string; slug: string; page_aliases: number; slug_redirects: number }>(
+ `SELECT source_id,slug,sum(page_aliases)::int AS page_aliases,sum(slug_redirects)::int AS slug_redirects FROM (
+ SELECT pa.source_id,pa.slug,1 AS page_aliases,0 AS slug_redirects FROM page_aliases pa WHERE pa.source_id=ANY($1::text[]) AND ${MISSING('pa', 'slug')}
+ UNION ALL SELECT sa.source_id,sa.canonical_slug,0,1 FROM slug_aliases sa WHERE sa.source_id=ANY($1::text[]) AND ${MISSING('sa', 'canonical_slug')}
+ ) o GROUP BY source_id,slug ORDER BY source_id,slug`, [scope.source_ids]);
+ const items: RepairItem[] = rows.map((row, index) => ({ cursor: { phase: 0, id: index + 1 }, source_id: row.source_id, slug: row.slug, chars: 0,
+ action: 'delete_orphaned_aliases', change: { from: `${row.page_aliases} page alias(es), ${row.slug_redirects} slug redirect(s)`, to: 'deleted' } }));
+ const [soft] = await engine.executeRaw<{ n: number }>(`SELECT
+ (SELECT count(*)::int FROM page_aliases pa WHERE pa.source_id=ANY($1::text[]) AND ${SOFT_DELETED('pa', 'slug')})
+ + (SELECT count(*)::int FROM slug_aliases sa WHERE sa.source_id=ANY($1::text[]) AND ${SOFT_DELETED('sa', 'canonical_slug')}) AS n`, [scope.source_ids]);
+ const residuals: Record<string, number> = soft?.n ? { soft_deleted_target: soft.n } : {};
+ return { items: items.filter(item => afterCursor(item.cursor, after)), residuals };
+ },
+ async apply(ctx, item) {
+ const removed = await ctx.engine.transaction(async tx => {
+ const managed = await readManagedMode(tx, { refusal: { subject: 'repair aliases' } });
+ const sweep = async () => {
+ await tx.lockPageKeys([{ sourceId: item.source_id, slug: item.slug }]);
+ const [row] = await tx.executeRaw<{ n: number }>(`WITH target AS (SELECT $1::text AS source_id,$2::text AS slug WHERE NOT EXISTS
+ (SELECT 1 FROM pages p WHERE p.source_id=$1 AND p.slug=$2)),
+ pa AS (DELETE FROM page_aliases a USING target t WHERE a.source_id=t.source_id AND a.slug=t.slug RETURNING 1),
+ sa AS (DELETE FROM slug_aliases a USING target t WHERE a.source_id=t.source_id AND a.canonical_slug=t.slug RETURNING 1)
+ SELECT (SELECT count(*) FROM pa)::int+(SELECT count(*) FROM sa)::int AS n`, [item.source_id, item.slug]);
+ return Number(row?.n ?? 0);
+ };
+ return managed ? withCoordinatedWrite(tx, [item.source_id], sweep, await maintenanceAttribution(tx)) : sweep();
+ });
+ return removed > 0;
+ },
+};
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 79403eedf0..1aa376c927 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -37,7 +37,7 @@ import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';
import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 2bd846b94b..5a176fa035 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -65,6 +65,7 @@ import { fileDriftRepair } from './file-drift.ts';
import { stuckRecoveryRepair } from './stuck-recovery.ts';
import { ghostPagesRepair, GHOST_CONSENT_TEXT, GHOST_CONSEQUENCES, GHOST_PURGE_FUSE_HOURS } from './ghost-pages.ts';
import { receiptCompactionRepair } from './receipt-compaction.ts';
+import { aliasesRepair } from './aliases.ts';
import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
import type { OperationError } from '../ops/contract.ts';
@@ -320,6 +321,13 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'open, and the newest sync receipt per worktree, are kept. Preview-bound and destructive: --apply --expect <hash> --yes compacts only the '
+ 'previewed set. No admission, so it runs at a full cap. Brain-wide. Runs only when named.',
},
+ aliases: {
+ handler: aliasesRepair, embeds: 'none', checks: ['dangling_aliases'], explicit_only: true,
+ summary: 'Delete free-text page aliases and slug redirects whose target page has no row at all (purged or hard-deleted, #6619), which doctor '
+ + 'dangling_aliases reports as orphaned. Aliases of a soft-deleted page are kept for gbrain restore and counted; a redirect from an old name '
+ + 'of a page that still exists is never touched. Each target slug is rechecked under its page lock; coordinated maintenance write on a managed '
+ + 'brain, no journal admission. Runs only when named.',
+ },
};
export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
index 4289d7687b..3850c0e739 100644
--- a/test/fix-wave-5-integration.test.ts
+++ b/test/fix-wave-5-integration.test.ts
@@ -196,7 +196,7 @@ for (const backend of testBackends()) {
const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts',
'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes',
frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift',
- 'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'receipt-compaction': 'gbrain repair receipt-compaction' };
+ 'stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases' };
// The post-upgrade banner names both findings with the kind's read-only preview.
const banner = await postUpgradeRecoveryBanner(engine, 'host');
diff --git a/test/purge-aliases-6619.test.ts b/test/purge-aliases-6619.test.ts
new file mode 100644
index 0000000000..6c8521ebda
--- /dev/null
+++ b/test/purge-aliases-6619.test.ts
@@ -0,0 +1,75 @@
+/**
+ * #6619: a coordinated page purge left the page's `page_aliases` rows (and
+ * the slug redirects resolving to it), and doctor `dangling_aliases` printed
+ * raw DELETE SQL that the managed writer guard refuses (and that would also
+ * have dropped the aliases of soft-deleted pages a restore still needs).
+ * Purge now removes both, and `gbrain repair aliases` clears leftovers whose
+ * target page row is gone, keeping soft-deleted targets and rename redirects.
+ */
+import { expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { checkDanglingAliases } from '../src/core/onboard/checks.ts';
+import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';
+import { aliasesRepair } from '../src/core/repair/aliases.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { durableGitRepo } from './helpers/git-publication.ts';
+
+const gitRoot = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };
+
+test('#6619 a coordinated purge removes the page aliases and redirects that resolve to it; a redirect away from it stays', () => managedBrain(async ({ engine, ctx }) => {
+ const slug = 'concepts/probe-widget';
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(),
+ content: `---\ntype: concept\ntitle: Probe Widget\naliases: ["Widget Alias One", "widget-alias-two"]\n---\n\n# Probe Widget\n\nNeutral probe page.\n` } });
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'concepts/other-widget', request_id: randomUUID(),
+ content: '---\ntype: concept\ntitle: Other Widget\n---\n\n# Other Widget\n\nAnother page.\n' } });
+ const before = await engine.executeRaw('SELECT alias_norm FROM page_aliases WHERE slug=$1', [slug]);
+ expect(before.length).toBe(2);
+ const snap = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ const purged = await submitPageMutation(ctx, { operation: 'delete_page', params: { slug, purge: true, expected_revision: snap.revision, request_id: randomUUID() } }) as Record<string, any>;
+ expect(await engine.executeRaw('SELECT alias_norm FROM page_aliases WHERE slug=$1', [slug])).toEqual([]);
+ expect(await engine.executeRaw('SELECT alias_slug FROM slug_aliases WHERE canonical_slug=$1', [slug])).toEqual([]);
+ expect(JSON.stringify(purged)).toContain('"page_aliases"');
+ expect(await engine.executeRaw('SELECT canonical_slug FROM slug_aliases WHERE alias_slug=$1', [slug])).toEqual([{ canonical_slug: 'concepts/other-widget' }]);
+ expect((await checkDanglingAliases(engine)).check.status).toBe('ok');
+}, { setup: async ({ engine, root }) => {
+ gitRoot({ root });
+ await engine.executeRaw(`INSERT INTO slug_aliases(source_id,alias_slug,canonical_slug) VALUES
+ ('default','concepts/old-probe-widget','concepts/probe-widget'),('default','concepts/probe-widget','concepts/other-widget')`);
+} }), 120_000);
+
+test('#6619 repair aliases removes orphaned aliases only; doctor names the per-source preview, never raw SQL', () => managedBrain(async ({ engine, ctx }) => {
+ const scope = await resolveRepairScope(engine, 'default');
+ const doctor = await checkDanglingAliases(engine);
+ expect(doctor.check.status).toBe('warn');
+ expect(doctor.check.message).toContain('4 alias rows');
+ expect(doctor.check.message).toContain('gbrain repair aliases --source default');
+ expect(doctor.check.message).toContain('soft-deleted');
+ expect(doctor.check.message).not.toContain('DELETE FROM');
+ expect(doctor.check.fix?.argv).toEqual(['gbrain', 'repair', 'aliases', '--source', 'default']);
+
+ const preview = await runRepair(ctx, aliasesRepair, scope, { apply: false, explicit: true });
+ expect(preview.sample).toEqual(['default:concepts/purged-example']);
+ expect(preview.residuals).toEqual({ soft_deleted_target: 1 });
+ const applied = await runRepair(ctx, aliasesRepair, scope, { apply: true, explicit: true });
+ expect(applied.applied).toBe(1);
+ const pageAliases = await engine.executeRaw<{ slug: string }>('SELECT slug FROM page_aliases ORDER BY slug');
+ expect(pageAliases.map(r => r.slug)).toEqual(['concepts/kept-example', 'concepts/soft-deleted-example']);
+ const redirects = await engine.executeRaw<{ alias_slug: string }>('SELECT alias_slug FROM slug_aliases ORDER BY alias_slug');
+ expect(redirects.map(r => r.alias_slug)).toEqual(['concepts/purged-example']);
+ const after = await checkDanglingAliases(engine);
+ expect(after.check.message).toContain('1 alias rows');
+ expect(after.check.message).not.toContain('gbrain repair aliases');
+}, { setup: async ({ engine, root }) => {
+ gitRoot({ root });
+ for (const slug of ['concepts/kept-example', 'concepts/soft-deleted-example']) {
+ await engine.putPage(slug, { type: 'concept', title: slug, compiled_truth: `# ${slug}`, timeline: '' }, { sourceId: 'default' });
+ }
+ await engine.softDeletePage('concepts/soft-deleted-example', { sourceId: 'default' });
+ await engine.executeRaw(`INSERT INTO page_aliases(source_id,alias_norm,slug) VALUES ('default','kept','concepts/kept-example'),
+ ('default','gone one','concepts/purged-example'),('default','gone two','concepts/purged-example'),('default','soft','concepts/soft-deleted-example')`);
+ await engine.executeRaw(`INSERT INTO slug_aliases(source_id,alias_slug,canonical_slug) VALUES ('default','concepts/old-purged','concepts/purged-example'),
+ ('default','concepts/purged-example','concepts/kept-example')`);
+} }), 120_000);
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
index f073f8b7cf..dd9d179ba8 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[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction'];
+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases'];
let engine: PGLiteEngine;
const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));