@serviceme/devtools-core 1.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/skill-linker/index.ts","../src/paths/userHome.ts"],"sourcesContent":["import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport { getHomeDir, getRepoDir } from \"../paths/userHome\";\n\n/**\n * Skill & Agent v2 — Client SkillLinker (M3, path-parity revision)\n *\n * SkillLinker exposes a skill/agent from the user's global repos\n * (`~/.serviceme/repos/<repoId>/{skills,agents}/<name>/`) into either:\n *\n * - a workspace, at `<workspace>/.github/{skills,agents}/<name>` —\n * the same path Copilot/Claude actually scan for `SKILL.md` /\n * `AGENT.md`, so linking here has real effect (see the v1 parity\n * note below); or\n * - the user's global scope, at `~/.agents/{skills,agents}/<name>`,\n * visible to every workspace.\n *\n * **v1 parity note**: an earlier revision linked into a private\n * `<workspace>/.serviceme/skills/<repoId>/<name>` directory. That path\n * is never scanned by the actual tooling, so installs were silently\n * inert. The path was moved to match `.github/skills` (the same\n * location the legacy v1 marketplace pipeline used). Because the link\n * path is now flat (no `<repoId>` segment), only one repo's version of\n * a given `<name>` can be linked into a given scope at a time.\n *\n * Platform behavior (per spec §11.8 — owner explicitly chose throw\n * over silent copy fallback):\n *\n * | platform | default mode | on failure |\n * |----------|--------------|-----------------------------|\n * | macOS | symlink | throw + platform hint |\n * | Linux | symlink | throw + platform hint |\n * | Windows | junction | throw + platform hint |\n *\n * Why junction first on Windows: NTFS junction doesn't require\n * SeCreateSymbolicLinkPrivilege; it works for any user. The limit is\n * the link target must be on a local NTFS volume. OneDrive / network\n * shares sometimes fail; we surface that as a typed error so callers\n * can decide whether to retry.\n *\n * @see docs/architecture/skill-agent-v2-repo.md §5.6 SkillLinker\n * @see docs/architecture/skill-agent-v2-repo.md §11.8 (throw, not copy)\n */\n\nexport type LinkMode = \"symlink\" | \"junction\" | \"copy\";\n\n/** Kind of artifact being linked. Mirrors `BridgeSkillKind`. */\nexport type EntryKind = \"skill\" | \"agent\";\n\n/**\n * Which scope the link lives in:\n * - `\"workspace\"` (default) → `<workspaceDir>/.github/<kind>/<name>`\n * - `\"user\"` → `~/.agents/<kind>/<name>` (visible to every workspace)\n */\nexport type LinkScope = \"workspace\" | \"user\";\n\nconst ENTRY_SUBDIR: Record<EntryKind, string> = {\n\tskill: \"skills\",\n\tagent: \"agents\",\n};\n\nexport interface InstallSkillOptions {\n\trepoId: string;\n\tskillName: string;\n\tworkspaceDir: string;\n\t/** Choose link mode explicitly. Defaults to platform-optimal. */\n\tmode?: \"auto\" | LinkMode;\n\t/** \"skill\" (default) or \"agent\". */\n\tkind?: EntryKind;\n\t/** \"workspace\" (default) or \"user\". */\n\tscope?: LinkScope;\n\t/**\n\t * Pre-resolved absolute source path (from `SkillStore`), overriding\n\t * the `<repoRoot>/{skills,agents}/<name>` formula in\n\t * {@link resolveSkillTarget}. Required for repos with non-standard\n\t * layouts — flat root (no `skills/` prefix), nested scope dirs\n\t * (`skills/official/<name>`), or flat single-file agent manifests\n\t * (`agents/<name>.agent.md`) — which the formula can't predict.\n\t * When omitted, falls back to the formula (kept for callers that\n\t * install a hand-authored skill without going through `SkillStore`).\n\t */\n\tsourcePath?: string;\n\t/**\n\t * True when `sourcePath` points at a single manifest FILE (e.g. a\n\t * flat `<name>.agent.md`) rather than a directory. Determines the\n\t * symlink type (file vs dir/junction) and the link's basename (the\n\t * link mirrors the source file's name + extension, since Copilot/\n\t * VS Code scan `.github/agents/<name>.agent.md` as a FILE).\n\t */\n\tsourceIsFile?: boolean;\n}\n\nexport interface InstallSkillResult {\n\tmode: LinkMode;\n\tlinkPath: string;\n\ttargetPath: string;\n}\n\n/** Describes one symlink/junction currently present in a workspace/user scope. */\nexport interface LinkedSkill {\n\t/**\n\t * Repo id the link resolves to, parsed back out of the symlink\n\t * target. Empty string when the target isn't under a recognizable\n\t * `~/.serviceme/repos/<repoId>/...` path.\n\t */\n\trepoId: string;\n\tskillName: string;\n\tlinkPath: string;\n\ttargetPath: string;\n\tmode: LinkMode;\n\t/** Which scope this link was found in — \"workspace\" or \"user\" (global). */\n\tscope: LinkScope;\n}\n\n/**\n * Sentinel error for link failures. Carries the chosen mode + platform\n * hint so the UI can render an actionable message.\n */\nexport class LinkError extends Error {\n\treadonly mode: LinkMode;\n\treadonly target: string;\n\treadonly linkPath: string;\n\treadonly platform: NodeJS.Platform;\n\treadonly cause: unknown;\n\n\tconstructor(opts: {\n\t\tmode: LinkMode;\n\t\ttarget: string;\n\t\tlinkPath: string;\n\t\tplatform: NodeJS.Platform;\n\t\tcause: unknown;\n\t}) {\n\t\tsuper(\n\t\t\t`failed to ${opts.mode} link ${opts.linkPath} → ${opts.target} on ${opts.platform}: ${\n\t\t\t\topts.cause instanceof Error ? opts.cause.message : String(opts.cause)\n\t\t\t}`\n\t\t);\n\t\tthis.name = \"LinkError\";\n\t\tthis.mode = opts.mode;\n\t\tthis.target = opts.target;\n\t\tthis.linkPath = opts.linkPath;\n\t\tthis.platform = opts.platform;\n\t\tthis.cause = opts.cause;\n\t}\n\n\t/** A user-facing hint for the platform that failed. */\n\thint(): string {\n\t\treturn getPlatformHint(this.platform);\n\t}\n}\n\n/** Choose the platform-optimal link mode. */\nexport function pickMode(platform: NodeJS.Platform = process.platform): LinkMode {\n\treturn platform === \"win32\" ? \"junction\" : \"symlink\";\n}\n\n/** A short hint string for the platform where the link failed. */\nexport function getPlatformHint(platform: NodeJS.Platform): string {\n\tif (platform === \"win32\") {\n\t\treturn (\n\t\t\t\"On Windows, enable Developer Mode in Settings → Privacy & Security → \" +\n\t\t\t\"For developers, or run as Administrator. NTFS junction also requires the \" +\n\t\t\t\"target to be on a local NTFS volume (OneDrive / network shares are not supported).\"\n\t\t);\n\t}\n\treturn (\n\t\t\"Symlink creation failed. Check filesystem permissions and that the source \" +\n\t\t\"directory exists. On some filesystems (FAT32, exFAT, network mounts) symlinks \" +\n\t\t\"are not supported.\"\n\t);\n}\n\n/**\n * Resolve the source path inside `~/.serviceme/repos/<repoId>/{skills,agents}/<name>`.\n * Exported for callers that need to inspect the target without installing.\n */\nexport function resolveSkillTarget(\n\trepoId: string,\n\tskillName: string,\n\tkind: EntryKind = \"skill\"\n): string {\n\treturn path.join(getRepoDir(repoId), ENTRY_SUBDIR[kind], skillName);\n}\n\n/**\n * Resolve the workspace link path — `<workspaceDir>/.github/{skills,agents}/<name>` —\n * the same directory Copilot/Claude actually scan.\n */\nexport function resolveSkillLinkPath(\n\tworkspaceDir: string,\n\tskillName: string,\n\tkind: EntryKind = \"skill\"\n): string {\n\treturn path.join(workspaceDir, \".github\", ENTRY_SUBDIR[kind], skillName);\n}\n\n/**\n * Resolve the user-scope link path — `~/.agents/{skills,agents}/<name>` —\n * visible to every workspace.\n */\nexport function resolveUserSkillLinkPath(skillName: string, kind: EntryKind = \"skill\"): string {\n\treturn path.join(getHomeDir(), \".agents\", ENTRY_SUBDIR[kind], skillName);\n}\n\nfunction resolveLinkPath(opts: {\n\tworkspaceDir: string;\n\tskillName: string;\n\tkind: EntryKind;\n\tscope: LinkScope;\n\t/** When set, use this basename instead of the bare `skillName` — for\n\t * file-based sources the link must mirror the source's filename\n\t * (including its extension) to be scannable at its real path. */\n\tlinkBasename?: string;\n}): string {\n\tif (opts.scope === \"workspace\" && !opts.workspaceDir) {\n\t\tthrow new Error(\n\t\t\t\"workspaceDir is required for scope: 'workspace' (pass scope: 'user' for a global install instead).\"\n\t\t);\n\t}\n\tconst base =\n\t\topts.scope === \"user\"\n\t\t\t? resolveUserSkillLinkPath(opts.skillName, opts.kind)\n\t\t\t: resolveSkillLinkPath(opts.workspaceDir, opts.skillName, opts.kind);\n\treturn opts.linkBasename ? path.join(path.dirname(base), opts.linkBasename) : base;\n}\n\n/**\n * Install a skill into a workspace by creating a link at the standard\n * path. Throws `LinkError` on failure (no silent copy fallback per\n * §11.8).\n *\n * Idempotent: if the correct link already exists, returns the existing\n * record without touching the filesystem. If a *wrong* link exists at\n * the target path, it is replaced.\n */\nexport async function installSkillToWorkspace(\n\topts: InstallSkillOptions\n): Promise<InstallSkillResult> {\n\tconst kind = opts.kind ?? \"skill\";\n\tconst scope = opts.scope ?? \"workspace\";\n\tconst isFile = opts.sourceIsFile ?? false;\n\tconst target = opts.sourcePath ?? resolveSkillTarget(opts.repoId, opts.skillName, kind);\n\tconst linkPath = resolveLinkPath({\n\t\tworkspaceDir: opts.workspaceDir,\n\t\tskillName: opts.skillName,\n\t\tkind,\n\t\tscope,\n\t\tlinkBasename: isFile ? path.basename(target) : undefined,\n\t});\n\n\t// Sanity-check: the skill source directory must exist before we try\n\t// to link it. Otherwise the link would dangle.\n\tawait fs.access(target).catch(() => {\n\t\tthrow new LinkError({\n\t\t\tmode: \"symlink\", // placeholder — mode not chosen yet\n\t\t\ttarget,\n\t\t\tlinkPath,\n\t\t\tplatform: process.platform,\n\t\t\tcause: new Error(`skill source not found: ${target}`),\n\t\t});\n\t});\n\n\t// If the link already exists and points to the right target, no-op.\n\tif (await isCorrectLink(linkPath, target)) {\n\t\treturn { mode: \"symlink\", linkPath, targetPath: target };\n\t}\n\t// Otherwise, remove any stale entry at the path.\n\tawait removeIfExists(linkPath);\n\n\t// Junctions are directory-only — a file source can never use one,\n\t// regardless of platform default. Fall back to a real symlink.\n\tconst requestedMode = opts.mode === undefined || opts.mode === \"auto\" ? pickMode() : opts.mode;\n\tconst mode = isFile && requestedMode === \"junction\" ? \"symlink\" : requestedMode;\n\n\t// Ensure the parent directory exists — fs.symlink does NOT create\n\t// missing parents. The path is `<workspace>/.serviceme/skills/<repoId>/`,\n\t// which is several levels deep on a fresh workspace.\n\tawait fs.mkdir(path.dirname(linkPath), { recursive: true });\n\n\ttry {\n\t\tif (mode === \"junction\") {\n\t\t\t// fs.symlink with type \"junction\" works on Windows for dirs.\n\t\t\tawait fs.symlink(target, linkPath, \"junction\");\n\t\t} else if (mode === \"symlink\") {\n\t\t\t// Windows requires an explicit \"file\" type for file symlinks;\n\t\t\t// POSIX ignores the type argument either way.\n\t\t\tawait fs.symlink(target, linkPath, isFile ? \"file\" : \"dir\");\n\t\t} else {\n\t\t\t// `copy` mode is intentionally NOT implemented for v1 — see\n\t\t\t// spec §11.8 (\"throw, not copy fallback\"). Reaching this branch\n\t\t\t// means a caller explicitly passed `mode: 'copy'`; we treat\n\t\t\t// it as a configuration error rather than silently dropping\n\t\t\t// to copy semantics.\n\t\t\tthrow new LinkError({\n\t\t\t\tmode: \"copy\",\n\t\t\t\ttarget,\n\t\t\t\tlinkPath,\n\t\t\t\tplatform: process.platform,\n\t\t\t\tcause: new Error(\n\t\t\t\t\t\"copy mode is not supported in v1 — see spec §11.8 (throw, not copy fallback)\"\n\t\t\t\t),\n\t\t\t});\n\t\t}\n\t} catch (err) {\n\t\tif (err instanceof LinkError) throw err;\n\t\tthrow new LinkError({\n\t\t\tmode,\n\t\t\ttarget,\n\t\t\tlinkPath,\n\t\t\tplatform: process.platform,\n\t\t\tcause: err,\n\t\t});\n\t}\n\n\treturn { mode, linkPath, targetPath: target };\n}\n\n/**\n * Convert an existing, real (non-symlink) skill/agent directory at the\n * standard scan path into a symlink pointing at the matching global\n * repo entry. Refuses to run when there's nothing real to convert —\n * callers should only surface this action when a marketplace/scope\n * state check already confirmed a non-symlink install is present.\n */\nexport async function convertToSymlink(opts: InstallSkillOptions): Promise<InstallSkillResult> {\n\tconst kind = opts.kind ?? \"skill\";\n\tconst scope = opts.scope ?? \"workspace\";\n\tconst linkPath = resolveLinkPath({\n\t\tworkspaceDir: opts.workspaceDir,\n\t\tskillName: opts.skillName,\n\t\tkind,\n\t\tscope,\n\t\tlinkBasename: opts.sourceIsFile && opts.sourcePath ? path.basename(opts.sourcePath) : undefined,\n\t});\n\n\tconst stat = await fs.lstat(linkPath).catch(() => null);\n\tif (!stat) {\n\t\tthrow new Error(`Nothing installed at ${linkPath} to convert.`);\n\t}\n\tif (stat.isSymbolicLink()) {\n\t\tthrow new Error(`${linkPath} is already a symlink.`);\n\t}\n\n\treturn installSkillToWorkspace(opts);\n}\n\n/**\n * Remove a skill/agent link from a workspace/user scope. Idempotent:\n * succeeds when the link does not exist (no error).\n *\n * Tries the bare `<name>` path first (directory-based entries), then\n * falls back to scanning the scope dir for a `<name>.<ext>` file (flat\n * manifest entries, e.g. `CSharpExpert.agent.md`) — the caller doesn't\n * necessarily still have the source repo entry to know which shape was\n * installed (e.g. the repo may have been removed since).\n */\nexport async function uninstallSkillFromWorkspace(opts: {\n\trepoId: string;\n\tskillName: string;\n\tworkspaceDir: string;\n\tkind?: EntryKind;\n\tscope?: LinkScope;\n}): Promise<void> {\n\tconst kind = opts.kind ?? \"skill\";\n\tconst scope = opts.scope ?? \"workspace\";\n\tconst linkPath = resolveLinkPath({\n\t\tworkspaceDir: opts.workspaceDir,\n\t\tskillName: opts.skillName,\n\t\tkind,\n\t\tscope,\n\t});\n\tif (await pathExists(linkPath)) {\n\t\tawait removeIfExists(linkPath);\n\t\treturn;\n\t}\n\n\tconst scopeDir = path.dirname(linkPath);\n\tlet entries: import(\"node:fs\").Dirent[];\n\ttry {\n\t\tentries = await fs.readdir(scopeDir, { withFileTypes: true });\n\t} catch {\n\t\treturn; // nothing installed at all — idempotent no-op\n\t}\n\tconst flatMatch = entries.find(\n\t\t(e) => e.name === opts.skillName || e.name.startsWith(`${opts.skillName}.`)\n\t);\n\tif (flatMatch) {\n\t\tawait removeIfExists(path.join(scopeDir, flatMatch.name));\n\t}\n}\n\n/** `true` when `p` exists (following symlinks is irrelevant — `lstat` is enough). */\nasync function pathExists(p: string): Promise<boolean> {\n\ttry {\n\t\tawait fs.lstat(p);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nconst MANIFEST_FILENAME: Record<EntryKind, string> = {\n\tskill: \"SKILL.md\",\n\tagent: \"AGENT.md\",\n};\n\n/**\n * Enumerate all skill/agent entries currently present in a workspace/user\n * scope — both symlinked installs (`mode: \"symlink\"`/`\"junction\"`) AND\n * real, non-symlink directories/files that already carry a valid\n * manifest (`mode: \"copy\"`). Used by the UI's \"Manage installed skills\"\n * view so it can show a real (copy-installed) entry as installed too —\n * this is common for the user (global) scope, where many skills are\n * placed by other tools/installers as plain copies rather than via this\n * package's symlink-only install flow. `repoId` is `\"\"` for `\"copy\"`\n * entries since there's no symlink target to resolve it from; callers\n * match these by name only. Returns an empty array when the scan\n * directory doesn't exist.\n */\nexport async function listLinkedSkills(\n\tworkspaceDir: string,\n\tkind: EntryKind = \"skill\",\n\tscope: LinkScope = \"workspace\"\n): Promise<LinkedSkill[]> {\n\t// No workspace open + workspace scope requested — nothing to scan.\n\t// Guard explicitly rather than falling through to\n\t// `path.join(\"\", \".github\", ...)`, which resolves to a *relative*\n\t// path (anchored at the process's cwd, not a real workspace) and\n\t// could accidentally match an unrelated directory there.\n\tif (scope === \"workspace\" && !workspaceDir) {\n\t\treturn [];\n\t}\n\tconst root =\n\t\tscope === \"user\"\n\t\t\t? path.join(getHomeDir(), \".agents\", ENTRY_SUBDIR[kind])\n\t\t\t: path.join(workspaceDir, \".github\", ENTRY_SUBDIR[kind]);\n\n\tlet entries: import(\"node:fs\").Dirent[];\n\ttry {\n\t\tentries = await fs.readdir(root, { withFileTypes: true });\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\tthrow err;\n\t}\n\n\tconst results: LinkedSkill[] = [];\n\tfor (const entry of entries) {\n\t\tconst entryPath = path.join(root, entry.name);\n\n\t\tif (entry.isSymbolicLink()) {\n\t\t\t// Flat manifest files (e.g. `CSharpExpert.agent.md`) report the\n\t\t\t// bare name, matching what SkillStore/install use elsewhere —\n\t\t\t// otherwise this would look like a different, unrelated entry.\n\t\t\tconst skillName = entry.name.replace(/\\.(agent|skill)\\.md$/, \"\");\n\t\t\tconst rawTarget = await readLinkTarget(entryPath);\n\t\t\tif (!rawTarget) continue; // unreadable\n\t\t\tconst resolvedTarget = resolveTargetPath(entryPath, rawTarget);\n\t\t\t// Skip dangling links — `fs.stat` follows symlinks and throws\n\t\t\t// ENOENT when the target is missing. That's the signal that\n\t\t\t// the link is broken.\n\t\t\tconst targetStat = await fs.stat(resolvedTarget).catch(() => null);\n\t\t\tif (!targetStat) continue;\n\t\t\tresults.push({\n\t\t\t\trepoId: extractRepoIdFromTarget(resolvedTarget) ?? \"\",\n\t\t\t\tskillName,\n\t\t\t\tlinkPath: entryPath,\n\t\t\t\ttargetPath: resolvedTarget,\n\t\t\t\tmode: process.platform === \"win32\" ? \"junction\" : \"symlink\",\n\t\t\t\tscope,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.isDirectory()) {\n\t\t\t// A real (copy-installed) directory — only counts as an\n\t\t\t// installed entry when it actually carries the expected\n\t\t\t// manifest file, so unrelated junk directories in the scope\n\t\t\t// dir (e.g. leftover `.DS_Store`-adjacent folders) aren't\n\t\t\t// misreported as installed skills/agents.\n\t\t\tconst hasManifest = await fs\n\t\t\t\t.access(path.join(entryPath, MANIFEST_FILENAME[kind]))\n\t\t\t\t.then(() => true)\n\t\t\t\t.catch(() => false);\n\t\t\tif (!hasManifest) continue;\n\t\t\tresults.push({\n\t\t\t\trepoId: \"\",\n\t\t\t\tskillName: entry.name,\n\t\t\t\tlinkPath: entryPath,\n\t\t\t\ttargetPath: entryPath,\n\t\t\t\tmode: \"copy\",\n\t\t\t\tscope,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.isFile() && entry.name.endsWith(`.${kind}.md`)) {\n\t\t\t// A real (copy-installed) flat manifest file, e.g. a plain\n\t\t\t// `CSharpExpert.agent.md` that was placed directly rather\n\t\t\t// than symlinked.\n\t\t\tresults.push({\n\t\t\t\trepoId: \"\",\n\t\t\t\tskillName: entry.name.replace(/\\.(agent|skill)\\.md$/, \"\"),\n\t\t\t\tlinkPath: entryPath,\n\t\t\t\ttargetPath: entryPath,\n\t\t\t\tmode: \"copy\",\n\t\t\t\tscope,\n\t\t\t});\n\t\t}\n\t}\n\treturn results;\n}\n\n// ─────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────\n\n/** Returns `true` when `linkPath` is a symlink/junction pointing at `expectedTarget`. */\nasync function isCorrectLink(linkPath: string, expectedTarget: string): Promise<boolean> {\n\tlet actual: string | undefined;\n\ttry {\n\t\tactual = await readLinkTarget(linkPath);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (!actual) return false;\n\treturn resolveTargetPath(linkPath, actual) === resolveTargetPath(linkPath, expectedTarget);\n}\n\n/** Read a link's target without throwing — returns undefined on ENOENT. */\nasync function readLinkTarget(linkPath: string): Promise<string | undefined> {\n\ttry {\n\t\treturn await fs.readlink(linkPath);\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n\t\tthrow err;\n\t}\n}\n\n/**\n * Resolve a relative symlink target against its parent directory so a\n * relative link reads back as an absolute path comparable to another\n * absolute path.\n */\nfunction resolveTargetPath(linkPath: string, target: string): string {\n\tif (path.isAbsolute(target)) return path.normalize(target);\n\treturn path.normalize(path.resolve(path.dirname(linkPath), target));\n}\n\n/**\n * Parse the `<repoId>` segment back out of a resolved link target of\n * the shape `.../.serviceme/repos/<repoId>/{skills,agents}/<name>`.\n * Returns `undefined` when the target doesn't match that shape (e.g. a\n * hand-authored local skill under `~/.agents/skills/<name>` with no\n * backing repo).\n */\nfunction extractRepoIdFromTarget(target: string): string | undefined {\n\tconst marker = `${path.sep}repos${path.sep}`;\n\tconst idx = target.indexOf(marker);\n\tif (idx === -1) return undefined;\n\tconst rest = target.slice(idx + marker.length);\n\tconst [repoId] = rest.split(path.sep);\n\treturn repoId || undefined;\n}\n\n/** Best-effort removal of a path. ENOENT is silently ignored. */\nasync function removeIfExists(p: string): Promise<void> {\n\ttry {\n\t\tconst stat = await fs.lstat(p);\n\t\tif (stat.isDirectory() && !stat.isSymbolicLink()) {\n\t\t\tawait fs.rm(p, { recursive: true, force: true });\n\t\t} else {\n\t\t\tawait fs.unlink(p);\n\t\t}\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === \"ENOENT\") return;\n\t\tthrow err;\n\t}\n}\n","import * as os from \"node:os\";\nimport * as path from \"node:path\";\n\n/**\n * SERVICEME user home directory helpers.\n *\n * All paths resolve under {@link getServicemeHome}, which is either the\n * `SERVICEME_HOME` environment variable (when set and non-empty) or\n * `$HOME/.serviceme` on POSIX / `%USERPROFILE%\\.serviceme` on Windows.\n *\n * Tests inject `homeDir` and `servicemeHomeEnv` overrides via\n * {@link setUserHomeOverrides} / {@link resetUserHomeOverrides} so they can\n * exercise the path logic without touching the real user environment.\n */\n\n/** Layout constants — kept in one place so other modules can reuse them. */\nexport const SERVICEME_DIR_NAME = \".serviceme\";\nexport const REPOS_SUBDIR = \"repos\";\nexport const CACHE_SUBDIR = \"cache\";\nexport const DRAFTS_SUBDIR = \"drafts\";\nexport const SKILL_DRAFTS_SUBDIR = \"skills\";\nexport const AGENT_DRAFTS_SUBDIR = \"agents\";\nexport const REPOS_CONFIG_FILENAME = \"repos.json\";\n\n/** rev.20 — r7 BYOM Server Proxy toggle self-state (read by ext + CLI + server). */\nexport const SERVER_PROXY_GLOBAL_FILENAME = \"server-proxy.json\";\n\n/**\n * Repo id regex — used to validate any `repoId` argument before it is joined\n * into a filesystem path. Keeps path traversal attempts out and gives us a\n * predictable on-disk shape.\n */\nexport const SAFE_REPO_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;\n\n/** Environment variable that overrides the user-home root directory. */\nexport const SERVICEME_HOME_ENV = \"SERVICEME_HOME\";\n\n/**\n * Test seam: lets unit tests inject deterministic values for `os.homedir()`\n * and the `SERVICEME_HOME` env override without actually mutating\n * `process.env` (which would leak into other tests).\n */\ninterface UserHomeOverrides {\n\thomeDir?: string | undefined;\n\tservicemeHomeEnv?: string | undefined;\n\tplatform?: NodeJS.Platform | undefined;\n}\n\nlet activeOverrides: UserHomeOverrides = {};\n\nexport function setUserHomeOverrides(overrides: UserHomeOverrides): void {\n\tactiveOverrides = { ...overrides };\n}\n\nexport function resetUserHomeOverrides(): void {\n\tactiveOverrides = {};\n}\n\nfunction resolveHomeDir(): string {\n\tconst injected = activeOverrides.homeDir;\n\tif (injected !== undefined) {\n\t\treturn injected;\n\t}\n\treturn os.homedir();\n}\n\nfunction resolveServicemeHomeEnv(): string | undefined {\n\tconst injected = activeOverrides.servicemeHomeEnv;\n\tif (injected !== undefined) {\n\t\t// Treat empty string as \"not set\" — `process.env` always returns a string\n\t\t// but tests may deliberately pass \"\" to opt out.\n\t\treturn injected.length > 0 ? injected : undefined;\n\t}\n\tconst envValue = process.env[SERVICEME_HOME_ENV];\n\treturn envValue && envValue.length > 0 ? envValue : undefined;\n}\n\nfunction resolvePlatform(): NodeJS.Platform {\n\treturn activeOverrides.platform ?? process.platform;\n}\n\nexport function assertSafeRepoId(repoId: string): string {\n\tif (typeof repoId !== \"string\" || repoId.length === 0 || !SAFE_REPO_ID_PATTERN.test(repoId)) {\n\t\tthrow new Error(\n\t\t\t`Invalid repo id: ${JSON.stringify(repoId)}. ` +\n\t\t\t\t`Must match ${SAFE_REPO_ID_PATTERN} (alphanumeric start, then ` +\n\t\t\t\t`alphanumerics / underscores / hyphens, ≤ 64 chars).`\n\t\t);\n\t}\n\treturn repoId;\n}\n\n/**\n * The raw OS home directory (`os.homedir()`), honoring test overrides\n * ({@link setUserHomeOverrides}). Exported for callers that need a\n * home-relative path *outside* of `~/.serviceme` — e.g. the\n * `~/.agents/{skills,agents}` convention used by `SkillLinker` for\n * user-scope links.\n */\nexport function getHomeDir(): string {\n\treturn resolveHomeDir();\n}\n\n/**\n * Root directory for all SERVICEME user-level state. Resolves to\n * `${SERVICEME_HOME}` when that env var is set, otherwise `${HOME}/.serviceme`\n * (POSIX) or `%USERPROFILE%\\.serviceme` (Windows via `os.homedir`).\n */\nexport function getServicemeHome(): string {\n\tconst override = resolveServicemeHomeEnv();\n\tif (override !== undefined) {\n\t\treturn path.resolve(override);\n\t}\n\treturn path.join(resolveHomeDir(), SERVICEME_DIR_NAME);\n}\n\n/** `$HOME/.serviceme/repos` (or `${SERVICEME_HOME}/repos`). */\nexport function getReposDir(): string {\n\treturn path.join(getServicemeHome(), REPOS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/repos/<repoId>` — validates `repoId` first. */\nexport function getRepoDir(repoId: string): string {\n\treturn path.join(getReposDir(), assertSafeRepoId(repoId));\n}\n\n/** `$HOME/.serviceme/cache` — generic per-user cache. */\nexport function getCacheDir(): string {\n\treturn path.join(getServicemeHome(), CACHE_SUBDIR);\n}\n\n/** `$HOME/.serviceme/cache/<repoId>` — per-repo sync state lives here. */\nexport function getRepoCacheDir(repoId: string): string {\n\treturn path.join(getCacheDir(), assertSafeRepoId(repoId));\n}\n\n/** `$HOME/.serviceme/drafts` — local edits not yet pushed upstream. */\nexport function getDraftsDir(): string {\n\treturn path.join(getServicemeHome(), DRAFTS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/drafts/skills` — local skill drafts. */\nexport function getSkillDraftsDir(): string {\n\treturn path.join(getDraftsDir(), SKILL_DRAFTS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/drafts/agents` — local agent drafts. */\nexport function getAgentDraftsDir(): string {\n\treturn path.join(getDraftsDir(), AGENT_DRAFTS_SUBDIR);\n}\n\n/**\n * `$HOME/.serviceme/repos.json` — the single config entry point for repo\n * metadata. Always under the resolved home root (i.e. follows\n * `SERVICEME_HOME` overrides too).\n */\nexport function getReposConfigPath(): string {\n\treturn path.join(getServicemeHome(), REPOS_CONFIG_FILENAME);\n}\n\n/**\n * Convenience helper for callers that need to switch behaviour on platform\n * (e.g. `SkillLinker` chooses symlink vs junction). Exported mostly so tests\n * can pin the value without touching `process.platform` directly.\n */\nexport function getHomePlatform(): NodeJS.Platform {\n\treturn resolvePlatform();\n}\n\n// ─── Scheduled Tasks paths (added by M1.5.3) ───────────────────────────────\n\n/** Layout constants for scheduled-tasks files. Kept here so other modules\n * can reuse them and the names stay in sync with the design doc. */\nexport const SCHEDULED_TASKS_CONFIG_FILENAME = \"scheduled-tasks.json\";\nexport const SCHEDULED_TASKS_LOG_FILENAME = \"scheduled-tasks-log.json\";\nexport const SCHEDULER_PID_FILENAME = \"scheduler.pid\";\nexport const SCHEDULER_LOCK_FILENAME = \"scheduler.lock\";\nexport const SCHEDULER_LOG_FILENAME = \"scheduler.log\";\nexport const MIGRATION_FAILURES_FILENAME = \"migration-failures.json\";\nexport const KNOWN_WORKSPACES_FILENAME = \"known-workspaces.json\";\n\n/** `~/.serviceme/scheduled-tasks.json` — the global v2 task list. */\nexport function getScheduledTasksConfigPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULED_TASKS_CONFIG_FILENAME);\n}\n\n/** `~/.serviceme/scheduled-tasks-log.json` — the global execution log (200 LRU). */\nexport function getScheduledTasksLogPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULED_TASKS_LOG_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.pid` — global daemon PID file. */\nexport function getSchedulerPidPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_PID_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.lock` — global daemon startup flock. */\nexport function getSchedulerLockPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_LOCK_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.log` — global daemon log (daemon lifecycle, not task execution). */\nexport function getSchedulerLogPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_LOG_FILENAME);\n}\n\n/** `~/.serviceme/migration-failures.json` — diagnostics for failed v1→v2 imports. */\nexport function getMigrationFailuresPath(): string {\n\treturn path.join(getServicemeHome(), MIGRATION_FAILURES_FILENAME);\n}\n\n/** `~/.serviceme/known-workspaces.json` — workspace list the extension has seen. */\nexport function getKnownWorkspacesPath(): string {\n\treturn path.join(getServicemeHome(), KNOWN_WORKSPACES_FILENAME);\n}\n\n// ─── r7 BYOM Server Proxy (rev.20) ─────────────────────────────────────────\n\n/**\n * `~/.serviceme/server-proxy.json` — r7 BYOM Server Proxy toggle\n * self-state. Written by the extension's `ProxyConfigService`, readable\n * by the CLI / Server so they can decide whether to route traffic\n * through the corporate proxy without booting VS Code.\n *\n * Lives under user-level `~/.serviceme/` (not under a workspace) because\n * the toggle is a *user preference* — the same human enabling it on\n * machine A should be able to rely on it on machine B after sync, not\n * have it disappear when they switch repos.\n */\nexport function getServerProxyGlobalPath(): string {\n\treturn path.join(getServicemeHome(), SERVER_PROXY_GLOBAL_FILENAME);\n}\n\n// ─── Phase 5 (auth + device + toolbox) placeholders (Spec §11.12) ────────\n\n/** Layout constants for the Phase 5 client-side state files. The server\n * already has the corresponding routes (`/api/v1/auth/...`,\n * `/api/v1/device/...`, etc.) — the client just needs the on-disk\n * file paths + a first-run bootstrap so the auth/device/toolbox\n * services can open + read them without a per-call existence check. */\nexport const CREDENTIALS_CONFIG_FILENAME = \"credentials.json\";\nexport const DEVICE_JSON_FILENAME = \"device.json\";\nexport const TOOLBOX_JSON_FILENAME = \"toolbox.json\";\nexport const MACHINE_ID_FILENAME = \"machine-id\";\nexport const PROFILES_JSON_FILENAME = \"profiles.json\";\n\n/** `~/.serviceme/credentials.json` — better-auth session tokens + refresh state (client-side cache). */\nexport function getCredentialsConfigPath(): string {\n\treturn path.join(getServicemeHome(), CREDENTIALS_CONFIG_FILENAME);\n}\n\n/** `~/.serviceme/device.json` — device enrollment payload (id, public key fingerprint, claimed-by). */\nexport function getDeviceJsonPath(): string {\n\treturn path.join(getServicemeHome(), DEVICE_JSON_FILENAME);\n}\n\n/** `~/.serviceme/toolbox.json` — local toolbox state (installed tool refs, per-user prefs). */\nexport function getToolboxJsonPath(): string {\n\treturn path.join(getServicemeHome(), TOOLBOX_JSON_FILENAME);\n}\n\n/** `~/.serviceme/machine-id` — opaque stable per-install id (uuid v4 string, no JSON wrapper). */\nexport function getMachineIdPath(): string {\n\treturn path.join(getServicemeHome(), MACHINE_ID_FILENAME);\n}\n\n/** `~/.serviceme/profiles.json` — cached projection of server-side profile rows; refresh on demand. */\nexport function getProfilesJsonPath(): string {\n\treturn path.join(getServicemeHome(), PROFILES_JSON_FILENAME);\n}\n"],"mappings":";AAAA,YAAY,QAAQ;AACpB,YAAYA,WAAU;;;ACDtB,YAAY,QAAQ;AACpB,YAAY,UAAU;AAef,IAAM,qBAAqB;AAC3B,IAAM,eAAe;AAerB,IAAM,uBAAuB;AAG7B,IAAM,qBAAqB;AAalC,IAAI,kBAAqC,CAAC;AAU1C,SAAS,iBAAyB;AACjC,QAAM,WAAW,gBAAgB;AACjC,MAAI,aAAa,QAAW;AAC3B,WAAO;AAAA,EACR;AACA,SAAU,WAAQ;AACnB;AAEA,SAAS,0BAA8C;AACtD,QAAM,WAAW,gBAAgB;AACjC,MAAI,aAAa,QAAW;AAG3B,WAAO,SAAS,SAAS,IAAI,WAAW;AAAA,EACzC;AACA,QAAM,WAAW,QAAQ,IAAI,kBAAkB;AAC/C,SAAO,YAAY,SAAS,SAAS,IAAI,WAAW;AACrD;AAMO,SAAS,iBAAiB,QAAwB;AACxD,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,KAAK,CAAC,qBAAqB,KAAK,MAAM,GAAG;AAC5F,UAAM,IAAI;AAAA,MACT,oBAAoB,KAAK,UAAU,MAAM,CAAC,gBAC3B,oBAAoB;AAAA,IAEpC;AAAA,EACD;AACA,SAAO;AACR;AASO,SAAS,aAAqB;AACpC,SAAO,eAAe;AACvB;AAOO,SAAS,mBAA2B;AAC1C,QAAM,WAAW,wBAAwB;AACzC,MAAI,aAAa,QAAW;AAC3B,WAAY,aAAQ,QAAQ;AAAA,EAC7B;AACA,SAAY,UAAK,eAAe,GAAG,kBAAkB;AACtD;AAGO,SAAS,cAAsB;AACrC,SAAY,UAAK,iBAAiB,GAAG,YAAY;AAClD;AAGO,SAAS,WAAW,QAAwB;AAClD,SAAY,UAAK,YAAY,GAAG,iBAAiB,MAAM,CAAC;AACzD;;;ADnEA,IAAM,eAA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Ae,cAAa,cAAQ,QAAQ,GAAG,MAAM,CAAC;AACnE;AASA,SAAS,wBAAwB,QAAoC;AACpE,QAAM,SAAS,GAAQ,SAAG,QAAa,SAAG;AAC1C,QAAM,MAAM,OAAO,QAAQ,MAAM;AACjC,MAAI,QAAQ,GAAI,QAAO;AACvB,QAAM,OAAO,OAAO,MAAM,MAAM,OAAO,MAAM;AAC7C,QAAM,CAAC,MAAM,IAAI,KAAK,MAAW,SAAG;AACpC,SAAO,UAAU;AAClB;AAGA,eAAe,eAAe,GAA0B;AACvD,MAAI;AACH,UAAMA,QAAO,MAAS,SAAM,CAAC;AAC7B,QAAIA,MAAK,YAAY,KAAK,CAACA,MAAK,eAAe,GAAG;AACjD,YAAS,MAAG,GAAG,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,IAChD,OAAO;AACN,YAAS,UAAO,CAAC;AAAA,IAClB;AAAA,EACD,SAAS,KAAK;AACb,QAAK,IAA8B,SAAS,SAAU;AACtD,UAAM;AAAA,EACP;AACD;","names":["path","stat"]}
1
+ {"version":3,"sources":["../src/skill-linker/index.ts","../src/paths/userHome.ts"],"sourcesContent":["import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport { getHomeDir, getRepoDir } from \"../paths/userHome\";\n\n/**\n * Skill & Agent v2 — Client SkillLinker (M3, path-parity revision)\n *\n * SkillLinker exposes a skill/agent from the user's global repos\n * (`~/.serviceme/repos/<repoId>/{skills,agents}/<name>/`) into either:\n *\n * - a workspace, at `<workspace>/.github/{skills,agents}/<name>` —\n * the same path Copilot/Claude actually scan for `SKILL.md` /\n * `AGENT.md`, so linking here has real effect (see the v1 parity\n * note below); or\n * - the user's global scope, at `~/.copilot/{skills,agents}/<name>`,\n * visible to every workspace.\n *\n * **v1 parity note**: an earlier revision linked into a private\n * `<workspace>/.serviceme/skills/<repoId>/<name>` directory. That path\n * is never scanned by the actual tooling, so installs were silently\n * inert. The path was moved to match `.github/skills` (the same\n * location the legacy v1 marketplace pipeline used). Because the link\n * path is now flat (no `<repoId>` segment), only one repo's version of\n * a given `<name>` can be linked into a given scope at a time.\n *\n * Platform behavior (per spec §11.8 — owner explicitly chose throw\n * over silent copy fallback):\n *\n * | platform | default mode | on failure |\n * |----------|--------------|-----------------------------|\n * | macOS | symlink | throw + platform hint |\n * | Linux | symlink | throw + platform hint |\n * | Windows | junction | throw + platform hint |\n *\n * Why junction first on Windows: NTFS junction doesn't require\n * SeCreateSymbolicLinkPrivilege; it works for any user. The limit is\n * the link target must be on a local NTFS volume. OneDrive / network\n * shares sometimes fail; we surface that as a typed error so callers\n * can decide whether to retry.\n *\n * @see docs/architecture/skill-agent-v2-repo.md §5.6 SkillLinker\n * @see docs/architecture/skill-agent-v2-repo.md §11.8 (throw, not copy)\n */\n\nexport type LinkMode = \"symlink\" | \"junction\" | \"copy\";\n\n/** Kind of artifact being linked. Mirrors `BridgeSkillKind`. */\nexport type EntryKind = \"skill\" | \"agent\";\n\n/**\n * Which scope the link lives in:\n * - `\"workspace\"` (default) → `<workspaceDir>/.github/<kind>/<name>`\n * - `\"user\"` → `~/.copilot/<kind>/<name>` (visible to every workspace)\n */\nexport type LinkScope = \"workspace\" | \"user\";\n\nconst ENTRY_SUBDIR: Record<EntryKind, string> = {\n\tskill: \"skills\",\n\tagent: \"agents\",\n};\n\nexport interface InstallSkillOptions {\n\trepoId: string;\n\tskillName: string;\n\tworkspaceDir: string;\n\t/** Choose link mode explicitly. Defaults to platform-optimal. */\n\tmode?: \"auto\" | LinkMode;\n\t/** \"skill\" (default) or \"agent\". */\n\tkind?: EntryKind;\n\t/** \"workspace\" (default) or \"user\". */\n\tscope?: LinkScope;\n\t/**\n\t * Pre-resolved absolute source path (from `SkillStore`), overriding\n\t * the `<repoRoot>/{skills,agents}/<name>` formula in\n\t * {@link resolveSkillTarget}. Required for repos with non-standard\n\t * layouts — flat root (no `skills/` prefix), nested scope dirs\n\t * (`skills/official/<name>`), or flat single-file agent manifests\n\t * (`agents/<name>.agent.md`) — which the formula can't predict.\n\t * When omitted, falls back to the formula (kept for callers that\n\t * install a hand-authored skill without going through `SkillStore`).\n\t */\n\tsourcePath?: string;\n\t/**\n\t * True when `sourcePath` points at a single manifest FILE (e.g. a\n\t * flat `<name>.agent.md`) rather than a directory. Determines the\n\t * symlink type (file vs dir/junction) and the link's basename (the\n\t * link mirrors the source file's name + extension, since Copilot/\n\t * VS Code scan `.github/agents/<name>.agent.md` as a FILE).\n\t */\n\tsourceIsFile?: boolean;\n}\n\nexport interface InstallSkillResult {\n\tmode: LinkMode;\n\tlinkPath: string;\n\ttargetPath: string;\n}\n\n/** Describes one symlink/junction currently present in a workspace/user scope. */\nexport interface LinkedSkill {\n\t/**\n\t * Repo id the link resolves to, parsed back out of the symlink\n\t * target. Empty string when the target isn't under a recognizable\n\t * `~/.serviceme/repos/<repoId>/...` path.\n\t */\n\trepoId: string;\n\tskillName: string;\n\tlinkPath: string;\n\ttargetPath: string;\n\tmode: LinkMode;\n\t/** Which scope this link was found in — \"workspace\" or \"user\" (global). */\n\tscope: LinkScope;\n}\n\n/**\n * Sentinel error for link failures. Carries the chosen mode + platform\n * hint so the UI can render an actionable message.\n */\nexport class LinkError extends Error {\n\treadonly mode: LinkMode;\n\treadonly target: string;\n\treadonly linkPath: string;\n\treadonly platform: NodeJS.Platform;\n\treadonly cause: unknown;\n\n\tconstructor(opts: {\n\t\tmode: LinkMode;\n\t\ttarget: string;\n\t\tlinkPath: string;\n\t\tplatform: NodeJS.Platform;\n\t\tcause: unknown;\n\t}) {\n\t\tsuper(\n\t\t\t`failed to ${opts.mode} link ${opts.linkPath} → ${opts.target} on ${opts.platform}: ${\n\t\t\t\topts.cause instanceof Error ? opts.cause.message : String(opts.cause)\n\t\t\t}`\n\t\t);\n\t\tthis.name = \"LinkError\";\n\t\tthis.mode = opts.mode;\n\t\tthis.target = opts.target;\n\t\tthis.linkPath = opts.linkPath;\n\t\tthis.platform = opts.platform;\n\t\tthis.cause = opts.cause;\n\t}\n\n\t/** A user-facing hint for the platform that failed. */\n\thint(): string {\n\t\treturn getPlatformHint(this.platform);\n\t}\n}\n\n/** Choose the platform-optimal link mode. */\nexport function pickMode(platform: NodeJS.Platform = process.platform): LinkMode {\n\treturn platform === \"win32\" ? \"junction\" : \"symlink\";\n}\n\n/** A short hint string for the platform where the link failed. */\nexport function getPlatformHint(platform: NodeJS.Platform): string {\n\tif (platform === \"win32\") {\n\t\treturn (\n\t\t\t\"On Windows, enable Developer Mode in Settings → Privacy & Security → \" +\n\t\t\t\"For developers, or run as Administrator. NTFS junction also requires the \" +\n\t\t\t\"target to be on a local NTFS volume (OneDrive / network shares are not supported).\"\n\t\t);\n\t}\n\treturn (\n\t\t\"Symlink creation failed. Check filesystem permissions and that the source \" +\n\t\t\"directory exists. On some filesystems (FAT32, exFAT, network mounts) symlinks \" +\n\t\t\"are not supported.\"\n\t);\n}\n\n/**\n * Resolve the source path inside `~/.serviceme/repos/<repoId>/{skills,agents}/<name>`.\n * Exported for callers that need to inspect the target without installing.\n */\nexport function resolveSkillTarget(\n\trepoId: string,\n\tskillName: string,\n\tkind: EntryKind = \"skill\"\n): string {\n\treturn path.join(getRepoDir(repoId), ENTRY_SUBDIR[kind], skillName);\n}\n\n/**\n * Resolve the workspace link path — `<workspaceDir>/.github/{skills,agents}/<name>` —\n * the same directory Copilot/Claude actually scan.\n */\nexport function resolveSkillLinkPath(\n\tworkspaceDir: string,\n\tskillName: string,\n\tkind: EntryKind = \"skill\"\n): string {\n\treturn path.join(workspaceDir, \".github\", ENTRY_SUBDIR[kind], skillName);\n}\n\n/**\n * Resolve the user-scope link path — `~/.copilot/{skills,agents}/<name>` —\n * visible to every workspace.\n */\nexport function resolveUserSkillLinkPath(skillName: string, kind: EntryKind = \"skill\"): string {\n\treturn path.join(getHomeDir(), \".copilot\", ENTRY_SUBDIR[kind], skillName);\n}\n\nfunction resolveLinkPath(opts: {\n\tworkspaceDir: string;\n\tskillName: string;\n\tkind: EntryKind;\n\tscope: LinkScope;\n\t/** When set, use this basename instead of the bare `skillName` — for\n\t * file-based sources the link must mirror the source's filename\n\t * (including its extension) to be scannable at its real path. */\n\tlinkBasename?: string;\n}): string {\n\tif (opts.scope === \"workspace\" && !opts.workspaceDir) {\n\t\tthrow new Error(\n\t\t\t\"workspaceDir is required for scope: 'workspace' (pass scope: 'user' for a global install instead).\"\n\t\t);\n\t}\n\tconst base =\n\t\topts.scope === \"user\"\n\t\t\t? resolveUserSkillLinkPath(opts.skillName, opts.kind)\n\t\t\t: resolveSkillLinkPath(opts.workspaceDir, opts.skillName, opts.kind);\n\treturn opts.linkBasename ? path.join(path.dirname(base), opts.linkBasename) : base;\n}\n\n/**\n * Install a skill into a workspace by creating a link at the standard\n * path. Throws `LinkError` on failure (no silent copy fallback per\n * §11.8).\n *\n * Idempotent: if the correct link already exists, returns the existing\n * record without touching the filesystem. If a *wrong* link exists at\n * the target path, it is replaced.\n */\nexport async function installSkillToWorkspace(\n\topts: InstallSkillOptions\n): Promise<InstallSkillResult> {\n\tconst kind = opts.kind ?? \"skill\";\n\tconst scope = opts.scope ?? \"workspace\";\n\tconst isFile = opts.sourceIsFile ?? false;\n\tconst target = opts.sourcePath ?? resolveSkillTarget(opts.repoId, opts.skillName, kind);\n\tconst linkPath = resolveLinkPath({\n\t\tworkspaceDir: opts.workspaceDir,\n\t\tskillName: opts.skillName,\n\t\tkind,\n\t\tscope,\n\t\tlinkBasename: isFile ? path.basename(target) : undefined,\n\t});\n\n\t// Sanity-check: the skill source directory must exist before we try\n\t// to link it. Otherwise the link would dangle.\n\tawait fs.access(target).catch(() => {\n\t\tthrow new LinkError({\n\t\t\tmode: \"symlink\", // placeholder — mode not chosen yet\n\t\t\ttarget,\n\t\t\tlinkPath,\n\t\t\tplatform: process.platform,\n\t\t\tcause: new Error(`skill source not found: ${target}`),\n\t\t});\n\t});\n\n\t// If the link already exists and points to the right target, no-op.\n\tif (await isCorrectLink(linkPath, target)) {\n\t\treturn { mode: \"symlink\", linkPath, targetPath: target };\n\t}\n\t// Otherwise, remove any stale entry at the path.\n\tawait removeIfExists(linkPath);\n\n\t// Junctions are directory-only — a file source can never use one,\n\t// regardless of platform default. Fall back to a real symlink.\n\tconst requestedMode = opts.mode === undefined || opts.mode === \"auto\" ? pickMode() : opts.mode;\n\tconst mode = isFile && requestedMode === \"junction\" ? \"symlink\" : requestedMode;\n\n\t// Ensure the parent directory exists — fs.symlink does NOT create\n\t// missing parents. The path is `<workspace>/.serviceme/skills/<repoId>/`,\n\t// which is several levels deep on a fresh workspace.\n\tawait fs.mkdir(path.dirname(linkPath), { recursive: true });\n\n\ttry {\n\t\tif (mode === \"junction\") {\n\t\t\t// fs.symlink with type \"junction\" works on Windows for dirs.\n\t\t\tawait fs.symlink(target, linkPath, \"junction\");\n\t\t} else if (mode === \"symlink\") {\n\t\t\t// Windows requires an explicit \"file\" type for file symlinks;\n\t\t\t// POSIX ignores the type argument either way.\n\t\t\tawait fs.symlink(target, linkPath, isFile ? \"file\" : \"dir\");\n\t\t} else {\n\t\t\t// `copy` mode is intentionally NOT implemented for v1 — see\n\t\t\t// spec §11.8 (\"throw, not copy fallback\"). Reaching this branch\n\t\t\t// means a caller explicitly passed `mode: 'copy'`; we treat\n\t\t\t// it as a configuration error rather than silently dropping\n\t\t\t// to copy semantics.\n\t\t\tthrow new LinkError({\n\t\t\t\tmode: \"copy\",\n\t\t\t\ttarget,\n\t\t\t\tlinkPath,\n\t\t\t\tplatform: process.platform,\n\t\t\t\tcause: new Error(\n\t\t\t\t\t\"copy mode is not supported in v1 — see spec §11.8 (throw, not copy fallback)\"\n\t\t\t\t),\n\t\t\t});\n\t\t}\n\t} catch (err) {\n\t\tif (err instanceof LinkError) throw err;\n\t\tthrow new LinkError({\n\t\t\tmode,\n\t\t\ttarget,\n\t\t\tlinkPath,\n\t\t\tplatform: process.platform,\n\t\t\tcause: err,\n\t\t});\n\t}\n\n\treturn { mode, linkPath, targetPath: target };\n}\n\n/**\n * Convert an existing, real (non-symlink) skill/agent directory at the\n * standard scan path into a symlink pointing at the matching global\n * repo entry. Refuses to run when there's nothing real to convert —\n * callers should only surface this action when a marketplace/scope\n * state check already confirmed a non-symlink install is present.\n */\nexport async function convertToSymlink(opts: InstallSkillOptions): Promise<InstallSkillResult> {\n\tconst kind = opts.kind ?? \"skill\";\n\tconst scope = opts.scope ?? \"workspace\";\n\tconst linkPath = resolveLinkPath({\n\t\tworkspaceDir: opts.workspaceDir,\n\t\tskillName: opts.skillName,\n\t\tkind,\n\t\tscope,\n\t\tlinkBasename: opts.sourceIsFile && opts.sourcePath ? path.basename(opts.sourcePath) : undefined,\n\t});\n\n\tconst stat = await fs.lstat(linkPath).catch(() => null);\n\tif (!stat) {\n\t\tthrow new Error(`Nothing installed at ${linkPath} to convert.`);\n\t}\n\tif (stat.isSymbolicLink()) {\n\t\tthrow new Error(`${linkPath} is already a symlink.`);\n\t}\n\n\treturn installSkillToWorkspace(opts);\n}\n\n/**\n * Remove a skill/agent link from a workspace/user scope. Idempotent:\n * succeeds when the link does not exist (no error).\n *\n * Tries the bare `<name>` path first (directory-based entries), then\n * falls back to scanning the scope dir for a `<name>.<ext>` file (flat\n * manifest entries, e.g. `CSharpExpert.agent.md`) — the caller doesn't\n * necessarily still have the source repo entry to know which shape was\n * installed (e.g. the repo may have been removed since).\n */\nexport async function uninstallSkillFromWorkspace(opts: {\n\trepoId: string;\n\tskillName: string;\n\tworkspaceDir: string;\n\tkind?: EntryKind;\n\tscope?: LinkScope;\n}): Promise<void> {\n\tconst kind = opts.kind ?? \"skill\";\n\tconst scope = opts.scope ?? \"workspace\";\n\tconst linkPath = resolveLinkPath({\n\t\tworkspaceDir: opts.workspaceDir,\n\t\tskillName: opts.skillName,\n\t\tkind,\n\t\tscope,\n\t});\n\tif (await pathExists(linkPath)) {\n\t\tawait removeIfExists(linkPath);\n\t\treturn;\n\t}\n\n\tconst scopeDir = path.dirname(linkPath);\n\tlet entries: import(\"node:fs\").Dirent[];\n\ttry {\n\t\tentries = await fs.readdir(scopeDir, { withFileTypes: true });\n\t} catch {\n\t\tentries = []; // primary scope dir missing — fall through (legacy handled below)\n\t}\n\tconst flatMatch = entries.find(\n\t\t(e) => e.name === opts.skillName || e.name.startsWith(`${opts.skillName}.`)\n\t);\n\tif (flatMatch) {\n\t\tawait removeIfExists(path.join(scopeDir, flatMatch.name));\n\t\treturn;\n\t}\n\tif (scope === \"user\") {\n\t\t// Legacy ~/.agents install — the primary root missed, so try there before giving up.\n\t\tconst legacyDir = path.join(getHomeDir(), LEGACY_USER_SCOPE_ROOT, ENTRY_SUBDIR[kind]);\n\t\tconst legacyEntries = await fs.readdir(legacyDir, { withFileTypes: true }).catch(() => []);\n\t\tconst legacyMatch = legacyEntries.find(\n\t\t\t(e) => e.name === opts.skillName || e.name.startsWith(`${opts.skillName}.`)\n\t\t);\n\t\tif (legacyMatch) {\n\t\t\tawait removeIfExists(path.join(legacyDir, legacyMatch.name));\n\t\t}\n\t}\n}\n\n/** `true` when `p` exists (following symlinks is irrelevant — `lstat` is enough). */\nasync function pathExists(p: string): Promise<boolean> {\n\ttry {\n\t\tawait fs.lstat(p);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nconst MANIFEST_FILENAME: Record<EntryKind, string> = {\n\tskill: \"SKILL.md\",\n\tagent: \"AGENT.md\",\n};\n\n/**\n * Legacy user-scope root used before the migration to `~/.copilot`.\n * Kept readable so user-scope listing can surface old links instead of\n * silently hiding content the user still has installed.\n */\nconst LEGACY_USER_SCOPE_ROOT = \".agents\";\n\n/**\n * Enumerate all skill/agent entries currently present in a workspace/user\n * scope — both symlinked installs (`mode: \"symlink\"`/`\"junction\"`) AND\n * real, non-symlink directories/files that already carry a valid\n * manifest (`mode: \"copy\"`). Used by the UI's \"Manage installed skills\"\n * view so it can show a real (copy-installed) entry as installed too —\n * this is common for the user (global) scope, where many skills are\n * placed by other tools/installers as plain copies rather than via this\n * package's symlink-only install flow. `repoId` is `\"\"` for `\"copy\"`\n * entries since there's no symlink target to resolve it from; callers\n * match these by name only. Returns an empty array when the scan\n * directory doesn't exist.\n */\nexport async function listLinkedSkills(\n\tworkspaceDir: string,\n\tkind: EntryKind = \"skill\",\n\tscope: LinkScope = \"workspace\"\n): Promise<LinkedSkill[]> {\n\t// No workspace open + workspace scope requested — nothing to scan.\n\t// Guard explicitly rather than falling through to\n\t// `path.join(\"\", \".github\", ...)`, which resolves to a *relative*\n\t// path (anchored at the process's cwd, not a real workspace) and\n\t// could accidentally match an unrelated directory there.\n\tif (scope === \"workspace\" && !workspaceDir) {\n\t\treturn [];\n\t}\n\tconst userRoot = path.join(getHomeDir(), \".copilot\", ENTRY_SUBDIR[kind]);\n\tconst root = scope === \"user\" ? userRoot : path.join(workspaceDir, \".github\", ENTRY_SUBDIR[kind]);\n\n\tlet entries: import(\"node:fs\").Dirent[];\n\ttry {\n\t\tentries = await fs.readdir(root, { withFileTypes: true });\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\tthrow err;\n\t}\n\n\tconst results: LinkedSkill[] = [];\n\tfor (const entry of entries) {\n\t\tconst entryPath = path.join(root, entry.name);\n\n\t\tif (entry.isSymbolicLink()) {\n\t\t\t// Flat manifest files (e.g. `CSharpExpert.agent.md`) report the\n\t\t\t// bare name, matching what SkillStore/install use elsewhere —\n\t\t\t// otherwise this would look like a different, unrelated entry.\n\t\t\tconst skillName = entry.name.replace(/\\.(agent|skill)\\.md$/, \"\");\n\t\t\tconst rawTarget = await readLinkTarget(entryPath);\n\t\t\tif (!rawTarget) continue; // unreadable\n\t\t\tconst resolvedTarget = resolveTargetPath(entryPath, rawTarget);\n\t\t\t// Skip dangling links — `fs.stat` follows symlinks and throws\n\t\t\t// ENOENT when the target is missing. That's the signal that\n\t\t\t// the link is broken.\n\t\t\tconst targetStat = await fs.stat(resolvedTarget).catch(() => null);\n\t\t\tif (!targetStat) continue;\n\t\t\tresults.push({\n\t\t\t\trepoId: extractRepoIdFromTarget(resolvedTarget) ?? \"\",\n\t\t\t\tskillName,\n\t\t\t\tlinkPath: entryPath,\n\t\t\t\ttargetPath: resolvedTarget,\n\t\t\t\tmode: process.platform === \"win32\" ? \"junction\" : \"symlink\",\n\t\t\t\tscope,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.isDirectory()) {\n\t\t\t// A real (copy-installed) directory — only counts as an\n\t\t\t// installed entry when it actually carries the expected\n\t\t\t// manifest file, so unrelated junk directories in the scope\n\t\t\t// dir (e.g. leftover `.DS_Store`-adjacent folders) aren't\n\t\t\t// misreported as installed skills/agents.\n\t\t\tconst hasManifest = await fs\n\t\t\t\t.access(path.join(entryPath, MANIFEST_FILENAME[kind]))\n\t\t\t\t.then(() => true)\n\t\t\t\t.catch(() => false);\n\t\t\tif (!hasManifest) continue;\n\t\t\tresults.push({\n\t\t\t\trepoId: \"\",\n\t\t\t\tskillName: entry.name,\n\t\t\t\tlinkPath: entryPath,\n\t\t\t\ttargetPath: entryPath,\n\t\t\t\tmode: \"copy\",\n\t\t\t\tscope,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.isFile() && entry.name.endsWith(`.${kind}.md`)) {\n\t\t\t// A real (copy-installed) flat manifest file, e.g. a plain\n\t\t\t// `CSharpExpert.agent.md` that was placed directly rather\n\t\t\t// than symlinked.\n\t\t\tresults.push({\n\t\t\t\trepoId: \"\",\n\t\t\t\tskillName: entry.name.replace(/\\.(agent|skill)\\.md$/, \"\"),\n\t\t\t\tlinkPath: entryPath,\n\t\t\t\ttargetPath: entryPath,\n\t\t\t\tmode: \"copy\",\n\t\t\t\tscope,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Surface legacy ~/.agents entries alongside ~/.copilot so entries installed before\n\t// the scope-root migration (or placed by other tooling) stay visible and manageable.\n\t// ~/.copilot wins on name conflicts.\n\tif (scope === \"user\") {\n\t\tconst seen = new Set(results.map((r) => r.skillName));\n\t\tfor (const legacy of await listLegacyUserScopeSkills(kind)) {\n\t\t\tif (!seen.has(legacy.skillName)) {\n\t\t\t\tresults.push(legacy);\n\t\t\t}\n\t\t}\n\t}\n\treturn results;\n}\n\n/**\n * List entries still living in the legacy `~/.agents` user scope.\n * Read-only: migration is an explicit user action elsewhere.\n */\nexport async function listLegacyUserScopeSkills(kind: EntryKind = \"skill\"): Promise<LinkedSkill[]> {\n\tconst root = path.join(getHomeDir(), LEGACY_USER_SCOPE_ROOT, ENTRY_SUBDIR[kind]);\n\tlet entries: import(\"node:fs\").Dirent[];\n\ttry {\n\t\tentries = await fs.readdir(root, { withFileTypes: true });\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\tthrow err;\n\t}\n\tconst results: LinkedSkill[] = [];\n\tfor (const entry of entries) {\n\t\tconst entryPath = path.join(root, entry.name);\n\t\tif (entry.isSymbolicLink()) {\n\t\t\tconst skillName = entry.name.replace(/\\.(agent|skill)\\.md$/, \"\");\n\t\t\tconst rawTarget = await readLinkTarget(entryPath);\n\t\t\tif (!rawTarget) continue;\n\t\t\tconst resolvedTarget = resolveTargetPath(entryPath, rawTarget);\n\t\t\tconst targetStat = await fs.stat(resolvedTarget).catch(() => null);\n\t\t\tif (!targetStat) continue;\n\t\t\tresults.push({\n\t\t\t\trepoId: extractRepoIdFromTarget(resolvedTarget) ?? \"\",\n\t\t\t\tskillName,\n\t\t\t\tlinkPath: entryPath,\n\t\t\t\ttargetPath: resolvedTarget,\n\t\t\t\tmode: process.platform === \"win32\" ? \"junction\" : \"symlink\",\n\t\t\t\tscope: \"user\",\n\t\t\t});\n\t\t} else if (entry.isDirectory()) {\n\t\t\tconst manifestPath = path.join(entryPath, MANIFEST_FILENAME[kind]);\n\t\t\tconst stat = await fs.stat(manifestPath).catch(() => null);\n\t\t\tif (stat?.isFile()) {\n\t\t\t\tresults.push({\n\t\t\t\t\trepoId: \"\",\n\t\t\t\t\tskillName: entry.name,\n\t\t\t\t\tlinkPath: entryPath,\n\t\t\t\t\ttargetPath: manifestPath,\n\t\t\t\t\tmode: \"copy\",\n\t\t\t\t\tscope: \"user\",\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\treturn results;\n}\n\n// ─────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ─────────────────────────────────────────────────────────────────────\n\n/** Returns `true` when `linkPath` is a symlink/junction pointing at `expectedTarget`. */\nasync function isCorrectLink(linkPath: string, expectedTarget: string): Promise<boolean> {\n\tlet actual: string | undefined;\n\ttry {\n\t\tactual = await readLinkTarget(linkPath);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (!actual) return false;\n\treturn resolveTargetPath(linkPath, actual) === resolveTargetPath(linkPath, expectedTarget);\n}\n\n/** Read a link's target without throwing — returns undefined on ENOENT. */\nasync function readLinkTarget(linkPath: string): Promise<string | undefined> {\n\ttry {\n\t\treturn await fs.readlink(linkPath);\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n\t\tthrow err;\n\t}\n}\n\n/**\n * Resolve a relative symlink target against its parent directory so a\n * relative link reads back as an absolute path comparable to another\n * absolute path.\n */\nfunction resolveTargetPath(linkPath: string, target: string): string {\n\tif (path.isAbsolute(target)) return path.normalize(target);\n\treturn path.normalize(path.resolve(path.dirname(linkPath), target));\n}\n\n/**\n * Parse the `<repoId>` segment back out of a resolved link target of\n * the shape `.../.serviceme/repos/<repoId>/{skills,agents}/<name>`.\n * Returns `undefined` when the target doesn't match that shape (e.g. a\n * hand-authored local skill under `~/.agents/skills/<name>` with no\n * backing repo).\n */\nfunction extractRepoIdFromTarget(target: string): string | undefined {\n\tconst marker = `${path.sep}repos${path.sep}`;\n\tconst idx = target.indexOf(marker);\n\tif (idx === -1) return undefined;\n\tconst rest = target.slice(idx + marker.length);\n\tconst [repoId] = rest.split(path.sep);\n\treturn repoId || undefined;\n}\n\n/** Best-effort removal of a path. ENOENT is silently ignored. */\nasync function removeIfExists(p: string): Promise<void> {\n\ttry {\n\t\tconst stat = await fs.lstat(p);\n\t\tif (stat.isDirectory() && !stat.isSymbolicLink()) {\n\t\t\tawait fs.rm(p, { recursive: true, force: true });\n\t\t} else {\n\t\t\tawait fs.unlink(p);\n\t\t}\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === \"ENOENT\") return;\n\t\tthrow err;\n\t}\n}\n","import * as os from \"node:os\";\nimport * as path from \"node:path\";\n\n/**\n * SERVICEME user home directory helpers.\n *\n * All paths resolve under {@link getServicemeHome}, which is either the\n * `SERVICEME_HOME` environment variable (when set and non-empty) or\n * `$HOME/.serviceme` on POSIX / `%USERPROFILE%\\.serviceme` on Windows.\n *\n * Tests inject `homeDir` and `servicemeHomeEnv` overrides via\n * {@link setUserHomeOverrides} / {@link resetUserHomeOverrides} so they can\n * exercise the path logic without touching the real user environment.\n */\n\n/** Layout constants — kept in one place so other modules can reuse them. */\nexport const SERVICEME_DIR_NAME = \".serviceme\";\nexport const REPOS_SUBDIR = \"repos\";\nexport const CACHE_SUBDIR = \"cache\";\nexport const DRAFTS_SUBDIR = \"drafts\";\nexport const SKILL_DRAFTS_SUBDIR = \"skills\";\nexport const AGENT_DRAFTS_SUBDIR = \"agents\";\nexport const REPOS_CONFIG_FILENAME = \"repos.json\";\nexport const WORKSPACES_SUBDIR = \"workspaces\";\nexport const WORKSPACE_CONTENT_STATE_FILENAME = \"copilot-content-state.json\";\n\n/** rev.20 — r7 BYOM Server Proxy toggle self-state (read by ext + CLI + server). */\nexport const SERVER_PROXY_GLOBAL_FILENAME = \"server-proxy.json\";\n\n/**\n * Repo id regex — used to validate any `repoId` argument before it is joined\n * into a filesystem path. Keeps path traversal attempts out and gives us a\n * predictable on-disk shape.\n */\nexport const SAFE_REPO_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;\n\n/** Environment variable that overrides the user-home root directory. */\nexport const SERVICEME_HOME_ENV = \"SERVICEME_HOME\";\n\n/**\n * Test seam: lets unit tests inject deterministic values for `os.homedir()`\n * and the `SERVICEME_HOME` env override without actually mutating\n * `process.env` (which would leak into other tests).\n */\ninterface UserHomeOverrides {\n\thomeDir?: string | undefined;\n\tservicemeHomeEnv?: string | undefined;\n\tplatform?: NodeJS.Platform | undefined;\n}\n\nlet activeOverrides: UserHomeOverrides = {};\n\nexport function setUserHomeOverrides(overrides: UserHomeOverrides): void {\n\tactiveOverrides = { ...overrides };\n}\n\nexport function resetUserHomeOverrides(): void {\n\tactiveOverrides = {};\n}\n\nfunction resolveHomeDir(): string {\n\tconst injected = activeOverrides.homeDir;\n\tif (injected !== undefined) {\n\t\treturn injected;\n\t}\n\treturn os.homedir();\n}\n\nfunction resolveServicemeHomeEnv(): string | undefined {\n\tconst injected = activeOverrides.servicemeHomeEnv;\n\tif (injected !== undefined) {\n\t\t// Treat empty string as \"not set\" — `process.env` always returns a string\n\t\t// but tests may deliberately pass \"\" to opt out.\n\t\treturn injected.length > 0 ? injected : undefined;\n\t}\n\tconst envValue = process.env[SERVICEME_HOME_ENV];\n\treturn envValue && envValue.length > 0 ? envValue : undefined;\n}\n\nfunction resolvePlatform(): NodeJS.Platform {\n\treturn activeOverrides.platform ?? process.platform;\n}\n\nexport function assertSafeRepoId(repoId: string): string {\n\tif (typeof repoId !== \"string\" || repoId.length === 0 || !SAFE_REPO_ID_PATTERN.test(repoId)) {\n\t\tthrow new Error(\n\t\t\t`Invalid repo id: ${JSON.stringify(repoId)}. ` +\n\t\t\t\t`Must match ${SAFE_REPO_ID_PATTERN} (alphanumeric start, then ` +\n\t\t\t\t`alphanumerics / underscores / hyphens, ≤ 64 chars).`\n\t\t);\n\t}\n\treturn repoId;\n}\n\n/**\n * The raw OS home directory (`os.homedir()`), honoring test overrides\n * ({@link setUserHomeOverrides}). Exported for callers that need a\n * home-relative path *outside* of `~/.serviceme` — e.g. the\n * `~/.agents/{skills,agents}` convention used by `SkillLinker` for\n * user-scope links.\n */\nexport function getHomeDir(): string {\n\treturn resolveHomeDir();\n}\n\n/**\n * Root directory for all SERVICEME user-level state. Resolves to\n * `${SERVICEME_HOME}` when that env var is set, otherwise `${HOME}/.serviceme`\n * (POSIX) or `%USERPROFILE%\\.serviceme` (Windows via `os.homedir`).\n */\nexport function getServicemeHome(): string {\n\tconst override = resolveServicemeHomeEnv();\n\tif (override !== undefined) {\n\t\treturn path.resolve(override);\n\t}\n\treturn path.join(resolveHomeDir(), SERVICEME_DIR_NAME);\n}\n\n/** `$HOME/.serviceme/repos` (or `${SERVICEME_HOME}/repos`). */\nexport function getReposDir(): string {\n\treturn path.join(getServicemeHome(), REPOS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/repos/<repoId>` — validates `repoId` first. */\nexport function getRepoDir(repoId: string): string {\n\treturn path.join(getReposDir(), assertSafeRepoId(repoId));\n}\n\n/** `$HOME/.serviceme/cache` — generic per-user cache. */\nexport function getCacheDir(): string {\n\treturn path.join(getServicemeHome(), CACHE_SUBDIR);\n}\n\n/** `$HOME/.serviceme/cache/<repoId>` — per-repo sync state lives here. */\nexport function getRepoCacheDir(repoId: string): string {\n\treturn path.join(getCacheDir(), assertSafeRepoId(repoId));\n}\n\n/** `$HOME/.serviceme/drafts` — local edits not yet pushed upstream. */\nexport function getDraftsDir(): string {\n\treturn path.join(getServicemeHome(), DRAFTS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/drafts/skills` — local skill drafts. */\nexport function getSkillDraftsDir(): string {\n\treturn path.join(getDraftsDir(), SKILL_DRAFTS_SUBDIR);\n}\n\n/** `$HOME/.serviceme/drafts/agents` — local agent drafts. */\nexport function getAgentDraftsDir(): string {\n\treturn path.join(getDraftsDir(), AGENT_DRAFTS_SUBDIR);\n}\n\n/**\n * `$HOME/.serviceme/repos.json` — the single config entry point for repo\n * metadata. Always under the resolved home root (i.e. follows\n * `SERVICEME_HOME` overrides too).\n */\nexport function getReposConfigPath(): string {\n\treturn path.join(getServicemeHome(), REPOS_CONFIG_FILENAME);\n}\n\n/** `~/.serviceme/workspaces` — machine-local per-workspace state root. */\nexport function getWorkspacesDir(): string {\n\treturn path.join(getServicemeHome(), WORKSPACES_SUBDIR);\n}\n\n/**\n * Convenience helper for callers that need to switch behaviour on platform\n * (e.g. `SkillLinker` chooses symlink vs junction). Exported mostly so tests\n * can pin the value without touching `process.platform` directly.\n */\nexport function getHomePlatform(): NodeJS.Platform {\n\treturn resolvePlatform();\n}\n\n// ─── Scheduled Tasks paths (added by M1.5.3) ───────────────────────────────\n\n/** Layout constants for scheduled-tasks files. Kept here so other modules\n * can reuse them and the names stay in sync with the design doc. */\nexport const SCHEDULED_TASKS_CONFIG_FILENAME = \"scheduled-tasks.json\";\nexport const SCHEDULED_TASKS_LOG_FILENAME = \"scheduled-tasks-log.json\";\nexport const SCHEDULER_PID_FILENAME = \"scheduler.pid\";\nexport const SCHEDULER_LOCK_FILENAME = \"scheduler.lock\";\nexport const SCHEDULER_LOG_FILENAME = \"scheduler.log\";\nexport const MIGRATION_FAILURES_FILENAME = \"migration-failures.json\";\nexport const KNOWN_WORKSPACES_FILENAME = \"known-workspaces.json\";\n\n/** `~/.serviceme/scheduled-tasks.json` — the global v2 task list. */\nexport function getScheduledTasksConfigPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULED_TASKS_CONFIG_FILENAME);\n}\n\n/** `~/.serviceme/scheduled-tasks-log.json` — the global execution log (200 LRU). */\nexport function getScheduledTasksLogPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULED_TASKS_LOG_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.pid` — global daemon PID file. */\nexport function getSchedulerPidPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_PID_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.lock` — global daemon startup flock. */\nexport function getSchedulerLockPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_LOCK_FILENAME);\n}\n\n/** `~/.serviceme/scheduler.log` — global daemon log (daemon lifecycle, not task execution). */\nexport function getSchedulerLogPath(): string {\n\treturn path.join(getServicemeHome(), SCHEDULER_LOG_FILENAME);\n}\n\n/** `~/.serviceme/migration-failures.json` — diagnostics for failed v1→v2 imports. */\nexport function getMigrationFailuresPath(): string {\n\treturn path.join(getServicemeHome(), MIGRATION_FAILURES_FILENAME);\n}\n\n/** `~/.serviceme/known-workspaces.json` — workspace list the extension has seen. */\nexport function getKnownWorkspacesPath(): string {\n\treturn path.join(getServicemeHome(), KNOWN_WORKSPACES_FILENAME);\n}\n\n// ─── r7 BYOM Server Proxy (rev.20) ─────────────────────────────────────────\n\n/**\n * `~/.serviceme/server-proxy.json` — r7 BYOM Server Proxy toggle\n * self-state. Written by the extension's `ProxyConfigService`, readable\n * by the CLI / Server so they can decide whether to route traffic\n * through the corporate proxy without booting VS Code.\n *\n * Lives under user-level `~/.serviceme/` (not under a workspace) because\n * the toggle is a *user preference* — the same human enabling it on\n * machine A should be able to rely on it on machine B after sync, not\n * have it disappear when they switch repos.\n */\nexport function getServerProxyGlobalPath(): string {\n\treturn path.join(getServicemeHome(), SERVER_PROXY_GLOBAL_FILENAME);\n}\n\n// ─── Phase 5 (auth + device + toolbox) placeholders (Spec §11.12) ────────\n\n/** Layout constants for the Phase 5 client-side state files. The server\n * already has the corresponding routes (`/api/v1/auth/...`,\n * `/api/v1/device/...`, etc.) — the client just needs the on-disk\n * file paths + a first-run bootstrap so the auth/device/toolbox\n * services can open + read them without a per-call existence check. */\nexport const CREDENTIALS_CONFIG_FILENAME = \"credentials.json\";\nexport const DEVICE_JSON_FILENAME = \"device.json\";\nexport const TOOLBOX_JSON_FILENAME = \"toolbox.json\";\nexport const MACHINE_ID_FILENAME = \"machine-id\";\nexport const PROFILES_JSON_FILENAME = \"profiles.json\";\n\n/** `~/.serviceme/credentials.json` — better-auth session tokens + refresh state (client-side cache). */\nexport function getCredentialsConfigPath(): string {\n\treturn path.join(getServicemeHome(), CREDENTIALS_CONFIG_FILENAME);\n}\n\n/** `~/.serviceme/device.json` — device enrollment payload (id, public key fingerprint, claimed-by). */\nexport function getDeviceJsonPath(): string {\n\treturn path.join(getServicemeHome(), DEVICE_JSON_FILENAME);\n}\n\n/** `~/.serviceme/toolbox.json` — local toolbox state (installed tool refs, per-user prefs). */\nexport function getToolboxJsonPath(): string {\n\treturn path.join(getServicemeHome(), TOOLBOX_JSON_FILENAME);\n}\n\n/** `~/.serviceme/machine-id` — opaque stable per-install id (uuid v4 string, no JSON wrapper). */\nexport function getMachineIdPath(): string {\n\treturn path.join(getServicemeHome(), MACHINE_ID_FILENAME);\n}\n\n/** `~/.serviceme/profiles.json` — cached projection of server-side profile rows; refresh on demand. */\nexport function getProfilesJsonPath(): string {\n\treturn path.join(getServicemeHome(), PROFILES_JSON_FILENAME);\n}\n"],"mappings":";AAAA,YAAY,QAAQ;AACpB,YAAYA,WAAU;;;ACDtB,YAAY,QAAQ;AACpB,YAAY,UAAU;AAef,IAAM,qBAAqB;AAC3B,IAAM,eAAe;AAiBrB,IAAM,uBAAuB;AAG7B,IAAM,qBAAqB;AAalC,IAAI,kBAAqC,CAAC;AAU1C,SAAS,iBAAyB;AACjC,QAAM,WAAW,gBAAgB;AACjC,MAAI,aAAa,QAAW;AAC3B,WAAO;AAAA,EACR;AACA,SAAU,WAAQ;AACnB;AAEA,SAAS,0BAA8C;AACtD,QAAM,WAAW,gBAAgB;AACjC,MAAI,aAAa,QAAW;AAG3B,WAAO,SAAS,SAAS,IAAI,WAAW;AAAA,EACzC;AACA,QAAM,WAAW,QAAQ,IAAI,kBAAkB;AAC/C,SAAO,YAAY,SAAS,SAAS,IAAI,WAAW;AACrD;AAMO,SAAS,iBAAiB,QAAwB;AACxD,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,KAAK,CAAC,qBAAqB,KAAK,MAAM,GAAG;AAC5F,UAAM,IAAI;AAAA,MACT,oBAAoB,KAAK,UAAU,MAAM,CAAC,gBAC3B,oBAAoB;AAAA,IAEpC;AAAA,EACD;AACA,SAAO;AACR;AASO,SAAS,aAAqB;AACpC,SAAO,eAAe;AACvB;AAOO,SAAS,mBAA2B;AAC1C,QAAM,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AAK,MAAW,SAAG;AACpC,SAAO,UAAU;AAClB;AAGA,eAAe,eAAe,GAA0B;AACvD,MAAI;AACH,UAAMA,QAAO,MAAS,SAAM,CAAC;AAC7B,QAAIA,MAAK,YAAY,KAAK,CAACA,MAAK,eAAe,GAAG;AACjD,YAAS,MAAG,GAAG,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,IAChD,OAAO;AACN,YAAS,UAAO,CAAC;AAAA,IAClB;AAAA,EACD,SAAS,KAAK;AACb,QAAK,IAA8B,SAAS,SAAU;AACtD,UAAM;AAAA,EACP;AACD;","names":["path","stat"]}
@@ -6,8 +6,9 @@ export { c as SkillKind, d as SkillNotFoundError } from './types-B9gk3dXH.mjs';
6
6
  * `WorkspaceSkillsInitializationService.extractFrontmatter`. We avoid
7
7
  * pulling a YAML dep into core; SKILL.md / AGENT.md in the wild use
8
8
  * a strict subset (top-level `key: value` pairs delimited by `---`).
9
- * Anything more exotic (nested mappings, multi-line scalars) is
10
- * passed through as the raw string in the corresponding value.
9
+ * Multi-line block scalars (`>`, `|-`, `|`) are folded into a single
10
+ * string value the very common `description: >` form would
11
+ * otherwise surface the bare `>` indicator as the whole description.
11
12
  */
12
13
  declare function extractFrontmatter(raw: string): {
13
14
  data: Record<string, unknown>;
@@ -16,13 +17,23 @@ declare function extractFrontmatter(raw: string): {
16
17
 
17
18
  declare class SkillStore {
18
19
  private readonly repoRoots;
20
+ /**
21
+ * Per-instance memo of repo walks. The catalog walk is a recursive
22
+ * readdir over the whole checkout — the dominant cost of every
23
+ * list/get — so results (and the in-flight promise) are reused for
24
+ * the store's lifetime. The handler that owns long-lived stores
25
+ * bounds staleness by rebuilding the store on a short TTL; within
26
+ * one store instance the tree is treated as immutable.
27
+ */
28
+ private readonly entriesMemo;
19
29
  constructor(opts: {
20
30
  repos: ReadonlyArray<{
21
31
  id: string;
22
32
  rootPath: string;
23
33
  }>;
24
34
  });
25
- /** All skills + agents across all registered repos. */
35
+ /** All skills + agents across all registered repos. Repos are walked
36
+ * concurrently — one slow checkout no longer stretches the total. */
26
37
  listAll(): Promise<SkillEntry[]>;
27
38
  /** All skills + agents under a single repo. */
28
39
  listByRepo(repoId: string): Promise<SkillEntry[]>;
@@ -30,6 +41,13 @@ declare class SkillStore {
30
41
  get(repoId: string, name: string): Promise<SkillDetail>;
31
42
  /** All files inside a single entry's directory (manifest + extras). */
32
43
  getFiles(repoId: string, name: string): Promise<SkillFile[]>;
44
+ /**
45
+ * Memoized walk. Sharing the promise collapses concurrent list/get
46
+ * calls over the same repo into a single traversal; a rejected walk
47
+ * is dropped so the next call retries from disk.
48
+ */
49
+ private listByRepoCached;
50
+ private walkRepo;
33
51
  }
34
52
 
35
53
  export { SkillDetail, SkillEntry, SkillFile, SkillStore, extractFrontmatter };
@@ -6,8 +6,9 @@ export { c as SkillKind, d as SkillNotFoundError } from './types-B9gk3dXH.js';
6
6
  * `WorkspaceSkillsInitializationService.extractFrontmatter`. We avoid
7
7
  * pulling a YAML dep into core; SKILL.md / AGENT.md in the wild use
8
8
  * a strict subset (top-level `key: value` pairs delimited by `---`).
9
- * Anything more exotic (nested mappings, multi-line scalars) is
10
- * passed through as the raw string in the corresponding value.
9
+ * Multi-line block scalars (`>`, `|-`, `|`) are folded into a single
10
+ * string value the very common `description: >` form would
11
+ * otherwise surface the bare `>` indicator as the whole description.
11
12
  */
12
13
  declare function extractFrontmatter(raw: string): {
13
14
  data: Record<string, unknown>;
@@ -16,13 +17,23 @@ declare function extractFrontmatter(raw: string): {
16
17
 
17
18
  declare class SkillStore {
18
19
  private readonly repoRoots;
20
+ /**
21
+ * Per-instance memo of repo walks. The catalog walk is a recursive
22
+ * readdir over the whole checkout — the dominant cost of every
23
+ * list/get — so results (and the in-flight promise) are reused for
24
+ * the store's lifetime. The handler that owns long-lived stores
25
+ * bounds staleness by rebuilding the store on a short TTL; within
26
+ * one store instance the tree is treated as immutable.
27
+ */
28
+ private readonly entriesMemo;
19
29
  constructor(opts: {
20
30
  repos: ReadonlyArray<{
21
31
  id: string;
22
32
  rootPath: string;
23
33
  }>;
24
34
  });
25
- /** All skills + agents across all registered repos. */
35
+ /** All skills + agents across all registered repos. Repos are walked
36
+ * concurrently — one slow checkout no longer stretches the total. */
26
37
  listAll(): Promise<SkillEntry[]>;
27
38
  /** All skills + agents under a single repo. */
28
39
  listByRepo(repoId: string): Promise<SkillEntry[]>;
@@ -30,6 +41,13 @@ declare class SkillStore {
30
41
  get(repoId: string, name: string): Promise<SkillDetail>;
31
42
  /** All files inside a single entry's directory (manifest + extras). */
32
43
  getFiles(repoId: string, name: string): Promise<SkillFile[]>;
44
+ /**
45
+ * Memoized walk. Sharing the promise collapses concurrent list/get
46
+ * calls over the same repo into a single traversal; a rejected walk
47
+ * is dropped so the next call retries from disk.
48
+ */
49
+ private listByRepoCached;
50
+ private walkRepo;
33
51
  }
34
52
 
35
53
  export { SkillDetail, SkillEntry, SkillFile, SkillStore, extractFrontmatter };
@@ -99,12 +99,35 @@ function extractFrontmatter(raw) {
99
99
  const yamlBody = match[1] ?? "";
100
100
  const body = match[2] ?? "";
101
101
  const data = {};
102
- for (const line of yamlBody.split(/\r?\n/)) {
102
+ const lines = yamlBody.split(/\r?\n/);
103
+ for (let i = 0; i < lines.length; i++) {
104
+ const line = lines[i] ?? "";
103
105
  if (line.trim().length === 0) continue;
104
106
  if (line.trim().startsWith("#")) continue;
105
107
  const kv = line.match(/^([a-zA-Z_][\w-]*)\s*:\s*(.*)$/);
106
108
  if (!kv?.[1]) continue;
107
109
  let value = (kv[2] ?? "").trim();
110
+ if (typeof value === "string" && /^[>|][+-]?$/.test(value)) {
111
+ const folded = [];
112
+ let j = i + 1;
113
+ for (; j < lines.length; j++) {
114
+ const next = lines[j] ?? "";
115
+ if (next.trim().length === 0) {
116
+ const after = lines[j + 1];
117
+ if (after !== void 0 && /^[ \t]/.test(after)) {
118
+ folded.push("");
119
+ continue;
120
+ }
121
+ break;
122
+ }
123
+ if (!/^[ \t]/.test(next)) break;
124
+ folded.push(next.trim());
125
+ }
126
+ i = j - 1;
127
+ value = folded.join(" ").replace(/\s+/g, " ").trim();
128
+ data[kv[1]] = value;
129
+ continue;
130
+ }
108
131
  if (typeof value === "string") {
109
132
  if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
110
133
  value = value.slice(1, -1);
@@ -116,55 +139,86 @@ function extractFrontmatter(raw) {
116
139
  }
117
140
  var SkillStore = class {
118
141
  constructor(opts) {
142
+ /**
143
+ * Per-instance memo of repo walks. The catalog walk is a recursive
144
+ * readdir over the whole checkout — the dominant cost of every
145
+ * list/get — so results (and the in-flight promise) are reused for
146
+ * the store's lifetime. The handler that owns long-lived stores
147
+ * bounds staleness by rebuilding the store on a short TTL; within
148
+ * one store instance the tree is treated as immutable.
149
+ */
150
+ this.entriesMemo = /* @__PURE__ */ new Map();
119
151
  this.repoRoots = /* @__PURE__ */ new Map();
120
152
  for (const r of opts.repos) this.repoRoots.set(r.id, r.rootPath);
121
153
  }
122
- /** All skills + agents across all registered repos. */
154
+ /** All skills + agents across all registered repos. Repos are walked
155
+ * concurrently — one slow checkout no longer stretches the total. */
123
156
  async listAll() {
124
- const all = [];
125
- for (const repoId of this.repoRoots.keys()) {
126
- all.push(...await this.listByRepo(repoId));
127
- }
128
- return all;
157
+ const perRepo = await Promise.all(
158
+ [...this.repoRoots.keys()].map((repoId) => this.listByRepo(repoId))
159
+ );
160
+ return perRepo.flat();
129
161
  }
130
162
  /** All skills + agents under a single repo. */
131
163
  async listByRepo(repoId) {
132
- const root = this.repoRoots.get(repoId);
133
- if (!root) return [];
134
- const layout = await loadRepoLayout(root) ?? DEFAULT_REPO_LAYOUT;
135
- const entries = [];
136
- await walkForEntries(root, repoId, entries, layout);
137
- return entries;
164
+ const entries = await this.listByRepoCached(repoId);
165
+ return [...entries];
138
166
  }
139
167
  /** Single entry detail (manifest + all files inside its dir). */
140
168
  async get(repoId, name) {
141
- const entries = await this.listByRepo(repoId);
169
+ const entries = await this.listByRepoCached(repoId);
142
170
  const found = entries.find((e) => e.name === name);
143
171
  if (!found) throw new SkillNotFoundError(repoId, name);
144
- const files = await this.getFiles(repoId, name);
172
+ const files = await collectEntryFiles(found);
145
173
  return { ...found, files };
146
174
  }
147
175
  /** All files inside a single entry's directory (manifest + extras). */
148
176
  async getFiles(repoId, name) {
149
- const entries = await this.listByRepo(repoId);
177
+ const entries = await this.listByRepoCached(repoId);
150
178
  const found = entries.find((e) => e.name === name);
151
179
  if (!found) throw new SkillNotFoundError(repoId, name);
152
- const out = [];
153
- if (found.dir === found.manifestPath) {
154
- const content = await fs2.readFile(found.manifestPath, "utf8");
155
- return [{ path: path2.basename(found.manifestPath), content }];
156
- }
157
- await collectFilesRecursive(found.dir, found.dir, out);
158
- out.sort((a, b) => {
159
- const aIsManifest = a.path === "SKILL.md" || a.path === "AGENT.md";
160
- const bIsManifest = b.path === "SKILL.md" || b.path === "AGENT.md";
161
- if (aIsManifest && !bIsManifest) return -1;
162
- if (bIsManifest && !aIsManifest) return 1;
163
- return a.path.localeCompare(b.path);
180
+ return collectEntryFiles(found);
181
+ }
182
+ /**
183
+ * Memoized walk. Sharing the promise collapses concurrent list/get
184
+ * calls over the same repo into a single traversal; a rejected walk
185
+ * is dropped so the next call retries from disk.
186
+ */
187
+ listByRepoCached(repoId) {
188
+ const memoized = this.entriesMemo.get(repoId);
189
+ if (memoized) return memoized;
190
+ const walk = this.walkRepo(repoId).catch((error) => {
191
+ this.entriesMemo.delete(repoId);
192
+ throw error;
164
193
  });
165
- return out;
194
+ this.entriesMemo.set(repoId, walk);
195
+ return walk;
196
+ }
197
+ async walkRepo(repoId) {
198
+ const root = this.repoRoots.get(repoId);
199
+ if (!root) return [];
200
+ const layout = await loadRepoLayout(root) ?? DEFAULT_REPO_LAYOUT;
201
+ const entries = [];
202
+ await walkForEntries(root, repoId, entries, layout);
203
+ return entries;
166
204
  }
167
205
  };
206
+ async function collectEntryFiles(found) {
207
+ const out = [];
208
+ if (found.dir === found.manifestPath) {
209
+ const content = await fs2.readFile(found.manifestPath, "utf8");
210
+ return [{ path: path2.basename(found.manifestPath), content }];
211
+ }
212
+ await collectFilesRecursive(found.dir, found.dir, out);
213
+ out.sort((a, b) => {
214
+ const aIsManifest = a.path === "SKILL.md" || a.path === "AGENT.md";
215
+ const bIsManifest = b.path === "SKILL.md" || b.path === "AGENT.md";
216
+ if (aIsManifest && !bIsManifest) return -1;
217
+ if (bIsManifest && !aIsManifest) return 1;
218
+ return a.path.localeCompare(b.path);
219
+ });
220
+ return out;
221
+ }
168
222
  var SKIP_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", ".vscode", "dist", "build", "out"]);
169
223
  var SKIP_TOP_LEVEL_SCAN_DIRS = /* @__PURE__ */ new Set([...SKIP_DIRS, "plugins"]);
170
224
  var FLAT_AGENT_FILE_SUFFIX = ".agent.md";
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/skill-store/index.ts","../src/repo-layout/index.ts","../src/skill-store/types.ts"],"sourcesContent":["import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { DEFAULT_REPO_LAYOUT, loadRepoLayout, type RepoLayoutDescriptor } from \"../repo-layout\";\nimport type { SkillDetail, SkillEntry, SkillFile, SkillKind } from \"./types\";\nimport { SkillNotFoundError } from \"./types\";\n\n/**\n * Minimal frontmatter reader — same shape as the extension's\n * `WorkspaceSkillsInitializationService.extractFrontmatter`. We avoid\n * pulling a YAML dep into core; SKILL.md / AGENT.md in the wild use\n * a strict subset (top-level `key: value` pairs delimited by `---`).\n * Anything more exotic (nested mappings, multi-line scalars) is\n * passed through as the raw string in the corresponding value.\n */\nexport function extractFrontmatter(\n\traw: string\n): { data: Record<string, unknown>; body: string } | null {\n\tif (typeof raw !== \"string\") return null;\n\tconst match = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n\tif (!match) return null;\n\tconst yamlBody = match[1] ?? \"\";\n\tconst body = match[2] ?? \"\";\n\tconst data: Record<string, unknown> = {};\n\tfor (const line of yamlBody.split(/\\r?\\n/)) {\n\t\tif (line.trim().length === 0) continue;\n\t\tif (line.trim().startsWith(\"#\")) continue;\n\t\tconst kv = line.match(/^([a-zA-Z_][\\w-]*)\\s*:\\s*(.*)$/);\n\t\tif (!kv?.[1]) continue;\n\t\tlet value: unknown = (kv[2] ?? \"\").trim();\n\t\tif (typeof value === \"string\") {\n\t\t\tif (\n\t\t\t\t(value.startsWith('\"') && value.endsWith('\"')) ||\n\t\t\t\t(value.startsWith(\"'\") && value.endsWith(\"'\"))\n\t\t\t) {\n\t\t\t\tvalue = value.slice(1, -1);\n\t\t\t}\n\t\t}\n\t\tdata[kv[1]] = value;\n\t}\n\treturn { data, body };\n}\n\nexport type { SkillDetail, SkillEntry, SkillFile, SkillKind } from \"./types\";\n/**\n * Skill & Agent v2 — SkillStore (M4)\n *\n * Scans the local `~/.serviceme/repos/<id>/` tree to produce a unified\n * list of skills + agents. Local-only — no git, no network. Spec §5.5.\n *\n * Layout normalization (spec §12):\n * 1. **Standard layout** — `skills/<name>/SKILL.md` or\n * `agents/<name>/AGENT.md` under the repo root.\n * 2. **Anthropic flat layout** — `<name>/SKILL.md` directly under\n * the repo root (the `skills/` prefix is omitted).\n * 3. **awesome-copilot style** — root contains README + subdirs\n * that are skills/agents/instructions; we ignore README and\n * any dir without a manifest file.\n * 4. **Flat agent files** — a directory (commonly `agents/` or\n * `agents/official/`) full of `<name>.agent.md` files, one per\n * agent, with NO per-agent subdirectory. This is the prevailing\n * real-world convention (VS Code custom chat agents, GitHub's\n * awesome-copilot, and our own official ms-skills repo all ship\n * agents this way) — unlike skills, agents in the wild are\n * essentially never a `<name>/AGENT.md` directory pair. Detected\n * unconditionally, no `.serviceme-repo.json` opt-in required.\n *\n * Implementation: walk every directory under the repo root, check for\n * SKILL.md or AGENT.md, register if present. We skip the repo root\n * itself (no manifest lives at the top), `.git/`, and `node_modules/`.\n * Flat `*.agent.md` files are checked alongside directories at every\n * level of the walk.\n */\n// Re-export the error class + shared types so callers can\n// `import { SkillNotFoundError, SkillFile } from \"...\"`.\nexport { SkillNotFoundError } from \"./types\";\n\nexport class SkillStore {\n\tprivate readonly repoRoots: Map<string, string>;\n\n\tconstructor(opts: {\n\t\trepos: ReadonlyArray<{ id: string; rootPath: string }>;\n\t}) {\n\t\tthis.repoRoots = new Map();\n\t\tfor (const r of opts.repos) this.repoRoots.set(r.id, r.rootPath);\n\t}\n\n\t/** All skills + agents across all registered repos. */\n\tasync listAll(): Promise<SkillEntry[]> {\n\t\tconst all: SkillEntry[] = [];\n\t\tfor (const repoId of this.repoRoots.keys()) {\n\t\t\tall.push(...(await this.listByRepo(repoId)));\n\t\t}\n\t\treturn all;\n\t}\n\n\t/** All skills + agents under a single repo. */\n\tasync listByRepo(repoId: string): Promise<SkillEntry[]> {\n\t\tconst root = this.repoRoots.get(repoId);\n\t\tif (!root) return [];\n\t\tconst layout = (await loadRepoLayout(root)) ?? DEFAULT_REPO_LAYOUT;\n\t\tconst entries: SkillEntry[] = [];\n\t\tawait walkForEntries(root, repoId, entries, layout);\n\t\treturn entries;\n\t}\n\n\t/** Single entry detail (manifest + all files inside its dir). */\n\tasync get(repoId: string, name: string): Promise<SkillDetail> {\n\t\tconst entries = await this.listByRepo(repoId);\n\t\tconst found = entries.find((e) => e.name === name);\n\t\tif (!found) throw new SkillNotFoundError(repoId, name);\n\t\tconst files = await this.getFiles(repoId, name);\n\t\treturn { ...found, files };\n\t}\n\n\t/** All files inside a single entry's directory (manifest + extras). */\n\tasync getFiles(repoId: string, name: string): Promise<SkillFile[]> {\n\t\tconst entries = await this.listByRepo(repoId);\n\t\tconst found = entries.find((e) => e.name === name);\n\t\tif (!found) throw new SkillNotFoundError(repoId, name);\n\n\t\tconst out: SkillFile[] = [];\n\t\t// Flat single-file entries (e.g. `agents/foo.agent.md`) have `dir`\n\t\t// pointing at the manifest file itself, not a directory — there's\n\t\t// no sibling files to collect, just the one manifest.\n\t\tif (found.dir === found.manifestPath) {\n\t\t\tconst content = await fs.readFile(found.manifestPath, \"utf8\");\n\t\t\treturn [{ path: path.basename(found.manifestPath), content }];\n\t\t}\n\t\tawait collectFilesRecursive(found.dir, found.dir, out);\n\t\t// Sort for determinism (manifest first, then alphabetical)\n\t\tout.sort((a, b) => {\n\t\t\tconst aIsManifest = a.path === \"SKILL.md\" || a.path === \"AGENT.md\";\n\t\t\tconst bIsManifest = b.path === \"SKILL.md\" || b.path === \"AGENT.md\";\n\t\t\tif (aIsManifest && !bIsManifest) return -1;\n\t\t\tif (bIsManifest && !aIsManifest) return 1;\n\t\t\treturn a.path.localeCompare(b.path);\n\t\t});\n\t\treturn out;\n\t}\n}\n\n// ─────────────────────────────────────────────────────────────────────\n// Internals\n// ─────────────────────────────────────────────────────────────────────\n\nconst SKIP_DIRS = new Set([\".git\", \"node_modules\", \".vscode\", \"dist\", \"build\", \"out\"]);\n\n/**\n * Directories that are never treated as candidate skill/agent parents\n * during the top-level catalog walk. `plugins/` is a distinct concept\n * from the skill/agent catalog itself — a plugin bundle\n * (`plugins/<scope>/<plugin-name>/{skills,agents}/...`) re-packages\n * ALREADY-cataloged official skills/agents (see the plugin's own\n * `catalog.json`, which lists them by name) purely for discovery\n * grouping. Walking into it produces duplicate `SkillEntry` values\n * with the SAME `repoId`+`name` as their real, top-level counterpart\n * (e.g. `skills/official/acreadiness-assess` AND\n * `plugins/official/acreadiness-cockpit/skills/acreadiness-assess`),\n * which breaks anything keyed on `repoId/name` (React list rendering,\n * the \"installed\" lookup, `SkillStore.get()`'s `.find()`).\n *\n * Scoped separately from `SKIP_DIRS` (used by both this walk AND\n * `collectFilesRecursive`) so an actual skill that happens to ship its\n * own `plugins/` asset folder still has that folder listed in its own\n * file detail view.\n */\nconst SKIP_TOP_LEVEL_SCAN_DIRS = new Set([...SKIP_DIRS, \"plugins\"]);\n\n/** Suffix that marks a standalone file as a flat agent manifest (no wrapping dir). */\nconst FLAT_AGENT_FILE_SUFFIX = \".agent.md\";\n\n/**\n * Recursive walk that yields SkillEntry values for any directory\n * containing a SKILL.md or AGENT.md file, PLUS any standalone\n * `<name>.agent.md` file (see class doc, layout style 4). The dir\n * itself is the \"entry root\" for directory-based entries; the\n * manifest file itself is the \"entry root\" for flat agent files.\n *\n * The optional `layout` descriptor (from `.serviceme-repo.json`)\n * widens the scan: included subdirs are walked even without a\n * manifest at the top level, and `treatFilesAsSkills` surfaces\n * `<name>.md` files inside them as skills (frontmatter parsed\n * from the file body).\n */\nasync function walkForEntries(\n\trootDir: string,\n\trepoId: string,\n\tout: SkillEntry[],\n\tlayout: RepoLayoutDescriptor = DEFAULT_REPO_LAYOUT\n): Promise<void> {\n\tlet dirents: import(\"node:fs\").Dirent[];\n\ttry {\n\t\tdirents = await fs.readdir(rootDir, { withFileTypes: true });\n\t} catch {\n\t\treturn;\n\t}\n\n\tfor (const d of dirents) {\n\t\tif (d.isFile() && d.name.endsWith(FLAT_AGENT_FILE_SUFFIX)) {\n\t\t\tconst filePath = path.join(rootDir, d.name);\n\t\t\tconst stat = await fs.stat(filePath);\n\t\t\tconst content = await fs.readFile(filePath, \"utf8\");\n\t\t\tconst parsed = extractFrontmatter(content);\n\t\t\tout.push({\n\t\t\t\trepoId,\n\t\t\t\tname: d.name.slice(0, -FLAT_AGENT_FILE_SUFFIX.length),\n\t\t\t\tkind: \"agent\",\n\t\t\t\tmanifestPath: filePath,\n\t\t\t\t// Sentinel: `dir === manifestPath` marks a flat single-file\n\t\t\t\t// entry (no directory of its own — see getFiles()).\n\t\t\t\tdir: filePath,\n\t\t\t\tfrontmatter: parsed?.data ?? {},\n\t\t\t\tmodifiedAt: stat.mtime.toISOString(),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!d.isDirectory()) continue;\n\t\tif (SKIP_TOP_LEVEL_SCAN_DIRS.has(d.name)) continue;\n\t\tif (layout.exclude.includes(d.name)) continue;\n\t\tconst childDir = path.join(rootDir, d.name);\n\t\tconst kind = await detectKind(childDir);\n\t\tif (kind) {\n\t\t\tconst manifestFilename = kind === \"skill\" ? \"SKILL.md\" : \"AGENT.md\";\n\t\t\tconst manifestPath = path.join(childDir, manifestFilename);\n\t\t\tconst stat = await fs.stat(manifestPath);\n\t\t\tconst content = await fs.readFile(manifestPath, \"utf8\");\n\t\t\tconst parsed = extractFrontmatter(content);\n\t\t\tout.push({\n\t\t\t\trepoId,\n\t\t\t\tname: d.name,\n\t\t\t\tkind,\n\t\t\t\tmanifestPath,\n\t\t\t\tdir: childDir,\n\t\t\t\tfrontmatter: parsed?.data ?? {},\n\t\t\t\tmodifiedAt: stat.mtime.toISOString(),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\t// No manifest at the top — recurse, but ALSO check whether\n\t\t// the layout descriptor wants this subdir widened.\n\t\tawait walkForEntries(childDir, repoId, out, layout);\n\t\tif (layout.treatFilesAsSkills && layout.include.includes(d.name)) {\n\t\t\tawait surfaceFilesAsSkills(childDir, d.name, repoId, out);\n\t\t}\n\t}\n}\n\n/**\n * Walk `<includedSubdir>/<file>.md` and register each as a skill.\n * The `.md` file itself is the manifest — frontmatter (if any) is\n * parsed and surfaced. This is the awesome-copilot style: a\n * `prompts/` dir full of `<name>.md` files, no SKILL.md anywhere.\n */\nasync function surfaceFilesAsSkills(\n\tabsDir: string,\n\trelName: string,\n\trepoId: string,\n\tout: SkillEntry[]\n): Promise<void> {\n\tlet dirents: import(\"node:fs\").Dirent[];\n\ttry {\n\t\tdirents = await fs.readdir(absDir, { withFileTypes: true });\n\t} catch {\n\t\treturn;\n\t}\n\tfor (const d of dirents) {\n\t\tif (!d.isFile()) continue;\n\t\tif (!d.name.endsWith(\".md\")) continue;\n\t\tconst filePath = path.join(absDir, d.name);\n\t\tconst stat = await fs.stat(filePath);\n\t\tconst content = await fs.readFile(filePath, \"utf8\");\n\t\tconst parsed = extractFrontmatter(content);\n\t\t// Entry name = \"<subdir>/<file>\" (with the .md stripped) so it\n\t\t// stays unique even when two included subdirs share filenames.\n\t\tconst entryName = `${relName}/${d.name.replace(/\\.md$/, \"\")}`;\n\t\tout.push({\n\t\t\trepoId,\n\t\t\tname: entryName,\n\t\t\tkind: \"skill\",\n\t\t\tmanifestPath: filePath,\n\t\t\tdir: absDir,\n\t\t\tfrontmatter: parsed?.data ?? {},\n\t\t\tmodifiedAt: stat.mtime.toISOString(),\n\t\t});\n\t}\n}\n\n/**\n * Returns the SkillKind of a directory if it contains a manifest file,\n * or `null` if it doesn't. Manifest precedence: SKILL.md wins if both\n * are present (defensive — the spec separates skills and agents into\n * different subdir trees, so this collision shouldn't happen in\n * well-formed repos).\n */\nasync function detectKind(dir: string): Promise<SkillKind | null> {\n\tconst [hasSkill, hasAgent] = await Promise.all([\n\t\tfs\n\t\t\t.access(path.join(dir, \"SKILL.md\"))\n\t\t\t.then(() => true)\n\t\t\t.catch(() => false),\n\t\tfs\n\t\t\t.access(path.join(dir, \"AGENT.md\"))\n\t\t\t.then(() => true)\n\t\t\t.catch(() => false),\n\t]);\n\tif (hasSkill) return \"skill\";\n\tif (hasAgent) return \"agent\";\n\treturn null;\n}\n\n/**\n * Walk a skill/agent directory recursively, pushing every file into\n * `out` with its path RELATIVE to the entry root. Skips `.git/`,\n * `node_modules/`, and the SKIP_DIRS set.\n */\nasync function collectFilesRecursive(\n\tabsDir: string,\n\tentryRoot: string,\n\tout: SkillFile[]\n): Promise<void> {\n\tlet dirents: import(\"node:fs\").Dirent[];\n\ttry {\n\t\tdirents = await fs.readdir(absDir, { withFileTypes: true });\n\t} catch {\n\t\treturn;\n\t}\n\tfor (const d of dirents) {\n\t\tif (SKIP_DIRS.has(d.name)) continue;\n\t\tconst full = path.join(absDir, d.name);\n\t\tif (d.isDirectory()) {\n\t\t\tawait collectFilesRecursive(full, entryRoot, out);\n\t\t} else if (d.isFile()) {\n\t\t\tconst content = await fs.readFile(full, \"utf8\");\n\t\t\tout.push({ path: path.relative(entryRoot, full), content });\n\t\t}\n\t}\n}\n","/**\n * Spec §12 — Repo layout descriptor.\n *\n * Some third-party repos (awesome-copilot, composio) use a\n * non-default layout that mixes prompts / instructions / agents /\n * hooks / plugins at the root. The default SkillStore scan\n * (see ../skill-store/index.ts) only picks up directories that\n * contain a `SKILL.md` or `AGENT.md` manifest, so prompts stored\n * as `<subdir>/<name>.md` (no manifest) get missed.\n *\n * This module is the loader for the optional `.serviceme-repo.json`\n * marker file a repo author can drop in at the repo root to opt\n * into a wider scan. The schema:\n *\n * {\n * \"schema\": 1,\n * \"include\": [\"prompts\", \"instructions\"], // subdirs to treat as \"skill dirs\"\n * \"exclude\": [\"hooks\", \"plugins\"], // subdirs to skip\n * \"treatFilesAsSkills\": true // inside an included subdir, each .md file is a skill\n * }\n *\n * All four fields are optional. The defaults match the v0.2\n * walkForEntries behaviour (manifest-based, no marker, no\n * extensions), so adding the file is purely additive.\n *\n * @see docs/architecture/skill-agent-v2-repo.md §12\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nconst MARKER_FILENAME = \".serviceme-repo.json\";\nconst SUPPORTED_SCHEMA = 1;\n\nexport interface RepoLayoutDescriptor {\n\t/** Schema version. Currently always 1. */\n\tschema: number;\n\t/** Subdirs (relative to repo root) to walk for entries. */\n\tinclude: string[];\n\t/** Subdirs (relative to repo root) to skip, even if a parent is included. */\n\texclude: string[];\n\t/**\n\t * When true, an included subdir's `<name>.md` files are\n\t * surfaced as skills (frontmatter is parsed from each file as\n\t * a stand-in for SKILL.md). When false (default), the\n\t * include list only widens the recursion — the manifest rule\n\t * still applies.\n\t */\n\ttreatFilesAsSkills: boolean;\n}\n\n/**\n * Default descriptor used when no `.serviceme-repo.json` is\n * present. The shape is the same as what an empty marker would\n * produce, so callers don't have to special-case the \"no marker\"\n * branch.\n */\nexport const DEFAULT_REPO_LAYOUT: RepoLayoutDescriptor = {\n\tschema: SUPPORTED_SCHEMA,\n\tinclude: [],\n\texclude: [],\n\ttreatFilesAsSkills: false,\n};\n\n/**\n * Try to load a `.serviceme-repo.json` from the given repo root.\n * Returns `DEFAULT_REPO_LAYOUT` (not undefined) when the file is\n * absent — callers branch on `include.length` / `treatFilesAsSkills`\n * to decide whether to widen the scan.\n *\n * Malformed markers (bad JSON, wrong schema) are surfaced as\n * `null` so callers can warn the user instead of silently\n * treating them as the default.\n */\nexport async function loadRepoLayout(repoRoot: string): Promise<RepoLayoutDescriptor | null> {\n\tconst markerPath = path.join(repoRoot, MARKER_FILENAME);\n\tlet raw: string;\n\ttry {\n\t\traw = await fs.readFile(markerPath, \"utf8\");\n\t} catch {\n\t\treturn DEFAULT_REPO_LAYOUT;\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (!parsed || typeof parsed !== \"object\") return null;\n\tconst obj = parsed as Record<string, unknown>;\n\n\tif (obj.schema !== SUPPORTED_SCHEMA) return null;\n\tif (!Array.isArray(obj.include) || obj.include.some((s) => typeof s !== \"string\")) {\n\t\treturn null;\n\t}\n\tif (!Array.isArray(obj.exclude) || obj.exclude.some((s) => typeof s !== \"string\")) {\n\t\treturn null;\n\t}\n\tif (typeof obj.treatFilesAsSkills !== \"boolean\") return null;\n\n\treturn {\n\t\tschema: SUPPORTED_SCHEMA,\n\t\tinclude: obj.include as string[],\n\t\texclude: obj.exclude as string[],\n\t\ttreatFilesAsSkills: obj.treatFilesAsSkills,\n\t};\n}\n\n/** Subdir name → entry kind override (rarely needed; default = manifest-driven). */\nexport type KindOverride = Map<string, \"skill\" | \"agent\">;\n","/**\n * Skill & Agent v2 — SkillStore Types\n *\n * SkillStore scans the local `~/.serviceme/repos/<id>/` tree to produce\n * a unified list of skills + agents. The store is the single source of\n * truth for \"what's available right now\" — the UI reads it; SubmitClient\n * reads it; install flows read it.\n *\n * Three repo layouts are supported in v1 (per spec §12):\n * 1. **Default** (`medalsoftchina-ms-skills`): `skills/<name>/SKILL.md`\n * + `agents/<name>/AGENT.md`.\n * 2. **Anthropic-style flat** (`anthropics/skills`): each subdir of\n * the repo root IS a skill — `<name>/SKILL.md` (no `skills/`\n * intermediate).\n * 3. **awesome-copilot style** (`github/awesome-copilot`): mixed\n * prompts/instructions/agents at the root.\n *\n * Normalization rule (spec §12): for every directory under the repo\n * root, peek for a `SKILL.md` or `AGENT.md` file. If present, register\n * it as a skill or agent respectively. This is more permissive than\n * guessing from the directory name and works for all three styles.\n *\n * The store is local-only and pure — no git, no network. Tests\n * construct a fixture repo tree and pass the root in directly.\n */\n\n/** What's available at this entry: a skill or an agent. */\nexport type SkillKind = \"skill\" | \"agent\";\n\n/** Top-level summary of a discovered skill/agent entry. */\nexport interface SkillEntry {\n\t/** Repository the entry was found in. */\n\trepoId: string;\n\t/** Skill or agent name (the directory name under the repo). */\n\tname: string;\n\tkind: SkillKind;\n\t/** Absolute path to the SKILL.md / AGENT.md file. */\n\tmanifestPath: string;\n\t/** Absolute path to the directory containing the entry's files. */\n\tdir: string;\n\t/** Parsed frontmatter (best-effort; raw key/value map). */\n\tfrontmatter: Record<string, unknown>;\n\t/** ISO timestamp of the manifest file's mtime. */\n\tmodifiedAt: string;\n}\n\n/** Full detail of an entry: summary + all the files inside the dir. */\nexport interface SkillDetail extends SkillEntry {\n\tfiles: SkillFile[];\n}\n\n/** A single file inside a skill / agent directory. */\nexport interface SkillFile {\n\t/** Path relative to the entry's directory. */\n\tpath: string;\n\t/** UTF-8 content. */\n\tcontent: string;\n}\n\n/** Sentinel error for store lookups that miss. */\nexport class SkillNotFoundError extends Error {\n\tconstructor(\n\t\tpublic readonly repoId: string,\n\t\tpublic readonly skillName: string\n\t) {\n\t\tsuper(`skill/agent not found: ${repoId}/${skillName}`);\n\t\tthis.name = \"SkillNotFoundError\";\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,MAAoB;AACpB,IAAAC,QAAsB;;;AC2BtB,SAAoB;AACpB,WAAsB;AAEtB,IAAM,kBAAkB;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rB,MAAI,SAAU,QAAO;AACrB,SAAO;AACR;AAOA,eAAe,sBACd,QACA,WACA,KACgB;AAChB,MAAI;AACJ,MAAI;AACH,cAAU,MAAS,YAAQ,QAAQ,EAAE,eAAe,KAAK,CAAC;AAAA,EAC3D,QAAQ;AACP;AAAA,EACD;AACA,aAAW,KAAK,SAAS;AACxB,QAAI,UAAU,IAAI,EAAE,IAAI,EAAG;AAC3B,UAAM,OAAY,WAAK,QAAQ,EAAE,IAAI;AACrC,QAAI,EAAE,YAAY,GAAG;AACpB,YAAM,sBAAsB,MAAM,WAAW,GAAG;AAAA,IACjD,WAAW,EAAE,OAAO,GAAG;AACtB,YAAM,UAAU,MAAS,aAAS,MAAM,MAAM;AAC9C,UAAI,KAAK,EAAE,MAAW,eAAS,WAAW,IAAI,GAAG,QAAQ,CAAC;AAAA,IAC3D;AAAA,EACD;AACD;","names":["fs","path","stat"]}
1
+ {"version":3,"sources":["../src/skill-store/index.ts","../src/repo-layout/index.ts","../src/skill-store/types.ts"],"sourcesContent":["import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { DEFAULT_REPO_LAYOUT, loadRepoLayout, type RepoLayoutDescriptor } from \"../repo-layout\";\nimport type { SkillDetail, SkillEntry, SkillFile, SkillKind } from \"./types\";\nimport { SkillNotFoundError } from \"./types\";\n\n/**\n * Minimal frontmatter reader — same shape as the extension's\n * `WorkspaceSkillsInitializationService.extractFrontmatter`. We avoid\n * pulling a YAML dep into core; SKILL.md / AGENT.md in the wild use\n * a strict subset (top-level `key: value` pairs delimited by `---`).\n * Multi-line block scalars (`>`, `|-`, `|`) are folded into a single\n * string value — the very common `description: >` form would\n * otherwise surface the bare `>` indicator as the whole description.\n */\nexport function extractFrontmatter(\n\traw: string\n): { data: Record<string, unknown>; body: string } | null {\n\tif (typeof raw !== \"string\") return null;\n\tconst match = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n\tif (!match) return null;\n\tconst yamlBody = match[1] ?? \"\";\n\tconst body = match[2] ?? \"\";\n\tconst data: Record<string, unknown> = {};\n\tconst lines = yamlBody.split(/\\r?\\n/);\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst line = lines[i] ?? \"\";\n\t\tif (line.trim().length === 0) continue;\n\t\tif (line.trim().startsWith(\"#\")) continue;\n\t\tconst kv = line.match(/^([a-zA-Z_][\\w-]*)\\s*:\\s*(.*)$/);\n\t\tif (!kv?.[1]) continue;\n\t\tlet value: unknown = (kv[2] ?? \"\").trim();\n\t\t// Block scalar indicators: fold the following more-indented\n\t\t// lines into one value (blank separators become newlines for\n\t\t// `|`, spaces for `>`; we keep it simple and always fold with\n\t\t// spaces, which is right for descriptions).\n\t\tif (typeof value === \"string\" && /^[>|][+-]?$/.test(value)) {\n\t\t\tconst folded: string[] = [];\n\t\t\tlet j = i + 1;\n\t\t\tfor (; j < lines.length; j++) {\n\t\t\t\tconst next = lines[j] ?? \"\";\n\t\t\t\tif (next.trim().length === 0) {\n\t\t\t\t\t// A blank line only belongs to the scalar if a later\n\t\t\t\t\t// more-indented line follows; otherwise it ends it.\n\t\t\t\t\tconst after = lines[j + 1];\n\t\t\t\t\tif (after !== undefined && /^[ \\t]/.test(after)) {\n\t\t\t\t\t\tfolded.push(\"\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!/^[ \\t]/.test(next)) break; // dedent ends the scalar\n\t\t\t\tfolded.push(next.trim());\n\t\t\t}\n\t\t\ti = j - 1;\n\t\t\t// Collapse whitespace runs so blank separators don't leave\n\t\t\t// double spaces (display text, not YAML fidelity).\n\t\t\tvalue = folded.join(\" \").replace(/\\s+/g, \" \").trim();\n\t\t\tdata[kv[1]] = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\tif (\n\t\t\t\t(value.startsWith('\"') && value.endsWith('\"')) ||\n\t\t\t\t(value.startsWith(\"'\") && value.endsWith(\"'\"))\n\t\t\t) {\n\t\t\t\tvalue = value.slice(1, -1);\n\t\t\t}\n\t\t}\n\t\tdata[kv[1]] = value;\n\t}\n\treturn { data, body };\n}\n\nexport type { SkillDetail, SkillEntry, SkillFile, SkillKind } from \"./types\";\n/**\n * Skill & Agent v2 — SkillStore (M4)\n *\n * Scans the local `~/.serviceme/repos/<id>/` tree to produce a unified\n * list of skills + agents. Local-only — no git, no network. Spec §5.5.\n *\n * Layout normalization (spec §12):\n * 1. **Standard layout** — `skills/<name>/SKILL.md` or\n * `agents/<name>/AGENT.md` under the repo root.\n * 2. **Anthropic flat layout** — `<name>/SKILL.md` directly under\n * the repo root (the `skills/` prefix is omitted).\n * 3. **awesome-copilot style** — root contains README + subdirs\n * that are skills/agents/instructions; we ignore README and\n * any dir without a manifest file.\n * 4. **Flat agent files** — a directory (commonly `agents/` or\n * `agents/official/`) full of `<name>.agent.md` files, one per\n * agent, with NO per-agent subdirectory. This is the prevailing\n * real-world convention (VS Code custom chat agents, GitHub's\n * awesome-copilot, and our own official ms-skills repo all ship\n * agents this way) — unlike skills, agents in the wild are\n * essentially never a `<name>/AGENT.md` directory pair. Detected\n * unconditionally, no `.serviceme-repo.json` opt-in required.\n *\n * Implementation: walk every directory under the repo root, check for\n * SKILL.md or AGENT.md, register if present. We skip the repo root\n * itself (no manifest lives at the top), `.git/`, and `node_modules/`.\n * Flat `*.agent.md` files are checked alongside directories at every\n * level of the walk.\n */\n// Re-export the error class + shared types so callers can\n// `import { SkillNotFoundError, SkillFile } from \"...\"`.\nexport { SkillNotFoundError } from \"./types\";\n\nexport class SkillStore {\n\tprivate readonly repoRoots: Map<string, string>;\n\t/**\n\t * Per-instance memo of repo walks. The catalog walk is a recursive\n\t * readdir over the whole checkout — the dominant cost of every\n\t * list/get — so results (and the in-flight promise) are reused for\n\t * the store's lifetime. The handler that owns long-lived stores\n\t * bounds staleness by rebuilding the store on a short TTL; within\n\t * one store instance the tree is treated as immutable.\n\t */\n\tprivate readonly entriesMemo = new Map<string, Promise<SkillEntry[]>>();\n\n\tconstructor(opts: {\n\t\trepos: ReadonlyArray<{ id: string; rootPath: string }>;\n\t}) {\n\t\tthis.repoRoots = new Map();\n\t\tfor (const r of opts.repos) this.repoRoots.set(r.id, r.rootPath);\n\t}\n\n\t/** All skills + agents across all registered repos. Repos are walked\n\t * concurrently — one slow checkout no longer stretches the total. */\n\tasync listAll(): Promise<SkillEntry[]> {\n\t\tconst perRepo = await Promise.all(\n\t\t\t[...this.repoRoots.keys()].map((repoId) => this.listByRepo(repoId))\n\t\t);\n\t\treturn perRepo.flat();\n\t}\n\n\t/** All skills + agents under a single repo. */\n\tasync listByRepo(repoId: string): Promise<SkillEntry[]> {\n\t\tconst entries = await this.listByRepoCached(repoId);\n\t\t// Copy so memoized state can't be corrupted by caller mutations.\n\t\treturn [...entries];\n\t}\n\n\t/** Single entry detail (manifest + all files inside its dir). */\n\tasync get(repoId: string, name: string): Promise<SkillDetail> {\n\t\tconst entries = await this.listByRepoCached(repoId);\n\t\tconst found = entries.find((e) => e.name === name);\n\t\tif (!found) throw new SkillNotFoundError(repoId, name);\n\t\tconst files = await collectEntryFiles(found);\n\t\treturn { ...found, files };\n\t}\n\n\t/** All files inside a single entry's directory (manifest + extras). */\n\tasync getFiles(repoId: string, name: string): Promise<SkillFile[]> {\n\t\tconst entries = await this.listByRepoCached(repoId);\n\t\tconst found = entries.find((e) => e.name === name);\n\t\tif (!found) throw new SkillNotFoundError(repoId, name);\n\t\treturn collectEntryFiles(found);\n\t}\n\n\t/**\n\t * Memoized walk. Sharing the promise collapses concurrent list/get\n\t * calls over the same repo into a single traversal; a rejected walk\n\t * is dropped so the next call retries from disk.\n\t */\n\tprivate listByRepoCached(repoId: string): Promise<SkillEntry[]> {\n\t\tconst memoized = this.entriesMemo.get(repoId);\n\t\tif (memoized) return memoized;\n\t\tconst walk = this.walkRepo(repoId).catch((error: unknown) => {\n\t\t\tthis.entriesMemo.delete(repoId);\n\t\t\tthrow error;\n\t\t});\n\t\tthis.entriesMemo.set(repoId, walk);\n\t\treturn walk;\n\t}\n\n\tprivate async walkRepo(repoId: string): Promise<SkillEntry[]> {\n\t\tconst root = this.repoRoots.get(repoId);\n\t\tif (!root) return [];\n\t\tconst layout = (await loadRepoLayout(root)) ?? DEFAULT_REPO_LAYOUT;\n\t\tconst entries: SkillEntry[] = [];\n\t\tawait walkForEntries(root, repoId, entries, layout);\n\t\treturn entries;\n\t}\n}\n\n/** All files inside a single entry (manifest first, then alphabetical). */\nasync function collectEntryFiles(found: SkillEntry): Promise<SkillFile[]> {\n\tconst out: SkillFile[] = [];\n\t// Flat single-file entries (e.g. `agents/foo.agent.md`) have `dir`\n\t// pointing at the manifest file itself, not a directory — there's\n\t// no sibling files to collect, just the one manifest.\n\tif (found.dir === found.manifestPath) {\n\t\tconst content = await fs.readFile(found.manifestPath, \"utf8\");\n\t\treturn [{ path: path.basename(found.manifestPath), content }];\n\t}\n\tawait collectFilesRecursive(found.dir, found.dir, out);\n\t// Sort for determinism (manifest first, then alphabetical)\n\tout.sort((a, b) => {\n\t\tconst aIsManifest = a.path === \"SKILL.md\" || a.path === \"AGENT.md\";\n\t\tconst bIsManifest = b.path === \"SKILL.md\" || b.path === \"AGENT.md\";\n\t\tif (aIsManifest && !bIsManifest) return -1;\n\t\tif (bIsManifest && !aIsManifest) return 1;\n\t\treturn a.path.localeCompare(b.path);\n\t});\n\treturn out;\n}\n\n// ─────────────────────────────────────────────────────────────────────\n// Internals\n// ─────────────────────────────────────────────────────────────────────\n\nconst SKIP_DIRS = new Set([\".git\", \"node_modules\", \".vscode\", \"dist\", \"build\", \"out\"]);\n\n/**\n * Directories that are never treated as candidate skill/agent parents\n * during the top-level catalog walk. `plugins/` is a distinct concept\n * from the skill/agent catalog itself — a plugin bundle\n * (`plugins/<scope>/<plugin-name>/{skills,agents}/...`) re-packages\n * ALREADY-cataloged official skills/agents (see the plugin's own\n * `catalog.json`, which lists them by name) purely for discovery\n * grouping. Walking into it produces duplicate `SkillEntry` values\n * with the SAME `repoId`+`name` as their real, top-level counterpart\n * (e.g. `skills/official/acreadiness-assess` AND\n * `plugins/official/acreadiness-cockpit/skills/acreadiness-assess`),\n * which breaks anything keyed on `repoId/name` (React list rendering,\n * the \"installed\" lookup, `SkillStore.get()`'s `.find()`).\n *\n * Scoped separately from `SKIP_DIRS` (used by both this walk AND\n * `collectFilesRecursive`) so an actual skill that happens to ship its\n * own `plugins/` asset folder still has that folder listed in its own\n * file detail view.\n */\nconst SKIP_TOP_LEVEL_SCAN_DIRS = new Set([...SKIP_DIRS, \"plugins\"]);\n\n/** Suffix that marks a standalone file as a flat agent manifest (no wrapping dir). */\nconst FLAT_AGENT_FILE_SUFFIX = \".agent.md\";\n\n/**\n * Recursive walk that yields SkillEntry values for any directory\n * containing a SKILL.md or AGENT.md file, PLUS any standalone\n * `<name>.agent.md` file (see class doc, layout style 4). The dir\n * itself is the \"entry root\" for directory-based entries; the\n * manifest file itself is the \"entry root\" for flat agent files.\n *\n * The optional `layout` descriptor (from `.serviceme-repo.json`)\n * widens the scan: included subdirs are walked even without a\n * manifest at the top level, and `treatFilesAsSkills` surfaces\n * `<name>.md` files inside them as skills (frontmatter parsed\n * from the file body).\n */\nasync function walkForEntries(\n\trootDir: string,\n\trepoId: string,\n\tout: SkillEntry[],\n\tlayout: RepoLayoutDescriptor = DEFAULT_REPO_LAYOUT\n): Promise<void> {\n\tlet dirents: import(\"node:fs\").Dirent[];\n\ttry {\n\t\tdirents = await fs.readdir(rootDir, { withFileTypes: true });\n\t} catch {\n\t\treturn;\n\t}\n\n\tfor (const d of dirents) {\n\t\tif (d.isFile() && d.name.endsWith(FLAT_AGENT_FILE_SUFFIX)) {\n\t\t\tconst filePath = path.join(rootDir, d.name);\n\t\t\tconst stat = await fs.stat(filePath);\n\t\t\tconst content = await fs.readFile(filePath, \"utf8\");\n\t\t\tconst parsed = extractFrontmatter(content);\n\t\t\tout.push({\n\t\t\t\trepoId,\n\t\t\t\tname: d.name.slice(0, -FLAT_AGENT_FILE_SUFFIX.length),\n\t\t\t\tkind: \"agent\",\n\t\t\t\tmanifestPath: filePath,\n\t\t\t\t// Sentinel: `dir === manifestPath` marks a flat single-file\n\t\t\t\t// entry (no directory of its own — see getFiles()).\n\t\t\t\tdir: filePath,\n\t\t\t\tfrontmatter: parsed?.data ?? {},\n\t\t\t\tmodifiedAt: stat.mtime.toISOString(),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!d.isDirectory()) continue;\n\t\tif (SKIP_TOP_LEVEL_SCAN_DIRS.has(d.name)) continue;\n\t\tif (layout.exclude.includes(d.name)) continue;\n\t\tconst childDir = path.join(rootDir, d.name);\n\t\tconst kind = await detectKind(childDir);\n\t\tif (kind) {\n\t\t\tconst manifestFilename = kind === \"skill\" ? \"SKILL.md\" : \"AGENT.md\";\n\t\t\tconst manifestPath = path.join(childDir, manifestFilename);\n\t\t\tconst stat = await fs.stat(manifestPath);\n\t\t\tconst content = await fs.readFile(manifestPath, \"utf8\");\n\t\t\tconst parsed = extractFrontmatter(content);\n\t\t\tout.push({\n\t\t\t\trepoId,\n\t\t\t\tname: d.name,\n\t\t\t\tkind,\n\t\t\t\tmanifestPath,\n\t\t\t\tdir: childDir,\n\t\t\t\tfrontmatter: parsed?.data ?? {},\n\t\t\t\tmodifiedAt: stat.mtime.toISOString(),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\t// No manifest at the top — recurse, but ALSO check whether\n\t\t// the layout descriptor wants this subdir widened.\n\t\tawait walkForEntries(childDir, repoId, out, layout);\n\t\tif (layout.treatFilesAsSkills && layout.include.includes(d.name)) {\n\t\t\tawait surfaceFilesAsSkills(childDir, d.name, repoId, out);\n\t\t}\n\t}\n}\n\n/**\n * Walk `<includedSubdir>/<file>.md` and register each as a skill.\n * The `.md` file itself is the manifest — frontmatter (if any) is\n * parsed and surfaced. This is the awesome-copilot style: a\n * `prompts/` dir full of `<name>.md` files, no SKILL.md anywhere.\n */\nasync function surfaceFilesAsSkills(\n\tabsDir: string,\n\trelName: string,\n\trepoId: string,\n\tout: SkillEntry[]\n): Promise<void> {\n\tlet dirents: import(\"node:fs\").Dirent[];\n\ttry {\n\t\tdirents = await fs.readdir(absDir, { withFileTypes: true });\n\t} catch {\n\t\treturn;\n\t}\n\tfor (const d of dirents) {\n\t\tif (!d.isFile()) continue;\n\t\tif (!d.name.endsWith(\".md\")) continue;\n\t\tconst filePath = path.join(absDir, d.name);\n\t\tconst stat = await fs.stat(filePath);\n\t\tconst content = await fs.readFile(filePath, \"utf8\");\n\t\tconst parsed = extractFrontmatter(content);\n\t\t// Entry name = \"<subdir>/<file>\" (with the .md stripped) so it\n\t\t// stays unique even when two included subdirs share filenames.\n\t\tconst entryName = `${relName}/${d.name.replace(/\\.md$/, \"\")}`;\n\t\tout.push({\n\t\t\trepoId,\n\t\t\tname: entryName,\n\t\t\tkind: \"skill\",\n\t\t\tmanifestPath: filePath,\n\t\t\tdir: absDir,\n\t\t\tfrontmatter: parsed?.data ?? {},\n\t\t\tmodifiedAt: stat.mtime.toISOString(),\n\t\t});\n\t}\n}\n\n/**\n * Returns the SkillKind of a directory if it contains a manifest file,\n * or `null` if it doesn't. Manifest precedence: SKILL.md wins if both\n * are present (defensive — the spec separates skills and agents into\n * different subdir trees, so this collision shouldn't happen in\n * well-formed repos).\n */\nasync function detectKind(dir: string): Promise<SkillKind | null> {\n\tconst [hasSkill, hasAgent] = await Promise.all([\n\t\tfs\n\t\t\t.access(path.join(dir, \"SKILL.md\"))\n\t\t\t.then(() => true)\n\t\t\t.catch(() => false),\n\t\tfs\n\t\t\t.access(path.join(dir, \"AGENT.md\"))\n\t\t\t.then(() => true)\n\t\t\t.catch(() => false),\n\t]);\n\tif (hasSkill) return \"skill\";\n\tif (hasAgent) return \"agent\";\n\treturn null;\n}\n\n/**\n * Walk a skill/agent directory recursively, pushing every file into\n * `out` with its path RELATIVE to the entry root. Skips `.git/`,\n * `node_modules/`, and the SKIP_DIRS set.\n */\nasync function collectFilesRecursive(\n\tabsDir: string,\n\tentryRoot: string,\n\tout: SkillFile[]\n): Promise<void> {\n\tlet dirents: import(\"node:fs\").Dirent[];\n\ttry {\n\t\tdirents = await fs.readdir(absDir, { withFileTypes: true });\n\t} catch {\n\t\treturn;\n\t}\n\tfor (const d of dirents) {\n\t\tif (SKIP_DIRS.has(d.name)) continue;\n\t\tconst full = path.join(absDir, d.name);\n\t\tif (d.isDirectory()) {\n\t\t\tawait collectFilesRecursive(full, entryRoot, out);\n\t\t} else if (d.isFile()) {\n\t\t\tconst content = await fs.readFile(full, \"utf8\");\n\t\t\tout.push({ path: path.relative(entryRoot, full), content });\n\t\t}\n\t}\n}\n","/**\n * Spec §12 — Repo layout descriptor.\n *\n * Some third-party repos (awesome-copilot, composio) use a\n * non-default layout that mixes prompts / instructions / agents /\n * hooks / plugins at the root. The default SkillStore scan\n * (see ../skill-store/index.ts) only picks up directories that\n * contain a `SKILL.md` or `AGENT.md` manifest, so prompts stored\n * as `<subdir>/<name>.md` (no manifest) get missed.\n *\n * This module is the loader for the optional `.serviceme-repo.json`\n * marker file a repo author can drop in at the repo root to opt\n * into a wider scan. The schema:\n *\n * {\n * \"schema\": 1,\n * \"include\": [\"prompts\", \"instructions\"], // subdirs to treat as \"skill dirs\"\n * \"exclude\": [\"hooks\", \"plugins\"], // subdirs to skip\n * \"treatFilesAsSkills\": true // inside an included subdir, each .md file is a skill\n * }\n *\n * All four fields are optional. The defaults match the v0.2\n * walkForEntries behaviour (manifest-based, no marker, no\n * extensions), so adding the file is purely additive.\n *\n * @see docs/architecture/skill-agent-v2-repo.md §12\n */\n\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nconst MARKER_FILENAME = \".serviceme-repo.json\";\nconst SUPPORTED_SCHEMA = 1;\n\nexport interface RepoLayoutDescriptor {\n\t/** Schema version. Currently always 1. */\n\tschema: number;\n\t/** Subdirs (relative to repo root) to walk for entries. */\n\tinclude: string[];\n\t/** Subdirs (relative to repo root) to skip, even if a parent is included. */\n\texclude: string[];\n\t/**\n\t * When true, an included subdir's `<name>.md` files are\n\t * surfaced as skills (frontmatter is parsed from each file as\n\t * a stand-in for SKILL.md). When false (default), the\n\t * include list only widens the recursion — the manifest rule\n\t * still applies.\n\t */\n\ttreatFilesAsSkills: boolean;\n}\n\n/**\n * Default descriptor used when no `.serviceme-repo.json` is\n * present. The shape is the same as what an empty marker would\n * produce, so callers don't have to special-case the \"no marker\"\n * branch.\n */\nexport const DEFAULT_REPO_LAYOUT: RepoLayoutDescriptor = {\n\tschema: SUPPORTED_SCHEMA,\n\tinclude: [],\n\texclude: [],\n\ttreatFilesAsSkills: false,\n};\n\n/**\n * Try to load a `.serviceme-repo.json` from the given repo root.\n * Returns `DEFAULT_REPO_LAYOUT` (not undefined) when the file is\n * absent — callers branch on `include.length` / `treatFilesAsSkills`\n * to decide whether to widen the scan.\n *\n * Malformed markers (bad JSON, wrong schema) are surfaced as\n * `null` so callers can warn the user instead of silently\n * treating them as the default.\n */\nexport async function loadRepoLayout(repoRoot: string): Promise<RepoLayoutDescriptor | null> {\n\tconst markerPath = path.join(repoRoot, MARKER_FILENAME);\n\tlet raw: string;\n\ttry {\n\t\traw = await fs.readFile(markerPath, \"utf8\");\n\t} catch {\n\t\treturn DEFAULT_REPO_LAYOUT;\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (!parsed || typeof parsed !== \"object\") return null;\n\tconst obj = parsed as Record<string, unknown>;\n\n\tif (obj.schema !== SUPPORTED_SCHEMA) return null;\n\tif (!Array.isArray(obj.include) || obj.include.some((s) => typeof s !== \"string\")) {\n\t\treturn null;\n\t}\n\tif (!Array.isArray(obj.exclude) || obj.exclude.some((s) => typeof s !== \"string\")) {\n\t\treturn null;\n\t}\n\tif (typeof obj.treatFilesAsSkills !== \"boolean\") return null;\n\n\treturn {\n\t\tschema: SUPPORTED_SCHEMA,\n\t\tinclude: obj.include as string[],\n\t\texclude: obj.exclude as string[],\n\t\ttreatFilesAsSkills: obj.treatFilesAsSkills,\n\t};\n}\n\n/** Subdir name → entry kind override (rarely needed; default = manifest-driven). */\nexport type KindOverride = Map<string, \"skill\" | \"agent\">;\n","/**\n * Skill & Agent v2 — SkillStore Types\n *\n * SkillStore scans the local `~/.serviceme/repos/<id>/` tree to produce\n * a unified list of skills + agents. The store is the single source of\n * truth for \"what's available right now\" — the UI reads it; SubmitClient\n * reads it; install flows read it.\n *\n * Three repo layouts are supported in v1 (per spec §12):\n * 1. **Default** (`medalsoftchina-ms-skills`): `skills/<name>/SKILL.md`\n * + `agents/<name>/AGENT.md`.\n * 2. **Anthropic-style flat** (`anthropics/skills`): each subdir of\n * the repo root IS a skill — `<name>/SKILL.md` (no `skills/`\n * intermediate).\n * 3. **awesome-copilot style** (`github/awesome-copilot`): mixed\n * prompts/instructions/agents at the root.\n *\n * Normalization rule (spec §12): for every directory under the repo\n * root, peek for a `SKILL.md` or `AGENT.md` file. If present, register\n * it as a skill or agent respectively. This is more permissive than\n * guessing from the directory name and works for all three styles.\n *\n * The store is local-only and pure — no git, no network. Tests\n * construct a fixture repo tree and pass the root in directly.\n */\n\n/** What's available at this entry: a skill or an agent. */\nexport type SkillKind = \"skill\" | \"agent\";\n\n/** Top-level summary of a discovered skill/agent entry. */\nexport interface SkillEntry {\n\t/** Repository the entry was found in. */\n\trepoId: string;\n\t/** Skill or agent name (the directory name under the repo). */\n\tname: string;\n\tkind: SkillKind;\n\t/** Absolute path to the SKILL.md / AGENT.md file. */\n\tmanifestPath: string;\n\t/** Absolute path to the directory containing the entry's files. */\n\tdir: string;\n\t/** Parsed frontmatter (best-effort; raw key/value map). */\n\tfrontmatter: Record<string, unknown>;\n\t/** ISO timestamp of the manifest file's mtime. */\n\tmodifiedAt: string;\n}\n\n/** Full detail of an entry: summary + all the files inside the dir. */\nexport interface SkillDetail extends SkillEntry {\n\tfiles: SkillFile[];\n}\n\n/** A single file inside a skill / agent directory. */\nexport interface SkillFile {\n\t/** Path relative to the entry's directory. */\n\tpath: string;\n\t/** UTF-8 content. */\n\tcontent: string;\n}\n\n/** Sentinel error for store lookups that miss. */\nexport class SkillNotFoundError extends Error {\n\tconstructor(\n\t\tpublic readonly repoId: string,\n\t\tpublic readonly skillName: string\n\t) {\n\t\tsuper(`skill/agent not found: ${repoId}/${skillName}`);\n\t\tthis.name = \"SkillNotFoundError\";\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,MAAoB;AACpB,IAAAC,QAAsB;;;AC2BtB,SAAoB;AACpB,WAAsB;AAEtB,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAyBlB,IAAM,sBAA4C;AAAA,EACxD,QAAQ;AAAA,EACR,SAAS,CAAC;AAAA,EACV,SAAS,CAAC;AAAA,EACV,oBAAoB;AACrB;AAYA,eAAsB,eAAe,UAAwD;AAC5F,QAAM,aAAkB,UAAK,UAAU,eAAe;AACtD,MAAI;AACJ,MAAI;AACH,UAAM,MAAS,YAAS,YAAY,MAAM;AAAA,EAC3C,QAAQ;AACP,WAAO;AAAA,EACR;AAEA,MAAI;AACJ,MAAI;AACH,aAAS,KAAK,MAAM,GAAG;AAAA,EACxB,QAAQ;AACP,WAAO;AAAA,EACR;AACA,MAAI,CAAC,UAAU,OAAO,WAAW,SAAU,QAAO;AAClD,QAAM,MAAM;AAEZ,MAAI,IAAI,WAAW,iBAAkB,QAAO;AAC5C,MAAI,CAAC,MAAM,QAAQ,IAAI,OAAO,KAAK,IAAI,QAAQ,KAAK,CAAC,MAAM,OAAO,MAAM,QAAQ,GAAG;AAClF,WAAO;AAAA,EACR;AACA,MAAI,CAAC,MAAM,QAAQ,IAAI,OAAO,KAAK,IAAI,QAAQ,KAAK,CAAC,MAAM,OAAO,MAAM,QAAQ,GAAG;AAClF,WAAO;AAAA,EACR;AACA,M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