Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): ghost-pages lists shared-skillpack ghosts apart and records per-item refusals (#6910)

garrytan75178ee1bdb0
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 27997f9332..a8f8504e19 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -965,6 +965,30 @@ database only and are never ghosts. Doctor `undeclared_db_only_pages` is a
separate audit. A preview lists at most 1,000 ghosts; apply them, then preview
again for the rest. Sync never removes ghost pages by itself.
+<a id="ghost-pages-skill-paths"></a>
+**Ghosts under the shared skillpack.** When a source has an adopted shared
+skillpack, its reserved paths (`skills/` and `skillpack.json`) belong to the
+shared skill publisher. A knowledge page on such a path whose file is gone (a
+legacy import from before the pack was adopted, say) is still a ghost, but no
+knowledge write can remove it: every one, a soft delete included, refuses
+`skill_bundle_required`, and `put_skill` / `delete_skill` change skill
+bundles, not knowledge pages. No gbrain command removes such a page today, so
+the preview lists it apart (class `skill_path`, `residuals.skill_paths`, and
+`details.skill_paths` with the first slugs, `owned_by: shared_skill_publisher`
+and `route: null`), leaves it out of the hash and never applies it; the other
+ghosts apply as usual. Doctor `ghost_pages` and `gbrain pages ghosts` count
+these pages apart too (`skill_paths`), never as ghosts waiting for this
+repair. A page on a `skills/` path of a source with no adopted pack is an
+ordinary ghost.
+
+**`refused`.** A page of the approved set that a per-page guard still refuses
+during the apply (a refusal of class `caller`, such as `skill_bundle_required`
+on a page an older preview approved) is recorded with outcome `refused` and its
+code in `outcome_items`; nothing is written for it, and the apply goes on with
+the rest of the set. Read the code (`gbrain errors <code>`) before retrying
+that page. Any other error, such as a storage fault, an unavailable owner or
+contention, still stops the apply; rerun the same apply command once it clears.
+
<a id="rename-identity"></a>
### Rename identity
diff --git a/src/commands/doctor/checks/ghost-pages.ts b/src/commands/doctor/checks/ghost-pages.ts
index 5edebf39a7..2a76292d25 100644
--- a/src/commands/doctor/checks/ghost-pages.ts
+++ b/src/commands/doctor/checks/ghost-pages.ts
@@ -12,12 +12,16 @@
* 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.
+ * `undeclared_db_only_pages` stays a separate audit. #6910: ghosts under an
+ * adopted shared skillpack are counted apart (`details.skill_paths`) and never
+ * as knowledge ghosts awaiting `gbrain repair ghost-pages`, which cannot remove
+ * them; on their own they leave the check `ok` with a note.
*/
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';
+import { SKILL_PATH_NOTE } from '../../../core/repair/ghost-pages.ts';
const DOCS = 'docs/guides/repair.md#ghost-pages';
@@ -26,7 +30,11 @@ async function runGhostPages(ctx: DoctorContext): Promise<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 };
+ truncated: summary.truncated, exact: summary.exact, docs: DOCS,
+ ...(summary.skill_paths ? { skill_paths: { count: summary.skill_paths, samples: summary.skill_path_samples, owned_by: 'shared_skill_publisher', route: null, note: SKILL_PATH_NOTE } } : {}) };
+ const skillNote = summary.skill_paths
+ ? ` ${summary.skill_paths} more under the shared skillpack are counted apart (${summary.skill_path_samples.map(page => `${page.source_id}:${page.slug}`).join(', ')}): no gbrain command removes them today, and they do not block the rest.`
+ : '';
const ghostSources = summary.by_source.filter(entry => entry.count > 0);
const unknown = summary.by_source.filter(entry => entry.status === 'unknown');
if (ghostSources.length) {
@@ -35,7 +43,7 @@ async function runGhostPages(ctx: DoctorContext): Promise<Check[]> {
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.`,
+ + ` Preview the removal with gbrain repair ghost-pages --source ${first}; to keep a page instead, restore its file at the recorded path and sync.${skillNote}`,
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 }) });
@@ -57,7 +65,7 @@ async function runGhostPages(ctx: DoctorContext): Promise<Check[]> {
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' : ''}).` });
+ message: `No live page is missing its canonical file (${summary.inspected} page(s) inspected${summary.truncated ? '; bounded, more not checked' : ''}).${skillNote}` });
} catch (error) {
checks.push(checkError('ghost_pages', 'check live pages for a missing canonical file', error, { details: { count: 'unknown', health: 'unknown', docs: DOCS } }));
}
diff --git a/src/commands/pages-ghosts.ts b/src/commands/pages-ghosts.ts
index 11d4c0c123..e7e7f1fbe7 100644
--- a/src/commands/pages-ghosts.ts
+++ b/src/commands/pages-ghosts.ts
@@ -10,7 +10,7 @@ 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';
+import { GHOST_CONSEQUENCES, GHOST_REPAIR_LIMIT, SKILL_PATH_NOTE, ghostPreviewCommand, ghostScanRefusal } from '../core/repair/ghost-pages.ts';
export const PAGES_GHOSTS_USAGE = 'Usage: gbrain pages ghosts [--source <id>] [--json]';
@@ -34,12 +34,15 @@ export async function runPagesGhosts(engine: BrainEngine, args: string[]): Promi
const next = scan.ghosts.length
? [`Preview the removal: ${ghostPreviewCommand(sourceId)} (writes nothing; apply only after the user agrees).`, GHOST_CONSEQUENCES.keep]
: [];
+ if (scan.skill_paths.length) next.push(SKILL_PATH_NOTE);
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));
+ ghosts: scan.ghosts, ...(scan.skill_paths.length ? { skill_paths: scan.skill_paths } : {}), 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}`);
+ if (scan.skill_paths.length) console.log(`${scan.skill_paths.length} more under the shared skillpack (listed apart, not removable today):`);
+ for (const ghost of scan.skill_paths) console.log(` ${ghost.slug} missing ${ghost.path} revision ${ghost.revision}`);
for (const line of next) console.log(line);
}
diff --git a/src/core/ghost-pages.ts b/src/core/ghost-pages.ts
index 3de36bffd7..86f679fc8d 100644
--- a/src/core/ghost-pages.ts
+++ b/src/core/ghost-pages.ts
@@ -21,6 +21,12 @@
* invalid gbrain.yml or a check that ends in any other reason
* (`ambiguous_storage`) make it `unknown`, never a count of zero.
*
+ * #6910: a ghost on a reserved shared-skillpack path (`isReservedSkillBundlePath`, the
+ * predicate sync discovery and managed import use) that the knowledge guard refuses to
+ * retire (`skill_bundle_required`: the source has an adopted shared skillpack) is not a
+ * knowledge ghost: it is reported apart as a skill path (`skill_paths`), never in the
+ * approved set, because no knowledge write can remove it.
+ *
* 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).
@@ -37,6 +43,9 @@ 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';
+import { isReservedSkillBundlePath } from './skill-reserved-paths.ts';
+import { assertKnowledgePublicationAllowed } from './shared-skills/knowledge-guard.ts';
+import { OperationError } from './ops/contract.ts';
export interface GhostPage { source_id: string; slug: string; path: string; revision: string; page_id: number }
export interface GhostPagesSummary {
@@ -45,9 +54,13 @@ export interface GhostPagesSummary {
reason?: string;
/** Ghosts found among inspected pages. */
count: number;
- by_source: Array<{ source_id: string; count: number; status: 'known' | 'unknown' | 'not_applicable'; reason?: string }>;
+ by_source: Array<{ source_id: string; count: number; status: 'known' | 'unknown' | 'not_applicable'; reason?: string; skill_paths?: number }>;
/** Bounded by `sampleLimit`. */
samples: GhostPage[];
+ /** #6910: ghosts under an adopted shared skillpack, which no knowledge write can retire; not in `count`. */
+ skill_paths: number;
+ /** Bounded by `sampleLimit`. */
+ skill_path_samples: GhostPage[];
inspected: number;
truncated: boolean;
exact: boolean;
@@ -61,6 +74,8 @@ export interface GhostSourceScan {
status: 'known' | 'unknown' | 'not_applicable';
reason?: string;
ghosts: GhostPage[];
+ /** #6910: confirmed ghosts on a reserved shared-skillpack path the knowledge guard refuses to retire; never in `ghosts`. */
+ skill_paths: 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. */
@@ -141,6 +156,18 @@ async function confirm(engine: BrainEngine, context: Extract<SourceContext, { ok
return { kind: 'unknown', reason: live.reason === 'not_owner_host' ? 'not_owner_host' : 'ambiguous_storage' };
}
+/** #6910: a ghost on a reserved skillpack path whose retirement the shared-skillpack knowledge guard refuses. */
+async function underSharedSkillpack(engine: BrainEngine, owner: GhostOwner, ghost: GhostPage): Promise<boolean> {
+ if (!isReservedSkillBundlePath(ghost.path) && !isReservedSkillBundlePath(ghost.slug)) return false;
+ try {
+ await assertKnowledgePublicationAllowed(engine, { source_id: ghost.source_id, source_incarnation: owner.source_incarnation, slug: ghost.slug, target_kind: 'page' });
+ return false;
+ } catch (error) {
+ if (error instanceof OperationError && error.code === 'skill_bundle_required') return true;
+ throw error;
+ }
+}
+
/**
* 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`.
@@ -148,7 +175,7 @@ async function confirm(engine: BrainEngine, context: Extract<SourceContext, { ok
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 };
+ const scan: GhostSourceScan = { source_id: sourceId, status: 'known', ghosts: [], skill_paths: [], 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;
@@ -167,13 +194,13 @@ export async function scanGhostSource(engine: BrainEngine, sourceId: string, opt
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);
+ if (result.kind === 'ghost') (await underSharedSkillpack(engine, context.owner, result.ghost) ? scan.skill_paths : 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;
+ scan.file_backed += scan.ghosts.length + scan.skill_paths.length + unchecked;
return scan;
}
@@ -198,12 +225,15 @@ export async function readGhostPages(engine: BrainEngine, opts: { sourceIds?: st
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 skillPaths = scans.reduce((sum, scan) => sum + scan.skill_paths.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 } : {}) })),
+ by_source: scans.map(scan => ({ source_id: scan.source_id, count: scan.ghosts.length, status: scan.status, ...(scan.reason ? { reason: scan.reason } : {}),
+ ...(scan.skill_paths.length ? { skill_paths: scan.skill_paths.length } : {}) })),
samples: scans.flatMap(scan => scan.ghosts).slice(0, opts.sampleLimit ?? GHOST_SAMPLE_LIMIT),
+ skill_paths: skillPaths, skill_path_samples: scans.flatMap(scan => scan.skill_paths).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/repair/ghost-pages.ts b/src/core/repair/ghost-pages.ts
index d3c9d91619..67a1758e6e 100644
--- a/src/core/repair/ghost-pages.ts
+++ b/src/core/repair/ghost-pages.ts
@@ -18,6 +18,12 @@
* came back is skipped (`file_restored`) and the result asks for a new
* preview; any other change is `changed_since_preview`.
*
+ * #6910: ghosts under an adopted shared skillpack (`skill_paths`, `src/core/ghost-pages.ts`) are listed
+ * apart and never approved: the knowledge guard refuses every knowledge write to them and no gbrain
+ * command removes them today. A page of the approved set that an item-level guard still refuses (a
+ * registry `caller` refusal such as `skill_bundle_required`) is recorded `refused` with its code
+ * and the apply continues; any other error (storage, contention, owner) still stops it.
+ *
* 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
@@ -33,6 +39,7 @@ 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 { CODES } from '../error-registry.ts';
import { readFix } from '../ops/op-fix.ts';
import { authorizeWrite } from '../persistence/authority.ts';
import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';
@@ -50,6 +57,12 @@ 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.';
+/** Skill-path slugs a preview lists by name. */
+const SKILL_PATH_SAMPLE = 20;
+/** #6910: why a ghost under the shared skillpack is left alone; the preview, `gbrain pages ghosts` and doctor say it. */
+export const SKILL_PATH_NOTE = 'Ghost pages under the source\'s adopted shared skillpack (skills/, skillpack.json) are knowledge pages the shared skill publisher owns the path of: '
+ + 'every knowledge write to them, a soft delete included, refuses skill_bundle_required, and put_skill/delete_skill change skill bundles, not knowledge pages, so no gbrain command removes them today. '
+ + 'They are listed apart, never applied, and do not block the other ghosts.';
interface ApprovedGhost extends GhostPage { owner: GhostOwner; selection: string[] }
interface GhostItem extends RepairItem { ghost: GhostPage; owner: GhostOwner; hash: string; last: boolean }
@@ -132,20 +145,26 @@ export const ghostPagesRepair: RepairHandler = {
if (refusal) throw refusal;
const mass = massGhosts(scan.ghosts.length, scan.file_backed);
if (!opts?.apply) {
+ const skillPaths = scan.skill_paths.length;
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.`] : []),
+ ...(skillPaths ? [`${skillPaths} ghost page(s) under the shared skillpack are listed apart (skill_path) and not applied: ${SKILL_PATH_NOTE}`] : []),
...(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',
+ residuals: { ghosts: scan.ghosts.length, file_backed: scan.file_backed, inspected: scan.inspected, ...(skillPaths ? { skill_paths: skillPaths } : {}) },
+ 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 } };
+ ...scan.skill_paths.map(ghost => ({ item: `${ghost.source_id}:${ghost.slug}`, class: 'skill_path',
+ detail: `file ${ghost.path} is missing under the shared skillpack; not applied (no command removes it today)` }))],
+ 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,
+ ...(skillPaths ? { skill_paths: { count: skillPaths, slugs: scan.skill_paths.slice(0, SKILL_PATH_SAMPLE).map(ghost => ghost.slug),
+ owned_by: 'shared_skill_publisher', route: null, note: SKILL_PATH_NOTE, docs: DOCS } } : {}) } };
}
if (!opts.expect) {
throw opError('invalid_params', 'gbrain repair ghost-pages --apply removes only the set a preview printed.',
@@ -163,7 +182,13 @@ export const ghostPagesRepair: RepairHandler = {
},
async apply(ctx, entry): Promise<RepairItemOutcome> {
const { ghost, owner, hash, last } = entry as GhostItem;
- const outcome = await retireGhost(ctx, ghost, owner, () => repairRequestId(ctx, 'ghost-pages', ghost, ghost.revision));
+ let outcome: RepairItemOutcome;
+ try {
+ outcome = await retireGhost(ctx, ghost, owner, () => repairRequestId(ctx, 'ghost-pages', ghost, ghost.revision));
+ } catch (error) {
+ if (!(error instanceof OperationError) || (CODES as Record<string, { class: string } | undefined>)[error.code]?.class !== 'caller') throw error;
+ outcome = { applied: false, outcome: 'refused', reason: error.code, detail: { message: error.message } };
+ }
if (last) await clearApprovedSet(ctx.engine, { command: 'ghost-pages', hash });
return outcome;
},
diff --git a/test/ghost-pages-skill-paths-6910.test.ts b/test/ghost-pages-skill-paths-6910.test.ts
new file mode 100644
index 0000000000..8f43035464
--- /dev/null
+++ b/test/ghost-pages-skill-paths-6910.test.ts
@@ -0,0 +1,154 @@
+/**
+ * #6910: `gbrain repair ghost-pages` on a source with an adopted shared skillpack.
+ *
+ * A legacy knowledge page under `skills/` whose file is gone is a ghost the knowledge guard refuses to retire
+ * (`skill_bundle_required`). Protects: such a page is listed apart (`skill_path`, `residuals.skill_paths`,
+ * `details.skill_paths`) and never enters the approved set, so the apply retires every ordinary ghost even when the
+ * skill page comes first in page-id order; doctor `ghost_pages` and `gbrain pages ghosts` count it apart; and a per-item
+ * `caller` refusal during the apply is recorded `refused` with its code while the rest of the approved set still applies.
+ * Every case drives a real PGLite brain with a claimed canonical worktree.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import { opError } from '../src/core/ops/contract.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';
+import { adoptSharedSkillpack } from '../src/core/shared-skills/publication.ts';
+import { setSharedSkillPolicy } from '../src/core/shared-skills/policy.ts';
+import { readGhostPages } from '../src/core/ghost-pages.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { runPagesGhosts } from '../src/commands/pages-ghosts.ts';
+import { ghostPagesEntry } from '../src/commands/doctor/checks/ghost-pages.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const logger = { info() {}, warn() {}, error() {} };
+const SOURCE = 'default';
+const SKILL = 'skills/legacy-skill/notes';
+const ORDINARY = ['notes/a', 'notes/b', 'notes/c'];
+
+interface Fixture { engine: BrainEngine; root: string }
+
+/**
+ * A legacy knowledge page under skills/ (lowest page id, imported before the pack was adopted), three ordinary pages and
+ * one kept page, all file-backed; then the shared skillpack is adopted on the source (pack root = source root) and every
+ * file but the kept one is removed.
+ */
+async function fixture(run: (f: Fixture) => Promise<void>): Promise<void> {
+ const scratch = mkdtempSync(join(tmpdir(), 'gbrain-ghost-skills-'));
+ try {
+ await withEnv({ GBRAIN_HOME: join(scratch, 'home'), DATABASE_URL: undefined }, async () => {
+ const isolated = await isolatedSharedSkillsEngine();
+ const engine = isolated.engine;
+ try {
+ const root = join(scratch, 'brain'); mkdirSync(root);
+ execFileSync('git', ['init', '-q'], { cwd: root });
+ writeFileSync(join(root, 'skillpack.json'), JSON.stringify({ api_version: 'gbrain-skillpack-v1', name: 'example-pack', version: '1.0.0',
+ description: 'Synthetic fixture', author: 'Example Maintainer', license: 'MIT', homepage: 'https://example.com/skills',
+ gbrain_min_version: '0.51.0', brain_resident: true, skills: ['skills/alpha'] }));
+ await engine.executeRaw('UPDATE sources SET local_path=$1 WHERE id=$2', [root, SOURCE]);
+ for (const slug of [SKILL, ...ORDINARY, 'notes/keep']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `${slug} body.` }, { sourceId: SOURCE });
+ await engine.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [SOURCE, slug, `${slug}.md`]);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: SOURCE }))!;
+ mkdirSync(dirname(join(root, `${slug}.md`)), { recursive: true });
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));
+ }
+ await claimWorktree(engine, SOURCE, root);
+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });
+ const ctx: OperationContext = { engine, config: { engine: engine.kind }, remote: false, sourceId: SOURCE, dryRun: false, logger };
+ await engine.setConfig('mcp.publish_skills', 'true');
+ await setSharedSkillPolicy(ctx, SOURCE, { version: 1, enabled: true, classes: ['prose'], audiences: ['readers'], requirements: [], allow_follow: true }, null);
+ const adopted = await adoptSharedSkillpack(ctx, SOURCE, { request_id: randomUUID(), pack_id: 'example-pack', skills: [
+ { pack_id: 'example-pack', name: 'alpha', expected_revision: null, files: [
+ { path: 'skills/alpha/SKILL.md', content: '---\nname: alpha\ndescription: A synthetic shared skill\n---\n\nApproved instructions.\n', file_class: 'prose' },
+ ] },
+ ] });
+ expect(adopted.receipts[0].state).toBe('committed');
+ for (const slug of [SKILL, ...ORDINARY]) unlinkSync(join(root, `${slug}.md`));
+ await run({ engine, root });
+ } finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); await isolated.close(); }
+ });
+ } finally { rmSync(scratch, { recursive: true, force: true }); }
+}
+
+const live = async (engine: BrainEngine, 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', [SOURCE, slug]))[0]!.n === 1;
+const repair = async (engine: BrainEngine, opts: { apply?: boolean; expect?: string } = {}) => (await repairRunner(engine, { apply: opts.apply === true, logger }))
+ .run('ghost-pages', await resolveRepairScope(engine, SOURCE), { explicit: true, sourceFlag: SOURCE, expect: opts.expect });
+
+async function capture(fn: () => Promise<void>): Promise<string> {
+ let printed = '';
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { printed += `${parts.map(String).join(' ')}\n`; };
+ try { await fn(); } finally { console.log = original; }
+ return printed;
+}
+
+describe('#6910 ghost pages under the shared skillpack', () => {
+ afterEach(() => installFaultHook(undefined));
+
+ test('the skill-path ghost is listed apart and every ordinary ghost is retired, though it comes first in page-id order', () => fixture(async f => {
+ const preview = await repair(f.engine);
+ expect(preview.affected).toBe(3);
+ expect(preview.residuals).toMatchObject({ ghosts: 3, skill_paths: 1 });
+ expect(preview.listing!.filter(entry => entry.class === 'canonical_file_missing').map(entry => entry.item)).toEqual(ORDINARY.map(slug => `${SOURCE}:${slug}`));
+ expect(preview.listing!.filter(entry => entry.class === 'skill_path').map(entry => entry.item)).toEqual([`${SOURCE}:${SKILL}`]);
+ expect(preview.details).toMatchObject({ skill_paths: { count: 1, slugs: [SKILL], owned_by: 'shared_skill_publisher', route: null } });
+ expect(String((preview.details as { skill_paths: { note: string } }).skill_paths.note)).toContain('no gbrain command removes them today');
+
+ const applied = await repair(f.engine, { apply: true, expect: preview.preview_hash });
+ expect(applied).toMatchObject({ applied: 3, failed: [], complete: true, outcomes: { soft_deleted: 3 } });
+ for (const slug of ORDINARY) expect(await live(f.engine, slug)).toBe(false);
+ expect(await live(f.engine, SKILL)).toBe(true);
+ expect(await live(f.engine, 'notes/keep')).toBe(true);
+
+ const after = await repair(f.engine);
+ expect(after.affected).toBe(0);
+ expect(after.residuals).toMatchObject({ ghosts: 0, skill_paths: 1 });
+ }), 120_000);
+
+ test('doctor ghost_pages and pages ghosts count the skill-path ghost apart, not as a knowledge ghost awaiting the repair', () => fixture(async f => {
+ const summary = await readGhostPages(f.engine, { sourceIds: [SOURCE] });
+ expect(summary).toMatchObject({ count: 3, skill_paths: 1, by_source: [{ source_id: SOURCE, count: 3, skill_paths: 1 }] });
+ expect(summary.samples.map(ghost => ghost.slug)).toEqual(ORDINARY);
+ expect(summary.skill_path_samples.map(ghost => ghost.slug)).toEqual([SKILL]);
+
+ const out = JSON.parse(await capture(() => runPagesGhosts(f.engine, ['--source', SOURCE, '--json'])));
+ expect(out.count).toBe(3);
+ expect(out.ghosts.map((ghost: { slug: string }) => ghost.slug)).toEqual(ORDINARY);
+ expect(out.skill_paths.map((ghost: { slug: string }) => ghost.slug)).toEqual([SKILL]);
+
+ const preview = await repair(f.engine);
+ await repair(f.engine, { apply: true, expect: preview.preview_hash });
+ const [check] = await ghostPagesEntry.run({ engine: f.engine } as never) as Array<Record<string, any>>;
+ expect(check).toMatchObject({ name: 'ghost_pages', status: 'ok', details: { count: 0, skill_paths: { count: 1, owned_by: 'shared_skill_publisher', route: null } } });
+ expect(check.details.skill_paths.samples.map((ghost: { slug: string }) => ghost.slug)).toEqual([SKILL]);
+ expect(check.message).toContain(`${SOURCE}:${SKILL}`);
+ }), 120_000);
+
+ test('a per-item caller refusal during the apply is recorded refused with its code and the rest still applies', () => fixture(async f => {
+ const preview = await repair(f.engine);
+ installFaultHook(async (at, detail) => {
+ if (at !== 'consumer:preparing' || detail.operation !== 'submit_job') return;
+ const [row] = await f.engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE id=$1', [detail.writeId]);
+ if (row?.slug === 'notes/b') throw opError('skill_bundle_required', 'Knowledge writes cannot change the canonical shared skillpack.', 'Forced per-item refusal.');
+ });
+ const applied = await repair(f.engine, { apply: true, expect: preview.preview_hash });
+ expect(applied).toMatchObject({ applied: 2, outcomes: { soft_deleted: 2, refused: 1 } });
+ expect(applied.outcome_items!.find(item => item.item === `${SOURCE}:notes/b`)).toMatchObject({ outcome: 'refused', reason: 'skill_bundle_required' });
+ expect(await live(f.engine, 'notes/a')).toBe(false);
+ expect(await live(f.engine, 'notes/b')).toBe(true);
+ expect(await live(f.engine, 'notes/c')).toBe(false);
+ }), 120_000);
+});