Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
PRD-8690: Retire legacy startup skill reconciliation (#4603)
tim-inkeep4dd52fed5080
diff --git a/.changeset/preserve-skills-on-startup.md b/.changeset/preserve-skills-on-startup.mdnew file mode 100644index 000000000..2541601d0--- /dev/null+++ b/.changeset/preserve-skills-on-startup.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Preserve existing skill links on startup, including broken and Git-tracked links. Startup no longer repairs links, converts copied skills to links, or merges editor-suffixed duplicates. Reinstall to repair a broken link, convert a copy to a symlink from its install menu, and remove unwanted duplicates manually.diff --git a/packages/server/src/boot-skill-ownership.test.ts b/packages/server/src/boot-skill-ownership.test.tsnew file mode 100644index 000000000..65fd65d6a--- /dev/null+++ b/packages/server/src/boot-skill-ownership.test.ts@@ -0,0 +1,136 @@+import { execFileSync } from 'node:child_process';+import {+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readlinkSync,+ realpathSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, expect, test, vi } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig } from './composition-rig.test-helper.ts';++const isolated = vi.hoisted(() => ({ home: '' }));+vi.mock('node:os', async (original) => ({+ ...(await original<typeof import('node:os')>()),+ homedir: () => isolated.home,+}));++let root: string;+let server: BootedServer | undefined;++beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-boot-skill-ownership-')));+ isolated.home = realpathSync(mkdtempSync(join(tmpdir(), 'ok-boot-skill-home-')));+});++afterEach(async () => {+ try {+ await server?.destroy();+ } finally {+ server = undefined;+ rmSync(root, { recursive: true, force: true });+ rmSync(isolated.home, { recursive: true, force: true });+ }+});++function git(...args: string[]): string {+ return execFileSync('git', args, {+ cwd: root,+ encoding: 'utf8',+ env: {+ ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_'))),+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_NOSYSTEM: '1',+ },+ }).trim();+}++test('startup preserves tracked dangling skill links without a legacy store', async () => {+ git('init', '--quiet', '--initial-branch=main');+ writeFileSync(join(root, '.gitignore'), '.ok/\n');+ const target = '../../shared-skills/retired';+ const links = ['.agents/skills/retired', '.codex/skills/retired'];+ for (const host of ['.agents', '.codex']) {+ mkdirSync(join(root, host, 'skills'), { recursive: true });+ symlinkSync(target, join(root, host, 'skills', 'retired'), 'dir');+ }+ git('add', '.');+ git(+ '-c',+ 'user.name=Skill test',+ '-c',+ '[email protected]',+ '-c',+ 'commit.gpgsign=false',+ '-c',+ 'core.hooksPath=/dev/null',+ 'commit',+ '--quiet',+ '-m',+ 'Seed tracked skill links',+ );+ expect(git('status', '--porcelain')).toBe('');+ expect(git('ls-files', '--stage')).toContain('120000');+ expect(existsSync(join(root, '.ok', 'skills'))).toBe(false);++ server = await bootCompositionRig(root, { configHomedirOverride: isolated.home });+ await server.ready;++ expect(git('status', '--porcelain')).toBe('');+ for (const link of links) {+ expect(lstatSync(join(root, link)).isSymbolicLink()).toBe(true);+ expect(readlinkSync(join(root, link))).toBe(target);+ }+}, 60_000);++test.each([false, true])(+ 'startup preserves untracked dangling links when a same-name legacy skill exists: %s',+ async (legacySkillExists) => {+ const target = '../../shared-skills/retired';+ const link = join(root, '.agents', 'skills', 'retired');+ mkdirSync(join(root, '.agents', 'skills'), { recursive: true });+ symlinkSync(target, link, 'dir');+ if (legacySkillExists) {+ const source = join(root, '.ok', 'skills', 'retired');+ mkdirSync(source, { recursive: true });+ writeFileSync(join(source, 'SKILL.md'), '---\nname: retired\n---\n# Legacy skill\n');+ }++ server = await bootCompositionRig(root, { configHomedirOverride: isolated.home });+ await server.ready;++ expect(lstatSync(link).isSymbolicLink()).toBe(true);+ expect(readlinkSync(link)).toBe(target);+ if (legacySkillExists) {+ expect(readFileSync(join(root, '.ok', 'skills', 'retired', 'SKILL.md'), 'utf8')).toBe(+ '---\nname: retired\n---\n# Legacy skill\n',+ );+ }+ },+ 60_000,+);++test('startup still migrates known legacy store installations into editor directories', async () => {+ const source = join(root, '.ok', 'skills', 'legacy');+ const host = join(root, '.codex', 'skills');+ const content = '---\nname: legacy\n---\n# Legacy skill\n';+ mkdirSync(source, { recursive: true });+ mkdirSync(host, { recursive: true });+ writeFileSync(join(source, 'SKILL.md'), content);+ symlinkSync('../../.ok/skills/legacy', join(host, 'legacy'), 'dir');++ server = await bootCompositionRig(root, { configHomedirOverride: isolated.home });+ await server.ready;++ expect(lstatSync(join(host, 'legacy')).isDirectory()).toBe(true);+ expect(readFileSync(join(host, 'legacy', 'SKILL.md'), 'utf8')).toBe(content);+ expect(existsSync(source)).toBe(false);+}, 60_000);diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex a1d144f5a..0ebb19060 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -58,7 +58,6 @@ import {migrateStoreSkillsInPlace,USER_HOST_ROOTS_BY_PRECEDENCE,} from './skill-migrate.ts';-import { reconcileSkillInstalls } from './skill-reconcile.ts';import { initTelemetry, shutdownTelemetry, withSpan } from './telemetry.ts';import {initToleranceTelemetryWriter,@@ -775,30 +774,6 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {);}- try {- const r = await reconcileSkillInstalls({- projectDir,- skillsRoot: resolve(opts.contentDir, OK_DIR, 'skills'),- });- const changed = r.healed.length + r.replaced.length + r.orphansRemoved.length;- if (changed > 0) {- log.info?.(- {- event: 'installed-skills-reconciled',- healed: r.healed.length,- replaced: r.replaced.length,- orphansRemoved: r.orphansRemoved.length,- },- `Reconciled ${changed} editor skill entr${changed === 1 ? 'y' : 'ies'} to the symlink model.`,- );- }- } catch (err) {- log.warn?.(- { event: 'installed-skills-reconcile-failed', err },- 'Installed-skills reconcile failed (non-fatal).',- );- }-return {httpServer,destroy,diff --git a/packages/server/src/skill-reconcile.test.ts b/packages/server/src/skill-reconcile.test.tsdeleted file mode 100644index d9819632a..000000000--- a/packages/server/src/skill-reconcile.test.ts+++ /dev/null@@ -1,298 +0,0 @@-import {- existsSync,- lstatSync,- mkdirSync,- mkdtempSync,- readFileSync,- readlinkSync,- rmSync,- symlinkSync,- writeFileSync,-} from 'node:fs';-import { tmpdir } from 'node:os';-import { isAbsolute, join, relative, resolve } from 'node:path';-import { afterEach, beforeEach, describe, expect, test } from 'vitest';-import { reconcileSkillInstalls } from './skill-reconcile.ts';--let root: string;-let skillsRoot: string;--function makeSource(name: string, body = '# Steps'): string {- const dir = join(skillsRoot, name);- mkdirSync(dir, { recursive: true });- writeFileSync(- join(dir, 'SKILL.md'),- `---\nname: ${name}\ndescription: Use when testing.\n---\n${body}`,- );- return dir;-}--function makeEditorCopy(editorRel: string, name: string, body = '# Steps'): string {- const dir = join(root, editorRel, name);- mkdirSync(dir, { recursive: true });- writeFileSync(- join(dir, 'SKILL.md'),- `---\nname: ${name}\ndescription: Use when testing.\n---\n${body}`,- );- return dir;-}--function isLinkToSource(editorRel: string, name: string, sourceName = name): boolean {- const link = join(root, editorRel, name);- if (!lstatSync(link).isSymbolicLink()) return false;- return existsSync(join(link, 'SKILL.md')) && existsSync(join(skillsRoot, sourceName, 'SKILL.md'));-}--beforeEach(() => {- root = mkdtempSync(join(tmpdir(), 'ok-reconcile-'));- skillsRoot = join(root, '.ok', 'skills');- mkdirSync(skillsRoot, { recursive: true });-});-afterEach(() => {- rmSync(root, { recursive: true, force: true });-});--describe('reconcileSkillInstalls', () => {- test('leaves a correct managed symlink untouched', async () => {- const src = makeSource('trip-log');- mkdirSync(join(root, '.claude', 'skills'), { recursive: true });- const link = join(root, '.claude', 'skills', 'trip-log');- symlinkSync(relative(join(root, '.claude', 'skills'), src), link, 'dir');-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(r.healed).toEqual([]);- expect(r.replaced).toEqual([]);- expect(isLinkToSource('.claude/skills', 'trip-log')).toBe(true);- });-- test('heals a broken / wrong-target link to point at the source', async () => {- makeSource('trip-log');- mkdirSync(join(root, '.claude', 'skills'), { recursive: true });- const link = join(root, '.claude', 'skills', 'trip-log');- symlinkSync('/nonexistent/elsewhere', link, 'dir');-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(r.healed).toContainEqual({ name: 'trip-log', editor: 'claude' });- expect(isLinkToSource('.claude/skills', 'trip-log')).toBe(true);- });-- test('removes an orphan link whose source is gone', async () => {- mkdirSync(join(root, '.claude', 'skills'), { recursive: true });- const link = join(root, '.claude', 'skills', 'ghost');- symlinkSync('/nonexistent/elsewhere', link, 'dir');-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(r.orphansRemoved).toContainEqual({ name: 'ghost', editor: 'claude' });- expect(existsSync(link)).toBe(false);- });-- test('leaves a real-dir editor skill with no source untouched (in-place)', async () => {- const foreign = join(root, '.codex', 'skills', 'recipe');- mkdirSync(foreign, { recursive: true });- writeFileSync(join(foreign, 'SKILL.md'), '---\nname: recipe\ndescription: x.\n---\n# Foreign');-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(r.skipped).toContainEqual({ name: 'recipe', editor: 'codex' });- expect(existsSync(join(skillsRoot, 'recipe'))).toBe(false);- expect(lstatSync(foreign).isSymbolicLink()).toBe(false);- expect(readFileSync(join(foreign, 'SKILL.md'), 'utf-8')).toContain('# Foreign');- });-- test('leaves a symlink resolving outside .ok/skills untouched, even unmanaged', async () => {- const shared = join(root, 'shared-skills', 'toolbox');- mkdirSync(shared, { recursive: true });- writeFileSync(join(shared, 'SKILL.md'), '---\nname: toolbox\n---\n# External');- mkdirSync(join(root, '.agents', 'skills'), { recursive: true });- const link = join(root, '.agents', 'skills', 'toolbox');- symlinkSync(relative(join(root, '.agents', 'skills'), shared), link, 'dir');-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(r.orphansRemoved).toEqual([]);- expect(r.healed).toEqual([]);- expect(lstatSync(link).isSymbolicLink()).toBe(true);- expect(readFileSync(join(link, 'SKILL.md'), 'utf-8')).toContain('# External');- });-- test('does not re-point a foreign resolving symlink at a same-named .ok source', async () => {- makeSource('toolbox', '# Managed');- const shared = join(root, 'shared-skills', 'toolbox');- mkdirSync(shared, { recursive: true });- writeFileSync(join(shared, 'SKILL.md'), '---\nname: toolbox\n---\n# External');- mkdirSync(join(root, '.codex', 'skills'), { recursive: true });- const link = join(root, '.codex', 'skills', 'toolbox');- symlinkSync(shared, link, 'dir');-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(r.healed).toEqual([]);- expect(readFileSync(join(link, 'SKILL.md'), 'utf-8')).toContain('# External');- });-- test('replaces a redundant real-dir copy (same content as source) with a symlink', async () => {- makeSource('dup', '# Same');- makeEditorCopy('.claude/skills', 'dup', '# Same');-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(r.replaced).toContainEqual({ name: 'dup', editor: 'claude' });- expect(isLinkToSource('.claude/skills', 'dup')).toBe(true);- });-- test('frontmatter serialization-only diff → redundant (symlink), not in-place', async () => {- mkdirSync(join(skillsRoot, 'route-plan'), { recursive: true });- writeFileSync(- join(skillsRoot, 'route-plan', 'SKILL.md'),- '---\nname: route-plan\ndescription: "A long value here."\n---\n# Body\n',- );- mkdirSync(join(root, '.codex', 'skills', 'route-plan'), { recursive: true });- writeFileSync(- join(root, '.codex', 'skills', 'route-plan', 'SKILL.md'),- '---\nname: route-plan\ndescription: >-\n A long value\n here.\n---\n# Body\n',- );-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(r.skipped).toEqual([]);- expect(r.replaced).toContainEqual({ name: 'route-plan', editor: 'codex' });- expect(isLinkToSource('.codex/skills', 'route-plan')).toBe(true);- });-- test('additive frontmatter field (argument-hint) → redundant, not in-place', async () => {- mkdirSync(join(skillsRoot, 'dx'), { recursive: true });- writeFileSync(- join(skillsRoot, 'dx', 'SKILL.md'),- '---\nname: dx\ndescription: Use it.\n---\n# Body\n',- );- mkdirSync(join(root, '.cursor', 'skills', 'dx'), { recursive: true });- writeFileSync(- join(root, '.cursor', 'skills', 'dx', 'SKILL.md'),- '---\nname: dx\ndescription: Use it.\nargument-hint: "[add|list]"\n---\n# Body\n',- );-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(r.skipped).toEqual([]);- expect(r.replaced).toContainEqual({ name: 'dx', editor: 'cursor' });- });-- test('a genuinely different skill sharing a source name is left in place (never moved)', async () => {- makeSource('clash', '# OK managed version');- makeEditorCopy('.cursor/skills', 'clash', '# A genuinely different skill');-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(r.skipped).toContainEqual({ name: 'clash', editor: 'cursor' });- expect(readFileSync(join(skillsRoot, 'clash', 'SKILL.md'), 'utf-8')).toContain(- '# OK managed version',- );- expect(lstatSync(join(root, '.cursor', 'skills', 'clash')).isDirectory()).toBe(true);- expect(readFileSync(join(root, '.cursor', 'skills', 'clash', 'SKILL.md'), 'utf-8')).toContain(- '# A genuinely different skill',- );- expect(existsSync(join(skillsRoot, 'clash-cursor'))).toBe(false);- });-- test('differing sibling file (scripts/) → in-place, even when SKILL.md matches', async () => {- mkdirSync(join(skillsRoot, 'gizmo', 'scripts'), { recursive: true });- writeFileSync(- join(skillsRoot, 'gizmo', 'SKILL.md'),- '---\nname: gizmo\ndescription: g.\n---\n# Body\n',- );- writeFileSync(join(skillsRoot, 'gizmo', 'scripts', 'run.sh'), 'echo source\n');- mkdirSync(join(root, '.cursor', 'skills', 'gizmo', 'scripts'), { recursive: true });- writeFileSync(- join(root, '.cursor', 'skills', 'gizmo', 'SKILL.md'),- '---\nname: gizmo\ndescription: g.\n---\n# Body\n',- );- writeFileSync(- join(root, '.cursor', 'skills', 'gizmo', 'scripts', 'run.sh'),- 'echo HOST DIFFERENT\n',- );-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(r.replaced).toEqual([]);- expect(r.skipped).toContainEqual({ name: 'gizmo', editor: 'cursor' });- });-- test('skips a host-dir entry whose name is not a valid skill id', async () => {- makeSource('valid-skill', '# Same');- makeEditorCopy('.codex/skills', 'Invalid_Name', '# Not a skill');- makeEditorCopy('.codex/skills', 'valid-skill', '# Same');-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(existsSync(join(skillsRoot, 'Invalid_Name'))).toBe(false);- expect(lstatSync(join(root, '.codex', 'skills', 'Invalid_Name')).isDirectory()).toBe(true);- expect(r.replaced).toContainEqual({ name: 'valid-skill', editor: 'codex' });- expect(isLinkToSource('.codex/skills', 'valid-skill')).toBe(true);- });-- test('leaves the shipped open-knowledge bundle copy untouched', async () => {- const bundle = makeEditorCopy('.claude/skills', 'open-knowledge', '# Shipped');-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- const all = [...r.replaced, ...r.healed, ...r.skipped];- expect(all.find((a) => a.name === 'open-knowledge')).toBeUndefined();- expect(lstatSync(bundle).isSymbolicLink()).toBe(false);- });-- test('leaves EVERY shipped bundle copy untouched, not just open-knowledge', async () => {- const bundle = makeEditorCopy('.claude/skills', 'open-knowledge-write-skill', '# Shipped');-- const r = await reconcileSkillInstalls({ projectDir: root, skillsRoot });- const all = [...r.replaced, ...r.healed, ...r.skipped];- expect(all.find((a) => a.name === 'open-knowledge-write-skill')).toBeUndefined();- expect(existsSync(join(skillsRoot, 'open-knowledge-write-skill'))).toBe(false);- expect(lstatSync(bundle).isSymbolicLink()).toBe(false);- });-});--describe('reconcileSkillInstalls — accreted suffix-dupe collapse', () => {- function makeSourceFm(name: string, fm: string, body: string): string {- const dir = join(skillsRoot, name);- mkdirSync(dir, { recursive: true });- writeFileSync(join(dir, 'SKILL.md'), `---\n${fm}\n---\n${body}`);- return dir;- }-- function linkTarget(linkPath: string): string {- const raw = readlinkSync(linkPath);- return isAbsolute(raw) ? raw : resolve(join(linkPath, '..'), raw);- }-- test('collapses an identity-equal `<name>-<editor>` dupe and re-points its link', async () => {- makeSourceFm('foo', 'name: foo\ndescription: Use when testing.', '# Steps\n');- makeSourceFm(- 'foo-codex',- 'name: foo\ndescription: Use when testing.\nargument-hint: x',- '# Steps\n',- );- mkdirSync(join(root, '.codex', 'skills'), { recursive: true });- symlinkSync(join(skillsRoot, 'foo-codex'), join(root, '.codex', 'skills', 'foo-codex'), 'dir');-- await reconcileSkillInstalls({ projectDir: root, skillsRoot });-- expect(existsSync(join(skillsRoot, 'foo-codex'))).toBe(false);- expect(existsSync(join(skillsRoot, 'foo', 'SKILL.md'))).toBe(true);- const link = join(root, '.codex', 'skills', 'foo-codex');- expect(lstatSync(link).isSymbolicLink()).toBe(true);- expect(resolve(linkTarget(link))).toBe(resolve(join(skillsRoot, 'foo')));- });-- test('leaves a genuinely-different suffixed skill untouched', async () => {- makeSourceFm('bar', 'name: bar\ndescription: Use when testing.', '# A\n');- makeSourceFm('bar-codex', 'name: bar\ndescription: Use when testing.', '# B\n');-- await reconcileSkillInstalls({ projectDir: root, skillsRoot });-- expect(existsSync(join(skillsRoot, 'bar', 'SKILL.md'))).toBe(true);- expect(existsSync(join(skillsRoot, 'bar-codex', 'SKILL.md'))).toBe(true);- });-- test('is idempotent — a second pass with the dupe gone is a no-op', async () => {- makeSourceFm('baz', 'name: baz\ndescription: Use when testing.', '# Steps\n');- makeSourceFm(- 'baz-agents',- 'name: baz\ndescription: Use when testing.\nargument-hint: y',- '# Steps\n',- );- await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(existsSync(join(skillsRoot, 'baz-agents'))).toBe(false);- await reconcileSkillInstalls({ projectDir: root, skillsRoot });- expect(existsSync(join(skillsRoot, 'baz', 'SKILL.md'))).toBe(true);- });-});diff --git a/packages/server/src/skill-reconcile.ts b/packages/server/src/skill-reconcile.tsdeleted file mode 100644index 25773f19e..000000000--- a/packages/server/src/skill-reconcile.ts+++ /dev/null@@ -1,296 +0,0 @@-import { existsSync, lstatSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs';-import { dirname, isAbsolute, join, relative, resolve } from 'node:path';-import {- AGENTS_SKILLS_ROOT,- EDITOR_PROJECT_SKILL_ROOT,- type EditorId,- PROJECT_SKILL_EDITOR_IDS,- SKILL_NAME_REGEX,- stripFrontmatter,- unwrapFrontmatterFences,-} from '@inkeep/open-knowledge-core';-import { parse as parseYaml } from 'yaml';-import { tracedMkdirSync, tracedRmSync, tracedSymlinkSync } from './fs-traced.ts';-import { readInstalledSkills, recordSkillInstall } from './installed-skills-marker.ts';-import { getLogger } from './logger.ts';-import { INTERNAL_BUNDLE_SKILL_NAMES } from './skill-bundles.ts';-import { hostSkillsRootEscapes, validateSkillForInstall } from './skill-projection.ts';--const logger = getLogger('skill-reconcile');--const SHIPPED_BUNDLE_NAMES = INTERNAL_BUNDLE_SKILL_NAMES;--interface ReconcileAction {- name: string;- editor: EditorId | null;-}--export interface ReconcileResult {- healed: ReconcileAction[];- replaced: ReconcileAction[];- orphansRemoved: ReconcileAction[];- skipped: ReconcileAction[];-}--interface DetectionRoot {- rel: string;- editor: EditorId | null;-}--function detectionRoots(): DetectionRoot[] {- const roots: DetectionRoot[] = [];- for (const id of PROJECT_SKILL_EDITOR_IDS) {- const rel = EDITOR_PROJECT_SKILL_ROOT[id];- if (rel !== null) roots.push({ rel, editor: id });- }- roots.push({ rel: AGENTS_SKILLS_ROOT, editor: null });- return roots;-}--function relativeLinkTarget(hostRoot: string, sourceDir: string): string {- const rel = relative(hostRoot, resolve(sourceDir));- return isAbsolute(rel) ? resolve(sourceDir) : rel;-}--const DIRS_EQUAL_MAX_BYTES = 1_048_576;--function parseSkillManifest(md: string): { fm: Record<string, unknown>; body: string } {- const { frontmatter: fenced, body } = stripFrontmatter(md);- let fm: Record<string, unknown> = {};- if (fenced !== '') {- try {- const parsed = parseYaml(unwrapFrontmatterFences(fenced));- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {- fm = parsed as Record<string, unknown>;- }- } catch {}- }- return { fm, body };-}--function skillManifestsSame(mdA: string, mdB: string): boolean {- const a = parseSkillManifest(mdA);- const b = parseSkillManifest(mdB);- if (a.body !== b.body) return false;- for (const key of Object.keys(a.fm)) {- if (key in b.fm && JSON.stringify(a.fm[key]) !== JSON.stringify(b.fm[key])) return false;- }- return true;-}--function sameSkillModuloFrontmatter(a: string, b: string): boolean {- const listA = listFiles(a);- const listB = listFiles(b);- if (listA.length !== listB.length) return false;- let total = 0;- for (let i = 0; i < listA.length; i += 1) {- if (listA[i] !== listB[i]) return false;- const rel = listA[i] as string;- const fileA = join(a, rel);- const fileB = join(b, rel);- total += statSync(fileA).size + statSync(fileB).size;- if (total > DIRS_EQUAL_MAX_BYTES) return false;- const bufA = readFileSync(fileA);- const bufB = readFileSync(fileB);- if (bufA.equals(bufB)) continue;- if (rel !== 'SKILL.md') return false;- if (!skillManifestsSame(bufA.toString('utf8'), bufB.toString('utf8'))) return false;- }- return true;-}--function listFiles(dir: string, prefix = ''): string[] {- const out: string[] = [];- for (const entry of readdirSync(dir, { withFileTypes: true })) {- const rel = prefix ? `${prefix}/${entry.name}` : entry.name;- if (entry.isDirectory()) out.push(...listFiles(join(dir, entry.name), rel));- else if (entry.isFile()) out.push(rel);- }- return out.sort();-}--function linkInto(hostRoot: string, linkPath: string, sourceDir: string): void {- tracedRmSync(linkPath, { recursive: true, force: true });- tracedMkdirSync(hostRoot, { recursive: true });- tracedSymlinkSync(relativeLinkTarget(hostRoot, sourceDir), linkPath, 'dir');-}--function pointsAtSource(linkPath: string, sourceDir: string): boolean {- try {- const raw = readlinkSync(linkPath);- const resolved = isAbsolute(raw) ? raw : resolve(dirname(linkPath), raw);- return resolve(resolved) === resolve(sourceDir);- } catch {- return false;- }-}--function isForeignSymlink(linkPath: string, skillsRoot: string): boolean {- try {- const raw = readlinkSync(linkPath);- const target = isAbsolute(raw) ? resolve(raw) : resolve(dirname(linkPath), raw);- if (!existsSync(target)) return false;- const rel = relative(resolve(skillsRoot), target);- return rel !== '' && (rel.startsWith('..') || isAbsolute(rel));- } catch (err) {- logger.warn(- { linkPath, err },- 'isForeignSymlink: could not resolve symlink; treating as reconcile-managed',- );- return false;- }-}--const SUFFIX_TOKENS: readonly string[] = [...PROJECT_SKILL_EDITOR_IDS, 'agents'];--function suffixBase(name: string): string | null {- for (const token of SUFFIX_TOKENS) {- const suffix = `-${token}`;- if (name.length > suffix.length && name.endsWith(suffix)) return name.slice(0, -suffix.length);- }- return null;-}--function collapseAccretedSuffixDupes(opts: { projectDir: string; skillsRoot: string }): void {- const { projectDir, skillsRoot } = opts;- if (!existsSync(skillsRoot)) return;- let entries: string[];- try {- entries = readdirSync(skillsRoot);- } catch {- return;- }- const roots = detectionRoots();- for (const suffixed of entries) {- const base = suffixBase(suffixed);- if (base === null) continue;- const suffixedDir = resolve(skillsRoot, suffixed);- const baseDir = resolve(skillsRoot, base);- if (!existsSync(baseDir)) continue;- try {- const stat = lstatSync(suffixedDir);- if (stat.isSymbolicLink() || !stat.isDirectory()) continue;- if (!existsSync(join(suffixedDir, 'SKILL.md')) || !existsSync(join(baseDir, 'SKILL.md'))) {- continue;- }- if (!sameSkillModuloFrontmatter(baseDir, suffixedDir)) continue;- for (const { rel } of roots) {- const hostRoot = resolve(projectDir, rel);- if (hostSkillsRootEscapes(projectDir, hostRoot)) continue;- const linkPath = join(hostRoot, suffixed);- if (pointsAtSource(linkPath, suffixedDir)) linkInto(hostRoot, linkPath, baseDir);- }- tracedRmSync(suffixedDir, { recursive: true, force: true });- logger.info({ base, suffixed }, 'collapsed accreted suffix-duplicate skill into its base');- } catch (err) {- logger.warn({ err, base, suffixed }, 'suffix-dupe collapse skipped one entry after error');- }- }-}--export async function reconcileSkillInstalls(opts: {- projectDir: string;- skillsRoot: string;-}): Promise<ReconcileResult> {- const { projectDir, skillsRoot } = opts;- const result: ReconcileResult = {- healed: [],- replaced: [],- orphansRemoved: [],- skipped: [],- };- const markerAdds = new Map<string, Set<EditorId>>();- const addMarkerHost = (name: string, editor: EditorId | null) => {- if (editor === null) return;- const set = markerAdds.get(name) ?? new Set<EditorId>();- set.add(editor);- markerAdds.set(name, set);- };-- for (const { rel, editor } of detectionRoots()) {- const hostRoot = resolve(projectDir, rel);- if (!existsSync(hostRoot)) continue;- if (hostSkillsRootEscapes(projectDir, hostRoot)) continue;-- let entries: string[];- try {- entries = readdirSync(hostRoot);- } catch (err) {- logger.warn({ hostRoot, err }, 'reconcile: skipped unreadable host skills root');- continue;- }-- for (const name of entries) {- if (SHIPPED_BUNDLE_NAMES.has(name)) continue;- const entryPath = join(hostRoot, name);- const sourceDir = resolve(skillsRoot, name);- const sourceExists = existsSync(sourceDir);- try {- const stat = lstatSync(entryPath);- if (stat.isSymbolicLink()) {- if (pointsAtSource(entryPath, sourceDir) && sourceExists) continue;- if (isForeignSymlink(entryPath, skillsRoot)) {- result.skipped.push({ name, editor });- continue;- }- if (sourceExists) {- linkInto(hostRoot, entryPath, sourceDir);- result.healed.push({ name, editor });- } else {- tracedRmSync(entryPath, { recursive: true, force: true });- result.orphansRemoved.push({ name, editor });- }- continue;- }- if (!stat.isDirectory()) continue;-- if (!SKILL_NAME_REGEX.test(name)) {- logger.warn(- { skill: name, editor },- 'reconcile: skipping host-dir entry with a non-skill name',- );- continue;- }-- if (sourceExists && sameSkillModuloFrontmatter(entryPath, sourceDir)) {- linkInto(hostRoot, entryPath, sourceDir);- result.replaced.push({ name, editor });- addMarkerHost(name, editor);- continue;- }-- result.skipped.push({ name, editor });- } catch (err) {- logger.warn({ err, skill: name, editor }, 'reconcile skipped one skill entry after error');- }- }- }-- if (markerAdds.size > 0) {- const marker = readInstalledSkills(projectDir);- for (const [name, editors] of markerAdds) {- const sourceDir = resolve(skillsRoot, name);- if (!existsSync(sourceDir)) continue;- const prior = marker.skills[name];- const hosts = Array.from(new Set([...(prior?.hosts ?? []), ...editors]));- try {- await recordSkillInstall(projectDir, name, {- hosts,- scope: prior?.scope ?? 'project',- scripts: prior?.scripts ?? validateSkillForInstall(sourceDir, name).hasScripts,- installedAt: prior?.installedAt ?? new Date().toISOString(),- });- } catch (err) {- logger.warn({ err, skill: name }, 'reconcile marker update failed (non-fatal)');- }- }- }-- try {- collapseAccretedSuffixDupes({ projectDir, skillsRoot });- } catch (err) {- logger.warn({ err }, 'suffix-dupe collapse pass failed (non-fatal)');- }-- return result;-}