Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Add ghost page classifier, doctor ghost_pages, pages ghosts and repair ghost-pages
garrytanf3bbaae505fc
diff --git a/src/cli/subcommands.ts b/src/cli/subcommands.tsindex 3fce5f15da..fc7ba47d2f 100644--- a/src/cli/subcommands.ts+++ b/src/cli/subcommands.ts@@ -17,7 +17,7 @@* returns before startup side effects, strict argument checks and engine* access.*/-export const PAGES_SUBCOMMANDS = ['purge-deleted', 'purges', 'unpurge'] as const;+export const PAGES_SUBCOMMANDS = ['purge-deleted', 'purges', 'unpurge', 'ghosts'] as const;export const CACHE_SUBCOMMANDS = ['stats', 'clear', 'prune'] as const;export const INTEGRITY_SUBCOMMANDS = ['check', 'auto', 'review', 'reset-progress'] as const;export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;diff --git a/src/commands/doctor/checks/ghost-pages.ts b/src/commands/doctor/checks/ghost-pages.tsnew file mode 100644index 0000000000..5edebf39a7--- /dev/null+++ b/src/commands/doctor/checks/ghost-pages.ts@@ -0,0 +1,67 @@+/**+ * #6696 B5 `ghost_pages`: live pages whose canonical file is missing on the+ * source's owner host (`liveFileDrift` reason `canonical_file_missing`, one+ * classifier in `src/core/ghost-pages.ts`). Every coordinated write to such a+ * page refuses and no sync can import its file, so the finding names the+ * read-only `gbrain repair ghost-pages --source <id>` preview; a person+ * decides between restoring the file and removing the page.+ *+ * Bounded: an existence pre-filter (a stat of each page's recorded canonical+ * path) before the full check of at most `GHOST_CHECK_LIMIT` candidates per+ * source, with bounded samples and `inspected` / `truncated` / `exact` details.+ * Off the owner host or on a brain with no bound source it is `ok` + info+ * (`not_applicable`), never a warning; an unreadable or ambiguous checkout is+ * the unknown convention (`warn`, `details.health: 'unknown'`).+ * `undeclared_db_only_pages` stays a separate audit.+ */+import type { Check } from '../../doctor.ts';+import { agentFix, checkError } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { readGhostPages } from '../../../core/ghost-pages.ts';++const DOCS = 'docs/guides/repair.md#ghost-pages';++async function runGhostPages(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const summary = await readGhostPages(connectedEngine(ctx), {});+ const details = { count: summary.count, by_source: summary.by_source, samples: summary.samples, inspected: summary.inspected,+ truncated: summary.truncated, exact: summary.exact, docs: DOCS };+ const ghostSources = summary.by_source.filter(entry => entry.count > 0);+ const unknown = summary.by_source.filter(entry => entry.status === 'unknown');+ if (ghostSources.length) {+ const first = ghostSources[0]!.source_id;+ checks.push({ name: 'ghost_pages', status: 'warn', details: { ...details, ...(unknown.length ? { health: 'unknown' } : {}) },+ message: `${summary.count}${summary.exact ? '' : '+'} live page(s) have no canonical file on the owner host (ghost pages), so every write to them refuses and no sync can import them `+ + `(${ghostSources.map(entry => `${entry.source_id}: ${entry.count}`).join('; ')}; e.g. ${summary.samples.map(page => `${page.source_id}:${page.slug} (${page.path})`).join(', ')}).`+ + `${unknown.length ? ` ${unknown.map(entry => entry.source_id).join(', ')} could not be checked (${unknown[0]!.reason}).` : ''}`+ + ` Preview the removal with gbrain repair ghost-pages --source ${first}; to keep a page instead, restore its file at the recorded path and sync.`,+ fix: agentFix(['gbrain', 'repair', 'ghost-pages', '--source', first, '--json'],+ 'Read-only preview: lists each ghost page with its recorded canonical path and revision, and prints the apply command with its hash. Apply only after the user agrees (it soft-deletes; restore the file and sync to keep a page).',+ 'ghost_pages', { docs: DOCS }) });+ return checks;+ }+ if (unknown.length) {+ const source = unknown[0]!.source_id;+ checks.push({ name: 'ghost_pages', status: 'warn', details: { ...details, health: 'unknown' },+ message: `Ghost pages of ${unknown.map(entry => `${entry.source_id} (${entry.reason})`).join(', ')} could not be checked: the canonical checkout is missing or could not be read reliably, so no count is reported.`,+ fix: agentFix(['gbrain', 'sources', 'writer', 'status', '--source', source, '--json'],+ 'Read-only: shows the source\'s canonical root and owner host so the checkout can be inspected.', 'ghost_pages', { docs: DOCS }) });+ return checks;+ }+ if (summary.reason === 'not_owner_host' || summary.reason === 'not_applicable') {+ checks.push({ name: 'ghost_pages', status: 'ok', severity: 'info', readiness_state: 'not_applicable', details: { ...details, reason: summary.reason },+ message: summary.reason === 'not_owner_host'+ ? 'Not applicable on this host: ghost pages are checked on each source\'s canonical owner host (run doctor there).'+ : 'Not applicable: no source has a canonical checkout, so no page owns a file that could be missing.' });+ return checks;+ }+ checks.push({ name: 'ghost_pages', status: 'ok', details,+ message: `No live page is missing its canonical file (${summary.inspected} page(s) inspected${summary.truncated ? '; bounded, more not checked' : ''}).` });+ } catch (error) {+ checks.push(checkError('ghost_pages', 'check live pages for a missing canonical file', error, { details: { count: 'unknown', health: 'unknown', docs: DOCS } }));+ }+ return checks;+}++export const ghostPagesEntry: DoctorEntry = { name: 'ghost_pages', emits: ['ghost_pages'], run: runGhostPages };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 118498301f..4da37fbec5 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -108,6 +108,7 @@ import { chatFallbackChainEntry } from './checks/chat-fallback.ts';import { providerConsentEntry } from './checks/provider-consent.ts';import { behaviorChangesEntry } from './checks/behavior-changes.ts';import { fenceIntegrityEntry } from './checks/fence-integrity.ts';+import { ghostPagesEntry } from './checks/ghost-pages.ts';import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';import { atomHeldFailedEntry } from './checks/atom-holds.ts';import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';@@ -198,6 +199,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [serveBuildDriftEntry,atomHeldFailedEntry,fenceIntegrityEntry,+ ghostPagesEntry,searchModeEntry,];diff --git a/src/commands/pages-ghosts.ts b/src/commands/pages-ghosts.tsnew file mode 100644index 0000000000..11d4c0c123--- /dev/null+++ b/src/commands/pages-ghosts.ts@@ -0,0 +1,45 @@+/**+ * `gbrain pages ghosts [--source <id>] [--json]` (#6696 B5): read-only list of+ * a source's ghost pages, live pages whose canonical file is missing on the+ * owner host. Same classifier as doctor `ghost_pages` and `gbrain repair+ * ghost-pages` (`src/core/ghost-pages.ts`); refuses off the owner host+ * (`not_owner_host`) and on an unreadable checkout (`ghost_storage_unknown`).+ */+import type { BrainEngine } from '../core/engine.ts';+import { opError } from '../core/ops/contract.ts';+import { readFix } from '../core/ops/op-fix.ts';+import { resolveSourceId } from '../core/source-resolver.ts';+import { scanGhostSource } from '../core/ghost-pages.ts';+import { GHOST_CONSEQUENCES, GHOST_REPAIR_LIMIT, ghostPreviewCommand, ghostScanRefusal } from '../core/repair/ghost-pages.ts';++export const PAGES_GHOSTS_USAGE = 'Usage: gbrain pages ghosts [--source <id>] [--json]';++export async function runPagesGhosts(engine: BrainEngine, args: string[]): Promise<void> {+ let explicit: string | undefined;+ let json = false;+ for (let i = 0; i < args.length; i++) {+ const token = args[i]!;+ if (token === '--json') json = true;+ else if (token === '--source' && args[i + 1] && !args[i + 1]!.startsWith('-')) explicit = args[++i];+ else if (token.startsWith('--source=') && token.length > '--source='.length) explicit = token.slice('--source='.length);+ else {+ throw opError('invalid_params', `Unexpected argument ${token} for gbrain pages ghosts.`, `${PAGES_GHOSTS_USAGE} (read-only).`,+ { fix: readFix('Lists the ghost pages of the default source; writes nothing.', { argv: ['gbrain', 'pages', 'ghosts', '--json'] }) });+ }+ }+ const sourceId = await resolveSourceId(engine, explicit ?? null);+ const scan = await scanGhostSource(engine, sourceId, { candidateLimit: GHOST_REPAIR_LIMIT });+ const refusal = ghostScanRefusal(scan);+ if (refusal) throw refusal;+ const next = scan.ghosts.length+ ? [`Preview the removal: ${ghostPreviewCommand(sourceId)} (writes nothing; apply only after the user agrees).`, GHOST_CONSEQUENCES.keep]+ : [];+ if (json) {+ console.log(JSON.stringify({ source_id: sourceId, status: scan.status, ...(scan.reason ? { reason: scan.reason } : {}), count: scan.ghosts.length,+ ghosts: scan.ghosts, inspected: scan.inspected, file_backed: scan.file_backed, truncated: scan.truncated, exact: !scan.truncated, next }, null, 2));+ return;+ }+ console.log(`${scan.ghosts.length}${scan.truncated ? '+' : ''} ghost page(s) in source ${sourceId} (${scan.inspected} live page(s) inspected, ${scan.file_backed} file-backed).`);+ for (const ghost of scan.ghosts) console.log(` ${ghost.slug} missing ${ghost.path} revision ${ghost.revision}`);+ for (const line of next) console.log(line);+}diff --git a/src/commands/pages.ts b/src/commands/pages.tsindex 8b94e43e5b..a731ee894d 100644--- a/src/commands/pages.ts+++ b/src/commands/pages.ts@@ -2,6 +2,7 @@* gbrain pages — page-level operator commands. v0.26.5+.** The first subcommand: `pages purge-deleted [--older-than HOURS|Nh|Nd] [--dry-run] [--json] [--yes]`.+ * `pages ghosts [--source <id>] [--json]` (#6696 B5, pages-ghosts.ts) lists ghost pages, read-only.* Manual escape hatch alongside the autopilot purge phase. Hard-deletes pages* whose `deleted_at` is older than the cutoff; cascades to content_chunks,* page_links, chunk_relations via existing FKs.@@ -90,6 +91,9 @@ export function printUsage(): void {console.log(`gbrain pages — page-level operator commands (v0.26.5)Subcommands:+ ghosts [--source <id>] [--json] List live pages whose canonical file is missing on the+ owner host (ghost pages). Read-only; remove them with+ gbrain repair ghost-pages --source <id> (preview first).purges list [--source <id>] [--json]List page purge tombstones (slug, hash, request, time).unpurge <slug> [--source <id>] [--json]@@ -118,6 +122,7 @@ export async function runPages(engine: BrainEngine, args: string[]): Promise<voiswitch (sub) {case 'purge-deleted': return runPurgeDeleted(engine, args.slice(1));case 'purges': case 'unpurge': return (await import('./pages-purges.ts')).runPagePurges(engine, sub, args.slice(1));+ case 'ghosts': return (await import('./pages-ghosts.ts')).runPagesGhosts(engine, args.slice(1));case undefined:printUsage();return;diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 98c3914aef..a85bd7baef 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -67,6 +67,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i[--only <glob>]... [--skip <glob>]... --prefer file|database [--apply --expect <preview-hash>] [--json]gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>][--keep prior|disk --apply --expect <preview-hash> --yes] [--json]+ gbrain repair ghost-pages --source <id> [--apply --expect <preview-hash> --yes] [--json]${REPAIR_CONTENT_HELP}Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.@@ -108,7 +109,7 @@ Options:stuck-recovery --apply: the version of each blocked file to keep (the user's choice from the preview).--request-id <uuid>stuck-recovery: resolve only this request's recovery (default: every blocked record of the source).- --yes frontmatter, conversation-labels, stuck-recovery --apply: the user agreed to the previewed changes (destructive+ --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages --apply: the user agreed to the previewed changes (destructiveconsent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).--json Machine-readable output with a stable shape (frontmatter: every per-file diff).@@ -118,13 +119,14 @@ run gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plWith no kind, previews every kind. Run it on the brain host.Held files (the content lane, then the two-pass frontmatter repair): docs/guides/repair.md#held-files.Malformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fences.-A write recovery blocked on unexpected_file_bytes: docs/guides/repair.md#stuck-recovery.`;+A write recovery blocked on unexpected_file_bytes: docs/guides/repair.md#stuck-recovery.+Live pages whose canonical file is missing (ghost pages): docs/guides/repair.md#ghost-pages.`;const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted']);const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--keep', '--request-id']);/** Flags only some kinds accept, with the kinds that do. */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'],+ '--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'],'--slug': ['fences', 'file-drift'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'],'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],};diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 8156ae4422..04ca4cad1e 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -572,6 +572,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.229.0', text: 'A `gbrain sync` handed to a running `gbrain serve` on a managed brain now treats processing options as the in-process sync does. With no `--no-embed` / `--no-extract` / `--no-schema-pack` flag it adopts an unfinished run\'s stored options instead of refusing `invalid_params`; an older CLI that omits the explicit-flag list counts each processing flag it sends as true as typed. The resident-owner lane of a PGLite brain follows the same rule and keeps an explicit list it is sent. A cost-gate embedding deferral stays a property of that run, so resuming a run that stored embedding on embeds nothing in it. A source with a configured strategy now gets one cursor for `gbrain sync --all`, a single-source sync, the cycle and a delegated run; an unfinished run under the old key finishes under that key first.' },{ since: '0.60.229.0', text: '`--skip-failed` and `--include-gitignored` on a managed source now refuse with `managed_sync_flag_refused`, naming the flag, before anything runs: at `gbrain sync` parse (`--all` included), before a hand-off to `gbrain serve`, and for jobs, MCP and the cycle. Before, the refusal was `writer_coordinator_required` "cannot bypass ignored-file or failed-receipt guards", raised later. Rerun without the flag.' },{ since: '0.60.229.0', text: '`gbrain sync --retry-failed` on a managed source now prints, for each failure held under another run\'s options, its class and the command that settles it: `resumable` (a replay of the unfinished run, or a fresh discovery under the failed run\'s options, labelled apart), `safely orphaned` (the `gbrain repair managed-sync-orphans` preview) or `unresolved` (what has to finish first). A failure recorded before runs kept their options no longer prints "with the same options as the failed run (this receipt no longer records them)"; its options are recovered when an option set reproduces its cursor key exactly.' },+ // #6696 PR B5 (GBRA-93 lane B, ghost pages). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.229.0', text: 'New doctor check `ghost_pages`: on a source\'s canonical owner host it counts live pages whose canonical file is missing (ghost pages: every write to them refuses `source_changed` with reason `canonical_file_missing` and no sync can import them) and names the read-only `gbrain repair ghost-pages --source <id>` preview. Off the owner host, or on a brain with no source checkout, it is `ok` (info, not applicable); an unreadable checkout warns with health unknown. `gbrain pages ghosts --source <id> [--json]` lists them, read-only. `undeclared_db_only_pages` is unchanged.' },+ { since: '0.60.229.0', text: 'New explicit-only repair kind `gbrain repair ghost-pages --source <id>`: the preview lists each ghost page with its recorded canonical path and revision and prints the apply command with its hash; `--apply --expect <hash> --yes` soft-deletes exactly that set (without `--yes` a non-interactive run exits 3 with the consent payload and changes nothing). It refuses off the owner host (`not_owner_host`), on an unreadable checkout (`ghost_storage_unknown`), and when ghosts are more than half of a source\'s file-backed pages (`ghost_mass_delete_refused`, unless `GBRAIN_ALLOW_MASS_RECONCILE=1`); a page whose file came back before the apply is kept. Removed pages are purged after 72 h; `gbrain restore <slug> --force` undoes one until then. Sync never removes ghost pages by itself.' },+ { since: '0.60.229.0', text: 'A coordinated write refused because the page\'s canonical file is missing now carries `detail: canonical_file_missing` (message unchanged), and the live file check behind the conflict audit, maintenance and doctor reports reason `canonical_file_missing` for such a page instead of `file_missing`; other `source_changed` refusals keep `file_missing`.' },// GBRA-96 (default reranker). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.228.0', text: 'The default search reranker is now Voyage `rerank-3-lite` instead of `rerank-2.5`, for brains that never set `search.reranker.model` (a brain that set one keeps it). In gbrain-evals #148 (v0.10.93) it cut rerank cost 60% at the same 50 candidates × 1,400 tokens, with retrieval quality within noise. To go back: `gbrain config set search.reranker.model voyage:rerank-2.5`.' },// #6650 follow-up (group follower stamps). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex cf278f28c8..bfde1264bb 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -184,6 +184,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([// #5254 — pages written database-only to a source with no canonical owner.'unbound_source','undeclared_db_only_pages',+ // #6696 B5: live pages whose canonical file is missing on the owner host (doctor/checks/ghost-pages.ts).+ 'ghost_pages','unified_multimodal_coverage','unverified_extractions','voice_gate_health',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex d7ef18dbd1..83bed5e7c9 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -203,6 +203,8 @@ export const CODES = {frontmatter_slug_conflict: { class: 'caller', summary: "The file's frontmatter `slug:` names a different page than its path does.", why: "The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes.", suggestion: 'Remove the `slug:` line or make it match the path, then commit and sync again.' },full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },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 } },+ 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.' },git_checkout_required: { class: 'host_only', summary: "The canonical root is not inside a Git checkout, so its Git effects have nothing to commit to.", suggestion: 'Initialize the root as a Git repository with a first commit and a remote on the brain host, then rerun; a database-only source needs no Git durability.' },git_detached_head: { class: 'host_only', summary: "The canonical checkout is on a detached HEAD, so a push would target the wrong ref.", suggestion: 'Check out the branch the remote should track (git switch <branch>) on the brain host, then rerun.' },@@ -322,6 +324,7 @@ export const CODES = {no_worker: { class: 'caller', summary: "No worker is running for this queue, so a queued job would wait until something runs it.", why: "PGLite brains have no background worker (the database is single-writer), and a Postgres queue needs a running `gbrain jobs work` or supervisor. Queuing without one leaves the job waiting with no error." },no_worker_surface: { class: 'caller', summary: "No worker surface." },not_a_git_repo: { class: 'caller', summary: "The source path must contain committed Git content." },+ not_owner_host: { class: 'host_only', summary: "This host does not own the source's active canonical worktree, so ghost pages (live pages whose canonical file is missing) cannot be checked or removed here; nothing was changed.", why: "Whether a page's canonical file is missing is only known on the host that holds the source's checkout; another host would read its own disk.", reasons: ['not_owner_host', 'not_applicable'], docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Run gbrain repair ghost-pages --source <id> in a terminal on the source\'s canonical owner host (writer status names it).', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: names the canonical owner host of the source.', requires_exclusive: false } },not_connected: { class: 'caller', summary: "Google connect credential error: not connected.", docs: 'docs/guides/google-connect.md#troubleshooting' },no_brain: { class: 'caller', summary: "No brain is configured on this machine.", suggestion: 'Run `gbrain init --pglite --no-embedding` to create a local keyless brain (or `gbrain init --help` for hosted and Postgres options).' },not_found: { class: 'caller', summary: "The requested resource does not exist or is not visible to this caller.", legacy_error: 'invalid_params' },diff --git a/src/core/ghost-pages.ts b/src/core/ghost-pages.tsnew file mode 100644index 0000000000..3de36bffd7--- /dev/null+++ b/src/core/ghost-pages.ts@@ -0,0 +1,209 @@+/**+ * #6696 B5: ghost pages, one classifier.+ *+ * A ghost is a live page whose canonical file is gone: `liveFileDrift` returns+ * reason `canonical_file_missing` for it on the source's canonical owner host+ * (`prepareFileTarget` refuses every coordinated write to it with that detail,+ * and no sync can import a file that is not there). Declared db_only pages,+ * never-filed derive-phase pages, read-only mirror and unbound-source pages+ * publish to the database only and are never ghosts; a deleted page is not one+ * either. `undeclared_db_only_pages` (doctor) stays a separate audit.+ *+ * The scan is bounded for large brains: the live pages of a source are read in+ * id order (at most `SCAN_LIMIT`), the recorded canonical path of each is+ * resolved exactly as `prepareFileTarget` does and stat'ed, and only the pages+ * whose file is absent and which are not database-only by declaration run the+ * full `liveFileDrift` check (at most `candidateLimit` of them). `inspected`,+ * `truncated` and `exact` say how much of the brain the answer covers.+ *+ * Off the owner host the source is `not_applicable` (`not_owner_host`); a+ * missing or unreadable root (`storage_unavailable`) or a stat error, an+ * invalid gbrain.yml or a check that ends in any other reason+ * (`ambiguous_storage`) make it `unknown`, never a count of zero.+ *+ * Readers: doctor `ghost_pages`, `gbrain pages ghosts` and `gbrain repair+ * ghost-pages` (`scanGhostSource`, `ghostPageNow`), and the read-scope MCP+ * health op (`readGhostPages`, counts only for remote callers).+ */+import { statSync } from 'node:fs';+import { join, relative, sep } from 'node:path';+import type { BrainEngine } from './engine.ts';+import type { PageSnapshot } from './page-state/types.ts';+import { resolveSourceLocalFilePath, sourceGitScope } from './markdown.ts';+import { recordedPathFromFileUri, scannerSlugRootMode } from './write-through.ts';+import { isOpPageSlug } from './ops/context.ts';+import { existingLocalHostId } from './persistence/identity.ts';+import { getWorktreeBinding } from './persistence/ownership.ts';+import { sourceMirrorReadOnly } from './persistence/mirror-read-only.ts';+import { publishesDatabaseOnly } from './persistence/page-prepare.ts';+import { liveFileDrift } from './persistence/drift-conflicts.ts';++export interface GhostPage { source_id: string; slug: string; path: string; revision: string; page_id: number }+export interface GhostPagesSummary {+ status: 'known' | 'unknown';+ /** 'not_owner_host' | 'not_applicable' | 'storage_unavailable' | 'ambiguous_storage' */+ reason?: string;+ /** Ghosts found among inspected pages. */+ count: number;+ by_source: Array<{ source_id: string; count: number; status: 'known' | 'unknown' | 'not_applicable'; reason?: string }>;+ /** Bounded by `sampleLimit`. */+ samples: GhostPage[];+ inspected: number;+ truncated: boolean;+ exact: boolean;+}++/** The canonical owner the scan ran under; the repair binds its approval to it. */+export interface GhostOwner { host_id: string; worktree_id: string; owner_epoch: string; source_incarnation: string }++export interface GhostSourceScan {+ source_id: string;+ status: 'known' | 'unknown' | 'not_applicable';+ reason?: string;+ ghosts: GhostPage[];+ /** Live pages the existence pre-filter examined. */+ inspected: number;+ /** Pages expected to own a canonical file (present, ghost, or not yet confirmed): the mass-delete valve's population. */+ file_backed: number;+ /** Pages whose recorded canonical file is absent and that publish no database-only exception. */+ candidates: number;+ truncated: boolean;+ owner?: GhostOwner;+}++export const GHOST_SAMPLE_LIMIT = 5;+/** Candidates `readGhostPages` (doctor, health) confirms per source. */+export const GHOST_CHECK_LIMIT = 200;+/** Live pages the pre-filter reads per source. */+export const GHOST_SCAN_LIMIT = 250_000;+const BATCH = 10_000;++interface PageRow { id: number; slug: string; source_path: string | null; source_uri: string | null }+type SourceContext = { ok: true; root: string; owner: GhostOwner; mode: Awaited<ReturnType<typeof scannerSlugRootMode>>; gitScope: string[] | null }+ | { ok: false; status: 'unknown' | 'not_applicable'; reason: string };++const missing = (error: unknown) => ['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException)?.code ?? '');++async function sourceContext(engine: BrainEngine, sourceId: string): Promise<SourceContext> {+ const hostId = existingLocalHostId();+ const binding = await getWorktreeBinding(engine, sourceId, hostId);+ if (!binding) return { ok: false, status: 'not_applicable', reason: 'not_applicable' };+ if (!hostId || !binding.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') {+ return { ok: false, status: 'not_applicable', reason: 'not_owner_host' };+ }+ if (await sourceMirrorReadOnly(engine, sourceId)) return { ok: false, status: 'not_applicable', reason: 'mirror_read_only' };+ const root = join(binding.local_path, binding.relative_path);+ try {+ if (!statSync(root).isDirectory()) return { ok: false, status: 'unknown', reason: 'storage_unavailable' };+ } catch {+ return { ok: false, status: 'unknown', reason: 'storage_unavailable' };+ }+ return { ok: true, root, mode: await scannerSlugRootMode(engine, sourceId, root), gitScope: sourceGitScope(root),+ owner: { host_id: hostId, worktree_id: binding.worktree_id, owner_epoch: String(binding.owner_epoch), source_incarnation: binding.source_incarnation } };+}++/** The path `prepareFileTarget` compares, resolved the same way (recorded source path, captured file URI, then the slug path). */+function canonicalPath(context: Extract<SourceContext, { ok: true }>, page: Pick<PageRow, 'slug' | 'source_path' | 'source_uri'>): string {+ const captured = recordedPathFromFileUri(page.source_uri, context.root);+ return resolveSourceLocalFilePath(context.root, page.source_path, page.slug, page.source_path ? context.mode : undefined, context.gitScope)+ ?? (captured ? join(context.root, captured) : join(context.root, `${page.slug}.md`));+}++/** The existence pre-filter: `present`, `database_only`, a `candidate` at its source-relative path, or `ambiguous`. */+function prefilter(context: Extract<SourceContext, { ok: true }>, page: PageRow): { kind: 'present' | 'database_only' | 'ambiguous' } | { kind: 'candidate'; path: string } {+ if (!isOpPageSlug(page.slug)) return { kind: 'database_only' };+ const path = canonicalPath(context, page);+ try {+ statSync(path);+ return { kind: 'present' };+ } catch (error) {+ if (!missing(error)) return { kind: 'ambiguous' };+ }+ try {+ if (publishesDatabaseOnly(context.root, page.slug, { page: { deleted_at: null, source_path: page.source_path, source_uri: page.source_uri } })) return { kind: 'database_only' };+ } catch {+ return { kind: 'ambiguous' };+ }+ return { kind: 'candidate', path: relative(context.root, path).split(sep).join('/') };+}++/** The full check of one candidate: `ghost` with its revision, `not_ghost`, or `unknown` with the classifier's reason. */+async function confirm(engine: BrainEngine, context: Extract<SourceContext, { ok: true }>, sourceId: string, slug: string):+ Promise<{ kind: 'ghost'; ghost: GhostPage } | { kind: 'not_ghost'; reason: string } | { kind: 'unknown'; reason: string }> {+ const snapshot: PageSnapshot | null = await engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot || snapshot.page.deleted_at) return { kind: 'not_ghost', reason: 'page_missing' };+ const live = await liveFileDrift(engine, sourceId, slug, snapshot);+ if (live.reason === 'canonical_file_missing') {+ return { kind: 'ghost', ghost: { source_id: sourceId, slug, path: relative(context.root, canonicalPath(context, { slug, source_path: snapshot.page.source_path ?? null,+ source_uri: snapshot.page.source_uri ?? null })).split(sep).join('/'), revision: snapshot.revision, page_id: Number(snapshot.page.id) } };+ }+ if (['agrees', 'file_database_drift', 'database_only', 'page_missing'].includes(live.reason)) return { kind: 'not_ghost', reason: live.reason };+ return { kind: 'unknown', reason: live.reason === 'not_owner_host' ? 'not_owner_host' : 'ambiguous_storage' };+}++/**+ * One source's ghosts in page-id order. `candidateLimit` bounds the full checks (default `GHOST_CHECK_LIMIT`);+ * anything past it, or past `GHOST_SCAN_LIMIT` live pages, sets `truncated`.+ */+export async function scanGhostSource(engine: BrainEngine, sourceId: string, opts: { candidateLimit?: number } = {}): Promise<GhostSourceScan> {+ const limit = opts.candidateLimit ?? GHOST_CHECK_LIMIT;+ const context = await sourceContext(engine, sourceId);+ const scan: GhostSourceScan = { source_id: sourceId, status: 'known', ghosts: [], inspected: 0, file_backed: 0, candidates: 0, truncated: false };+ if (!context.ok) return { ...scan, status: context.status, reason: context.reason };+ scan.owner = context.owner;+ let after = 0;+ let unchecked = 0;+ for (;;) {+ const rows = await engine.executeRaw<PageRow>(`SELECT id, slug, source_path, source_uri FROM pages+ WHERE source_id=$1 AND deleted_at IS NULL AND id > $2 ORDER BY id LIMIT ${BATCH}`, [sourceId, after]);+ for (const row of rows) {+ if (scan.inspected >= GHOST_SCAN_LIMIT) { scan.truncated = true; break; }+ scan.inspected++;+ const verdict = prefilter(context, row);+ if (verdict.kind === 'present') { scan.file_backed++; continue; }+ if (verdict.kind === 'database_only') continue;+ if (verdict.kind === 'ambiguous') return { ...scan, status: 'unknown', reason: 'ambiguous_storage' };+ scan.candidates++;+ if (scan.candidates > limit) { scan.truncated = true; unchecked++; continue; }+ const result = await confirm(engine, context, sourceId, row.slug);+ if (result.kind === 'unknown') return { ...scan, status: result.reason === 'not_owner_host' ? 'not_applicable' : 'unknown', reason: result.reason };+ if (result.kind === 'ghost') scan.ghosts.push(result.ghost);+ else if (result.reason === 'agrees' || result.reason === 'file_database_drift') scan.file_backed++;+ }+ if (rows.length < BATCH || scan.inspected >= GHOST_SCAN_LIMIT) break;+ after = Number(rows[rows.length - 1]!.id);+ }+ scan.file_backed += scan.ghosts.length + unchecked;+ return scan;+}++/**+ * One page, checked now under the current owner: the ghost it still is (same classifier as the scan), or why not.+ * The repair re-runs it before each soft delete and inside the preparer.+ */+export async function ghostPageNow(engine: BrainEngine, sourceId: string, slug: string):+ Promise<{ ghost: GhostPage; owner: GhostOwner } | { ghost: null; reason: string; owner?: GhostOwner }> {+ const context = await sourceContext(engine, sourceId);+ if (!context.ok) return { ghost: null, reason: context.reason };+ const result = await confirm(engine, context, sourceId, slug);+ return result.kind === 'ghost' ? { ghost: result.ghost, owner: context.owner } : { ghost: null, reason: result.reason, owner: context.owner };+}++/** Every selected (default: every active) source's ghost count, bounded samples and coverage; the doctor and health reader. */+export async function readGhostPages(engine: BrainEngine, opts: { sourceIds?: string[]; sampleLimit?: number }): Promise<GhostPagesSummary> {+ const sourceIds = opts.sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);+ const scans: GhostSourceScan[] = [];+ for (const sourceId of sourceIds) scans.push(await scanGhostSource(engine, sourceId));+ const unknown = scans.find(scan => scan.status === 'unknown');+ const known = scans.filter(scan => scan.status === 'known');+ const offOwner = scans.some(scan => scan.reason === 'not_owner_host');+ const count = scans.reduce((sum, scan) => sum + scan.ghosts.length, 0);+ const truncated = scans.some(scan => scan.truncated);+ const status = unknown || (!known.length && offOwner) ? 'unknown' : 'known';+ const reason = unknown?.reason ?? (!known.length ? (offOwner ? 'not_owner_host' : 'not_applicable') : undefined);+ return { status, ...(reason ? { reason } : {}), count,+ by_source: scans.map(scan => ({ source_id: scan.source_id, count: scan.ghosts.length, status: scan.status, ...(scan.reason ? { reason: scan.reason } : {}) })),+ samples: scans.flatMap(scan => scan.ghosts).slice(0, opts.sampleLimit ?? GHOST_SAMPLE_LIMIT),+ inspected: scans.reduce((sum, scan) => sum + scan.inspected, 0), truncated,+ exact: status === 'known' && !truncated && !offOwner && !unknown };+}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex fb8c8c6ffd..57fd9dbc15 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -524,6 +524,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, coreturn (await import('../chronicle/publish.ts')).prepareChronicleMutation(engine, row, config);}if (row.intent?.kind === 'managed_maintenance_retire_stale_atoms') return (await import('../repair/stale-atoms.ts')).prepareStaleAtomRetirement(engine, row, config);+ if (row.intent?.kind === 'managed_maintenance_retire_ghost_page') return (await import('../repair/ghost-pages.ts')).prepareGhostPageRetirement(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 ddf5d3dbd7..e385c97d45 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' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex bd16b10f58..740e7b43fa 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -35,7 +35,7 @@ import type { RepairKindSpec } from './registry.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.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'] 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'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/ghost-pages.ts b/src/core/repair/ghost-pages.tsnew file mode 100644index 0000000000..6327e488d8--- /dev/null+++ b/src/core/repair/ghost-pages.ts@@ -0,0 +1,245 @@+/**+ * `gbrain repair ghost-pages --source <id>` (#6696 B5): soft-delete live pages+ * whose canonical file is gone (a ghost: `liveFileDrift` reason+ * `canonical_file_missing` on the owner host, `src/core/ghost-pages.ts`).+ *+ * Explicit-only, preview-bound and destructive: the preview lists every ghost+ * with its recorded canonical path and revision, binds the set to the+ * canonical owner it ran under (host, worktree, owner epoch, source+ * incarnation) and saves it under its hash; `--apply --expect <hash> --yes`+ * (the user's consent, else exit 3 / `ask_user` with nothing changed)+ * soft-deletes exactly that set. Each page is a `delete_page` with+ * `allowMissingFile`: a managed brain submits one+ * `managed_maintenance_retire_ghost_page` request per page bound to its+ * revision, and the preparer re-runs the classifier and refuses when the file+ * exists again; filesystem publication refuses a file that appeared after+ * preparation (the prepared file target expects no bytes). An unmanaged brain+ * soft-deletes in one transaction after the same recheck. A page whose file+ * came back is skipped (`file_restored`) and the result asks for a new+ * preview; any other change is `changed_since_preview`.+ *+ * Refuses off the owner host (`not_owner_host`), fails closed when the source+ * root is unavailable or a check is ambiguous (`ghost_storage_unknown`),+ * never lists a declared db_only page, and applies the sync mass-delete valve+ * (`ghost_mass_delete_refused` unless `GBRAIN_ALLOW_MASS_RECONCILE=1`) when the+ * ghosts are more than half of a source's file-backed pages. Soft-deleted+ * pages are purged by the autopilot purge phase after 72 h; until then+ * `gbrain restore <slug> --force` undoes one page.+ */+import { existsSync } from 'node:fs';+import { join, relative, sep } from 'node:path';+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 } from '../ops/op-fix.ts';+import { authorizeWrite } from '../persistence/authority.ts';+import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';+import { preparePageMutation } from '../persistence/page-prepare.ts';+import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';+import { ghostPageNow, scanGhostSource, type GhostOwner, type GhostPage, type GhostSourceScan } from '../ghost-pages.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';++export const GHOST_PAGES_INTENT = 'managed_maintenance_retire_ghost_page';+/** Ghosts one preview lists; a larger set is applied in rounds (preview, apply, preview again). */+export const GHOST_REPAIR_LIMIT = 1000;+export const GHOST_PURGE_FUSE_HOURS = 72;+const DOCS = 'docs/guides/repair.md#ghost-pages';+const FILE_CHANGED = 'The canonical file changed after preparation.';++interface ApprovedGhost extends GhostPage { owner: GhostOwner; selection: string[] }+interface GhostItem extends RepairItem { ghost: GhostPage; owner: GhostOwner; hash: string; last: boolean }++export const ghostPreviewCommand = (sourceId: string) => `gbrain repair ghost-pages --source ${sourceId}`;+const previewFix = (sourceId: string) => readFix('Previews the ghost pages of the source again; writes nothing.',+ { argv: ['gbrain', 'repair', 'ghost-pages', '--source', sourceId, '--json'] });+const writerStatusFix = (sourceId: string) => readFix('Shows the source\'s canonical binding and owner host, read-only.',+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });++/** The three consequences every preview and the consent payload state. */+export const GHOST_CONSEQUENCES = {+ purge: `Soft-deleted pages are purged for good by the autopilot purge phase ${GHOST_PURGE_FUSE_HOURS} h after deletion.`,+ undo: 'Until then, undo one page with gbrain restore <slug> --force (per slug; it writes the file back).',+ keep: 'To keep a page instead, restore its file at the recorded canonical path on the owner host (from Git or a backup; gbrain has no automated file restore), then run gbrain sync for the source.',+};++/** The consent payload of `--apply --expect <hash>` (registry `consentText`). */+export const GHOST_CONSENT_TEXT = {+ what: 'Soft-delete the previewed ghost pages: live pages whose canonical file is missing on the owner host',+ why: 'The preview listed each page with its recorded canonical path and revision; no sync can import a file that is not there, so every write to these pages refuses until the file is restored or the page is removed.',+ risk: `The pages leave search and reads now. ${GHOST_CONSEQUENCES.purge} ${GHOST_CONSEQUENCES.undo} ${GHOST_CONSEQUENCES.keep.replace('To keep a page instead, ', 'To keep a page instead, do not apply: ')} A page whose file comes back before the apply is kept.`,+ user_message: `Soft-delete the previewed ghost pages? They are purged after ${GHOST_PURGE_FUSE_HOURS} h; gbrain restore <slug> --force undoes one until then`,+};++/** The sync valve (#2828) over a source's file-backed pages. */+export function massGhosts(ghosts: number, fileBacked: number): boolean {+ return fileBacked > MASS_RECONCILE_MIN_PAGES && ghosts > fileBacked * MASS_RECONCILE_RATIO;+}++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;++/** `not_owner_host`: the classifier only answers on the source's canonical owner host. */+export function notOwnerHostError(sourceId: string, reason: string): OperationError {+ return opError('not_owner_host', `Ghost pages of source ${sourceId} can only be checked and removed on its canonical owner host.`,+ reason === 'not_applicable'+ ? `Source ${sourceId} has no canonical checkout, so none of its pages owns a file that could be missing; nothing was listed or changed.`+ : `This host does not own source ${sourceId}'s active canonical worktree, so it cannot tell whether a page's file is missing; nothing was listed or changed. Run ${ghostPreviewCommand(sourceId)} in a terminal on the owner host (writer status names it).`,+ { reason, fix: writerStatusFix(sourceId), docs: DOCS });+}++export function ghostScanRefusal(scan: GhostSourceScan): OperationError | null {+ if (scan.status === 'known' || scan.reason === 'mirror_read_only') return null;+ if (scan.status === 'not_applicable') return notOwnerHostError(scan.source_id, scan.reason ?? 'not_owner_host');+ return opError('ghost_storage_unknown', `Ghost pages of source ${scan.source_id} cannot be classified: ${scan.reason === 'storage_unavailable'+ ? 'its canonical root is missing or is not a readable directory' : 'a canonical path could not be read or a page check was ambiguous'}.`,+ `Nothing was listed or changed: a page is never removed while its file may only be unreadable. Inspect the source's checkout on the owner host (writer status shows its root), fix it, then preview again: ${ghostPreviewCommand(scan.source_id)}`,+ { reason: scan.reason, fix: writerStatusFix(scan.source_id), docs: DOCS });+}++function massRefusal(sourceId: string, ghosts: number, fileBacked: number): OperationError {+ return opError('ghost_mass_delete_refused', `Refusing to soft-delete ${ghosts} of ${fileBacked} file-backed page(s) of source ${sourceId} (more than ${Math.round(MASS_RECONCILE_RATIO * 100)}%).`,+ `That many missing files almost always means the checkout is the wrong path, unmounted or half-cloned, not that the files were deleted; nothing was changed. Check the checkout on the 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: writerStatusFix(sourceId), docs: DOCS });+}++function hashParts(scope: RepairScope, owner: GhostOwner | undefined, ghosts: GhostPage[]) {+ return { kind: 'ghost-pages-v1', brain_id: scope.brain_id, selection: { source_ids: scope.source_ids }, owner: owner ?? null, ghosts };+}++function item(ghost: GhostPage, owner: GhostOwner, hash: string, last: boolean): GhostItem {+ return { cursor: { phase: 1, id: ghost.page_id }, source_id: ghost.source_id, slug: ghost.slug, chars: 0, action: 'soft_delete:canonical_file_missing',+ ghost, owner, hash, last };+}++export const ghostPagesRepair: RepairHandler = {+ kind: 'ghost-pages',+ embeds: false,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ if (scope.source_ids.length !== 1) {+ throw opError('invalid_params', 'gbrain repair ghost-pages needs --source <id>.',+ 'Ghost pages are checked on each source\'s own canonical owner host; name one source, e.g. gbrain repair ghost-pages --source default.',+ { fix: readFix('Lists the registered sources.', { argv: ['gbrain', 'sources', 'list', '--json'] }), docs: DOCS });+ }+ const sourceId = scope.source_ids[0]!;+ const command = ghostPreviewCommand(sourceId);+ const scan = await scanGhostSource(engine, sourceId, { candidateLimit: GHOST_REPAIR_LIMIT });+ const refusal = ghostScanRefusal(scan);+ if (refusal) throw refusal;+ const mass = massGhosts(scan.ghosts.length, scan.file_backed);+ if (!opts?.apply) {+ const hash = previewHash(hashParts(scope, scan.owner, scan.ghosts));+ if (scan.ghosts.length) await saveApprovedSet<ApprovedGhost>(engine, { command: 'ghost-pages', hash },+ scan.ghosts.map(ghost => ({ ...ghost, owner: scan.owner!, selection: scope.source_ids })));+ const warnings = [+ ...(mass ? [`${scan.ghosts.length} of ${scan.file_backed} file-backed page(s) are ghosts (more than ${Math.round(MASS_RECONCILE_RATIO * 100)}%): the apply refuses (ghost_mass_delete_refused) unless GBRAIN_ALLOW_MASS_RECONCILE=1; check the checkout first.`] : []),+ ...(scan.truncated ? [`More ghosts may exist past the first ${GHOST_REPAIR_LIMIT} checked; apply this set, then preview again.`] : []),+ ...(scan.reason === 'mirror_read_only' ? [`Source ${sourceId} is a read-only mirror: its pages publish no file, so none is a ghost.`] : []),+ ...(scan.ghosts.length ? Object.values(GHOST_CONSEQUENCES) : []),+ ];+ return { warnings, items: scan.ghosts.map((ghost, index) => item(ghost, scan.owner!, hash, index === scan.ghosts.length - 1)), preview_hash: hash,+ residuals: { ghosts: scan.ghosts.length, file_backed: scan.file_backed, inspected: scan.inspected },+ listing: scan.ghosts.map(ghost => ({ item: `${ghost.source_id}:${ghost.slug}`, class: 'canonical_file_missing',+ detail: `file ${ghost.path} is missing; revision ${ghost.revision}` })),+ details: { purge_fuse_hours: GHOST_PURGE_FUSE_HOURS, undo: 'gbrain restore <slug> --force', keep: GHOST_CONSEQUENCES.keep, mass_delete: mass, truncated: scan.truncated, docs: DOCS } };+ }+ if (!opts.expect) {+ throw opError('invalid_params', 'gbrain repair ghost-pages --apply removes 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<ApprovedGhost>(engine, { command: 'ghost-pages', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash(hashParts(scope, scan.owner, [])) });+ if (approved.items.some(ghost => JSON.stringify(ghost.selection) !== JSON.stringify(scope.source_ids) || !sameOwner(scan.owner, ghost.owner))) {+ throw previewChangedError(opts.expect, command);+ }+ if (massGhosts(approved.items.length, scan.file_backed) && !massReconcileAllowed()) throw massRefusal(sourceId, approved.items.length, scan.file_backed);+ const items = approved.items.map(({ selection: _selection, owner, ...ghost }, index) => item(ghost, owner, 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 { ghost, owner, hash, last } = entry as GhostItem;+ const outcome = await retireGhost(ctx, ghost, owner);+ if (last) await clearApprovedSet(ctx.engine, { command: 'ghost-pages', hash });+ return outcome;+ },+ render(details) {+ return [` each removed page: soft-deleted, purged after ${details.purge_fuse_hours} h; undo per slug: ${details.undo}; guide: ${details.docs}`];+ },+};++const restored = (ghost: GhostPage): RepairItemOutcome => ({ applied: false, outcome: 'file_restored', detail: { path: ghost.path },+ reason: `The canonical file ${ghost.path} exists again, so ${ghost.slug} was kept; run ${ghostPreviewCommand(ghost.source_id)} again for a new preview.` });+const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });++/** Whether the live page is still the approved ghost under the approved owner; otherwise the outcome that skips it. */+async function stillApproved(engine: BrainEngine, ghost: GhostPage, owner: GhostOwner): Promise<RepairItemOutcome | null> {+ const now = await ghostPageNow(engine, ghost.source_id, ghost.slug);+ if (!now.ghost) return now.reason === 'agrees' || now.reason === 'file_database_drift' ? restored(ghost) : changed(`the page is no longer a ghost (${now.reason})`);+ if (!sameOwner(now.owner, owner)) return changed('the source\'s canonical owner changed since the preview');+ if (now.ghost.revision !== ghost.revision || now.ghost.page_id !== ghost.page_id || now.ghost.path !== ghost.path) return changed('the page or its recorded canonical path changed since the preview');+ return null;+}++async function retireGhost(ctx: OperationContext, ghost: GhostPage, owner: GhostOwner): Promise<RepairItemOutcome> {+ const engine = ctx.engine;+ const skip = await stillApproved(engine, ghost, owner);+ if (skip) return skip;+ if (await managedPersistenceEnabled(engine)) {+ const authority = (await maintenancePreflight(engine, ghost.source_id))!;+ try {+ await submitMaintenanceIntent(engine, authority, ghost.slug, { kind: GHOST_PAGES_INTENT, expected_revision: ghost.revision, ghost, owner },+ await repairRequestId(ctx, 'ghost-pages', ghost, ghost.revision));+ } catch (error) {+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return changed(error.message);+ if (error instanceof OperationError && error.code === 'source_changed') return restored(ghost);+ throw error;+ }+ return { applied: true, outcome: 'soft_deleted' };+ }+ const binding = await getWorktreeBinding(engine, ghost.source_id, owner.host_id);+ const file = binding?.local_path ? join(binding.local_path, binding.relative_path, ghost.path) : null;+ const result = await maintenanceTransaction(engine, async tx => {+ await tx.lockPageKeys([{ sourceId: ghost.source_id, slug: ghost.slug }]);+ const snapshot = await tx.readPageSnapshot(ghost.slug, { sourceId: ghost.source_id });+ if (!snapshot || snapshot.revision !== ghost.revision || Number(snapshot.page.id) !== ghost.page_id) return 'changed';+ if (!file || existsSync(file)) return 'restored';+ await tx.createVersion(ghost.slug, { sourceId: ghost.source_id });+ await tx.softDeletePage(ghost.slug, { sourceId: ghost.source_id });+ return 'deleted';+ });+ if (result === 'deleted') return { applied: true, outcome: 'soft_deleted' };+ return result === 'restored' ? restored(ghost) : changed('the page changed since the preview');+}++/**+ * Preparer for `managed_maintenance_retire_ghost_page`: re-runs the classifier under the approved owner, prepares a+ * `delete_page` with `allowMissingFile`, and refuses unless the prepared file target is the approved path with no+ * bytes (a file restored in between refuses here, or at filesystem publication when it appears later).+ */+export async function prepareGhostPageRetirement(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {+ const ghost = row.intent!.ghost as GhostPage | undefined;+ const owner = row.intent!.owner as GhostOwner | undefined;+ if (!ghost || !owner || ghost.slug !== row.slug || ghost.source_id !== row.source_id || ghost.page_id !== Number(row.page_id)) {+ throw opError('invalid_params', 'The ghost page retirement intent does not name its page.',+ `Request ${row.request_id} for ${row.slug} in source ${row.source_id} does not name the ghost page it removes, so nothing changed. Preview the repair again and apply the new preview after the user agrees.`,+ { fix: previewFix(row.source_id) });+ }+ const refuse = (outcome: RepairItemOutcome) => outcome.outcome === 'file_restored'+ ? opError('source_changed', FILE_CHANGED, `The canonical file ${ghost.path} of ${row.slug} in source ${row.source_id} exists again, so request ${row.request_id} removed nothing. Preview the repair again; a restored page is kept.`,+ { detail: 'ghost_file_restored', fix: previewFix(row.source_id) })+ : opError('revision_conflict', 'The ghost page changed since the preview.',+ `Page ${row.slug} in source ${row.source_id} changed after the preview (${outcome.reason}), so request ${row.request_id} removed nothing. Preview the repair again and apply the new preview after the user agrees.`,+ { fix: previewFix(row.source_id) });+ const skip = await stillApproved(engine, ghost, owner);+ if (skip) throw refuse(skip);+ await authorizeWrite(engine, row.authority, 'delete_page', row.slug);+ const page = await preparePageMutation(engine, { ...row, operation: 'delete_page' }, config, undefined, undefined, { allowMissingFile: true });+ if (!page.file || relative(page.file.root, page.file.path).split(sep).join('/') !== ghost.path) throw refuse(changed('its canonical file target moved'));+ if (page.file.expectedBeforeHash !== null) throw refuse(restored(ghost));+ return { ...page, validate: async tx => { await page.validate?.(tx); await authorizeWrite(tx, row.authority, 'delete_page', row.slug); } };+}diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex e3c1161456..5432700793 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -63,6 +63,7 @@ import { slugConflictsRepair } from './slug-conflicts.ts';import { frontmatterKeysRepair } from './frontmatter-keys.ts';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 { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';import type { OperationError } from '../ops/contract.ts';@@ -294,6 +295,16 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'bytes back and the accepted write publishes again, disk keeps the edit and abandons the write (reconcile the page afterwards). A terminal request is '+ 'refused (recovery_choice_refused). Runs only when named.',},+ 'ghost-pages': {+ handler: ghostPagesRepair, embeds: 'none', checks: ['ghost_pages'], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: GHOST_CONSENT_TEXT,+ summary: 'Soft-delete live pages whose canonical file is missing on the owner host (ghost pages, #6696): every write to them refuses source_changed / '+ + 'canonical_file_missing and no sync can import a file that is not there. Needs --source; refused off the canonical owner host (not_owner_host) '+ + 'and when the checkout cannot be read (ghost_storage_unknown). Declared db_only and never-filed derived pages are never listed. The preview lists '+ + 'each page with its recorded path and revision, bound to the owner; --apply --expect <hash> --yes soft-deletes exactly that set through delete_page, '+ + 'rechecking each file is still absent (a restored file keeps its page and asks for a new preview). Refused when ghosts are over half of the source\'s '+ + `file-backed pages unless GBRAIN_ALLOW_MASS_RECONCILE=1. Purged after ${GHOST_PURGE_FUSE_HOURS} h; ${GHOST_CONSEQUENCES.undo} Runs only when named.`,+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));diff --git a/test/doctor-day-zero.test.ts b/test/doctor-day-zero.test.tsindex 18cbffc25b..8c77b36cc4 100644--- a/test/doctor-day-zero.test.ts+++ b/test/doctor-day-zero.test.ts@@ -48,6 +48,8 @@ describe('day-zero keyless doctor', () => {for (const name of ['embeddings', 'embedding_provider', 'takes_count', 'retrieval_reflex_health', 'skill_preconditions', 'cycle_freshness', 'backup_coverage']) {if (report.checks.some(c => c.name === name)) expect(info.has(name), name).toBe(true);}+ // #6696 B5: ghost_pages runs on day zero and is ok, never a warning.+ expect(report.checks.find(c => c.name === 'ghost_pages')).toMatchObject({ status: 'ok' });}, 120_000);test('human doctor on a pipe keeps the heartbeat within 10 stderr lines', async () => {diff --git a/test/e2e/ghost-pages-6696-postgres.test.ts b/test/e2e/ghost-pages-6696-postgres.test.tsnew file mode 100644index 0000000000..e66611a9fc--- /dev/null+++ b/test/e2e/ghost-pages-6696-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../ghost-pages-6696.test.ts'));diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 39a0aea1cd..37d5ac69ab 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -2213,6 +2213,27 @@"name": "fence_integrity","status": "ok"},+ {+ "category": "brain",+ "details": {+ "by_source": [+ {+ "count": 0,+ "source_id": "default",+ "status": "known"+ }+ ],+ "count": 0,+ "docs": "docs/guides/repair.md#ghost-pages",+ "exact": true,+ "inspected": 0,+ "samples": [],+ "truncated": false+ },+ "message": "No live page is missing its canonical file (0 page(s) inspected).",+ "name": "ghost_pages",+ "status": "ok"+ },{"category": "ops","message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 495967df89..0f040b67d5 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -2221,6 +2221,27 @@"name": "fence_integrity","status": "ok"},+ {+ "category": "brain",+ "details": {+ "by_source": [+ {+ "count": 0,+ "source_id": "default",+ "status": "known"+ }+ ],+ "count": 0,+ "docs": "docs/guides/repair.md#ghost-pages",+ "exact": true,+ "inspected": 0,+ "samples": [],+ "truncated": false+ },+ "message": "No live page is missing its canonical file (0 page(s) inspected).",+ "name": "ghost_pages",+ "status": "ok"+ },{"category": "ops","message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex c938d62a59..7249a7afaf 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -785,6 +785,10 @@"category": "brain","name": "fence_integrity"},+ {+ "category": "brain",+ "name": "ghost_pages"+ },{"category": "ops","name": "search_mode"diff --git a/test/ghost-pages-6696.test.ts b/test/ghost-pages-6696.test.tsnew file mode 100644index 0000000000..c39577309c--- /dev/null+++ b/test/ghost-pages-6696.test.ts@@ -0,0 +1,268 @@+/**+ * #6696 B5: ghost pages, one classifier.+ *+ * A ghost is a live page whose canonical file is gone on the owner host (`liveFileDrift` reason+ * `canonical_file_missing`). Protects: the classifier per state (agrees, drift, missing file, declared db_only, deleted+ * page), doctor `ghost_pages`, `gbrain pages ghosts --json`, and `gbrain repair ghost-pages`: preview, consent refusal+ * (exit 3, nothing changed), apply of exactly the previewed set, refusal off the owner host, the mass-delete valve, a file+ * restored between preview and apply (before the run, before preparation, before filesystem publication), the unmanaged+ * soft delete, and the exact argv the terminal-receipt classifier prints. Every case drives a real PGLite brain with a+ * claimed canonical worktree; none needs a seam beyond the existing persistence fault hook.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { liveFileDrift } from '../src/core/persistence/drift-conflicts.ts';+import { classifyTerminal } from '../src/core/persistence/terminal-classify.ts';+import { readGhostPages, ghostPageNow } from '../src/core/ghost-pages.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, repairForCheck, repairRunner, repairSpec } from '../src/core/repair/registry.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { runPagesGhosts } from '../src/commands/pages-ghosts.ts';+import { ghostPagesEntry } from '../src/commands/doctor/checks/ghost-pages.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import { withEnv } from './helpers/with-env.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const logger = { info() {}, warn() {}, error() {} };+let engine: BrainEngine;++interface Fixture { root: string; home: string; sourceId: string; ctx: OperationContext }++async function fixture(run: (f: Fixture) => Promise<void>, opts: { managed?: boolean } = {}): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-ghosts-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const home = join(dir, 'home');+ execFileSync('git', ['init', '-q'], { cwd: root });+ const sourceId = `ghost-${randomUUID().slice(0, 8)}`;+ const managed = opts.managed !== false;+ try {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ if (managed) await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ await run({ root, home, sourceId, ctx });+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);+ rmSync(dir, { recursive: true, force: true });+ }+}++const page = (title: string) => `---\ntype: note\ntitle: ${title}\n---\n\n${title} body.\n`;+const put = (ctx: OperationContext, slug: string) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: page(slug), request_id: randomUUID() } });+const live = async (sourceId: string, slug: string) => (await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]))[0]!.n === 1;++async function capture(fn: () => Promise<void>): Promise<string> {+ let printed = '';+ const original = console.log, write = process.stdout.write;+ console.log = (...parts: unknown[]) => { printed += `${parts.map(String).join(' ')}\n`; };+ process.stdout.write = ((chunk: string | Uint8Array) => { printed += String(chunk); return true; }) as typeof process.stdout.write;+ try { await fn(); } finally { console.log = original; process.stdout.write = write; }+ return printed;+}++async function refusal(fn: () => Promise<unknown>): Promise<OperationError> {+ try { await fn(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++const repair = async (sourceId: string, opts: { apply?: boolean; expect?: string } = {}) => (await repairRunner(engine, { apply: opts.apply === true, logger }))+ .run('ghost-pages', await resolveRepairScope(engine, sourceId), { explicit: true, sourceFlag: sourceId, expect: opts.expect });++/** notes/agrees (file matches), notes/drift (file edited), notes/ghost (file removed), scratch/kept (declared db_only, file removed), notes/gone (deleted). */+async function seed(f: Fixture): Promise<string> {+ writeFileSync(join(f.root, 'gbrain.yml'), 'storage:\n db_only:\n - scratch/\n');+ for (const slug of ['notes/agrees', 'notes/drift', 'notes/ghost', 'scratch/kept', 'notes/gone']) await put(f.ctx, slug);+ writeFileSync(join(f.root, 'notes/drift.md'), readFileSync(join(f.root, 'notes/drift.md'), 'utf8').replace('body.', 'body, edited in the file only.'));+ const ghostBytes = readFileSync(join(f.root, 'notes/ghost.md'), 'utf8');+ unlinkSync(join(f.root, 'notes/ghost.md'));+ if (existsSync(join(f.root, 'scratch/kept.md'))) unlinkSync(join(f.root, 'scratch/kept.md'));+ const gone = (await engine.readPageSnapshot('notes/gone', { sourceId: f.sourceId }))!;+ await submitPageMutation(f.ctx, { operation: 'delete_page', params: { slug: 'notes/gone', expected_revision: gone.revision, request_id: randomUUID() } });+ return ghostBytes;+}++for (const backend of testBackends()) describe(`#6696 B5 ghost pages (${backend})`, () => {+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (backend === 'pglite') {+ const pglite = new PGLiteEngine();+ await pglite.connect({}); await pglite.initSchema(); engine = pglite;+ } else {+ const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase());+ engine = pg.engine; closePostgres = pg.close;+ }+ }, 120_000);+ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ if (closePostgres) await closePostgres(); else await engine.disconnect();+ });+ beforeEach(() => _resetCliExitVerdictForTests());+ afterEach(() => { installFaultHook(undefined); _resetCliExitVerdictForTests(); });++ test('one classifier: a missing canonical file is a ghost; agrees, drift, declared db_only and deleted pages are not', () => fixture(async f => {+ await seed(f);+ expect((await liveFileDrift(engine, f.sourceId, 'notes/ghost')).reason).toBe('canonical_file_missing');+ expect((await liveFileDrift(engine, f.sourceId, 'notes/drift')).reason).toBe('file_database_drift');+ expect((await liveFileDrift(engine, f.sourceId, 'notes/agrees')).reason).toBe('agrees');+ expect((await liveFileDrift(engine, f.sourceId, 'scratch/kept')).reason).toBe('database_only');+ const summary = await readGhostPages(engine, { sourceIds: [f.sourceId] });+ expect(summary).toMatchObject({ status: 'known', count: 1, truncated: false, exact: true,+ by_source: [{ source_id: f.sourceId, count: 1, status: 'known' }] });+ expect(summary.samples).toEqual([{ source_id: f.sourceId, slug: 'notes/ghost', path: 'notes/ghost.md', revision: expect.any(String), page_id: expect.any(Number) }]);+ expect(summary.inspected).toBe(4);+ expect((await ghostPageNow(engine, f.sourceId, 'notes/agrees')).ghost).toBeNull();+ }));++ test('doctor ghost_pages counts the ghosts with bounded samples and the read-only preview as its fix', () => fixture(async f => {+ await seed(f);+ const [check] = await ghostPagesEntry.run({ engine } as never) as Array<Record<string, any>>;+ expect(check).toMatchObject({ name: 'ghost_pages', status: 'warn', details: { count: 1, inspected: 4, truncated: false, exact: true } });+ expect(check.details.samples.map((s: { slug: string }) => s.slug)).toEqual(['notes/ghost']);+ expect(check.fix).toMatchObject({ argv: ['gbrain', 'repair', 'ghost-pages', '--source', f.sourceId, '--json'], consent: [], actor: 'agent',+ requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'ghost_pages', '--json'] }, docs: 'docs/guides/repair.md#ghost-pages' });+ expect(check.message).toContain(`gbrain repair ghost-pages --source ${f.sourceId}`);+ expect(categorizeCheck('ghost_pages')).toBe('brain');+ expect(repairForCheck('ghost_pages')?.kind).toBe('ghost-pages');+ }));++ test('off the owner host doctor is ok/info, pages ghosts and the repair refuse not_owner_host', () => fixture(async f => {+ await seed(f);+ const hash = (await repair(f.sourceId)).preview_hash!;+ await withEnv({ GBRAIN_HOME: join(f.home, '..', 'other-host') }, async () => {+ const [check] = await ghostPagesEntry.run({ engine } as never) as Array<Record<string, any>>;+ expect(check).toMatchObject({ name: 'ghost_pages', status: 'ok', severity: 'info', readiness_state: 'not_applicable' });+ expect((await readGhostPages(engine, { sourceIds: [f.sourceId] })).reason).toBe('not_owner_host');+ expect((await refusal(() => runPagesGhosts(engine, ['--source', f.sourceId, '--json']))).code).toBe('not_owner_host');+ expect((await refusal(() => repair(f.sourceId))).code).toBe('not_owner_host');+ expect((await refusal(() => repair(f.sourceId, { apply: true, expect: hash }))).code).toBe('not_owner_host');+ });+ expect(await live(f.sourceId, 'notes/ghost')).toBe(true);+ }));++ test('pages ghosts --json lists the ghost with its recorded path and revision', () => fixture(async f => {+ await seed(f);+ const out = JSON.parse(await capture(() => runPagesGhosts(engine, ['--source', f.sourceId, '--json'])));+ expect(out).toMatchObject({ source_id: f.sourceId, status: 'known', count: 1, inspected: 4, truncated: false, exact: true });+ expect(out.ghosts).toEqual([{ source_id: f.sourceId, slug: 'notes/ghost', path: 'notes/ghost.md', revision: expect.any(String), page_id: expect.any(Number) }]);+ expect(out.next[0]).toContain(`gbrain repair ghost-pages --source ${f.sourceId}`);+ }));++ test('the exact argv the terminal classifier prints is a read-only preview that prints the apply command with its hash', () => fixture(async f => {+ await seed(f);+ const verdict = classifyTerminal({ source_id: f.sourceId, slug: 'notes/ghost', operation: 'put_page', state: 'conflict', error_code: 'source_changed',+ error_detail: null, error_message: 'The canonical file was removed outside coordinated publication.', recovery: null, blocked_reason: null, compacted: false })!;+ expect(verdict.action.argv).toEqual(['gbrain', 'repair', 'ghost-pages', '--source', f.sourceId]);+ const out = await capture(() => runRepairCommand(engine, verdict.action.argv!.slice(2)));+ expect(out).toContain('ghost-pages: 1 item(s) to repair');+ expect(out).toContain(`canonical_file_missing: ${f.sourceId}:notes/ghost (file notes/ghost.md is missing`);+ expect(out).toMatch(new RegExp(`apply: gbrain repair ghost-pages --source ${f.sourceId} --apply --expect [0-9a-f]{64} --yes`));+ expect(out).toContain('gbrain restore <slug> --force');+ expect(out).toContain('72 h');+ expect(await live(f.sourceId, 'notes/ghost')).toBe(true);+ }));++ test('preview, consent refusal with zero changes, then apply soft-deletes exactly the previewed set', () => fixture(async f => {+ await seed(f);+ expect(repairSpec('ghost-pages')).toMatchObject({ explicit_only: true, preview_bound: true, consent: 'destructive', embeds: 'none', checks: ['ghost_pages'] });+ expect(EXPLICIT_REPAIR_REGISTRY.map(spec => spec.kind)).toContain('ghost-pages');+ expect(AUTO_REPAIR_REGISTRY.map(spec => spec.kind)).not.toContain('ghost-pages');+ const preview = JSON.parse(await capture(() => runRepairCommand(engine, ['ghost-pages', '--source', f.sourceId, '--json']))).results[0];+ expect(preview.listing.map((entry: { item: string }) => entry.item)).toEqual([`${f.sourceId}:notes/ghost`]);+ expect(preview.apply_command).toBe(`gbrain repair ghost-pages --source ${f.sourceId} --apply --expect ${preview.preview_hash} --yes`);+ const requests = async () => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1', [f.sourceId]))[0]!.n);+ const before = await requests();++ const priorExitCode = process.exitCode;+ const refused = await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() =>+ runRepairCommand(engine, ['ghost-pages', '--source', f.sourceId, '--apply', '--expect', preview.preview_hash, '--json'])));+ expect(currentExitCode()).toBe(3);+ process.exitCode = priorExitCode ?? 0;+ expect(refused).toContain('user_message');+ expect(refused).toContain('gbrain restore <slug> --force');+ expect(await live(f.sourceId, 'notes/ghost')).toBe(true);+ expect(await requests()).toBe(before);+ _resetCliExitVerdictForTests();++ const applied = JSON.parse(await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() =>+ runRepairCommand(engine, ['ghost-pages', '--source', f.sourceId, '--apply', '--expect', preview.preview_hash, '--yes', '--json'])))).results[0];+ expect(applied).toMatchObject({ mode: 'apply', applied: 1, skipped: 0, failed: [], complete: true, outcomes: { soft_deleted: 1 } });+ expect(await live(f.sourceId, 'notes/ghost')).toBe(false);+ for (const slug of ['notes/agrees', 'notes/drift', 'scratch/kept']) expect(await live(f.sourceId, slug)).toBe(true);+ expect((await readGhostPages(engine, { sourceIds: [f.sourceId] })).count).toBe(0);+ }));++ test('the mass-delete valve refuses when ghosts are over half of the file-backed pages', () => fixture(async f => {+ const slugs = Array.from({ length: 22 }, (_, i) => `notes/page-${String(i).padStart(2, '0')}`);+ for (const slug of slugs) await put(f.ctx, slug);+ for (const slug of slugs.slice(0, 12)) unlinkSync(join(f.root, `${slug}.md`));+ const preview = await repair(f.sourceId);+ expect(preview.affected).toBe(12);+ expect(preview.residuals).toMatchObject({ ghosts: 12, file_backed: 22 });+ expect(preview.warnings?.[0]).toContain('ghost_mass_delete_refused');+ const error = await refusal(() => repair(f.sourceId, { apply: true, expect: preview.preview_hash }));+ expect(error.code).toBe('ghost_mass_delete_refused');+ for (const slug of slugs) expect(await live(f.sourceId, slug)).toBe(true);+ }));++ test('a file restored between preview and apply keeps its page and asks for a new preview', () => fixture(async f => {+ const bytes = await seed(f);+ const preview = await repair(f.sourceId);+ writeFileSync(join(f.root, 'notes/ghost.md'), bytes);+ const applied = await repair(f.sourceId, { apply: true, expect: preview.preview_hash });+ expect(applied).toMatchObject({ applied: 0, skipped: 1, outcomes: { file_restored: 1 } });+ expect(applied.outcome_items![0]!.reason).toContain(`gbrain repair ghost-pages --source ${f.sourceId}`);+ expect(await live(f.sourceId, 'notes/ghost')).toBe(true);+ }));++ for (const point of ['consumer:preparing', 'consumer:prepared'] as const) {+ test(`a file restored at ${point} is refused by the ${point === 'consumer:preparing' ? 'preparer' : 'filesystem publication'} and the page is kept`, () => fixture(async f => {+ const bytes = await seed(f);+ const preview = await repair(f.sourceId);+ installFaultHook((at, detail) => {+ if (at === point && detail.operation === 'submit_job') writeFileSync(join(f.root, 'notes/ghost.md'), bytes);+ });+ const applied = await repair(f.sourceId, { apply: true, expect: preview.preview_hash });+ expect(applied).toMatchObject({ applied: 0, outcomes: { file_restored: 1 } });+ expect(await live(f.sourceId, 'notes/ghost')).toBe(true);+ expect(readFileSync(join(f.root, 'notes/ghost.md'), 'utf8')).toBe(bytes);+ }));+ }++ test('an unmanaged brain soft-deletes the approved ghost directly', () => fixture(async f => {+ mkdirSync(join(f.root, 'notes'));+ for (const slug of ['notes/one', 'notes/two']) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `${slug} body.` }, { sourceId: f.sourceId });+ await engine.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [f.sourceId, slug, `${slug}.md`]);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: f.sourceId }))!;+ const { serializePageToMarkdown } = await import('../src/core/markdown.ts');+ writeFileSync(join(f.root, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));+ }+ unlinkSync(join(f.root, 'notes/two.md'));+ const preview = await repair(f.sourceId);+ expect(preview.sample).toEqual([`${f.sourceId}:notes/two`]);+ const applied = await repair(f.sourceId, { apply: true, expect: preview.preview_hash });+ expect(applied).toMatchObject({ applied: 1, outcomes: { soft_deleted: 1 } });+ expect(await live(f.sourceId, 'notes/two')).toBe(false);+ expect(await live(f.sourceId, 'notes/one')).toBe(true);+ }, { managed: false }));+});diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex e5335d51c4..b008a0c8e8 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'];+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'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));