Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): ghost-pages retires non-member skills/ ghosts DB-only and lists pack members as ghost_skill_pack_member (#6910)

garrytane10772926e15
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index a8f8504e19..54c3d3d85f 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -968,18 +968,29 @@ 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.
+shared skill publisher, and knowledge writes there refuse
+`skill_bundle_required`. Two kinds of ghost can sit on those paths:
+
+- A legacy knowledge page that no live pack skill owns (imported before the
+ pack was adopted, say, under a `skills/<name>/` directory the pack does not
+ publish). It is an ordinary ghost: the preview lists it with the others and
+ the apply retires it as a database-only soft delete. Its file is already
+ gone and filesystem publication refuses one that reappears, so no pack file
+ changes.
+- A page on a path the pack owns: `skillpack.json`, a file of a live skill's
+ current revision, or anything under a live skill's `skills/<name>/`
+ directory. Its missing file is the pack's own, so the repair never removes
+ the page. The preview lists it apart with code `ghost_skill_pack_member`
+ (`residuals.skill_paths`, and `details.skill_paths` with the first slugs,
+ `owned_by: shared_skill_publisher` and one `restore` command per page) and
+ leaves it out of the hash. To clear it, restore the file on the owner host:
+ `git -C <source root> checkout -- <path>` when the file is committed, or
+ republish the skill with `put_skill` and its catalog `expected_revision` so
+ the publisher writes it again. The page then stops being a ghost.
+
+Doctor `ghost_pages` and `gbrain pages ghosts` count pack-member ghosts apart
+(`skill_paths`, with the same restore step), never as ghosts waiting for this
+repair; on their own they leave the check `ok`.
**`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`
diff --git a/src/commands/doctor/checks/ghost-pages.ts b/src/commands/doctor/checks/ghost-pages.ts
index 2a76292d25..56da0aa480 100644
--- a/src/commands/doctor/checks/ghost-pages.ts
+++ b/src/commands/doctor/checks/ghost-pages.ts
@@ -12,16 +12,17 @@
* 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. #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.
+ * `undeclared_db_only_pages` stays a separate audit. #6910: ghosts on files of
+ * an adopted shared skillpack are counted apart (`details.skill_paths`, code
+ * `ghost_skill_pack_member`, with their restore commands), never as knowledge
+ * ghosts awaiting `gbrain repair ghost-pages`, which leaves them alone; on
+ * their own they leave the check `ok` with the restore step.
*/
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';
+import { SKILL_PACK_MEMBER_CODE, skillPathDetail } from '../../../core/repair/ghost-pages.ts';
const DOCS = 'docs/guides/repair.md#ghost-pages';
@@ -31,9 +32,9 @@ async function runGhostPages(ctx: DoctorContext): Promise<Check[]> {
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,
- ...(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 } } : {}) };
+ ...(summary.skill_paths ? { skill_paths: { ...skillPathDetail(undefined, summary.skill_path_samples, summary.skill_paths), samples: summary.skill_path_samples } } : {}) };
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.`
+ ? ` ${summary.skill_paths} more are files of the shared skillpack missing from the checkout (${SKILL_PACK_MEMBER_CODE}: ${summary.skill_path_samples.map(page => `${page.source_id}:${page.slug}`).join(', ')}); the repair leaves them alone: restore each file on the owner host (git -C <source root> checkout -- <path>, or republish the skill with put_skill).`
: '';
const ghostSources = summary.by_source.filter(entry => entry.count > 0);
const unknown = summary.by_source.filter(entry => entry.status === 'unknown');
diff --git a/src/commands/pages-ghosts.ts b/src/commands/pages-ghosts.ts
index e7e7f1fbe7..04253b1a34 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, SKILL_PATH_NOTE, ghostPreviewCommand, ghostScanRefusal } from '../core/repair/ghost-pages.ts';
+import { GHOST_CONSEQUENCES, GHOST_REPAIR_LIMIT, SKILL_PATH_NOTE, ghostPreviewCommand, ghostScanRefusal, skillPathRestore } from '../core/repair/ghost-pages.ts';
export const PAGES_GHOSTS_USAGE = 'Usage: gbrain pages ghosts [--source <id>] [--json]';
@@ -42,7 +42,7 @@ export async function runPagesGhosts(engine: BrainEngine, args: string[]): Promi
}
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}`);
+ if (scan.skill_paths.length) console.log(`${scan.skill_paths.length} more are files of the shared skillpack (listed apart; the repair leaves them alone):`);
+ for (const ghost of scan.skill_paths) console.log(` ${ghost.slug} missing ${ghost.path} restore: ${skillPathRestore(scan.root, ghost)}`);
for (const line of next) console.log(line);
}
diff --git a/src/core/ghost-pages.ts b/src/core/ghost-pages.ts
index 86f679fc8d..5024f0b4fa 100644
--- a/src/core/ghost-pages.ts
+++ b/src/core/ghost-pages.ts
@@ -22,10 +22,12 @@
* (`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.
+ * predicate sync discovery and managed import use) whose path is a member of the source's
+ * adopted shared skillpack (`sharedPackMember`) is not a knowledge ghost: the pack's own
+ * file is missing, so it is reported apart (`skill_paths`, code `ghost_skill_pack_member`)
+ * and never approved. A legacy page on a reserved path that is not a pack member is an
+ * ordinary ghost; the knowledge guard lets its retirement through as a database-only
+ * soft delete.
*
* Readers: doctor `ghost_pages`, `gbrain pages ghosts` and `gbrain repair
* ghost-pages` (`scanGhostSource`, `ghostPageNow`), and the read-scope MCP
@@ -44,8 +46,7 @@ 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';
+import { sharedPackMember } from './shared-skills/knowledge-guard.ts';
export interface GhostPage { source_id: string; slug: string; path: string; revision: string; page_id: number }
export interface GhostPagesSummary {
@@ -57,7 +58,7 @@ export interface GhostPagesSummary {
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`. */
+ /** #6910: ghosts whose path is a member of an adopted shared skillpack (the pack's file is missing); not in `count`. */
skill_paths: number;
/** Bounded by `sampleLimit`. */
skill_path_samples: GhostPage[];
@@ -74,8 +75,10 @@ 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`. */
+ /** #6910: confirmed ghosts whose path is a member of the source's adopted shared skillpack; never in `ghosts`. */
skill_paths: GhostPage[];
+ /** The source's canonical root on this host, when the scan ran (the skill-path restore step names it). */
+ root?: string;
/** 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. */
@@ -156,16 +159,13 @@ 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> {
+/** #6910: a ghost on a reserved skillpack path that is a member of the source's adopted shared skillpack. */
+async function sharedPackMemberGhost(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;
- }
+ const [schema] = await engine.executeRaw<{ present: boolean }>(`SELECT to_regclass('shared_skill_packs') IS NOT NULL AS present`);
+ if (!schema?.present) return false;
+ const adopted = await engine.executeRaw('SELECT 1 FROM shared_skill_packs WHERE source_id=$1 AND source_incarnation=$2::uuid', [ghost.source_id, owner.source_incarnation]);
+ return adopted.length > 0 && sharedPackMember(engine, ghost.source_id, owner.source_incarnation, [ghost.path, `${ghost.slug}.md`]);
}
/**
@@ -178,6 +178,7 @@ export async function scanGhostSource(engine: BrainEngine, sourceId: string, opt
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;
+ scan.root = context.root;
let after = 0;
let unchecked = 0;
for (;;) {
@@ -194,7 +195,7 @@ 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') (await underSharedSkillpack(engine, context.owner, result.ghost) ? scan.skill_paths : scan.ghosts).push(result.ghost);
+ if (result.kind === 'ghost') (await sharedPackMemberGhost(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;
diff --git a/src/core/repair/ghost-pages.ts b/src/core/repair/ghost-pages.ts
index 67a1758e6e..aa60522fa5 100644
--- a/src/core/repair/ghost-pages.ts
+++ b/src/core/repair/ghost-pages.ts
@@ -18,9 +18,11 @@
* 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
+ * #6910: a ghost whose path is a member of the source's adopted shared skillpack (`skill_paths`, code
+ * `ghost_skill_pack_member`, `src/core/ghost-pages.ts`) is listed apart with its restore step and never
+ * approved: the pack's own file is missing and the shared skill publisher owns it. A legacy page on a
+ * reserved path that is not a pack member is an ordinary ghost (the knowledge guard lets its retirement
+ * through as a database-only soft delete). 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.
*
@@ -40,6 +42,7 @@ 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 { GHOST_RETIREMENT_INTENT } from '../shared-skills/knowledge-guard.ts';
import { readFix } from '../ops/op-fix.ts';
import { authorizeWrite } from '../persistence/authority.ts';
import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';
@@ -51,7 +54,7 @@ import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed }
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';
+export const GHOST_PAGES_INTENT = GHOST_RETIREMENT_INTENT;
/** 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;
@@ -59,10 +62,20 @@ 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.';
+/** #6910: the stable code of a ghost on a file of the adopted shared skillpack. */
+export const SKILL_PACK_MEMBER_CODE = 'ghost_skill_pack_member';
+/** #6910: why such a ghost is left alone and the human step that clears it; the preview, `gbrain pages ghosts` and doctor say it. */
+export const SKILL_PATH_NOTE = 'A ghost page whose path is a file of the source\'s adopted shared skillpack (skills/<name>/..., skillpack.json) is the pack\'s own file missing from the checkout; '
+ + 'the shared skill publisher owns it, so this repair never removes the page. Restore the file on the owner host (git -C <source root> checkout -- <path> when it is committed; '
+ + 'otherwise republish the skill with put_skill and its catalog expected_revision so the publisher writes it again); the page then stops being a ghost. These pages never block the other ghosts.';
+/** The exact restore command for one pack-member ghost. */
+export const skillPathRestore = (root: string | undefined, ghost: GhostPage) => `git -C ${root ?? '<source root>'} checkout -- ${ghost.path}`;
+/** The `skill_paths` detail every reader prints. */
+export function skillPathDetail(root: string | undefined, ghosts: GhostPage[], count = ghosts.length) {
+ const sample = ghosts.slice(0, SKILL_PATH_SAMPLE);
+ return { code: SKILL_PACK_MEMBER_CODE, count, slugs: sample.map(ghost => ghost.slug), owned_by: 'shared_skill_publisher',
+ restore: sample.map(ghost => skillPathRestore(root, ghost)), note: SKILL_PATH_NOTE, docs: DOCS };
+}
interface ApprovedGhost extends GhostPage { owner: GhostOwner; selection: string[] }
interface GhostItem extends RepairItem { ghost: GhostPage; owner: GhostOwner; hash: string; last: boolean }
@@ -152,7 +165,7 @@ export const ghostPagesRepair: RepairHandler = {
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}`] : []),
+ ...(skillPaths ? [`${skillPaths} ghost page(s) on files of the shared skillpack are listed apart (${SKILL_PACK_MEMBER_CODE}) 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) : []),
];
@@ -160,11 +173,10 @@ export const ghostPagesRepair: RepairHandler = {
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}` })),
- ...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)` }))],
+ ...scan.skill_paths.map(ghost => ({ item: `${ghost.source_id}:${ghost.slug}`, class: SKILL_PACK_MEMBER_CODE,
+ detail: `shared skillpack file ${ghost.path} is missing; not applied. Restore it: ${skillPathRestore(scan.root, ghost)}` }))],
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 } } : {}) } };
+ ...(skillPaths ? { skill_paths: skillPathDetail(scan.root, scan.skill_paths) } : {}) } };
}
if (!opts.expect) {
throw opError('invalid_params', 'gbrain repair ghost-pages --apply removes only the set a preview printed.',
diff --git a/src/core/shared-skills/knowledge-guard.ts b/src/core/shared-skills/knowledge-guard.ts
index 2b14216116..4eb5c028df 100644
--- a/src/core/shared-skills/knowledge-guard.ts
+++ b/src/core/shared-skills/knowledge-guard.ts
@@ -8,8 +8,11 @@ import { localHostId } from '../persistence/identity.ts';
import type { SqlEngine, WriteRequest } from '../persistence/model.ts';
import { canonicalFilesystemPath } from '../persistence/root-registry.ts';
-export type KnowledgePublicationTarget = Pick<WriteRequest, 'source_id' | 'source_incarnation' | 'slug' | 'target_kind'>;
-export interface KnowledgePublicationFile { path: string; root: string; }
+export type KnowledgePublicationTarget = Pick<WriteRequest, 'source_id' | 'source_incarnation' | 'slug' | 'target_kind'> & Partial<Pick<WriteRequest, 'intent'>>;
+export interface KnowledgePublicationFile { path: string; root: string; expectedBeforeHash?: string | null }
+
+/** The maintenance intent that soft-deletes an approved ghost page (`gbrain repair ghost-pages`, `file-drift --prefer file`). */
+export const GHOST_RETIREMENT_INTENT = 'managed_maintenance_retire_ghost_page';
interface PackRoot {
source_id: string;
@@ -29,6 +32,32 @@ function reject(): never {
'Use put_skill with the catalog expected_revision and complete approved file bundle; an existing pack requires host-authorized adoptSharedSkillpack adoption. Imported skill text remains knowledge data, not published instructions.');
}
+/**
+ * #6910: whether a source-relative path is a member of the source's adopted shared skillpack: `skillpack.json`, a file of a
+ * live skill's current revision, or a path under a live skill's `skills/<name>/` directory.
+ */
+export async function sharedPackMember(engine: SqlEngine, sourceId: string, sourceIncarnation: string, paths: string[]): Promise<boolean> {
+ const normalized = paths.map(path => path.split(sep).join('/'));
+ if (normalized.some(path => path.toLowerCase() === 'skillpack.json')) return true;
+ const [row] = await engine.executeRaw<{ member: boolean }>(`SELECT EXISTS (SELECT 1 FROM shared_skill_heads h
+ JOIN shared_skill_revisions r ON r.source_id=h.source_id AND r.source_incarnation=h.source_incarnation AND r.pack_id=h.pack_id AND r.name=h.name AND r.revision=h.revision
+ WHERE h.source_id=$1 AND h.source_incarnation=$2::uuid AND NOT h.deleted AND (
+ EXISTS (SELECT 1 FROM jsonb_array_elements(r.files) f WHERE f->>'path' = ANY($3::text[]))
+ OR EXISTS (SELECT 1 FROM unnest($3::text[]) p WHERE starts_with(p, 'skills/' || h.name || '/')))) AS member`, [sourceId, sourceIncarnation, normalized]);
+ return row?.member === true;
+}
+
+/**
+ * #6910: the retirement of an approved ghost page that is not a pack member changes no pack file: its file is already gone and
+ * the prepared target expects no bytes (filesystem publication refuses a file that appears), so it is a database-only soft
+ * delete of a legacy knowledge page. A pack member's page stays refused.
+ */
+async function retiresNonMemberGhost(engine: SqlEngine, row: KnowledgePublicationTarget, preparedFile?: KnowledgePublicationFile): Promise<boolean> {
+ const ghost = row.intent?.kind === GHOST_RETIREMENT_INTENT ? row.intent.ghost as { path?: unknown } | undefined : undefined;
+ if (typeof ghost?.path !== 'string' || (preparedFile && preparedFile.expectedBeforeHash !== null)) return false;
+ return !(await sharedPackMember(engine, row.source_id, row.source_incarnation, [ghost.path, `${row.slug}.md`]));
+}
+
const packsInTransaction = new WeakMap<object, Promise<PackRoot[]>>();
/** Engines (the connection owner, not a transaction view of it) whose schema has shared_skill_packs; migrations never drop it. */
const packTablePresent = new WeakSet<object>();
@@ -69,6 +98,7 @@ export async function assertKnowledgePublicationAllowed(
if (row.target_kind === 'skill_bundle') return;
const packs = await sharedPacks(engine);
if (!packs.length) return;
+ if (await retiresNonMemberGhost(engine, row, preparedFile)) return;
const ownPack = packs.find(pack => pack.source_id === row.source_id && pack.source_incarnation === row.source_incarnation);
if (ownPack && reserved(row.slug)) reject();
const roots = [...new Set(packs.flatMap(pack => [
diff --git a/test/ghost-pages-skill-paths-6910.test.ts b/test/ghost-pages-skill-paths-6910.test.ts
index 8f43035464..b76df1aafe 100644
--- a/test/ghost-pages-skill-paths-6910.test.ts
+++ b/test/ghost-pages-skill-paths-6910.test.ts
@@ -1,17 +1,19 @@
/**
* #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.
+ * Before the fix the knowledge guard refused the retirement of any ghost under `skills/` (`skill_bundle_required`) and the
+ * apply stopped there, so nothing past the first such page in page-id order was retired. Protects: a legacy page under
+ * `skills/` that is not a pack member is retired with the other ghosts as a database-only soft delete (no pack file changes);
+ * a ghost on a pack member's path (the pack's own file missing) is listed apart with code `ghost_skill_pack_member` and its
+ * exact restore command, never approved, and still refused by the guard; 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 and a really
+ * adopted pack.
*/
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 { existsSync, mkdirSync, mkdtempSync, readFileSync, 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';
@@ -25,6 +27,7 @@ import { activateSharedSkillPersistence } from '../src/core/persistence/skill-ac
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 { assertKnowledgePublicationAllowed, GHOST_RETIREMENT_INTENT } from '../src/core/shared-skills/knowledge-guard.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';
@@ -34,15 +37,20 @@ import { withEnv } from './helpers/with-env.ts';
const logger = { info() {}, warn() {}, error() {} };
const SOURCE = 'default';
+/** A legacy knowledge page under skills/ that no live pack skill owns. */
const SKILL = 'skills/legacy-skill/notes';
+/** A knowledge page under the live pack skill alpha's directory: a pack member path. */
+const MEMBER = 'skills/alpha/references/old';
const ORDINARY = ['notes/a', 'notes/b', 'notes/c'];
+const SKILL_FILE = 'skills/alpha/SKILL.md';
+const SKILL_TEXT = '---\nname: alpha\ndescription: A synthetic shared skill\n---\n\nApproved instructions.\n';
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.
+ * A legacy knowledge page under skills/ (lowest page id, imported before the pack was adopted), a page under the pack skill's
+ * directory, 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 and the pack's SKILL.md is removed.
*/
async function fixture(run: (f: Fixture) => Promise<void>): Promise<void> {
const scratch = mkdtempSync(join(tmpdir(), 'gbrain-ghost-skills-'));
@@ -57,7 +65,7 @@ async function fixture(run: (f: Fixture) => Promise<void>): Promise<void> {
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']) {
+ for (const slug of [SKILL, MEMBER, ...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 }))!;
@@ -71,11 +79,11 @@ async function fixture(run: (f: Fixture) => Promise<void>): Promise<void> {
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' },
+ { path: SKILL_FILE, content: SKILL_TEXT, file_class: 'prose' },
] },
] });
expect(adopted.receipts[0].state).toBe('committed');
- for (const slug of [SKILL, ...ORDINARY]) unlinkSync(join(root, `${slug}.md`));
+ for (const slug of [SKILL, MEMBER, ...ORDINARY]) unlinkSync(join(root, `${slug}.md`));
await run({ engine, root });
} finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); await isolated.close(); }
});
@@ -98,43 +106,58 @@ async function capture(fn: () => Promise<void>): Promise<string> {
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');
+ test('a legacy skills/ ghost that is no pack member is retired with the rest; a pack member ghost is listed apart with its restore step', () => fixture(async f => {
+ const preview = await repair(f.engine);
+ expect(preview.affected).toBe(4);
+ expect(preview.residuals).toMatchObject({ ghosts: 4, skill_paths: 1 });
+ expect(preview.listing!.filter(entry => entry.class === 'canonical_file_missing').map(entry => entry.item)).toEqual([SKILL, ...ORDINARY].map(slug => `${SOURCE}:${slug}`));
+ expect(preview.listing!.filter(entry => entry.class === 'ghost_skill_pack_member').map(entry => entry.item)).toEqual([`${SOURCE}:${MEMBER}`]);
+ expect(preview.details).toMatchObject({ skill_paths: { code: 'ghost_skill_pack_member', count: 1, slugs: [MEMBER], owned_by: 'shared_skill_publisher',
+ restore: [`git -C ${f.root} checkout -- ${MEMBER}.md`] } });
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(applied).toMatchObject({ applied: 4, failed: [], complete: true, outcomes: { soft_deleted: 4 } });
+ for (const slug of [SKILL, ...ORDINARY]) expect(await live(f.engine, slug)).toBe(false);
+ expect(await live(f.engine, MEMBER)).toBe(true);
expect(await live(f.engine, 'notes/keep')).toBe(true);
+ expect(readFileSync(join(f.root, SKILL_FILE), 'utf8')).toBe(SKILL_TEXT);
+ expect(existsSync(join(f.root, `${SKILL}.md`))).toBe(false);
const after = await repair(f.engine);
expect(after.affected).toBe(0);
expect(after.residuals).toMatchObject({ ghosts: 0, skill_paths: 1 });
}), 120_000);
+ test('the knowledge guard lets a non-member ghost retirement through and still refuses a pack member or a target that expects bytes', () => fixture(async f => {
+ const [source] = await f.engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [SOURCE]);
+ const row = (slug: string) => ({ source_id: SOURCE, source_incarnation: source!.incarnation, slug, target_kind: 'page' as const,
+ intent: { kind: GHOST_RETIREMENT_INTENT, ghost: { path: `${slug}.md` } } });
+ await expect(assertKnowledgePublicationAllowed(f.engine, row(SKILL))).resolves.toBeUndefined();
+ await expect(assertKnowledgePublicationAllowed(f.engine, row(SKILL), { root: f.root, path: join(f.root, `${SKILL}.md`), expectedBeforeHash: null })).resolves.toBeUndefined();
+ await expect(assertKnowledgePublicationAllowed(f.engine, row(SKILL), { root: f.root, path: join(f.root, `${SKILL}.md`), expectedBeforeHash: 'a'.repeat(64) }))
+ .rejects.toMatchObject({ code: 'skill_bundle_required' });
+ await expect(assertKnowledgePublicationAllowed(f.engine, row(MEMBER))).rejects.toMatchObject({ code: 'skill_bundle_required' });
+ await expect(assertKnowledgePublicationAllowed(f.engine, { ...row(SKILL), intent: { kind: 'put_page' } })).rejects.toMatchObject({ code: 'skill_bundle_required' });
+ }), 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]);
+ expect(summary).toMatchObject({ count: 4, skill_paths: 1, by_source: [{ source_id: SOURCE, count: 4, skill_paths: 1 }] });
+ expect(summary.samples.map(ghost => ghost.slug)).toEqual([SKILL, ...ORDINARY]);
+ expect(summary.skill_path_samples.map(ghost => ghost.slug)).toEqual([MEMBER]);
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]);
+ expect(out.count).toBe(4);
+ expect(out.ghosts.map((ghost: { slug: string }) => ghost.slug)).toEqual([SKILL, ...ORDINARY]);
+ expect(out.skill_paths.map((ghost: { slug: string }) => ghost.slug)).toEqual([MEMBER]);
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}`);
+ expect(check).toMatchObject({ name: 'ghost_pages', status: 'ok', details: { count: 0, skill_paths: { code: 'ghost_skill_pack_member', count: 1, owned_by: 'shared_skill_publisher' } } });
+ expect(check.details.skill_paths.samples.map((ghost: { slug: string }) => ghost.slug)).toEqual([MEMBER]);
+ expect(check.message).toContain(`${SOURCE}:${MEMBER}`);
+ expect(check.message).toContain('checkout --');
}), 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 => {
@@ -145,10 +168,11 @@ describe('#6910 ghost pages under the shared skillpack', () => {
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).toMatchObject({ applied: 3, outcomes: { soft_deleted: 3, 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);
+ expect(await live(f.engine, SKILL)).toBe(false);
}), 120_000);
});