Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
PRD-8403: Move Group 10 skills routes to native HTTP (#4287)
omar-inkeepa70c44c52346
diff --git a/packages/app/tests/integration/error-envelope-coverage.test.ts b/packages/app/tests/integration/error-envelope-coverage.test.tsindex 69c38738f..25d132e31 100644--- a/packages/app/tests/integration/error-envelope-coverage.test.ts+++ b/packages/app/tests/integration/error-envelope-coverage.test.ts@@ -171,17 +171,20 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()test('the shared success spine flows 2xx through successResponse (delegation is not a bypass)', () => {const spineDecl = new RegExp(`\\n {2}(?:async )?function ${SHARED_SUCCESS_SPINE_NAME}\\(`);- const declMatch = spineDecl.exec(source);+ const owners = HANDLER_SOURCES.filter(({ text }) => spineDecl.test(text));+ expect(owners).toHaveLength(1);+ const owner = owners[0]?.text ?? '';+ const declMatch = spineDecl.exec(owner);expect(declMatch).not.toBeNull();const start = declMatch?.index ?? -1;expect(start).toBeGreaterThan(-1);const afterStart = start + 1;- const nextFn = source.indexOf('\n async function ', afterStart);- const nextSyncFn = source.indexOf('\n function ', afterStart);- const nextConst = source.indexOf('\n const handle', afterStart);+ const nextFn = owner.indexOf('\n async function ', afterStart);+ const nextSyncFn = owner.indexOf('\n function ', afterStart);+ const nextConst = owner.indexOf('\n const handle', afterStart);const bounds = [nextFn, nextSyncFn, nextConst].filter((i) => i !== -1);- const end = bounds.length === 0 ? source.length : Math.min(...bounds);- const spineBody = source.slice(start, end);+ const end = bounds.length === 0 ? owner.length : Math.min(...bounds);+ const spineBody = owner.slice(start, end);expect(spineBody.includes('successResponse(')).toBe(true);expect(INLINE_ERROR_RE.test(spineBody)).toBe(false);expect(INLINE_SUCCESS_WRAPPER_RE.test(spineBody)).toBe(false);diff --git a/packages/server/src/agent-presence.test.ts b/packages/server/src/agent-presence.test.tsindex e6759b32b..b77da2403 100644--- a/packages/server/src/agent-presence.test.ts+++ b/packages/server/src/agent-presence.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from 'node:fs';+import { readdirSync, readFileSync } from 'node:fs';import { resolve } from 'node:path';import type { Hocuspocus } from '@hocuspocus/server';import { type AgentPresenceEntry, SYSTEM_DOC_NAME } from '@inkeep/open-knowledge-core';@@ -316,23 +316,34 @@ describe('AgentPresenceBroadcaster', () => {test('structural: every agent write handler pairs setPresence("writing") + touchMode("idle")', () => {const dir = import.meta.dirname ?? new URL('.', import.meta.url).pathname;- const src = readFileSync(resolve(dir, 'api-extension.ts'), 'utf-8');-- const NOT_AN_AGENT_WRITE = 'presence-exempt: no CRDT write, no agent identity';- const handlerCallSites = [- ...src.matchAll(/apply(?:AgentMarkdownWrite|AgentUndo|PatchToFm)\(/g),- ].filter((m) => !src.slice(Math.max(0, m.index - 200), m.index).includes(NOT_AN_AGENT_WRITE));- const expectedCount = handlerCallSites.length;- expect(expectedCount).toBeGreaterThanOrEqual(5);-- const tryShapePattern =- /try\s*\{\s*const\s+icon\s*=\s*iconFromClientName\([^)]*\);\s*const\s+color\s*=\s*[\s\S]*?;\s*agentPresenceBroadcaster\?\.setPresence\(\s*agentId,\s*\{[\s\S]*?mode:\s*'writing'/g;- const tryMatches = src.match(tryShapePattern) ?? [];- expect(tryMatches.length).toBe(expectedCount);-- const finallyPattern =- /finally\s*\{[^{}]*agentPresenceBroadcaster\?\.touchMode\(agentId,\s*'idle'\);\s*\}/g;- const finallyMatches = src.match(finallyPattern) ?? [];- expect(finallyMatches.length).toBe(expectedCount);+ const files = [+ 'api-extension.ts',+ ...readdirSync(resolve(dir, 'http'))+ .filter((file) => file.endsWith('-routes.ts'))+ .sort()+ .map((file) => `http/${file}`),+ ];+ let totalCallSites = 0;++ for (const file of files) {+ const src = readFileSync(resolve(dir, file), 'utf-8');+ const NOT_AN_AGENT_WRITE = 'presence-exempt: no CRDT write, no agent identity';+ const handlerCallSites = [+ ...src.matchAll(/apply(?:AgentMarkdownWrite|AgentUndo|PatchToFm)\(/g),+ ].filter((m) => !src.slice(Math.max(0, m.index - 200), m.index).includes(NOT_AN_AGENT_WRITE));+ const expectedCount = handlerCallSites.length;+ totalCallSites += expectedCount;++ const tryShapePattern =+ /try\s*\{\s*const\s+icon\s*=\s*iconFromClientName\([^)]*\);\s*const\s+color\s*=\s*[\s\S]*?;\s*agentPresenceBroadcaster\?\.setPresence\(\s*agentId,\s*\{[\s\S]*?mode:\s*'writing'/g;+ const tryMatches = src.match(tryShapePattern) ?? [];+ expect(tryMatches.length, file).toBe(expectedCount);++ const finallyPattern =+ /finally\s*\{[^{}]*agentPresenceBroadcaster\?\.touchMode\(agentId,\s*'idle'\);\s*\}/g;+ const finallyMatches = src.match(finallyPattern) ?? [];+ expect(finallyMatches.length, file).toBe(expectedCount);+ }+ expect(totalCallSites).toBeGreaterThanOrEqual(5);});});diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 364e6ad56..70112b288 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -3,20 +3,17 @@ import {createReadStream,type Dirent,existsSync,- lstatSync,mkdirSync,- mkdtempSync,readdirSync,readFileSync,realpathSync,- rmSync,statSync,writeFileSync,} from 'node:fs';import { readdir, readFile, realpath, stat } from 'node:fs/promises';import type { IncomingMessage, ServerResponse } from 'node:http';-import { homedir, tmpdir } from 'node:os';-import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';+import { homedir } from 'node:os';+import { dirname, extname, join, relative, resolve, sep } from 'node:path';import { pipeline } from 'node:stream/promises';import type { Document, Extension, Hocuspocus } from '@hocuspocus/server';import type { EnvTier } from '@inkeep/open-knowledge-core';@@ -51,20 +48,14 @@ import {type DiskEditReconciledWarning,type DocumentListEntry,detectFmRegion,- type EditorId,EmptyRequestSchema,estimateSkillCost,- externalSkillLiveDocName,FrontmatterPatchRequestSchema,FrontmatterPatchSuccessSchema,FrontmatterSchemaWriteRequestSchema,type HeadingEntry,type InlineAssetMediaKind,- InstallSkillRequestSchema,- InstallSkillSuccessSchema,isManagedArtifactDocName,- isOpenKnowledgeSkillsSource,- isSkillInstallTarget,LEGACY_SKILL_STORE_ROOT,type LinksValidationSetting,LintConfigResponseSchema,@@ -80,13 +71,10 @@ import {mediaKindForSidebarAssetExtension,OK_DIR,OPENKNOWLEDGE_SKILLS_REPO,- PROJECT_SKILL_EDITOR_IDS,type Principal,type ProblemType,parseFrontmatterRecord,prependFrontmatter,- projectSkillContentDocName,- RENAMED_PACK_SKILLS,type ReLintFailure,RollbackRequestSchema,RollbackSuccessSchema,@@ -94,89 +82,28 @@ import {SaveVersionRequestSchema,SaveVersionSuccessSchema,SKILL_NAME_REGEX,- SkillDeleteSuccessSchema,- SkillDuplicateRequestSchema,- SkillDuplicateSuccessSchema,- SkillEditExternalRequestSchema,- SkillEditExternalSuccessSchema,- SkillFileDeleteSuccessSchema,- SkillFileGetSuccessSchema,- SkillFilePutRequestSchema,- SkillFilePutSuccessSchema,- SkillFileRenameRequestSchema,- SkillFileRenameSuccessSchema,- SkillGetSuccessSchema,- type SkillImportBulkResult,- SkillImportRequestSchema,- SkillImportSuccessSchema,- SkillInstallRequestSchema,- SkillInstallSuccessSchema,- type SkillInstallWarningCode,- SkillMoveRequestSchema,- SkillMoveScopeRequestSchema,- SkillMoveScopeSuccessSchema,- SkillMoveSuccessSchema,- SkillPutRequestSchema,- SkillPutSuccessSchema,- type SkillReimportBulkResult,- SkillReimportRequestSchema,- SkillReimportSuccessSchema,- SkillRestoreRequestSchema,- SkillRestoreSuccessSchema,- SkillRevertRequestSchema,- SkillRevertSuccessSchema,SkillScopeSchema,- SkillsImportBulkRequestSchema,- SkillsImportBulkSuccessSchema,- SkillsListSuccessSchema,- SkillsReimportBulkRequestSchema,- SkillsReimportBulkSuccessSchema,- SkillTrackInGitRequestSchema,- SkillTrackInGitSuccessSchema,SkillUninstallRequestSchema,SkillUninstallSuccessSchema,SYSTEM_DOC_NAME,scanHeadingLine,- skillLiveDocName,stripFrontmatter,summarizeLintPluginFailures,TestFlushGitSuccessSchema,TestRescanBacklinksSuccessSchema,TestRescanFilesSuccessSchema,TestResetSuccessSchema,- USER_SKILL_EDITOR_IDS,type ValidationDiagnostic,} from '@inkeep/open-knowledge-core';import {formatRenameSubject,formatRollbackSubject,- resolveProjectIdentity,} from '@inkeep/open-knowledge-core/shadow-repo-layout';import {- discoverSkillDirs,- enumerateInstalledSkills,- fetchSource,- type PluginUpstream,parseSkillDir,- parseSkillsLock,- parseSource,pluginRepositoryUrl,- pluginUpstreamsByName,- readRepoMarketplacePlugins,- readSkillDirMeta,- readWellKnownIndex,- repoMarketplacePluginFor,- resolvePluginUpdateSource,- resolveSkillsShImportSource,- retrofitPackLockEntry,- SKILLS_LOCK_REL,- SkillFetchError,type SkillsLock,- type SourceSpec,- upsertLockEntry,- type WellKnownIndex,} from '@inkeep/open-knowledge-core/skills-catalog';-import { type Entry, fromBuffer as yauzlFromBuffer, type ZipFile } from 'yauzl';import {type AcpHarnessAvailability,createAcpHarnessAvailabilityProbe,@@ -217,18 +144,6 @@ import {RESOLUTION_OPTIONS,respondDocInConflict,} from './conflict-errors.ts';-import {- applySkillBundleFileDelete,- applySkillBundleFileRename,- applySkillBundleFileWrite,- applySkillDelete,- applySkillMove,- applySkillWrite,- BUNDLE_FILE_MAX_BYTES,- BUNDLE_MAX_FILES,- composeSkillContent,- countBundleFiles,-} from './content/skills-write.ts';import {evaluateContentDivergence,toContentDivergenceWarning,@@ -251,12 +166,16 @@ import {createOsProbe,type InstalledAgentScheme,} from './handoff-api.ts';+import { createHandoffInstallRoutes } from './http/handoff-install-routes.ts';+import { createSkillsDocumentRoutes } from './http/skills-document-routes.ts';+import { createSkillsFileRoutes } from './http/skills-file-routes.ts';+import { createSkillsImportRoutes } from './http/skills-import-routes.ts';+import { createSkillsInstallRoutes } from './http/skills-install-routes.ts';+import { createSkillsListRoutes } from './http/skills-list-routes.ts';+import { createSkillsRecoveryRoutes } from './http/skills-recovery-routes.ts';+import { createSkillsTrackingRoutes } from './http/skills-tracking-routes.ts';import { findHubCandidates } from './hub-candidates.ts';-import {- readInstalledSkills,- recordSkillInstall,- removeSkillInstall,-} from './installed-skills-marker.ts';+import { recordSkillInstall, removeSkillInstall } from './installed-skills-marker.ts';import { collectDocFiles, lintAndFixSource } from './lint/audit.ts';import {createEmptyFrontmatterSchemaFile,@@ -287,42 +206,19 @@ import {BUNDLE_SCOPE,BUNDLE_SKILL_NAME,isInternalBundleSkillName,- USER_GLOBAL_BUNDLE_IDS,} from './skill-bundles.ts';import {- buildAndOpenSkill,- detectProjectSkillEditors,- detectUserSkillHosts,-} from './skill-install.ts';-import {- listSkillBundledFilePaths,projectSkill,- readSkillBundledFiles,removeInPlaceSkillCopies,- resolvedHosts,resolveSkillTargets,reverseProjectSkill,skillProjectionEditorIds,skillProjectionRoots,- validateSkillForInstall,} from './skill-projection.ts';-import { rewriteSkillRefsAcrossScope, type SkillRefRewrite } from './skill-ref-rename.ts';--function bundleSelfIdentifiesAsPack(dir: string): boolean {- try {- const md = readFileSync(join(dir, 'SKILL.md'), 'utf-8');- const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(md)?.[1];- return (- frontmatter !== undefined && /^[ \t]+pack:[ \t]*"?[a-z0-9-]+"?[ \t]*$/m.test(frontmatter)- );- } catch {- return false;- }-}+import { createSkillsCatalogCache } from './skills-catalog-cache.ts';export { extractPageTitle } from './page-identity.ts';-import type { SkillHostId } from '@inkeep/open-knowledge-core/skills-catalog';import simpleGit from 'simple-git';import { parseAgentBodyFields, resolveAgentType, validateAgentId } from './agent-id.ts';import {@@ -368,7 +264,6 @@ import {type ReconcileBeforeWriteResult,reconcileDiskBeforeAgentWrite,} from './external-change.ts';-import { registerExternalSkill } from './external-skill-registry.ts';import { extractActorIdentity } from './extract-actor-identity.ts';import {contentHash,@@ -409,7 +304,6 @@ import { createLinkGraphRoutes } from './http/link-graph-routes.ts';import { createLintRoutes } from './http/lint-routes.ts';import { createLocalApiDispatch, type LocalApiDispatch } from './http/local-api-dispatch.ts';import { createLocalOpRoutes } from './http/local-op-routes.ts';-import { methodRouter } from './http/method-router.ts';import { createMetricsRoutes } from './http/metrics-routes.ts';import { getRequestId } from './http/request-id.ts';import { withValidation } from './http/request-validation.ts';@@ -425,15 +319,10 @@ import {type GeneratedIndexSettingsStatus,} from './http/workspace-tools-routes.ts';import {- aliasedSourceRoots,- isActivatedSkillRoot,removableSkillOccurrenceDirs,- resolveDefaultSkillHomeRel,resolveGlobalNativeSkillDir,scanGlobalInPlaceSkills,- scanHostRootAliases,scanInPlaceSkills,- standardSkillRoots,} from './in-place-skills.ts';import {buildIngressPolicy,@@ -446,7 +335,6 @@ import {checkLocalOpSecurity as checkLocalOpSecurityBase,createConcurrencyGuard,isLoopbackRequest,- isSafeLocalPath,} from './local-op-security.ts';import { localTargetInventoryFromIndexes } from './local-target-inventory.ts';import { getLogger } from './logger.ts';@@ -466,10 +354,9 @@ import {incrementSummariesProvided,incrementSummariesTruncated,} from './metrics.ts';-import { createMultipartParser, type MultipartParser } from './multipart.ts';+import { precomputeParse } from './parse-pool.ts';import { isWithinDir, toPosix } from './path-utils.ts';-import { openPluginBaselines } from './plugin-skill-baseline.ts';import {appendRenameLogEntry,createAncestorShaSetCache,@@ -481,15 +368,10 @@ import type { PairedWriteOrigin } from './server-observers.ts';import { createAssetService } from './services/assets.ts';import { createFileOpsService, DuplicateNameExhaustedError } from './services/file-ops.ts';import { createSearchService } from './services/search.ts';-import { createSkillImportService, type SkillImportOutcome } from './services/skill-import.ts';+import { createSkillImportService } from './services/skill-import.ts';import { createSkillInstallOpsService } from './services/skill-install-ops.ts';import { createSkillPlacementOpsService } from './services/skill-placement-ops.ts';-import {- createSkillReimportService,- groupReimportNamesBySource,- pickReimportDir,- type SkillReimportOutcome,-} from './services/skill-reimport.ts';+import { createSkillReimportService } from './services/skill-reimport.ts';import { createVersionOpsService } from './services/version-ops.ts';import {SERVICE_WRITER,@@ -498,16 +380,9 @@ import {shadowGit,type WriterIdentity,} from './shadow-repo.ts';-import { isDisallowedGitSpec, rejectDisallowedGitSpec } from './skill-git-spec-guard.ts';-import { resolveSkillInstallReportSettings } from './skill-install-report-config.ts';-import {- clearSkillPlacements,- readSkillInstallModeRaw,- readSkillPlacements,-} from './skill-placements.ts';-import { restoreSkillVersion } from './skill-restore.ts';-import { mutateSkillsLock, readSkillsLockFile } from './skills-lock-store.ts';-import { reportSkillInstall } from './skills-sh-install-report.ts';++import { readSkillInstallModeRaw } from './skill-placements.ts';+import type { SyncEngine } from './sync-engine.ts';import { getMeter, withSpan, withSpanSync } from './telemetry.ts';import { computeWriteAdvisoryLinks } from './write-advisory-links.ts';@@ -1624,6 +1499,8 @@ export function createApiExtension(getLinkPreviewsEnabled,getConfigDiagnostics,} = options;+ const catalogCache = createSkillsCatalogCache({ homeDirOverride, log });+ const { bumpSkillsCatalogGen, enumerateInstalledSkillsCached, pluginSkillsByName } = catalogCache;const signalChannel: typeof rawSignalChannel = rawSignalChannel? (channel) => {if (channel === 'files') bumpSkillsCatalogGen();@@ -3405,34 +3282,6 @@ export function createApiExtension();}- let skillsCatalogGen = 0;- let skillsListCache: { at: number; gen: number; fp: string; body: unknown } | null = null;- let installedCatalogCache: {- at: number;- gen: number;- key: string;- value: ReturnType<typeof enumerateInstalledSkills>;- } | null = null;- function bumpSkillsCatalogGen(): void {- skillsCatalogGen += 1;- }- function enumerateInstalledSkillsCached(- opts: Parameters<typeof enumerateInstalledSkills>[0],- ): ReturnType<typeof enumerateInstalledSkills> {- const key = `${opts?.projectDir ?? ''}|${opts && 'home' in opts ? opts.home : ''}`;- const now = Date.now();- if (- installedCatalogCache !== null &&- installedCatalogCache.gen === skillsCatalogGen &&- installedCatalogCache.key === key &&- now - installedCatalogCache.at < 5_000- ) {- return installedCatalogCache.value;- }- const value = enumerateInstalledSkills(opts);- installedCatalogCache = { at: now, gen: skillsCatalogGen, key, value };- return value;- }let deferredIgnoreRebuildTimer: NodeJS.Timeout | null = null;function scheduleDeferredIgnoreRebuild(): void {if (!contentFilter) return;@@ -5714,42 +5563,6 @@ export function createApiExtension(recordDerivedMutationsBestEffort,});- const handleInstallSkill = withValidation(- InstallSkillRequestSchema,- async (_req, res, body) => {- if (body.out !== undefined && !isSafeLocalPath(body.out)) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Output path must be within home directory.',- { handler: 'install-skill' },- );- return;- }-- try {- const result = await buildAndOpenSkill({- ...(body.noOpen !== undefined ? { noOpen: body.noOpen } : {}),- ...(body.out !== undefined ? { out: body.out } : {}),- });- successResponse(res, 200, InstallSkillSuccessSchema, result, {- handler: 'install-skill',- });- } catch (err) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to install skill.', {- handler: 'install-skill',- cause: err,- });- }- },- {- handler: 'install-skill',- method: 'POST',- preBodyGate: (req, res) => checkLocalOpSecurity(req, res, { handler: 'install-skill' }),- },- );-function validateFolderRel(raw: string,res: ServerResponse,@@ -5915,98 +5728,6 @@ export function createApiExtension();}- function projectionModeFor(scope: 'project' | 'global', name: string): 'symlink' | 'copy' {- const base = scope === 'project' ? projectDir : skillsHome;- if (!base) return 'symlink';- try {- const lock = readSkillsLock(join(base, ...SKILLS_LOCK_REL));- return lock.skills[name] !== undefined ? 'copy' : 'symlink';- } catch {- return 'symlink';- }- }-- function skillLockPath(scope: 'project' | 'global'): string | null {- const base = scope === 'project' ? projectDir : skillsHome;- return base ? join(base, ...SKILLS_LOCK_REL) : null;- }-- function rekeySkillLockEntry(- scope: 'project' | 'global',- fromName: string,- toName: string,- patch: Partial<SkillsLock['skills'][string]> = {},- ): Promise<void> {- const lockPath = skillLockPath(scope);- if (!lockPath) return Promise.resolve();- return mutateSkillsLock(lockPath, (lock) => {- const entry = lock.skills[fromName];- if (!entry) return lock;- const skills = { ...lock.skills };- delete skills[fromName];- skills[toName] = { ...entry, ...patch };- return { ...lock, skills };- });- }-- async function transferSkillLockEntry(- fromScope: 'project' | 'global',- toScope: 'project' | 'global',- name: string,- ): Promise<boolean> {- const fromPath = skillLockPath(fromScope);- const toPath = skillLockPath(toScope);- if (!fromPath || !toPath) return false;- const entry = readSkillsLockFile(fromPath).skills[name];- if (!entry) return false;-- const movedEntry = { ...entry };- if (toScope === 'global') delete movedEntry.baselineRef;- await mutateSkillsLock(toPath, (lock) => ({- ...lock,- skills: { ...lock.skills, [name]: movedEntry },- }));- await mutateSkillsLock(fromPath, (lock) => {- const remaining = { ...lock.skills };- delete remaining[name];- return { ...lock, skills: remaining };- });- return true;- }-- function updateSkillLockEntry(- scope: 'project' | 'global',- name: string,- patch: Partial<SkillsLock['skills'][string]>,- ): Promise<void> {- const lockPath = skillLockPath(scope);- if (!lockPath) return Promise.resolve();- return mutateSkillsLock(lockPath, (lock) => {- const entry = lock.skills[name];- if (!entry) return lock;- return { ...lock, skills: { ...lock.skills, [name]: { ...entry, ...patch } } };- });- }-- function respondSkillRestoreFailure(- res: ServerResponse,- result: {- code: 'no-shadow' | 'version-not-found' | 'skill-absent' | 'io-error' | 'path-escape';- error: string;- },- handler: 'skill-restore' | 'skill-revert',- ): void {- const map = {- 'no-shadow': [409, 'urn:ok:error:shadow-not-configured'],- 'version-not-found': [404, 'urn:ok:error:not-found'],- 'skill-absent': [404, 'urn:ok:error:not-found'],- 'io-error': [500, 'urn:ok:error:storage-error'],- 'path-escape': [500, 'urn:ok:error:path-escape'],- } as const;- const [status, typeUri] = map[result.code];- errorResponse(res, status, typeUri, result.error, { handler, detail: result.code });- }-function effectiveInstallMode(scope: 'project' | 'global',name: string,@@ -6027,8 +5748,6 @@ export function createApiExtension(: `${LEGACY_SKILL_STORE_ROOT}/${name}`;}- const BUILTIN_PROJECT_SKILL_NAME = BUNDLE_SKILL_NAME.project;-function resolveBuiltinSkillDir(base: string,name: string,@@ -6098,33 +5817,6 @@ export function createApiExtension(};}- const PLUGIN_INDEX_TTL_MS = 30_000;- let pluginIndex: { at: number; identity: string; byName: Map<string, PluginUpstream> } | null =- null;-- function pluginSkillsByName(identity: string): Map<string, PluginUpstream> {- const now = Date.now();- if (- pluginIndex &&- pluginIndex.identity === identity &&- now - pluginIndex.at < PLUGIN_INDEX_TTL_MS- )- return pluginIndex.byName;- let byName = new Map<string, PluginUpstream>();- try {- byName = pluginUpstreamsByName(- enumerateInstalledSkillsCached(- homeDirOverride !== undefined ? { home: homeDirOverride } : {},- ).skills,- (home) => parseSkillDir(home)?.contentHash,- );- } catch (err) {- log.warn({ err }, 'plugin upstream index failed; origins will be omitted');- }- pluginIndex = { at: now, identity, byName };- return byName;- }-function pluginUpstreamHash(name: string, identity: string): string | null {return pluginSkillsByName(identity).get(name)?.contentHash ?? null;}@@ -6366,4249 +6058,170 @@ export function createApiExtension(return { skills, truncated };}- function trackInGitLine(skillDirRel: string): string {- const root = dirname(skillDirRel);- return `!/${root.split(sep).join('/')}/`;+ function effectiveSkillRoot(+ scope: 'project' | 'global',+ name: string,+ host?: string,+ ): { root: string; dirRel: string; realDir: string | null } {+ const base = scope === 'project' ? contentDir : skillsHome;+ const realDir = resolveSkillDirForRead(scope, name, host);+ const root = realDir !== null ? dirname(realDir) : resolveSkillsRoot(scope);+ const dirRel =+ realDir !== null ? relative(base, realDir).split(sep).join('/') : `.ok/skills/${name}`;+ return { root, dirRel, realDir };+ }+ function localSkillHash(skillsRoot: string, name: string): string | undefined {+ return parseSkillDir(resolve(skillsRoot, name))?.contentHash;+ }+ async function shadowHeadSha(+ writerId?: string,+ verifyPathRel?: string,+ ): Promise<string | undefined> {+ const shadow = shadowRef?.current;+ if (!shadow || !writerId) return undefined;+ /**+ * The shadow repo has no `HEAD`/`main`: writes land on per-writer WIP refs+ * (`refs/wip/<branch>/<writerId>`, precedent #25), so capture the actor's WIP ref rather+ * than `rev-parse HEAD`.+ */+ try {+ const sg = shadowGit(shadow);+ const readMine = async (): Promise<string | undefined> => {+ const refs = (await sg.raw('for-each-ref', '--format=%(refname)', 'refs/wip/'))+ .trim()+ .split('\n')+ .filter(Boolean);+ const mine = refs.find((r) => r.endsWith(`/${writerId}`));+ if (!mine) return undefined;+ return (await sg.raw('rev-parse', mine)).trim();+ };+ const treeHas = async (sha: string, rel: string): Promise<boolean> => {+ const out = await sg.raw('ls-tree', '-r', '--name-only', sha, '--', rel);+ return out.trim().length > 0;+ };+ let sha = await readMine();+ if (+ sha !== undefined &&+ verifyPathRel !== undefined &&+ !(await treeHas(sha, verifyPathRel))+ ) {+ await commitOkArtifactWrite('baseline-verify');+ sha = await readMine();+ if (sha !== undefined && !(await treeHas(sha, verifyPathRel))) return undefined;+ }+ return sha;+ } catch {+ return undefined;+ }+ }+ const artifactWriterId = (actor: ReturnType<typeof extractActorIdentity>): string | undefined =>+ actor.kind === 'agent' || actor.kind === 'principal' ? actor.writerId : undefined;+ async function projectImportedSkillCopy(args: {+ skillsRoot: string;+ name: string;+ scope: 'project' | 'global';+ hasScripts: boolean;+ handler: string;+ }): Promise<void> {+ try {+ const installBase = skillInstallBase(args.scope);+ if (!installBase) return;+ const targets = resolveSkillTargets(installBase);+ if (targets.length === 0) return;+ const hosts = projectSkill(+ resolve(args.skillsRoot, args.name),+ args.name,+ installBase,+ targets,+ 'copy',+ skillProjectionRoots(args.scope),+ );+ if (hosts.length === 0) return;+ await recordSkillInstall(installBase, args.name, {+ hosts,+ scope: args.scope,+ scripts: args.hasScripts,+ installedAt: new Date().toISOString(),+ projection: 'copy',+ });+ } catch (projectErr) {+ log.warn(+ { skill: args.name, err: projectErr },+ `${args.handler}: inline projection failed; skill written, reconcile will project on next open`,+ );+ }}- const handleSkillTrackInGit = withValidation(- SkillTrackInGitRequestSchema,- catchErrors(- async (_req, res, body) => {- if (!validateSkillName(body.name, res, 'skill-track-in-git')) return;- if (body.scope !== 'project') {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Only project skills live in the repository; a global skill is outside any .gitignore.',- { handler: 'skill-track-in-git' },- );- return;- }- if (!projectDir) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project directory.', {- handler: 'skill-track-in-git',- });- return;- }- const inPlace = scanInPlaceSkills(contentDir).find((s) => s.name === body.name);- const mountedDirRel = inPlace?.dir ?? `${LEGACY_SKILL_STORE_ROOT}/${body.name}`;- const indexedFileRel =- indexedSkillContentPath(resolve(contentDir, mountedDirRel, 'SKILL.md'), contentDir) ??- `${mountedDirRel}/SKILL.md`;- const skillDirRel = dirname(indexedFileRel);- const skillFileRel = indexedFileRel;- const line = trackInGitLine(skillDirRel);- const gitignoreRel = '.gitignore';- const gitignoreAbs = resolve(contentDir, gitignoreRel);-- if (contentFilter && !contentFilter.isPathIgnored(skillFileRel)) {- successResponse(- res,- 200,- SkillTrackInGitSuccessSchema,- { line, gitignorePath: gitignoreRel, applied: false, alreadyTracked: true },- { handler: 'skill-track-in-git' },- );- return;- }- if (body.apply !== true) {- successResponse(- res,- 200,- SkillTrackInGitSuccessSchema,- { line, gitignorePath: gitignoreRel, applied: false },- { handler: 'skill-track-in-git' },- );- return;- }+ const skillImportService = createSkillImportService({+ contentDir,+ skillsHome,+ ...(projectDir !== undefined ? { projectDir } : {}),+ resolveSkillDirForRead,+ parseFrontmatterDoc,+ attributeOkArtifactWrite,+ commitOkArtifactWrite,+ shadowHeadSha,+ artifactWriterId,+ effectiveInstallMode,+ signalFiles: () => signalChannel?.('files'),+ });- const before = existsSync(gitignoreAbs) ? readFileSync(gitignoreAbs, 'utf-8') : null;- const lines = (before ?? '').split('\n');- if (lines.some((l) => l.trim() === line)) {- errorResponse(- res,- 409,- 'urn:ok:error:invalid-request',- `"${line}" is already in ${gitignoreRel}, but ${skillFileRel} is still ignored — another rule excludes it.`,- { handler: 'skill-track-in-git' },- );- return;- }- const next = `${before === null || before.endsWith('\n') || before === '' ? (before ?? '') : `${before}\n`}${line}\n`;- writeFileSync(gitignoreAbs, next, 'utf-8');- bumpSkillsCatalogGen();- await contentFilter?.rebuildIgnorePatterns();-- if (contentFilter?.isPathIgnored(skillFileRel)) {- if (before === null) rmSync(gitignoreAbs, { force: true });- else writeFileSync(gitignoreAbs, before, 'utf-8');- bumpSkillsCatalogGen();- await contentFilter.rebuildIgnorePatterns();+ const skillReimportService = createSkillReimportService({+ contentDir,+ skillsHome,+ ...(projectDir !== undefined ? { projectDir } : {}),+ legacyStoreRoot: LEGACY_SKILL_STORE_ROOT,+ effectiveSkillRoot,+ parseFrontmatterDoc,+ attributeOkArtifactWrite,+ commitOkArtifactWrite,+ shadowHeadSha,+ artifactWriterId,+ skillArtifactKey: (name) => okArtifactKey('skill', '', name),+ captureAndCloseDocuments,+ projectImportedSkillCopy,+ signalFiles: () => signalChannel?.('files'),+ });++ const handleSkillUninstall = withValidation(+ SkillUninstallRequestSchema,+ async (_req, res, body) => {+ try {+ if (!validateSkillName(body.name, res, 'skill-uninstall')) return;+ const base = skillInstallBase(body.scope);+ if (!base) {errorResponse(res,- 409,+ 400,'urn:ok:error:invalid-request',- `Adding "${line}" did not make ${skillFileRel} trackable — another .gitignore rule excludes a parent directory. ${gitignoreRel} was left unchanged.`,- { handler: 'skill-track-in-git' },+ 'Cannot uninstall — no project root is resolved for this server.',+ { handler: 'skill-uninstall', detail: 'NO_PROJECT_ROOT' },);return;}+ const uninstalled = await uninstallSkillFromHostDirs(base, body.name, body.scope);signalChannel?.('files');successResponse(res,200,- SkillTrackInGitSuccessSchema,- { line, gitignorePath: gitignoreRel, applied: true },- { handler: 'skill-track-in-git' },- );- },- { handler: 'skill-track-in-git', title: 'Failed to update .gitignore.' },- ),- { handler: 'skill-track-in-git', method: 'POST' },- );-- const skillAdmissionHeal: SkillAdmissionHealState = { lastKey: null };-- const handleSkillsList = withValidation(- EmptyRequestSchema,- catchErrors(- async (_req, res) => {- const inPlaceFp =- (contentFilter?.peekFreshInPlaceSkillDirsFingerprint() ?? '') +- '\u0001' +- (projectDir ? detectProjectSkillEditors(projectDir).join(',') : '') +- '\u0001' +- detectUserSkillHosts(skillsHome)- .map((h) => h.editorId)- .join(',') +- '\u0001' +- scanGlobalInPlaceSkills(skillsHome)- .map((s) => s.dir)- .sort()- .join(',');- if (skillsListCache !== null && skillsListCache.fp !== inPlaceFp) {- bumpSkillsCatalogGen();- }- if (- skillsListCache !== null &&- skillsListCache.gen === skillsCatalogGen &&- skillsListCache.fp === inPlaceFp &&- Date.now() - skillsListCache.at < 5_000- ) {- successResponse(res, 200, SkillsListSuccessSchema, skillsListCache.body, {- handler: 'skills-list',- });- return;- }- const projectSkillsRoot = resolveSkillsRoot('project');- const project = resolveSkillsList(projectSkillsRoot, 'project');- const globalSkills = resolveSkillsList(resolveSkillsRoot('global'), 'global');- const projectInstallableEditors: string[] = projectDir- ? detectProjectSkillEditors(projectDir)- : [];- const globalInstallableEditors: string[] = detectUserSkillHosts(skillsHome).map(- (h) => h.editorId,- );- const projectHubOffered: boolean = projectDir- ? isActivatedSkillRoot(projectDir, 'project', AGENTS_SKILLS_ROOT, skillsHome)- : false;- const globalHubOffered: boolean = isActivatedSkillRoot(- skillsHome,- 'global',- AGENTS_SKILLS_ROOT,- skillsHome,+ SkillUninstallSuccessSchema,+ { name: body.name, uninstalled },+ { handler: 'skill-uninstall' },);- const projectInstalled = projectDir ? readInstalledSkills(projectDir).skills : {};- const globalInstalled = readInstalledSkills(skillsHome).skills;- const lock: SkillsLock | null = projectDir- ? (parseSkillsLock(- existsSync(join(projectDir, ...SKILLS_LOCK_REL))- ? readFileSync(join(projectDir, ...SKILLS_LOCK_REL), 'utf-8')- : '',- ) ?? null)- : null;- const skillOrigin = skillOriginFor;- const enrich = (- list: typeof project,- marker: Record<string, { hosts: string[] }>,- withOrigin: boolean,- ) =>- list.skills.map((skill) => {- const record = marker[skill.name];- const hosts = record?.hosts ?? [];- const entry = withOrigin ? lock?.skills[skill.name] : undefined;- const origin = entry ? skillOrigin(entry) : undefined;- const modified =- entry?.localHash !== undefined &&- localSkillHash(projectSkillsRoot, skill.name) !== entry.localHash;- const revertable = entry?.baselineRef !== undefined;- return {- ...skill,- installed: hosts.length > 0,- hosts,- ...(origin ? { origin } : {}),- ...(modified ? { modified: true } : {}),- ...(revertable ? { revertable: true } : {}),- };- });- const placements = projectDir ? readSkillPlacements(projectDir) : {};- const placementFlags = (- baseDir: string,- list: ReturnType<typeof readSkillPlacements>[string] | undefined,- canonicalAbs?: string,- ): { drift: string[] } => {- const drift: string[] = [];- for (const p of list ?? []) {- const abs = resolve(baseDir, p.path);- if (canonicalAbs !== undefined && abs === resolve(canonicalAbs)) continue;- let isLink = false;- try {- isLink = lstatSync(abs).isSymbolicLink();- } catch {- continue;- }- if ((isLink ? 'link' : 'copy') === p.mode) continue;- if (isLink && canonicalAbs !== undefined) {- try {- if (realpathSync(abs) === realpathSync(canonicalAbs)) continue;- } catch {}- }- drift.push(p.path);- }- return { drift };- };- const projectAliases = projectDir ? scanHostRootAliases(contentDir, 'project') : {};- const projectAliasRoots = aliasedSourceRoots(projectAliases, 'project');- const underRoots = (path: string, roots: ReadonlySet<string>): boolean =>- [...roots].some((r) => path === r || path.startsWith(`${r}/`));- const detectedIdentity = resolveProjectIdentity(projectDir ?? contentDir);- const pluginBaselines = openPluginBaselines(contentDir);- const stdRootsProject = standardSkillRoots('project');- const stdRootsGlobal = standardSkillRoots('global');- const dropAliased = (- list: ReturnType<typeof readSkillPlacements>[string] | undefined,- aliasRoots: Set<string>,- ): ReturnType<typeof readSkillPlacements>[string] =>- (list ?? []).filter(- (pl) => ![...aliasRoots].some((r) => pl.path === r || pl.path.startsWith(`${r}/`)),- );- const projectNameSeen = new Set<string>();- const repoPlugins = readRepoMarketplacePlugins(contentDir);- const repoPluginIdentity = (dir: string) => {- const p = repoMarketplacePluginFor(repoPlugins, dir);- return p- ? {- name: p.name,- marketplace: p.marketplace,- provider: 'claude',- ...(p.url ? { url: p.url } : {}),- }- : null;- };- const inPlace = projectDir- ? scanInPlaceSkills(contentDir).map((s) => {- const tracked = !projectNameSeen.has(s.name);- projectNameSeen.add(s.name);- const skillAbsDir = resolve(contentDir, s.dir);- const selfPlugin = tracked- ? (pluginSelfIdentity(s.name, detectedIdentity, skillAbsDir) ??- repoPluginIdentity(skillAbsDir))- : null;- const entry =- tracked && selfPlugin === null- ? (lock?.skills[s.name] ??- synthBuiltinLockEntry(contentDir, s.name, 'project') ??- synthPluginLockEntry(s.name, detectedIdentity, skillAbsDir))- : undefined;- const origin = entry ? skillOrigin(entry) : undefined;- const modified =- entry?.localHash !== undefined- ? s.contentHash !== entry.localHash- : (() => {- if (!entry || !tracked) return false;- const up = pluginUpstreamHash(s.name, detectedIdentity);- return (- up !== null &&- pluginBaselines.isModified('project', s.name, s.contentHash, up)- );- })();- return {- name: s.name,- ...(s.description ? { description: s.description } : {}),- scope: 'project' as const,- path: `${s.dir}/SKILL.md`,- absolutePath: resolve(contentDir, s.dir, 'SKILL.md'),- installed: true,- hosts: [...s.hosts],- size: s.size,- installableEditors: projectInstallableEditors,- hubOffered: projectHubOffered,- ...(s.pack !== undefined ? { pack: s.pack } : {}),- ...(s.linkedHosts.length > 0 ? { symlinkedHosts: [...s.linkedHosts] } : {}),- ...(Object.keys(projectAliases).length > 0 ? { hostAliases: projectAliases } : {}),- ...(s.conflictHosts.length > 0 ? { conflictHosts: [...s.conflictHosts] } : {}),- ...(selfPlugin !== null ? { plugin: selfPlugin } : {}),- ...(() => {- const custom = dropAliased(- tracked ? placements[s.name] : undefined,- projectAliasRoots,- ).filter((cp) => !underRoots(cp.path, stdRootsProject));- return custom.length- ? { customPlacements: custom.map((cp) => ({ path: cp.path, mode: cp.mode })) }- : {};- })(),- ...(() => {- const f = placementFlags(- projectDir,- dropAliased(tracked ? placements[s.name] : undefined, projectAliasRoots),- resolve(contentDir, s.dir),- );- return f.drift.length > 0 ? { driftPaths: f.drift } : {};- })(),- ...(effectiveInstallMode('project', s.name, s) === 'link'- ? { linkMode: true }- : {}),- ...(origin ? { origin } : {}),- ...(modified ? { modified: true } : {}),- ...(entry?.baselineRef !== undefined ? { revertable: true } : {}),- ...(isInternalBundleSkillName(s.name) ? { managed: true as const } : {}),- };- })- : [];- const globalPlacements = readSkillPlacements(skillsHome);- const globalLock = readSkillsLock(join(skillsHome, ...SKILLS_LOCK_REL));- const globalAliases = scanHostRootAliases(skillsHome, 'global');- const globalAliasRoots = aliasedSourceRoots(globalAliases, 'global');- const globalInPlaceNames = new Set(scanGlobalInPlaceSkills(skillsHome).map((s) => s.name));- globalSkills.skills = globalSkills.skills.filter((s) => !globalInPlaceNames.has(s.name));- const globalNameSeen = new Set<string>();- const globalInPlace = scanGlobalInPlaceSkills(skillsHome).map((s) => {- const tracked = !globalNameSeen.has(s.name);- globalNameSeen.add(s.name);- const placementsForRow = tracked ? globalPlacements[s.name] : undefined;- const defaultDir = resolveGlobalNativeSkillDir(skillsHome, s.name);- const hostQualifier =- defaultDir !== null && resolve(skillsHome, s.dir) !== resolve(defaultDir)- ? s.hosts[0]- : undefined;- return {- name: s.name,- ...(s.description ? { description: s.description } : {}),- scope: 'global' as const,- path: `${s.dir}/SKILL.md`,- absolutePath: resolve(skillsHome, s.dir, 'SKILL.md'),- installed: true,- hosts: [...s.hosts],- ...(hostQualifier !== undefined ? { hostQualifier } : {}),- size: s.size,- installableEditors: globalInstallableEditors,- hubOffered: globalHubOffered,- ...(s.pack !== undefined ? { pack: s.pack } : {}),- ...(s.linkedHosts.length > 0 ? { symlinkedHosts: [...s.linkedHosts] } : {}),- ...(Object.keys(globalAliases).length > 0 ? { hostAliases: globalAliases } : {}),- ...(s.conflictHosts.length > 0 ? { conflictHosts: [...s.conflictHosts] } : {}),- ...(() => {- const f = placementFlags(- skillsHome,- dropAliased(placementsForRow, globalAliasRoots),- resolve(skillsHome, s.dir),- );- return f.drift.length > 0 ? { driftPaths: f.drift } : {};- })(),- ...(() => {- const custom = dropAliased(placementsForRow, globalAliasRoots).filter(- (cp) => !underRoots(cp.path, stdRootsGlobal),- );- return custom.length- ? { customPlacements: custom.map((cp) => ({ path: cp.path, mode: cp.mode })) }- : {};- })(),- ...(effectiveInstallMode('global', s.name, s) === 'link' ? { linkMode: true } : {}),- ...(isInternalBundleSkillName(s.name) ? { managed: true as const } : {}),- ...(() => {- if (!tracked) return {};- const globalAbsDir = resolve(skillsHome, s.dir);- const selfPluginGlobal = pluginSelfIdentity(s.name, detectedIdentity, globalAbsDir);- if (selfPluginGlobal !== null) return { plugin: selfPluginGlobal };- const entry =- globalLock.skills[s.name] ??- synthBuiltinLockEntry(skillsHome, s.name, 'global') ??- synthPluginLockEntry(s.name, detectedIdentity, globalAbsDir);- if (!entry) return {};- const globallyModified =- entry.localHash !== undefined- ? s.contentHash !== entry.localHash- : (() => {- const up = pluginUpstreamHash(s.name, detectedIdentity);- return (- up !== null &&- pluginBaselines.isModified('global', s.name, s.contentHash, up)- );- })();- return {- origin: skillOrigin(entry),- ...(globallyModified ? { modified: true } : {}),- };- })(),- };- });- const inPlaceNamesEarly = new Set(inPlace.map((e) => e.name));- const projectBuiltin =- projectDir &&- !project.skills.some((s) => s.name === BUILTIN_PROJECT_SKILL_NAME) &&- !inPlaceNamesEarly.has(BUILTIN_PROJECT_SKILL_NAME)- ? builtinSkillListEntry(projectDir, BUILTIN_PROJECT_SKILL_NAME, 'project')- : null;- const globalInPlaceNamesEarly = new Set(globalInPlace.map((e) => e.name));- const globalBuiltins = USER_GLOBAL_BUNDLE_IDS.map((id) => BUNDLE_SKILL_NAME[id])- .filter(- (name) =>- !globalSkills.skills.some((s) => s.name === name) &&- !globalInPlaceNamesEarly.has(name),- )- .map((name) => builtinSkillListEntry(skillsHome, name, 'global'))- .filter((e): e is NonNullable<typeof e> => e !== null);- const inPlaceNames = new Set(inPlace.map((e) => e.name));- const listed = [- ...enrich(project, projectInstalled, true).filter((e) => !inPlaceNames.has(e.name)),- ...inPlace,- ...enrich(globalSkills, globalInstalled, false),- ...globalInPlace,- ...(projectBuiltin ? [projectBuiltin] : []),- ...globalBuiltins,- ];- pluginBaselines.flush();- const enriched = {- skills: listed.map((entry) => {- const canonicalPath =- entry.scope === 'project' && entry.absolutePath- ? indexedSkillContentPath(entry.absolutePath, contentDir)- : null;- const filePaths = entry.absolutePath- ? listSkillBundledFilePaths(dirname(entry.absolutePath))- : [];- const withFiles = filePaths.length > 0 ? { ...entry, filePaths } : entry;- const withCanonical =- canonicalPath === null || canonicalPath === entry.path- ? withFiles- : { ...withFiles, canonicalPath };- const openedPath = canonicalPath ?? entry.path;- return entry.scope === 'project' && contentFilter?.isPathIgnored(openedPath) === true- ? { ...withCanonical, ignored: true }- : withCanonical;- }),- truncated: project.truncated || globalSkills.truncated,- };- const healed = await healUnservableSkillAdmission(- inPlace.map((e) => e.path),- contentFilter ?? null,- skillAdmissionHeal,- );- const responseBody = !healed- ? enriched- : {- ...enriched,- skills: enriched.skills.map((entry) => {- if (entry.scope !== 'project') return entry;- const opened = (entry as { canonicalPath?: string }).canonicalPath ?? entry.path;- const nowIgnored = contentFilter?.isPathIgnored(opened) === true;- const wasIgnored = (entry as { ignored?: boolean }).ignored === true;- if (nowIgnored === wasIgnored) return entry;- if (nowIgnored) return { ...entry, ignored: true };- const { ignored: _drop, ...rest } = entry as { ignored?: boolean } & typeof entry;- return rest;- }),- };- skillsListCache = {- at: Date.now(),- gen: skillsCatalogGen,- fp: inPlaceFp,- body: responseBody,- };- successResponse(res, 200, SkillsListSuccessSchema, responseBody, {- handler: 'skills-list',- });- },- { handler: 'skills-list', title: 'Failed to list skills.' },- ),- { handler: 'skills-list', method: 'GET', skipBodyParse: true },- );-- const handleSkillGet = withValidation(- EmptyRequestSchema,- async (req, res) => {- try {- const url = new URL(req.url ?? '', 'http://localhost');- const name = url.searchParams.get('name') ?? '';- if (!validateSkillName(name, res, 'skill-get')) return;- const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-get');- if (scope === null) return;-- if (isInternalBundleSkillName(name)) {- const base = scope === 'global' ? skillsHome : projectDir;- const builtin = base- ? resolveBuiltinSkillDir(base, name, scope, url.searchParams.get('host') ?? undefined)- : null;- if (builtin) {- const { frontmatter, body } = parseFrontmatterDoc(- await readFile(builtin.skillMd, 'utf-8'),- );- successResponse(- res,- 200,- SkillGetSuccessSchema,- {- skill: {- name,- scope,- path: builtin.relPath,- frontmatter: {- name: typeof frontmatter.name === 'string' ? frontmatter.name : name,- description:- typeof frontmatter.description === 'string' ? frontmatter.description : '',- },- body,- files: readSkillBundledFiles(builtin.dir),- managed: true,- },- },- { handler: 'skill-get' },- );- return;- }- }- const host = url.searchParams.get('host') ?? undefined;- const skillDirAbs = resolveSkillDirForRead(scope, name, host);- if (skillDirAbs === null) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {- handler: 'skill-get',- detail:- host === undefined- ? `Skill "${name}" not found in ${scope} scope.`- : `No skill "${name}" (${scope}) in ${host}.`,- });- return;- }- const skillMd = resolve(skillDirAbs, 'SKILL.md');- const { frontmatter, body } = parseFrontmatterDoc(await readFile(skillMd, 'utf-8'));- successResponse(- res,- 200,- SkillGetSuccessSchema,- {- skill: {- name,- scope,- path: skillRelPath(skillMd, scope),- frontmatter: {- name: typeof frontmatter.name === 'string' ? frontmatter.name : name,- description:- typeof frontmatter.description === 'string' ? frontmatter.description : '',- },- body,- files: readSkillBundledFiles(skillDirAbs),- },- },- { handler: 'skill-get' },- );- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to read skill.', {- handler: 'skill-get',- cause: e,- });- }- },- { handler: 'skill-get', method: 'GET', skipBodyParse: true },- );-- async function seedSkillDerivedViews(docName: string, markdown: string): Promise<void> {- if (!derivedDocumentIndex || isLinkIndexExcludedDoc(docName)) return;- if (contentFilter) {- bumpSkillsCatalogGen();- contentFilter.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();- }- void recordDerivedDocumentBestEffort(docName, markdown, 'skill-put');- }-- const handleSkillPut = withValidation(- SkillPutRequestSchema,- async (_req, res, body) => {- try {- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-put',- });- return;- }- if (!validateSkillName(body.name, res, 'skill-put')) return;- if (rejectReservedBuiltinSkill(body.name, res, 'skill-put')) return;-- const composed = composeSkillContent({- name: body.name,- body: typeof body.body === 'string' ? body.body : '',- frontmatter: { name: body.frontmatter.name, description: body.frontmatter.description },- });- if (!composed.ok) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid skill request.', {- handler: 'skill-put',- detail: composed.error.code,- cause: new Error(composed.error.message),- });- return;- }-- const putBase = body.scope === 'project' ? contentDir : skillsHome;- const existingAbs = resolveSkillDirForRead(body.scope, body.name);- if (existingAbs === null) {- const homeRel = resolveDefaultSkillHomeRel(putBase, body.scope);- if (homeRel === null) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'No agent skill host is available.',- { handler: 'skill-put', detail: 'NO_USABLE_SKILL_HOME' },- );- return;- }- const wr = applySkillWrite({- skillsRoot: resolve(putBase, homeRel),- name: body.name,- body: typeof body.body === 'string' ? body.body : '',- frontmatter: {- name: body.frontmatter.name,- description: body.frontmatter.description,- },- });- if (!wr.ok) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid skill request.', {- handler: 'skill-put',- detail: wr.error.code,- cause: new Error(wr.error.message),- });- return;- }- if (body.scope === 'project') {- attributeOkArtifactWrite(- actor,- `${homeRel}/${body.name}/SKILL`,- `skill-create: ${homeRel}/${body.name}/SKILL.md`,- );- scheduleOkArtifactFlush('skill-put');- }- await seedSkillDerivedViews(- body.scope === 'project'- ? `${homeRel}/${body.name}/SKILL`- : skillLiveDocName('global', body.name),- composed.content,- );- signalChannel?.('files');- successResponse(- res,- 200,- SkillPutSuccessSchema,- {- path: `${homeRel}/${body.name}/SKILL.md`,- created: true,- warnings: [...composed.warnings, ...wr.warnings],- },- { handler: 'skill-put' },- );- return;- }- const created = false;- const dirRel = relative(putBase, existingAbs).split(sep).join('/');- const relPath = `${dirRel}/SKILL.md`;- const docName =- body.scope === 'project' ? `${dirRel}/SKILL` : skillLiveDocName(body.scope, body.name);-- if (checkSkillDocConflictGate(docName, 'skill-put', res)) return;-- /**- * CRDT write (precedent #24 / #38): the full SKILL.md goes through the doc's- * `Y.Text('source')` via the sanctioned paired-write primitive under the per-session- * frozen origin.- */- const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(- body as unknown as Record<string, unknown>,- );- const session = await sessionManager.getSession(docName, agentId, {- displayName: agentName,- colorSeed,- clientName,- });- session.dc.document.transact(() => {- composeAndWriteRawBody(session.dc.document, composed.content, 'agent');- }, session.origin);-- const flushOutcome = await flushDiskAndDetectOutcome(docName);- if (flushOutcome?.kind === 'failure') {- respondPersistenceFailure(res, flushOutcome.failure, 'skill-put');- return;- }- if (flushOutcome?.kind === 'divergence') {- respondDiskDivergence(res, 'skill-put');- return;- }- if (flushOutcome?.kind === 'stale-external-write') {- respondStaleExternalWrite(res, 'skill-put', docName);- return;- }-- if (body.scope === 'project') {- attributeOkArtifactWrite(- actor,- okArtifactKey('skill', '', body.name),- `${created ? 'skill-create' : 'skill-edit'}: ${relPath}`,- );- scheduleOkArtifactFlush('skill-put');- }- await seedSkillDerivedViews(docName, composed.content);- signalChannel?.('files');- successResponse(- res,- 200,- SkillPutSuccessSchema,- { path: relPath, created, warnings: composed.warnings },- { handler: 'skill-put' },- );- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to write skill.', {- handler: 'skill-put',- cause: e,- });- }- },- { handler: 'skill-put', method: 'PUT' },- );-- function effectiveSkillRoot(- scope: 'project' | 'global',- name: string,- host?: string,- ): { root: string; dirRel: string; realDir: string | null } {- const base = scope === 'project' ? contentDir : skillsHome;- const realDir = resolveSkillDirForRead(scope, name, host);- const root = realDir !== null ? dirname(realDir) : resolveSkillsRoot(scope);- const dirRel =- realDir !== null ? relative(base, realDir).split(sep).join('/') : `.ok/skills/${name}`;- return { root, dirRel, realDir };- }- function sweepSkillOccurrences(scope: 'project' | 'global', name: string): void {- const base = scope === 'project' ? contentDir : skillsHome;- const inPlace = (- scope === 'project' ? scanInPlaceSkills(contentDir) : scanGlobalInPlaceSkills(skillsHome)- ).find((sk) => sk.name === name);- if (!inPlace) return;- removeInPlaceSkillCopies({- canonicalAbs: resolve(base, inPlace.dir),- canonicalHash: inPlace.contentHash,- name,- cwd: base,- targets: inPlace.hosts.filter((h): h is SkillHostId => isSkillInstallTarget(h)),- roots: skillProjectionRoots(scope),- });- }-- const handleSkillDelete = withValidation(- EmptyRequestSchema,- async (req, res) => {- try {- const url = new URL(req.url ?? '', 'http://localhost');- const name = url.searchParams.get('name') ?? '';- if (!validateSkillName(name, res, 'skill-delete')) return;- const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-delete');- if (scope === null) return;- const host = url.searchParams.get('host') ?? undefined;- const { root: skillsRoot, dirRel, realDir } = effectiveSkillRoot(scope, name, host);- if (host !== undefined && realDir === null) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {- handler: 'skill-delete',- detail: `No skill "${name}" (${scope}) in ${host}.`,- });- return;- }-- const actor = extractActorIdentityFromQuery(url, getPrincipal);- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-delete',- });- return;- }-- await captureAndCloseDocuments(- scope === 'project'- ? [...new Set([`${dirRel}/SKILL`, skillLiveDocName(scope, name)])]- : [skillLiveDocName(scope, name, host)],- 'deleted-upstream',- );-- if (host === undefined) sweepSkillOccurrences(scope, name);- const result = applySkillDelete({ skillsRoot, name });- const storeRoot = resolveSkillsRoot(scope);- if (- host === undefined &&- result.ok &&- storeRoot !== skillsRoot &&- existsSync(resolve(storeRoot, name, 'SKILL.md'))- ) {- const storeSweep = applySkillDelete({ skillsRoot: storeRoot, name });- if (!storeSweep.ok) {- log.warn(- { name, scope, detail: storeSweep.error.code },- '[skill-delete] legacy store resident survived the delete',- );- }- }- if (!result.ok) {- const status = result.error.code === 'UNLINK_FAILED' ? 500 : 400;- errorResponse(- res,- status,- status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',- status === 500 ? 'Failed to delete skill.' : 'Invalid skill request.',- {- handler: 'skill-delete',- detail: result.error.code,- cause: new Error(result.error.message),- },- );- return;- }- if (result.existed) {- if (scope === 'project') {- attributeOkArtifactWrite(actor, dirRel, `skill-delete: ${dirRel}`);- bumpSkillsCatalogGen();- void commitOkArtifactWrite('skill-delete');- }- signalChannel?.('files');- }- const uninstallBase = skillInstallBase(scope);- if (host === undefined && uninstallBase) {- await uninstallSkillFromHostDirs(uninstallBase, name, scope);- }- successResponse(- res,- 200,- SkillDeleteSuccessSchema,- { existed: result.existed, path: result.path },- { handler: 'skill-delete' },- );- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to delete skill.', {- handler: 'skill-delete',- cause: e,- });- }- },- { handler: 'skill-delete', method: 'DELETE', skipBodyParse: true },- );-- const handleSkillMove = withValidation(- SkillMoveRequestSchema,- async (_req, res, body) => {- try {- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-move',- });- return;- }- if (!validateSkillName(body.fromName, res, 'skill-move')) return;- if (!validateSkillName(body.toName, res, 'skill-move')) return;- if (rejectReservedBuiltinSkill(body.toName, res, 'skill-move')) return;- const { root: skillsRoot, dirRel: fromDirRel } = effectiveSkillRoot(- body.scope,- body.fromName,- );- if (resolveSkillDirForRead(body.scope, body.toName) !== null) {- errorResponse(- res,- 409,- 'urn:ok:error:doc-already-exists',- `A skill named "${body.toName}" already exists.`,- { handler: 'skill-move' },- );- return;- }-- const moveBase = skillInstallBase(body.scope);- const priorInstall = moveBase- ? readInstalledSkills(moveBase).skills[body.fromName]- : undefined;- const fromScanBase = body.scope === 'project' ? contentDir : skillsHome;- const renameScanEntry = (- body.scope === 'project'- ? scanInPlaceSkills(contentDir)- : scanGlobalInPlaceSkills(skillsHome)- ).find((sk) => sk.name === body.fromName);- const renameCanonicalRootRel = renameScanEntry ? dirname(renameScanEntry.dir) : null;- const renameAliasAudience =- renameCanonicalRootRel !== null- ? Object.entries(scanHostRootAliases(fromScanBase, body.scope))- .filter(([, target]) => target === renameCanonicalRootRel)- .map(([editor]) => editor)- : [];- const priorHosts = [- ...new Set([- ...(priorInstall ? resolvedHosts(priorInstall.hosts, body.scope) : []),- ...(renameScanEntry ? resolvedHosts(renameScanEntry.hosts, body.scope) : []),- ...resolvedHosts(renameAliasAudience, body.scope),- ]),- ];-- await captureAndCloseDocuments(- body.scope === 'project'- ? [...new Set([`${fromDirRel}/SKILL`, skillLiveDocName(body.scope, body.fromName)])]- : [skillLiveDocName(body.scope, body.fromName)],- 'renamed',- );-- sweepSkillOccurrences(body.scope, body.fromName);- const result = await applySkillMove({- skillsRoot,- fromName: body.fromName,- toName: body.toName,- relocate: async (fromAbs, toAbs) => {- const movedWithGit = await renameTrackedPathInGit(projectDir, fromAbs, toAbs);- if (!movedWithGit) renamePathOnDisk(fromAbs, toAbs);- return movedWithGit;- },- });- if (!result.ok) {- if (result.error.code === 'SKILL_NOT_FOUND') {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {- handler: 'skill-move',- detail: result.error.message,- });- return;- }- if (result.error.code === 'SKILL_EXISTS') {- errorResponse(res, 409, 'urn:ok:error:doc-already-exists', result.error.message, {- handler: 'skill-move',- detail: result.error.code,- });- return;- }- const status = result.error.code === 'MOVE_FAILED' ? 500 : 400;- errorResponse(- res,- status,- status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',- status === 500 ? 'Failed to move skill.' : 'Invalid skill move request.',- {- handler: 'skill-move',- detail: result.error.code,- cause: new Error(result.error.message),- },- );- return;- }-- let contentEditError: { code: string; message: string } | null = null;- const movedSkillMd = resolve(skillsRoot, body.toName, 'SKILL.md');- let parsedBody = '';- let parsedDescription = '';- try {- const parsed = parseFrontmatterDoc(readFileSync(movedSkillMd, 'utf-8'));- parsedBody = parsed.body;- if (typeof parsed.frontmatter.description === 'string') {- parsedDescription = parsed.frontmatter.description;- }- } catch {}- const writeBody = typeof body.body === 'string' ? body.body : parsedBody;- const writeDescription =- body.frontmatter !== undefined ? body.frontmatter.description : parsedDescription;- const rewrite = applySkillWrite({- skillsRoot,- name: body.toName,- body: writeBody,- frontmatter: { name: body.toName, description: writeDescription },- });- if (!rewrite.ok) contentEditError = rewrite.error;-- let refRewrites: SkillRefRewrite[] = [];- if (!contentEditError) {- try {- refRewrites = rewriteSkillRefsAcrossScope({- base: body.scope === 'project' ? contentDir : skillsHome,- scope: body.scope,- fromName: body.fromName,- toName: body.toName,- });- } catch (err) {- getLogger('skill-move').warn(- { err, fromName: body.fromName, toName: body.toName },- 'skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored',- );- }- }-- if (body.scope === 'project' && !contentEditError) {- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- void reindexMovedProjectSkillDocs(skillsRoot, body.fromName, body.toName)- .then(() => reindexRewrittenSkillRefDocs(refRewrites, body.toName))- .catch(() => {});- scheduleDeferredIgnoreRebuild();- }-- const fromKeyPath = skillRelPath(resolve(skillsRoot, body.fromName), body.scope);- const toKeyPath = skillRelPath(resolve(skillsRoot, body.toName), body.scope);- const renamedLocalHash = localSkillHash(skillsRoot, body.toName);- await rekeySkillLockEntry(body.scope, body.fromName, body.toName, {- localHash: renamedLocalHash,- });- if (body.scope === 'project') {- attributeOkArtifactWrite(- actor,- okArtifactKey('skill', '', body.toName),- `skill-rename: ${fromKeyPath} -> ${toKeyPath}`,- [{ from: fromKeyPath, to: toKeyPath }],- );- void (async () => {- try {- await commitOkArtifactWrite('skill-move');- const baselineRef = await shadowHeadSha(artifactWriterId(actor), toKeyPath);- if (baselineRef !== undefined) {- await updateSkillLockEntry('project', body.toName, { baselineRef });- }- } catch (err) {- getLogger('skill-move').warn(- { err, toName: body.toName },- 'deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush',- );- }- })();- }-- if (moveBase) {- await removeSkillInstall(moveBase, body.fromName);- reverseProjectSkill(- body.fromName,- moveBase,- priorHosts,- skillProjectionRoots(body.scope),- );- const movedDir = resolve(skillsRoot, body.toName);- if (priorHosts.length > 0) {- const newHosts = projectSkill(- movedDir,- body.toName,- moveBase,- priorHosts,- projectionModeFor(body.scope, body.toName),- skillProjectionRoots(body.scope),- );- await recordSkillInstall(moveBase, body.toName, {- ...priorInstall,- scope: body.scope,- hosts: newHosts,- scripts:- priorInstall?.scripts ?? validateSkillForInstall(movedDir, body.toName).hasScripts,- installedAt: priorInstall?.installedAt ?? new Date().toISOString(),- });- }- }- signalChannel?.('files');-- if (contentEditError) {- const isServerError = contentEditError.code === 'WRITE_ERROR';- errorResponse(- res,- isServerError ? 500 : 400,- isServerError ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',- `Skill renamed to "${body.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,- {- handler: 'skill-move',- detail: contentEditError.code,- cause: new Error(contentEditError.message),- },- );- return;- }- successResponse(- res,- 200,- SkillMoveSuccessSchema,- {- from: fromKeyPath,- to: toKeyPath,- committed: result.committed,- },- { handler: 'skill-move' },- );- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to move skill.', {- handler: 'skill-move',- cause: e,- });- }- },- { handler: 'skill-move', method: 'POST' },- );-- const handleSkillEditExternal = withValidation(- SkillEditExternalRequestSchema,- async (_req, res, body) => {- const { name, home } = body;- if (!validateSkillName(name, res, 'skill-edit-external')) return;- let realDir: string;- try {- realDir = realpathSync(home);- } catch {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill directory not found.', {- handler: 'skill-edit-external',- detail: 'HOME_NOT_FOUND',- });- return;- }- if (!statSync(realDir).isDirectory() || !existsSync(resolve(realDir, 'SKILL.md'))) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Not a skill directory (no SKILL.md).',- { handler: 'skill-edit-external' },- );- return;- }- registerExternalSkill(name, realDir);- successResponse(- res,- 200,- SkillEditExternalSuccessSchema,- { docName: externalSkillLiveDocName(name) },- { handler: 'skill-edit-external' },- );- },- {- handler: 'skill-edit-external',- method: 'POST',- preBodyGate: (req, res) => checkLocalOpSecurity(req, res, { handler: 'skill-edit-external' }),- },- );-- const handleSkillMoveScope = withValidation(- SkillMoveScopeRequestSchema,- async (_req, res, body) => {- try {- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-move-scope',- });- return;- }- const { name, fromScope, toScope } = body;- if (!validateSkillName(name, res, 'skill-move-scope')) return;- if (isInternalBundleSkillName(name)) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- `"${name}" is a built-in skill and always lives at its own scope.`,- { handler: 'skill-move-scope', detail: 'BUILTIN_SCOPE_FIXED' },- );- return;- }- if (fromScope === toScope) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Source and destination scope are the same.',- { handler: 'skill-move-scope' },- );- return;- }- if (toScope === 'project' && !projectDir) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Cannot move to project scope — no project root is resolved for this server.',- { handler: 'skill-move-scope', detail: 'NO_PROJECT_ROOT' },- );- return;- }-- const { root: fromRoot, dirRel: fromDirRel, realDir } = effectiveSkillRoot(fromScope, name);- const fromDir = resolve(fromRoot, name);- const fromContentDir = (() => {- try {- return realpathSync(fromDir);- } catch {- return fromDir;- }- })();- const toBase2 = toScope === 'project' ? contentDir : skillsHome;- const toHomeRel = resolveDefaultSkillHomeRel(toBase2, toScope);- if (toHomeRel === null) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'No agent skill host is available in the destination scope.',- { handler: 'skill-move-scope', detail: 'NO_USABLE_SKILL_HOME' },- );- return;- }- const toRoot = resolve(toBase2, toHomeRel);- const toDir = resolve(toRoot, name);- if (realDir === null || !existsSync(fromDir)) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {- handler: 'skill-move-scope',- detail: `Skill "${name}" not found in ${fromScope} scope.`,- });- return;- }- if (- resolve(realDir) === resolve(toDir) ||- (existsSync(toDir) && realpathSync(realDir) === realpathSync(toDir))- ) {- errorResponse(- res,- 409,- 'urn:ok:error:doc-already-exists',- 'The source and destination resolve to the same skill directory.',- { handler: 'skill-move-scope', detail: 'SAME_STORAGE' },- );- return;- }- if (resolveSkillDirForRead(toScope, name) !== null || existsSync(toDir)) {- errorResponse(- res,- 409,- 'urn:ok:error:doc-already-exists',- `A ${toScope} skill named "${name}" already exists.`,- { handler: 'skill-move-scope' },- );- return;- }-- const fromBase = skillInstallBase(fromScope);- const toBase = skillInstallBase(toScope);- const priorInstall = fromBase ? readInstalledSkills(fromBase).skills[name] : undefined;- const fromScanBase = fromScope === 'project' ? contentDir : skillsHome;- const scanEntry = (- fromScope === 'project'- ? scanInPlaceSkills(contentDir)- : scanGlobalInPlaceSkills(skillsHome)- ).find((sk) => sk.name === name);- const canonicalRootRel = scanEntry ? dirname(scanEntry.dir) : null;- const aliasAudience =- canonicalRootRel !== null- ? Object.entries(scanHostRootAliases(fromScanBase, fromScope))- .filter(([, target]) => target === canonicalRootRel)- .map(([editor]) => editor)- : [];- const priorHosts = [- ...new Set([- ...(priorInstall ? resolvedHosts(priorInstall.hosts, fromScope) : []),- ...(scanEntry ? resolvedHosts(scanEntry.hosts, fromScope) : []),- ...resolvedHosts(aliasAudience, fromScope),- ]),- ];-- await captureAndCloseDocuments(- [- ...new Set([- ...(fromScope === 'project' ? [`${fromDirRel}/SKILL`] : []),- skillLiveDocName(fromScope, name),- skillLiveDocName(toScope, name),- ]),- ],- 'renamed',- );-- tracedMkdirSync(toRoot, { recursive: true });- tracedCpSync(fromContentDir, toDir, { recursive: true, dereference: true });-- sweepSkillOccurrences(fromScope, name);- const del = applySkillDelete({ skillsRoot: fromRoot, name });- if (del.ok && fromContentDir !== fromDir) {- const realScanBase = (() => {- try {- return realpathSync(fromScanBase);- } catch {- return fromScanBase;- }- })();- const relFromBase = relative(realScanBase, fromContentDir);- if (relFromBase !== '' && !relFromBase.startsWith('..') && !isAbsolute(relFromBase)) {- tracedRmSync(fromContentDir, { recursive: true, force: true });- }- }- if (!del.ok) {- applySkillDelete({ skillsRoot: toRoot, name });- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to move skill (source removal failed); rolled back the copy.',- {- handler: 'skill-move-scope',- detail: del.error.code,- cause: new Error(del.error.message),- },- );- return;- }-- const movedLockEntry = await transferSkillLockEntry(fromScope, toScope, name);-- if (fromBase) {- await uninstallSkillFromHostDirs(- fromBase,- name,- fromScope,- scanEntry ? { purge: { contentHash: scanEntry.contentHash } } : {},- );- }- if (fromBase) await clearSkillPlacements(fromBase, name);- if (toBase && priorHosts.length > 0) {- const newHosts = projectSkill(- toDir,- name,- toBase,- priorHosts,- projectionModeFor(toScope, body.name),- skillProjectionRoots(toScope),- );- await recordSkillInstall(toBase, name, {- ...priorInstall,- scope: toScope,- hosts: newHosts,- scripts: priorInstall?.scripts ?? validateSkillForInstall(toDir, name).hasScripts,- installedAt: priorInstall?.installedAt ?? new Date().toISOString(),- });- }-- if (movedLockEntry) {- const movedLocalHash = localSkillHash(toRoot, name);- await updateSkillLockEntry(toScope, name, { localHash: movedLocalHash });- }- if (fromScope === 'project' || toScope === 'project') {- attributeOkArtifactWrite(- actor,- fromScope === 'project' ? fromDirRel : relative(contentDir, toDir).split(sep).join('/'),- `skill-move-scope: ${fromScope} -> ${toScope} ${name}`,- );- const toKeyForBaseline = relative(contentDir, toDir).split(sep).join('/');- const wantBaseline = Boolean(movedLockEntry) && toScope === 'project';- void (async () => {- try {- await commitOkArtifactWrite('skill-move-scope');- if (wantBaseline) {- const baselineRef = await shadowHeadSha(artifactWriterId(actor), toKeyForBaseline);- if (baselineRef !== undefined) {- await updateSkillLockEntry(toScope, name, { baselineRef });- }- }- } catch (err) {- getLogger('skill-move-scope').warn(- { err, name },- 'deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush',- );- }- })();- }-- if (!existsSync(join(toDir, 'SKILL.md'))) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'The move did not leave a readable skill at the destination; nothing was reported as moved.',- { handler: 'skill-move-scope', detail: relative(toBase2, toDir).split(sep).join('/') },- );- return;- }-- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();-- signalChannel?.('files');- successResponse(- res,- 200,- SkillMoveScopeSuccessSchema,- { scope: toScope, path: relative(toBase2, toDir).split(sep).join('/') },- { handler: 'skill-move-scope' },- );- } catch (e) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to move skill across scopes.',- { handler: 'skill-move-scope', cause: e },- );- }- },- { handler: 'skill-move-scope', method: 'POST' },- );-- const handleSkillDuplicate = withValidation(- SkillDuplicateRequestSchema,- async (_req, res, body) => {- try {- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-duplicate',- });- return;- }- if (!validateSkillName(body.name, res, 'skill-duplicate')) return;- if (!validateSkillName(body.toName, res, 'skill-duplicate')) return;- if (rejectReservedBuiltinSkill(body.toName, res, 'skill-duplicate')) return;-- const sourceDir = resolveSkillDirForRead(body.scope, body.name);- if (sourceDir === null || !existsSync(join(sourceDir, 'SKILL.md'))) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {- handler: 'skill-duplicate',- detail: 'SOURCE_NOT_FOUND',- });- return;- }- const base = body.scope === 'project' ? contentDir : skillsHome;- const targetHomeRel = resolveDefaultSkillHomeRel(base, body.scope);- if (targetHomeRel === null) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'No agent skill host is available.',- { handler: 'skill-duplicate', detail: 'NO_USABLE_SKILL_HOME' },- );- return;- }- const targetRoot = resolve(base, targetHomeRel);- const targetDir = resolve(targetRoot, body.toName);- if (resolveSkillDirForRead(body.scope, body.toName) !== null || existsSync(targetDir)) {- errorResponse(- res,- 409,- 'urn:ok:error:doc-already-exists',- `A ${body.scope} skill named "${body.toName}" already exists.`,- { handler: 'skill-duplicate' },- );- return;- }-- const source = parseSkillDir(sourceDir);- if (!source) {- errorResponse(res, 422, 'urn:ok:error:invalid-request', 'Source has no readable skill.', {- handler: 'skill-duplicate',- });- return;- }- tracedMkdirSync(targetRoot, { recursive: true });- tracedCpSync(sourceDir, targetDir, { recursive: true, dereference: true });- const { fenced, body: sourceBody } = detectFmRegion(source.skillMd);- // presence-exempt: no CRDT write, no agent identity- const renamed = applyPatchToFm(fenced, { name: body.toName });- if (!renamed.ok) {- applySkillDelete({ skillsRoot: targetRoot, name: body.toName });- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Failed to write duplicated skill.',- {- handler: 'skill-duplicate',- detail: renamed.error.kind,- },- );- return;- }- try {- tracedWriteFileSync(join(targetDir, 'SKILL.md'), `${renamed.nextFenced}${sourceBody}`);- } catch (error) {- applySkillDelete({ skillsRoot: targetRoot, name: body.toName });- throw error;- }-- if (body.scope === 'project') {- const targetRel = relative(contentDir, targetDir).split(sep).join('/');- attributeOkArtifactWrite(- actor,- okArtifactKey('skill', '', body.toName),- `skill-duplicate: ${body.name} -> ${targetRel}`,- );- void commitOkArtifactWrite('skill-duplicate');- }- signalChannel?.('files');- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();-- successResponse(- res,- 200,- SkillDuplicateSuccessSchema,- { name: body.toName },- { handler: 'skill-duplicate' },- );- } catch (e) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to duplicate skill.',- { handler: 'skill-duplicate', cause: e },- );- }- },- { handler: 'skill-duplicate', method: 'POST' },- );-- const handleSkill = methodRouter(- { GET: handleSkillGet, PUT: handleSkillPut, POST: handleSkillMove, DELETE: handleSkillDelete },- { handler: 'skill' },- );-- function classifySkillFilePath(rel: string): 'reference' | 'script' | 'file' | null {- if (rel.includes('\x00')) return null;- const segments = rel- .replace(/\\/g, '/')- .split('/')- .filter((s) => s !== '' && s !== '.');- if (segments.length < 1 || segments.some((s) => s === '..')) return null;- if (segments.length === 1 && (segments[0] as string).toLowerCase() === 'skill.md') return null;- if (segments[0] === 'references' && segments.length >= 2) return 'reference';- if (segments[0] === 'scripts' && segments.length >= 2) return 'script';- return 'file';- }-- function isProjectMdReference(- scope: 'project' | 'global',- kind: 'reference' | 'script' | 'file',- rel: string,- ): boolean {- return scope === 'project' && kind === 'reference' && rel.toLowerCase().endsWith('.md');- }-- function nestedProjectRefDocNames(realDir: string, dirRel: string): string[] {- const base = resolve(realDir, dirRel);- const dirDocPrefix = relative(contentDir, realDir).split(sep).join('/');- let entries: string[];- try {- entries = readdirSync(base, { recursive: true, encoding: 'utf-8' });- } catch {- return [];- }- return entries- .filter((e) => /\.md$/i.test(e))- .map((e) => `${dirDocPrefix}/${dirRel}/${e.split(sep).join('/').replace(/\.md$/i, '')}`);- }-- function projectRefContentDocName(name: string, rel: string): string {- const extLess = rel.replace(/\.md$/i, '');- return `${projectSkillContentDocName(name).replace(/\/SKILL$/, '')}/${extLess}`;- }-- function listProjectMdReferences(skillsRoot: string, name: string): string[] {- const refsDir = resolve(skillsRoot, name, 'references');- if (!existsSync(refsDir)) return [];- const out: string[] = [];- const walk = (dir: string, prefix: string): void => {- for (const entry of readdirSync(dir, { withFileTypes: true })) {- const rel = prefix ? `${prefix}/${entry.name}` : entry.name;- if (entry.isDirectory()) walk(resolve(dir, entry.name), rel);- else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) {- out.push(`references/${rel}`);- }- }- };- walk(refsDir, '');- return out;- }-- async function reindexMovedProjectSkillDocs(- skillsRoot: string,- fromName: string,- toName: string,- ): Promise<void> {- if (!derivedDocumentIndex) {- getLogger('skill-move').warn(- { fromName, toName },- 'no derived-document index available — skipping re-index of the moved skill (its old entries will be dropped with no replacement)',- );- return;- }- const derivedMutations: DerivedDocumentIndexMutation[] = [];- const collectReindex = (oldDocName: string, newDocName: string, absFile: string): void => {- let markdown: string;- try {- markdown = readFileSync(absFile, 'utf-8');- } catch (err) {- getLogger('skill-move').warn(- { err, absFile, oldDocName, newDocName },- 'relocated skill file unreadable after move — dropping the old index entry with no replacement',- );- derivedMutations.push({ kind: 'delete', documentName: oldDocName });- return;- }- derivedMutations.push({- kind: 'rename',- oldDocumentName: oldDocName,- newDocumentName: newDocName,- markdown,- });- };-- const rootRel = relative(contentDir, skillsRoot).split(sep).join('/');- const docFor = (n: string, rel?: string): string =>- `${rootRel}/${n}/${rel ? rel.replace(/\.mdx?$/i, '') : 'SKILL'}`;- collectReindex(docFor(fromName), docFor(toName), resolve(skillsRoot, toName, 'SKILL.md'));- for (const rel of listProjectMdReferences(skillsRoot, toName)) {- collectReindex(docFor(fromName, rel), docFor(toName, rel), resolve(skillsRoot, toName, rel));- }- await derivedDocumentIndex.recordDirectMutations(derivedMutations);- }-- async function reindexRewrittenSkillRefDocs(- rewrites: readonly SkillRefRewrite[],- movedName: string,- ): Promise<void> {- if (!derivedDocumentIndex || rewrites.length === 0) return;- const mutations: DerivedDocumentIndexMutation[] = [];- for (const rw of rewrites) {- if (rw.dir.split('/').pop() === movedName) continue;- mutations.push({- kind: 'link-rewrite',- documentName: `${rw.dir}/${rw.rel.replace(/\.mdx?$/i, '')}`,- markdown: rw.markdown,- });- }- if (mutations.length > 0) await derivedDocumentIndex.recordDirectMutations(mutations);- }-- const handleSkillFileGet = withValidation(- EmptyRequestSchema,- async (req, res) => {- try {- const url = new URL(req.url ?? '', 'http://localhost');- const name = url.searchParams.get('name') ?? '';- if (!validateSkillName(name, res, 'skill-file-get')) return;- const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-file-get');- if (scope === null) return;- const rel = url.searchParams.get('path') ?? '';- const builtinBase = isInternalBundleSkillName(name)- ? scope === 'global'- ? skillsHome- : projectDir- : undefined;- const builtinHost = url.searchParams.get('host') ?? undefined;- const builtin = builtinBase- ? resolveBuiltinSkillDir(builtinBase, name, scope, builtinHost)- : null;- if (rel === '' || rel.includes('\x00')) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid skill file path.', {- handler: 'skill-file-get',- });- return;- }- const kind =- (builtin && rel === 'SKILL.md' ? 'reference' : classifySkillFilePath(rel)) ?? 'reference';- const host = builtinHost;- const resolvedSkillDir = builtinBase- ? (builtin?.dir ?? null)- : resolveSkillDirForRead(scope, name, host);- if (resolvedSkillDir === null && host !== undefined) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {- handler: 'skill-file-get',- detail: `No skill "${name}" (${scope}) in ${host}.`,- });- return;- }- const skillDir = resolvedSkillDir ?? resolve(resolveSkillsRoot(scope), name);- const abs = resolve(skillDir, rel);- if (abs !== skillDir && !abs.startsWith(`${skillDir}${sep}`)) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Skill file path escapes the skill dir.',- {- handler: 'skill-file-get',- },- );- return;- }- let resolvedAbs = abs;- let resolvedRel = rel;- if (!existsSync(resolvedAbs)) {- const docStem = rel.match(/^(.*)\.(?:md|mdx)$/);- const sibling = docStem- ? SUPPORTED_DOC_EXTENSIONS.map((ext) => `${docStem[1]}${ext}`).find(- (candidate) => candidate !== rel && existsSync(resolve(skillDir, candidate)),- )- : undefined;- if (sibling === undefined) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill file not found.', {- handler: 'skill-file-get',- detail: `${rel} not found in skill "${name}" (${scope}).`,- });- return;- }- resolvedRel = sibling;- resolvedAbs = resolve(skillDir, sibling);- }- const buf = await readFile(resolvedAbs);- if (buf.includes(0)) {- errorResponse(- res,- 415,- 'urn:ok:error:invalid-request',- 'Skill file is binary — only text bundle files are readable via MCP.',- { handler: 'skill-file-get' },- );- return;- }- successResponse(- res,- 200,- SkillFileGetSuccessSchema,- { path: resolvedRel.replace(/\\/g, '/'), kind, text: buf.toString('utf-8') },- { handler: 'skill-file-get' },- );- } catch (e) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to read skill file.',- {- handler: 'skill-file-get',- cause: e,- },- );- }- },- { handler: 'skill-file-get', method: 'GET', skipBodyParse: true },- );-- const handleSkillFilePut = withValidation(- SkillFilePutRequestSchema,- async (_req, res, body) => {- try {- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-file-put',- });- return;- }- if (!validateSkillName(body.name, res, 'skill-file-put')) return;- if (rejectReservedBuiltinSkill(body.name, res, 'skill-file-put')) return;- const kind = classifySkillFilePath(body.path);- if (kind === null) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Invalid skill file path (must name a file inside the skill dir, no `..`).',- { handler: 'skill-file-put' },- );- return;- }- if (Buffer.byteLength(body.content, 'utf-8') > BUNDLE_FILE_MAX_BYTES) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Skill file exceeds the 256 KB per-file cap.',- { handler: 'skill-file-put' },- );- return;- }- const skillDirAbs = resolveSkillDirForRead(body.scope, body.name);- if (skillDirAbs === null || !existsSync(join(skillDirAbs, 'SKILL.md'))) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {- handler: 'skill-file-put',- detail: `Create skill "${body.name}" before adding bundle files.`,- });- return;- }- const fileBase = body.scope === 'project' ? contentDir : skillsHome;- const skillDirRel = relative(fileBase, skillDirAbs).split(sep).join('/');- const rel = body.path.replace(/\\/g, '/');- const routedThroughContent = isProjectMdReference(body.scope, kind, rel);- let created: boolean;-- if (routedThroughContent) {- /**- * A project `.md` reference routes through the sanctioned paired-write primitive- * (precedent #24 / #38), the same branch as the SKILL.md body.- */- const refDocName = `${skillDirRel}/${rel.replace(/\.mdx?$/i, '')}`;- if (checkSkillDocConflictGate(refDocName, 'skill-file-put', res)) return;- created = !existsSync(resolve(skillDirAbs, rel));- if (created && countBundleFiles(skillDirAbs) >= BUNDLE_MAX_FILES) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- `Skill "${body.name}" already holds ${BUNDLE_MAX_FILES} bundle files (the cap) — delete one before adding another.`,- { handler: 'skill-file-put' },- );- return;- }- const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(- body as unknown as Record<string, unknown>,- );- const session = await sessionManager.getSession(refDocName, agentId, {- displayName: agentName,- colorSeed,- clientName,- });- session.dc.document.transact(() => {- composeAndWriteRawBody(session.dc.document, body.content, 'agent');- }, session.origin);- const flushOutcome = await flushDiskAndDetectOutcome(refDocName);- if (flushOutcome?.kind === 'failure') {- respondPersistenceFailure(res, flushOutcome.failure, 'skill-file-put');- return;- }- if (flushOutcome?.kind === 'divergence') {- respondDiskDivergence(res, 'skill-file-put');- return;- }- if (flushOutcome?.kind === 'stale-external-write') {- respondStaleExternalWrite(res, 'skill-file-put', refDocName);- return;- }- } else {- const fsResult = applySkillBundleFileWrite({- skillsRoot: dirname(skillDirAbs),- name: body.name,- relPath: rel,- content: body.content,- });- if (!fsResult.ok) {- const status =- fsResult.error.code === 'WRITE_ERROR'- ? 500- : fsResult.error.code === 'SKILL_NOT_FOUND'- ? 404- : 400;- errorResponse(- res,- status,- status === 500- ? 'urn:ok:error:internal-server-error'- : status === 404- ? 'urn:ok:error:not-found'- : 'urn:ok:error:invalid-request',- status === 500 ? 'Failed to write skill file.' : 'Invalid skill file request.',- {- handler: 'skill-file-put',- detail: fsResult.error.code,- cause: new Error(fsResult.error.message),- },- );- return;- }- created = fsResult.created;- }-- if (body.scope === 'project') {- attributeOkArtifactWrite(- actor,- okArtifactKey('skill', '', body.name),- `${created ? 'skill-file-create' : 'skill-file-edit'}: ${skillDirRel}/${rel}`,- );- void commitOkArtifactWrite('skill-file-put');- }- signalChannel?.('files');- successResponse(- res,- 200,- SkillFilePutSuccessSchema,- { path: rel, created, kind, content: routedThroughContent },- { handler: 'skill-file-put' },- );- } catch (e) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to write skill file.',- {- handler: 'skill-file-put',- cause: e,- },- );- }- },- { handler: 'skill-file-put', method: 'PUT' },- );-- const handleSkillFileDelete = withValidation(- EmptyRequestSchema,- async (req, res) => {- try {- const url = new URL(req.url ?? '', 'http://localhost');- const sp = url.searchParams;- const name = sp.get('name') ?? '';- if (!validateSkillName(name, res, 'skill-file-delete')) return;- if (rejectReservedBuiltinSkill(name, res, 'skill-file-delete')) return;- const scope = parseSkillScope(sp.get('scope'), res, 'skill-file-delete');- if (scope === null) return;- const rel = (sp.get('path') ?? '').replace(/\\/g, '/');- const kind = classifySkillFilePath(rel);- if (kind === null) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Invalid skill file path (must name a file inside the skill dir).',- { handler: 'skill-file-delete' },- );- return;- }- const actor = extractActorIdentityFromQuery(url, getPrincipal);- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-file-delete',- });- return;- }- const realDir = resolveSkillDirForRead(scope, name);- const skillsRoot = realDir !== null ? dirname(realDir) : resolveSkillsRoot(scope);-- const bundleAbs = resolve(realDir ?? join(skillsRoot, name), rel);- if (existsSync(bundleAbs) && isProjectMdReference(scope, kind, rel)) {- const extLess = rel.replace(/\.md$/i, '');- const refDoc =- realDir !== null- ? `${relative(contentDir, realDir).split(sep).join('/')}/${extLess}`- : projectRefContentDocName(name, rel);- await captureAndCloseDocuments([refDoc], 'deleted-upstream');- } else if (- scope === 'project' &&- realDir !== null &&- existsSync(bundleAbs) &&- statSync(bundleAbs).isDirectory()- ) {- const docs = nestedProjectRefDocNames(realDir, rel);- if (docs.length > 0) await captureAndCloseDocuments(docs, 'deleted-upstream');- }-- const result = applySkillBundleFileDelete({ skillsRoot, name, relPath: rel });- if (!result.ok) {- const status = result.error.code === 'UNLINK_FAILED' ? 500 : 400;- errorResponse(- res,- status,- status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',- status === 500 ? 'Failed to delete skill file.' : 'Invalid skill file request.',- {- handler: 'skill-file-delete',- detail: result.error.code,- cause: new Error(result.error.message),- },- );- return;- }- if (result.existed && scope === 'project') {- attributeOkArtifactWrite(- actor,- okArtifactKey('skill', '', name),- `skill-file-delete: ${- realDir !== null- ? `${relative(contentDir, realDir).split(sep).join('/')}/${rel}`- : `${name}/${rel}`- }`,- );- void commitOkArtifactWrite('skill-file-delete');- }- if (result.existed) signalChannel?.('files');- successResponse(- res,- 200,- SkillFileDeleteSuccessSchema,- { path: rel, existed: result.existed, kind },- { handler: 'skill-file-delete' },- );- } catch (e) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to delete skill file.',- {- handler: 'skill-file-delete',- cause: e,- },- );- }- },- { handler: 'skill-file-delete', method: 'DELETE', skipBodyParse: true },- );-- const handleSkillFile = methodRouter(- { GET: handleSkillFileGet, PUT: handleSkillFilePut, DELETE: handleSkillFileDelete },- { handler: 'skill-file' },- );- const handleSkillFileRename = withValidation(- SkillFileRenameRequestSchema,- async (_req, res, body) => {- try {- if (!validateSkillName(body.name, res, 'skill-file-rename')) return;- if (rejectReservedBuiltinSkill(body.name, res, 'skill-file-rename')) return;- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-file-rename',- });- return;- }- const from = body.from.replace(/\\/g, '/');- const to = body.to.replace(/\\/g, '/');- const fromKind = classifySkillFilePath(from);- const toKind = classifySkillFilePath(to);- if (fromKind === null || toKind === null) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Both paths must stay inside the skill dir.',- { handler: 'skill-file-rename', detail: fromKind === null ? from : to },- );- return;- }- const realDir = resolveSkillDirForRead(body.scope, body.name);- if (realDir === null) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {- handler: 'skill-file-rename',- });- return;- }- const skillsRoot = dirname(realDir);-- const fromIsDoc = isProjectMdReference(body.scope, fromKind, from);- const toIsDoc = isProjectMdReference(body.scope, toKind, to);- const dirRel = relative(contentDir, realDir).split(sep).join('/');- const fromDocName = fromIsDoc ? `${dirRel}/${from.replace(/\.md$/i, '')}` : null;- const toDocName = toIsDoc ? `${dirRel}/${to.replace(/\.md$/i, '')}` : null;-- if (- fromDocName !== null &&- checkSkillDocConflictGate(fromDocName, 'skill-file-rename', res)- )- return;- if (fromDocName !== null) {- await captureAndCloseDocuments([fromDocName], 'deleted-upstream');- } else if (body.scope === 'project') {- const fromAbs = resolve(realDir, from);- if (existsSync(fromAbs) && statSync(fromAbs).isDirectory()) {- const docs = nestedProjectRefDocNames(realDir, from);- if (docs.length > 0) await captureAndCloseDocuments(docs, 'deleted-upstream');- }- }-- const result = applySkillBundleFileRename({- skillsRoot,- name: body.name,- relPath: from,- toRelPath: to,- });- if (!result.ok) {- const status = result.error.code === 'RENAME_FAILED' ? 500 : 400;- errorResponse(- res,- status,- status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',- result.error.message,- { handler: 'skill-file-rename', detail: result.error.code },- );- return;- }-- if (derivedDocumentIndex) {- const mutations: DerivedDocumentIndexMutation[] = [];- if (fromDocName !== null && toDocName !== null) {- try {- mutations.push({- kind: 'rename',- oldDocumentName: fromDocName,- newDocumentName: toDocName,- markdown: readFileSync(resolve(skillsRoot, body.name, to), 'utf-8'),- });- } catch {- mutations.push({ kind: 'delete', documentName: fromDocName });- }- } else if (fromDocName !== null) {- mutations.push({ kind: 'delete', documentName: fromDocName });- } else if (toDocName !== null) {- try {- mutations.push({- kind: 'upsert',- documentName: toDocName,- markdown: readFileSync(resolve(skillsRoot, body.name, to), 'utf-8'),- });- } catch {}- }- await recordDerivedMutationsBestEffort(mutations, 'skill-file-rename');- }-- if (body.scope === 'project') {- attributeOkArtifactWrite(- actor,- okArtifactKey('skill', '', body.name),- `skill-file-rename: ${body.name}/${from} -> ${to}`,- );- void commitOkArtifactWrite('skill-file-rename');- }- signalChannel?.('files');- successResponse(- res,- 200,- SkillFileRenameSuccessSchema,- {- from,- to,- ...(fromDocName !== null ? { fromDocName } : {}),- ...(toDocName !== null ? { toDocName } : {}),- },- { handler: 'skill-file-rename' },- );- } catch (err) {- log.error({ err }, '[skill-file-rename] failed');- if (!res.headersSent) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to rename skill file.',- { handler: 'skill-file-rename' },- );- }- }- },- { handler: 'skill-file-rename', method: 'POST' },- );-- function publisherFromSource(source: string): string | undefined {- const m = /github\.com[/:]([\w.-]+)\//.exec(source);- return m ? m[1] : undefined;- }-- const readSkillsLock = readSkillsLockFile;- function localSkillHash(skillsRoot: string, name: string): string | undefined {- return parseSkillDir(resolve(skillsRoot, name))?.contentHash;- }- async function shadowHeadSha(- writerId?: string,- verifyPathRel?: string,- ): Promise<string | undefined> {- const shadow = shadowRef?.current;- if (!shadow || !writerId) return undefined;- /**- * The shadow repo has no `HEAD`/`main`: writes land on per-writer WIP refs- * (`refs/wip/<branch>/<writerId>`, precedent #25), so capture the actor's WIP ref rather- * than `rev-parse HEAD`.- */- try {- const sg = shadowGit(shadow);- const readMine = async (): Promise<string | undefined> => {- const refs = (await sg.raw('for-each-ref', '--format=%(refname)', 'refs/wip/'))- .trim()- .split('\n')- .filter(Boolean);- const mine = refs.find((r) => r.endsWith(`/${writerId}`));- if (!mine) return undefined;- return (await sg.raw('rev-parse', mine)).trim();- };- const treeHas = async (sha: string, rel: string): Promise<boolean> => {- const out = await sg.raw('ls-tree', '-r', '--name-only', sha, '--', rel);- return out.trim().length > 0;- };- let sha = await readMine();- if (- sha !== undefined &&- verifyPathRel !== undefined &&- !(await treeHas(sha, verifyPathRel))- ) {- await commitOkArtifactWrite('baseline-verify');- sha = await readMine();- if (sha !== undefined && !(await treeHas(sha, verifyPathRel))) return undefined;- }- return sha;- } catch {- return undefined;- }- }- const artifactWriterId = (actor: ReturnType<typeof extractActorIdentity>): string | undefined =>- actor.kind === 'agent' || actor.kind === 'principal' ? actor.writerId : undefined;- async function projectImportedSkillCopy(args: {- skillsRoot: string;- name: string;- scope: 'project' | 'global';- hasScripts: boolean;- handler: string;- }): Promise<void> {- try {- const installBase = skillInstallBase(args.scope);- if (!installBase) return;- const targets = resolveSkillTargets(installBase);- if (targets.length === 0) return;- const hosts = projectSkill(- resolve(args.skillsRoot, args.name),- args.name,- installBase,- targets,- 'copy',- skillProjectionRoots(args.scope),- );- if (hosts.length === 0) return;- await recordSkillInstall(installBase, args.name, {- hosts,- scope: args.scope,- scripts: args.hasScripts,- installedAt: new Date().toISOString(),- projection: 'copy',- });- } catch (projectErr) {- log.warn(- { skill: args.name, err: projectErr },- `${args.handler}: inline projection failed; skill written, reconcile will project on next open`,- );- }- }-- function respondSkillImport(res: ServerResponse, outcome: SkillImportOutcome): void {- if (outcome.ok) {- successResponse(res, 200, SkillImportSuccessSchema, outcome.body, {- handler: 'skill-import',- });- return;- }- errorResponse(res, outcome.status, outcome.urn, outcome.title, {- handler: 'skill-import',- ...(outcome.detail !== undefined ? { detail: outcome.detail } : {}),- ...(outcome.cause !== undefined ? { cause: outcome.cause } : {}),- });- }-- const skillImportService = createSkillImportService({- contentDir,- skillsHome,- ...(projectDir !== undefined ? { projectDir } : {}),- resolveSkillDirForRead,- parseFrontmatterDoc,- attributeOkArtifactWrite,- commitOkArtifactWrite,- shadowHeadSha,- artifactWriterId,- effectiveInstallMode,- signalFiles: () => signalChannel?.('files'),- });-- const skillReimportService = createSkillReimportService({- contentDir,- skillsHome,- ...(projectDir !== undefined ? { projectDir } : {}),- legacyStoreRoot: LEGACY_SKILL_STORE_ROOT,- effectiveSkillRoot,- parseFrontmatterDoc,- attributeOkArtifactWrite,- commitOkArtifactWrite,- shadowHeadSha,- artifactWriterId,- skillArtifactKey: (name) => okArtifactKey('skill', '', name),- captureAndCloseDocuments,- projectImportedSkillCopy,- signalFiles: () => signalChannel?.('files'),- });-- function respondSkillReimport(res: ServerResponse, outcome: SkillReimportOutcome): void {- if (outcome.ok) {- successResponse(res, 200, SkillReimportSuccessSchema, outcome.body, {- handler: 'skill-reimport',- });- return;- }- errorResponse(res, outcome.status, outcome.urn, outcome.title, {- handler: 'skill-reimport',- ...(outcome.detail !== undefined ? { detail: outcome.detail } : {}),- ...(outcome.cause !== undefined ? { cause: outcome.cause } : {}),- });- }-- function packBundleDir(scope: 'project' | 'global', name: string, skillsRoot: string): string {- const base = scope === 'project' ? contentDir : skillsHome;- const found = (- scope === 'project' ? scanInPlaceSkills(contentDir) : scanGlobalInPlaceSkills(skillsHome)- ).find((s) => s.name === name);- return found ? resolve(base, found.dir) : resolve(skillsRoot, name);- }-- function resolveReimportLockEntry(- scope: 'project' | 'global',- name: string,- skillsRoot: string,- lock: SkillsLock,- ): SkillsLock['skills'][string] | null {- const recorded = lock.skills[name];- if (recorded) return recorded;- const bundleDir = packBundleDir(scope, name, skillsRoot);- return (- retrofitPackLockEntry(- name,- parseSkillDir(bundleDir)?.contentHash ?? '',- new Date().toISOString(),- { selfIdentifiesAsPack: bundleSelfIdentifiesAsPack(bundleDir) },- ) ??- synthBuiltinLockEntry(scope === 'global' ? skillsHome : contentDir, name, scope) ??- synthPluginLockEntry(name, resolveProjectIdentity(projectDir ?? contentDir), bundleDir)- );- }- const handleSkillImport = withValidation(- SkillImportRequestSchema,- async (_req, res, body) => {- let cleanup: () => void = () => {};- try {- if (!projectDir) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {- handler: 'skill-import',- detail: 'NO_PROJECT_ROOT',- });- return;- }- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-import',- });- return;- }- const scope = body.scope;-- let acquiredDir: string | null = null;- let sourceLabel: string;- let ref: string | undefined;- let publisher: string | undefined;- let upstreamSkill: string | undefined;- let resolvedSourceForReport = body.source;-- {- const rawSource = body.source;- try {- const skillsSh = await resolveSkillsShImportSource(rawSource, body.skill);- const resolvedSource = skillsSh?.source ?? rawSource;- resolvedSourceForReport = resolvedSource;- const selectedSkill = body.skill ?? skillsSh?.skill;- const spec = skillsSh?.spec ?? parseSource(resolvedSource);- if (!spec) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Unrecognized import source.',- {- handler: 'skill-import',- detail:- 'Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.',- },- );- return;- }- if (rejectDisallowedGitSpec(res, spec, 'skill-import')) return;- const fetched = await fetchSource(spec);- cleanup = fetched.cleanup;- ref = fetched.ref;- const dirs = discoverSkillDirs(fetched.dir);- if (dirs.length === 0) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in source.', {- handler: 'skill-import',- });- return;- }- let pick = dirs[0];- if (selectedSkill) {- const found =- dirs.find((d) => d.name === selectedSkill) ??- dirs.find((d) => readSkillDirMeta(d.dir)?.name === selectedSkill) ??- dirs.find((d) => d.name === RENAMED_PACK_SKILLS[selectedSkill]);- if (!found) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Named skill not in source.', {- handler: 'skill-import',- detail: `--skill "${selectedSkill}" not among: ${dirs.map((d) => d.name).join(', ')}.`,- });- return;- }- pick = found;- } else if (dirs.length > 1) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Source has multiple skills; pass `skill` to choose one.',- { handler: 'skill-import', detail: dirs.map((d) => d.name).join(', ') },- );- return;- }- acquiredDir = pick.dir;- upstreamSkill = pick.name;- sourceLabel = rawSource;- publisher = skillsSh?.publisher ?? publisherFromSource(resolvedSource);- } catch (e) {- if (e instanceof SkillFetchError) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {- handler: 'skill-import',- cause: e,- });- return;- }- throw e;- }- }-- if (!acquiredDir) {- errorResponse(res, 422, 'urn:ok:error:invalid-request', 'Source has no readable skill.', {- handler: 'skill-import',- });- return;- }- const outcome = await skillImportService.runSkillImport({- acquiredDir,- scope,- sourceLabel,- ref,- publisher,- upstreamSkill,- actor,- skipProjection: body.install === false,- });- if (- outcome.ok &&- (body.marketplace === true || isOpenKnowledgeSkillsSource(resolvedSourceForReport))- ) {- void reportSkillInstall(- { source: resolvedSourceForReport, skills: [outcome.body.name] },- resolveSkillInstallReportSettings(),- );- }- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();- signalChannel?.('files');-- respondSkillImport(res, outcome);- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to import skill.', {- handler: 'skill-import',- cause: e,- });- } finally {- cleanup();- }- },- { handler: 'skill-import', method: 'POST' },- );-- const handleSkillsImportBulk = withValidation(- SkillsImportBulkRequestSchema,- async (_req, res, body) => {- let cleanup: () => void = () => {};- try {- if (!projectDir) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {- handler: 'skills-import-bulk',- detail: 'NO_PROJECT_ROOT',- });- return;- }- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skills-import-bulk',- });- return;- }- const rawSource = body.source;- let siteSpec: (SourceSpec & { kind: 'well-known' }) | null = null;- let siteIndex: WellKnownIndex | null = null;- let dirs: ReturnType<typeof discoverSkillDirs> = [];- let ref: string | undefined;- let publisher: string | undefined;- let resolvedSourceForReport = rawSource;- try {- const skillsSh = await resolveSkillsShImportSource(rawSource, body.skills[0]);- const resolvedSource = skillsSh?.source ?? rawSource;- resolvedSourceForReport = resolvedSource;- const spec = skillsSh?.spec ?? parseSource(resolvedSource);- if (!spec) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized import source.', {- handler: 'skills-import-bulk',- detail:- 'Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.',- });- return;- }- if (rejectDisallowedGitSpec(res, spec, 'skills-import-bulk')) return;- publisher = skillsSh?.publisher ?? publisherFromSource(resolvedSource);- if (spec.kind === 'well-known') {- siteSpec = spec;- siteIndex = await readWellKnownIndex(spec.origin);- } else {- const fetched = await fetchSource(spec);- cleanup = fetched.cleanup;- ref = fetched.ref;- dirs = discoverSkillDirs(fetched.dir);- }- } catch (e) {- if (e instanceof SkillFetchError) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {- handler: 'skills-import-bulk',- cause: e,- });- return;- }- throw e;- }- if (siteSpec === null && dirs.length === 0) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in source.', {- handler: 'skills-import-bulk',- });- return;- }- const results: SkillImportBulkResult[] = [];- for (const requested of new Set(body.skills)) {- let acquiredDir: string;- let upstreamSkill: string;- let perSkill: () => void = () => {};- if (siteSpec !== null) {- try {- const one = await fetchSource(- { ...siteSpec, skill: requested },- siteIndex ? { index: siteIndex } : {},- );- acquiredDir = one.dir;- perSkill = one.cleanup;- upstreamSkill = requested;- } catch (e) {- results.push({- requested,- status: e instanceof SkillFetchError ? 'not-found' : 'failed',- warnings: [],- ...(e instanceof SkillFetchError ? {} : { error: String(e) }),- });- continue;- }- } else {- const found =- dirs.find((d) => d.name === requested) ??- dirs.find((d) => parseSkillDir(d.dir)?.name === requested) ??- dirs.find((d) => d.name === RENAMED_PACK_SKILLS[requested]);- if (!found) {- results.push({ requested, status: 'not-found', warnings: [] });- continue;- }- acquiredDir = found.dir;- upstreamSkill = found.name;- }- try {- const outcome = await skillImportService.runSkillImport({- acquiredDir,- scope: body.scope,- sourceLabel: rawSource,- ref,- publisher,- upstreamSkill,- actor,- skipProjection: body.install === false,- });- if (!outcome.ok) {- getLogger('skills-import-bulk').warn(- { skill: requested, err: outcome.cause, detail: outcome.detail },- 'bulk import: one skill failed (rest continue)',- );- results.push({- requested,- status: 'failed',- warnings: [],- error: outcome.detail ?? outcome.title,- });- continue;- }- results.push({- requested,- status: outcome.body.alreadyImported ? 'already-imported' : 'imported',- name: outcome.body.name,- ...(outcome.body.collisionRenamedFrom !== undefined- ? { collisionRenamedFrom: outcome.body.collisionRenamedFrom }- : {}),- warnings: outcome.body.warnings,- });- } catch (e) {- getLogger('skills-import-bulk').warn(- { skill: requested, err: e },- 'bulk import: one skill threw (rest continue)',- );- results.push({- requested,- status: 'failed',- warnings: [],- error: e instanceof Error ? e.message : String(e),- });- } finally {- perSkill();- }- }- if (body.marketplace === true || isOpenKnowledgeSkillsSource(resolvedSourceForReport)) {- const importedNames = results- .filter((r) => r.status === 'imported')- .map((r) => r.requested);- if (importedNames.length > 0) {- void reportSkillInstall(- { source: resolvedSourceForReport, skills: importedNames },- resolveSkillInstallReportSettings(),- );- }- }- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();- signalChannel?.('files');-- successResponse(- res,- 200,- SkillsImportBulkSuccessSchema,- {- results,- imported: results.filter((r) => r.status === 'imported').length,- alreadyImported: results.filter((r) => r.status === 'already-imported').length,- failed: results.filter((r) => r.status === 'failed' || r.status === 'not-found').length,- },- { handler: 'skills-import-bulk' },- );- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to import skills.', {- handler: 'skills-import-bulk',- cause: e,- });- } finally {- cleanup();- }- },- { handler: 'skills-import-bulk', method: 'POST' },- );-- const UPLOAD_MAX_FILES = 200;- const UPLOAD_MAX_ENTRY_BYTES = 8 * 1024 * 1024;- const UPLOAD_MAX_TOTAL_BYTES = 32 * 1024 * 1024;-- function resolveUploadPath(root: string, rel: string): string | null {- const norm = rel.split('\\').join('/').replace(/^\/+/, '');- if (norm === '' || norm.split('/').some((seg) => seg === '..')) return null;- const abs = resolve(root, norm);- if (abs !== root && !abs.startsWith(root + sep)) return null;- return abs;- }-- interface UploadedPart {- relPath: string;- data: Buffer;- }-- function readSkillUploadParts(req: IncomingMessage): Promise<UploadedPart[]> {- return new Promise((resolveP, reject) => {- let bb: MultipartParser;- try {- bb = createMultipartParser(req, {- files: UPLOAD_MAX_FILES,- fields: 10,- fieldSize: 2 * 1024,- fileSize: UPLOAD_MAX_ENTRY_BYTES,- });- } catch (err) {- reject(err);- return;- }- const parts: UploadedPart[] = [];- let total = 0;- let aborted: Error | null = null;- const abort = (err: Error) => {- if (aborted) return;- aborted = err;- req.unpipe(bb);- req.destroy();- bb.destroy();- reject(err);- };- bb.on('file', (_field, stream, info) => {- const chunks: Buffer[] = [];- let truncated = false;- stream.on('data', (c: Buffer) => {- if (aborted) return;- total += c.length;- if (total > UPLOAD_MAX_TOTAL_BYTES) {- abort(new Error('Upload too large.'));- return;- }- chunks.push(c);- });- stream.on('limit', () => {- truncated = true;- });- stream.on('end', () => {- if (aborted) return;- if (truncated) {- aborted = new Error(`File "${info.filename}" exceeds the per-file size limit.`);- return;- }- parts.push({ relPath: info.filename || 'file', data: Buffer.concat(chunks) });- });- });- bb.on('error', reject);- bb.on('close', () => (aborted ? reject(aborted) : resolveP(parts)));- req.pipe(bb);- });- }-- function unzipBufferToDir(buffer: Buffer, destDir: string): Promise<void> {- return new Promise((resolveP, reject) => {- yauzlFromBuffer(buffer, { lazyEntries: true }, (err, zip?: ZipFile) => {- if (err || !zip) {- reject(err ?? new Error('Unreadable archive.'));- return;- }- let total = 0;- let entries = 0;- const fail = (e: unknown) => {- try {- zip.close();- } catch {}- reject(e instanceof Error ? e : new Error(String(e)));- };- zip.on('entry', (entry: Entry) => {- if (++entries > UPLOAD_MAX_FILES) {- fail(new Error('Archive has too many entries.'));- return;- }- const abs = resolveUploadPath(destDir, entry.fileName);- if (!abs) {- fail(new Error(`Unsafe archive entry: ${entry.fileName}`));- return;- }- if (entry.fileName.endsWith('/')) {- tracedMkdirSync(abs, { recursive: true });- zip.readEntry();- return;- }- if (entry.uncompressedSize > UPLOAD_MAX_ENTRY_BYTES) {- fail(new Error(`Archive entry too large: ${entry.fileName}`));- return;- }- zip.openReadStream(entry, (e2, rs) => {- if (e2 || !rs) {- fail(e2 ?? new Error('Could not read archive entry.'));- return;- }- const chunks: Buffer[] = [];- rs.on('data', (c: Buffer) => {- total += c.length;- if (total > UPLOAD_MAX_TOTAL_BYTES) {- rs.destroy();- fail(new Error('Archive expands beyond the size limit.'));- return;- }- chunks.push(c);- });- rs.on('error', fail);- rs.on('end', () => {- try {- tracedMkdirSync(dirname(abs), { recursive: true });- tracedWriteFileSync(abs, Buffer.concat(chunks));- } catch (writeErr) {- fail(writeErr instanceof Error ? writeErr : new Error(String(writeErr)));- return;- }- zip.readEntry();- });- });- });- zip.on('end', () => resolveP());- zip.on('error', fail);- zip.readEntry();- });- });- }-- async function handleSkillUpload(req: IncomingMessage, res: ServerResponse): Promise<void> {- const tmp = mkdtempSync(join(tmpdir(), 'ok-skill-upload-'));- const cleanup = () => {- try {- tracedRmSync(tmp, { recursive: true, force: true });- } catch {}- };- try {- if (!projectDir) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {- handler: 'skill-upload',- detail: 'NO_PROJECT_ROOT',- });- return;- }- if ((req.method ?? '').toUpperCase() !== 'POST') {- errorResponse(res, 405, 'urn:ok:error:invalid-request', 'Use POST to upload a skill.', {- handler: 'skill-upload',- });- return;- }- const url = new URL(req.url ?? '', 'http://localhost');- const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-upload');- if (!scope) return;- const queryField = (key: string): string | undefined =>- url.searchParams.get(key) ?? undefined;- const actor = extractActorIdentity(- {- agentId: queryField('agentId'),- agentName: queryField('agentName'),- colorSeed: queryField('colorSeed'),- clientName: queryField('clientName'),- summary: queryField('summary'),- },- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-upload',- });- return;- }-- let parts: UploadedPart[];- try {- parts = await readSkillUploadParts(req);- } catch (e) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not read the upload.', {- handler: 'skill-upload',- cause: e,- });- return;- }- if (parts.length === 0) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No files uploaded.', {- handler: 'skill-upload',- });- return;- }-- const single = parts.length === 1 ? parts[0] : null;- const zipName = single && /\.(zip|skill)$/i.test(single.relPath) ? single.relPath : null;- if (single && zipName) {- try {- await unzipBufferToDir(single.data, tmp);- } catch (e) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not unpack the archive.', {- handler: 'skill-upload',- cause: e,- });- return;- }- } else {- for (const part of parts) {- const abs = resolveUploadPath(tmp, part.relPath);- if (!abs) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unsafe file path in upload.', {- handler: 'skill-upload',- detail: part.relPath,- });- return;- }- tracedMkdirSync(dirname(abs), { recursive: true });- tracedWriteFileSync(abs, part.data);- }- }-- const dirs = discoverSkillDirs(tmp);- if (dirs.length === 0) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in the upload.', {- handler: 'skill-upload',- });- return;- }- if (dirs.length > 1) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Upload contains multiple skills; upload one at a time.',- { handler: 'skill-upload', detail: dirs.map((d) => d.name).join(', ') },- );- return;- }- const pick = dirs[0];- respondSkillImport(- res,- await skillImportService.runSkillImport({- acquiredDir: pick.dir,- scope,- sourceLabel: `upload:${zipName ?? pick.name}`,- upstreamSkill: pick.name,- actor,- }),- );- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to upload skill.', {- handler: 'skill-upload',- cause: e,- });- } finally {- cleanup();- }- }-- const handleSkillInstall = withValidation(- SkillInstallRequestSchema,- async (_req, res, body) => {- try {- const skillsRoot = resolveSkillsRoot(body.scope);- if (!validateSkillName(body.name, res, 'skill-install')) return;-- if (body.scope === 'project' && !projectDir) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.',- { handler: 'skill-install', detail: 'NO_PROJECT_ROOT' },- );- return;- }- const base = skillInstallBase(body.scope) as string;-- const storeSkillDir = resolve(skillsRoot, body.name);- const inPlaceScanBase = body.scope === 'project' ? contentDir : skillsHome;- const inPlaceEntry = (- body.scope === 'project'- ? scanInPlaceSkills(contentDir)- : scanGlobalInPlaceSkills(skillsHome)- ).find((s) => s.name === body.name);- const bundleSource = isInternalBundleSkillName(body.name)- ? shippedBundleSkillMd(body.name, body.scope)- : null;- const skillDir = inPlaceEntry- ? resolve(inPlaceScanBase, inPlaceEntry.dir)- : existsSync(storeSkillDir) || bundleSource === null- ? storeSkillDir- : dirname(bundleSource);- if (!existsSync(skillDir)) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {- handler: 'skill-install',- detail: `Skill "${body.name}" not found in ${body.scope} scope — create it with write({ skill }) first.`,- });- return;- }-- const liveSkillDoc =- body.scope === 'project'- ? `${relative(inPlaceScanBase, skillDir).split(sep).join('/')}/SKILL`- : skillLiveDocName(body.scope, body.name);- const liveSkillFlush = await flushDiskAndDetectOutcome(liveSkillDoc);- if (liveSkillFlush?.kind === 'stale-external-write') {- respondStaleExternalWrite(res, 'skill-install', liveSkillDoc);- return;- }-- const validity = validateSkillForInstall(skillDir, body.name, {- allowReservedName: isInternalBundleSkillName(body.name),- });- if (!validity.ok) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- `Skill "${body.name}" cannot be installed: ${validity.errors.join(' ')}`,- { handler: 'skill-install', detail: 'INVALID_SKILL_SOURCE' },- );- return;- }-- if (body.fork !== undefined) {- if (!inPlaceEntry) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Skill is not in-place.', {- handler: 'skill-install',- detail: 'FORK_STORE_BACKED',- });- return;- }- const forkResolved = skillInstallOps.resolveFork({- scope: body.scope,- name: body.name,- fork: body.fork,- inPlaceEntry,- });- if (!forkResolved.ok) {- switch (forkResolved.kind) {- case 'unknown-editor':- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unknown editor.', {- handler: 'skill-install',- detail: forkResolved.editor,- });- return;- case 'fork-absent':- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No fork at that editor.', {- handler: 'skill-install',- detail: 'FORK_ABSENT',- });- return;- case 'not-a-fork':- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'That copy matches the source — nothing to resolve.',- { handler: 'skill-install', detail: 'NOT_A_FORK' },- );- return;- case 'invalid-new-name':- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid new name.', {- handler: 'skill-install',- detail: forkResolved.toName,- });- return;- case 'name-taken':- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Name already taken.', {- handler: 'skill-install',- detail: forkResolved.toName,- });- return;- default: {- const _exhaustive: never = forkResolved;- throw new Error(- `Unhandled fork outcome: ${String((_exhaustive as { kind?: unknown }).kind)}`,- );- }- }- }- signalChannel?.('files');- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();- successResponse(- res,- 200,- SkillInstallSuccessSchema,- {- name: body.name,- hosts: inPlaceEntry.hosts.filter(isSkillInstallTarget),- scripts: false,- warnings: forkResolved.warnings,- warningCodes: forkResolved.warnings.length > 0 ? ['skill-fork-name-unpatched'] : [],- },- { handler: 'skill-install' },- );- return;- }-- const setSourceReq = body.setSource ?? body.source;- const linkModeReq =- body.linkMode ?? (body.mode !== undefined ? body.mode === 'link' : undefined);- let targetsReq = body.targets;- const rootAdds: string[] = [];- const rootRemoves: string[] = [];- if (body.add !== undefined || body.remove !== undefined) {- if (!inPlaceEntry) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.',- { handler: 'skill-install', detail: 'STORE_BACKED_ADDITIVE' },- );- return;- }- const addRemove = await skillInstallOps.applyAddRemove({- scope: body.scope,- name: body.name,- inPlaceEntry,- ...(body.add !== undefined ? { add: body.add } : {}),- ...(body.remove !== undefined ? { remove: body.remove } : {}),- });- if (!addRemove.ok) {- if (addRemove.kind === 'remove-source') {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- `"${addRemove.sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,- { handler: 'skill-install', detail: 'REMOVE_SOURCE' },- );- } else {- errorResponse(- res,- 409,- 'urn:ok:error:invalid-request',- `Could not stop ${addRemove.subRoot} following its pool (${addRemove.reason}).`,- { handler: 'skill-install', detail: addRemove.reason },- );- }- return;- }- targetsReq = addRemove.targets.filter(isSkillInstallTarget);- rootAdds.push(...addRemove.rootAdds);- rootRemoves.push(...addRemove.rootRemoves);- }-- if (setSourceReq && !inPlaceEntry) {- const promoted = await skillInstallOps.promoteStoreBackedSource({- scope: body.scope,- name: body.name,- base,- skillDir,- newSource: setSourceReq as SkillHostId,- });- if (!promoted.ok) {- errorResponse(- res,- 409,- 'urn:ok:error:doc-already-exists',- 'Cannot move the source there — a different skill occupies the target.',- {- handler: 'skill-install',- detail: promoted.kind === 'source-occupied' ? promoted.reason : promoted.target,- },- );- return;- }- signalChannel?.('files');- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();- successResponse(- res,- 200,- SkillInstallSuccessSchema,- {- name: body.name,- hosts: promoted.hosts,- scripts: validity.hasScripts,- warnings: [],- warningCodes: [],- sourceMovedTo: promoted.sourceMovedTo,- },- { handler: 'skill-install' },- );- return;- }-- if (body.place) {- const placeBase = body.scope === 'project' ? projectDir : skillsHome;- if (!placeBase) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Cannot place — no project root is resolved for this server.',- { handler: 'skill-install', detail: 'NO_PROJECT_ROOT' },- );- return;- }- const placed = await skillPlacementOps.place({- placeBase,- name: body.name,- rawDir: body.place.dir,- skillDir,- mode: body.place.mode,- });- if (!placed.ok) {- if (placed.kind === 'invalid-path') {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Placement path must be a project-relative directory outside .ok/.',- { handler: 'skill-install', detail: 'PLACE_PATH_INVALID' },- );- } else {- errorResponse(- res,- 409,- 'urn:ok:error:doc-already-exists',- 'Something already exists at that path — placement never overwrites.',- { handler: 'skill-install', detail: 'PLACE_DEST_EXISTS' },- );- }- return;- }- if (!('alreadyAtSource' in placed)) {- signalChannel?.('files');- }- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();- successResponse(- res,- 200,- SkillInstallSuccessSchema,- {- name: body.name,- hosts: inPlaceEntry ? [...inPlaceEntry.hosts] : [],- scripts: validity.hasScripts,- warnings: [],- warningCodes: [],- placedAt: placed.placedAt,- },- { handler: 'skill-install' },- );- return;- }-- if (body.unplace) {- const placeBase = body.scope === 'project' ? projectDir : skillsHome;- if (!placeBase) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Cannot remove a placement — no project root is resolved for this server.',- { handler: 'skill-install', detail: 'NO_PROJECT_ROOT' },- );- return;- }- const unplaced = await skillPlacementOps.unplace({- placeBase,- name: body.name,- rawPath: body.unplace.path,- skillDir,- });- if (!unplaced.ok) {- switch (unplaced.kind) {- case 'not-recorded':- errorResponse(- res,- 404,- 'urn:ok:error:not-found',- 'No recorded placement at that path.',- { handler: 'skill-install', detail: unplaced.path },- );- return;- case 'unsafe-path':- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Recorded placement path is no longer safe.',- { handler: 'skill-install', detail: 'PLACE_PATH_INVALID' },- );- return;- case 'forked':- errorResponse(- res,- 409,- 'urn:ok:error:doc-already-exists',- 'That copy has been edited and no longer matches the skill — remove it manually if you mean it.',- { handler: 'skill-install', detail: unplaced.path },- );- return;- case 'canonical-dir':- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- "That is the skill's own folder (the source) — it can't be removed here.",- { handler: 'skill-install', detail: unplaced.path },- );- return;- default: {- const _exhaustive: never = unplaced;- throw new Error(- `Unhandled unplace outcome: ${String((_exhaustive as { kind?: unknown }).kind)}`,- );- }- }- }- signalChannel?.('files');- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();- successResponse(- res,- 200,- SkillInstallSuccessSchema,- {- name: body.name,- hosts: inPlaceEntry ? [...inPlaceEntry.hosts] : [],- scripts: validity.hasScripts,- warnings: [],- warningCodes: [],- },- { handler: 'skill-install' },- );- return;- }-- if (body.convert) {- if (!inPlaceEntry) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.',- { handler: 'skill-install', detail: 'STORE_BACKED_CONVERT' },- );- return;- }- const { target, mode } = body.convert;- const prefBase = body.scope === 'project' ? projectDir : skillsHome;- const converted = await skillPlacementOps.convert({- ledgerBase: prefBase ?? base,- scope: body.scope,- name: body.name,- target,- mode,- skillDir,- canonicalHash: inPlaceEntry.contentHash,- });- if (!converted.ok) {- switch (converted.kind) {- case 'invalid-location':- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'That location has no skills folder to convert.',- { handler: 'skill-install', detail: target },- );- return;- case 'canonical-dir':- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- "That is the skill's own folder (the source) — move the source instead of converting it.",- { handler: 'skill-install', detail: target },- );- return;- case 'forked':- errorResponse(- res,- 409,- 'urn:ok:error:doc-already-exists',- 'That copy has been edited and no longer matches the skill — resolve the fork before converting it.',- { handler: 'skill-install', detail: target },- );- return;- case 'not-installed':- errorResponse(- res,- 404,- 'urn:ok:error:not-found',- 'The skill is not installed there.',- { handler: 'skill-install', detail: target },- );- return;- default: {- const _exhaustive: never = converted;- throw new Error(- `Unhandled convert outcome: ${String((_exhaustive as { kind?: unknown }).kind)}`,- );- }- }- }- signalChannel?.('files');- successResponse(- res,- 200,- SkillInstallSuccessSchema,- {- name: body.name,- hosts: [...inPlaceEntry.hosts],- scripts: validity.hasScripts,- warnings: [],- warningCodes: [],- },- { handler: 'skill-install' },- );- return;- }-- const targets: EditorId[] =- body.scope === 'global'- ? targetsReq !== undefined- ? USER_SKILL_EDITOR_IDS.filter((id) => targetsReq?.some((t) => t === id))- : detectUserSkillHosts(skillsHome).map((host) => host.editorId)- : targetsReq !== undefined- ? PROJECT_SKILL_EDITOR_IDS.filter((id) => targetsReq?.some((t) => t === id))- : resolveSkillTargets(base);- const warnings: string[] = [];- const warningCodes: SkillInstallWarningCode[] = [];- if (targets.length === 0 && targetsReq === undefined) {- warnings.push(- body.scope === 'global'- ? 'No editor skill folders are configured to install into.'- : 'No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`.',- );- warningCodes.push('no-targets');- }- if (validity.hasScripts) {- warnings.push(- 'This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing.',- );- warningCodes.push('scripts-present');- }- if (validity.warnings.length > 0) {- warnings.push(validity.warnings[0]);- warningCodes.push('no-description');- }-- if (inPlaceEntry) {- const canonicalRootRel = inPlaceEntry.dir.split('/').slice(0, -1).join('/');- const hubTargeted =- targetsReq !== undefined- ? targetsReq.includes('agents')- : body.scope === 'global' && existsSync(join(skillsHome, '.agents'));- const inPlaceTargets: SkillHostId[] = hubTargeted ? [...targets, 'agents'] : [...targets];- const prefBase = body.scope === 'project' ? projectDir : skillsHome;- const installMode: 'copy' | 'link' =- linkModeReq !== undefined- ? linkModeReq- ? 'link'- : 'copy'- : effectiveInstallMode(body.scope, body.name, inPlaceEntry);- if (setSourceReq) {- const promoted = await skillInstallOps.promoteInPlaceSource({- scope: body.scope,- name: body.name,- base,- ...(prefBase ? { prefBase } : {}),- skillDir,- inPlaceEntry,- newSource: setSourceReq,- });- if (!promoted.ok) {- if (promoted.kind === 'invalid-target') {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Source target must be an editor id, "agents", or a project-relative skills root.',- { handler: 'skill-install', detail: promoted.target },- );- } else {- errorResponse(- res,- 409,- 'urn:ok:error:doc-already-exists',- 'Cannot move the source there — a different skill occupies the target.',- { handler: 'skill-install', detail: promoted.reason },- );- }- return;- }- signalChannel?.('files');- successResponse(- res,- 200,- SkillInstallSuccessSchema,- {- name: body.name,- hosts: promoted.hosts,- scripts: validity.hasScripts,- warnings: [],- warningCodes: [],- ...(promoted.sourceMovedTo !== undefined- ? { sourceMovedTo: promoted.sourceMovedTo }- : {}),- },- { handler: 'skill-install' },- );- return;- }-- const fanOut = await skillInstallOps.fanOutInPlace({- scope: body.scope,- name: body.name,- base,- ...(prefBase ? { prefBase } : {}),- skillDir,- inPlaceEntry,- canonicalRootRel,- inPlaceTargets,- setExact: targetsReq !== undefined,- installMode,- ...(linkModeReq !== undefined ? { linkModeReq } : {}),- rootAdds,- rootRemoves,- });- if (!fanOut.ok) {- errorResponse(- res,- 409,- 'urn:ok:error:doc-already-exists',- 'Cannot move the source there — a different skill occupies the target.',- { handler: 'skill-install', detail: fanOut.reason },- );- return;- }- warnings.push(...fanOut.warnings);- warningCodes.push(...fanOut.warningCodes);- signalChannel?.('files');- successResponse(- res,- 200,- SkillInstallSuccessSchema,- {- name: body.name,- hosts: fanOut.hosts,- scripts: validity.hasScripts,- warnings,- warningCodes,- ...(fanOut.sourceMovedTo !== undefined- ? { sourceMovedTo: fanOut.sourceMovedTo }- : {}),- },- { handler: 'skill-install' },- );- return;- }-- const priorHosts = resolvedHosts(- readInstalledSkills(base).skills[body.name]?.hosts ?? [],- body.scope,- );- const dropped = priorHosts.filter((h) => !targets.includes(h));- if (dropped.length > 0)- reverseProjectSkill(body.name, base, dropped, skillProjectionRoots(body.scope));- const lockPathForInstall = join(base, ...SKILLS_LOCK_REL);- const lockRawForInstall = existsSync(lockPathForInstall)- ? readFileSync(lockPathForInstall, 'utf-8')- : null;- const lockForInstall =- lockRawForInstall !== null ? parseSkillsLock(lockRawForInstall) : null;- if (lockRawForInstall !== null && lockForInstall === null) {- log.warn(- { skill: body.name },- 'skills-lock.json failed to parse — projecting as symlink (import origin unknown)',- );- }- const isAcquired = lockForInstall?.skills[body.name] !== undefined;- const projectionMode: 'symlink' | 'copy' =- linkModeReq !== undefined- ? linkModeReq- ? 'symlink'- : 'copy'- : isAcquired- ? 'copy'- : 'symlink';- const hosts = projectSkill(- skillDir,- body.name,- base,- targets,- projectionMode,- skillProjectionRoots(body.scope),- );- if (hosts.length === 0) {- await removeSkillInstall(base, body.name);- } else {- await recordSkillInstall(base, body.name, {- hosts,- scope: body.scope,- scripts: validity.hasScripts,- installedAt: new Date().toISOString(),- projection: projectionMode,- });- }- signalChannel?.('files');- successResponse(- res,- 200,- SkillInstallSuccessSchema,- { name: body.name, hosts, scripts: validity.hasScripts, warnings, warningCodes },- { handler: 'skill-install' },- );- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to install skill.', {- handler: 'skill-install',- cause: e,- });- }- },- { handler: 'skill-install', method: 'POST' },- );-- const handleSkillUninstall = withValidation(- SkillUninstallRequestSchema,- async (_req, res, body) => {- try {- if (!validateSkillName(body.name, res, 'skill-uninstall')) return;- const base = skillInstallBase(body.scope);- if (!base) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Cannot uninstall — no project root is resolved for this server.',- { handler: 'skill-uninstall', detail: 'NO_PROJECT_ROOT' },- );- return;- }- const uninstalled = await uninstallSkillFromHostDirs(base, body.name, body.scope);- signalChannel?.('files');- successResponse(- res,- 200,- SkillUninstallSuccessSchema,- { name: body.name, uninstalled },- { handler: 'skill-uninstall' },- );- } catch (e) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to uninstall skill.',- {- handler: 'skill-uninstall',- cause: e,- },- );- }- },- { handler: 'skill-uninstall', method: 'POST' },- );-- const handleSkillRestore = withValidation(- SkillRestoreRequestSchema,- async (_req, res, body) => {- try {- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-restore',- });- return;- }- if (!validateSkillName(body.name, res, 'skill-restore')) return;- if (rejectReservedBuiltinSkill(body.name, res, 'skill-restore')) return;- if (body.scope === 'global') {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Global skills are unversioned — there is no version history to restore from.',- { handler: 'skill-restore', detail: 'GLOBAL_SCOPE_UNVERSIONED' },- );- return;- }-- const shadow = shadowRef?.current;- if (!shadow) {- errorResponse(- res,- 409,- 'urn:ok:error:shadow-not-configured',- 'No version history available to restore from.',- {- handler: 'skill-restore',- detail: 'NO_SHADOW_REPO',- },- );- return;- }- const result = await restoreSkillVersion({- shadow,- contentDir,- contentRoot: contentRoot ?? '.',- name: body.name,- version: body.version,- skillDirRel: projectSkillDirRel(body.name),- });- if (!result.ok) {- respondSkillRestoreFailure(res, result, 'skill-restore');- return;- }-- const warnings: string[] = [];- const skillDir = resolve(contentDir, projectSkillDirRel(body.name));- const validity = validateSkillForInstall(skillDir, body.name);- if (!validity.ok) {- warnings.push(- `Restored, but the skill no longer validates: ${validity.errors.join(' ')}`,- );- }-- attributeOkArtifactWrite(- actor,- okArtifactKey('skill', '', body.name),- `skill-restore: ${body.name} @ ${body.version.slice(0, 8)}`,- );- await commitOkArtifactWrite('skill-restore');- signalChannel?.('files');- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();-- successResponse(- res,- 200,- SkillRestoreSuccessSchema,- {- name: body.name,- version: body.version,- restoredFiles: result.restoredFiles,- warnings,- },- { handler: 'skill-restore' },- );- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to restore skill.', {- handler: 'skill-restore',- cause: e,- });- }- },- { handler: 'skill-restore', method: 'POST' },- );-- const handleSkillReimport = withValidation(- SkillReimportRequestSchema,- async (_req, res, body) => {- let cleanup: () => void = () => {};- try {- if (body.scope === 'project' && !projectDir) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {- handler: 'skill-reimport',- detail: 'NO_PROJECT_ROOT',- });- return;- }- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-reimport',- });- return;- }- if (!validateSkillName(body.name, res, 'skill-reimport')) return;-- const reimportBase = body.scope === 'global' ? skillsHome : contentDir;- const {- root: skillsRoot,- dirRel: skillDirRel,- realDir: reimportRealDir,- } = effectiveSkillRoot(body.scope, body.name);- if (- reimportRealDir === null ||- !existsSync(resolve(reimportBase, skillDirRel, 'SKILL.md'))- ) {- errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill is not installed.', {- handler: 'skill-reimport',- detail: 'SKILL_ABSENT',- });- return;- }-- const lockPath = join(- body.scope === 'global' ? skillsHome : (projectDir as string),- ...SKILLS_LOCK_REL,- );- const entry = resolveReimportLockEntry(- body.scope,- body.name,- skillsRoot,- readSkillsLock(lockPath),- );- if (!entry) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'This skill has no recorded import source to update from.',- { handler: 'skill-reimport', detail: 'NOT_IMPORTED' },- );- return;- }- if (body.setAutoUpdate !== undefined) {- await mutateSkillsLock(lockPath, (current) => ({- ...current,- skills: {- ...current.skills,- [body.name]: {- ...(current.skills[body.name] ?? entry),- autoUpdate: body.setAutoUpdate,- },- },- }));- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();-- successResponse(- res,- 200,- SkillReimportSuccessSchema,- { name: body.name, updated: false, source: entry.source, warnings: [] },- { handler: 'skill-reimport' },- );- return;- }- let ref: string | undefined;- let acquiredDir: string | null = null;- try {- const recordedSkill = entry.skill ?? body.name;- const renamedSkill = RENAMED_PACK_SKILLS[recordedSkill];- const skillsSh = await resolveSkillsShImportSource(entry.source, recordedSkill).catch(- async (err: unknown) => {- if (renamedSkill === undefined) throw err;- return resolveSkillsShImportSource(entry.source, renamedSkill);- },- );- const resolvedSource =- skillsSh?.source ?? resolvePluginUpdateSource(entry.source, entry.pluginProvider);- const resolvedSkill = skillsSh?.skill ?? entry.skill;- const spec = skillsSh?.spec ?? parseSource(resolvedSource);- if (!spec) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'The recorded import source is no longer a valid source.',- { handler: 'skill-reimport', detail: entry.source },- );- return;- }- if (rejectDisallowedGitSpec(res, spec, 'skill-reimport')) return;- const fetched = await fetchSource(spec);- cleanup = fetched.cleanup;- ref = fetched.ref;- const dirs = discoverSkillDirs(fetched.dir);- const pick = pickReimportDir(dirs, {- ...(resolvedSkill !== undefined ? { recordedSkill: resolvedSkill } : {}),- localName: body.name,- frontmatterNameOf: (dir) => parseSkillDir(dir)?.name,- });- if (!pick) {- errorResponse(- res,- 404,- 'urn:ok:error:not-found',- 'Could not locate this skill in its source anymore.',- { handler: 'skill-reimport', detail: dirs.map((d) => d.name).join(', ') },- );- return;- }- acquiredDir = pick.dir;- } catch (e) {- if (e instanceof SkillFetchError) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {- handler: 'skill-reimport',- cause: e,- });- return;- }- throw e;- }- if (!acquiredDir) {- errorResponse(res, 422, 'urn:ok:error:invalid-request', 'Source has no readable skill.', {- handler: 'skill-reimport',- });- return;- }- const outcome = await skillReimportService.runSkillReimport({- acquiredDir,- name: body.name,- scope: body.scope,- entry,- lockPath,- ref,- actor,- ...(body.dryRun !== undefined ? { dryRun: body.dryRun } : {}),- });- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- scheduleDeferredIgnoreRebuild();-- respondSkillReimport(res, outcome);- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to reimport skill.', {- handler: 'skill-reimport',- cause: e,- });- } finally {- cleanup();- }- },- { handler: 'skill-reimport', method: 'POST' },- );-- const handleSkillsReimportBulk = withValidation(- SkillsReimportBulkRequestSchema,- async (_req, res, body) => {- try {- if (body.scope === 'project' && !projectDir) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {- handler: 'skills-reimport-bulk',- detail: 'NO_PROJECT_ROOT',- });- return;- }- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skills-reimport-bulk',- });- return;- }- const lockPath = join(- body.scope === 'global' ? skillsHome : (projectDir as string),- ...SKILLS_LOCK_REL,- );- const lock = readSkillsLock(lockPath);- const results: SkillReimportBulkResult[] = [];- const named = new Set(body.names);- const wellFormed = [...named].filter((name) => {- if (isValidSkillName(name)) return true;- results.push({ requested: name, status: 'failed', warnings: [], error: 'INVALID_NAME' });- return false;- });- const { bySource, unrecorded } = groupReimportNamesBySource(wellFormed, (name) =>- resolveReimportLockEntry(- body.scope,- name,- effectiveSkillRoot(body.scope, name).root,- lock,- ),- );- for (const name of unrecorded) {- results.push({ requested: name, status: 'not-found', warnings: [] });- }-- for (const group of bySource) {- let cleanup: () => void = () => {};- try {- let ref: string | undefined;- let dirs: ReturnType<typeof discoverSkillDirs> = [];- try {- const probe = group.names[0] as string;- const skillsSh = await resolveSkillsShImportSource(group.source, probe).catch(- async (err: unknown) => {- const renamed = RENAMED_PACK_SKILLS[probe];- if (renamed === undefined) throw err;- return resolveSkillsShImportSource(group.source, renamed);- },- );- const resolvedSource =- skillsSh?.source ??- resolvePluginUpdateSource(- group.source,- lock.skills[group.names[0] as string]?.pluginProvider,- );- const spec = skillsSh?.spec ?? parseSource(resolvedSource);- if (!spec || isDisallowedGitSpec(spec)) {- for (const name of group.names) {- results.push({- requested: name,- status: 'failed',- source: group.source,- warnings: [],- error: 'INVALID_SOURCE',- });- }- continue;- }- const fetched = await fetchSource(spec);- cleanup = fetched.cleanup;- ref = fetched.ref;- dirs = discoverSkillDirs(fetched.dir);- } catch (e) {- getLogger('skills-reimport-bulk').warn(- { source: group.source, err: e, requestId: getRequestId(_req) },- 'bulk update: one source could not be fetched (rest continue)',- );- for (const name of group.names) {- results.push({- requested: name,- status: 'failed',- source: group.source,- warnings: [],- error: e instanceof Error ? e.message : String(e),- });- }- continue;- }- for (const name of group.names) {- const entry = resolveReimportLockEntry(- body.scope,- name,- effectiveSkillRoot(body.scope, name).root,- lock,- );- if (!entry) {- results.push({ requested: name, status: 'not-found', warnings: [] });- continue;- }- const pick = pickReimportDir(dirs, {- ...(entry.skill !== undefined ? { recordedSkill: entry.skill } : {}),- localName: name,- frontmatterNameOf: (dir) => parseSkillDir(dir)?.name,- });- if (!pick) {- results.push({- requested: name,- status: 'not-found',- source: entry.source,- warnings: [],- });- continue;- }- try {- const outcome = await skillReimportService.runSkillReimport({- acquiredDir: pick.dir,- name,- scope: body.scope,- entry,- lockPath,- ref,- actor,- });- if (!outcome.ok) {- getLogger('skills-reimport-bulk').warn(- {- skill: name,- err: outcome.cause,- detail: outcome.detail,- requestId: getRequestId(_req),- },- 'bulk update: one skill failed (rest continue)',- );- results.push({- requested: name,- status: 'failed',- source: entry.source,- warnings: [],- error: outcome.detail ?? outcome.title,- });- continue;- }- results.push({- requested: name,- status: outcome.body.updated ? 'updated' : 'up-to-date',- source: outcome.body.source,- warnings: outcome.body.warnings,- });- } catch (e) {- getLogger('skills-reimport-bulk').warn(- { skill: name, err: e, requestId: getRequestId(_req) },- 'bulk update: one skill threw (rest continue)',- );- results.push({- requested: name,- status: 'failed',- source: entry.source,- warnings: [],- error: e instanceof Error ? e.message : String(e),- });- }- }- } finally {- cleanup();- }- }- successResponse(- res,- 200,- SkillsReimportBulkSuccessSchema,- {- results,- updated: results.filter((r) => r.status === 'updated').length,- upToDate: results.filter((r) => r.status === 'up-to-date').length,- failed: results.filter((r) => r.status === 'failed' || r.status === 'not-found').length,- },- { handler: 'skills-reimport-bulk' },- );-- try {- bumpSkillsCatalogGen();- contentFilter?.refreshInPlaceSkillDirs();- bumpSkillsCatalogGen();- await contentFilter?.rebuildIgnorePatterns();- } catch (e) {- getLogger('skills-reimport-bulk').warn(- { err: e },- 'bulk update: ignore-pattern rebuild failed after a reported success',- );- }} catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to update skills.', {- handler: 'skills-reimport-bulk',- cause: e,- });- }- },- { handler: 'skills-reimport-bulk', method: 'POST' },- );-- const handleSkillRevert = withValidation(- SkillRevertRequestSchema,- async (_req, res, body) => {- try {- if (!projectDir) {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {- handler: 'skill-revert',- detail: 'NO_PROJECT_ROOT',- });- return;- }- const actor = extractActorIdentity(- body as unknown as Record<string, unknown>,- getPrincipal,- );- if (actor.kind === 'invalid-summary') {- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {- handler: 'skill-revert',- });- return;- }- if (!validateSkillName(body.name, res, 'skill-revert')) return;- if (rejectReservedBuiltinSkill(body.name, res, 'skill-revert')) return;- if (body.scope === 'global') {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Global skills are unversioned — there is nothing to revert to.',- { handler: 'skill-revert', detail: 'GLOBAL_SCOPE' },- );- return;- }-- const lockPath = join(projectDir, ...SKILLS_LOCK_REL);- const lock = readSkillsLock(lockPath);- const entry = lock.skills[body.name];- if (!entry?.baselineRef) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'This skill has no recorded install baseline to revert to.',- { handler: 'skill-revert', detail: 'NO_BASELINE' },- );- return;- }- const shadow = shadowRef?.current;- if (!shadow) {- errorResponse(- res,- 409,- 'urn:ok:error:shadow-not-configured',- 'No version history available to revert from.',- { handler: 'skill-revert', detail: 'NO_SHADOW_REPO' },- );- return;- }-- const result = await restoreSkillVersion({- shadow,- contentDir,- contentRoot: contentRoot ?? '.',- name: body.name,- version: entry.baselineRef,- skillDirRel: projectSkillDirRel(body.name),- });- if (!result.ok) {- respondSkillRestoreFailure(res, result, 'skill-revert');- return;- }-- attributeOkArtifactWrite(- actor,- okArtifactKey('skill', '', body.name),- `skill-revert: ${body.name} @ ${entry.baselineRef.slice(0, 8)}`,- );- await commitOkArtifactWrite('skill-revert');-- const revertRoot = resolve(contentDir, projectSkillDirRel(body.name), '..');- const revertedLocalHash = localSkillHash(revertRoot, body.name);- await mutateSkillsLock(lockPath, (current) =>- upsertLockEntry(current, body.name, {- ...(current.skills[body.name] ?? entry),- ...(revertedLocalHash !== undefined ? { localHash: revertedLocalHash } : {}),- }),- );-- if (revertRoot === resolveSkillsRoot('project')) {- await projectImportedSkillCopy({- skillsRoot: revertRoot,- name: body.name,- scope: 'project',- hasScripts: result.restoredFiles.some((f) => f.startsWith('scripts/')),- handler: 'skill-revert',- });- }-- signalChannel?.('files');- successResponse(+ errorResponse(res,- 200,- SkillRevertSuccessSchema,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to uninstall skill.',{- name: body.name,- baselineRef: entry.baselineRef,- restoredFiles: result.restoredFiles,- warnings: [],+ handler: 'skill-uninstall',+ cause: e,},- { handler: 'skill-revert' },);- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to revert skill.', {- handler: 'skill-revert',- cause: e,- });}},- { handler: 'skill-revert', method: 'POST' },+ { handler: 'skill-uninstall', method: 'POST' },);const searchService = createSearchService({@@ -11139,23 +6752,7 @@ export function createApiExtension(const routes: Record<string, (req: IncomingMessage, res: ServerResponse) => Promise<void>> = {'/api/asset': handleAsset,'/api/asset-text': handleAssetText,- '/api/skill': handleSkill,- '/api/skill-file': handleSkillFile,- '/api/skill-file/rename': handleSkillFileRename,- '/api/skills': handleSkillsList,- '/api/skill/import': handleSkillImport,- '/api/skills/import-bulk': handleSkillsImportBulk,- '/api/skill/edit-external': handleSkillEditExternal,- '/api/skill/duplicate': handleSkillDuplicate,- '/api/skill/move-scope': handleSkillMoveScope,- '/api/skill-upload': handleSkillUpload,- '/api/skill/install': handleSkillInstall,'/api/skill/uninstall': handleSkillUninstall,- '/api/skill/restore': handleSkillRestore,- '/api/skill/reimport': handleSkillReimport,- '/api/skills/reimport-bulk': handleSkillsReimportBulk,- '/api/skill/revert': handleSkillRevert,- '/api/skill/track-in-git': handleSkillTrackInGit,'/api/lint/markdownlint-config': handleWriteMarkdownlintRule,'/api/lint/frontmatter-schema': handleWriteFrontmatterSchema,'/api/lint/fix': handleLintFix,@@ -11170,7 +6767,6 @@ export function createApiExtension('/api/save-version': handleSaveVersion,'/api/rollback': handleRollback,'/api/agent-integrations/apply': handleAgentIntegrationsApply,- '/api/install-skill': handleInstallSkill,};if (enableTestRoutes) {@@ -11196,23 +6792,7 @@ export function createApiExtension('/api/test-flush-git','/api/test-rescan-backlinks','/api/test-rescan-files',- '/api/install-skill',- '/api/skill',- '/api/skill-file',- '/api/skill-file/rename',- '/api/skill/import',- '/api/skills/import-bulk',- '/api/skill/duplicate',- '/api/skill/move-scope',- '/api/skill/edit-external',- '/api/skill-upload',- '/api/skill/install','/api/skill/uninstall',- '/api/skill/restore',- '/api/skill/reimport',- '/api/skills/reimport-bulk',- '/api/skill/revert',- '/api/skill/track-in-git','/api/agent-integrations/apply',]);@@ -11305,6 +6885,106 @@ export function createApiExtension(safeDocPath,docTreePathCandidates,});+ const skillsFileRoutes = createSkillsFileRoutes({+ validateSkillName,+ parseSkillScope,+ skillsHome,+ projectDir,+ resolveBuiltinSkillDir,+ resolveSkillDirForRead,+ resolveSkillsRoot,+ getPrincipal,+ rejectReservedBuiltinSkill,+ contentDir,+ checkSkillDocConflictGate,+ extractAgentIdentity,+ sessionManager,+ flushDiskAndDetectOutcome,+ respondStaleExternalWrite,+ respondPersistenceFailure,+ respondDiskDivergence,+ attributeOkArtifactWrite,+ okArtifactKey,+ commitOkArtifactWrite,+ signalChannel,+ extractActorIdentityFromQuery,+ captureAndCloseDocuments,+ derivedDocumentIndex,+ log,+ recordDerivedMutationsBestEffort,+ });+ const skillsImportRoutes = createSkillsImportRoutes({+ projectDir,+ getPrincipal,+ skillImportService,+ bumpSkillsCatalogGen,+ contentFilter,+ scheduleDeferredIgnoreRebuild,+ signalChannel,+ parseSkillScope,+ });+ const skillsDocumentRoutes = createSkillsDocumentRoutes({+ validateSkillName,+ parseSkillScope,+ skillsHome,+ projectDir,+ resolveBuiltinSkillDir,+ parseFrontmatterDoc,+ resolveSkillDirForRead,+ skillRelPath,+ derivedDocumentIndex,+ contentFilter,+ bumpSkillsCatalogGen,+ scheduleDeferredIgnoreRebuild,+ recordDerivedDocumentBestEffort,+ getPrincipal,+ rejectReservedBuiltinSkill,+ contentDir,+ attributeOkArtifactWrite,+ scheduleOkArtifactFlush,+ signalChannel,+ checkSkillDocConflictGate,+ extractAgentIdentity,+ sessionManager,+ flushDiskAndDetectOutcome,+ respondStaleExternalWrite,+ respondPersistenceFailure,+ respondDiskDivergence,+ okArtifactKey,+ resolveSkillsRoot,+ extractActorIdentityFromQuery,+ captureAndCloseDocuments,+ log,+ commitOkArtifactWrite,+ skillInstallBase,+ uninstallSkillFromHostDirs,+ renameTrackedPathInGit,+ renamePathOnDisk,+ localSkillHash,+ shadowHeadSha,+ artifactWriterId,+ checkLocalOpSecurity,+ effectiveSkillRoot,+ });+ const skillsListRoutes = createSkillsListRoutes({+ contentDir,+ projectDir,+ skillsHome,+ contentFilter,+ catalogCache,+ resolveSkillsRoot,+ resolveSkillsList,+ skillOriginFor,+ localSkillHash,+ effectiveInstallMode,+ pluginSelfIdentity,+ synthBuiltinLockEntry,+ synthPluginLockEntry,+ pluginUpstreamHash,+ builtinSkillListEntry,+ indexedSkillContentPath,+ healUnservableSkillAdmission,+ });const skillsReadRoutes = createSkillsReadRoutes({contentDir,projectDir,@@ -11456,13 +7136,76 @@ export function createApiExtension(splitContentPath,mutateFileIndex,});+ const handoffInstallRoutes = createHandoffInstallRoutes({ checkLocalOpSecurity });+ const skillsInstallRoutes = createSkillsInstallRoutes({+ resolveSkillsRoot,+ validateSkillName,+ projectDir,+ skillInstallBase,+ contentDir,+ skillsHome,+ shippedBundleSkillMd,+ flushDiskAndDetectOutcome,+ respondStaleExternalWrite,+ skillInstallOps,+ skillPlacementOps,+ signalChannel,+ bumpSkillsCatalogGen,+ contentFilter,+ scheduleDeferredIgnoreRebuild,+ effectiveInstallMode,+ log,+ });+ const skillsRecoveryRoutes = createSkillsRecoveryRoutes({+ synthPluginLockEntry,+ synthBuiltinLockEntry,+ isValidSkillName,+ getPrincipal,+ validateSkillName,+ rejectReservedBuiltinSkill,+ shadowRef,+ contentDir,+ contentRoot,+ projectDir,+ skillsHome,+ projectSkillDirRel,+ attributeOkArtifactWrite,+ okArtifactKey,+ commitOkArtifactWrite,+ signalChannel,+ bumpSkillsCatalogGen,+ contentFilter,+ scheduleDeferredIgnoreRebuild,+ effectiveSkillRoot,+ skillReimportService,+ localSkillHash,+ resolveSkillsRoot,+ projectImportedSkillCopy,+ });+ const skillsTrackingRoutes = createSkillsTrackingRoutes({+ contentDir,+ projectDir,+ contentFilter,+ validateSkillName,+ indexedSkillContentPath,+ bumpSkillsCatalogGen,+ signalChannel,+ });const nativeGroups = [+ skillsTrackingRoutes,+ skillsRecoveryRoutes,+ skillsInstallRoutes,+ handoffInstallRoutes,+ skillsImportRoutes,+ skillsFileRoutes,linkGraphRoutes,metricsRoutes,documentRoutes,configSystemRoutes,lintRoutes,historyRoutes,+ skillsDocumentRoutes,+ skillsListRoutes,skillsReadRoutes,skillsShRoutes,workspaceToolsRoutes,diff --git a/packages/server/src/api-skill-document-composition.test.ts b/packages/server/src/api-skill-document-composition.test.tsnew file mode 100644index 000000000..b4cc43e32--- /dev/null+++ b/packages/server/src/api-skill-document-composition.test.ts@@ -0,0 +1,168 @@+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterAll, afterEach, beforeAll, expect, test, vi } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';+import * as contributorTracker from './contributor-tracker.ts';++let root: string;+let server: BootedServer;+let home: string;++beforeAll(async () => {+ root = mkdtempSync(join(tmpdir(), 'ok-skill-document-contract-'));+ const builtin = join(root, '.agents/skills/open-knowledge');+ mkdirSync(builtin, { recursive: true });+ writeFileSync(+ join(builtin, 'SKILL.md'),+ '---\nname: open-knowledge\ndescription: Project instructions\n---\n\nProject.\n',+ );+ home = mkdtempSync(join(tmpdir(), 'ok-skill-document-home-'));+ mkdirSync(join(home, '.claude'));+ server = await bootCompositionRig(root, { configHomedirOverride: home });+ await server.ready;+}, 60_000);++afterEach(() => vi.restoreAllMocks());++afterAll(async () => {+ await server?.destroy();+ rmSync(root, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+});++async function request(path: string, method = 'GET', body?: object) {+ const response = await rawRequest(server.port, path, {+ method,+ headers: { 'Content-Type': 'application/json' },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ expect(response.status, response.body).toBe(200);+ return JSON.parse(response.body);+}++test('create, edit, list and delete retain disk bytes and the editing session origin', async () => {+ const attribution = vi.spyOn(contributorTracker, 'recordContributor');+ const name = 'document-contract';+ const created = await request('/api/skill', 'PUT', {+ name,+ scope: 'project',+ frontmatter: { name, description: 'Before' },+ body: 'Initial.\n',+ agentId: 'document-writer',+ });+ expect(created.created).toBe(true);+ const path = created.path as string;+ const docName = path.slice(0, -3);+ const session = await server.serverInstance.sessionManager.getSession(+ docName,+ 'agent-document-writer',+ { displayName: 'Document Writer', colorSeed: 'document-writer' },+ );+ const origins: unknown[] = [];+ const observe = (event: { transaction: { origin: unknown } }) =>+ origins.push(event.transaction.origin);+ session.dc.document.getText('source').observe(observe);+ attribution.mockClear();+ try {+ const body = '## Exact bytes\n\nBackslash \\* and <custom data="x">raw</custom>.\n\n';+ const edited = await request('/api/skill', 'PUT', {+ name,+ scope: 'project',+ frontmatter: { name, description: 'After' },+ body,+ agentId: 'document-writer',+ agentName: 'Document Writer',+ });+ expect(edited.created).toBe(false);+ const expected = `---\nname: ${name}\ndescription: After\n---\n${body}`;+ expect(session.dc.document.getText('source').toString()).toBe(expected);+ expect(readFileSync(join(root, path), 'utf8')).toBe(expected);+ expect(origins).toContain(session.origin);+ expect(attribution.mock.calls.map(([doc, writer]) => [doc, writer])).toContainEqual([+ docName,+ 'agent-document-writer',+ ]);+ const read = await request(`/api/skill?name=${name}&scope=project`);+ expect(read.skill.frontmatter.description).toBe('After');+ expect(read.skill.body).toBe(body);+ const listed = await request('/api/skills');+ expect(listed.skills.find((skill: { name: string }) => skill.name === name)?.description).toBe(+ 'After',+ );+ } finally {+ session.dc.document.getText('source').unobserve(observe);+ }+ const deleted = await request(+ `/api/skill?name=${name}&scope=project&agentId=document-writer`,+ 'DELETE',+ );+ expect(deleted.existed).toBe(true);+ const listed = await request('/api/skills');+ expect(listed.skills.some((skill: { name: string }) => skill.name === name)).toBe(false);+});++test('mixed-method skill reads retain mutation admission', async () => {+ const response = await rawRequest(server.port, '/api/skill?name=missing', {+ headers: { Origin: 'https://untrusted.example.com' },+ });+ expect(response.status).toBe(403);+});++test('duplicate, rename and scope round trips preserve bundled bytes and remove prior paths', async () => {+ const name = 'directory-contract';+ const created = await request('/api/skill', 'PUT', {+ name,+ scope: 'project',+ frontmatter: { name, description: 'Directory contract' },+ body: 'Body with <raw> and trailing space. \n',+ });+ const dir = join(root, (created.path as string).slice(0, -9));+ mkdirSync(join(dir, 'scripts'));+ const bytes = Buffer.from([0, 255, 127, 13, 10]);+ writeFileSync(join(dir, 'scripts/data.bin'), bytes);+ await request('/api/skill/duplicate', 'POST', {+ name,+ toName: 'directory-copy',+ scope: 'project',+ });+ await request('/api/skill', 'POST', {+ fromName: 'directory-copy',+ toName: 'directory-renamed',+ scope: 'project',+ });+ const renamed = await request('/api/skill?name=directory-renamed&scope=project');+ const renamedPath = renamed.skill.path as string;+ expect(readFileSync(join(root, renamedPath.slice(0, -9), 'scripts/data.bin'))).toEqual(bytes);+ const before = readFileSync(join(root, renamedPath), 'utf8');+ const global = await request('/api/skill/move-scope', 'POST', {+ name: 'directory-renamed',+ fromScope: 'project',+ toScope: 'global',+ });+ expect(readFileSync(join(home, global.path, 'SKILL.md'), 'utf8')).toBe(before);+ expect(readFileSync(join(home, global.path, 'scripts/data.bin'))).toEqual(bytes);+ const back = await request('/api/skill/move-scope', 'POST', {+ name: 'directory-renamed',+ fromScope: 'global',+ toScope: 'project',+ });+ expect(readFileSync(join(root, back.path, 'SKILL.md'), 'utf8')).toBe(before);+ expect(readFileSync(join(root, back.path, 'scripts/data.bin'))).toEqual(bytes);+ const missing = await rawRequest(server.port, '/api/skill?name=directory-copy&scope=project');+ expect(missing.status).toBe(404);+ await request('/api/skill?name=directory-renamed&scope=project', 'DELETE');+ await request(`/api/skill?name=${name}&scope=project`, 'DELETE');+});++test('external editing resolves a real skill directory without launching an editor', async () => {+ const dir = join(home, 'external');+ mkdirSync(dir);+ writeFileSync(+ join(dir, 'SKILL.md'),+ '---\nname: external\ndescription: External contract\n---\nRaw body.\n',+ );+ const result = await request('/api/skill/edit-external', 'POST', { name: 'external', home: dir });+ expect(result.docName).toBe('__extskill__/external');+});diff --git a/packages/server/src/api-skill-file-composition.test.ts b/packages/server/src/api-skill-file-composition.test.tsnew file mode 100644index 000000000..d4aaa50f4--- /dev/null+++ b/packages/server/src/api-skill-file-composition.test.ts@@ -0,0 +1,226 @@+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterAll, afterEach, beforeAll, expect, test, vi } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';+import * as contributorTracker from './contributor-tracker.ts';++let root: string;+let server: BootedServer;+let home: string;++beforeAll(async () => {+ root = mkdtempSync(join(tmpdir(), 'ok-skill-file-contract-'));+ const builtin = join(root, '.agents/skills/open-knowledge');+ mkdirSync(builtin, { recursive: true });+ writeFileSync(+ join(builtin, 'SKILL.md'),+ '---\nname: open-knowledge\ndescription: Project instructions\n---\n\nProject.\n',+ );+ home = mkdtempSync(join(tmpdir(), 'ok-skill-file-home-'));+ mkdirSync(join(home, '.claude'));+ server = await bootCompositionRig(root, { configHomedirOverride: home });+ await server.ready;+}, 60_000);++afterEach(() => vi.restoreAllMocks());++afterAll(async () => {+ await server?.destroy();+ rmSync(root, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+});++async function request(path: string, method = 'GET', body?: object) {+ const response = await rawRequest(server.port, path, {+ method,+ headers: { 'Content-Type': 'application/json' },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ expect(response.status, response.body).toBe(200);+ return JSON.parse(response.body);+}++test('reference edits and rename preserve live bytes and writer identity', async () => {+ const attribution = vi.spyOn(contributorTracker, 'recordContributor');+ const name = 'file-contract';+ const skill = await request('/api/skill', 'PUT', {+ name,+ scope: 'project',+ frontmatter: { name, description: 'File contract' },+ body: 'Body.\n',+ });+ const dir = (skill.path as string).slice(0, -9);+ const path = 'references/notes.md';+ const docName = `${dir}/${path.slice(0, -3)}`;+ await request('/api/skill-file', 'PUT', {+ name,+ scope: 'project',+ path,+ content: 'Initial.\n',+ agentId: 'file-writer',+ });+ const session = await server.serverInstance.sessionManager.getSession(+ docName,+ 'agent-file-writer',+ { displayName: 'File Writer', colorSeed: 'file-writer' },+ );+ const origins: unknown[] = [];+ const observe = (event: { transaction: { origin: unknown } }) =>+ origins.push(event.transaction.origin);+ session.dc.document.getText('source').observe(observe);+ attribution.mockClear();+ const content = '## Bytes\n\nBackslash \\* and <custom>raw</custom>. \n\n';+ try {+ const result = await request('/api/skill-file', 'PUT', {+ name,+ scope: 'project',+ path,+ content,+ agentId: 'file-writer',+ });+ expect(result).toMatchObject({ path, kind: 'reference', content: true, created: false });+ expect(session.dc.document.getText('source').toString()).toBe(content);+ expect(readFileSync(join(root, dir, path), 'utf8')).toBe(content);+ expect(origins).toContain(session.origin);+ expect(attribution.mock.calls.map(([doc, writer]) => [doc, writer])).toContainEqual([+ `${dir}/SKILL`,+ 'agent-file-writer',+ ]);+ } finally {+ session.dc.document.getText('source').unobserve(observe);+ }+ const oldDocument = session.dc.document;+ attribution.mockClear();+ const renamed = await request('/api/skill-file/rename', 'POST', {+ name,+ scope: 'project',+ from: path,+ to: 'references/renamed.md',+ agentId: 'file-renamer',+ });+ expect(renamed).toMatchObject({+ from: path,+ to: 'references/renamed.md',+ fromDocName: docName,+ toDocName: `${dir}/references/renamed`,+ });+ expect(readFileSync(join(root, dir, 'references/renamed.md'), 'utf8')).toBe(content);+ expect(oldDocument.getMap('lifecycle').get('status')).toBe('deleted-upstream');+ expect(attribution.mock.calls.map(([doc, writer]) => [doc, writer])).toContainEqual([+ `${dir}/SKILL`,+ 'agent-file-renamer',+ ]);+ expect((await request(`/api/skill-file?name=${name}&path=references/renamed.md`)).text).toBe(+ content,+ );+ expect(+ (+ await request(+ `/api/skill-file?name=${name}&path=references/renamed.md&agentId=file-writer`,+ 'DELETE',+ )+ ).existed,+ ).toBe(true);+ expect(+ (await request(`/api/skill-file?name=${name}&path=references/renamed.md`, 'DELETE')).existed,+ ).toBe(false);+});++test('bundle-file reads retain mutation admission', async () => {+ const response = await rawRequest(server.port, '/api/skill-file?name=missing&path=notes.md', {+ headers: { Origin: 'https://untrusted.example.com' },+ });+ expect(response.status).toBe(403);+});++test('raw bundle writes preserve text, resolve sibling extensions, and reject binary reads', async () => {+ const name = 'raw-file-contract';+ const skill = await request('/api/skill', 'PUT', {+ name,+ scope: 'project',+ frontmatter: { name, description: 'Raw files' },+ body: 'Body.\n',+ });+ const dir = (skill.path as string).slice(0, -9);+ for (const [path, content, kind] of [+ ['scripts/run.sh', '#!/bin/sh\r\nprintf "hello"\r\n', 'script'],+ ['references/example.mdx', '<Example value="raw" />\n\n', 'reference'],+ ['assets/data.txt', 'Unicode: 水\t\r\n', 'file'],+ ]) {+ const written = await request('/api/skill-file', 'PUT', {+ name,+ scope: 'project',+ path,+ content,+ });+ expect(written).toMatchObject({ path, kind, content: false, created: true });+ expect(readFileSync(join(root, dir, path), 'utf8')).toBe(content);+ expect((await request(`/api/skill-file?name=${name}&path=${path}`)).text).toBe(content);+ }+ expect(await request(`/api/skill-file?name=${name}&path=references/example.md`)).toMatchObject({+ path: 'references/example.mdx',+ text: '<Example value="raw" />\n\n',+ });+ writeFileSync(join(root, dir, 'assets/binary.dat'), Buffer.from([0, 255, 10]));+ const binary = await rawRequest(+ server.port,+ `/api/skill-file?name=${name}&path=assets/binary.dat`,+ { headers: { 'X-Request-Id': 'file-binary-contract' } },+ );+ expect(binary.status).toBe(415);+ expect(binary.headers['content-type']).toContain('application/problem+json');+ expect(binary.headers['x-request-id']).toBe('file-binary-contract');+ await request('/api/skill-file/rename', 'POST', {+ name,+ scope: 'project',+ from: 'assets/binary.dat',+ to: 'assets/moved.dat',+ });+ expect(readFileSync(join(root, dir, 'assets/moved.dat'))).toEqual(Buffer.from([0, 255, 10]));+ expect(+ (await request(`/api/skill-file?name=${name}&path=assets/moved.dat`, 'DELETE')).existed,+ ).toBe(true);+});++test('bundle path and size errors leave the existing file unchanged', async () => {+ const name = 'file-errors';+ await request('/api/skill', 'PUT', {+ name,+ scope: 'project',+ frontmatter: { name, description: 'Errors' },+ body: 'Body.\n',+ });+ await request('/api/skill-file', 'PUT', {+ name,+ scope: 'project',+ path: 'assets/keep.txt',+ content: 'Keep.\n',+ });+ for (const body of [+ { path: '../outside.txt', content: 'Escape' },+ { path: 'SKILL.md', content: 'Overwrite' },+ { path: 'assets/keep.txt', content: 'x'.repeat(256 * 1024 + 1) },+ ]) {+ const response = await rawRequest(server.port, '/api/skill-file', {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name, scope: 'project', ...body }),+ });+ expect(response.status, response.body).toBe(400);+ expect(response.headers['content-type']).toContain('application/problem+json');+ }+ const missing = await rawRequest(server.port, '/api/skill-file/rename', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ name,+ scope: 'project',+ from: 'assets/missing.txt',+ to: 'assets/keep.txt',+ }),+ });+ expect(missing.status).toBe(400);+ expect((await request(`/api/skill-file?name=${name}&path=assets/keep.txt`)).text).toBe('Keep.\n');+});diff --git a/packages/server/src/api-skill-import-composition.test.ts b/packages/server/src/api-skill-import-composition.test.tsnew file mode 100644index 000000000..663a9c9d4--- /dev/null+++ b/packages/server/src/api-skill-import-composition.test.ts@@ -0,0 +1,431 @@+import { fork } from 'node:child_process';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { connect } from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterAll, afterEach, beforeAll, expect, test, vi } from 'vitest';+import yazl from 'yazl';+import { createApiExtension } from './api-extension.test-helper.ts';+import type { BootedServer } from './boot.ts';+import {+ bootCompositionRig,+ makeCaptureRes,+ makeSyntheticReq,+ rawRequest,+} from './composition-rig.test-helper.ts';+import * as contributorTracker from './contributor-tracker.ts';++let root: string;+let source: string;+let server: BootedServer;+const markdown = (name: string) =>+ `---\nname: ${name}\ndescription: Import contract\n---\n\n## Bytes\n\nBackslash \\* and <custom>raw</custom>. \n\n`;++beforeAll(async () => {+ root = mkdtempSync(join(tmpdir(), 'ok-import-contract-'));+ source = mkdtempSync(join(tmpdir(), 'ok-import-contract-source-'));+ mkdirSync(join(root, '.claude'));+ server = await bootCompositionRig(root);+ await server.ready;+}, 60_000);++afterEach(() => vi.restoreAllMocks());++afterAll(async () => {+ await server?.destroy();+ rmSync(root, { recursive: true, force: true });+ rmSync(source, { recursive: true, force: true });+});++async function post(path: string, body: object) {+ const result = await rawRequest(server.port, path, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+ expect(result.status, result.body).toBe(200);+ return JSON.parse(result.body);+}++function seed(name: string) {+ const dir = join(source, name);+ mkdirSync(join(dir, 'assets'), { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), markdown(name));+ writeFileSync(join(dir, 'assets/data.bin'), Buffer.from([0, 255, 10]));+ return dir;+}++test('single import preserves bundle bytes, provenance and actor attribution', async () => {+ const attribution = vi.spyOn(contributorTracker, 'recordContributor');+ const name = 'single-contract';+ const dir = seed(name);+ const result = await post('/api/skill/import', {+ source: dir,+ agentId: 'import-writer',+ install: false,+ });+ expect(result).toMatchObject({+ name,+ created: true,+ alreadyImported: false,+ provenance: { source: dir },+ });+ expect(readFileSync(join(root, '.claude/skills', name, 'SKILL.md'), 'utf8')).toBe(markdown(name));+ expect(readFileSync(join(root, '.claude/skills', name, 'assets/data.bin'))).toEqual(+ Buffer.from([0, 255, 10]),+ );+ expect(attribution.mock.calls.map(([doc, writer]) => [doc, writer])).toContainEqual([+ `.claude/skills/${name}/SKILL`,+ 'agent-import-writer',+ ]);+ expect(await post('/api/skill/import', { source: dir, install: false })).toMatchObject({+ name,+ alreadyImported: true,+ });+ expect(existsSync(join(root, '.ok/skills-lock.json'))).toBe(true);+});++test('bulk import retains request order, deduplication and partial results', async () => {+ const attribution = vi.spyOn(contributorTracker, 'recordContributor');+ seed('bulk-first');+ seed('bulk-second');+ const result = await post('/api/skills/import-bulk', {+ source,+ skills: ['bulk-second', 'missing', 'bulk-first', 'bulk-second'],+ install: false,+ agentId: 'bulk-writer',+ });+ expect(result).toMatchObject({+ imported: 2,+ alreadyImported: 0,+ failed: 1,+ results: [+ { requested: 'bulk-second', name: 'bulk-second', status: 'imported' },+ { requested: 'missing', status: 'not-found' },+ { requested: 'bulk-first', name: 'bulk-first', status: 'imported' },+ ],+ });+ for (const name of ['bulk-first', 'bulk-second']) {+ expect(readFileSync(join(root, '.claude/skills', name, 'SKILL.md'), 'utf8')).toBe(+ markdown(name),+ );+ }+ for (const name of ['bulk-first', 'bulk-second']) {+ expect(attribution.mock.calls.map(([doc, writer]) => [doc, writer])).toContainEqual([+ `.claude/skills/${name}/SKILL`,+ 'agent-bulk-writer',+ ]);+ }+});++function multipart(files: Array<{ name: string; data: string | Buffer }>) {+ const boundary = 'ok-import-contract-boundary';+ const body = Buffer.concat([+ ...files.flatMap(({ name, data }) => [+ Buffer.from(+ `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${name}"\r\nContent-Type: application/octet-stream\r\n\r\n`,+ ),+ Buffer.from(data),+ Buffer.from('\r\n'),+ ]),+ Buffer.from(`--${boundary}--\r\n`),+ ]);+ return {+ body,+ headers: {+ 'Content-Type': `multipart/form-data; boundary=${boundary}`,+ 'X-Request-Id': 'upload-contract',+ },+ };+}++test('completed multipart import preserves raw bytes and query actor attribution', async () => {+ const attribution = vi.spyOn(contributorTracker, 'recordContributor');+ const name = 'upload-contract';+ const result = await rawRequest(server.port, '/api/skill-upload?agentId=upload-writer', {+ method: 'POST',+ ...multipart([+ { name: 'SKILL.md', data: markdown(name) },+ { name: 'assets/data.bin', data: Buffer.from([0, 255, 10]) },+ ]),+ });+ expect(result.status, result.body).toBe(200);+ expect(JSON.parse(result.body)).toMatchObject({ name, created: true });+ expect(readFileSync(join(root, '.claude/skills', name, 'SKILL.md'), 'utf8')).toBe(markdown(name));+ expect(existsSync(join(root, '.claude/skills', name, 'assets/data.bin'))).toBe(false);+ expect(attribution.mock.calls.map(([doc, writer]) => [doc, writer])).toContainEqual([+ `.claude/skills/${name}/SKILL`,+ 'agent-upload-writer',+ ]);+ expect(result.headers['x-request-id']).toBe('upload-contract');+});++test('multipart failures preserve malformed, empty and archive envelopes', async () => {+ for (const [files, title, status] of [+ [[], 'No files uploaded.', 400],+ [[{ name: 'bundle.zip', data: 'invalid archive' }], 'Could not unpack the archive.', 400],+ [[{ name: 'notes.txt', data: 'No skill' }], 'No SKILL.md found in the upload.', 404],+ [+ [{ name: 'SKILL.md', data: Buffer.alloc(8 * 1024 * 1024 + 1, 65) }],+ 'Could not read the upload.',+ 400,+ ],+ ] as const) {+ const result = await rawRequest(server.port, '/api/skill-upload', {+ method: 'POST',+ ...multipart([...files]),+ });+ expect(result.status, result.body).toBe(status);+ expect(result.headers['content-type']).toContain('application/problem+json');+ expect(result.headers['x-request-id']).toBe('upload-contract');+ expect(JSON.parse(result.body)).toMatchObject({ title });+ }+ const malformed = await rawRequest(server.port, '/api/skill-upload', {+ method: 'POST',+ headers: { 'Content-Type': 'multipart/form-data' },+ body: 'broken',+ });+ expect(malformed.status).toBe(400);+ expect(JSON.parse(malformed.body).title).toBe('Could not read the upload.');+});++async function archive(files: Array<{ name: string; data: string | Buffer }>): Promise<Buffer> {+ const zip = new yazl.ZipFile();+ const chunks: Buffer[] = [];+ const completed = new Promise<Buffer>((resolve, reject) => {+ zip.outputStream.on('data', (chunk: Buffer) => chunks.push(chunk));+ zip.outputStream.on('end', () => resolve(Buffer.concat(chunks)));+ zip.outputStream.on('error', reject);+ });+ for (const file of files) zip.addBuffer(Buffer.from(file.data), file.name);+ zip.end();+ return completed;+}++test('archive upload preserves nested bundle bytes and rejects expanded entry limits', async () => {+ const name = 'archive-contract';+ const data = await archive([+ { name: 'SKILL.md', data: markdown(name) },+ { name: 'assets/data.bin', data: Buffer.from([0, 255, 10]) },+ ]);+ const result = await rawRequest(server.port, '/api/skill-upload', {+ method: 'POST',+ ...multipart([{ name: 'bundle.skill', data }]),+ });+ expect(result.status, result.body).toBe(200);+ expect(readFileSync(join(root, '.claude/skills', name, 'SKILL.md'), 'utf8')).toBe(markdown(name));+ expect(readFileSync(join(root, '.claude/skills', name, 'assets/data.bin'))).toEqual(+ Buffer.from([0, 255, 10]),+ );+ for (const entries of [+ [{ name: 'large.bin', data: Buffer.alloc(8 * 1024 * 1024 + 1) }],+ Array.from({ length: 201 }, (_, i) => ({ name: `files/${i}.txt`, data: 'x' })),+ Array.from({ length: 5 }, (_, i) => ({+ name: `files/${i}.txt`,+ data: Buffer.alloc(7 * 1024 * 1024),+ })),+ ]) {+ const rejected = await rawRequest(server.port, '/api/skill-upload', {+ method: 'POST',+ ...multipart([{ name: 'large.zip', data: await archive(entries) }]),+ });+ expect(rejected.status, rejected.body).toBe(400);+ expect(JSON.parse(rejected.body).title).toBe('Could not unpack the archive.');+ }+});++test('aggregate multipart overflow retains the parser failure in an isolated server process', async () => {+ const contentDir = mkdtempSync(join(tmpdir(), 'ok-overflow-contract-'));+ const home = mkdtempSync(join(tmpdir(), 'ok-overflow-home-'));+ const child = fork(+ fileURLToPath(new URL('./skill-upload-process.test-helper.ts', import.meta.url)),+ [contentDir, home],+ {+ execArgv: ['--import', 'tsx', '--conditions=@inkeep/source'],+ silent: true,+ env: { ...process.env, TMPDIR: home, TMP: home, TEMP: home },+ },+ );+ let stderr = '';+ child.stderr?.on('data', (chunk) => {+ stderr += String(chunk);+ });+ child.stdout?.resume();+ const exited = new Promise<number | null>((resolve) => child.once('exit', resolve));+ try {+ const port = await new Promise<number>((resolve, reject) => {+ child.once('message', (message) => {+ if (+ typeof message !== 'object' ||+ message === null ||+ !('port' in message) ||+ typeof message.port !== 'number'+ ) {+ reject(new Error('Upload fixture sent no port.'));+ return;+ }+ resolve(message.port);+ });+ child.once('error', reject);+ child.once('exit', (code) => reject(new Error(`Upload fixture exited ${code}: ${stderr}`)));+ });+ await expect(+ rawRequest(port, '/api/skill-upload', {+ method: 'POST',+ ...multipart(+ Array.from({ length: 5 }, (_, i) => ({+ name: `${i}.txt`,+ data: Buffer.alloc(7 * 1024 * 1024),+ })),+ ),+ }),+ ).rejects.toThrow(/socket hang up|ECONNRESET|EPIPE/);+ expect(await exited).toBe(1);+ expect(stderr).toContain('Unexpected end of file');+ } finally {+ child.kill();+ await exited;+ rmSync(contentDir, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+ }+}, 30_000);++test('disconnect during an incomplete multipart request retains staging while the listener stays usable', async () => {+ const contentDir = mkdtempSync(join(tmpdir(), 'ok-disconnect-contract-'));+ const home = mkdtempSync(join(tmpdir(), 'ok-disconnect-home-'));+ const child = fork(+ fileURLToPath(new URL('./skill-upload-process.test-helper.ts', import.meta.url)),+ [contentDir, home],+ {+ execArgv: ['--import', 'tsx', '--conditions=@inkeep/source'],+ silent: true,+ env: { ...process.env, TMPDIR: home, TMP: home, TEMP: home },+ },+ );+ let stderr = '';+ child.stderr?.on('data', (chunk) => {+ stderr += String(chunk);+ });+ child.stdout?.resume();+ const exited = new Promise<number | null>((resolve) => child.once('exit', resolve));+ try {+ const port = await new Promise<number>((resolve, reject) => {+ child.once('message', (message) => {+ if (+ typeof message !== 'object' ||+ message === null ||+ !('port' in message) ||+ typeof message.port !== 'number'+ ) {+ reject(new Error('Upload fixture sent no port.'));+ return;+ }+ resolve(message.port);+ });+ child.once('error', reject);+ child.once('exit', (code) => reject(new Error(`Upload fixture exited ${code}: ${stderr}`)));+ });+ const socket = connect(port, '127.0.0.1');+ socket.on('error', () => {});+ try {+ await new Promise<void>((resolve) => socket.once('connect', resolve));+ socket.write(+ [+ 'POST /api/skill-upload HTTP/1.1',+ `Host: 127.0.0.1:${port}`,+ 'Content-Type: multipart/form-data; boundary=partial-contract',+ 'Content-Length: 100000',+ '',+ '--partial-contract',+ 'Content-Disposition: form-data; name="file"; filename="SKILL.md"',+ '',+ markdown('aborted-contract'),+ ].join('\r\n'),+ );+ const staged = () => readdirSync(home).filter((name) => name.startsWith('ok-skill-upload-'));+ await vi.waitFor(() => expect(staged()).toHaveLength(1));+ socket.destroy();+ const result = await rawRequest(port, '/api/skill-upload', {+ method: 'POST',+ ...multipart([]),+ });+ expect(result.status).toBe(400);+ expect(existsSync(join(contentDir, '.claude/skills/aborted-contract'))).toBe(false);+ expect(staged()).toHaveLength(1);+ expect(child.exitCode).toBeNull();+ } finally {+ socket.destroy();+ }+ } finally {+ child.kill();+ await exited;+ rmSync(contentDir, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+ }+}, 30_000);++test('upload without a project root rejects before method validation', async () => {+ const extension = createApiExtension({+ contentDir: root,+ hocuspocus: server.serverInstance.hocuspocus,+ sessionManager: server.serverInstance.sessionManager,+ });+ const request = makeSyntheticReq({ method: 'GET', url: '/api/skill-upload' });+ const { res, captured } = makeCaptureRes();+ try {+ await extension.onRequest({ request, response: res });+ expect(captured.status).toBe(400);+ expect(JSON.parse(captured.body)).toMatchObject({+ title: 'No project root resolved.',+ detail: 'NO_PROJECT_ROOT',+ });+ expect(captured.headers.allow).toBeUndefined();+ } finally {+ request.destroy();+ }+});++test('raw multipart keeps the first two hundred files and ignores oversized excess text fields', async () => {+ const name = 'raw-count-contract';+ const payload = multipart([+ { name: 'SKILL.md', data: markdown(name) },+ ...Array.from({ length: 199 }, (_, i) => ({ name: `note-${i}.txt`, data: `file ${i}` })),+ { name: 'beyond-limit.txt', data: 'not admitted' },+ ]);+ const fields = Buffer.from(+ Array.from(+ { length: 11 },+ (_, i) =>+ `--ok-import-contract-boundary\r\nContent-Disposition: form-data; name="field-${i}"\r\n\r\n${'x'.repeat(2049)}\r\n`,+ ).join(''),+ );+ const response = await rawRequest(server.port, '/api/skill-upload', {+ method: 'POST',+ headers: payload.headers,+ body: Buffer.concat([fields, payload.body]),+ });+ expect(response.status, response.body).toBe(200);+ const installed = join(root, '.claude/skills', name);+ expect(readFileSync(join(installed, 'SKILL.md'), 'utf8')).toBe(markdown(name));+ expect(readFileSync(join(installed, 'note-198.txt'), 'utf8')).toBe('file 198');+ expect(existsSync(join(installed, 'beyond-limit.txt'))).toBe(false);+ const omittedSkill = await rawRequest(server.port, '/api/skill-upload', {+ method: 'POST',+ ...multipart([+ ...Array.from({ length: 200 }, (_, i) => ({ name: `note-${i}.txt`, data: 'x' })),+ { name: 'SKILL.md', data: markdown('beyond-count') },+ ]),+ });+ expect(omittedSkill.status, omittedSkill.body).toBe(404);+ expect(JSON.parse(omittedSkill.body).title).toBe('No SKILL.md found in the upload.');+ expect(existsSync(join(root, '.claude/skills/beyond-count'))).toBe(false);+});diff --git a/packages/server/src/api-skill-install-composition.test.ts b/packages/server/src/api-skill-install-composition.test.tsnew file mode 100644index 000000000..c8141eff0--- /dev/null+++ b/packages/server/src/api-skill-install-composition.test.ts@@ -0,0 +1,180 @@+import { createHash } from 'node:crypto';+import {+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { InstallSkillSuccessSchema, SkillInstallSuccessSchema } from '@inkeep/open-knowledge-core';+import { afterAll, beforeAll, expect, test, vi } from 'vitest';+import { type Entry, fromBuffer } from 'yauzl';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';+import { readSkillStateFile } from './skill-state.ts';++const isolated = vi.hoisted(() => ({ home: '' }));+vi.mock('node:os', async (original) => ({+ ...(await original<typeof import('node:os')>()),+ homedir: () => isolated.home,+}));+let root: string;+let server: BootedServer;+beforeAll(async () => {+ isolated.home = mkdtempSync(join(tmpdir(), 'ok-install-home-'));+ root = mkdtempSync(join(tmpdir(), 'ok-install-contract-'));+ mkdirSync(join(root, '.claude'));+ mkdirSync(join(root, '.cursor'));+ server = await bootCompositionRig(root, { configHomedirOverride: isolated.home });+ await server.ready;+}, 60_000);+afterAll(async () => {+ await server?.destroy();+ rmSync(root, { recursive: true, force: true });+ rmSync(isolated.home, { recursive: true, force: true });+});+async function post(path: string, body: object) {+ return rawRequest(server.port, path, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', 'X-Request-Id': 'install-contract' },+ body: JSON.stringify(body),+ });+}+test('handoff builds a real archive without opening and ignores force on a current installation', async () => {+ const out = join(isolated.home, 'bundle.skill');+ const first = await post('/api/install-skill', { noOpen: true, out });+ expect(first.status, first.body).toBe(200);+ const built = InstallSkillSuccessSchema.parse(JSON.parse(first.body));+ expect(built).toMatchObject({ status: 'built', outputPath: out });+ const bytes = readFileSync(out);+ expect(built).toMatchObject({+ size: bytes.length,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ });+ const entries = await readArchive(bytes);+ const skill = entries.get('open-knowledge/SKILL.md');+ expect(skill).toMatch(/^name: open-knowledge$/m);+ expect(skill).toContain('OpenKnowledge');+ expect((await readSkillStateFile(isolated.home)).targets['claude-cowork']?.version).toBe(+ built.skillVersion,+ );+ const another = join(isolated.home, 'another.skill');+ const second = await post('/api/install-skill', { noOpen: true, out: another, force: true });+ expect(second.status, second.body).toBe(200);+ expect(InstallSkillSuccessSchema.parse(JSON.parse(second.body))).toMatchObject({+ status: 'skip-current',+ });+ expect(existsSync(another)).toBe(false);+ expect(SkillInstallSuccessSchema.safeParse(JSON.parse(first.body)).success).toBe(false);+ expect(first.headers['x-request-id']).toBe('install-contract');+});++const markdown = (name: string) =>+ `---\nname: ${name}\ndescription: Install contract\n---\n\nLiteral \\* and <custom>raw</custom>. \n`;+function seed(name: string) {+ const dir = join(root, '.claude/skills', name);+ mkdirSync(join(dir, 'assets'), { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), markdown(name));+ writeFileSync(join(dir, 'assets/data.bin'), Buffer.from([0, 255, 10]));+ return dir;+}++test('catalog installation projects exact bytes and preserves placement, conversion and source outcomes', async () => {+ const name = 'catalog-contract';+ seed(name);+ const install = async (extra: object) => {+ const response = await post('/api/skill/install', { scope: 'project', name, ...extra });+ expect(response.status, response.body).toBe(200);+ return SkillInstallSuccessSchema.parse(JSON.parse(response.body));+ };+ const result = await install({ targets: ['claude', 'cursor'], mode: 'copy' });+ expect(result.hosts).toContain('cursor');+ expect(InstallSkillSuccessSchema.safeParse(result).success).toBe(false);+ expect(readFileSync(join(root, '.cursor/skills', name, 'SKILL.md'), 'utf8')).toBe(markdown(name));+ expect(readFileSync(join(root, '.cursor/skills', name, 'assets/data.bin'))).toEqual(+ Buffer.from([0, 255, 10]),+ );+ await install({ convert: { target: 'cursor', mode: 'link' } });+ expect(lstatSync(join(root, '.cursor/skills', name)).isSymbolicLink()).toBe(true);+ expect(await install({ place: { dir: 'bundles', mode: 'copy' } })).toMatchObject({+ placedAt: `bundles/${name}`,+ });+ expect(readFileSync(join(root, 'bundles', name, 'SKILL.md'), 'utf8')).toBe(markdown(name));+ await install({ unplace: { path: `bundles/${name}` } });+ expect(existsSync(join(root, 'bundles', name))).toBe(false);+ expect(await install({ source: 'cursor' })).toMatchObject({+ sourceMovedTo: `.cursor/skills/${name}`,+ });+ expect(readFileSync(join(root, '.cursor/skills', name, 'SKILL.md'), 'utf8')).toBe(markdown(name));+});++test('install contracts reject unsafe output, invalid source and conflicting operations independently', async () => {+ const name = 'negative-contract';+ seed(name);+ for (const [path, body, status, detail] of [+ ['/api/install-skill', { noOpen: true, out: join(root, 'outside.skill') }, 400, undefined],+ ['/api/skill/install', { noOpen: true }, 400, undefined],+ ['/api/skill/install', { scope: 'project', name: 'missing' }, 404, undefined],+ [+ '/api/skill/install',+ { scope: 'project', name, place: { dir: '../escape', mode: 'copy' } },+ 400,+ 'PLACE_PATH_INVALID',+ ],+ ['/api/skill/install', { scope: 'project', name, remove: ['claude'] }, 400, 'REMOVE_SOURCE'],+ [+ '/api/skill/install',+ { scope: 'project', name, convert: { target: 'cursor', mode: 'link' } },+ 404,+ 'cursor',+ ],+ ] as const) {+ const result = await post(path, body);+ expect(result.status, result.body).toBe(status);+ expect(result.headers['content-type']).toContain('application/problem+json');+ expect(result.headers['x-request-id']).toBe('install-contract');+ if (detail !== undefined) expect(JSON.parse(result.body).detail).toBe(detail);+ }+ expect(existsSync(join(root, 'outside.skill'))).toBe(false);+ const malformed = await rawRequest(server.port, '/api/install-skill', {+ method: 'POST',+ headers: { Origin: 'https://untrusted.example.com' },+ body: '{broken',+ });+ expect(malformed.status, malformed.body).toBe(403);+});++async function readArchive(bytes: Buffer): Promise<Map<string, string>> {+ return new Promise((resolve, reject) => {+ fromBuffer(bytes, { lazyEntries: true }, (error, zip) => {+ if (error) {+ reject(error);+ return;+ }+ const contents = new Map<string, string>();+ zip.on('error', reject);+ zip.on('end', () => resolve(contents));+ zip.on('entry', (entry: Entry) => {+ zip.openReadStream(entry, (streamError, stream) => {+ if (streamError) {+ zip.close();+ reject(streamError);+ return;+ }+ const chunks: Buffer[] = [];+ stream.on('error', reject);+ stream.on('data', (chunk: Buffer) => chunks.push(chunk));+ stream.on('end', () => {+ contents.set(entry.fileName, Buffer.concat(chunks).toString('utf8'));+ zip.readEntry();+ });+ });+ });+ zip.readEntry();+ });+ });+}diff --git a/packages/server/src/api-skill-recovery-composition.test.ts b/packages/server/src/api-skill-recovery-composition.test.tsnew file mode 100644index 000000000..acb1d6f04--- /dev/null+++ b/packages/server/src/api-skill-recovery-composition.test.ts@@ -0,0 +1,225 @@+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ HistorySuccessSchema,+ SkillReimportSuccessSchema,+ SkillRestoreSuccessSchema,+ SkillRevertSuccessSchema,+ SkillsReimportBulkSuccessSchema,+} from '@inkeep/open-knowledge-core';+import { afterAll, beforeAll, expect, test } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';+import { ensureProjectGit } from './project-git.ts';+import { readSkillsLockFile as readSkillsLock } from './skills-lock-store.ts';++let root: string;+let source: string;+let server: BootedServer;+const markdown = (name: string, revision: string) =>+ `---\nname: ${name}\ndescription: Recovery contract\n---\n\n${revision}: \\* and <custom>raw</custom>. \n\n`;+beforeAll(async () => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-recovery-contract-')));+ source = mkdtempSync(join(tmpdir(), 'ok-recovery-source-'));+ mkdirSync(join(root, '.claude'));+ await ensureProjectGit(root);+ server = await bootCompositionRig(root, { gitEnabled: true });+ await server.ready;+}, 60_000);+afterAll(async () => {+ await server?.destroy();+ rmSync(root, { recursive: true, force: true });+ rmSync(source, { recursive: true, force: true });+});+async function post(path: string, body: object) {+ return rawRequest(server.port, path, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', 'X-Request-Id': 'recovery-contract' },+ body: JSON.stringify(body),+ });+}+function seed(name: string, revision: string) {+ const dir = join(source, name);+ mkdirSync(join(dir, 'assets'), { recursive: true });+ writeFileSync(join(dir, 'SKILL.md'), markdown(name, revision));+ writeFileSync(join(dir, 'assets/data.bin'), Buffer.from([0, 255, revision.length]));+ return dir;+}+async function importSkill(name: string) {+ const result = await post('/api/skill/import', {+ source: seed(name, 'old'),+ install: false,+ agentId: 'recovery-importer',+ });+ expect(result.status, result.body).toBe(200);+}++test('reimport preserves upstream bytes, removed files, dry runs and actor provenance', async () => {+ const name = 'recover-single';+ await importSkill(name);+ const installed = join(root, '.claude/skills', name);+ const before = readFileSync(join(installed, 'SKILL.md'), 'utf8');+ seed(name, 'new revision');+ rmSync(join(source, name, 'assets/data.bin'));+ const dry = await post('/api/skill/reimport', { name, scope: 'project', dryRun: true });+ expect(dry.status, dry.body).toBe(200);+ expect(readFileSync(join(installed, 'SKILL.md'), 'utf8')).toBe(before);+ expect(existsSync(join(installed, 'assets/data.bin'))).toBe(true);+ const result = await post('/api/skill/reimport', {+ name,+ scope: 'project',+ agentId: 'recovery-writer',+ });+ expect(result.status, result.body).toBe(200);+ expect(SkillReimportSuccessSchema.parse(JSON.parse(result.body))).toMatchObject({+ name,+ updated: true,+ source: join(source, name),+ });+ expect(readFileSync(join(installed, 'SKILL.md'), 'utf8')).toBe(markdown(name, 'new revision'));+ expect(existsSync(join(installed, 'assets/data.bin'))).toBe(false);+ const history = await rawRequest(+ server.port,+ `/api/history?docName=${encodeURIComponent(`.claude/skills/${name}/SKILL`)}`,+ );+ expect(history.status, history.body).toBe(200);+ expect(+ HistorySuccessSchema.parse(JSON.parse(history.body)).entries.flatMap(+ (entry) => entry.contributors,+ ),+ ).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: 'agent-recovery-writer',+ docs: expect.arrayContaining([`.claude/skills/${name}/SKILL`]),+ }),+ ]),+ );+ expect(result.headers['x-request-id']).toBe('recovery-contract');+ const setting = await post('/api/skill/reimport', {+ name,+ scope: 'project',+ setAutoUpdate: false,+ });+ expect(setting.status, setting.body).toBe(200);+ expect(SkillReimportSuccessSchema.parse(JSON.parse(setting.body))).toMatchObject({+ name,+ updated: false,+ });+ expect(readSkillsLock(join(root, '.ok/skills-lock.json')).skills[name]?.autoUpdate).toBe(false);+});++test('restore and revert use the imported historical tree and preserve subsequent local tracking', async () => {+ const name = 'recover-history';+ await importSkill(name);+ const baseline = readSkillsLock(join(root, '.ok/skills-lock.json')).skills[name]?.baselineRef;+ expect(baseline).toMatch(/^[a-f0-9]{40}$/);+ const installed = join(root, '.claude/skills', name);+ const original = readFileSync(join(installed, 'SKILL.md'), 'utf8');+ writeFileSync(join(installed, 'SKILL.md'), markdown(name, 'local change'));+ writeFileSync(join(installed, 'extra.txt'), 'local addition');+ const restored = await post('/api/skill/restore', {+ name,+ version: baseline,+ agentId: 'restore-writer',+ });+ expect(restored.status, restored.body).toBe(200);+ expect(SkillRestoreSuccessSchema.parse(JSON.parse(restored.body))).toMatchObject({+ name,+ version: baseline,+ restoredFiles: ['SKILL.md', 'assets/data.bin'],+ warnings: [],+ });+ expect(readFileSync(join(installed, 'SKILL.md'), 'utf8')).toBe(original);+ expect(existsSync(join(installed, 'extra.txt'))).toBe(false);+ writeFileSync(join(installed, 'SKILL.md'), markdown(name, 'another change'));+ const reverted = await post('/api/skill/revert', { name, agentId: 'revert-writer' });+ expect(reverted.status, reverted.body).toBe(200);+ expect(SkillRevertSuccessSchema.parse(JSON.parse(reverted.body))).toMatchObject({+ name,+ baselineRef: baseline,+ restoredFiles: ['SKILL.md', 'assets/data.bin'],+ warnings: [],+ });+ expect(readFileSync(join(installed, 'SKILL.md'), 'utf8')).toBe(original);+ expect(readSkillsLock(join(root, '.ok/skills-lock.json')).skills[name]).toMatchObject({+ baselineRef: baseline,+ localHash: expect.any(String),+ });+ expect(reverted.headers['x-request-id']).toBe('recovery-contract');+});++test('bulk recovery deduplicates and preserves invalid, unrecorded and grouped partial result order', async () => {+ for (const name of ['recover-first', 'recover-second', 'recover-missing-source'])+ await importSkill(name);+ seed('recover-second', 'upstream changed');+ rmSync(join(source, 'recover-missing-source'), { recursive: true });+ const response = await post('/api/skills/reimport-bulk', {+ scope: 'project',+ names: [+ 'recover-second',+ 'not-imported',+ 'INVALID NAME',+ 'recover-first',+ 'recover-second',+ 'recover-missing-source',+ ],+ agentId: 'bulk-recovery-writer',+ });+ expect(response.status, response.body).toBe(200);+ const result = SkillsReimportBulkSuccessSchema.parse(JSON.parse(response.body));+ expect(result).toMatchObject({+ updated: 1,+ upToDate: 1,+ failed: 3,+ results: [+ { requested: 'INVALID NAME', status: 'failed', error: 'INVALID_NAME' },+ { requested: 'not-imported', status: 'not-found' },+ { requested: 'recover-second', status: 'updated' },+ { requested: 'recover-first', status: 'up-to-date' },+ { requested: 'recover-missing-source', status: 'failed' },+ ],+ });+ expect(readFileSync(join(root, '.claude/skills/recover-second/SKILL.md'), 'utf8')).toBe(+ markdown('recover-second', 'upstream changed'),+ );+ expect(readFileSync(join(root, '.claude/skills/recover-missing-source/SKILL.md'), 'utf8')).toBe(+ markdown('recover-missing-source', 'old'),+ );+ expect(response.headers['x-request-id']).toBe('recovery-contract');+});++test('recovery refusal envelopes preserve scope, absent source and missing baseline distinctions', async () => {+ for (const [path, body, status, detail] of [+ [+ '/api/skill/restore',+ { name: 'recover-history', scope: 'global', version: 'f'.repeat(40) },+ 400,+ 'GLOBAL_SCOPE_UNVERSIONED',+ ],+ [+ '/api/skill/restore',+ { name: 'recover-history', version: 'f'.repeat(40) },+ 404,+ 'version-not-found',+ ],+ ['/api/skill/revert', { name: 'recover-history', scope: 'global' }, 400, 'GLOBAL_SCOPE'],+ ['/api/skill/revert', { name: 'not-imported' }, 400, 'NO_BASELINE'],+ ['/api/skill/reimport', { name: 'not-imported' }, 404, 'SKILL_ABSENT'],+ ] as const) {+ const response = await post(path, body);+ expect(response.status, response.body).toBe(status);+ expect(JSON.parse(response.body).detail).toBe(detail);+ expect(response.headers['content-type']).toContain('application/problem+json');+ expect(response.headers['x-request-id']).toBe('recovery-contract');+ }+});diff --git a/packages/server/src/api-skill-tracking-composition.test.ts b/packages/server/src/api-skill-tracking-composition.test.tsnew file mode 100644index 000000000..7637cbed4--- /dev/null+++ b/packages/server/src/api-skill-tracking-composition.test.ts@@ -0,0 +1,317 @@+import { spawnSync } from 'node:child_process';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import type { IncomingMessage } from 'node:http';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Readable } from 'node:stream';+import { afterAll, afterEach, beforeAll, expect, test, vi } from 'vitest';+import { createApiExtension } from './api-extension.test-helper.ts';+import type { BootedServer } from './boot.ts';+import {+ bootCompositionRig,+ makeCaptureRes,+ makeSyntheticReq,+ parseProblem,+ rawRequest,+} from './composition-rig.test-helper.ts';+import { createContentFilter } from './content-filter.ts';++let root: string;+let server: BootedServer;++function writeSkill(base: string, path: string, name: string, description = 'before'): void {+ const dir = join(base, path);+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, 'SKILL.md'),+ `---\nname: ${name}\ndescription: ${description}\n---\n\nBody.\n`,+ );+}++function gitIgnored(base: string, path: string): boolean {+ const result = spawnSync(+ 'git',+ ['-c', 'core.excludesFile=/dev/null', 'check-ignore', '-q', path],+ { cwd: base },+ );+ expect(result.error).toBeUndefined();+ expect([0, 1]).toContain(result.status);+ return result.status === 0;+}++beforeAll(async () => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-skill-tracking-')));+ const result = spawnSync('git', ['init', '-q', root]);+ expect(result.status).toBe(0);+ writeSkill(root, '.agents/skills/open-knowledge', 'open-knowledge');+ writeSkill(root, '.claude/skills/hidden', 'hidden');+ writeFileSync(join(root, '.gitignore'), '.claude/*');+ server = await bootCompositionRig(root, { projectDir: root });+ await server.ready;+}, 60_000);++afterAll(async () => {+ await server?.destroy();+ rmSync(root, { recursive: true, force: true });+});++async function track(body: object) {+ return rawRequest(server.port, '/api/skill/track-in-git', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', 'X-Request-Id': 'tracking-contract' },+ body: JSON.stringify(body),+ });+}++test('tracking previews without writing and then makes the actual Git path trackable', async () => {+ const path = '.claude/skills/hidden/SKILL.md';+ expect(gitIgnored(root, path)).toBe(true);+ const before = readFileSync(join(root, '.gitignore'), 'utf8');+ const preview = await track({ name: 'hidden', scope: 'project' });+ expect(preview.status, preview.body).toBe(200);+ expect(JSON.parse(preview.body)).toMatchObject({+ line: '!/.claude/skills/',+ gitignorePath: '.gitignore',+ applied: false,+ });+ expect(readFileSync(join(root, '.gitignore'), 'utf8')).toBe(before);+ const applied = await track({ name: 'hidden', scope: 'project', apply: true });+ expect(applied.status, applied.body).toBe(200);+ expect(applied.headers['x-request-id']).toBe('tracking-contract');+ expect(JSON.parse(applied.body)).toMatchObject({ applied: true });+ expect(readFileSync(join(root, '.gitignore'), 'utf8')).toBe('.claude/*\n!/.claude/skills/\n');+ expect(gitIgnored(root, path)).toBe(false);+ const list = await rawRequest(server.port, '/api/skills');+ expect(list.status, list.body).toBe(200);+ expect(+ JSON.parse(list.body).skills.find((skill: { name: string }) => skill.name === 'hidden'),+ ).toMatchObject({ name: 'hidden' });+ expect(+ JSON.parse(list.body).skills.find((skill: { name: string }) => skill.name === 'hidden').ignored,+ ).toBeUndefined();+ const repeated = await track({ name: 'hidden', scope: 'project', apply: true });+ expect(repeated.status, repeated.body).toBe(200);+ expect(JSON.parse(repeated.body)).toMatchObject({ applied: false, alreadyTracked: true });+ expect(readFileSync(join(root, '.gitignore'), 'utf8')).toBe('.claude/*\n!/.claude/skills/\n');+});++afterEach(() => vi.restoreAllMocks());++function isolatedFixture(rule: string | null, withSignal: boolean) {+ const contentDir = mkdtempSync(join(root, 'isolated-'));+ const home = mkdtempSync(join(root, 'home-'));+ writeSkill(contentDir, '.agents/skills/open-knowledge', 'open-knowledge');+ writeSkill(contentDir, '.claude/skills/hidden', 'hidden');+ writeSkill(contentDir, '.ok/skills/probe', 'probe');+ if (rule !== null) writeFileSync(join(contentDir, '.gitignore'), rule);+ const rebuildBytes: Array<string | null> = [];+ const signals: string[] = [];+ const contentFilter = createContentFilter({+ contentDir,+ projectDir: contentDir,+ inPlaceSkillDirs: new Set(['.agents/skills/open-knowledge', '.claude/skills/hidden']),+ onAfterRebuild: () => {+ const path = join(contentDir, '.gitignore');+ rebuildBytes.push(existsSync(path) ? readFileSync(path, 'utf8') : null);+ },+ });+ const extension = createApiExtension({+ contentDir,+ projectDir: contentDir,+ homeDirOverride: home,+ contentFilter,+ hocuspocus: server.serverInstance.hocuspocus,+ sessionManager: server.serverInstance.sessionManager,+ ...(withSignal ? { signalChannel: (channel: string) => signals.push(channel) } : {}),+ });+ return { contentDir, home, contentFilter, extension, rebuildBytes, signals };+}++async function request(+ extension: ReturnType<typeof createApiExtension>,+ path: string,+ body?: object,+) {+ const method = body === undefined ? 'GET' : 'POST';+ const base = makeSyntheticReq({ method, url: path });+ const req = Object.assign(+ Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]),+ {+ method,+ url: path,+ headers: {+ ...base.headers,+ 'content-type': 'application/json',+ 'x-request-id': 'tracking-cache',+ },+ socket: base.socket,+ },+ ) as IncomingMessage;+ const { res, captured } = makeCaptureRes();+ await extension.onRequest({ request: req, response: res });+ return captured;+}++async function probeDescription(extension: ReturnType<typeof createApiExtension>) {+ const response = await request(extension, '/api/skills');+ expect(response.status, response.body).toBe(200);+ const body = JSON.parse(response.body) as {+ skills: Array<{ name: string; description?: string }>;+ };+ return body.skills.find((skill) => skill.name === 'probe')?.description;+}++test.each([false, true])(+ 'tracking refreshes cached content before TTL with files callback %s',+ async (withSignal) => {+ const r = isolatedFixture('.claude/*', withSignal);+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await probeDescription(r.extension)).toBe('before');+ r.rebuildBytes.length = 0;+ r.signals.length = 0;+ writeSkill(r.contentDir, '.ok/skills/probe', 'probe', 'after');+ expect(await probeDescription(r.extension)).toBe('before');+ const preview = await request(r.extension, '/api/skill/track-in-git', {+ name: 'hidden',+ scope: 'project',+ });+ expect(preview.status).toBe(200);+ expect(await probeDescription(r.extension)).toBe('before');+ expect(r.rebuildBytes).toEqual([]);+ const applied = await request(r.extension, '/api/skill/track-in-git', {+ name: 'hidden',+ scope: 'project',+ apply: true,+ });+ expect(applied.status, applied.body).toBe(200);+ expect(r.contentFilter.isPathIgnored('.claude/skills/hidden/SKILL.md')).toBe(false);+ expect(r.rebuildBytes).toEqual(['.claude/*\n!/.claude/skills/\n']);+ expect(r.signals).toEqual(withSignal ? ['files'] : []);+ expect(await probeDescription(r.extension)).toBe('after');+ writeSkill(r.contentDir, '.ok/skills/probe', 'probe', 'later');+ const repeated = await request(r.extension, '/api/skill/track-in-git', {+ name: 'hidden',+ scope: 'project',+ apply: true,+ });+ expect(JSON.parse(repeated.body)).toMatchObject({ applied: false, alreadyTracked: true });+ expect(await probeDescription(r.extension)).toBe('after');+ expect(r.rebuildBytes).toHaveLength(1);+ expect(r.signals).toEqual(withSignal ? ['files'] : []);+ },+);++test.each([false, true])(+ 'an ineffective rule restores bytes, rebuilds twice and refreshes the cache with files callback %s',+ async (withSignal) => {+ const before = '# preserve\r\n.claude/';+ const r = isolatedFixture(before, withSignal);+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await probeDescription(r.extension)).toBe('before');+ r.rebuildBytes.length = 0;+ r.signals.length = 0;+ writeSkill(r.contentDir, '.ok/skills/probe', 'probe', 'after');+ expect(await probeDescription(r.extension)).toBe('before');+ const failed = await request(r.extension, '/api/skill/track-in-git', {+ name: 'hidden',+ scope: 'project',+ apply: true,+ });+ expect(failed.status, failed.body).toBe(409);+ expect(failed.headers['x-request-id']).toBe('tracking-cache');+ expect(failed.headers['content-type']).toBe('application/problem+json');+ expect(parseProblem(failed.body).title).toContain('was left unchanged');+ expect(readFileSync(join(r.contentDir, '.gitignore'), 'utf8')).toBe(before);+ expect(r.rebuildBytes).toEqual([`${before}\n!/.claude/skills/\n`, before]);+ expect(r.contentFilter.isPathIgnored('.claude/skills/hidden/SKILL.md')).toBe(true);+ expect(r.signals).toEqual([]);+ expect(await probeDescription(r.extension)).toBe('after');+ },+);++test('an existing ineffective negation refuses without writes, rebuilds or cache invalidation', async () => {+ const before = '.claude/\n!/.claude/skills/\n';+ const r = isolatedFixture(before, true);+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await probeDescription(r.extension)).toBe('before');+ r.rebuildBytes.length = 0;+ r.signals.length = 0;+ writeSkill(r.contentDir, '.ok/skills/probe', 'probe', 'after');+ const failed = await request(r.extension, '/api/skill/track-in-git', {+ name: 'hidden',+ scope: 'project',+ apply: true,+ });+ expect(failed.status, failed.body).toBe(409);+ expect(parseProblem(failed.body).title).toContain('is already in .gitignore');+ expect(readFileSync(join(r.contentDir, '.gitignore'), 'utf8')).toBe(before);+ expect(r.rebuildBytes).toEqual([]);+ expect(r.signals).toEqual([]);+ expect(await probeDescription(r.extension)).toBe('before');+});++test('rollback removes a newly created ignore file when an OK ignore rule still excludes the skill', async () => {+ const r = isolatedFixture(null, true);+ writeFileSync(join(r.contentDir, '.okignore'), '.claude/\n');+ await r.contentFilter.rebuildIgnorePatterns();+ expect(r.contentFilter.isPathIgnored('.claude/skills/hidden/SKILL.md')).toBe(true);+ r.rebuildBytes.length = 0;+ const failed = await request(r.extension, '/api/skill/track-in-git', {+ name: 'hidden',+ scope: 'project',+ apply: true,+ });+ expect(failed.status, failed.body).toBe(409);+ expect(existsSync(join(r.contentDir, '.gitignore'))).toBe(false);+ expect(r.rebuildBytes).toEqual(['!/.claude/skills/\n', null]);+ expect(r.signals).toEqual([]);+});++test('filesystem errors and invalid scopes keep their error envelopes without side effects', async () => {+ const r = isolatedFixture('.claude/', true);+ rmSync(join(r.contentDir, '.gitignore'));+ mkdirSync(join(r.contentDir, '.gitignore'));+ const failed = await request(r.extension, '/api/skill/track-in-git', {+ name: 'hidden',+ scope: 'project',+ apply: true,+ });+ expect(failed.status, failed.body).toBe(500);+ expect(parseProblem(failed.body)).toMatchObject({+ type: 'urn:ok:error:internal-server-error',+ title: 'Failed to update .gitignore.',+ });+ expect(failed.headers['x-request-id']).toBe('tracking-cache');+ expect(r.rebuildBytes).toEqual([]);+ expect(r.signals).toEqual([]);+ const invalid = await track({ name: '../invalid', scope: 'project', apply: true });+ expect(invalid.status).toBe(400);+ const global = await track({ name: 'hidden', scope: 'global', apply: true });+ expect(global.status).toBe(400);+ expect(parseProblem(global.body).title).toContain('Only project skills');+});++test('tracking rejects an untrusted origin before reading its body or changing gitignore', async () => {+ const r = isolatedFixture('.claude/*', true);+ const req = makeSyntheticReq({+ method: 'POST',+ url: '/api/skill/track-in-git',+ origin: 'https://untrusted.example',+ });+ const { res, captured } = makeCaptureRes();+ await r.extension.onRequest({ request: req, response: res });+ expect(captured.status).toBe(403);+ expect(req.readableEnded).toBe(false);+ req.destroy();+ expect(readFileSync(join(r.contentDir, '.gitignore'), 'utf8')).toBe('.claude/*');+ expect(r.rebuildBytes).toEqual([]);+ expect(r.signals).toEqual([]);+});diff --git a/packages/server/src/api-skills-cache.test.ts b/packages/server/src/api-skills-cache.test.tsnew file mode 100644index 000000000..01519119a--- /dev/null+++ b/packages/server/src/api-skills-cache.test.ts@@ -0,0 +1,328 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import type { IncomingMessage } from 'node:http';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Readable } from 'node:stream';+import { afterAll, afterEach, beforeAll, expect, test, vi } from 'vitest';+import { createApiExtension } from './api-extension.test-helper.ts';+import type { BootedServer } from './boot.ts';+import {+ bootCompositionRig,+ makeCaptureRes,+ makeSyntheticReq,+} from './composition-rig.test-helper.ts';+import { createContentFilter } from './content-filter.ts';++let root: string;+let server: BootedServer;++beforeAll(async () => {+ root = mkdtempSync(join(tmpdir(), 'ok-skills-cache-'));+ const contentDir = join(root, 'server');+ const builtin = join(contentDir, '.agents/skills/open-knowledge');+ mkdirSync(builtin, { recursive: true });+ writeFileSync(+ join(builtin, 'SKILL.md'),+ '---\nname: open-knowledge\ndescription: Project instructions\n---\n\nProject.\n',+ );+ writeSkill(contentDir, '.ok/skills/alpha', 'listener');+ server = await bootCompositionRig(contentDir);+ await server.ready;+}, 60_000);++afterEach(() => vi.restoreAllMocks());+afterAll(async () => {+ await server?.destroy();+ rmSync(root, { recursive: true, force: true });+});++function writeSkill(base: string, path: string, description: string): void {+ const dir = join(base, path);+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, 'SKILL.md'),+ `---\nname: alpha\ndescription: ${description}\n---\n\nBody.\n`,+ );+}++function rig(signal?: (channel: string) => void, withFilter = false) {+ const contentDir = mkdtempSync(join(root, 'project-'));+ const home = mkdtempSync(join(root, 'home-'));+ writeSkill(contentDir, '.ok/skills/alpha', 'before');+ if (withFilter) {+ const builtin = join(contentDir, '.agents/skills/open-knowledge');+ mkdirSync(builtin, { recursive: true });+ writeFileSync(+ join(builtin, 'SKILL.md'),+ '---\nname: open-knowledge\ndescription: Fixture\n---\nBody.\n',+ );+ }+ const contentFilter = withFilter+ ? createContentFilter({ contentDir, projectDir: contentDir })+ : undefined;+ const extension = createApiExtension({+ contentDir,+ projectDir: contentDir,+ homeDirOverride: home,+ contentFilter,+ enableTestRoutes: true,+ hocuspocus: server.serverInstance.hocuspocus,+ sessionManager: server.serverInstance.sessionManager,+ ...(signal ? { signalChannel: signal } : {}),+ });+ return { contentDir, home, extension, contentFilter };+}++async function request(+ extension: ReturnType<typeof createApiExtension>,+ path: string,+ method = 'GET',+ body?: object,+ expectedStatus = 200,+) {+ const base = makeSyntheticReq({ method, url: path });+ const req =+ body === undefined+ ? base+ : (Object.assign(Readable.from([Buffer.from(JSON.stringify(body))]), {+ method,+ url: path,+ headers: { ...base.headers, 'content-type': 'application/json' },+ socket: base.socket,+ }) as IncomingMessage);+ const { res, captured } = makeCaptureRes();+ await extension.onRequest({ request: req, response: res });+ expect(captured.status, captured.body).toBe(expectedStatus);+ return JSON.parse(captured.body) as { skills: Array<{ name: string; description?: string }> };+}++async function description(extension: ReturnType<typeof createApiExtension>) {+ return (await request(extension, '/api/skills')).skills.find((s) => s.name === 'alpha')+ ?.description;+}++test('list hits retain disk content until the exact five second expiry', async () => {+ const r = rig();+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await description(r.extension)).toBe('before');+ writeSkill(r.contentDir, '.ok/skills/alpha', 'after');+ now.mockReturnValue(104_999);+ expect(await description(r.extension)).toBe('before');+ now.mockReturnValue(105_000);+ expect(await description(r.extension)).toBe('after');+});++test.each([false, true])(+ 'legacy uninstall files invalidation is conditional on a signal callback: %s',+ async (withSignal) => {+ const signals: string[] = [];+ const r = rig(withSignal ? (channel) => signals.push(channel) : undefined);+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await description(r.extension)).toBe('before');+ writeSkill(r.contentDir, '.ok/skills/alpha', 'after');+ await request(r.extension, '/api/skill/uninstall', 'POST', { name: 'alpha', scope: 'project' });+ expect(await description(r.extension)).toBe(withSignal ? 'after' : 'before');+ expect(signals).toEqual(withSignal ? ['files'] : []);+ },+);++test('a detected editor fingerprint change refreshes list content before expiry', async () => {+ const r = rig();+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await description(r.extension)).toBe('before');+ writeSkill(r.contentDir, '.ok/skills/alpha', 'after');+ mkdirSync(join(r.contentDir, '.cursor'), { recursive: true });+ expect(await description(r.extension)).toBe('after');+});++test('one extension invalidates without changing another extension cache', async () => {+ const a = rig(() => {});+ const b = rig(() => {});+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await description(a.extension)).toBe('before');+ expect(await description(b.extension)).toBe('before');+ writeSkill(a.contentDir, '.ok/skills/alpha', 'after');+ writeSkill(b.contentDir, '.ok/skills/alpha', 'after');+ await request(a.extension, '/api/skill/uninstall', 'POST', { name: 'alpha', scope: 'project' });+ expect(await description(a.extension)).toBe('after');+ expect(await description(b.extension)).toBe('before');+});++test('a native delete directly invalidates list content without a files callback', async () => {+ const r = rig();+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await description(r.extension)).toBe('before');+ await request(r.extension, '/api/skill?name=alpha&scope=project', 'DELETE');+ expect(await description(r.extension)).toBeUndefined();+});++test('installed reads share the generation invalidated by legacy files signals', async () => {+ const r = rig(() => {});+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ const before = await request(r.extension, '/api/skills/installed');+ expect(before.skills.some((s) => s.name === 'alpha')).toBe(false);+ const installPath = join(r.home, '.claude/plugins/cache/team/eng/1.0.0');+ writeSkill(installPath, 'skills/alpha', 'installed');+ mkdirSync(join(installPath, '.claude-plugin'), { recursive: true });+ writeFileSync(+ join(installPath, '.claude-plugin/plugin.json'),+ JSON.stringify({ name: 'eng', version: '1.0.0' }),+ );+ writeFileSync(+ join(r.home, '.claude/plugins/installed_plugins.json'),+ JSON.stringify({+ version: 2,+ plugins: { 'eng@team': [{ scope: 'user', installPath, version: '1.0.0' }] },+ }),+ );+ const cached = await request(r.extension, '/api/skills/installed');+ expect(cached.skills.some((s) => s.name === 'alpha')).toBe(false);+ await request(r.extension, '/api/skill/uninstall', 'POST', { name: 'alpha', scope: 'project' });+ const refreshed = await request(r.extension, '/api/skills/installed');+ expect(refreshed.skills.some((s) => s.name === 'alpha')).toBe(true);+});++test('the composed listener serves the list and admitted documents from shared skill resolution', async () => {+ const response = await fetch(`http://127.0.0.1:${server.port}/api/skills`);+ expect(response.status).toBe(200);+ expect(response.headers.get('content-type')).toBe('application/json');+ expect(response.headers.get('x-request-id')).not.toBeNull();+ const body = (await response.json()) as { skills: Array<{ name: string; description?: string }> };+ expect(body.skills.find((s) => s.name === 'alpha')?.description).toBe('listener');+ const docs = await fetch(`http://127.0.0.1:${server.port}/api/documents`);+ expect(docs.status).toBe(200);+ const indexed = (await docs.json()) as { documents: Array<{ docName?: string }> };+ expect(indexed.documents.some((d) => d.docName === '.agents/skills/open-knowledge/SKILL')).toBe(+ true,+ );+});++test('folder artifact writes invalidate the shared list without an optional files signal', async () => {+ const r = rig();+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await description(r.extension)).toBe('before');+ writeSkill(r.contentDir, '.ok/skills/alpha', 'after');+ await request(r.extension, '/api/folder-config', 'PUT', {+ path: '',+ frontmatter: { category: 'artifact' },+ });+ expect(await description(r.extension)).toBe('after');+ writeSkill(r.contentDir, '.ok/skills/alpha', 'later');+ await request(r.extension, '/api/folder-config', 'PUT', { path: '' });+ expect(await description(r.extension)).toBe('after');+});++test.each([false, true])(+ 'legacy test reset preserves its conditional direct invalidation: reset ignores %s',+ async (resetIgnores) => {+ const r = rig(undefined, true);+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await description(r.extension)).toBe('before');+ writeSkill(r.contentDir, '.ok/skills/alpha', 'after');+ await request(+ r.extension,+ `/api/test-reset?docName=cache-reset&reset-okignore=${resetIgnores}`,+ 'POST',+ );+ expect(await description(r.extension)).toBe(resetIgnores ? 'after' : 'before');+ },+);++test('a list populated across a real rebuild uses completion time and the generation at completion', async () => {+ const r = rig(undefined, true);+ for (let i = 0; i < 120; i += 1) mkdirSync(join(r.contentDir, `directory-${i}`));+ const clock = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ let completed = false;+ const listing = description(r.extension).then((value) => {+ completed = true;+ return value;+ });+ expect(completed).toBe(false);+ await request(r.extension, '/api/folder-config', 'PUT', {+ path: '',+ frontmatter: { category: 'during-list' },+ });+ expect(completed).toBe(false);+ writeSkill(r.contentDir, '.ok/skills/alpha', 'after');+ clock.mockReturnValue(104_000);+ expect(await listing).toBe('before');+ clock.mockReturnValue(108_999);+ expect(await description(r.extension)).toBe('before');+ clock.mockReturnValue(109_000);+ expect(await description(r.extension)).toBe('after');+});++function addPlugin(home: string): void {+ const installPath = join(home, '.claude/plugins/cache/team/cache-probe/1.0.0');+ writeSkill(installPath, 'skills/alpha', 'plugin');+ mkdirSync(join(installPath, '.claude-plugin'), { recursive: true });+ writeFileSync(+ join(installPath, '.claude-plugin/plugin.json'),+ JSON.stringify({ name: 'cache-probe', version: '1.0.0' }),+ );+ writeFileSync(+ join(home, '.claude/plugins/installed_plugins.json'),+ JSON.stringify({+ version: 2,+ plugins: { 'cache-probe@team': [{ scope: 'user', installPath, version: '1.0.0' }] },+ }),+ );+}++test.each([false, true])(+ 'partial bulk imports refresh both catalogs without depending on the files callback: %s',+ async (withSignal) => {+ const r = rig(withSignal ? () => {} : undefined);+ mkdirSync(join(r.home, '.claude'));+ mkdirSync(join(r.contentDir, '.claude'));+ const source = mkdtempSync(join(root, 'source-'));+ writeSkill(source, 'alpha', 'source');+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await description(r.extension)).toBe('before');+ expect((await request(r.extension, '/api/skills/installed')).skills).toEqual([]);+ writeSkill(r.contentDir, '.ok/skills/alpha', 'after');+ addPlugin(r.home);+ expect((await request(r.extension, '/api/skills/installed')).skills).toEqual([]);+ const outcome = await request(r.extension, '/api/skills/import-bulk', 'POST', {+ source,+ skills: ['alpha', 'missing'],+ install: false,+ });+ expect(outcome).toMatchObject({ imported: 1, failed: 1 });+ expect(await description(r.extension)).toBe('after');+ expect((await request(r.extension, '/api/skills/installed')).skills).toEqual(+ expect.arrayContaining([expect.objectContaining({ name: 'alpha' })]),+ );+ },+);++test.each([false, true])(+ 'failed bulk recovery still refreshes catalogs but an early install refusal does not: %s',+ async (withSignal) => {+ const r = rig(withSignal ? () => {} : undefined);+ mkdirSync(join(r.home, '.claude'));+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(await description(r.extension)).toBe('before');+ expect((await request(r.extension, '/api/skills/installed')).skills).toEqual([]);+ writeSkill(r.contentDir, '.ok/skills/alpha', 'after');+ addPlugin(r.home);+ await request(+ r.extension,+ '/api/skill/install',+ 'POST',+ { name: 'absent', scope: 'project', targets: ['cursor'] },+ 404,+ );+ expect(await description(r.extension)).toBe('before');+ expect((await request(r.extension, '/api/skills/installed')).skills).toEqual([]);+ const result = await request(r.extension, '/api/skills/reimport-bulk', 'POST', {+ scope: 'project',+ names: ['not-imported', 'INVALID NAME'],+ });+ expect(result).toMatchObject({ updated: 0, failed: 2 });+ expect(await description(r.extension)).toBe('after');+ expect((await request(r.extension, '/api/skills/installed')).skills).toEqual(+ expect.arrayContaining([expect.objectContaining({ name: 'alpha' })]),+ );+ },+);diff --git a/packages/server/src/api-skills-composition.test.ts b/packages/server/src/api-skills-composition.test.tsnew file mode 100644index 000000000..88fa9c7e5--- /dev/null+++ b/packages/server/src/api-skills-composition.test.ts@@ -0,0 +1,228 @@+import { mkdtemp, rm } from 'node:fs/promises';+import { homedir, tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import { createApiExtension } from './api-extension.test-helper.ts';+import type { BootedServer } from './boot.ts';+import {+ bootCompositionRig,+ makeCaptureRes,+ makeSyntheticReq,+ parseProblem,+ rawRequest,+} from './composition-rig.test-helper.ts';++const SKILL_METHODS = [+ ['/api/skills', 'GET'],+ ['/api/skill', 'GET, PUT, POST, DELETE'],+ ['/api/skill-file', 'GET, PUT, DELETE'],+ ['/api/skill-file/rename', 'POST'],+ ['/api/skill/import', 'POST'],+ ['/api/skills/import-bulk', 'POST'],+ ['/api/skill/edit-external', 'POST'],+ ['/api/skill/duplicate', 'POST'],+ ['/api/skill/move-scope', 'POST'],+ ['/api/skill/install', 'POST'],+ ['/api/skill/restore', 'POST'],+ ['/api/skill/reimport', 'POST'],+ ['/api/skills/reimport-bulk', 'POST'],+ ['/api/skill/revert', 'POST'],+ ['/api/skill/track-in-git', 'POST'],+ ['/api/install-skill', 'POST'],+] as const;++let contentDir: string;+let server: BootedServer;++beforeAll(async () => {+ contentDir = await mkdtemp(resolve(tmpdir(), 'ok-skills-contract-'));+ server = await bootCompositionRig(contentDir);+ await server.ready;+}, 60_000);++afterAll(async () => {+ await server?.destroy();+ await rm(contentDir, { recursive: true, force: true });+});++describe('skills contracts over the composed listener', () => {+ test.each(SKILL_METHODS)('%s preserves HEAD refusal and preflight', async (path, allow) => {+ const head = await rawRequest(server.port, path, { method: 'HEAD' });+ expect(head.status).toBe(405);+ expect(head.headers.allow).toBe(allow);+ expect(head.body).toBe('');+ const options = await rawRequest(server.port, path, {+ method: 'OPTIONS',+ headers: { Origin: 'http://localhost:5173' },+ });+ expect(options.status).toBe(204);+ expect(options.headers['access-control-allow-origin']).toBe('http://localhost:5173');+ expect(options.body).toBe('');+ });++ test('raw upload preserves its custom method envelope without Allow', async () => {+ const res = await rawRequest(server.port, '/api/skill-upload', { method: 'GET' });+ expect(res.status).toBe(405);+ expect(res.headers.allow).toBeUndefined();+ expect(res.headers['content-type']).toBe('application/problem+json');+ expect(parseProblem(res.body)).toMatchObject({+ type: 'urn:ok:error:invalid-request',+ title: 'Use POST to upload a skill.',+ });+ });++ test('handoff admission refuses an absent peer before consuming the body', async () => {+ const extension = createApiExtension({+ contentDir,+ projectDir: contentDir,+ hocuspocus: server.serverInstance.hocuspocus,+ sessionManager: server.serverInstance.sessionManager,+ });+ const request = makeSyntheticReq({ method: 'POST', url: '/api/install-skill' });+ Object.defineProperty(request.socket, 'remoteAddress', { value: undefined });+ const { res, captured } = makeCaptureRes();+ await extension.onRequest({ request, response: res });+ expect(captured.status).toBe(403);+ expect(parseProblem(captured.body)).toMatchObject({+ type: 'urn:ok:error:loopback-required',+ title: 'Local-op endpoints require a loopback connection.',+ });+ expect(request.readableEnded).toBe(false);+ request.destroy();+ });++ test('null Origin reaches catalog install and import validation but is refused by handoff admission', async () => {+ for (const path of ['/api/skill/install', '/api/skill/import']) {+ const catalog = await rawRequest(server.port, path, {+ method: 'POST',+ headers: { Origin: 'null', 'Content-Type': 'application/json' },+ body: '{}',+ });+ expect(catalog.status, `${path}: ${catalog.body}`).toBe(400);+ expect(parseProblem(catalog.body).type).toBe('urn:ok:error:invalid-request');+ expect(parseProblem(catalog.body).title).toBe('Request body is invalid.');+ }+ const handoff = await rawRequest(server.port, '/api/install-skill', {+ method: 'POST',+ headers: { Origin: 'null', 'Content-Type': 'application/json' },+ body: '{}',+ });+ expect(handoff.status, handoff.body).toBe(403);+ expect(parseProblem(handoff.body).type).toBe('urn:ok:error:invalid-origin');+ });++ test('both install routes accept consented external origins before parsing malformed JSON', async () => {+ const externalDir = await mkdtemp(resolve(tmpdir(), 'ok-skills-external-contract-'));+ const external = await bootCompositionRig(externalDir, {+ serverRuntime: {+ bind: ['127.0.0.1'],+ port: 0,+ externalUrl: 'https://skills.example.com',+ allowExternal: true,+ openBrowser: false,+ idleShutdown: 'off',+ loopbackOnly: true,+ },+ });+ try {+ await external.ready;+ const headers = { Origin: 'https://skills.example.com', 'Content-Type': 'application/json' };+ const handoff = await rawRequest(external.port, '/api/install-skill', {+ method: 'POST',+ headers,+ body: '{',+ });+ expect(handoff.status).toBe(400);+ expect(parseProblem(handoff.body)).toMatchObject({+ type: 'urn:ok:error:invalid-request',+ title: 'Request body is not valid JSON.',+ });+ const catalog = await rawRequest(external.port, '/api/skill/install', {+ method: 'POST',+ headers,+ body: '{',+ });+ expect(catalog.status).toBe(400);+ expect(parseProblem(catalog.body).title).toBe('Request body is not valid JSON.');+ } finally {+ await external.destroy();+ await rm(externalDir, { recursive: true, force: true });+ }+ });++ test('catalog install requires a name while handoff validates its output path', async () => {+ const body = JSON.stringify({+ noOpen: true,+ out: resolve(homedir(), '..', 'ok-skills-contract-output.skill'),+ });+ const headers = { 'Content-Type': 'application/json' };+ const catalog = await rawRequest(server.port, '/api/skill/install', {+ method: 'POST',+ headers,+ body,+ });+ expect(catalog.status).toBe(400);+ expect(parseProblem(catalog.body)).toMatchObject({ title: 'Request body is invalid.' });+ expect(parseProblem(catalog.body).detail).toContain('name');+ const handoff = await rawRequest(server.port, '/api/install-skill', {+ method: 'POST',+ headers,+ body,+ });+ expect(handoff.status).toBe(400);+ expect(parseProblem(handoff.body).title).toBe('Output path must be within home directory.');+ });++ test('JSON skill writes preserve the one-megabyte limit', async () => {+ const res = await rawRequest(server.port, '/api/skill', {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'oversized', body: 'x'.repeat(1_048_576) }),+ });+ expect(res.status).toBe(413);+ expect(parseProblem(res.body).type).toBe('urn:ok:error:payload-too-large');+ });++ test.each(['GET', 'DELETE'])('skill %s parses scope from the query', async (method) => {+ const res = await rawRequest(server.port, '/api/skill?name=missing&scope=invalid', { method });+ expect(res.status).toBe(400);+ expect(parseProblem(res.body).type).toBe('urn:ok:error:invalid-request');+ expect(parseProblem(res.body).title).toContain('scope');+ });++ test.each(SKILL_METHODS.filter(([, methods]) => methods.includes('POST')))(+ '%s preserves malformed JSON errors',+ async (path) => {+ const res = await rawRequest(server.port, path, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', 'X-Request-Id': 'skills-json-contract' },+ body: '{',+ });+ expect(res.status).toBe(400);+ expect(res.headers['x-request-id']).toBe('skills-json-contract');+ expect(res.headers['content-type']).toBe('application/problem+json');+ expect(parseProblem(res.body)).toMatchObject({+ type: 'urn:ok:error:invalid-request',+ title: 'Request body is not valid JSON.',+ });+ },+ );++ test.each(SKILL_METHODS)(+ '%s preserves unsupported methods and Allow: %s',+ async (path, allow) => {+ const res = await rawRequest(server.port, path, {+ method: 'PATCH',+ headers: { 'X-Request-Id': 'skills-method-contract' },+ });+ expect(res.status).toBe(405);+ expect(res.headers.allow).toBe(allow);+ expect(res.headers['content-type']).toBe('application/problem+json');+ expect(res.headers['x-request-id']).toBe('skills-method-contract');+ expect(parseProblem(res.body)).toMatchObject({+ type: 'urn:ok:error:method-not-allowed',+ status: 405,+ });+ },+ );+});diff --git a/packages/server/src/api-skills-native-preservation.test.ts b/packages/server/src/api-skills-native-preservation.test.tsnew file mode 100644index 000000000..6495a68eb--- /dev/null+++ b/packages/server/src/api-skills-native-preservation.test.ts@@ -0,0 +1,394 @@+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import type { IncomingMessage } from 'node:http';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PassThrough } from 'node:stream';+import { afterAll, afterEach, beforeAll, expect, test, vi } from 'vitest';+import { createApiExtension } from './api-extension.test-helper.ts';+import type { BootedServer } from './boot.ts';+import {+ bootCompositionRig,+ makeCaptureRes,+ makeSyntheticReq,+ parseProblem,+ rawRequest,+} from './composition-rig.test-helper.ts';+import { buildIngressPolicy } from './ingress-policy.ts';++const FAMILIES = {+ 'skills-list': ['/api/skills'],+ 'skills-document': [+ '/api/skill',+ '/api/skill/edit-external',+ '/api/skill/duplicate',+ '/api/skill/move-scope',+ ],+ 'skills-file': ['/api/skill-file', '/api/skill-file/rename'],+ 'skills-import': ['/api/skill/import', '/api/skills/import-bulk', '/api/skill-upload'],+ 'skills-install': ['/api/skill/install'],+ 'handoff-install': ['/api/install-skill'],+ 'skills-recovery': [+ '/api/skill/restore',+ '/api/skill/reimport',+ '/api/skills/reimport-bulk',+ '/api/skill/revert',+ ],+ 'skills-tracking': ['/api/skill/track-in-git'],+} as const;+const PATHS = Object.values(FAMILIES).flat();+let root: string;+let server: BootedServer;+let ephemeral: BootedServer;++beforeAll(async () => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-skills-native-preservation-')));+ const contentDir = join(root, 'normal');+ const builtin = join(contentDir, '.agents/skills/open-knowledge');+ mkdirSync(builtin, { recursive: true });+ writeFileSync(+ join(builtin, 'SKILL.md'),+ '---\nname: open-knowledge\ndescription: Fixture\n---\nBody.\n',+ );+ server = await bootCompositionRig(contentDir, { projectDir: contentDir });+ await server.ready;+ const single = join(root, 'ephemeral');+ mkdirSync(single);+ writeFileSync(join(single, 'note.md'), '# Note\n');+ ephemeral = await bootCompositionRig(single, { ephemeral: true, singleDocRelPath: 'note.md' });+ await ephemeral.ready;+}, 60_000);+afterEach(() => vi.restoreAllMocks());+afterAll(async () => {+ await Promise.allSettled([server?.destroy(), ephemeral?.destroy()]);+ rmSync(root, { recursive: true, force: true });+});++test('all seventeen paths have exclusive native ownership while uninstall remains legacy', async () => {+ expect(PATHS).toHaveLength(17);+ const nativePaths = server.serverInstance.nativeApi.paths;+ for (const path of PATHS)+ expect(+ nativePaths.filter((entry) => entry === path),+ path,+ ).toHaveLength(1);+ expect(nativePaths).not.toContain('/api/skill/uninstall');+ const uninstalled = await rawRequest(server.port, '/api/skill/uninstall', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'missing', scope: 'project' }),+ });+ expect(uninstalled.status, uninstalled.body).toBe(200);+});++test('every native family preserves Host, Origin and forwarded-header refusal over the listener', async () => {+ for (const path of PATHS) {+ for (const [headers, type] of [+ [{ Host: 'evil.example' }, 'urn:ok:error:host-not-allowed'],+ [{ Origin: 'https://evil.example' }, 'urn:ok:error:invalid-origin'],+ [{ 'X-Forwarded-For': '127.0.0.1' }, 'urn:ok:error:host-not-allowed'],+ ] as const) {+ const response = await rawRequest(server.port, path, {+ method: 'PATCH',+ headers: { ...headers, 'X-Request-Id': 'skills-admission' },+ });+ expect(response.status, `${path}: ${response.body}`).toBe(403);+ expect(response.headers.allow).toBeUndefined();+ expect(response.headers['content-type']).toBe('application/problem+json');+ expect(response.headers['x-request-id']).toBe(+ 'X-Forwarded-For' in headers ? undefined : 'skills-admission',+ );+ expect(parseProblem(response.body).type).toBe(type);+ }+ }+});++function extension(options: { external?: boolean; ephemeral?: boolean } = {}) {+ return createApiExtension({+ contentDir: join(root, 'normal'),+ projectDir: join(root, 'normal'),+ homeDirOverride: join(root, 'home'),+ hocuspocus: server.serverInstance.hocuspocus,+ sessionManager: server.serverInstance.sessionManager,+ ephemeral: options.ephemeral,+ ...(options.external+ ? {+ ingressPolicy: buildIngressPolicy({+ serverRuntime: {+ bind: ['127.0.0.1'],+ port: 0,+ externalUrl: 'https://skills.example.com',+ allowExternal: true,+ openBrowser: false,+ idleShutdown: 'off',+ loopbackOnly: false,+ },+ }),+ }+ : {}),+ });+}++test('non-loopback peers are refused before parsing on all paths, while configured external peers reach dispatch', async () => {+ const local = extension();+ const external = extension({ external: true });+ for (const path of PATHS) {+ for (const [api, consented] of [+ [local, false],+ [external, true],+ ] as const) {+ const req = makeSyntheticReq({+ method: 'PATCH',+ url: path,+ remoteAddress: '203.0.113.8',+ host: consented ? 'skills.example.com' : '127.0.0.1',+ });+ const { res, captured } = makeCaptureRes();+ expect(await api.nativeApi.dispatch(req, res)).toBe(true);+ expect(captured.status, `${path}: ${captured.body}`).toBe(consented ? 405 : 403);+ expect(parseProblem(captured.body).type).toBe(+ consented+ ? path === '/api/skill-upload'+ ? 'urn:ok:error:invalid-request'+ : 'urn:ok:error:method-not-allowed'+ : 'urn:ok:error:loopback-required',+ );+ expect(req.readableEnded).toBe(false);+ req.destroy();+ }+ }+});++test('ephemeral admission still rejects hostile Hosts and retains the existing method surface', async () => {+ for (const path of PATHS) {+ const refused = await rawRequest(ephemeral.port, path, {+ method: 'PATCH',+ headers: { Host: 'evil.example' },+ });+ expect(refused.status, `${path}: ${refused.body}`).toBe(403);+ const admitted = await rawRequest(ephemeral.port, path, { method: 'PATCH' });+ expect(admitted.status, `${path}: ${admitted.body}`).toBe(405);+ }+ const restricted = await rawRequest(ephemeral.port, '/api/folder-config', {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ path: '', frontmatter: { category: 'refused' } }),+ });+ expect(restricted.status, restricted.body).toBe(403);+ expect(parseProblem(restricted.body).type).toBe('urn:ok:error:single-file-mode');+ expect(existsSync(join(root, 'ephemeral/.ok/frontmatter.yml'))).toBe(false);+});++test.each(['timeout', 'disconnect'] as const)(+ 'interrupted skill JSON bodies preserve %s handling without writing content',+ async (kind) => {+ const controller = new AbortController();+ const deadlines: number[] = [];+ const reading = Promise.withResolvers<void>();+ vi.spyOn(AbortSignal, 'timeout').mockImplementation((milliseconds) => {+ deadlines.push(milliseconds);+ reading.resolve();+ return controller.signal;+ });+ const base = makeSyntheticReq({ method: 'PUT', url: '/api/skill' });+ const stream = new PassThrough();+ const req = Object.assign(stream, {+ method: 'PUT',+ url: '/api/skill',+ headers: { ...base.headers, 'content-type': 'application/json' },+ socket: base.socket,+ }) as IncomingMessage;+ const { res, captured } = makeCaptureRes();+ const pending = extension().nativeApi.dispatch(req, res);+ stream.write('{"name":"interrupted","body":"unfinished');+ await reading.promise;+ expect(deadlines).toEqual([30_000]);+ if (kind === 'timeout') controller.abort();+ else stream.destroy();+ expect(await pending).toBe(true);+ expect(captured.status, captured.body).toBe(kind === 'timeout' ? 408 : 500);+ expect(parseProblem(captured.body)).toMatchObject({+ type:+ kind === 'timeout' ? 'urn:ok:error:request-timeout' : 'urn:ok:error:internal-server-error',+ title: kind === 'timeout' ? 'Request body read timed out.' : 'Failed to read request body.',+ });+ expect(existsSync(join(root, 'normal/.agents/skills/interrupted/SKILL.md'))).toBe(false);+ expect(existsSync(join(root, 'normal/.ok/skills/interrupted/SKILL.md'))).toBe(false);+ req.destroy();+ },+);++test('real live skill and reference conflicts refuse edits and rename without changing either source', async () => {+ const name = 'conflicted-skill';+ const post = (path: string, method: string, body: object) =>+ rawRequest(server.port, path, {+ method,+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+ const created = await post('/api/skill', 'PUT', {+ name,+ scope: 'project',+ frontmatter: { name, description: 'Before' },+ body: 'Keep this body.\n',+ agentId: 'conflict-writer',+ });+ expect(created.status, created.body).toBe(200);+ const path = JSON.parse(created.body).path as string;+ const docName = path.slice(0, -3);+ const file = 'references/note.md';+ const reference = await post('/api/skill-file', 'PUT', {+ name,+ scope: 'project',+ path: file,+ content: 'Reference bytes. \n',+ agentId: 'conflict-writer',+ });+ expect(reference.status, reference.body).toBe(200);+ const referenceDocName = `${docName.slice(0, -5)}${file.slice(0, -3)}`;+ for (const current of [docName, referenceDocName]) {+ const session = await server.serverInstance.sessionManager.getSession(+ current,+ 'agent-conflict-writer',+ { displayName: 'Conflict Writer', colorSeed: 'conflict-writer' },+ );+ session.dc.document.transact(+ () => session.dc.document.getMap('lifecycle').set('status', 'conflict'),+ session.origin,+ );+ }+ const skillBefore = readFileSync(join(root, 'normal', path), 'utf8');+ const referenceBefore = readFileSync(join(root, 'normal', `${referenceDocName}.md`), 'utf8');+ for (const [route, method, body] of [+ [+ '/api/skill',+ 'PUT',+ {+ name,+ scope: 'project',+ frontmatter: { name, description: 'After' },+ body: 'Forbidden edit.',+ },+ ],+ [+ '/api/skill-file',+ 'PUT',+ { name, scope: 'project', path: file, content: 'Forbidden reference edit.' },+ ],+ [+ '/api/skill-file/rename',+ 'POST',+ { name, scope: 'project', from: file, to: 'references/moved.md' },+ ],+ ] as const) {+ const refused = await post(route, method, body);+ expect(refused.status, `${route}: ${refused.body}`).toBe(409);+ expect(parseProblem(refused.body).type).toBe('urn:ok:error:doc-in-conflict');+ }+ expect(readFileSync(join(root, 'normal', path), 'utf8')).toBe(skillBefore);+ expect(readFileSync(join(root, 'normal', `${referenceDocName}.md`), 'utf8')).toBe(+ referenceBefore,+ );+ expect(+ server.serverInstance.hocuspocus.documents.get(docName)?.getText('source').toString(),+ ).toBe(skillBefore);+ expect(+ server.serverInstance.hocuspocus.documents.get(referenceDocName)?.getText('source').toString(),+ ).toBe(referenceBefore);+ expect(existsSync(join(root, 'normal', `${docName.slice(0, -5)}references/moved.md`))).toBe(+ false,+ );+});++test('the retained local dispatcher imports and installs through the native tables in a real authoring round trip', async () => {+ const name = 'local-round-trip';+ const source = join(root, 'source', name);+ mkdirSync(source, { recursive: true });+ writeFileSync(+ join(source, 'SKILL.md'),+ `---\nname: ${name}\ndescription: Original\n---\nOriginal bytes.\n`,+ );+ const imported = await server.serverInstance.localApi('POST', '/api/skill/import', {+ body: JSON.stringify({ source, install: false, agentId: 'local-importer' }),+ contentType: 'application/json',+ });+ expect(imported?.status, imported?.bodyText).toBe(200);+ const edited = await rawRequest(server.port, '/api/skill', {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ name,+ scope: 'project',+ frontmatter: { name, description: 'Edited' },+ body: 'Exact \\* and <custom>raw</custom>. \n\n',+ agentId: 'local-editor',+ }),+ });+ expect(edited.status, edited.body).toBe(200);+ const path = JSON.parse(edited.body).path as string;+ const bytes = readFileSync(join(root, 'normal', path), 'utf8');+ expect(bytes).toBe(+ `---\nname: ${name}\ndescription: Edited\n---\nExact \\* and <custom>raw</custom>. \n\n`,+ );+ const listing = await rawRequest(server.port, '/api/skills');+ expect(listing.status, listing.body).toBe(200);+ expect(JSON.parse(listing.body).skills).toEqual(+ expect.arrayContaining([expect.objectContaining({ name, description: 'Edited' })]),+ );+ const installed = await server.serverInstance.localApi('POST', '/api/skill/install', {+ body: JSON.stringify({ name, scope: 'project', targets: ['cursor'] }),+ contentType: 'application/json',+ });+ expect(installed?.status, installed?.bodyText).toBe(200);+ expect(readFileSync(join(root, 'normal/.cursor/skills', name, 'SKILL.md'), 'utf8')).toBe(bytes);+ const deleted = await rawRequest(+ server.port,+ `/api/skill?name=${name}&scope=project&agentId=local-editor`,+ { method: 'DELETE' },+ );+ expect(deleted.status, deleted.body).toBe(200);+ expect(existsSync(join(root, 'normal', path))).toBe(false);+ expect(existsSync(join(root, 'normal/.cursor/skills', name, 'SKILL.md'))).toBe(false);+});++test('consented external forwarding reaches each native method gate on the composed listener', async () => {+ const contentDir = join(root, 'external');+ mkdirSync(contentDir);+ const external = await bootCompositionRig(contentDir, {+ serverRuntime: {+ bind: ['127.0.0.1'],+ port: 0,+ externalUrl: 'https://skills.example.com',+ allowExternal: true,+ openBrowser: false,+ idleShutdown: 'off',+ loopbackOnly: true,+ },+ });+ try {+ await external.ready;+ for (const path of PATHS) {+ const response = await rawRequest(external.port, path, {+ method: 'PATCH',+ headers: {+ Host: 'skills.example.com',+ Origin: 'https://skills.example.com',+ 'X-Forwarded-For': '203.0.113.8',+ 'X-Request-Id': 'consented-skills',+ },+ });+ expect(response.status, `${path}: ${response.body}`).toBe(405);+ expect(response.headers['x-request-id']).toBe('consented-skills');+ expect(response.headers['access-control-allow-origin']).toBe('https://skills.example.com');+ }+ } finally {+ await external.destroy();+ }+});diff --git a/packages/server/src/http/folder-template-routes.test.ts b/packages/server/src/http/folder-template-routes.test.tsindex af6bf6598..a3d43f12d 100644--- a/packages/server/src/http/folder-template-routes.test.ts+++ b/packages/server/src/http/folder-template-routes.test.ts@@ -33,6 +33,7 @@ function buildGroup() {flushDiskAndDetectOutcome: () => Promise.resolve(null),respondPersistenceFailure: () => {},respondDiskDivergence: () => {},+ respondStaleExternalWrite: () => {},registerWrittenDocInFileIndex: () => {},captureAndCloseDocuments: () => Promise.resolve(new Map()),renameTrackedPathInGit: () => Promise.resolve(false),diff --git a/packages/server/src/http/handoff-install-routes.test.ts b/packages/server/src/http/handoff-install-routes.test.tsnew file mode 100644index 000000000..1f05b5d6e--- /dev/null+++ b/packages/server/src/http/handoff-install-routes.test.ts@@ -0,0 +1,21 @@+import { describe, expect, test } from 'vitest';+import { createHandoffInstallRoutes } from './handoff-install-routes.ts';++function buildGroup() {+ return createHandoffInstallRoutes({+ checkLocalOpSecurity: () => true,+ });+}++describe('createHandoffInstallRoutes table', () => {+ test('registers exactly the one handoff-install path', () => {+ expect([...buildGroup().paths].sort()).toEqual(['/api/install-skill'].sort());+ });++ test('every handoff-install path is mutating (whole-family legacy MUTATING_ROUTES membership)', () => {+ const { table } = buildGroup();+ for (const path of ['/api/install-skill']) {+ expect(table.isMutating(path), path).toBe(true);+ }+ });+});diff --git a/packages/server/src/http/handoff-install-routes.ts b/packages/server/src/http/handoff-install-routes.tsnew file mode 100644index 000000000..c8b0a7b4a--- /dev/null+++ b/packages/server/src/http/handoff-install-routes.ts@@ -0,0 +1,60 @@+import type { IncomingMessage, ServerResponse } from 'node:http';+import { InstallSkillRequestSchema, InstallSkillSuccessSchema } from '@inkeep/open-knowledge-core';+import { isSafeLocalPath } from '../local-op-security.ts';+import { buildAndOpenSkill } from '../skill-install.ts';+import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';+import { errorResponse } from './error-response.ts';+import { withValidation } from './request-validation.ts';+import { successResponse } from './success-response.ts';++export interface HandoffInstallRouteDeps {+ checkLocalOpSecurity: (+ req: IncomingMessage,+ res: ServerResponse,+ opts: { handler: string },+ ) => boolean;+}++export function createHandoffInstallRoutes(deps: HandoffInstallRouteDeps): ApiRouteGroup {+ const { checkLocalOpSecurity } = deps;+ const handleInstallSkill = withValidation(+ InstallSkillRequestSchema,+ async (_req, res, body) => {+ if (body.out !== undefined && !isSafeLocalPath(body.out)) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Output path must be within home directory.',+ { handler: 'install-skill' },+ );+ return;+ }++ try {+ const result = await buildAndOpenSkill({+ ...(body.noOpen !== undefined ? { noOpen: body.noOpen } : {}),+ ...(body.out !== undefined ? { out: body.out } : {}),+ });+ successResponse(res, 200, InstallSkillSuccessSchema, result, {+ handler: 'install-skill',+ });+ } catch (err) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to install skill.', {+ handler: 'install-skill',+ cause: err,+ });+ }+ },+ {+ handler: 'install-skill',+ method: 'POST',+ preBodyGate: (req, res) => checkLocalOpSecurity(req, res, { handler: 'install-skill' }),+ },+ );++ return createApiRouteGroup(+ { '/api/install-skill': handleInstallSkill },+ { mutating: ['/api/install-skill'] },+ );+}diff --git a/packages/server/src/http/skills-document-routes.test.ts b/packages/server/src/http/skills-document-routes.test.tsnew file mode 100644index 000000000..6c7423891--- /dev/null+++ b/packages/server/src/http/skills-document-routes.test.ts@@ -0,0 +1,84 @@+import { Hocuspocus } from '@hocuspocus/server';+import { describe, expect, test } from 'vitest';+import { AgentSessionManager } from '../agent-sessions.ts';+import { loggerFactory } from '../logger.ts';+import { createSkillsDocumentRoutes } from './skills-document-routes.ts';++function buildGroup() {+ return createSkillsDocumentRoutes({+ validateSkillName: () => true,+ parseSkillScope: () => 'project',+ skillsHome: '/nonexistent-skills-home',+ projectDir: undefined,+ resolveBuiltinSkillDir: () => null,+ resolveSkillDirForRead: () => null,+ derivedDocumentIndex: undefined,+ getPrincipal: undefined,+ rejectReservedBuiltinSkill: () => false,+ contentDir: '/nonexistent-content',+ attributeOkArtifactWrite: () => {},+ signalChannel: undefined,+ checkSkillDocConflictGate: () => false,+ extractAgentIdentity: () => ({+ rawAgentId: undefined,+ agentId: 'test',+ agentName: 'test',+ colorSeed: 'test',+ clientName: undefined,+ clientVersion: undefined,+ label: undefined,+ }),+ sessionManager: new AgentSessionManager(new Hocuspocus({ quiet: true })),+ flushDiskAndDetectOutcome: () => Promise.resolve(null),+ respondStaleExternalWrite: () => {},+ respondPersistenceFailure: () => {},+ respondDiskDivergence: () => {},+ okArtifactKey: () => '',+ resolveSkillsRoot: () => '/nonexistent-skills',+ extractActorIdentityFromQuery: () => ({ kind: 'invalid-summary' }),+ captureAndCloseDocuments: () => Promise.resolve(new Map()),+ log: loggerFactory.getLogger('test'),+ commitOkArtifactWrite: () => Promise.resolve(),+ parseFrontmatterDoc: () => ({ frontmatter: {}, body: '' }),+ skillRelPath: (path) => path,+ contentFilter: undefined,+ bumpSkillsCatalogGen: () => {},+ scheduleDeferredIgnoreRebuild: () => {},+ recordDerivedDocumentBestEffort: () => Promise.resolve(),+ scheduleOkArtifactFlush: () => {},+ skillInstallBase: () => undefined,+ uninstallSkillFromHostDirs: () => Promise.resolve(false),+ renameTrackedPathInGit: () => Promise.resolve(false),+ renamePathOnDisk: () => {},+ localSkillHash: () => undefined,+ shadowHeadSha: () => Promise.resolve(undefined),+ artifactWriterId: () => undefined,+ checkLocalOpSecurity: () => true,+ effectiveSkillRoot: () => ({ root: '/nonexistent-skills', dirRel: '', realDir: null }),+ });+}++describe('createSkillsDocumentRoutes table', () => {+ test('registers exactly the four skill-document paths', () => {+ expect([...buildGroup().paths].sort()).toEqual(+ [+ '/api/skill',+ '/api/skill/edit-external',+ '/api/skill/duplicate',+ '/api/skill/move-scope',+ ].sort(),+ );+ });++ test('every skill-document path is mutating (whole-family legacy MUTATING_ROUTES membership)', () => {+ const { table } = buildGroup();+ for (const path of [+ '/api/skill',+ '/api/skill/edit-external',+ '/api/skill/duplicate',+ '/api/skill/move-scope',+ ]) {+ expect(table.isMutating(path), path).toBe(true);+ }+ });+});diff --git a/packages/server/src/http/skills-document-routes.ts b/packages/server/src/http/skills-document-routes.tsnew file mode 100644index 000000000..b73ea3858--- /dev/null+++ b/packages/server/src/http/skills-document-routes.ts@@ -0,0 +1,1442 @@+import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';+import { readFile } from 'node:fs/promises';+import type { IncomingMessage, ServerResponse } from 'node:http';+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';+import {+ applyPatchToFm,+ detectFmRegion,+ EmptyRequestSchema,+ externalSkillLiveDocName,+ isSkillInstallTarget,+ type Principal,+ SkillDeleteSuccessSchema,+ SkillDuplicateRequestSchema,+ SkillDuplicateSuccessSchema,+ SkillEditExternalRequestSchema,+ SkillEditExternalSuccessSchema,+ SkillGetSuccessSchema,+ SkillMoveRequestSchema,+ SkillMoveScopeRequestSchema,+ SkillMoveScopeSuccessSchema,+ SkillMoveSuccessSchema,+ SkillPutRequestSchema,+ SkillPutSuccessSchema,+ skillLiveDocName,+} from '@inkeep/open-knowledge-core';+import type { SkillHostId } from '@inkeep/open-knowledge-core/skills-catalog';+import {+ parseSkillDir,+ SKILLS_LOCK_REL,+ type SkillsLock,+} from '@inkeep/open-knowledge-core/skills-catalog';+import type { AgentSessionManager } from '../agent-sessions.ts';+import { composeAndWriteRawBody } from '../bridge-intake.ts';+import { isLinkIndexExcludedDoc } from '../cc1-broadcast.ts';+import {+ applySkillDelete,+ applySkillMove,+ applySkillWrite,+ composeSkillContent,+} from '../content/skills-write.ts';+import type { ContentFilter } from '../content-filter.ts';+import type {+ DerivedDocumentIndexApiPort,+ DerivedDocumentIndexMutation,+} from '../derived-document-index.ts';+import type { StoreFailure } from '../document-durability-state.ts';+import { registerExternalSkill } from '../external-skill-registry.ts';+import { extractActorIdentity } from '../extract-actor-identity.ts';+import { tracedCpSync, tracedMkdirSync, tracedRmSync, tracedWriteFileSync } from '../fs-traced.ts';+import {+ resolveDefaultSkillHomeRel,+ scanGlobalInPlaceSkills,+ scanHostRootAliases,+ scanInPlaceSkills,+} from '../in-place-skills.ts';+import {+ readInstalledSkills,+ recordSkillInstall,+ removeSkillInstall,+} from '../installed-skills-marker.ts';+import type { PinoLogger } from '../logger.ts';+import { getLogger } from '../logger.ts';+import { isInternalBundleSkillName } from '../skill-bundles.ts';+import { clearSkillPlacements } from '../skill-placements.ts';+import {+ projectSkill,+ readSkillBundledFiles,+ removeInPlaceSkillCopies,+ resolvedHosts,+ reverseProjectSkill,+ skillProjectionRoots,+ validateSkillForInstall,+} from '../skill-projection.ts';+import { rewriteSkillRefsAcrossScope, type SkillRefRewrite } from '../skill-ref-rename.ts';+import { mutateSkillsLock, readSkillsLockFile } from '../skills-lock-store.ts';+import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';+import { errorResponse } from './error-response.ts';+import { methodRouter } from './method-router.ts';+import { withValidation } from './request-validation.ts';+import { successResponse } from './success-response.ts';++export interface SkillsDocumentRouteDeps {+ validateSkillName: (name: string, res: ServerResponse, handler: string) => boolean;+ parseSkillScope: (+ raw: string | null,+ res: ServerResponse,+ handler: string,+ ) => 'project' | 'global' | null;+ skillsHome: string;+ projectDir: string | undefined;+ resolveBuiltinSkillDir: (+ base: string,+ name: string,+ scope: 'project' | 'global',+ host?: string,+ ) => { dir: string; skillMd: string; hosts: string[]; relPath: string } | null;+ parseFrontmatterDoc: (raw: string) => { frontmatter: Record<string, unknown>; body: string };+ resolveSkillDirForRead: (+ scope: 'project' | 'global',+ name: string,+ host?: string,+ ) => string | null;+ skillRelPath: (abs: string, scope: 'project' | 'global') => string;+ derivedDocumentIndex: Pick<DerivedDocumentIndexApiPort, 'recordDirectMutations'> | undefined;+ contentFilter: ContentFilter | undefined;+ bumpSkillsCatalogGen: () => void;+ scheduleDeferredIgnoreRebuild: () => void;+ recordDerivedDocumentBestEffort: (+ documentName: string,+ markdown: string,+ reason: string,+ ) => Promise<void>;+ getPrincipal: (() => Principal | null) | undefined;+ rejectReservedBuiltinSkill: (name: string, res: ServerResponse, handler: string) => boolean;+ contentDir: string;+ attributeOkArtifactWrite: (+ actor: ReturnType<typeof extractActorIdentity>,+ artifactKey: string,+ subject: string,+ previousPaths?: Array<{ from: string; to: string }>,+ ) => void;+ scheduleOkArtifactFlush: (context: string) => void;+ signalChannel: ((channel: 'files' | 'lint-config' | 'comments') => void) | undefined;+ checkSkillDocConflictGate: (docName: string, handler: string, res: ServerResponse) => boolean;+ extractAgentIdentity: (body: Record<string, unknown>) => {+ rawAgentId: string | undefined;+ agentId: string;+ agentName: string;+ colorSeed: string;+ clientName: string | undefined;+ clientVersion: string | undefined;+ label: string | undefined;+ };+ sessionManager: AgentSessionManager;+ respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;+ flushDiskAndDetectOutcome: (+ docName: string,+ ) => Promise<+ | { kind: 'failure'; failure: StoreFailure }+ | { kind: 'divergence' }+ | { kind: 'stale-external-write' }+ | null+ >;+ respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;+ respondDiskDivergence: (res: ServerResponse, handler: string) => void;+ okArtifactKey: (+ kind: 'template' | 'folder-frontmatter' | 'folder' | 'skill',+ folder: string,+ name?: string,+ ) => string;+ resolveSkillsRoot: (scope: 'project' | 'global') => string;+ extractActorIdentityFromQuery: (+ url: URL,+ principal: (() => Principal | null) | undefined,+ ) => ReturnType<typeof extractActorIdentity>;+ captureAndCloseDocuments: (+ docNames: string[],+ lifecycleStatus: 'deleted-upstream' | 'renamed',+ ) => Promise<Map<string, string>>;+ log: PinoLogger;+ commitOkArtifactWrite: (context: string) => Promise<void>;+ skillInstallBase: (scope: 'project' | 'global') => string | undefined;+ uninstallSkillFromHostDirs: (+ base: string,+ name: string,+ scope: 'project' | 'global',+ opts?: { purge?: { contentHash: string } },+ ) => Promise<boolean>;+ renameTrackedPathInGit: (+ projectDir: string | undefined,+ sourcePath: string,+ destinationPath: string,+ ) => Promise<boolean>;+ renamePathOnDisk: (sourcePath: string, destinationPath: string) => void;+ localSkillHash: (skillsRoot: string, name: string) => string | undefined;+ shadowHeadSha: (writerId?: string, verifyPathRel?: string) => Promise<string | undefined>;+ artifactWriterId: (actor: ReturnType<typeof extractActorIdentity>) => string | undefined;+ checkLocalOpSecurity: (+ req: IncomingMessage,+ res: ServerResponse,+ opts: { handler: string },+ ) => boolean;+ effectiveSkillRoot: (+ scope: 'project' | 'global',+ name: string,+ host?: string,+ ) => { root: string; dirRel: string; realDir: string | null };+}++export function createSkillsDocumentRoutes(deps: SkillsDocumentRouteDeps): ApiRouteGroup {+ const {+ validateSkillName,+ parseSkillScope,+ skillsHome,+ projectDir,+ resolveBuiltinSkillDir,+ parseFrontmatterDoc,+ resolveSkillDirForRead,+ skillRelPath,+ derivedDocumentIndex,+ contentFilter,+ bumpSkillsCatalogGen,+ scheduleDeferredIgnoreRebuild,+ recordDerivedDocumentBestEffort,+ getPrincipal,+ rejectReservedBuiltinSkill,+ contentDir,+ attributeOkArtifactWrite,+ scheduleOkArtifactFlush,+ signalChannel,+ checkSkillDocConflictGate,+ extractAgentIdentity,+ sessionManager,+ flushDiskAndDetectOutcome,+ respondStaleExternalWrite,+ respondPersistenceFailure,+ respondDiskDivergence,+ okArtifactKey,+ resolveSkillsRoot,+ extractActorIdentityFromQuery,+ captureAndCloseDocuments,+ log,+ commitOkArtifactWrite,+ skillInstallBase,+ uninstallSkillFromHostDirs,+ renameTrackedPathInGit,+ renamePathOnDisk,+ localSkillHash,+ shadowHeadSha,+ artifactWriterId,+ checkLocalOpSecurity,+ effectiveSkillRoot,+ } = deps;++ function projectionModeFor(scope: 'project' | 'global', name: string): 'symlink' | 'copy' {+ const base = scope === 'project' ? projectDir : skillsHome;+ if (!base) return 'symlink';+ try {+ const lock = readSkillsLockFile(join(base, ...SKILLS_LOCK_REL));+ return lock.skills[name] !== undefined ? 'copy' : 'symlink';+ } catch {+ return 'symlink';+ }+ }++ function skillLockPath(scope: 'project' | 'global'): string | null {+ const base = scope === 'project' ? projectDir : skillsHome;+ return base ? join(base, ...SKILLS_LOCK_REL) : null;+ }++ function rekeySkillLockEntry(+ scope: 'project' | 'global',+ fromName: string,+ toName: string,+ patch: Partial<SkillsLock['skills'][string]> = {},+ ): Promise<void> {+ const lockPath = skillLockPath(scope);+ if (!lockPath) return Promise.resolve();+ return mutateSkillsLock(lockPath, (lock) => {+ const entry = lock.skills[fromName];+ if (!entry) return lock;+ const skills = { ...lock.skills };+ delete skills[fromName];+ skills[toName] = { ...entry, ...patch };+ return { ...lock, skills };+ });+ }++ async function transferSkillLockEntry(+ fromScope: 'project' | 'global',+ toScope: 'project' | 'global',+ name: string,+ ): Promise<boolean> {+ const fromPath = skillLockPath(fromScope);+ const toPath = skillLockPath(toScope);+ if (!fromPath || !toPath) return false;+ const entry = readSkillsLockFile(fromPath).skills[name];+ if (!entry) return false;++ const movedEntry = { ...entry };+ if (toScope === 'global') delete movedEntry.baselineRef;+ await mutateSkillsLock(toPath, (lock) => ({+ ...lock,+ skills: { ...lock.skills, [name]: movedEntry },+ }));+ await mutateSkillsLock(fromPath, (lock) => {+ const remaining = { ...lock.skills };+ delete remaining[name];+ return { ...lock, skills: remaining };+ });+ return true;+ }++ function updateSkillLockEntry(+ scope: 'project' | 'global',+ name: string,+ patch: Partial<SkillsLock['skills'][string]>,+ ): Promise<void> {+ const lockPath = skillLockPath(scope);+ if (!lockPath) return Promise.resolve();+ return mutateSkillsLock(lockPath, (lock) => {+ const entry = lock.skills[name];+ if (!entry) return lock;+ return { ...lock, skills: { ...lock.skills, [name]: { ...entry, ...patch } } };+ });+ }++ function listProjectMdReferences(skillsRoot: string, name: string): string[] {+ const refsDir = resolve(skillsRoot, name, 'references');+ if (!existsSync(refsDir)) return [];+ const out: string[] = [];+ const walk = (dir: string, prefix: string): void => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;+ if (entry.isDirectory()) walk(resolve(dir, entry.name), rel);+ else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) {+ out.push(`references/${rel}`);+ }+ }+ };+ walk(refsDir, '');+ return out;+ }++ async function reindexMovedProjectSkillDocs(+ skillsRoot: string,+ fromName: string,+ toName: string,+ ): Promise<void> {+ if (!derivedDocumentIndex) {+ getLogger('skill-move').warn(+ { fromName, toName },+ 'no derived-document index available — skipping re-index of the moved skill (its old entries will be dropped with no replacement)',+ );+ return;+ }+ const derivedMutations: DerivedDocumentIndexMutation[] = [];+ const collectReindex = (oldDocName: string, newDocName: string, absFile: string): void => {+ let markdown: string;+ try {+ markdown = readFileSync(absFile, 'utf-8');+ } catch (err) {+ getLogger('skill-move').warn(+ { err, absFile, oldDocName, newDocName },+ 'relocated skill file unreadable after move — dropping the old index entry with no replacement',+ );+ derivedMutations.push({ kind: 'delete', documentName: oldDocName });+ return;+ }+ derivedMutations.push({+ kind: 'rename',+ oldDocumentName: oldDocName,+ newDocumentName: newDocName,+ markdown,+ });+ };++ const rootRel = relative(contentDir, skillsRoot).split(sep).join('/');+ const docFor = (n: string, rel?: string): string =>+ `${rootRel}/${n}/${rel ? rel.replace(/\.mdx?$/i, '') : 'SKILL'}`;+ collectReindex(docFor(fromName), docFor(toName), resolve(skillsRoot, toName, 'SKILL.md'));+ for (const rel of listProjectMdReferences(skillsRoot, toName)) {+ collectReindex(docFor(fromName, rel), docFor(toName, rel), resolve(skillsRoot, toName, rel));+ }+ await derivedDocumentIndex.recordDirectMutations(derivedMutations);+ }++ async function reindexRewrittenSkillRefDocs(+ rewrites: readonly SkillRefRewrite[],+ movedName: string,+ ): Promise<void> {+ if (!derivedDocumentIndex || rewrites.length === 0) return;+ const mutations: DerivedDocumentIndexMutation[] = [];+ for (const rw of rewrites) {+ if (rw.dir.split('/').pop() === movedName) continue;+ mutations.push({+ kind: 'link-rewrite',+ documentName: `${rw.dir}/${rw.rel.replace(/\.mdx?$/i, '')}`,+ markdown: rw.markdown,+ });+ }+ if (mutations.length > 0) await derivedDocumentIndex.recordDirectMutations(mutations);+ }++ const handleSkillGet = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ try {+ const url = new URL(req.url ?? '', 'http://localhost');+ const name = url.searchParams.get('name') ?? '';+ if (!validateSkillName(name, res, 'skill-get')) return;+ const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-get');+ if (scope === null) return;++ if (isInternalBundleSkillName(name)) {+ const base = scope === 'global' ? skillsHome : projectDir;+ const builtin = base+ ? resolveBuiltinSkillDir(base, name, scope, url.searchParams.get('host') ?? undefined)+ : null;+ if (builtin) {+ const { frontmatter, body } = parseFrontmatterDoc(+ await readFile(builtin.skillMd, 'utf-8'),+ );+ successResponse(+ res,+ 200,+ SkillGetSuccessSchema,+ {+ skill: {+ name,+ scope,+ path: builtin.relPath,+ frontmatter: {+ name: typeof frontmatter.name === 'string' ? frontmatter.name : name,+ description:+ typeof frontmatter.description === 'string' ? frontmatter.description : '',+ },+ body,+ files: readSkillBundledFiles(builtin.dir),+ managed: true,+ },+ },+ { handler: 'skill-get' },+ );+ return;+ }+ }+ const host = url.searchParams.get('host') ?? undefined;+ const skillDirAbs = resolveSkillDirForRead(scope, name, host);+ if (skillDirAbs === null) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {+ handler: 'skill-get',+ detail:+ host === undefined+ ? `Skill "${name}" not found in ${scope} scope.`+ : `No skill "${name}" (${scope}) in ${host}.`,+ });+ return;+ }+ const skillMd = resolve(skillDirAbs, 'SKILL.md');+ const { frontmatter, body } = parseFrontmatterDoc(await readFile(skillMd, 'utf-8'));+ successResponse(+ res,+ 200,+ SkillGetSuccessSchema,+ {+ skill: {+ name,+ scope,+ path: skillRelPath(skillMd, scope),+ frontmatter: {+ name: typeof frontmatter.name === 'string' ? frontmatter.name : name,+ description:+ typeof frontmatter.description === 'string' ? frontmatter.description : '',+ },+ body,+ files: readSkillBundledFiles(skillDirAbs),+ },+ },+ { handler: 'skill-get' },+ );+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to read skill.', {+ handler: 'skill-get',+ cause: e,+ });+ }+ },+ { handler: 'skill-get', method: 'GET', skipBodyParse: true },+ );++ async function seedSkillDerivedViews(docName: string, markdown: string): Promise<void> {+ if (!derivedDocumentIndex || isLinkIndexExcludedDoc(docName)) return;+ if (contentFilter) {+ bumpSkillsCatalogGen();+ contentFilter.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();+ }+ void recordDerivedDocumentBestEffort(docName, markdown, 'skill-put');+ }++ const handleSkillPut = withValidation(+ SkillPutRequestSchema,+ async (_req, res, body) => {+ try {+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-put',+ });+ return;+ }+ if (!validateSkillName(body.name, res, 'skill-put')) return;+ if (rejectReservedBuiltinSkill(body.name, res, 'skill-put')) return;++ const composed = composeSkillContent({+ name: body.name,+ body: typeof body.body === 'string' ? body.body : '',+ frontmatter: { name: body.frontmatter.name, description: body.frontmatter.description },+ });+ if (!composed.ok) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid skill request.', {+ handler: 'skill-put',+ detail: composed.error.code,+ cause: new Error(composed.error.message),+ });+ return;+ }++ const putBase = body.scope === 'project' ? contentDir : skillsHome;+ const existingAbs = resolveSkillDirForRead(body.scope, body.name);+ if (existingAbs === null) {+ const homeRel = resolveDefaultSkillHomeRel(putBase, body.scope);+ if (homeRel === null) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'No agent skill host is available.',+ { handler: 'skill-put', detail: 'NO_USABLE_SKILL_HOME' },+ );+ return;+ }+ const wr = applySkillWrite({+ skillsRoot: resolve(putBase, homeRel),+ name: body.name,+ body: typeof body.body === 'string' ? body.body : '',+ frontmatter: {+ name: body.frontmatter.name,+ description: body.frontmatter.description,+ },+ });+ if (!wr.ok) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid skill request.', {+ handler: 'skill-put',+ detail: wr.error.code,+ cause: new Error(wr.error.message),+ });+ return;+ }+ if (body.scope === 'project') {+ attributeOkArtifactWrite(+ actor,+ `${homeRel}/${body.name}/SKILL`,+ `skill-create: ${homeRel}/${body.name}/SKILL.md`,+ );+ scheduleOkArtifactFlush('skill-put');+ }+ await seedSkillDerivedViews(+ body.scope === 'project'+ ? `${homeRel}/${body.name}/SKILL`+ : skillLiveDocName('global', body.name),+ composed.content,+ );+ signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillPutSuccessSchema,+ {+ path: `${homeRel}/${body.name}/SKILL.md`,+ created: true,+ warnings: [...composed.warnings, ...wr.warnings],+ },+ { handler: 'skill-put' },+ );+ return;+ }+ const created = false;+ const dirRel = relative(putBase, existingAbs).split(sep).join('/');+ const relPath = `${dirRel}/SKILL.md`;+ const docName =+ body.scope === 'project' ? `${dirRel}/SKILL` : skillLiveDocName(body.scope, body.name);++ if (checkSkillDocConflictGate(docName, 'skill-put', res)) return;++ /**+ * CRDT write (precedent #24 / #38): the full SKILL.md goes through the doc's+ * `Y.Text('source')` via the sanctioned paired-write primitive under the per-session+ * frozen origin.+ */+ const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(+ body as unknown as Record<string, unknown>,+ );+ const session = await sessionManager.getSession(docName, agentId, {+ displayName: agentName,+ colorSeed,+ clientName,+ });+ session.dc.document.transact(() => {+ composeAndWriteRawBody(session.dc.document, composed.content, 'agent');+ }, session.origin);++ const flushOutcome = await flushDiskAndDetectOutcome(docName);+ if (flushOutcome?.kind === 'failure') {+ respondPersistenceFailure(res, flushOutcome.failure, 'skill-put');+ return;+ }+ if (flushOutcome?.kind === 'divergence') {+ respondDiskDivergence(res, 'skill-put');+ return;+ }+ if (flushOutcome?.kind === 'stale-external-write') {+ respondStaleExternalWrite(res, 'skill-put', docName);+ return;+ }++ if (body.scope === 'project') {+ attributeOkArtifactWrite(+ actor,+ okArtifactKey('skill', '', body.name),+ `${created ? 'skill-create' : 'skill-edit'}: ${relPath}`,+ );+ scheduleOkArtifactFlush('skill-put');+ }+ await seedSkillDerivedViews(docName, composed.content);+ signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillPutSuccessSchema,+ { path: relPath, created, warnings: composed.warnings },+ { handler: 'skill-put' },+ );+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to write skill.', {+ handler: 'skill-put',+ cause: e,+ });+ }+ },+ { handler: 'skill-put', method: 'PUT' },+ );++ function sweepSkillOccurrences(scope: 'project' | 'global', name: string): void {+ const base = scope === 'project' ? contentDir : skillsHome;+ const inPlace = (+ scope === 'project' ? scanInPlaceSkills(contentDir) : scanGlobalInPlaceSkills(skillsHome)+ ).find((sk) => sk.name === name);+ if (!inPlace) return;+ removeInPlaceSkillCopies({+ canonicalAbs: resolve(base, inPlace.dir),+ canonicalHash: inPlace.contentHash,+ name,+ cwd: base,+ targets: inPlace.hosts.filter((h): h is SkillHostId => isSkillInstallTarget(h)),+ roots: skillProjectionRoots(scope),+ });+ }++ const handleSkillDelete = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ try {+ const url = new URL(req.url ?? '', 'http://localhost');+ const name = url.searchParams.get('name') ?? '';+ if (!validateSkillName(name, res, 'skill-delete')) return;+ const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-delete');+ if (scope === null) return;+ const host = url.searchParams.get('host') ?? undefined;+ const { root: skillsRoot, dirRel, realDir } = effectiveSkillRoot(scope, name, host);+ if (host !== undefined && realDir === null) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {+ handler: 'skill-delete',+ detail: `No skill "${name}" (${scope}) in ${host}.`,+ });+ return;+ }++ const actor = extractActorIdentityFromQuery(url, getPrincipal);+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-delete',+ });+ return;+ }++ await captureAndCloseDocuments(+ scope === 'project'+ ? [...new Set([`${dirRel}/SKILL`, skillLiveDocName(scope, name)])]+ : [skillLiveDocName(scope, name, host)],+ 'deleted-upstream',+ );++ if (host === undefined) sweepSkillOccurrences(scope, name);+ const result = applySkillDelete({ skillsRoot, name });+ const storeRoot = resolveSkillsRoot(scope);+ if (+ host === undefined &&+ result.ok &&+ storeRoot !== skillsRoot &&+ existsSync(resolve(storeRoot, name, 'SKILL.md'))+ ) {+ const storeSweep = applySkillDelete({ skillsRoot: storeRoot, name });+ if (!storeSweep.ok) {+ log.warn(+ { name, scope, detail: storeSweep.error.code },+ '[skill-delete] legacy store resident survived the delete',+ );+ }+ }+ if (!result.ok) {+ const status = result.error.code === 'UNLINK_FAILED' ? 500 : 400;+ errorResponse(+ res,+ status,+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',+ status === 500 ? 'Failed to delete skill.' : 'Invalid skill request.',+ {+ handler: 'skill-delete',+ detail: result.error.code,+ cause: new Error(result.error.message),+ },+ );+ return;+ }+ if (result.existed) {+ if (scope === 'project') {+ attributeOkArtifactWrite(actor, dirRel, `skill-delete: ${dirRel}`);+ bumpSkillsCatalogGen();+ void commitOkArtifactWrite('skill-delete');+ }+ signalChannel?.('files');+ }+ const uninstallBase = skillInstallBase(scope);+ if (host === undefined && uninstallBase) {+ await uninstallSkillFromHostDirs(uninstallBase, name, scope);+ }+ successResponse(+ res,+ 200,+ SkillDeleteSuccessSchema,+ { existed: result.existed, path: result.path },+ { handler: 'skill-delete' },+ );+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to delete skill.', {+ handler: 'skill-delete',+ cause: e,+ });+ }+ },+ { handler: 'skill-delete', method: 'DELETE', skipBodyParse: true },+ );++ const handleSkillMove = withValidation(+ SkillMoveRequestSchema,+ async (_req, res, body) => {+ try {+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-move',+ });+ return;+ }+ if (!validateSkillName(body.fromName, res, 'skill-move')) return;+ if (!validateSkillName(body.toName, res, 'skill-move')) return;+ if (rejectReservedBuiltinSkill(body.toName, res, 'skill-move')) return;+ const { root: skillsRoot, dirRel: fromDirRel } = effectiveSkillRoot(+ body.scope,+ body.fromName,+ );+ if (resolveSkillDirForRead(body.scope, body.toName) !== null) {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:doc-already-exists',+ `A skill named "${body.toName}" already exists.`,+ { handler: 'skill-move' },+ );+ return;+ }++ const moveBase = skillInstallBase(body.scope);+ const priorInstall = moveBase+ ? readInstalledSkills(moveBase).skills[body.fromName]+ : undefined;+ const fromScanBase = body.scope === 'project' ? contentDir : skillsHome;+ const renameScanEntry = (+ body.scope === 'project'+ ? scanInPlaceSkills(contentDir)+ : scanGlobalInPlaceSkills(skillsHome)+ ).find((sk) => sk.name === body.fromName);+ const renameCanonicalRootRel = renameScanEntry ? dirname(renameScanEntry.dir) : null;+ const renameAliasAudience =+ renameCanonicalRootRel !== null+ ? Object.entries(scanHostRootAliases(fromScanBase, body.scope))+ .filter(([, target]) => target === renameCanonicalRootRel)+ .map(([editor]) => editor)+ : [];+ const priorHosts = [+ ...new Set([+ ...(priorInstall ? resolvedHosts(priorInstall.hosts, body.scope) : []),+ ...(renameScanEntry ? resolvedHosts(renameScanEntry.hosts, body.scope) : []),+ ...resolvedHosts(renameAliasAudience, body.scope),+ ]),+ ];++ await captureAndCloseDocuments(+ body.scope === 'project'+ ? [...new Set([`${fromDirRel}/SKILL`, skillLiveDocName(body.scope, body.fromName)])]+ : [skillLiveDocName(body.scope, body.fromName)],+ 'renamed',+ );++ sweepSkillOccurrences(body.scope, body.fromName);+ const result = await applySkillMove({+ skillsRoot,+ fromName: body.fromName,+ toName: body.toName,+ relocate: async (fromAbs, toAbs) => {+ const movedWithGit = await renameTrackedPathInGit(projectDir, fromAbs, toAbs);+ if (!movedWithGit) renamePathOnDisk(fromAbs, toAbs);+ return movedWithGit;+ },+ });+ if (!result.ok) {+ if (result.error.code === 'SKILL_NOT_FOUND') {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {+ handler: 'skill-move',+ detail: result.error.message,+ });+ return;+ }+ if (result.error.code === 'SKILL_EXISTS') {+ errorResponse(res, 409, 'urn:ok:error:doc-already-exists', result.error.message, {+ handler: 'skill-move',+ detail: result.error.code,+ });+ return;+ }+ const status = result.error.code === 'MOVE_FAILED' ? 500 : 400;+ errorResponse(+ res,+ status,+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',+ status === 500 ? 'Failed to move skill.' : 'Invalid skill move request.',+ {+ handler: 'skill-move',+ detail: result.error.code,+ cause: new Error(result.error.message),+ },+ );+ return;+ }++ let contentEditError: { code: string; message: string } | null = null;+ const movedSkillMd = resolve(skillsRoot, body.toName, 'SKILL.md');+ let parsedBody = '';+ let parsedDescription = '';+ try {+ const parsed = parseFrontmatterDoc(readFileSync(movedSkillMd, 'utf-8'));+ parsedBody = parsed.body;+ if (typeof parsed.frontmatter.description === 'string') {+ parsedDescription = parsed.frontmatter.description;+ }+ } catch {}+ const writeBody = typeof body.body === 'string' ? body.body : parsedBody;+ const writeDescription =+ body.frontmatter !== undefined ? body.frontmatter.description : parsedDescription;+ const rewrite = applySkillWrite({+ skillsRoot,+ name: body.toName,+ body: writeBody,+ frontmatter: { name: body.toName, description: writeDescription },+ });+ if (!rewrite.ok) contentEditError = rewrite.error;++ let refRewrites: SkillRefRewrite[] = [];+ if (!contentEditError) {+ try {+ refRewrites = rewriteSkillRefsAcrossScope({+ base: body.scope === 'project' ? contentDir : skillsHome,+ scope: body.scope,+ fromName: body.fromName,+ toName: body.toName,+ });+ } catch (err) {+ getLogger('skill-move').warn(+ { err, fromName: body.fromName, toName: body.toName },+ 'skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored',+ );+ }+ }++ if (body.scope === 'project' && !contentEditError) {+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ void reindexMovedProjectSkillDocs(skillsRoot, body.fromName, body.toName)+ .then(() => reindexRewrittenSkillRefDocs(refRewrites, body.toName))+ .catch(() => {});+ scheduleDeferredIgnoreRebuild();+ }++ const fromKeyPath = skillRelPath(resolve(skillsRoot, body.fromName), body.scope);+ const toKeyPath = skillRelPath(resolve(skillsRoot, body.toName), body.scope);+ const renamedLocalHash = localSkillHash(skillsRoot, body.toName);+ await rekeySkillLockEntry(body.scope, body.fromName, body.toName, {+ localHash: renamedLocalHash,+ });+ if (body.scope === 'project') {+ attributeOkArtifactWrite(+ actor,+ okArtifactKey('skill', '', body.toName),+ `skill-rename: ${fromKeyPath} -> ${toKeyPath}`,+ [{ from: fromKeyPath, to: toKeyPath }],+ );+ void (async () => {+ try {+ await commitOkArtifactWrite('skill-move');+ const baselineRef = await shadowHeadSha(artifactWriterId(actor), toKeyPath);+ if (baselineRef !== undefined) {+ await updateSkillLockEntry('project', body.toName, { baselineRef });+ }+ } catch (err) {+ getLogger('skill-move').warn(+ { err, toName: body.toName },+ 'deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush',+ );+ }+ })();+ }++ if (moveBase) {+ await removeSkillInstall(moveBase, body.fromName);+ reverseProjectSkill(+ body.fromName,+ moveBase,+ priorHosts,+ skillProjectionRoots(body.scope),+ );+ const movedDir = resolve(skillsRoot, body.toName);+ if (priorHosts.length > 0) {+ const newHosts = projectSkill(+ movedDir,+ body.toName,+ moveBase,+ priorHosts,+ projectionModeFor(body.scope, body.toName),+ skillProjectionRoots(body.scope),+ );+ await recordSkillInstall(moveBase, body.toName, {+ ...priorInstall,+ scope: body.scope,+ hosts: newHosts,+ scripts:+ priorInstall?.scripts ?? validateSkillForInstall(movedDir, body.toName).hasScripts,+ installedAt: priorInstall?.installedAt ?? new Date().toISOString(),+ });+ }+ }+ signalChannel?.('files');++ if (contentEditError) {+ const isServerError = contentEditError.code === 'WRITE_ERROR';+ errorResponse(+ res,+ isServerError ? 500 : 400,+ isServerError ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',+ `Skill renamed to "${body.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,+ {+ handler: 'skill-move',+ detail: contentEditError.code,+ cause: new Error(contentEditError.message),+ },+ );+ return;+ }+ successResponse(+ res,+ 200,+ SkillMoveSuccessSchema,+ {+ from: fromKeyPath,+ to: toKeyPath,+ committed: result.committed,+ },+ { handler: 'skill-move' },+ );+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to move skill.', {+ handler: 'skill-move',+ cause: e,+ });+ }+ },+ { handler: 'skill-move', method: 'POST' },+ );++ const handleSkillEditExternal = withValidation(+ SkillEditExternalRequestSchema,+ async (_req, res, body) => {+ const { name, home } = body;+ if (!validateSkillName(name, res, 'skill-edit-external')) return;+ let realDir: string;+ try {+ realDir = realpathSync(home);+ } catch {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill directory not found.', {+ handler: 'skill-edit-external',+ detail: 'HOME_NOT_FOUND',+ });+ return;+ }+ if (!statSync(realDir).isDirectory() || !existsSync(resolve(realDir, 'SKILL.md'))) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Not a skill directory (no SKILL.md).',+ { handler: 'skill-edit-external' },+ );+ return;+ }+ registerExternalSkill(name, realDir);+ successResponse(+ res,+ 200,+ SkillEditExternalSuccessSchema,+ { docName: externalSkillLiveDocName(name) },+ { handler: 'skill-edit-external' },+ );+ },+ {+ handler: 'skill-edit-external',+ method: 'POST',+ preBodyGate: (req, res) => checkLocalOpSecurity(req, res, { handler: 'skill-edit-external' }),+ },+ );++ const handleSkillMoveScope = withValidation(+ SkillMoveScopeRequestSchema,+ async (_req, res, body) => {+ try {+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-move-scope',+ });+ return;+ }+ const { name, fromScope, toScope } = body;+ if (!validateSkillName(name, res, 'skill-move-scope')) return;+ if (isInternalBundleSkillName(name)) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ `"${name}" is a built-in skill and always lives at its own scope.`,+ { handler: 'skill-move-scope', detail: 'BUILTIN_SCOPE_FIXED' },+ );+ return;+ }+ if (fromScope === toScope) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Source and destination scope are the same.',+ { handler: 'skill-move-scope' },+ );+ return;+ }+ if (toScope === 'project' && !projectDir) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Cannot move to project scope — no project root is resolved for this server.',+ { handler: 'skill-move-scope', detail: 'NO_PROJECT_ROOT' },+ );+ return;+ }++ const { root: fromRoot, dirRel: fromDirRel, realDir } = effectiveSkillRoot(fromScope, name);+ const fromDir = resolve(fromRoot, name);+ const fromContentDir = (() => {+ try {+ return realpathSync(fromDir);+ } catch {+ return fromDir;+ }+ })();+ const toBase2 = toScope === 'project' ? contentDir : skillsHome;+ const toHomeRel = resolveDefaultSkillHomeRel(toBase2, toScope);+ if (toHomeRel === null) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'No agent skill host is available in the destination scope.',+ { handler: 'skill-move-scope', detail: 'NO_USABLE_SKILL_HOME' },+ );+ return;+ }+ const toRoot = resolve(toBase2, toHomeRel);+ const toDir = resolve(toRoot, name);+ if (realDir === null || !existsSync(fromDir)) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {+ handler: 'skill-move-scope',+ detail: `Skill "${name}" not found in ${fromScope} scope.`,+ });+ return;+ }+ if (+ resolve(realDir) === resolve(toDir) ||+ (existsSync(toDir) && realpathSync(realDir) === realpathSync(toDir))+ ) {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:doc-already-exists',+ 'The source and destination resolve to the same skill directory.',+ { handler: 'skill-move-scope', detail: 'SAME_STORAGE' },+ );+ return;+ }+ if (resolveSkillDirForRead(toScope, name) !== null || existsSync(toDir)) {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:doc-already-exists',+ `A ${toScope} skill named "${name}" already exists.`,+ { handler: 'skill-move-scope' },+ );+ return;+ }++ const fromBase = skillInstallBase(fromScope);+ const toBase = skillInstallBase(toScope);+ const priorInstall = fromBase ? readInstalledSkills(fromBase).skills[name] : undefined;+ const fromScanBase = fromScope === 'project' ? contentDir : skillsHome;+ const scanEntry = (+ fromScope === 'project'+ ? scanInPlaceSkills(contentDir)+ : scanGlobalInPlaceSkills(skillsHome)+ ).find((sk) => sk.name === name);+ const canonicalRootRel = scanEntry ? dirname(scanEntry.dir) : null;+ const aliasAudience =+ canonicalRootRel !== null+ ? Object.entries(scanHostRootAliases(fromScanBase, fromScope))+ .filter(([, target]) => target === canonicalRootRel)+ .map(([editor]) => editor)+ : [];+ const priorHosts = [+ ...new Set([+ ...(priorInstall ? resolvedHosts(priorInstall.hosts, fromScope) : []),+ ...(scanEntry ? resolvedHosts(scanEntry.hosts, fromScope) : []),+ ...resolvedHosts(aliasAudience, fromScope),+ ]),+ ];++ await captureAndCloseDocuments(+ [+ ...new Set([+ ...(fromScope === 'project' ? [`${fromDirRel}/SKILL`] : []),+ skillLiveDocName(fromScope, name),+ skillLiveDocName(toScope, name),+ ]),+ ],+ 'renamed',+ );++ tracedMkdirSync(toRoot, { recursive: true });+ tracedCpSync(fromContentDir, toDir, { recursive: true, dereference: true });++ sweepSkillOccurrences(fromScope, name);+ const del = applySkillDelete({ skillsRoot: fromRoot, name });+ if (del.ok && fromContentDir !== fromDir) {+ const realScanBase = (() => {+ try {+ return realpathSync(fromScanBase);+ } catch {+ return fromScanBase;+ }+ })();+ const relFromBase = relative(realScanBase, fromContentDir);+ if (relFromBase !== '' && !relFromBase.startsWith('..') && !isAbsolute(relFromBase)) {+ tracedRmSync(fromContentDir, { recursive: true, force: true });+ }+ }+ if (!del.ok) {+ applySkillDelete({ skillsRoot: toRoot, name });+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to move skill (source removal failed); rolled back the copy.',+ {+ handler: 'skill-move-scope',+ detail: del.error.code,+ cause: new Error(del.error.message),+ },+ );+ return;+ }++ const movedLockEntry = await transferSkillLockEntry(fromScope, toScope, name);++ if (fromBase) {+ await uninstallSkillFromHostDirs(+ fromBase,+ name,+ fromScope,+ scanEntry ? { purge: { contentHash: scanEntry.contentHash } } : {},+ );+ }+ if (fromBase) await clearSkillPlacements(fromBase, name);+ if (toBase && priorHosts.length > 0) {+ const newHosts = projectSkill(+ toDir,+ name,+ toBase,+ priorHosts,+ projectionModeFor(toScope, body.name),+ skillProjectionRoots(toScope),+ );+ await recordSkillInstall(toBase, name, {+ ...priorInstall,+ scope: toScope,+ hosts: newHosts,+ scripts: priorInstall?.scripts ?? validateSkillForInstall(toDir, name).hasScripts,+ installedAt: priorInstall?.installedAt ?? new Date().toISOString(),+ });+ }++ if (movedLockEntry) {+ const movedLocalHash = localSkillHash(toRoot, name);+ await updateSkillLockEntry(toScope, name, { localHash: movedLocalHash });+ }+ if (fromScope === 'project' || toScope === 'project') {+ attributeOkArtifactWrite(+ actor,+ fromScope === 'project' ? fromDirRel : relative(contentDir, toDir).split(sep).join('/'),+ `skill-move-scope: ${fromScope} -> ${toScope} ${name}`,+ );+ const toKeyForBaseline = relative(contentDir, toDir).split(sep).join('/');+ const wantBaseline = Boolean(movedLockEntry) && toScope === 'project';+ void (async () => {+ try {+ await commitOkArtifactWrite('skill-move-scope');+ if (wantBaseline) {+ const baselineRef = await shadowHeadSha(artifactWriterId(actor), toKeyForBaseline);+ if (baselineRef !== undefined) {+ await updateSkillLockEntry(toScope, name, { baselineRef });+ }+ }+ } catch (err) {+ getLogger('skill-move-scope').warn(+ { err, name },+ 'deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush',+ );+ }+ })();+ }++ if (!existsSync(join(toDir, 'SKILL.md'))) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'The move did not leave a readable skill at the destination; nothing was reported as moved.',+ { handler: 'skill-move-scope', detail: relative(toBase2, toDir).split(sep).join('/') },+ );+ return;+ }++ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();++ signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillMoveScopeSuccessSchema,+ { scope: toScope, path: relative(toBase2, toDir).split(sep).join('/') },+ { handler: 'skill-move-scope' },+ );+ } catch (e) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to move skill across scopes.',+ { handler: 'skill-move-scope', cause: e },+ );+ }+ },+ { handler: 'skill-move-scope', method: 'POST' },+ );++ const handleSkillDuplicate = withValidation(+ SkillDuplicateRequestSchema,+ async (_req, res, body) => {+ try {+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-duplicate',+ });+ return;+ }+ if (!validateSkillName(body.name, res, 'skill-duplicate')) return;+ if (!validateSkillName(body.toName, res, 'skill-duplicate')) return;+ if (rejectReservedBuiltinSkill(body.toName, res, 'skill-duplicate')) return;++ const sourceDir = resolveSkillDirForRead(body.scope, body.name);+ if (sourceDir === null || !existsSync(join(sourceDir, 'SKILL.md'))) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {+ handler: 'skill-duplicate',+ detail: 'SOURCE_NOT_FOUND',+ });+ return;+ }+ const base = body.scope === 'project' ? contentDir : skillsHome;+ const targetHomeRel = resolveDefaultSkillHomeRel(base, body.scope);+ if (targetHomeRel === null) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'No agent skill host is available.',+ { handler: 'skill-duplicate', detail: 'NO_USABLE_SKILL_HOME' },+ );+ return;+ }+ const targetRoot = resolve(base, targetHomeRel);+ const targetDir = resolve(targetRoot, body.toName);+ if (resolveSkillDirForRead(body.scope, body.toName) !== null || existsSync(targetDir)) {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:doc-already-exists',+ `A ${body.scope} skill named "${body.toName}" already exists.`,+ { handler: 'skill-duplicate' },+ );+ return;+ }++ const source = parseSkillDir(sourceDir);+ if (!source) {+ errorResponse(res, 422, 'urn:ok:error:invalid-request', 'Source has no readable skill.', {+ handler: 'skill-duplicate',+ });+ return;+ }+ tracedMkdirSync(targetRoot, { recursive: true });+ tracedCpSync(sourceDir, targetDir, { recursive: true, dereference: true });+ const { fenced, body: sourceBody } = detectFmRegion(source.skillMd);+ // presence-exempt: no CRDT write, no agent identity+ const renamed = applyPatchToFm(fenced, { name: body.toName });+ if (!renamed.ok) {+ applySkillDelete({ skillsRoot: targetRoot, name: body.toName });+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Failed to write duplicated skill.',+ {+ handler: 'skill-duplicate',+ detail: renamed.error.kind,+ },+ );+ return;+ }+ try {+ tracedWriteFileSync(join(targetDir, 'SKILL.md'), `${renamed.nextFenced}${sourceBody}`);+ } catch (error) {+ applySkillDelete({ skillsRoot: targetRoot, name: body.toName });+ throw error;+ }++ if (body.scope === 'project') {+ const targetRel = relative(contentDir, targetDir).split(sep).join('/');+ attributeOkArtifactWrite(+ actor,+ okArtifactKey('skill', '', body.toName),+ `skill-duplicate: ${body.name} -> ${targetRel}`,+ );+ void commitOkArtifactWrite('skill-duplicate');+ }+ signalChannel?.('files');+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();++ successResponse(+ res,+ 200,+ SkillDuplicateSuccessSchema,+ { name: body.toName },+ { handler: 'skill-duplicate' },+ );+ } catch (e) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to duplicate skill.',+ { handler: 'skill-duplicate', cause: e },+ );+ }+ },+ { handler: 'skill-duplicate', method: 'POST' },+ );++ const handleSkill = methodRouter(+ { GET: handleSkillGet, PUT: handleSkillPut, POST: handleSkillMove, DELETE: handleSkillDelete },+ { handler: 'skill' },+ );++ return createApiRouteGroup(+ {+ '/api/skill': handleSkill,+ '/api/skill/edit-external': handleSkillEditExternal,+ '/api/skill/duplicate': handleSkillDuplicate,+ '/api/skill/move-scope': handleSkillMoveScope,+ },+ {+ mutating: [+ '/api/skill',+ '/api/skill/edit-external',+ '/api/skill/duplicate',+ '/api/skill/move-scope',+ ],+ },+ );+}diff --git a/packages/server/src/http/skills-file-routes.test.ts b/packages/server/src/http/skills-file-routes.test.tsnew file mode 100644index 000000000..ebb5a77b3--- /dev/null+++ b/packages/server/src/http/skills-file-routes.test.ts@@ -0,0 +1,59 @@+import { Hocuspocus } from '@hocuspocus/server';+import { describe, expect, test } from 'vitest';+import { AgentSessionManager } from '../agent-sessions.ts';+import { loggerFactory } from '../logger.ts';+import { createSkillsFileRoutes } from './skills-file-routes.ts';++function buildGroup() {+ return createSkillsFileRoutes({+ validateSkillName: () => true,+ parseSkillScope: () => 'project',+ skillsHome: '/nonexistent-skills-home',+ projectDir: undefined,+ resolveBuiltinSkillDir: () => null,+ resolveSkillDirForRead: () => null,+ derivedDocumentIndex: undefined,+ getPrincipal: undefined,+ rejectReservedBuiltinSkill: () => false,+ contentDir: '/nonexistent-content',+ attributeOkArtifactWrite: () => {},+ signalChannel: undefined,+ checkSkillDocConflictGate: () => false,+ extractAgentIdentity: () => ({+ rawAgentId: undefined,+ agentId: 'test',+ agentName: 'test',+ colorSeed: 'test',+ clientName: undefined,+ clientVersion: undefined,+ label: undefined,+ }),+ sessionManager: new AgentSessionManager(new Hocuspocus({ quiet: true })),+ flushDiskAndDetectOutcome: () => Promise.resolve(null),+ respondStaleExternalWrite: () => {},+ respondPersistenceFailure: () => {},+ respondDiskDivergence: () => {},+ okArtifactKey: () => '',+ resolveSkillsRoot: () => '/nonexistent-skills',+ extractActorIdentityFromQuery: () => ({ kind: 'invalid-summary' }),+ captureAndCloseDocuments: () => Promise.resolve(new Map()),+ log: loggerFactory.getLogger('test'),+ commitOkArtifactWrite: () => Promise.resolve(),+ recordDerivedMutationsBestEffort: () => Promise.resolve(),+ });+}++describe('createSkillsFileRoutes table', () => {+ test('registers exactly the two skill-file paths', () => {+ expect([...buildGroup().paths].sort()).toEqual(+ ['/api/skill-file', '/api/skill-file/rename'].sort(),+ );+ });++ test('every skill-file path is mutating (whole-family legacy MUTATING_ROUTES membership)', () => {+ const { table } = buildGroup();+ for (const path of ['/api/skill-file', '/api/skill-file/rename']) {+ expect(table.isMutating(path), path).toBe(true);+ }+ });+});diff --git a/packages/server/src/http/skills-file-routes.ts b/packages/server/src/http/skills-file-routes.tsnew file mode 100644index 000000000..e92d012c2--- /dev/null+++ b/packages/server/src/http/skills-file-routes.ts@@ -0,0 +1,702 @@+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { readFile } from 'node:fs/promises';+import type { ServerResponse } from 'node:http';+import { dirname, join, relative, resolve, sep } from 'node:path';+import {+ EmptyRequestSchema,+ type Principal,+ projectSkillContentDocName,+ SkillFileDeleteSuccessSchema,+ SkillFileGetSuccessSchema,+ SkillFilePutRequestSchema,+ SkillFilePutSuccessSchema,+ SkillFileRenameRequestSchema,+ SkillFileRenameSuccessSchema,+} from '@inkeep/open-knowledge-core';+import type { AgentSessionManager } from '../agent-sessions.ts';+import { composeAndWriteRawBody } from '../bridge-intake.ts';+import {+ applySkillBundleFileDelete,+ applySkillBundleFileRename,+ applySkillBundleFileWrite,+ BUNDLE_FILE_MAX_BYTES,+ BUNDLE_MAX_FILES,+ countBundleFiles,+} from '../content/skills-write.ts';+import type {+ DerivedDocumentIndexApiPort,+ DerivedDocumentIndexMutation,+} from '../derived-document-index.ts';+import { SUPPORTED_DOC_EXTENSIONS } from '../doc-extensions.ts';+import type { StoreFailure } from '../document-durability-state.ts';+import { extractActorIdentity } from '../extract-actor-identity.ts';+import type { PinoLogger } from '../logger.ts';+import { isInternalBundleSkillName } from '../skill-bundles.ts';+import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';+import { errorResponse } from './error-response.ts';+import { methodRouter } from './method-router.ts';+import { withValidation } from './request-validation.ts';+import { successResponse } from './success-response.ts';++export interface SkillsFileRouteDeps {+ validateSkillName: (name: string, res: ServerResponse, handler: string) => boolean;+ parseSkillScope: (+ raw: string | null,+ res: ServerResponse,+ handler: string,+ ) => 'project' | 'global' | null;+ skillsHome: string;+ projectDir: string | undefined;+ resolveBuiltinSkillDir: (+ base: string,+ name: string,+ scope: 'project' | 'global',+ host?: string,+ ) => { dir: string; skillMd: string; hosts: string[]; relPath: string } | null;+ resolveSkillDirForRead: (+ scope: 'project' | 'global',+ name: string,+ host?: string,+ ) => string | null;+ derivedDocumentIndex: DerivedDocumentIndexApiPort | undefined;+ getPrincipal: (() => Principal | null) | undefined;+ rejectReservedBuiltinSkill: (name: string, res: ServerResponse, handler: string) => boolean;+ contentDir: string;+ attributeOkArtifactWrite: (+ actor: ReturnType<typeof extractActorIdentity>,+ artifactKey: string,+ subject: string,+ previousPaths?: Array<{ from: string; to: string }>,+ ) => void;+ signalChannel: ((channel: 'files' | 'lint-config' | 'comments') => void) | undefined;+ checkSkillDocConflictGate: (docName: string, handler: string, res: ServerResponse) => boolean;+ extractAgentIdentity: (body: Record<string, unknown>) => {+ rawAgentId: string | undefined;+ agentId: string;+ agentName: string;+ colorSeed: string;+ clientName: string | undefined;+ clientVersion: string | undefined;+ label: string | undefined;+ };+ sessionManager: AgentSessionManager;+ respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;+ flushDiskAndDetectOutcome: (+ docName: string,+ ) => Promise<+ | { kind: 'failure'; failure: StoreFailure }+ | { kind: 'divergence' }+ | { kind: 'stale-external-write' }+ | null+ >;+ respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;+ respondDiskDivergence: (res: ServerResponse, handler: string) => void;+ okArtifactKey: (+ kind: 'template' | 'folder-frontmatter' | 'folder' | 'skill',+ folder: string,+ name?: string,+ ) => string;+ resolveSkillsRoot: (scope: 'project' | 'global') => string;+ extractActorIdentityFromQuery: (+ url: URL,+ principal: (() => Principal | null) | undefined,+ ) => ReturnType<typeof extractActorIdentity>;+ captureAndCloseDocuments: (+ docNames: string[],+ lifecycleStatus: 'deleted-upstream' | 'renamed',+ ) => Promise<Map<string, string>>;+ log: PinoLogger;+ commitOkArtifactWrite: (context: string) => Promise<void>;+ recordDerivedMutationsBestEffort: (+ mutations: DerivedDocumentIndexMutation[],+ reason: string,+ ) => Promise<void>;+}++export function createSkillsFileRoutes(deps: SkillsFileRouteDeps): ApiRouteGroup {+ const {+ validateSkillName,+ parseSkillScope,+ skillsHome,+ projectDir,+ resolveBuiltinSkillDir,+ resolveSkillDirForRead,+ resolveSkillsRoot,+ getPrincipal,+ rejectReservedBuiltinSkill,+ contentDir,+ checkSkillDocConflictGate,+ extractAgentIdentity,+ sessionManager,+ flushDiskAndDetectOutcome,+ respondStaleExternalWrite,+ respondPersistenceFailure,+ respondDiskDivergence,+ attributeOkArtifactWrite,+ okArtifactKey,+ commitOkArtifactWrite,+ signalChannel,+ extractActorIdentityFromQuery,+ captureAndCloseDocuments,+ derivedDocumentIndex,+ log,+ recordDerivedMutationsBestEffort,+ } = deps;+ function classifySkillFilePath(rel: string): 'reference' | 'script' | 'file' | null {+ if (rel.includes('\x00')) return null;+ const segments = rel+ .replace(/\\/g, '/')+ .split('/')+ .filter((s) => s !== '' && s !== '.');+ if (segments.length < 1 || segments.some((s) => s === '..')) return null;+ if (segments.length === 1 && (segments[0] as string).toLowerCase() === 'skill.md') return null;+ if (segments[0] === 'references' && segments.length >= 2) return 'reference';+ if (segments[0] === 'scripts' && segments.length >= 2) return 'script';+ return 'file';+ }++ function isProjectMdReference(+ scope: 'project' | 'global',+ kind: 'reference' | 'script' | 'file',+ rel: string,+ ): boolean {+ return scope === 'project' && kind === 'reference' && rel.toLowerCase().endsWith('.md');+ }++ function nestedProjectRefDocNames(realDir: string, dirRel: string): string[] {+ const base = resolve(realDir, dirRel);+ const dirDocPrefix = relative(contentDir, realDir).split(sep).join('/');+ let entries: string[];+ try {+ entries = readdirSync(base, { recursive: true, encoding: 'utf-8' });+ } catch {+ return [];+ }+ return entries+ .filter((e) => /\.md$/i.test(e))+ .map((e) => `${dirDocPrefix}/${dirRel}/${e.split(sep).join('/').replace(/\.md$/i, '')}`);+ }++ function projectRefContentDocName(name: string, rel: string): string {+ const extLess = rel.replace(/\.md$/i, '');+ return `${projectSkillContentDocName(name).replace(/\/SKILL$/, '')}/${extLess}`;+ }++ const handleSkillFileGet = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ try {+ const url = new URL(req.url ?? '', 'http://localhost');+ const name = url.searchParams.get('name') ?? '';+ if (!validateSkillName(name, res, 'skill-file-get')) return;+ const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-file-get');+ if (scope === null) return;+ const rel = url.searchParams.get('path') ?? '';+ const builtinBase = isInternalBundleSkillName(name)+ ? scope === 'global'+ ? skillsHome+ : projectDir+ : undefined;+ const builtinHost = url.searchParams.get('host') ?? undefined;+ const builtin = builtinBase+ ? resolveBuiltinSkillDir(builtinBase, name, scope, builtinHost)+ : null;+ if (rel === '' || rel.includes('\x00')) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid skill file path.', {+ handler: 'skill-file-get',+ });+ return;+ }+ const kind =+ (builtin && rel === 'SKILL.md' ? 'reference' : classifySkillFilePath(rel)) ?? 'reference';+ const host = builtinHost;+ const resolvedSkillDir = builtinBase+ ? (builtin?.dir ?? null)+ : resolveSkillDirForRead(scope, name, host);+ if (resolvedSkillDir === null && host !== undefined) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {+ handler: 'skill-file-get',+ detail: `No skill "${name}" (${scope}) in ${host}.`,+ });+ return;+ }+ const skillDir = resolvedSkillDir ?? resolve(resolveSkillsRoot(scope), name);+ const abs = resolve(skillDir, rel);+ if (abs !== skillDir && !abs.startsWith(`${skillDir}${sep}`)) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Skill file path escapes the skill dir.',+ {+ handler: 'skill-file-get',+ },+ );+ return;+ }+ let resolvedAbs = abs;+ let resolvedRel = rel;+ if (!existsSync(resolvedAbs)) {+ const docStem = rel.match(/^(.*)\.(?:md|mdx)$/);+ const sibling = docStem+ ? SUPPORTED_DOC_EXTENSIONS.map((ext) => `${docStem[1]}${ext}`).find(+ (candidate) => candidate !== rel && existsSync(resolve(skillDir, candidate)),+ )+ : undefined;+ if (sibling === undefined) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill file not found.', {+ handler: 'skill-file-get',+ detail: `${rel} not found in skill "${name}" (${scope}).`,+ });+ return;+ }+ resolvedRel = sibling;+ resolvedAbs = resolve(skillDir, sibling);+ }+ const buf = await readFile(resolvedAbs);+ if (buf.includes(0)) {+ errorResponse(+ res,+ 415,+ 'urn:ok:error:invalid-request',+ 'Skill file is binary — only text bundle files are readable via MCP.',+ { handler: 'skill-file-get' },+ );+ return;+ }+ successResponse(+ res,+ 200,+ SkillFileGetSuccessSchema,+ { path: resolvedRel.replace(/\\/g, '/'), kind, text: buf.toString('utf-8') },+ { handler: 'skill-file-get' },+ );+ } catch (e) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to read skill file.',+ {+ handler: 'skill-file-get',+ cause: e,+ },+ );+ }+ },+ { handler: 'skill-file-get', method: 'GET', skipBodyParse: true },+ );++ const handleSkillFilePut = withValidation(+ SkillFilePutRequestSchema,+ async (_req, res, body) => {+ try {+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-file-put',+ });+ return;+ }+ if (!validateSkillName(body.name, res, 'skill-file-put')) return;+ if (rejectReservedBuiltinSkill(body.name, res, 'skill-file-put')) return;+ const kind = classifySkillFilePath(body.path);+ if (kind === null) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Invalid skill file path (must name a file inside the skill dir, no `..`).',+ { handler: 'skill-file-put' },+ );+ return;+ }+ if (Buffer.byteLength(body.content, 'utf-8') > BUNDLE_FILE_MAX_BYTES) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Skill file exceeds the 256 KB per-file cap.',+ { handler: 'skill-file-put' },+ );+ return;+ }+ const skillDirAbs = resolveSkillDirForRead(body.scope, body.name);+ if (skillDirAbs === null || !existsSync(join(skillDirAbs, 'SKILL.md'))) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {+ handler: 'skill-file-put',+ detail: `Create skill "${body.name}" before adding bundle files.`,+ });+ return;+ }+ const fileBase = body.scope === 'project' ? contentDir : skillsHome;+ const skillDirRel = relative(fileBase, skillDirAbs).split(sep).join('/');+ const rel = body.path.replace(/\\/g, '/');+ const routedThroughContent = isProjectMdReference(body.scope, kind, rel);+ let created: boolean;++ if (routedThroughContent) {+ /**+ * A project `.md` reference routes through the sanctioned paired-write primitive+ * (precedent #24 / #38), the same branch as the SKILL.md body.+ */+ const refDocName = `${skillDirRel}/${rel.replace(/\.mdx?$/i, '')}`;+ if (checkSkillDocConflictGate(refDocName, 'skill-file-put', res)) return;+ created = !existsSync(resolve(skillDirAbs, rel));+ if (created && countBundleFiles(skillDirAbs) >= BUNDLE_MAX_FILES) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ `Skill "${body.name}" already holds ${BUNDLE_MAX_FILES} bundle files (the cap) — delete one before adding another.`,+ { handler: 'skill-file-put' },+ );+ return;+ }+ const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(+ body as unknown as Record<string, unknown>,+ );+ const session = await sessionManager.getSession(refDocName, agentId, {+ displayName: agentName,+ colorSeed,+ clientName,+ });+ session.dc.document.transact(() => {+ composeAndWriteRawBody(session.dc.document, body.content, 'agent');+ }, session.origin);+ const flushOutcome = await flushDiskAndDetectOutcome(refDocName);+ if (flushOutcome?.kind === 'failure') {+ respondPersistenceFailure(res, flushOutcome.failure, 'skill-file-put');+ return;+ }+ if (flushOutcome?.kind === 'divergence') {+ respondDiskDivergence(res, 'skill-file-put');+ return;+ }+ if (flushOutcome?.kind === 'stale-external-write') {+ respondStaleExternalWrite(res, 'skill-file-put', refDocName);+ return;+ }+ } else {+ const fsResult = applySkillBundleFileWrite({+ skillsRoot: dirname(skillDirAbs),+ name: body.name,+ relPath: rel,+ content: body.content,+ });+ if (!fsResult.ok) {+ const status =+ fsResult.error.code === 'WRITE_ERROR'+ ? 500+ : fsResult.error.code === 'SKILL_NOT_FOUND'+ ? 404+ : 400;+ errorResponse(+ res,+ status,+ status === 500+ ? 'urn:ok:error:internal-server-error'+ : status === 404+ ? 'urn:ok:error:not-found'+ : 'urn:ok:error:invalid-request',+ status === 500 ? 'Failed to write skill file.' : 'Invalid skill file request.',+ {+ handler: 'skill-file-put',+ detail: fsResult.error.code,+ cause: new Error(fsResult.error.message),+ },+ );+ return;+ }+ created = fsResult.created;+ }++ if (body.scope === 'project') {+ attributeOkArtifactWrite(+ actor,+ okArtifactKey('skill', '', body.name),+ `${created ? 'skill-file-create' : 'skill-file-edit'}: ${skillDirRel}/${rel}`,+ );+ void commitOkArtifactWrite('skill-file-put');+ }+ signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillFilePutSuccessSchema,+ { path: rel, created, kind, content: routedThroughContent },+ { handler: 'skill-file-put' },+ );+ } catch (e) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to write skill file.',+ {+ handler: 'skill-file-put',+ cause: e,+ },+ );+ }+ },+ { handler: 'skill-file-put', method: 'PUT' },+ );++ const handleSkillFileDelete = withValidation(+ EmptyRequestSchema,+ async (req, res) => {+ try {+ const url = new URL(req.url ?? '', 'http://localhost');+ const sp = url.searchParams;+ const name = sp.get('name') ?? '';+ if (!validateSkillName(name, res, 'skill-file-delete')) return;+ if (rejectReservedBuiltinSkill(name, res, 'skill-file-delete')) return;+ const scope = parseSkillScope(sp.get('scope'), res, 'skill-file-delete');+ if (scope === null) return;+ const rel = (sp.get('path') ?? '').replace(/\\/g, '/');+ const kind = classifySkillFilePath(rel);+ if (kind === null) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Invalid skill file path (must name a file inside the skill dir).',+ { handler: 'skill-file-delete' },+ );+ return;+ }+ const actor = extractActorIdentityFromQuery(url, getPrincipal);+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-file-delete',+ });+ return;+ }+ const realDir = resolveSkillDirForRead(scope, name);+ const skillsRoot = realDir !== null ? dirname(realDir) : resolveSkillsRoot(scope);++ const bundleAbs = resolve(realDir ?? join(skillsRoot, name), rel);+ if (existsSync(bundleAbs) && isProjectMdReference(scope, kind, rel)) {+ const extLess = rel.replace(/\.md$/i, '');+ const refDoc =+ realDir !== null+ ? `${relative(contentDir, realDir).split(sep).join('/')}/${extLess}`+ : projectRefContentDocName(name, rel);+ await captureAndCloseDocuments([refDoc], 'deleted-upstream');+ } else if (+ scope === 'project' &&+ realDir !== null &&+ existsSync(bundleAbs) &&+ statSync(bundleAbs).isDirectory()+ ) {+ const docs = nestedProjectRefDocNames(realDir, rel);+ if (docs.length > 0) await captureAndCloseDocuments(docs, 'deleted-upstream');+ }++ const result = applySkillBundleFileDelete({ skillsRoot, name, relPath: rel });+ if (!result.ok) {+ const status = result.error.code === 'UNLINK_FAILED' ? 500 : 400;+ errorResponse(+ res,+ status,+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',+ status === 500 ? 'Failed to delete skill file.' : 'Invalid skill file request.',+ {+ handler: 'skill-file-delete',+ detail: result.error.code,+ cause: new Error(result.error.message),+ },+ );+ return;+ }+ if (result.existed && scope === 'project') {+ attributeOkArtifactWrite(+ actor,+ okArtifactKey('skill', '', name),+ `skill-file-delete: ${+ realDir !== null+ ? `${relative(contentDir, realDir).split(sep).join('/')}/${rel}`+ : `${name}/${rel}`+ }`,+ );+ void commitOkArtifactWrite('skill-file-delete');+ }+ if (result.existed) signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillFileDeleteSuccessSchema,+ { path: rel, existed: result.existed, kind },+ { handler: 'skill-file-delete' },+ );+ } catch (e) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to delete skill file.',+ {+ handler: 'skill-file-delete',+ cause: e,+ },+ );+ }+ },+ { handler: 'skill-file-delete', method: 'DELETE', skipBodyParse: true },+ );++ const handleSkillFile = methodRouter(+ { GET: handleSkillFileGet, PUT: handleSkillFilePut, DELETE: handleSkillFileDelete },+ { handler: 'skill-file' },+ );+ const handleSkillFileRename = withValidation(+ SkillFileRenameRequestSchema,+ async (_req, res, body) => {+ try {+ if (!validateSkillName(body.name, res, 'skill-file-rename')) return;+ if (rejectReservedBuiltinSkill(body.name, res, 'skill-file-rename')) return;+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-file-rename',+ });+ return;+ }+ const from = body.from.replace(/\\/g, '/');+ const to = body.to.replace(/\\/g, '/');+ const fromKind = classifySkillFilePath(from);+ const toKind = classifySkillFilePath(to);+ if (fromKind === null || toKind === null) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Both paths must stay inside the skill dir.',+ { handler: 'skill-file-rename', detail: fromKind === null ? from : to },+ );+ return;+ }+ const realDir = resolveSkillDirForRead(body.scope, body.name);+ if (realDir === null) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {+ handler: 'skill-file-rename',+ });+ return;+ }+ const skillsRoot = dirname(realDir);++ const fromIsDoc = isProjectMdReference(body.scope, fromKind, from);+ const toIsDoc = isProjectMdReference(body.scope, toKind, to);+ const dirRel = relative(contentDir, realDir).split(sep).join('/');+ const fromDocName = fromIsDoc ? `${dirRel}/${from.replace(/\.md$/i, '')}` : null;+ const toDocName = toIsDoc ? `${dirRel}/${to.replace(/\.md$/i, '')}` : null;++ if (+ fromDocName !== null &&+ checkSkillDocConflictGate(fromDocName, 'skill-file-rename', res)+ )+ return;+ if (fromDocName !== null) {+ await captureAndCloseDocuments([fromDocName], 'deleted-upstream');+ } else if (body.scope === 'project') {+ const fromAbs = resolve(realDir, from);+ if (existsSync(fromAbs) && statSync(fromAbs).isDirectory()) {+ const docs = nestedProjectRefDocNames(realDir, from);+ if (docs.length > 0) await captureAndCloseDocuments(docs, 'deleted-upstream');+ }+ }++ const result = applySkillBundleFileRename({+ skillsRoot,+ name: body.name,+ relPath: from,+ toRelPath: to,+ });+ if (!result.ok) {+ const status = result.error.code === 'RENAME_FAILED' ? 500 : 400;+ errorResponse(+ res,+ status,+ status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',+ result.error.message,+ { handler: 'skill-file-rename', detail: result.error.code },+ );+ return;+ }++ if (derivedDocumentIndex) {+ const mutations: DerivedDocumentIndexMutation[] = [];+ if (fromDocName !== null && toDocName !== null) {+ try {+ mutations.push({+ kind: 'rename',+ oldDocumentName: fromDocName,+ newDocumentName: toDocName,+ markdown: readFileSync(resolve(skillsRoot, body.name, to), 'utf-8'),+ });+ } catch {+ mutations.push({ kind: 'delete', documentName: fromDocName });+ }+ } else if (fromDocName !== null) {+ mutations.push({ kind: 'delete', documentName: fromDocName });+ } else if (toDocName !== null) {+ try {+ mutations.push({+ kind: 'upsert',+ documentName: toDocName,+ markdown: readFileSync(resolve(skillsRoot, body.name, to), 'utf-8'),+ });+ } catch {}+ }+ await recordDerivedMutationsBestEffort(mutations, 'skill-file-rename');+ }++ if (body.scope === 'project') {+ attributeOkArtifactWrite(+ actor,+ okArtifactKey('skill', '', body.name),+ `skill-file-rename: ${body.name}/${from} -> ${to}`,+ );+ void commitOkArtifactWrite('skill-file-rename');+ }+ signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillFileRenameSuccessSchema,+ {+ from,+ to,+ ...(fromDocName !== null ? { fromDocName } : {}),+ ...(toDocName !== null ? { toDocName } : {}),+ },+ { handler: 'skill-file-rename' },+ );+ } catch (err) {+ log.error({ err }, '[skill-file-rename] failed');+ if (!res.headersSent) {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Failed to rename skill file.',+ { handler: 'skill-file-rename' },+ );+ }+ }+ },+ { handler: 'skill-file-rename', method: 'POST' },+ );++ return createApiRouteGroup(+ { '/api/skill-file': handleSkillFile, '/api/skill-file/rename': handleSkillFileRename },+ { mutating: ['/api/skill-file', '/api/skill-file/rename'] },+ );+}diff --git a/packages/server/src/http/skills-import-routes.test.ts b/packages/server/src/http/skills-import-routes.test.tsnew file mode 100644index 000000000..fee811c06--- /dev/null+++ b/packages/server/src/http/skills-import-routes.test.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from 'vitest';+import { createSkillsImportRoutes } from './skills-import-routes.ts';++function unexpectedCall(): never {+ throw new Error('Route table construction must not invoke skill services.');+}++function buildGroup() {+ return createSkillsImportRoutes({+ projectDir: undefined,+ getPrincipal: undefined,+ skillImportService: { runSkillImport: unexpectedCall },+ bumpSkillsCatalogGen: () => {},+ contentFilter: undefined,+ scheduleDeferredIgnoreRebuild: () => {},+ signalChannel: undefined,+ parseSkillScope: () => 'project',+ });+}++describe('createSkillsImportRoutes table', () => {+ test('registers exactly the three skill-import paths', () => {+ expect([...buildGroup().paths].sort()).toEqual(+ ['/api/skill/import', '/api/skills/import-bulk', '/api/skill-upload'].sort(),+ );+ });++ test('every skill-import path is mutating (whole-family legacy MUTATING_ROUTES membership)', () => {+ const { table } = buildGroup();+ for (const path of ['/api/skill/import', '/api/skills/import-bulk', '/api/skill-upload']) {+ expect(table.isMutating(path), path).toBe(true);+ }+ });+});diff --git a/packages/server/src/http/skills-import-routes.ts b/packages/server/src/http/skills-import-routes.tsnew file mode 100644index 000000000..ce11d68bf--- /dev/null+++ b/packages/server/src/http/skills-import-routes.ts@@ -0,0 +1,700 @@+import { mkdtempSync } from 'node:fs';+import type { IncomingMessage, ServerResponse } from 'node:http';+import { tmpdir } from 'node:os';+import { dirname, join, resolve, sep } from 'node:path';+import {+ isOpenKnowledgeSkillsSource,+ type Principal,+ RENAMED_PACK_SKILLS,+ type SkillImportBulkResult,+ SkillImportRequestSchema,+ SkillImportSuccessSchema,+ SkillsImportBulkRequestSchema,+ SkillsImportBulkSuccessSchema,+} from '@inkeep/open-knowledge-core';+import {+ discoverSkillDirs,+ fetchSource,+ parseSkillDir,+ parseSource,+ readSkillDirMeta,+ readWellKnownIndex,+ resolveSkillsShImportSource,+ SkillFetchError,+ type SourceSpec,+ type WellKnownIndex,+} from '@inkeep/open-knowledge-core/skills-catalog';+import { type Entry, fromBuffer as yauzlFromBuffer, type ZipFile } from 'yauzl';+import type { ContentFilter } from '../content-filter.ts';+import { extractActorIdentity } from '../extract-actor-identity.ts';+import { tracedMkdirSync, tracedRmSync, tracedWriteFileSync } from '../fs-traced.ts';+import { getLogger } from '../logger.ts';+import { createMultipartParser, type MultipartParser } from '../multipart.ts';+import type { SkillImportOutcome, SkillImportService } from '../services/skill-import.ts';+import { rejectDisallowedGitSpec } from '../skill-git-spec-guard.ts';+import { resolveSkillInstallReportSettings } from '../skill-install-report-config.ts';+import { reportSkillInstall } from '../skills-sh-install-report.ts';+import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';+import { errorResponse } from './error-response.ts';+import { withValidation } from './request-validation.ts';+import { successResponse } from './success-response.ts';++export interface SkillsImportRouteDeps {+ projectDir: string | undefined;+ getPrincipal: (() => Principal | null) | undefined;+ skillImportService: SkillImportService;+ bumpSkillsCatalogGen: () => void;+ contentFilter: ContentFilter | undefined;+ scheduleDeferredIgnoreRebuild: () => void;+ signalChannel: ((channel: 'files' | 'lint-config' | 'comments') => void) | undefined;+ parseSkillScope: (+ raw: string | null,+ res: ServerResponse,+ handler: string,+ ) => 'project' | 'global' | null;+}++export function createSkillsImportRoutes(deps: SkillsImportRouteDeps): ApiRouteGroup {+ const {+ projectDir,+ getPrincipal,+ skillImportService,+ bumpSkillsCatalogGen,+ contentFilter,+ scheduleDeferredIgnoreRebuild,+ signalChannel,+ parseSkillScope,+ } = deps;+ function publisherFromSource(source: string): string | undefined {+ const m = /github\.com[/:]([\w.-]+)\//.exec(source);+ return m ? m[1] : undefined;+ }++ function respondSkillImport(res: ServerResponse, outcome: SkillImportOutcome): void {+ if (outcome.ok) {+ successResponse(res, 200, SkillImportSuccessSchema, outcome.body, {+ handler: 'skill-import',+ });+ return;+ }+ errorResponse(res, outcome.status, outcome.urn, outcome.title, {+ handler: 'skill-import',+ ...(outcome.detail !== undefined ? { detail: outcome.detail } : {}),+ ...(outcome.cause !== undefined ? { cause: outcome.cause } : {}),+ });+ }++ const handleSkillImport = withValidation(+ SkillImportRequestSchema,+ async (_req, res, body) => {+ let cleanup: () => void = () => {};+ try {+ if (!projectDir) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {+ handler: 'skill-import',+ detail: 'NO_PROJECT_ROOT',+ });+ return;+ }+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-import',+ });+ return;+ }+ const scope = body.scope;++ let acquiredDir: string | null = null;+ let sourceLabel: string;+ let ref: string | undefined;+ let publisher: string | undefined;+ let upstreamSkill: string | undefined;+ let resolvedSourceForReport = body.source;++ {+ const rawSource = body.source;+ try {+ const skillsSh = await resolveSkillsShImportSource(rawSource, body.skill);+ const resolvedSource = skillsSh?.source ?? rawSource;+ resolvedSourceForReport = resolvedSource;+ const selectedSkill = body.skill ?? skillsSh?.skill;+ const spec = skillsSh?.spec ?? parseSource(resolvedSource);+ if (!spec) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Unrecognized import source.',+ {+ handler: 'skill-import',+ detail:+ 'Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.',+ },+ );+ return;+ }+ if (rejectDisallowedGitSpec(res, spec, 'skill-import')) return;+ const fetched = await fetchSource(spec);+ cleanup = fetched.cleanup;+ ref = fetched.ref;+ const dirs = discoverSkillDirs(fetched.dir);+ if (dirs.length === 0) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in source.', {+ handler: 'skill-import',+ });+ return;+ }+ let pick = dirs[0];+ if (selectedSkill) {+ const found =+ dirs.find((d) => d.name === selectedSkill) ??+ dirs.find((d) => readSkillDirMeta(d.dir)?.name === selectedSkill) ??+ dirs.find((d) => d.name === RENAMED_PACK_SKILLS[selectedSkill]);+ if (!found) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Named skill not in source.', {+ handler: 'skill-import',+ detail: `--skill "${selectedSkill}" not among: ${dirs.map((d) => d.name).join(', ')}.`,+ });+ return;+ }+ pick = found;+ } else if (dirs.length > 1) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Source has multiple skills; pass `skill` to choose one.',+ { handler: 'skill-import', detail: dirs.map((d) => d.name).join(', ') },+ );+ return;+ }+ acquiredDir = pick.dir;+ upstreamSkill = pick.name;+ sourceLabel = rawSource;+ publisher = skillsSh?.publisher ?? publisherFromSource(resolvedSource);+ } catch (e) {+ if (e instanceof SkillFetchError) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {+ handler: 'skill-import',+ cause: e,+ });+ return;+ }+ throw e;+ }+ }++ if (!acquiredDir) {+ errorResponse(res, 422, 'urn:ok:error:invalid-request', 'Source has no readable skill.', {+ handler: 'skill-import',+ });+ return;+ }+ const outcome = await skillImportService.runSkillImport({+ acquiredDir,+ scope,+ sourceLabel,+ ref,+ publisher,+ upstreamSkill,+ actor,+ skipProjection: body.install === false,+ });+ if (+ outcome.ok &&+ (body.marketplace === true || isOpenKnowledgeSkillsSource(resolvedSourceForReport))+ ) {+ void reportSkillInstall(+ { source: resolvedSourceForReport, skills: [outcome.body.name] },+ resolveSkillInstallReportSettings(),+ );+ }+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();+ signalChannel?.('files');++ respondSkillImport(res, outcome);+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to import skill.', {+ handler: 'skill-import',+ cause: e,+ });+ } finally {+ cleanup();+ }+ },+ { handler: 'skill-import', method: 'POST' },+ );++ const handleSkillsImportBulk = withValidation(+ SkillsImportBulkRequestSchema,+ async (_req, res, body) => {+ let cleanup: () => void = () => {};+ try {+ if (!projectDir) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {+ handler: 'skills-import-bulk',+ detail: 'NO_PROJECT_ROOT',+ });+ return;+ }+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skills-import-bulk',+ });+ return;+ }+ const rawSource = body.source;+ let siteSpec: (SourceSpec & { kind: 'well-known' }) | null = null;+ let siteIndex: WellKnownIndex | null = null;+ let dirs: ReturnType<typeof discoverSkillDirs> = [];+ let ref: string | undefined;+ let publisher: string | undefined;+ let resolvedSourceForReport = rawSource;+ try {+ const skillsSh = await resolveSkillsShImportSource(rawSource, body.skills[0]);+ const resolvedSource = skillsSh?.source ?? rawSource;+ resolvedSourceForReport = resolvedSource;+ const spec = skillsSh?.spec ?? parseSource(resolvedSource);+ if (!spec) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unrecognized import source.', {+ handler: 'skills-import-bulk',+ detail:+ 'Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.',+ });+ return;+ }+ if (rejectDisallowedGitSpec(res, spec, 'skills-import-bulk')) return;+ publisher = skillsSh?.publisher ?? publisherFromSource(resolvedSource);+ if (spec.kind === 'well-known') {+ siteSpec = spec;+ siteIndex = await readWellKnownIndex(spec.origin);+ } else {+ const fetched = await fetchSource(spec);+ cleanup = fetched.cleanup;+ ref = fetched.ref;+ dirs = discoverSkillDirs(fetched.dir);+ }+ } catch (e) {+ if (e instanceof SkillFetchError) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {+ handler: 'skills-import-bulk',+ cause: e,+ });+ return;+ }+ throw e;+ }+ if (siteSpec === null && dirs.length === 0) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in source.', {+ handler: 'skills-import-bulk',+ });+ return;+ }+ const results: SkillImportBulkResult[] = [];+ for (const requested of new Set(body.skills)) {+ let acquiredDir: string;+ let upstreamSkill: string;+ let perSkill: () => void = () => {};+ if (siteSpec !== null) {+ try {+ const one = await fetchSource(+ { ...siteSpec, skill: requested },+ siteIndex ? { index: siteIndex } : {},+ );+ acquiredDir = one.dir;+ perSkill = one.cleanup;+ upstreamSkill = requested;+ } catch (e) {+ results.push({+ requested,+ status: e instanceof SkillFetchError ? 'not-found' : 'failed',+ warnings: [],+ ...(e instanceof SkillFetchError ? {} : { error: String(e) }),+ });+ continue;+ }+ } else {+ const found =+ dirs.find((d) => d.name === requested) ??+ dirs.find((d) => parseSkillDir(d.dir)?.name === requested) ??+ dirs.find((d) => d.name === RENAMED_PACK_SKILLS[requested]);+ if (!found) {+ results.push({ requested, status: 'not-found', warnings: [] });+ continue;+ }+ acquiredDir = found.dir;+ upstreamSkill = found.name;+ }+ try {+ const outcome = await skillImportService.runSkillImport({+ acquiredDir,+ scope: body.scope,+ sourceLabel: rawSource,+ ref,+ publisher,+ upstreamSkill,+ actor,+ skipProjection: body.install === false,+ });+ if (!outcome.ok) {+ getLogger('skills-import-bulk').warn(+ { skill: requested, err: outcome.cause, detail: outcome.detail },+ 'bulk import: one skill failed (rest continue)',+ );+ results.push({+ requested,+ status: 'failed',+ warnings: [],+ error: outcome.detail ?? outcome.title,+ });+ continue;+ }+ results.push({+ requested,+ status: outcome.body.alreadyImported ? 'already-imported' : 'imported',+ name: outcome.body.name,+ ...(outcome.body.collisionRenamedFrom !== undefined+ ? { collisionRenamedFrom: outcome.body.collisionRenamedFrom }+ : {}),+ warnings: outcome.body.warnings,+ });+ } catch (e) {+ getLogger('skills-import-bulk').warn(+ { skill: requested, err: e },+ 'bulk import: one skill threw (rest continue)',+ );+ results.push({+ requested,+ status: 'failed',+ warnings: [],+ error: e instanceof Error ? e.message : String(e),+ });+ } finally {+ perSkill();+ }+ }+ if (body.marketplace === true || isOpenKnowledgeSkillsSource(resolvedSourceForReport)) {+ const importedNames = results+ .filter((r) => r.status === 'imported')+ .map((r) => r.requested);+ if (importedNames.length > 0) {+ void reportSkillInstall(+ { source: resolvedSourceForReport, skills: importedNames },+ resolveSkillInstallReportSettings(),+ );+ }+ }+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();+ signalChannel?.('files');++ successResponse(+ res,+ 200,+ SkillsImportBulkSuccessSchema,+ {+ results,+ imported: results.filter((r) => r.status === 'imported').length,+ alreadyImported: results.filter((r) => r.status === 'already-imported').length,+ failed: results.filter((r) => r.status === 'failed' || r.status === 'not-found').length,+ },+ { handler: 'skills-import-bulk' },+ );+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to import skills.', {+ handler: 'skills-import-bulk',+ cause: e,+ });+ } finally {+ cleanup();+ }+ },+ { handler: 'skills-import-bulk', method: 'POST' },+ );++ const UPLOAD_MAX_FILES = 200;+ const UPLOAD_MAX_ENTRY_BYTES = 8 * 1024 * 1024;+ const UPLOAD_MAX_TOTAL_BYTES = 32 * 1024 * 1024;++ function resolveUploadPath(root: string, rel: string): string | null {+ const norm = rel.split('\\').join('/').replace(/^\/+/, '');+ if (norm === '' || norm.split('/').some((seg) => seg === '..')) return null;+ const abs = resolve(root, norm);+ if (abs !== root && !abs.startsWith(root + sep)) return null;+ return abs;+ }++ interface UploadedPart {+ relPath: string;+ data: Buffer;+ }++ function readSkillUploadParts(req: IncomingMessage): Promise<UploadedPart[]> {+ return new Promise((resolveP, reject) => {+ let bb: MultipartParser;+ try {+ bb = createMultipartParser(req, {+ files: UPLOAD_MAX_FILES,+ fields: 10,+ fieldSize: 2 * 1024,+ fileSize: UPLOAD_MAX_ENTRY_BYTES,+ });+ } catch (err) {+ reject(err);+ return;+ }+ const parts: UploadedPart[] = [];+ let total = 0;+ let aborted: Error | null = null;+ const abort = (err: Error) => {+ if (aborted) return;+ aborted = err;+ req.unpipe(bb);+ req.destroy();+ bb.destroy();+ reject(err);+ };+ bb.on('file', (_field, stream, info) => {+ const chunks: Buffer[] = [];+ let truncated = false;+ stream.on('data', (c: Buffer) => {+ if (aborted) return;+ total += c.length;+ if (total > UPLOAD_MAX_TOTAL_BYTES) {+ abort(new Error('Upload too large.'));+ return;+ }+ chunks.push(c);+ });+ stream.on('limit', () => {+ truncated = true;+ });+ stream.on('end', () => {+ if (aborted) return;+ if (truncated) {+ aborted = new Error(`File "${info.filename}" exceeds the per-file size limit.`);+ return;+ }+ parts.push({ relPath: info.filename || 'file', data: Buffer.concat(chunks) });+ });+ });+ bb.on('error', reject);+ bb.on('close', () => (aborted ? reject(aborted) : resolveP(parts)));+ req.pipe(bb);+ });+ }++ function unzipBufferToDir(buffer: Buffer, destDir: string): Promise<void> {+ return new Promise((resolveP, reject) => {+ yauzlFromBuffer(buffer, { lazyEntries: true }, (err, zip?: ZipFile) => {+ if (err || !zip) {+ reject(err ?? new Error('Unreadable archive.'));+ return;+ }+ let total = 0;+ let entries = 0;+ const fail = (e: unknown) => {+ try {+ zip.close();+ } catch {}+ reject(e instanceof Error ? e : new Error(String(e)));+ };+ zip.on('entry', (entry: Entry) => {+ if (++entries > UPLOAD_MAX_FILES) {+ fail(new Error('Archive has too many entries.'));+ return;+ }+ const abs = resolveUploadPath(destDir, entry.fileName);+ if (!abs) {+ fail(new Error(`Unsafe archive entry: ${entry.fileName}`));+ return;+ }+ if (entry.fileName.endsWith('/')) {+ tracedMkdirSync(abs, { recursive: true });+ zip.readEntry();+ return;+ }+ if (entry.uncompressedSize > UPLOAD_MAX_ENTRY_BYTES) {+ fail(new Error(`Archive entry too large: ${entry.fileName}`));+ return;+ }+ zip.openReadStream(entry, (e2, rs) => {+ if (e2 || !rs) {+ fail(e2 ?? new Error('Could not read archive entry.'));+ return;+ }+ const chunks: Buffer[] = [];+ rs.on('data', (c: Buffer) => {+ total += c.length;+ if (total > UPLOAD_MAX_TOTAL_BYTES) {+ rs.destroy();+ fail(new Error('Archive expands beyond the size limit.'));+ return;+ }+ chunks.push(c);+ });+ rs.on('error', fail);+ rs.on('end', () => {+ try {+ tracedMkdirSync(dirname(abs), { recursive: true });+ tracedWriteFileSync(abs, Buffer.concat(chunks));+ } catch (writeErr) {+ fail(writeErr instanceof Error ? writeErr : new Error(String(writeErr)));+ return;+ }+ zip.readEntry();+ });+ });+ });+ zip.on('end', () => resolveP());+ zip.on('error', fail);+ zip.readEntry();+ });+ });+ }++ async function handleSkillUpload(req: IncomingMessage, res: ServerResponse): Promise<void> {+ const tmp = mkdtempSync(join(tmpdir(), 'ok-skill-upload-'));+ const cleanup = () => {+ try {+ tracedRmSync(tmp, { recursive: true, force: true });+ } catch {}+ };+ try {+ if (!projectDir) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {+ handler: 'skill-upload',+ detail: 'NO_PROJECT_ROOT',+ });+ return;+ }+ if ((req.method ?? '').toUpperCase() !== 'POST') {+ errorResponse(res, 405, 'urn:ok:error:invalid-request', 'Use POST to upload a skill.', {+ handler: 'skill-upload',+ });+ return;+ }+ const url = new URL(req.url ?? '', 'http://localhost');+ const scope = parseSkillScope(url.searchParams.get('scope'), res, 'skill-upload');+ if (!scope) return;+ const queryField = (key: string): string | undefined =>+ url.searchParams.get(key) ?? undefined;+ const actor = extractActorIdentity(+ {+ agentId: queryField('agentId'),+ agentName: queryField('agentName'),+ colorSeed: queryField('colorSeed'),+ clientName: queryField('clientName'),+ summary: queryField('summary'),+ },+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-upload',+ });+ return;+ }++ let parts: UploadedPart[];+ try {+ parts = await readSkillUploadParts(req);+ } catch (e) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not read the upload.', {+ handler: 'skill-upload',+ cause: e,+ });+ return;+ }+ if (parts.length === 0) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No files uploaded.', {+ handler: 'skill-upload',+ });+ return;+ }++ const single = parts.length === 1 ? parts[0] : null;+ const zipName = single && /\.(zip|skill)$/i.test(single.relPath) ? single.relPath : null;+ if (single && zipName) {+ try {+ await unzipBufferToDir(single.data, tmp);+ } catch (e) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not unpack the archive.', {+ handler: 'skill-upload',+ cause: e,+ });+ return;+ }+ } else {+ for (const part of parts) {+ const abs = resolveUploadPath(tmp, part.relPath);+ if (!abs) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unsafe file path in upload.', {+ handler: 'skill-upload',+ detail: part.relPath,+ });+ return;+ }+ tracedMkdirSync(dirname(abs), { recursive: true });+ tracedWriteFileSync(abs, part.data);+ }+ }++ const dirs = discoverSkillDirs(tmp);+ if (dirs.length === 0) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'No SKILL.md found in the upload.', {+ handler: 'skill-upload',+ });+ return;+ }+ if (dirs.length > 1) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Upload contains multiple skills; upload one at a time.',+ { handler: 'skill-upload', detail: dirs.map((d) => d.name).join(', ') },+ );+ return;+ }+ const pick = dirs[0];+ respondSkillImport(+ res,+ await skillImportService.runSkillImport({+ acquiredDir: pick.dir,+ scope,+ sourceLabel: `upload:${zipName ?? pick.name}`,+ upstreamSkill: pick.name,+ actor,+ }),+ );+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to upload skill.', {+ handler: 'skill-upload',+ cause: e,+ });+ } finally {+ cleanup();+ }+ }++ return createApiRouteGroup(+ {+ '/api/skill/import': handleSkillImport,+ '/api/skills/import-bulk': handleSkillsImportBulk,+ '/api/skill-upload': handleSkillUpload,+ },+ { mutating: ['/api/skill/import', '/api/skills/import-bulk', '/api/skill-upload'] },+ );+}diff --git a/packages/server/src/http/skills-install-routes.test.ts b/packages/server/src/http/skills-install-routes.test.tsnew file mode 100644index 000000000..32f4324e5--- /dev/null+++ b/packages/server/src/http/skills-install-routes.test.ts@@ -0,0 +1,52 @@+import { describe, expect, test } from 'vitest';+import { loggerFactory } from '../logger.ts';+import { createSkillsInstallRoutes } from './skills-install-routes.ts';++function unexpectedCall(): never {+ throw new Error('Route table construction must not invoke skill services.');+}++function buildGroup() {+ return createSkillsInstallRoutes({+ resolveSkillsRoot: () => '/nonexistent-skills',+ validateSkillName: () => true,+ projectDir: undefined,+ skillInstallBase: () => undefined,+ contentDir: '/nonexistent-content',+ skillsHome: '/nonexistent-skills-home',+ shippedBundleSkillMd: () => null,+ flushDiskAndDetectOutcome: () => Promise.resolve(null),+ respondStaleExternalWrite: unexpectedCall,+ skillInstallOps: {+ resolveFork: unexpectedCall,+ applyAddRemove: unexpectedCall,+ promoteStoreBackedSource: unexpectedCall,+ promoteInPlaceSource: unexpectedCall,+ fanOutInPlace: unexpectedCall,+ },+ skillPlacementOps: {+ place: unexpectedCall,+ unplace: unexpectedCall,+ convert: unexpectedCall,+ },+ signalChannel: undefined,+ bumpSkillsCatalogGen: () => {},+ contentFilter: undefined,+ scheduleDeferredIgnoreRebuild: () => {},+ effectiveInstallMode: () => 'copy',+ log: loggerFactory.getLogger('test'),+ });+}++describe('createSkillsInstallRoutes table', () => {+ test('registers exactly the one skill-install path', () => {+ expect([...buildGroup().paths].sort()).toEqual(['/api/skill/install'].sort());+ });++ test('every skill-install path is mutating (whole-family legacy MUTATING_ROUTES membership)', () => {+ const { table } = buildGroup();+ for (const path of ['/api/skill/install']) {+ expect(table.isMutating(path), path).toBe(true);+ }+ });+});diff --git a/packages/server/src/http/skills-install-routes.ts b/packages/server/src/http/skills-install-routes.tsnew file mode 100644index 000000000..72f94f384--- /dev/null+++ b/packages/server/src/http/skills-install-routes.ts@@ -0,0 +1,764 @@+import { existsSync, readFileSync } from 'node:fs';+import type { ServerResponse } from 'node:http';+import { dirname, join, relative, resolve, sep } from 'node:path';+import {+ type EditorId,+ isSkillInstallTarget,+ PROJECT_SKILL_EDITOR_IDS,+ SkillInstallRequestSchema,+ SkillInstallSuccessSchema,+ type SkillInstallWarningCode,+ skillLiveDocName,+ USER_SKILL_EDITOR_IDS,+} from '@inkeep/open-knowledge-core';+import type { SkillHostId } from '@inkeep/open-knowledge-core/skills-catalog';+import { parseSkillsLock, SKILLS_LOCK_REL } from '@inkeep/open-knowledge-core/skills-catalog';+import type { ContentFilter } from '../content-filter.ts';+import type { StoreFailure } from '../document-durability-state.ts';+import { scanGlobalInPlaceSkills, scanInPlaceSkills } from '../in-place-skills.ts';+import {+ readInstalledSkills,+ recordSkillInstall,+ removeSkillInstall,+} from '../installed-skills-marker.ts';+import type { PinoLogger } from '../logger.ts';+import type { SkillInstallOpsDeps, SkillInstallOpsService } from '../services/skill-install-ops.ts';+import type { SkillPlacementOpsService } from '../services/skill-placement-ops.ts';+import { isInternalBundleSkillName } from '../skill-bundles.ts';+import { detectUserSkillHosts } from '../skill-install.ts';+import {+ projectSkill,+ resolvedHosts,+ resolveSkillTargets,+ reverseProjectSkill,+ skillProjectionRoots,+ validateSkillForInstall,+} from '../skill-projection.ts';+import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';+import { errorResponse } from './error-response.ts';+import { withValidation } from './request-validation.ts';+import { successResponse } from './success-response.ts';++export interface SkillsInstallRouteDeps {+ resolveSkillsRoot: (scope: 'project' | 'global') => string;+ validateSkillName: (name: string, res: ServerResponse, handler: string) => boolean;+ projectDir: string | undefined;+ skillInstallBase: (scope: 'project' | 'global') => string | undefined;+ contentDir: string;+ skillsHome: string;+ shippedBundleSkillMd: (name: string, scope?: 'project' | 'global') => string | null;+ respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;+ flushDiskAndDetectOutcome: (+ docName: string,+ ) => Promise<+ | { kind: 'failure'; failure: StoreFailure }+ | { kind: 'divergence' }+ | { kind: 'stale-external-write' }+ | null+ >;+ skillInstallOps: SkillInstallOpsService;+ skillPlacementOps: SkillPlacementOpsService;+ signalChannel: ((channel: 'files' | 'lint-config' | 'comments') => void) | undefined;+ bumpSkillsCatalogGen: () => void;+ contentFilter: ContentFilter | undefined;+ scheduleDeferredIgnoreRebuild: () => void;+ effectiveInstallMode: SkillInstallOpsDeps['effectiveInstallMode'];+ log: PinoLogger;+}++export function createSkillsInstallRoutes(deps: SkillsInstallRouteDeps): ApiRouteGroup {+ const {+ resolveSkillsRoot,+ validateSkillName,+ projectDir,+ skillInstallBase,+ contentDir,+ skillsHome,+ shippedBundleSkillMd,+ flushDiskAndDetectOutcome,+ respondStaleExternalWrite,+ skillInstallOps,+ skillPlacementOps,+ signalChannel,+ bumpSkillsCatalogGen,+ contentFilter,+ scheduleDeferredIgnoreRebuild,+ effectiveInstallMode,+ log,+ } = deps;+ const handleSkillInstall = withValidation(+ SkillInstallRequestSchema,+ async (_req, res, body) => {+ try {+ const skillsRoot = resolveSkillsRoot(body.scope);+ if (!validateSkillName(body.name, res, 'skill-install')) return;++ if (body.scope === 'project' && !projectDir) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.',+ { handler: 'skill-install', detail: 'NO_PROJECT_ROOT' },+ );+ return;+ }+ const base = skillInstallBase(body.scope) as string;++ const storeSkillDir = resolve(skillsRoot, body.name);+ const inPlaceScanBase = body.scope === 'project' ? contentDir : skillsHome;+ const inPlaceEntry = (+ body.scope === 'project'+ ? scanInPlaceSkills(contentDir)+ : scanGlobalInPlaceSkills(skillsHome)+ ).find((s) => s.name === body.name);+ const bundleSource = isInternalBundleSkillName(body.name)+ ? shippedBundleSkillMd(body.name, body.scope)+ : null;+ const skillDir = inPlaceEntry+ ? resolve(inPlaceScanBase, inPlaceEntry.dir)+ : existsSync(storeSkillDir) || bundleSource === null+ ? storeSkillDir+ : dirname(bundleSource);+ if (!existsSync(skillDir)) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill not found.', {+ handler: 'skill-install',+ detail: `Skill "${body.name}" not found in ${body.scope} scope — create it with write({ skill }) first.`,+ });+ return;+ }++ const liveSkillDoc =+ body.scope === 'project'+ ? `${relative(inPlaceScanBase, skillDir).split(sep).join('/')}/SKILL`+ : skillLiveDocName(body.scope, body.name);+ const liveSkillFlush = await flushDiskAndDetectOutcome(liveSkillDoc);+ if (liveSkillFlush?.kind === 'stale-external-write') {+ respondStaleExternalWrite(res, 'skill-install', liveSkillDoc);+ return;+ }++ const validity = validateSkillForInstall(skillDir, body.name, {+ allowReservedName: isInternalBundleSkillName(body.name),+ });+ if (!validity.ok) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ `Skill "${body.name}" cannot be installed: ${validity.errors.join(' ')}`,+ { handler: 'skill-install', detail: 'INVALID_SKILL_SOURCE' },+ );+ return;+ }++ if (body.fork !== undefined) {+ if (!inPlaceEntry) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Skill is not in-place.', {+ handler: 'skill-install',+ detail: 'FORK_STORE_BACKED',+ });+ return;+ }+ const forkResolved = skillInstallOps.resolveFork({+ scope: body.scope,+ name: body.name,+ fork: body.fork,+ inPlaceEntry,+ });+ if (!forkResolved.ok) {+ switch (forkResolved.kind) {+ case 'unknown-editor':+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Unknown editor.', {+ handler: 'skill-install',+ detail: forkResolved.editor,+ });+ return;+ case 'fork-absent':+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No fork at that editor.', {+ handler: 'skill-install',+ detail: 'FORK_ABSENT',+ });+ return;+ case 'not-a-fork':+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'That copy matches the source — nothing to resolve.',+ { handler: 'skill-install', detail: 'NOT_A_FORK' },+ );+ return;+ case 'invalid-new-name':+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid new name.', {+ handler: 'skill-install',+ detail: forkResolved.toName,+ });+ return;+ case 'name-taken':+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Name already taken.', {+ handler: 'skill-install',+ detail: forkResolved.toName,+ });+ return;+ default: {+ const _exhaustive: never = forkResolved;+ throw new Error(+ `Unhandled fork outcome: ${String((_exhaustive as { kind?: unknown }).kind)}`,+ );+ }+ }+ }+ signalChannel?.('files');+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();+ successResponse(+ res,+ 200,+ SkillInstallSuccessSchema,+ {+ name: body.name,+ hosts: inPlaceEntry.hosts.filter(isSkillInstallTarget),+ scripts: false,+ warnings: forkResolved.warnings,+ warningCodes: forkResolved.warnings.length > 0 ? ['skill-fork-name-unpatched'] : [],+ },+ { handler: 'skill-install' },+ );+ return;+ }++ const setSourceReq = body.setSource ?? body.source;+ const linkModeReq =+ body.linkMode ?? (body.mode !== undefined ? body.mode === 'link' : undefined);+ let targetsReq = body.targets;+ const rootAdds: string[] = [];+ const rootRemoves: string[] = [];+ if (body.add !== undefined || body.remove !== undefined) {+ if (!inPlaceEntry) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.',+ { handler: 'skill-install', detail: 'STORE_BACKED_ADDITIVE' },+ );+ return;+ }+ const addRemove = await skillInstallOps.applyAddRemove({+ scope: body.scope,+ name: body.name,+ inPlaceEntry,+ ...(body.add !== undefined ? { add: body.add } : {}),+ ...(body.remove !== undefined ? { remove: body.remove } : {}),+ });+ if (!addRemove.ok) {+ if (addRemove.kind === 'remove-source') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ `"${addRemove.sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,+ { handler: 'skill-install', detail: 'REMOVE_SOURCE' },+ );+ } else {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:invalid-request',+ `Could not stop ${addRemove.subRoot} following its pool (${addRemove.reason}).`,+ { handler: 'skill-install', detail: addRemove.reason },+ );+ }+ return;+ }+ targetsReq = addRemove.targets.filter(isSkillInstallTarget);+ rootAdds.push(...addRemove.rootAdds);+ rootRemoves.push(...addRemove.rootRemoves);+ }++ if (setSourceReq && !inPlaceEntry) {+ const promoted = await skillInstallOps.promoteStoreBackedSource({+ scope: body.scope,+ name: body.name,+ base,+ skillDir,+ newSource: setSourceReq as SkillHostId,+ });+ if (!promoted.ok) {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:doc-already-exists',+ 'Cannot move the source there — a different skill occupies the target.',+ {+ handler: 'skill-install',+ detail: promoted.kind === 'source-occupied' ? promoted.reason : promoted.target,+ },+ );+ return;+ }+ signalChannel?.('files');+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();+ successResponse(+ res,+ 200,+ SkillInstallSuccessSchema,+ {+ name: body.name,+ hosts: promoted.hosts,+ scripts: validity.hasScripts,+ warnings: [],+ warningCodes: [],+ sourceMovedTo: promoted.sourceMovedTo,+ },+ { handler: 'skill-install' },+ );+ return;+ }++ if (body.place) {+ const placeBase = body.scope === 'project' ? projectDir : skillsHome;+ if (!placeBase) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Cannot place — no project root is resolved for this server.',+ { handler: 'skill-install', detail: 'NO_PROJECT_ROOT' },+ );+ return;+ }+ const placed = await skillPlacementOps.place({+ placeBase,+ name: body.name,+ rawDir: body.place.dir,+ skillDir,+ mode: body.place.mode,+ });+ if (!placed.ok) {+ if (placed.kind === 'invalid-path') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Placement path must be a project-relative directory outside .ok/.',+ { handler: 'skill-install', detail: 'PLACE_PATH_INVALID' },+ );+ } else {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:doc-already-exists',+ 'Something already exists at that path — placement never overwrites.',+ { handler: 'skill-install', detail: 'PLACE_DEST_EXISTS' },+ );+ }+ return;+ }+ if (!('alreadyAtSource' in placed)) {+ signalChannel?.('files');+ }+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();+ successResponse(+ res,+ 200,+ SkillInstallSuccessSchema,+ {+ name: body.name,+ hosts: inPlaceEntry ? [...inPlaceEntry.hosts] : [],+ scripts: validity.hasScripts,+ warnings: [],+ warningCodes: [],+ placedAt: placed.placedAt,+ },+ { handler: 'skill-install' },+ );+ return;+ }++ if (body.unplace) {+ const placeBase = body.scope === 'project' ? projectDir : skillsHome;+ if (!placeBase) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Cannot remove a placement — no project root is resolved for this server.',+ { handler: 'skill-install', detail: 'NO_PROJECT_ROOT' },+ );+ return;+ }+ const unplaced = await skillPlacementOps.unplace({+ placeBase,+ name: body.name,+ rawPath: body.unplace.path,+ skillDir,+ });+ if (!unplaced.ok) {+ switch (unplaced.kind) {+ case 'not-recorded':+ errorResponse(+ res,+ 404,+ 'urn:ok:error:not-found',+ 'No recorded placement at that path.',+ { handler: 'skill-install', detail: unplaced.path },+ );+ return;+ case 'unsafe-path':+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Recorded placement path is no longer safe.',+ { handler: 'skill-install', detail: 'PLACE_PATH_INVALID' },+ );+ return;+ case 'forked':+ errorResponse(+ res,+ 409,+ 'urn:ok:error:doc-already-exists',+ 'That copy has been edited and no longer matches the skill — remove it manually if you mean it.',+ { handler: 'skill-install', detail: unplaced.path },+ );+ return;+ case 'canonical-dir':+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ "That is the skill's own folder (the source) — it can't be removed here.",+ { handler: 'skill-install', detail: unplaced.path },+ );+ return;+ default: {+ const _exhaustive: never = unplaced;+ throw new Error(+ `Unhandled unplace outcome: ${String((_exhaustive as { kind?: unknown }).kind)}`,+ );+ }+ }+ }+ signalChannel?.('files');+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();+ successResponse(+ res,+ 200,+ SkillInstallSuccessSchema,+ {+ name: body.name,+ hosts: inPlaceEntry ? [...inPlaceEntry.hosts] : [],+ scripts: validity.hasScripts,+ warnings: [],+ warningCodes: [],+ },+ { handler: 'skill-install' },+ );+ return;+ }++ if (body.convert) {+ if (!inPlaceEntry) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.',+ { handler: 'skill-install', detail: 'STORE_BACKED_CONVERT' },+ );+ return;+ }+ const { target, mode } = body.convert;+ const prefBase = body.scope === 'project' ? projectDir : skillsHome;+ const converted = await skillPlacementOps.convert({+ ledgerBase: prefBase ?? base,+ scope: body.scope,+ name: body.name,+ target,+ mode,+ skillDir,+ canonicalHash: inPlaceEntry.contentHash,+ });+ if (!converted.ok) {+ switch (converted.kind) {+ case 'invalid-location':+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'That location has no skills folder to convert.',+ { handler: 'skill-install', detail: target },+ );+ return;+ case 'canonical-dir':+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ "That is the skill's own folder (the source) — move the source instead of converting it.",+ { handler: 'skill-install', detail: target },+ );+ return;+ case 'forked':+ errorResponse(+ res,+ 409,+ 'urn:ok:error:doc-already-exists',+ 'That copy has been edited and no longer matches the skill — resolve the fork before converting it.',+ { handler: 'skill-install', detail: target },+ );+ return;+ case 'not-installed':+ errorResponse(+ res,+ 404,+ 'urn:ok:error:not-found',+ 'The skill is not installed there.',+ { handler: 'skill-install', detail: target },+ );+ return;+ default: {+ const _exhaustive: never = converted;+ throw new Error(+ `Unhandled convert outcome: ${String((_exhaustive as { kind?: unknown }).kind)}`,+ );+ }+ }+ }+ signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillInstallSuccessSchema,+ {+ name: body.name,+ hosts: [...inPlaceEntry.hosts],+ scripts: validity.hasScripts,+ warnings: [],+ warningCodes: [],+ },+ { handler: 'skill-install' },+ );+ return;+ }++ const targets: EditorId[] =+ body.scope === 'global'+ ? targetsReq !== undefined+ ? USER_SKILL_EDITOR_IDS.filter((id) => targetsReq?.some((t) => t === id))+ : detectUserSkillHosts(skillsHome).map((host) => host.editorId)+ : targetsReq !== undefined+ ? PROJECT_SKILL_EDITOR_IDS.filter((id) => targetsReq?.some((t) => t === id))+ : resolveSkillTargets(base);+ const warnings: string[] = [];+ const warningCodes: SkillInstallWarningCode[] = [];+ if (targets.length === 0 && targetsReq === undefined) {+ warnings.push(+ body.scope === 'global'+ ? 'No editor skill folders are configured to install into.'+ : 'No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`.',+ );+ warningCodes.push('no-targets');+ }+ if (validity.hasScripts) {+ warnings.push(+ 'This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing.',+ );+ warningCodes.push('scripts-present');+ }+ if (validity.warnings.length > 0) {+ warnings.push(validity.warnings[0]);+ warningCodes.push('no-description');+ }++ if (inPlaceEntry) {+ const canonicalRootRel = inPlaceEntry.dir.split('/').slice(0, -1).join('/');+ const hubTargeted =+ targetsReq !== undefined+ ? targetsReq.includes('agents')+ : body.scope === 'global' && existsSync(join(skillsHome, '.agents'));+ const inPlaceTargets: SkillHostId[] = hubTargeted ? [...targets, 'agents'] : [...targets];+ const prefBase = body.scope === 'project' ? projectDir : skillsHome;+ const installMode: 'copy' | 'link' =+ linkModeReq !== undefined+ ? linkModeReq+ ? 'link'+ : 'copy'+ : effectiveInstallMode(body.scope, body.name, inPlaceEntry);+ if (setSourceReq) {+ const promoted = await skillInstallOps.promoteInPlaceSource({+ scope: body.scope,+ name: body.name,+ base,+ ...(prefBase ? { prefBase } : {}),+ skillDir,+ inPlaceEntry,+ newSource: setSourceReq,+ });+ if (!promoted.ok) {+ if (promoted.kind === 'invalid-target') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Source target must be an editor id, "agents", or a project-relative skills root.',+ { handler: 'skill-install', detail: promoted.target },+ );+ } else {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:doc-already-exists',+ 'Cannot move the source there — a different skill occupies the target.',+ { handler: 'skill-install', detail: promoted.reason },+ );+ }+ return;+ }+ signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillInstallSuccessSchema,+ {+ name: body.name,+ hosts: promoted.hosts,+ scripts: validity.hasScripts,+ warnings: [],+ warningCodes: [],+ ...(promoted.sourceMovedTo !== undefined+ ? { sourceMovedTo: promoted.sourceMovedTo }+ : {}),+ },+ { handler: 'skill-install' },+ );+ return;+ }++ const fanOut = await skillInstallOps.fanOutInPlace({+ scope: body.scope,+ name: body.name,+ base,+ ...(prefBase ? { prefBase } : {}),+ skillDir,+ inPlaceEntry,+ canonicalRootRel,+ inPlaceTargets,+ setExact: targetsReq !== undefined,+ installMode,+ ...(linkModeReq !== undefined ? { linkModeReq } : {}),+ rootAdds,+ rootRemoves,+ });+ if (!fanOut.ok) {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:doc-already-exists',+ 'Cannot move the source there — a different skill occupies the target.',+ { handler: 'skill-install', detail: fanOut.reason },+ );+ return;+ }+ warnings.push(...fanOut.warnings);+ warningCodes.push(...fanOut.warningCodes);+ signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillInstallSuccessSchema,+ {+ name: body.name,+ hosts: fanOut.hosts,+ scripts: validity.hasScripts,+ warnings,+ warningCodes,+ ...(fanOut.sourceMovedTo !== undefined+ ? { sourceMovedTo: fanOut.sourceMovedTo }+ : {}),+ },+ { handler: 'skill-install' },+ );+ return;+ }++ const priorHosts = resolvedHosts(+ readInstalledSkills(base).skills[body.name]?.hosts ?? [],+ body.scope,+ );+ const dropped = priorHosts.filter((h) => !targets.includes(h));+ if (dropped.length > 0)+ reverseProjectSkill(body.name, base, dropped, skillProjectionRoots(body.scope));+ const lockPathForInstall = join(base, ...SKILLS_LOCK_REL);+ const lockRawForInstall = existsSync(lockPathForInstall)+ ? readFileSync(lockPathForInstall, 'utf-8')+ : null;+ const lockForInstall =+ lockRawForInstall !== null ? parseSkillsLock(lockRawForInstall) : null;+ if (lockRawForInstall !== null && lockForInstall === null) {+ log.warn(+ { skill: body.name },+ 'skills-lock.json failed to parse — projecting as symlink (import origin unknown)',+ );+ }+ const isAcquired = lockForInstall?.skills[body.name] !== undefined;+ const projectionMode: 'symlink' | 'copy' =+ linkModeReq !== undefined+ ? linkModeReq+ ? 'symlink'+ : 'copy'+ : isAcquired+ ? 'copy'+ : 'symlink';+ const hosts = projectSkill(+ skillDir,+ body.name,+ base,+ targets,+ projectionMode,+ skillProjectionRoots(body.scope),+ );+ if (hosts.length === 0) {+ await removeSkillInstall(base, body.name);+ } else {+ await recordSkillInstall(base, body.name, {+ hosts,+ scope: body.scope,+ scripts: validity.hasScripts,+ installedAt: new Date().toISOString(),+ projection: projectionMode,+ });+ }+ signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillInstallSuccessSchema,+ { name: body.name, hosts, scripts: validity.hasScripts, warnings, warningCodes },+ { handler: 'skill-install' },+ );+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to install skill.', {+ handler: 'skill-install',+ cause: e,+ });+ }+ },+ // STOP: Unlike /api/install-skill, this route serves local-api-dispatch.ts callers without a socket; checkLocalOpSecurity requires one.+ { handler: 'skill-install', method: 'POST' },+ );++ return createApiRouteGroup(+ { '/api/skill/install': handleSkillInstall },+ { mutating: ['/api/skill/install'] },+ );+}diff --git a/packages/server/src/http/skills-list-routes.test.ts b/packages/server/src/http/skills-list-routes.test.tsnew file mode 100644index 000000000..1a3428175--- /dev/null+++ b/packages/server/src/http/skills-list-routes.test.ts@@ -0,0 +1,42 @@+import { describe, expect, test } from 'vitest';+import { loggerFactory } from '../logger.ts';+import { createSkillsCatalogCache } from '../skills-catalog-cache.ts';+import { createSkillsListRoutes } from './skills-list-routes.ts';++function buildGroup() {+ return createSkillsListRoutes({+ contentDir: '/nonexistent-content',+ projectDir: undefined,+ skillsHome: '/nonexistent-skills-home',+ contentFilter: undefined,+ catalogCache: createSkillsCatalogCache({+ homeDirOverride: '/nonexistent-skills-home',+ log: loggerFactory.getLogger('test'),+ }),+ resolveSkillsRoot: () => '/nonexistent-skills',+ resolveSkillsList: () => ({ skills: [], truncated: false }),+ skillOriginFor: () => ({ source: 'test', importedAt: '' }),+ localSkillHash: () => undefined,+ effectiveInstallMode: () => 'copy',+ pluginSelfIdentity: () => null,+ synthBuiltinLockEntry: () => null,+ synthPluginLockEntry: () => null,+ pluginUpstreamHash: () => null,+ builtinSkillListEntry: () => null,+ indexedSkillContentPath: () => null,+ healUnservableSkillAdmission: () => Promise.resolve(false),+ });+}++describe('createSkillsListRoutes table', () => {+ test('registers exactly the one skills-list path', () => {+ expect([...buildGroup().paths].sort()).toEqual(['/api/skills'].sort());+ });++ test('the skills-list read is not mutating', () => {+ const { table } = buildGroup();+ for (const path of ['/api/skills']) {+ expect(table.isMutating(path), path).toBe(false);+ }+ });+});diff --git a/packages/server/src/http/skills-list-routes.ts b/packages/server/src/http/skills-list-routes.tsnew file mode 100644index 000000000..ae329f3ca--- /dev/null+++ b/packages/server/src/http/skills-list-routes.ts@@ -0,0 +1,496 @@+import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import {+ AGENTS_SKILLS_ROOT,+ EmptyRequestSchema,+ type estimateSkillCost,+ SkillsListSuccessSchema,+} from '@inkeep/open-knowledge-core';+import { resolveProjectIdentity } from '@inkeep/open-knowledge-core/shadow-repo-layout';+import {+ parseSkillsLock,+ readRepoMarketplacePlugins,+ repoMarketplacePluginFor,+ SKILLS_LOCK_REL,+ type SkillsLock,+} from '@inkeep/open-knowledge-core/skills-catalog';+import type { ContentFilter } from '../content-filter.ts';+import {+ aliasedSourceRoots,+ isActivatedSkillRoot,+ resolveGlobalNativeSkillDir,+ scanGlobalInPlaceSkills,+ scanHostRootAliases,+ scanInPlaceSkills,+ standardSkillRoots,+} from '../in-place-skills.ts';+import { readInstalledSkills } from '../installed-skills-marker.ts';+import { openPluginBaselines } from '../plugin-skill-baseline.ts';+import {+ BUNDLE_SKILL_NAME,+ isInternalBundleSkillName,+ USER_GLOBAL_BUNDLE_IDS,+} from '../skill-bundles.ts';+import { detectProjectSkillEditors, detectUserSkillHosts } from '../skill-install.ts';+import { readSkillPlacements } from '../skill-placements.ts';+import { listSkillBundledFilePaths } from '../skill-projection.ts';+import type { SkillsCatalogCache } from '../skills-catalog-cache.ts';+import { readSkillsLockFile as readSkillsLock } from '../skills-lock-store.ts';+import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';+import { catchErrors } from './catch-errors.ts';+import { withValidation } from './request-validation.ts';+import { successResponse } from './success-response.ts';++export interface SkillsListRouteDeps {+ contentDir: string;+ projectDir: string | undefined;+ skillsHome: string;+ contentFilter: ContentFilter | undefined;+ catalogCache: SkillsCatalogCache;+ resolveSkillsRoot: (scope: 'project' | 'global') => string;+ resolveSkillsList: (+ skillsRoot: string,+ scope: 'project' | 'global',+ ) => {+ skills: Array<{+ name: string;+ description?: string;+ scope: 'project' | 'global';+ path: string;+ absolutePath: string;+ installedVersion?: string;+ }>;+ truncated: boolean;+ };+ skillOriginFor: (entry: SkillsLock['skills'][string]) => {+ source: string;+ publisher?: string;+ skill?: string;+ marketplaceUrl?: string;+ importedAt: string;+ autoUpdate?: boolean;+ };+ localSkillHash: (skillsRoot: string, name: string) => string | undefined;+ effectiveInstallMode: (+ scope: 'project' | 'global',+ name: string,+ existing: { hosts: readonly string[]; linkedHosts: readonly string[] },+ ) => 'copy' | 'link';+ pluginSelfIdentity: (+ name: string,+ identity: string,+ skillAbsDir: string,+ ) => { name: string; marketplace: string; provider: string; url?: string } | null;+ synthBuiltinLockEntry: (+ base: string,+ name: string,+ scope: 'project' | 'global',+ ) => SkillsLock['skills'][string] | null;+ synthPluginLockEntry: (+ name: string,+ identity: string,+ skillAbsDir?: string,+ ) => SkillsLock['skills'][string] | null;+ pluginUpstreamHash: (name: string, identity: string) => string | null;+ builtinSkillListEntry: (+ base: string,+ name: string,+ scope: 'project' | 'global',+ ) => {+ name: string;+ description?: string;+ scope: 'project' | 'global';+ path: string;+ absolutePath: string;+ installed: boolean;+ hosts: string[];+ managed: true;+ size?: ReturnType<typeof estimateSkillCost>;+ origin?: ReturnType<SkillsListRouteDeps['skillOriginFor']>;+ } | null;+ indexedSkillContentPath: (absolutePath: string, contentDir: string) => string | null;+ healUnservableSkillAdmission: (+ paths: readonly string[],+ filter: ContentFilter | null,+ state: { lastKey: string | null },+ ) => Promise<boolean>;+}++export function createSkillsListRoutes(deps: SkillsListRouteDeps): ApiRouteGroup {+ const {+ contentDir,+ projectDir,+ skillsHome,+ contentFilter,+ catalogCache,+ resolveSkillsRoot,+ resolveSkillsList,+ skillOriginFor,+ localSkillHash,+ effectiveInstallMode,+ pluginSelfIdentity,+ synthBuiltinLockEntry,+ synthPluginLockEntry,+ pluginUpstreamHash,+ builtinSkillListEntry,+ indexedSkillContentPath,+ healUnservableSkillAdmission,+ } = deps;+ const BUILTIN_PROJECT_SKILL_NAME = BUNDLE_SKILL_NAME.project;+ const skillAdmissionHeal: { lastKey: string | null } = { lastKey: null };++ const handleSkillsList = withValidation(+ EmptyRequestSchema,+ catchErrors(+ async (_req, res) => {+ const inPlaceFp =+ (contentFilter?.peekFreshInPlaceSkillDirsFingerprint() ?? '') ++ '\u0001' ++ (projectDir ? detectProjectSkillEditors(projectDir).join(',') : '') ++ '\u0001' ++ detectUserSkillHosts(skillsHome)+ .map((h) => h.editorId)+ .join(',') ++ '\u0001' ++ scanGlobalInPlaceSkills(skillsHome)+ .map((s) => s.dir)+ .sort()+ .join(',');+ const cached = catalogCache.readList(inPlaceFp);+ if (cached !== null) {+ successResponse(res, 200, SkillsListSuccessSchema, cached.body, {+ handler: 'skills-list',+ });+ return;+ }+ const projectSkillsRoot = resolveSkillsRoot('project');+ const project = resolveSkillsList(projectSkillsRoot, 'project');+ const globalSkills = resolveSkillsList(resolveSkillsRoot('global'), 'global');+ const projectInstallableEditors: string[] = projectDir+ ? detectProjectSkillEditors(projectDir)+ : [];+ const globalInstallableEditors: string[] = detectUserSkillHosts(skillsHome).map(+ (h) => h.editorId,+ );+ const projectHubOffered: boolean = projectDir+ ? isActivatedSkillRoot(projectDir, 'project', AGENTS_SKILLS_ROOT, skillsHome)+ : false;+ const globalHubOffered: boolean = isActivatedSkillRoot(+ skillsHome,+ 'global',+ AGENTS_SKILLS_ROOT,+ skillsHome,+ );+ const projectInstalled = projectDir ? readInstalledSkills(projectDir).skills : {};+ const globalInstalled = readInstalledSkills(skillsHome).skills;+ const lock: SkillsLock | null = projectDir+ ? (parseSkillsLock(+ existsSync(join(projectDir, ...SKILLS_LOCK_REL))+ ? readFileSync(join(projectDir, ...SKILLS_LOCK_REL), 'utf-8')+ : '',+ ) ?? null)+ : null;+ const skillOrigin = skillOriginFor;+ const enrich = (+ list: typeof project,+ marker: Record<string, { hosts: string[] }>,+ withOrigin: boolean,+ ) =>+ list.skills.map((skill) => {+ const record = marker[skill.name];+ const hosts = record?.hosts ?? [];+ const entry = withOrigin ? lock?.skills[skill.name] : undefined;+ const origin = entry ? skillOrigin(entry) : undefined;+ const modified =+ entry?.localHash !== undefined &&+ localSkillHash(projectSkillsRoot, skill.name) !== entry.localHash;+ const revertable = entry?.baselineRef !== undefined;+ return {+ ...skill,+ installed: hosts.length > 0,+ hosts,+ ...(origin ? { origin } : {}),+ ...(modified ? { modified: true } : {}),+ ...(revertable ? { revertable: true } : {}),+ };+ });+ const placements = projectDir ? readSkillPlacements(projectDir) : {};+ const placementFlags = (+ baseDir: string,+ list: ReturnType<typeof readSkillPlacements>[string] | undefined,+ canonicalAbs?: string,+ ): { drift: string[] } => {+ const drift: string[] = [];+ for (const p of list ?? []) {+ const abs = resolve(baseDir, p.path);+ if (canonicalAbs !== undefined && abs === resolve(canonicalAbs)) continue;+ let isLink = false;+ try {+ isLink = lstatSync(abs).isSymbolicLink();+ } catch {+ continue;+ }+ if ((isLink ? 'link' : 'copy') === p.mode) continue;+ if (isLink && canonicalAbs !== undefined) {+ try {+ if (realpathSync(abs) === realpathSync(canonicalAbs)) continue;+ } catch {}+ }+ drift.push(p.path);+ }+ return { drift };+ };+ const projectAliases = projectDir ? scanHostRootAliases(contentDir, 'project') : {};+ const projectAliasRoots = aliasedSourceRoots(projectAliases, 'project');+ const underRoots = (path: string, roots: ReadonlySet<string>): boolean =>+ [...roots].some((r) => path === r || path.startsWith(`${r}/`));+ const detectedIdentity = resolveProjectIdentity(projectDir ?? contentDir);+ const pluginBaselines = openPluginBaselines(contentDir);+ const stdRootsProject = standardSkillRoots('project');+ const stdRootsGlobal = standardSkillRoots('global');+ const dropAliased = (+ list: ReturnType<typeof readSkillPlacements>[string] | undefined,+ aliasRoots: Set<string>,+ ): ReturnType<typeof readSkillPlacements>[string] =>+ (list ?? []).filter(+ (pl) => ![...aliasRoots].some((r) => pl.path === r || pl.path.startsWith(`${r}/`)),+ );+ const projectNameSeen = new Set<string>();+ const repoPlugins = readRepoMarketplacePlugins(contentDir);+ const repoPluginIdentity = (dir: string) => {+ const p = repoMarketplacePluginFor(repoPlugins, dir);+ return p+ ? {+ name: p.name,+ marketplace: p.marketplace,+ provider: 'claude',+ ...(p.url ? { url: p.url } : {}),+ }+ : null;+ };+ const inPlace = projectDir+ ? scanInPlaceSkills(contentDir).map((s) => {+ const tracked = !projectNameSeen.has(s.name);+ projectNameSeen.add(s.name);+ const skillAbsDir = resolve(contentDir, s.dir);+ const selfPlugin = tracked+ ? (pluginSelfIdentity(s.name, detectedIdentity, skillAbsDir) ??+ repoPluginIdentity(skillAbsDir))+ : null;+ const entry =+ tracked && selfPlugin === null+ ? (lock?.skills[s.name] ??+ synthBuiltinLockEntry(contentDir, s.name, 'project') ??+ synthPluginLockEntry(s.name, detectedIdentity, skillAbsDir))+ : undefined;+ const origin = entry ? skillOrigin(entry) : undefined;+ const modified =+ entry?.localHash !== undefined+ ? s.contentHash !== entry.localHash+ : (() => {+ if (!entry || !tracked) return false;+ const up = pluginUpstreamHash(s.name, detectedIdentity);+ return (+ up !== null &&+ pluginBaselines.isModified('project', s.name, s.contentHash, up)+ );+ })();+ return {+ name: s.name,+ ...(s.description ? { description: s.description } : {}),+ scope: 'project' as const,+ path: `${s.dir}/SKILL.md`,+ absolutePath: resolve(contentDir, s.dir, 'SKILL.md'),+ installed: true,+ hosts: [...s.hosts],+ size: s.size,+ installableEditors: projectInstallableEditors,+ hubOffered: projectHubOffered,+ ...(s.pack !== undefined ? { pack: s.pack } : {}),+ ...(s.linkedHosts.length > 0 ? { symlinkedHosts: [...s.linkedHosts] } : {}),+ ...(Object.keys(projectAliases).length > 0 ? { hostAliases: projectAliases } : {}),+ ...(s.conflictHosts.length > 0 ? { conflictHosts: [...s.conflictHosts] } : {}),+ ...(selfPlugin !== null ? { plugin: selfPlugin } : {}),+ ...(() => {+ const custom = dropAliased(+ tracked ? placements[s.name] : undefined,+ projectAliasRoots,+ ).filter((cp) => !underRoots(cp.path, stdRootsProject));+ return custom.length+ ? { customPlacements: custom.map((cp) => ({ path: cp.path, mode: cp.mode })) }+ : {};+ })(),+ ...(() => {+ const f = placementFlags(+ projectDir,+ dropAliased(tracked ? placements[s.name] : undefined, projectAliasRoots),+ resolve(contentDir, s.dir),+ );+ return f.drift.length > 0 ? { driftPaths: f.drift } : {};+ })(),+ ...(effectiveInstallMode('project', s.name, s) === 'link'+ ? { linkMode: true }+ : {}),+ ...(origin ? { origin } : {}),+ ...(modified ? { modified: true } : {}),+ ...(entry?.baselineRef !== undefined ? { revertable: true } : {}),+ ...(isInternalBundleSkillName(s.name) ? { managed: true as const } : {}),+ };+ })+ : [];+ const globalPlacements = readSkillPlacements(skillsHome);+ const globalLock = readSkillsLock(join(skillsHome, ...SKILLS_LOCK_REL));+ const globalAliases = scanHostRootAliases(skillsHome, 'global');+ const globalAliasRoots = aliasedSourceRoots(globalAliases, 'global');+ const globalInPlaceNames = new Set(scanGlobalInPlaceSkills(skillsHome).map((s) => s.name));+ globalSkills.skills = globalSkills.skills.filter((s) => !globalInPlaceNames.has(s.name));+ const globalNameSeen = new Set<string>();+ const globalInPlace = scanGlobalInPlaceSkills(skillsHome).map((s) => {+ const tracked = !globalNameSeen.has(s.name);+ globalNameSeen.add(s.name);+ const placementsForRow = tracked ? globalPlacements[s.name] : undefined;+ const defaultDir = resolveGlobalNativeSkillDir(skillsHome, s.name);+ const hostQualifier =+ defaultDir !== null && resolve(skillsHome, s.dir) !== resolve(defaultDir)+ ? s.hosts[0]+ : undefined;+ return {+ name: s.name,+ ...(s.description ? { description: s.description } : {}),+ scope: 'global' as const,+ path: `${s.dir}/SKILL.md`,+ absolutePath: resolve(skillsHome, s.dir, 'SKILL.md'),+ installed: true,+ hosts: [...s.hosts],+ ...(hostQualifier !== undefined ? { hostQualifier } : {}),+ size: s.size,+ installableEditors: globalInstallableEditors,+ hubOffered: globalHubOffered,+ ...(s.pack !== undefined ? { pack: s.pack } : {}),+ ...(s.linkedHosts.length > 0 ? { symlinkedHosts: [...s.linkedHosts] } : {}),+ ...(Object.keys(globalAliases).length > 0 ? { hostAliases: globalAliases } : {}),+ ...(s.conflictHosts.length > 0 ? { conflictHosts: [...s.conflictHosts] } : {}),+ ...(() => {+ const f = placementFlags(+ skillsHome,+ dropAliased(placementsForRow, globalAliasRoots),+ resolve(skillsHome, s.dir),+ );+ return f.drift.length > 0 ? { driftPaths: f.drift } : {};+ })(),+ ...(() => {+ const custom = dropAliased(placementsForRow, globalAliasRoots).filter(+ (cp) => !underRoots(cp.path, stdRootsGlobal),+ );+ return custom.length+ ? { customPlacements: custom.map((cp) => ({ path: cp.path, mode: cp.mode })) }+ : {};+ })(),+ ...(effectiveInstallMode('global', s.name, s) === 'link' ? { linkMode: true } : {}),+ ...(isInternalBundleSkillName(s.name) ? { managed: true as const } : {}),+ ...(() => {+ if (!tracked) return {};+ const globalAbsDir = resolve(skillsHome, s.dir);+ const selfPluginGlobal = pluginSelfIdentity(s.name, detectedIdentity, globalAbsDir);+ if (selfPluginGlobal !== null) return { plugin: selfPluginGlobal };+ const entry =+ globalLock.skills[s.name] ??+ synthBuiltinLockEntry(skillsHome, s.name, 'global') ??+ synthPluginLockEntry(s.name, detectedIdentity, globalAbsDir);+ if (!entry) return {};+ const globallyModified =+ entry.localHash !== undefined+ ? s.contentHash !== entry.localHash+ : (() => {+ const up = pluginUpstreamHash(s.name, detectedIdentity);+ return (+ up !== null &&+ pluginBaselines.isModified('global', s.name, s.contentHash, up)+ );+ })();+ return {+ origin: skillOrigin(entry),+ ...(globallyModified ? { modified: true } : {}),+ };+ })(),+ };+ });+ const inPlaceNamesEarly = new Set(inPlace.map((e) => e.name));+ const projectBuiltin =+ projectDir &&+ !project.skills.some((s) => s.name === BUILTIN_PROJECT_SKILL_NAME) &&+ !inPlaceNamesEarly.has(BUILTIN_PROJECT_SKILL_NAME)+ ? builtinSkillListEntry(projectDir, BUILTIN_PROJECT_SKILL_NAME, 'project')+ : null;+ const globalInPlaceNamesEarly = new Set(globalInPlace.map((e) => e.name));+ const globalBuiltins = USER_GLOBAL_BUNDLE_IDS.map((id) => BUNDLE_SKILL_NAME[id])+ .filter(+ (name) =>+ !globalSkills.skills.some((s) => s.name === name) &&+ !globalInPlaceNamesEarly.has(name),+ )+ .map((name) => builtinSkillListEntry(skillsHome, name, 'global'))+ .filter((e): e is NonNullable<typeof e> => e !== null);+ const inPlaceNames = new Set(inPlace.map((e) => e.name));+ const listed = [+ ...enrich(project, projectInstalled, true).filter((e) => !inPlaceNames.has(e.name)),+ ...inPlace,+ ...enrich(globalSkills, globalInstalled, false),+ ...globalInPlace,+ ...(projectBuiltin ? [projectBuiltin] : []),+ ...globalBuiltins,+ ];+ pluginBaselines.flush();+ const enriched = {+ skills: listed.map((entry) => {+ const canonicalPath =+ entry.scope === 'project' && entry.absolutePath+ ? indexedSkillContentPath(entry.absolutePath, contentDir)+ : null;+ const filePaths = entry.absolutePath+ ? listSkillBundledFilePaths(dirname(entry.absolutePath))+ : [];+ const withFiles = filePaths.length > 0 ? { ...entry, filePaths } : entry;+ const withCanonical =+ canonicalPath === null || canonicalPath === entry.path+ ? withFiles+ : { ...withFiles, canonicalPath };+ const openedPath = canonicalPath ?? entry.path;+ return entry.scope === 'project' && contentFilter?.isPathIgnored(openedPath) === true+ ? { ...withCanonical, ignored: true }+ : withCanonical;+ }),+ truncated: project.truncated || globalSkills.truncated,+ };+ const healed = await healUnservableSkillAdmission(+ inPlace.map((e) => e.path),+ contentFilter ?? null,+ skillAdmissionHeal,+ );+ const responseBody = !healed+ ? enriched+ : {+ ...enriched,+ skills: enriched.skills.map((entry) => {+ if (entry.scope !== 'project') return entry;+ const opened = (entry as { canonicalPath?: string }).canonicalPath ?? entry.path;+ const nowIgnored = contentFilter?.isPathIgnored(opened) === true;+ const wasIgnored = (entry as { ignored?: boolean }).ignored === true;+ if (nowIgnored === wasIgnored) return entry;+ if (nowIgnored) return { ...entry, ignored: true };+ const { ignored: _drop, ...rest } = entry as { ignored?: boolean } & typeof entry;+ return rest;+ }),+ };+ catalogCache.writeList(inPlaceFp, responseBody);+ successResponse(res, 200, SkillsListSuccessSchema, responseBody, {+ handler: 'skills-list',+ });+ },+ { handler: 'skills-list', title: 'Failed to list skills.' },+ ),+ { handler: 'skills-list', method: 'GET', skipBodyParse: true },+ );++ return createApiRouteGroup({ '/api/skills': handleSkillsList });+}diff --git a/packages/server/src/http/skills-recovery-routes.test.ts b/packages/server/src/http/skills-recovery-routes.test.tsnew file mode 100644index 000000000..686f15ad5--- /dev/null+++ b/packages/server/src/http/skills-recovery-routes.test.ts@@ -0,0 +1,60 @@+import { describe, expect, test } from 'vitest';+import { createSkillsRecoveryRoutes } from './skills-recovery-routes.ts';++function unexpectedCall(): never {+ throw new Error('Route table construction must not invoke skill services.');+}++function buildGroup() {+ return createSkillsRecoveryRoutes({+ synthPluginLockEntry: () => null,+ synthBuiltinLockEntry: () => null,+ isValidSkillName: () => true,+ getPrincipal: undefined,+ validateSkillName: () => true,+ rejectReservedBuiltinSkill: () => false,+ shadowRef: undefined,+ contentDir: '/nonexistent-content',+ contentRoot: undefined,+ projectDir: undefined,+ skillsHome: '/nonexistent-skills-home',+ projectSkillDirRel: (name) => `.agents/skills/${name}`,+ attributeOkArtifactWrite: () => {},+ okArtifactKey: () => '',+ commitOkArtifactWrite: () => Promise.resolve(),+ signalChannel: undefined,+ bumpSkillsCatalogGen: () => {},+ contentFilter: undefined,+ scheduleDeferredIgnoreRebuild: () => {},+ effectiveSkillRoot: () => ({ root: '/nonexistent-skills', dirRel: '', realDir: null }),+ skillReimportService: { runSkillReimport: unexpectedCall },+ localSkillHash: () => undefined,+ resolveSkillsRoot: () => '/nonexistent-skills',+ projectImportedSkillCopy: unexpectedCall,+ });+}++describe('createSkillsRecoveryRoutes table', () => {+ test('registers exactly the four skill-recovery paths', () => {+ expect([...buildGroup().paths].sort()).toEqual(+ [+ '/api/skill/restore',+ '/api/skill/reimport',+ '/api/skills/reimport-bulk',+ '/api/skill/revert',+ ].sort(),+ );+ });++ test('every skill-recovery path is mutating (whole-family legacy MUTATING_ROUTES membership)', () => {+ const { table } = buildGroup();+ for (const path of [+ '/api/skill/restore',+ '/api/skill/reimport',+ '/api/skills/reimport-bulk',+ '/api/skill/revert',+ ]) {+ expect(table.isMutating(path), path).toBe(true);+ }+ });+});diff --git a/packages/server/src/http/skills-recovery-routes.ts b/packages/server/src/http/skills-recovery-routes.tsnew file mode 100644index 000000000..e75d91a2d--- /dev/null+++ b/packages/server/src/http/skills-recovery-routes.ts@@ -0,0 +1,807 @@+import { existsSync, readFileSync } from 'node:fs';+import type { ServerResponse } from 'node:http';+import { join, resolve } from 'node:path';+import {+ type Principal,+ RENAMED_PACK_SKILLS,+ type SkillReimportBulkResult,+ SkillReimportRequestSchema,+ SkillReimportSuccessSchema,+ SkillRestoreRequestSchema,+ SkillRestoreSuccessSchema,+ SkillRevertRequestSchema,+ SkillRevertSuccessSchema,+ SkillsReimportBulkRequestSchema,+ SkillsReimportBulkSuccessSchema,+} from '@inkeep/open-knowledge-core';+import { resolveProjectIdentity } from '@inkeep/open-knowledge-core/shadow-repo-layout';+import {+ discoverSkillDirs,+ fetchSource,+ parseSkillDir,+ parseSource,+ resolvePluginUpdateSource,+ resolveSkillsShImportSource,+ retrofitPackLockEntry,+ SKILLS_LOCK_REL,+ SkillFetchError,+ type SkillsLock,+ upsertLockEntry,+} from '@inkeep/open-knowledge-core/skills-catalog';+import type { ContentFilter } from '../content-filter.ts';+import { extractActorIdentity } from '../extract-actor-identity.ts';+import { scanGlobalInPlaceSkills, scanInPlaceSkills } from '../in-place-skills.ts';+import { getLogger } from '../logger.ts';+import type { SkillReimportDeps, SkillReimportService } from '../services/skill-reimport.ts';+import {+ groupReimportNamesBySource,+ pickReimportDir,+ type SkillReimportOutcome,+} from '../services/skill-reimport.ts';+import type { ShadowRef } from '../shadow-repo.ts';+import { isDisallowedGitSpec, rejectDisallowedGitSpec } from '../skill-git-spec-guard.ts';+import { validateSkillForInstall } from '../skill-projection.ts';+import { restoreSkillVersion } from '../skill-restore.ts';+import { mutateSkillsLock, readSkillsLockFile } from '../skills-lock-store.ts';+import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';+import { errorResponse } from './error-response.ts';+import { getRequestId } from './request-id.ts';+import { withValidation } from './request-validation.ts';+import { successResponse } from './success-response.ts';++function bundleSelfIdentifiesAsPack(dir: string): boolean {+ try {+ const md = readFileSync(join(dir, 'SKILL.md'), 'utf-8');+ const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(md)?.[1];+ return (+ frontmatter !== undefined && /^[ \t]+pack:[ \t]*"?[a-z0-9-]+"?[ \t]*$/m.test(frontmatter)+ );+ } catch {+ return false;+ }+}++export interface SkillsRecoveryRouteDeps {+ synthPluginLockEntry: (+ name: string,+ identity: string,+ skillAbsDir?: string,+ ) => SkillsLock['skills'][string] | null;+ synthBuiltinLockEntry: (+ base: string,+ name: string,+ scope: 'project' | 'global',+ ) => SkillsLock['skills'][string] | null;+ isValidSkillName: (name: string) => boolean;+ getPrincipal: (() => Principal | null) | undefined;+ validateSkillName: (name: string, res: ServerResponse, handler: string) => boolean;+ rejectReservedBuiltinSkill: (name: string, res: ServerResponse, handler: string) => boolean;+ shadowRef: ShadowRef | undefined;+ contentDir: string;+ contentRoot: string | undefined;+ projectDir: string | undefined;+ skillsHome: string;+ projectSkillDirRel: (name: string) => string;+ attributeOkArtifactWrite: SkillReimportDeps['attributeOkArtifactWrite'];+ okArtifactKey: (+ kind: 'template' | 'folder-frontmatter' | 'folder' | 'skill',+ folder: string,+ name?: string,+ ) => string;+ commitOkArtifactWrite: SkillReimportDeps['commitOkArtifactWrite'];+ signalChannel: ((channel: 'files' | 'lint-config' | 'comments') => void) | undefined;+ bumpSkillsCatalogGen: () => void;+ contentFilter: ContentFilter | undefined;+ scheduleDeferredIgnoreRebuild: () => void;+ effectiveSkillRoot: SkillReimportDeps['effectiveSkillRoot'];+ skillReimportService: SkillReimportService;+ localSkillHash: (skillsRoot: string, name: string) => string | undefined;+ resolveSkillsRoot: (scope: 'project' | 'global') => string;+ projectImportedSkillCopy: SkillReimportDeps['projectImportedSkillCopy'];+}+export function createSkillsRecoveryRoutes(deps: SkillsRecoveryRouteDeps): ApiRouteGroup {+ const {+ synthPluginLockEntry,+ synthBuiltinLockEntry,+ isValidSkillName,+ getPrincipal,+ validateSkillName,+ rejectReservedBuiltinSkill,+ shadowRef,+ contentDir,+ contentRoot,+ projectDir,+ skillsHome,+ projectSkillDirRel,+ attributeOkArtifactWrite,+ okArtifactKey,+ commitOkArtifactWrite,+ signalChannel,+ bumpSkillsCatalogGen,+ contentFilter,+ scheduleDeferredIgnoreRebuild,+ effectiveSkillRoot,+ skillReimportService,+ localSkillHash,+ resolveSkillsRoot,+ projectImportedSkillCopy,+ } = deps;+ function respondSkillRestoreFailure(+ res: ServerResponse,+ result: {+ code: 'no-shadow' | 'version-not-found' | 'skill-absent' | 'io-error' | 'path-escape';+ error: string;+ },+ handler: 'skill-restore' | 'skill-revert',+ ): void {+ const map = {+ 'no-shadow': [409, 'urn:ok:error:shadow-not-configured'],+ 'version-not-found': [404, 'urn:ok:error:not-found'],+ 'skill-absent': [404, 'urn:ok:error:not-found'],+ 'io-error': [500, 'urn:ok:error:storage-error'],+ 'path-escape': [500, 'urn:ok:error:path-escape'],+ } as const;+ const [status, typeUri] = map[result.code];+ errorResponse(res, status, typeUri, result.error, { handler, detail: result.code });+ }++ function respondSkillReimport(res: ServerResponse, outcome: SkillReimportOutcome): void {+ if (outcome.ok) {+ successResponse(res, 200, SkillReimportSuccessSchema, outcome.body, {+ handler: 'skill-reimport',+ });+ return;+ }+ errorResponse(res, outcome.status, outcome.urn, outcome.title, {+ handler: 'skill-reimport',+ ...(outcome.detail !== undefined ? { detail: outcome.detail } : {}),+ ...(outcome.cause !== undefined ? { cause: outcome.cause } : {}),+ });+ }++ function packBundleDir(scope: 'project' | 'global', name: string, skillsRoot: string): string {+ const base = scope === 'project' ? contentDir : skillsHome;+ const found = (+ scope === 'project' ? scanInPlaceSkills(contentDir) : scanGlobalInPlaceSkills(skillsHome)+ ).find((s) => s.name === name);+ return found ? resolve(base, found.dir) : resolve(skillsRoot, name);+ }++ function resolveReimportLockEntry(+ scope: 'project' | 'global',+ name: string,+ skillsRoot: string,+ lock: SkillsLock,+ ): SkillsLock['skills'][string] | null {+ const recorded = lock.skills[name];+ if (recorded) return recorded;+ const bundleDir = packBundleDir(scope, name, skillsRoot);+ return (+ retrofitPackLockEntry(+ name,+ parseSkillDir(bundleDir)?.contentHash ?? '',+ new Date().toISOString(),+ { selfIdentifiesAsPack: bundleSelfIdentifiesAsPack(bundleDir) },+ ) ??+ synthBuiltinLockEntry(scope === 'global' ? skillsHome : contentDir, name, scope) ??+ synthPluginLockEntry(name, resolveProjectIdentity(projectDir ?? contentDir), bundleDir)+ );+ }++ const handleSkillRestore = withValidation(+ SkillRestoreRequestSchema,+ async (_req, res, body) => {+ try {+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-restore',+ });+ return;+ }+ if (!validateSkillName(body.name, res, 'skill-restore')) return;+ if (rejectReservedBuiltinSkill(body.name, res, 'skill-restore')) return;+ if (body.scope === 'global') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Global skills are unversioned — there is no version history to restore from.',+ { handler: 'skill-restore', detail: 'GLOBAL_SCOPE_UNVERSIONED' },+ );+ return;+ }++ const shadow = shadowRef?.current;+ if (!shadow) {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:shadow-not-configured',+ 'No version history available to restore from.',+ {+ handler: 'skill-restore',+ detail: 'NO_SHADOW_REPO',+ },+ );+ return;+ }+ const result = await restoreSkillVersion({+ shadow,+ contentDir,+ contentRoot: contentRoot ?? '.',+ name: body.name,+ version: body.version,+ skillDirRel: projectSkillDirRel(body.name),+ });+ if (!result.ok) {+ respondSkillRestoreFailure(res, result, 'skill-restore');+ return;+ }++ const warnings: string[] = [];+ const skillDir = resolve(contentDir, projectSkillDirRel(body.name));+ const validity = validateSkillForInstall(skillDir, body.name);+ if (!validity.ok) {+ warnings.push(+ `Restored, but the skill no longer validates: ${validity.errors.join(' ')}`,+ );+ }++ attributeOkArtifactWrite(+ actor,+ okArtifactKey('skill', '', body.name),+ `skill-restore: ${body.name} @ ${body.version.slice(0, 8)}`,+ );+ await commitOkArtifactWrite('skill-restore');+ signalChannel?.('files');+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();++ successResponse(+ res,+ 200,+ SkillRestoreSuccessSchema,+ {+ name: body.name,+ version: body.version,+ restoredFiles: result.restoredFiles,+ warnings,+ },+ { handler: 'skill-restore' },+ );+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to restore skill.', {+ handler: 'skill-restore',+ cause: e,+ });+ }+ },+ { handler: 'skill-restore', method: 'POST' },+ );++ const handleSkillReimport = withValidation(+ SkillReimportRequestSchema,+ async (_req, res, body) => {+ let cleanup: () => void = () => {};+ try {+ if (body.scope === 'project' && !projectDir) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {+ handler: 'skill-reimport',+ detail: 'NO_PROJECT_ROOT',+ });+ return;+ }+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-reimport',+ });+ return;+ }+ if (!validateSkillName(body.name, res, 'skill-reimport')) return;++ const reimportBase = body.scope === 'global' ? skillsHome : contentDir;+ const {+ root: skillsRoot,+ dirRel: skillDirRel,+ realDir: reimportRealDir,+ } = effectiveSkillRoot(body.scope, body.name);+ if (+ reimportRealDir === null ||+ !existsSync(resolve(reimportBase, skillDirRel, 'SKILL.md'))+ ) {+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Skill is not installed.', {+ handler: 'skill-reimport',+ detail: 'SKILL_ABSENT',+ });+ return;+ }++ const lockPath = join(+ body.scope === 'global' ? skillsHome : (projectDir as string),+ ...SKILLS_LOCK_REL,+ );+ const entry = resolveReimportLockEntry(+ body.scope,+ body.name,+ skillsRoot,+ readSkillsLockFile(lockPath),+ );+ if (!entry) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'This skill has no recorded import source to update from.',+ { handler: 'skill-reimport', detail: 'NOT_IMPORTED' },+ );+ return;+ }+ if (body.setAutoUpdate !== undefined) {+ await mutateSkillsLock(lockPath, (current) => ({+ ...current,+ skills: {+ ...current.skills,+ [body.name]: {+ ...(current.skills[body.name] ?? entry),+ autoUpdate: body.setAutoUpdate,+ },+ },+ }));+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();++ successResponse(+ res,+ 200,+ SkillReimportSuccessSchema,+ { name: body.name, updated: false, source: entry.source, warnings: [] },+ { handler: 'skill-reimport' },+ );+ return;+ }+ let ref: string | undefined;+ let acquiredDir: string | null = null;+ try {+ const recordedSkill = entry.skill ?? body.name;+ const renamedSkill = RENAMED_PACK_SKILLS[recordedSkill];+ const skillsSh = await resolveSkillsShImportSource(entry.source, recordedSkill).catch(+ async (err: unknown) => {+ if (renamedSkill === undefined) throw err;+ return resolveSkillsShImportSource(entry.source, renamedSkill);+ },+ );+ const resolvedSource =+ skillsSh?.source ?? resolvePluginUpdateSource(entry.source, entry.pluginProvider);+ const resolvedSkill = skillsSh?.skill ?? entry.skill;+ const spec = skillsSh?.spec ?? parseSource(resolvedSource);+ if (!spec) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'The recorded import source is no longer a valid source.',+ { handler: 'skill-reimport', detail: entry.source },+ );+ return;+ }+ if (rejectDisallowedGitSpec(res, spec, 'skill-reimport')) return;+ const fetched = await fetchSource(spec);+ cleanup = fetched.cleanup;+ ref = fetched.ref;+ const dirs = discoverSkillDirs(fetched.dir);+ const pick = pickReimportDir(dirs, {+ ...(resolvedSkill !== undefined ? { recordedSkill: resolvedSkill } : {}),+ localName: body.name,+ frontmatterNameOf: (dir) => parseSkillDir(dir)?.name,+ });+ if (!pick) {+ errorResponse(+ res,+ 404,+ 'urn:ok:error:not-found',+ 'Could not locate this skill in its source anymore.',+ { handler: 'skill-reimport', detail: dirs.map((d) => d.name).join(', ') },+ );+ return;+ }+ acquiredDir = pick.dir;+ } catch (e) {+ if (e instanceof SkillFetchError) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Could not fetch source.', {+ handler: 'skill-reimport',+ cause: e,+ });+ return;+ }+ throw e;+ }+ if (!acquiredDir) {+ errorResponse(res, 422, 'urn:ok:error:invalid-request', 'Source has no readable skill.', {+ handler: 'skill-reimport',+ });+ return;+ }+ const outcome = await skillReimportService.runSkillReimport({+ acquiredDir,+ name: body.name,+ scope: body.scope,+ entry,+ lockPath,+ ref,+ actor,+ ...(body.dryRun !== undefined ? { dryRun: body.dryRun } : {}),+ });+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ scheduleDeferredIgnoreRebuild();++ respondSkillReimport(res, outcome);+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to reimport skill.', {+ handler: 'skill-reimport',+ cause: e,+ });+ } finally {+ cleanup();+ }+ },+ { handler: 'skill-reimport', method: 'POST' },+ );++ const handleSkillsReimportBulk = withValidation(+ SkillsReimportBulkRequestSchema,+ async (_req, res, body) => {+ try {+ if (body.scope === 'project' && !projectDir) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {+ handler: 'skills-reimport-bulk',+ detail: 'NO_PROJECT_ROOT',+ });+ return;+ }+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skills-reimport-bulk',+ });+ return;+ }+ const lockPath = join(+ body.scope === 'global' ? skillsHome : (projectDir as string),+ ...SKILLS_LOCK_REL,+ );+ const lock = readSkillsLockFile(lockPath);+ const results: SkillReimportBulkResult[] = [];+ const named = new Set(body.names);+ const wellFormed = [...named].filter((name) => {+ if (isValidSkillName(name)) return true;+ results.push({ requested: name, status: 'failed', warnings: [], error: 'INVALID_NAME' });+ return false;+ });+ const { bySource, unrecorded } = groupReimportNamesBySource(wellFormed, (name) =>+ resolveReimportLockEntry(+ body.scope,+ name,+ effectiveSkillRoot(body.scope, name).root,+ lock,+ ),+ );+ for (const name of unrecorded) {+ results.push({ requested: name, status: 'not-found', warnings: [] });+ }++ for (const group of bySource) {+ let cleanup: () => void = () => {};+ try {+ let ref: string | undefined;+ let dirs: ReturnType<typeof discoverSkillDirs> = [];+ try {+ const probe = group.names[0] as string;+ const skillsSh = await resolveSkillsShImportSource(group.source, probe).catch(+ async (err: unknown) => {+ const renamed = RENAMED_PACK_SKILLS[probe];+ if (renamed === undefined) throw err;+ return resolveSkillsShImportSource(group.source, renamed);+ },+ );+ const resolvedSource =+ skillsSh?.source ??+ resolvePluginUpdateSource(+ group.source,+ lock.skills[group.names[0] as string]?.pluginProvider,+ );+ const spec = skillsSh?.spec ?? parseSource(resolvedSource);+ if (!spec || isDisallowedGitSpec(spec)) {+ for (const name of group.names) {+ results.push({+ requested: name,+ status: 'failed',+ source: group.source,+ warnings: [],+ error: 'INVALID_SOURCE',+ });+ }+ continue;+ }+ const fetched = await fetchSource(spec);+ cleanup = fetched.cleanup;+ ref = fetched.ref;+ dirs = discoverSkillDirs(fetched.dir);+ } catch (e) {+ getLogger('skills-reimport-bulk').warn(+ { source: group.source, err: e, requestId: getRequestId(_req) },+ 'bulk update: one source could not be fetched (rest continue)',+ );+ for (const name of group.names) {+ results.push({+ requested: name,+ status: 'failed',+ source: group.source,+ warnings: [],+ error: e instanceof Error ? e.message : String(e),+ });+ }+ continue;+ }+ for (const name of group.names) {+ const entry = resolveReimportLockEntry(+ body.scope,+ name,+ effectiveSkillRoot(body.scope, name).root,+ lock,+ );+ if (!entry) {+ results.push({ requested: name, status: 'not-found', warnings: [] });+ continue;+ }+ const pick = pickReimportDir(dirs, {+ ...(entry.skill !== undefined ? { recordedSkill: entry.skill } : {}),+ localName: name,+ frontmatterNameOf: (dir) => parseSkillDir(dir)?.name,+ });+ if (!pick) {+ results.push({+ requested: name,+ status: 'not-found',+ source: entry.source,+ warnings: [],+ });+ continue;+ }+ try {+ const outcome = await skillReimportService.runSkillReimport({+ acquiredDir: pick.dir,+ name,+ scope: body.scope,+ entry,+ lockPath,+ ref,+ actor,+ });+ if (!outcome.ok) {+ getLogger('skills-reimport-bulk').warn(+ {+ skill: name,+ err: outcome.cause,+ detail: outcome.detail,+ requestId: getRequestId(_req),+ },+ 'bulk update: one skill failed (rest continue)',+ );+ results.push({+ requested: name,+ status: 'failed',+ source: entry.source,+ warnings: [],+ error: outcome.detail ?? outcome.title,+ });+ continue;+ }+ results.push({+ requested: name,+ status: outcome.body.updated ? 'updated' : 'up-to-date',+ source: outcome.body.source,+ warnings: outcome.body.warnings,+ });+ } catch (e) {+ getLogger('skills-reimport-bulk').warn(+ { skill: name, err: e, requestId: getRequestId(_req) },+ 'bulk update: one skill threw (rest continue)',+ );+ results.push({+ requested: name,+ status: 'failed',+ source: entry.source,+ warnings: [],+ error: e instanceof Error ? e.message : String(e),+ });+ }+ }+ } finally {+ cleanup();+ }+ }+ successResponse(+ res,+ 200,+ SkillsReimportBulkSuccessSchema,+ {+ results,+ updated: results.filter((r) => r.status === 'updated').length,+ upToDate: results.filter((r) => r.status === 'up-to-date').length,+ failed: results.filter((r) => r.status === 'failed' || r.status === 'not-found').length,+ },+ { handler: 'skills-reimport-bulk' },+ );++ try {+ bumpSkillsCatalogGen();+ contentFilter?.refreshInPlaceSkillDirs();+ bumpSkillsCatalogGen();+ await contentFilter?.rebuildIgnorePatterns();+ } catch (e) {+ getLogger('skills-reimport-bulk').warn(+ { err: e },+ 'bulk update: ignore-pattern rebuild failed after a reported success',+ );+ }+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to update skills.', {+ handler: 'skills-reimport-bulk',+ cause: e,+ });+ }+ },+ { handler: 'skills-reimport-bulk', method: 'POST' },+ );++ const handleSkillRevert = withValidation(+ SkillRevertRequestSchema,+ async (_req, res, body) => {+ try {+ if (!projectDir) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project root resolved.', {+ handler: 'skill-revert',+ detail: 'NO_PROJECT_ROOT',+ });+ return;+ }+ const actor = extractActorIdentity(+ body as unknown as Record<string, unknown>,+ getPrincipal,+ );+ if (actor.kind === 'invalid-summary') {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {+ handler: 'skill-revert',+ });+ return;+ }+ if (!validateSkillName(body.name, res, 'skill-revert')) return;+ if (rejectReservedBuiltinSkill(body.name, res, 'skill-revert')) return;+ if (body.scope === 'global') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Global skills are unversioned — there is nothing to revert to.',+ { handler: 'skill-revert', detail: 'GLOBAL_SCOPE' },+ );+ return;+ }++ const lockPath = join(projectDir, ...SKILLS_LOCK_REL);+ const lock = readSkillsLockFile(lockPath);+ const entry = lock.skills[body.name];+ if (!entry?.baselineRef) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'This skill has no recorded install baseline to revert to.',+ { handler: 'skill-revert', detail: 'NO_BASELINE' },+ );+ return;+ }+ const shadow = shadowRef?.current;+ if (!shadow) {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:shadow-not-configured',+ 'No version history available to revert from.',+ { handler: 'skill-revert', detail: 'NO_SHADOW_REPO' },+ );+ return;+ }++ const result = await restoreSkillVersion({+ shadow,+ contentDir,+ contentRoot: contentRoot ?? '.',+ name: body.name,+ version: entry.baselineRef,+ skillDirRel: projectSkillDirRel(body.name),+ });+ if (!result.ok) {+ respondSkillRestoreFailure(res, result, 'skill-revert');+ return;+ }++ attributeOkArtifactWrite(+ actor,+ okArtifactKey('skill', '', body.name),+ `skill-revert: ${body.name} @ ${entry.baselineRef.slice(0, 8)}`,+ );+ await commitOkArtifactWrite('skill-revert');++ const revertRoot = resolve(contentDir, projectSkillDirRel(body.name), '..');+ const revertedLocalHash = localSkillHash(revertRoot, body.name);+ await mutateSkillsLock(lockPath, (current) =>+ upsertLockEntry(current, body.name, {+ ...(current.skills[body.name] ?? entry),+ ...(revertedLocalHash !== undefined ? { localHash: revertedLocalHash } : {}),+ }),+ );++ if (revertRoot === resolveSkillsRoot('project')) {+ await projectImportedSkillCopy({+ skillsRoot: revertRoot,+ name: body.name,+ scope: 'project',+ hasScripts: result.restoredFiles.some((f) => f.startsWith('scripts/')),+ handler: 'skill-revert',+ });+ }++ signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillRevertSuccessSchema,+ {+ name: body.name,+ baselineRef: entry.baselineRef,+ restoredFiles: result.restoredFiles,+ warnings: [],+ },+ { handler: 'skill-revert' },+ );+ } catch (e) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to revert skill.', {+ handler: 'skill-revert',+ cause: e,+ });+ }+ },+ { handler: 'skill-revert', method: 'POST' },+ );+ return createApiRouteGroup(+ {+ '/api/skill/restore': handleSkillRestore,+ '/api/skill/reimport': handleSkillReimport,+ '/api/skills/reimport-bulk': handleSkillsReimportBulk,+ '/api/skill/revert': handleSkillRevert,+ },+ {+ mutating: [+ '/api/skill/restore',+ '/api/skill/reimport',+ '/api/skills/reimport-bulk',+ '/api/skill/revert',+ ],+ },+ );+}diff --git a/packages/server/src/http/skills-tracking-routes.test.ts b/packages/server/src/http/skills-tracking-routes.test.tsnew file mode 100644index 000000000..65f29c3c5--- /dev/null+++ b/packages/server/src/http/skills-tracking-routes.test.ts@@ -0,0 +1,27 @@+import { describe, expect, test } from 'vitest';+import { createSkillsTrackingRoutes } from './skills-tracking-routes.ts';++function buildGroup() {+ return createSkillsTrackingRoutes({+ contentDir: '/nonexistent-content',+ projectDir: undefined,+ contentFilter: undefined,+ validateSkillName: () => true,+ indexedSkillContentPath: () => null,+ bumpSkillsCatalogGen: () => {},+ signalChannel: undefined,+ });+}++describe('createSkillsTrackingRoutes table', () => {+ test('registers exactly the one skill-tracking path', () => {+ expect([...buildGroup().paths].sort()).toEqual(['/api/skill/track-in-git'].sort());+ });++ test('every skill-tracking path is mutating (whole-family legacy MUTATING_ROUTES membership)', () => {+ const { table } = buildGroup();+ for (const path of ['/api/skill/track-in-git']) {+ expect(table.isMutating(path), path).toBe(true);+ }+ });+});diff --git a/packages/server/src/http/skills-tracking-routes.ts b/packages/server/src/http/skills-tracking-routes.tsnew file mode 100644index 000000000..a3e511e33--- /dev/null+++ b/packages/server/src/http/skills-tracking-routes.ts@@ -0,0 +1,144 @@+import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import type { ServerResponse } from 'node:http';+import { dirname, resolve, sep } from 'node:path';+import {+ LEGACY_SKILL_STORE_ROOT,+ SkillTrackInGitRequestSchema,+ SkillTrackInGitSuccessSchema,+} from '@inkeep/open-knowledge-core';+import type { ContentFilter } from '../content-filter.ts';+import { scanInPlaceSkills } from '../in-place-skills.ts';+import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';+import { catchErrors } from './catch-errors.ts';+import { errorResponse } from './error-response.ts';+import { withValidation } from './request-validation.ts';+import { successResponse } from './success-response.ts';++export interface SkillsTrackingRouteDeps {+ contentDir: string;+ projectDir: string | undefined;+ contentFilter: ContentFilter | undefined;+ validateSkillName: (name: string, res: ServerResponse, handler: string) => boolean;+ indexedSkillContentPath: (absolutePath: string, contentDir: string) => string | null;+ bumpSkillsCatalogGen: () => void;+ signalChannel: ((channel: 'files' | 'lint-config' | 'comments') => void) | undefined;+}++export function createSkillsTrackingRoutes(deps: SkillsTrackingRouteDeps): ApiRouteGroup {+ const {+ contentDir,+ projectDir,+ contentFilter,+ validateSkillName,+ indexedSkillContentPath,+ bumpSkillsCatalogGen,+ signalChannel,+ } = deps;+ function trackInGitLine(skillDirRel: string): string {+ const root = dirname(skillDirRel);+ return `!/${root.split(sep).join('/')}/`;+ }++ const handleSkillTrackInGit = withValidation(+ SkillTrackInGitRequestSchema,+ catchErrors(+ async (_req, res, body) => {+ if (!validateSkillName(body.name, res, 'skill-track-in-git')) return;+ if (body.scope !== 'project') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Only project skills live in the repository; a global skill is outside any .gitignore.',+ { handler: 'skill-track-in-git' },+ );+ return;+ }+ if (!projectDir) {+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'No project directory.', {+ handler: 'skill-track-in-git',+ });+ return;+ }+ const inPlace = scanInPlaceSkills(contentDir).find((s) => s.name === body.name);+ const mountedDirRel = inPlace?.dir ?? `${LEGACY_SKILL_STORE_ROOT}/${body.name}`;+ const indexedFileRel =+ indexedSkillContentPath(resolve(contentDir, mountedDirRel, 'SKILL.md'), contentDir) ??+ `${mountedDirRel}/SKILL.md`;+ const skillDirRel = dirname(indexedFileRel);+ const skillFileRel = indexedFileRel;+ const line = trackInGitLine(skillDirRel);+ const gitignoreRel = '.gitignore';+ const gitignoreAbs = resolve(contentDir, gitignoreRel);++ if (contentFilter && !contentFilter.isPathIgnored(skillFileRel)) {+ successResponse(+ res,+ 200,+ SkillTrackInGitSuccessSchema,+ { line, gitignorePath: gitignoreRel, applied: false, alreadyTracked: true },+ { handler: 'skill-track-in-git' },+ );+ return;+ }+ if (body.apply !== true) {+ successResponse(+ res,+ 200,+ SkillTrackInGitSuccessSchema,+ { line, gitignorePath: gitignoreRel, applied: false },+ { handler: 'skill-track-in-git' },+ );+ return;+ }++ const before = existsSync(gitignoreAbs) ? readFileSync(gitignoreAbs, 'utf-8') : null;+ const lines = (before ?? '').split('\n');+ if (lines.some((l) => l.trim() === line)) {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:invalid-request',+ `"${line}" is already in ${gitignoreRel}, but ${skillFileRel} is still ignored — another rule excludes it.`,+ { handler: 'skill-track-in-git' },+ );+ return;+ }+ const next = `${before === null || before.endsWith('\n') || before === '' ? (before ?? '') : `${before}\n`}${line}\n`;+ writeFileSync(gitignoreAbs, next, 'utf-8');+ bumpSkillsCatalogGen();+ await contentFilter?.rebuildIgnorePatterns();++ if (contentFilter?.isPathIgnored(skillFileRel)) {+ if (before === null) rmSync(gitignoreAbs, { force: true });+ else writeFileSync(gitignoreAbs, before, 'utf-8');+ bumpSkillsCatalogGen();+ await contentFilter.rebuildIgnorePatterns();+ errorResponse(+ res,+ 409,+ 'urn:ok:error:invalid-request',+ `Adding "${line}" did not make ${skillFileRel} trackable — another .gitignore rule excludes a parent directory. ${gitignoreRel} was left unchanged.`,+ { handler: 'skill-track-in-git' },+ );+ return;+ }+ signalChannel?.('files');+ successResponse(+ res,+ 200,+ SkillTrackInGitSuccessSchema,+ { line, gitignorePath: gitignoreRel, applied: true },+ { handler: 'skill-track-in-git' },+ );+ },+ { handler: 'skill-track-in-git', title: 'Failed to update .gitignore.' },+ ),+ { handler: 'skill-track-in-git', method: 'POST' },+ );++ return createApiRouteGroup(+ { '/api/skill/track-in-git': handleSkillTrackInGit },+ { mutating: ['/api/skill/track-in-git'] },+ );+}diff --git a/packages/server/src/skill-upload-process.test-helper.ts b/packages/server/src/skill-upload-process.test-helper.tsnew file mode 100644index 000000000..82e3ee5db--- /dev/null+++ b/packages/server/src/skill-upload-process.test-helper.ts@@ -0,0 +1,15 @@+import { bootCompositionRig } from './composition-rig.test-helper.ts';++process.once('disconnect', () => process.exit(0));+setTimeout(() => process.exit(2), 20_000).unref();++const contentDir = process.argv[2];+const home = process.argv[3];+if (!contentDir || !home) throw new Error('Upload fixture requires content and home directories.');+const server = await bootCompositionRig(contentDir, { configHomedirOverride: home });+await server.ready;+process.send?.({ port: server.port });+process.on('message', async () => {+ await server.destroy();+ process.exit(0);+});diff --git a/packages/server/src/skills-catalog-cache.test.ts b/packages/server/src/skills-catalog-cache.test.tsnew file mode 100644index 000000000..dd0dd3956--- /dev/null+++ b/packages/server/src/skills-catalog-cache.test.ts@@ -0,0 +1,134 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, expect, test, vi } from 'vitest';+import { getLogger } from './logger.ts';+import { createSkillsCatalogCache } from './skills-catalog-cache.ts';++let home: string;+beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'ok-catalog-owner-'));+});+afterEach(() => {+ vi.restoreAllMocks();+ rmSync(home, { recursive: true, force: true });+});++function cache() {+ return createSkillsCatalogCache({ homeDirOverride: home, log: getLogger('cache-test') });+}++function writeSkill(dir: string, description: string): void {+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, 'SKILL.md'),+ `---\nname: alpha\ndescription: ${description}\n---\n\nBody.\n`,+ );+}++test('installed enumeration caches each project and home key until exactly five seconds', () => {+ const c = cache();+ const clock = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ const initial = c.enumerateInstalledSkillsCached({ home });+ writeSkill(join(home, '.claude/skills/alpha'), 'added');+ clock.mockReturnValue(104_999);+ expect(c.enumerateInstalledSkillsCached({ home })).toBe(initial);+ clock.mockReturnValue(105_000);+ const refreshed = c.enumerateInstalledSkillsCached({ home });+ expect(refreshed.skills.some((s) => s.name === 'alpha')).toBe(true);+ expect(refreshed).not.toBe(initial);+ expect(c.enumerateInstalledSkillsCached({ home, projectDir: home })).not.toBe(refreshed);+ const otherHome = join(home, 'other');+ mkdirSync(otherHome);+ expect(c.enumerateInstalledSkillsCached({ home: otherHome }).skills).toEqual([]);+});++test('generation invalidation refreshes installed results while owners stay independent', () => {+ const a = cache();+ const b = cache();+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ const initialA = a.enumerateInstalledSkillsCached({ home });+ const initialB = b.enumerateInstalledSkillsCached({ home });+ writeSkill(join(home, '.claude/skills/alpha'), 'added');+ a.bumpSkillsCatalogGen();+ const refreshed = a.enumerateInstalledSkillsCached({ home });+ expect(refreshed).not.toBe(initialA);+ expect(refreshed.skills.some((s) => s.name === 'alpha')).toBe(true);+ expect(b.enumerateInstalledSkillsCached({ home })).toBe(initialB);+});++test('list completion stamps the current generation and completion time', async () => {+ const c = cache();+ const clock = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ expect(c.readList('fingerprint')).toBeNull();+ const completing = Promise.resolve().then(() =>+ c.writeList('fingerprint', { skills: ['alpha'] }),+ );+ c.bumpSkillsCatalogGen();+ clock.mockReturnValue(104_000);+ await completing;+ clock.mockReturnValue(108_999);+ expect(c.readList('fingerprint')?.body).toEqual({ skills: ['alpha'] });+ clock.mockReturnValue(109_000);+ expect(c.readList('fingerprint')).toBeNull();+});++test('list reads expose only the body and cannot replace the cached record', () => {+ const c = cache();+ const body = { skills: ['alpha'] };+ c.writeList('fingerprint', body);+ const hit = c.readList('fingerprint');+ expect(hit).toEqual({ body });+ expect(hit?.body).toBe(body);+ Object.assign(hit ?? {}, { body: { skills: ['replacement'] } });+ expect(c.readList('fingerprint')).toEqual({ body });+});++test('changed list fingerprints invalidate installed enumeration too', () => {+ const c = cache();+ vi.spyOn(Date, 'now').mockReturnValue(100_000);+ c.writeList('before', {});+ c.enumerateInstalledSkillsCached({ home });+ writeSkill(join(home, '.claude/skills/alpha'), 'added');+ expect(c.readList('after')).toBeNull();+ expect(c.enumerateInstalledSkillsCached({ home }).skills.some((s) => s.name === 'alpha')).toBe(+ true,+ );+});++function installPlugin(description: string): void {+ const installPath = join(home, '.claude/plugins/cache/team/eng/1.0.0');+ writeSkill(join(installPath, 'skills/alpha'), description);+ mkdirSync(join(installPath, '.claude-plugin'), { recursive: true });+ writeFileSync(+ join(installPath, '.claude-plugin/plugin.json'),+ JSON.stringify({ name: 'eng', version: '1.0.0' }),+ );+ writeFileSync(+ join(home, '.claude/plugins/installed_plugins.json'),+ JSON.stringify({+ version: 2,+ plugins: { 'eng@team': [{ scope: 'user', installPath, version: '1.0.0' }] },+ }),+ );+}++test('plugin content refreshes only on identity change or its independent thirty second expiry', () => {+ installPlugin('before');+ const c = cache();+ const clock = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ const first = c.pluginSkillsByName('project-a');+ expect(first.get('alpha')).toBeDefined();+ const hash = first.get('alpha')?.contentHash;+ installPlugin('after');+ c.bumpSkillsCatalogGen();+ clock.mockReturnValue(129_999);+ expect(c.pluginSkillsByName('project-a')).toBe(first);+ clock.mockReturnValue(130_000);+ const expired = c.pluginSkillsByName('project-a');+ expect(expired.get('alpha')?.contentHash).not.toBe(hash);+ installPlugin('third');+ c.bumpSkillsCatalogGen();+ const changedIdentity = c.pluginSkillsByName('project-b');+ expect(changedIdentity.get('alpha')?.contentHash).not.toBe(expired.get('alpha')?.contentHash);+});diff --git a/packages/server/src/skills-catalog-cache.ts b/packages/server/src/skills-catalog-cache.tsnew file mode 100644index 000000000..3a1273238--- /dev/null+++ b/packages/server/src/skills-catalog-cache.ts@@ -0,0 +1,105 @@+import {+ enumerateInstalledSkills,+ type PluginUpstream,+ parseSkillDir,+ pluginUpstreamsByName,+} from '@inkeep/open-knowledge-core/skills-catalog';+import type { PinoLogger } from './logger.ts';++export type SkillsCatalogCache = ReturnType<typeof createSkillsCatalogCache>;++export function createSkillsCatalogCache({+ homeDirOverride,+ log,+}: {+ homeDirOverride: string | undefined;+ log: PinoLogger;+}) {+ let skillsCatalogGen = 0;+ let skillsListCache: { at: number; gen: number; fp: string; body: unknown } | null = null;+ let installedCatalogCache: {+ at: number;+ gen: number;+ key: string;+ value: ReturnType<typeof enumerateInstalledSkills>;+ } | null = null;+ function bumpSkillsCatalogGen(): void {+ skillsCatalogGen += 1;+ }+ function enumerateInstalledSkillsCached(+ opts: Parameters<typeof enumerateInstalledSkills>[0],+ ): ReturnType<typeof enumerateInstalledSkills> {+ const key = `${opts?.projectDir ?? ''}|${opts && 'home' in opts ? opts.home : ''}`;+ const now = Date.now();+ if (+ installedCatalogCache !== null &&+ installedCatalogCache.gen === skillsCatalogGen &&+ installedCatalogCache.key === key &&+ now - installedCatalogCache.at < 5_000+ ) {+ return installedCatalogCache.value;+ }+ const value = enumerateInstalledSkills(opts);+ installedCatalogCache = { at: now, gen: skillsCatalogGen, key, value };+ return value;+ }++ function readList(inPlaceFp: string): { readonly body: unknown } | null {+ if (skillsListCache !== null && skillsListCache.fp !== inPlaceFp) {+ bumpSkillsCatalogGen();+ }+ if (+ skillsListCache !== null &&+ skillsListCache.gen === skillsCatalogGen &&+ skillsListCache.fp === inPlaceFp &&+ Date.now() - skillsListCache.at < 5_000+ ) {+ return { body: skillsListCache.body };+ }+ return null;+ }++ function writeList(inPlaceFp: string, responseBody: unknown): void {+ skillsListCache = {+ at: Date.now(),+ gen: skillsCatalogGen,+ fp: inPlaceFp,+ body: responseBody,+ };+ }++ const PLUGIN_INDEX_TTL_MS = 30_000;+ let pluginIndex: { at: number; identity: string; byName: Map<string, PluginUpstream> } | null =+ null;++ function pluginSkillsByName(identity: string): Map<string, PluginUpstream> {+ const now = Date.now();+ if (+ pluginIndex &&+ pluginIndex.identity === identity &&+ now - pluginIndex.at < PLUGIN_INDEX_TTL_MS+ )+ return pluginIndex.byName;+ let byName = new Map<string, PluginUpstream>();+ try {+ byName = pluginUpstreamsByName(+ enumerateInstalledSkillsCached(+ homeDirOverride !== undefined ? { home: homeDirOverride } : {},+ ).skills,+ (home) => parseSkillDir(home)?.contentHash,+ );+ } catch (err) {+ log.warn({ err }, 'plugin upstream index failed; origins will be omitted');+ }+ pluginIndex = { at: now, identity, byName };+ return byName;+ }++ return {+ bumpSkillsCatalogGen,+ enumerateInstalledSkillsCached,+ readList,+ writeList,+ pluginSkillsByName,+ };+}