skill-flow 1.3.3 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js.map CHANGED
@@ -1 +1,7 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.tsx"],"names":[],"mappings":";;AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAC7B,OAAO,WAAW,MAAM,iBAAiB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,wBAAwB,EAA0B,MAAM,6BAA6B,CAAC;AAC3G,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAC;AACtE,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EAEjB,kBAAkB,GACnB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,mCAAmC,CAAC;AAC/F,OAAO,EAAE,gBAAgB,EAAE,MAAM,4CAA4C,CAAC;AAC9E,OAAO,EACL,mBAAmB,EACnB,kBAAkB,GAEnB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAE3D,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;AAC9B,MAAM,GAAG,GAAG,IAAI,YAAY,EAAE,CAAC;AAE/B,OAAO,CAAC,GAAG,CAAC,iBAAiB,KAAK,KAAK,CAAC;AAExC,OAAO;KACJ,IAAI,CAAC,YAAY,CAAC;KAClB,WAAW,CAAC,yCAAyC,CAAC;KACtD,OAAO,CAAC,WA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;IACT,CAAC;IAED,WAAW,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IAC3C,aAAa,CAAC,iBAAiB,CAAC,MAAM,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,CAAC;IACxD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC;AAED,SAAS,aAAa,CAAC,KAAa,EAAE,QAAkB;IACtD,OAAO,CAAC,GAAG,QAAQ,EAAE,KAAK,CAAC,CAAC;AAC9B,CAAC"}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/cli.tsx", "../package.json", "../../../packages/query/src/runtime.ts", "../../../packages/integration/src/adapters/channel-adapters.ts", "../../../packages/integration/src/utils/constants.ts", "../../../packages/integration/src/utils/fs.ts", "../../../packages/domain/src/projection-compat.ts", "../../../packages/storage/src/store.ts", "../../../packages/storage/src/import-data-cache.ts", "../../../packages/storage/src/preferences-store.ts", "../../../packages/storage/src/source-metadata-cache.ts", "../../../packages/integration/src/utils/builtin-git-sources.ts", "../../../packages/integration/src/utils/naming.ts", "../../../packages/integration/src/utils/github-catalog.ts", "../../../packages/integration/src/utils/result.ts", "../../../packages/integration/src/utils/clawhub.ts", "../../../packages/integration/src/utils/source-id.ts", "../../../packages/integration/src/utils/skills-directory.ts", "../../../packages/integration/src/utils/source-details.ts", "../../../packages/core-engine/src/services/deployment-applier.ts", "../../../packages/query/src/config-coordinator.ts", "../../../packages/core-engine/src/services/deployment-planner.ts", "../../../packages/core-engine/src/services/doctor-service.ts", "../../../packages/core-engine/src/services/inventory-service.ts", "../../../packages/core-engine/src/services/recent-project-service.ts", "../../../packages/integration/src/project-observations.ts", "../../../packages/integration/src/utils/cli.ts", "../../../packages/integration/src/utils/find-command.ts", "../../../packages/integration/src/utils/format.ts", "../../../packages/integration/src/utils/git.ts", "../../../packages/core-engine/src/services/source-service.ts", "../../../packages/query/src/workflow-service.ts", "../../../packages/core-engine/src/services/workspace-bootstrap-service.ts", "../../../packages/tui/src/config-app.tsx", "../../../packages/tui/src/selection-state.ts", "../../../packages/tui/src/add-flow.tsx", "../../../packages/tui/src/add-flow-model.ts", "../../../packages/tui/src/find-app.tsx", "../../../packages/shared-types/src/protocol.ts", "../src/bridge-command.ts"],
4
+ "sourcesContent": ["#!/usr/bin/env node\nimport React from \"react\";\nimport { Command } from \"commander\";\nimport { render } from \"ink\";\nimport packageJson from \"../package.json\" with { type: \"json\" };\nimport { SkillFlowApp } from \"@skill-flow/query/runtime\";\nimport { ConfigBootstrapApp } from \"@skill-flow/tui/config-app.js\";\nimport { FindApp } from \"@skill-flow/tui/find-app.js\";\nimport { AddFlowApp, runAddFlowNonInteractive, type AddFlowExitResult } from \"@skill-flow/tui/add-flow.js\";\nimport { formatGroupRef } from \"@skill-flow/integration/utils/naming\";\nimport {\n formatActionSummary,\n formatDoctorIssue,\n formatSkillCandidates,\n formatWorkflowList,\n} from \"@skill-flow/integration/utils/format\";\nimport { filterAddWarnings, resolveAddSourceLocator } from \"@skill-flow/integration/utils/cli\";\nimport { buildFindCommand } from \"@skill-flow/integration/utils/find-command\";\nimport {\n buildBridgeResponse,\n parseBridgeRequest,\n type BridgeRequest,\n} from \"@skill-flow/shared-types/protocol\";\nimport { executeBridgeRequest } from \"./bridge-command.js\";\n\nconst program = new Command();\nconst app = new SkillFlowApp();\n\nprocess.env.SKILL_FLOW_CALLER ??= \"cli\";\n\nprogram\n .name(\"skill-flow\")\n .description(\"Workflow-first skill projection manager\")\n .version(packageJson.version);\n\nprogram\n .command(\"add\")\n .argument(\"<source>\", \"Source locator\")\n .option(\"--path <repoSubpath>\", \"Filter Git sources to a specific repo subpath\")\n .option(\"--from <catalog>\", \"Interpret source using a named catalog\")\n .option(\"--skill <id>\", \"Enable a specific skill selector\", collectOption, [])\n .option(\"--agent <target>\", \"Enable a specific deployment target\", collectOption, [])\n .option(\"--yes\", \"Skip prompts and use default selections\")\n .option(\"--all\", \"Enable all discovered skills and all detected targets\")\n .action(async (\n source: string,\n options: {\n path?: string;\n from?: string;\n skill?: string[];\n agent?: string[];\n yes?: boolean;\n all?: boolean;\n },\n ) => {\n let resolvedSource: string;\n try {\n resolvedSource = resolveAddSourceLocator(source, options.from);\n } catch (error) {\n printErrors([{ message: error instanceof Error ? error.message : String(error) }]);\n process.exitCode = 1;\n return;\n }\n\n const request = {\n locator: resolvedSource,\n ...(options.path ? { path: options.path } : {}),\n ...(options.skill?.length ? { requestedSkills: options.skill } : {}),\n ...(options.agent?.length ? { requestedAgents: options.agent } : {}),\n ...(options.yes ? { yes: true } : {}),\n ...(options.all ? { all: true } : {}),\n };\n\n if (options.all || options.yes) {\n const result = await runAddFlowNonInteractive(app, request);\n handleAddFlowResult(result);\n return;\n }\n\n const result = await runRenderedAddFlow(app, request);\n handleAddFlowResult(result, { rendered: true });\n });\n\nprogram.command(\"list\").action(async () => {\n const result = await app.listWorkflows();\n if (!result.ok) {\n printErrors(result.errors);\n process.exitCode = 1;\n return;\n }\n console.log(formatWorkflowList(result.data.summaries));\n});\n\nprogram\n .command(\"find\")\n .alias(\"search\")\n .argument(\"<query>\", \"Search query\")\n .option(\"--json\", \"Print JSON output\")\n .action(async (query: string, options: { json?: boolean }) => {\n if (options.json) {\n const result = await app.findSkills(query);\n if (!result.ok) {\n printErrors(result.errors);\n process.exitCode = 1;\n return;\n }\n console.log(\n JSON.stringify(\n result.data.candidates.map((candidate) => ({\n ...candidate,\n nextCommand: buildFindCommand(candidate),\n })),\n null,\n 2,\n ),\n );\n return;\n }\n const instance = render(<FindApp app={app} query={query} />);\n await instance.waitUntilExit();\n });\n\nprogram.command(\"config\").action(async () => {\n const instance = render(<ConfigBootstrapApp app={app} />);\n await instance.waitUntilExit();\n});\n\nprogram\n .command(\"repair-source\")\n .argument(\"[sourceId]\", \"Optional skills group id\")\n .option(\"--all\", \"Repair owned source checkouts for all registered skills groups\")\n .action(async (sourceId: string | undefined, options: { all?: boolean }) => {\n const ids = options.all || !sourceId ? undefined : [sourceId];\n const result = await app.repairSource(ids);\n if (!result.ok) {\n printErrors(result.errors);\n process.exitCode = 1;\n return;\n }\n for (const item of result.data.updated) {\n console.log(\n `${item.sourceId} changed:${item.changed} +${item.addedLeafIds.length} -${item.removedLeafIds.length} invalidated:${item.invalidatedLeafIds.length}`,\n );\n }\n printWarnings(result.warnings.map((warning) => warning.message));\n });\n\nprogram\n .command(\"repair-state\")\n .argument(\"[sourceId]\", \"Optional skills group id\")\n .option(\"--all\", \"Rebuild source-side state for all registered skills groups\")\n .action(async (sourceId: string | undefined, options: { all?: boolean }) => {\n const ids = options.all || !sourceId ? undefined : [sourceId];\n const result = await app.repairState(ids);\n if (!result.ok) {\n printErrors(result.errors);\n process.exitCode = 1;\n return;\n }\n console.log(\n `repaired sources:${result.data.repairedSourceIds.length} removed deployments:${result.data.removedDeploymentCount}`,\n );\n printWarnings(result.warnings.map((warning) => warning.message));\n });\n\nprogram\n .command(\"update\")\n .argument(\"[sourceId]\", \"Optional skills group id\")\n .option(\"--all\", \"Update all registered skills groups\")\n .action(async (sourceId: string | undefined, options: { all?: boolean }) => {\n const ids = options.all || !sourceId ? undefined : [sourceId];\n const result = await app.updateSources(ids);\n if (!result.ok) {\n printErrors(result.errors);\n process.exitCode = 1;\n return;\n }\n const summariesResult = await app.listWorkflows();\n const summaries = summariesResult.ok ? summariesResult.data.summaries : [];\n for (const item of result.data.updated) {\n const summary = summaries.find((summary) => summary.source.id === item.sourceId);\n const groupRef = summary ? formatGroupRef(summary.source) : item.sourceId;\n console.log(\n `${groupRef} changed:${item.changed} +${item.addedLeafIds.length} -${item.removedLeafIds.length} invalidated:${item.invalidatedLeafIds.length}`,\n );\n }\n printWarnings(result.warnings.map((warning) => warning.message));\n });\n\nprogram\n .command(\"repair-targets\")\n .argument(\"[sourceId]\", \"Optional skills group id\")\n .option(\"--all\", \"Repair targets for all registered skills groups\")\n .action(async (sourceId: string | undefined, options: { all?: boolean }) => {\n const ids = options.all || !sourceId ? undefined : [sourceId];\n const result = await app.repairTargets(ids);\n if (!result.ok) {\n printErrors(result.errors);\n process.exitCode = 1;\n return;\n }\n console.log(formatActionSummary(result.data.actions));\n printWarnings(result.warnings.map((warning) => warning.message));\n });\n\nprogram.command(\"doctor\").action(async () => {\n const result = await app.doctor();\n if (!result.ok) {\n printErrors(result.errors);\n process.exitCode = 1;\n return;\n }\n console.log(result.data.status);\n if (result.data.issues.length === 0) {\n console.log(\"No issues detected.\");\n return;\n }\n for (const issue of result.data.issues) {\n console.log(formatDoctorIssue(issue));\n }\n});\n\nprogram\n .command(\"uninstall\")\n .argument(\"<sourceIds...>\", \"Skills group ids to remove\")\n .action(async (sourceIds: string[]) => {\n const result = await app.uninstall(sourceIds);\n if (!result.ok) {\n printErrors(result.errors);\n process.exitCode = 1;\n return;\n }\n const removed = result.data.removedRefs.map((source) => formatGroupRef(source));\n console.log(`Removed: ${removed.join(\", \")}`);\n printWarnings(result.data.warnings);\n });\n\nprogram\n .command(\"bridge\")\n .description(\"Execute machine protocol requests for desktop/helper integrations\")\n .option(\"--json\", \"Require JSON request/response envelope\")\n .option(\"--request <json>\", \"Raw request JSON (falls back to stdin if omitted)\")\n .action(async (options: { json?: boolean; request?: string }) => {\n if (!options.json) {\n console.error(\"bridge requires --json\");\n process.exitCode = 2;\n return;\n }\n\n const requestInput = options.request ?? (await readStdin()).trim();\n if (!requestInput) {\n console.log(\n JSON.stringify(\n buildBridgeResponse({\n command: \"list\",\n ok: false,\n errors: [\n {\n code: \"BRIDGE_EMPTY_REQUEST\",\n message: \"Bridge request payload is empty.\",\n },\n ],\n }),\n ),\n );\n process.exitCode = 1;\n return;\n }\n\n let request: BridgeRequest;\n try {\n request = parseBridgeRequest(JSON.parse(requestInput));\n } catch (error) {\n console.log(\n JSON.stringify(\n buildBridgeResponse({\n command: \"list\",\n ok: false,\n errors: [\n {\n code: \"BRIDGE_REQUEST_INVALID\",\n message: error instanceof Error ? error.message : String(error),\n },\n ],\n }),\n ),\n );\n process.exitCode = 1;\n return;\n }\n\n const response = await executeBridgeRequest(app, request);\n console.log(JSON.stringify(response));\n if (!response.ok) {\n process.exitCode = 1;\n }\n });\n\nawait program.parseAsync(process.argv);\n\nfunction printErrors(errors: Array<{ message: string }>) {\n for (const error of errors) {\n console.error(error.message);\n }\n}\n\nfunction printWarnings(messages: string[]) {\n for (const message of messages) {\n console.warn(`warning: ${message}`);\n }\n}\n\nasync function runRenderedAddFlow(\n app: SkillFlowApp,\n request: {\n locator: string;\n path?: string;\n requestedSkills?: string[];\n requestedAgents?: string[];\n yes?: boolean;\n all?: boolean;\n },\n): Promise<AddFlowExitResult> {\n return new Promise<AddFlowExitResult>((resolve) => {\n const instance = render(\n <AddFlowApp\n app={app}\n request={request}\n onExit={(result) => {\n resolve(result);\n instance.unmount();\n }}\n />,\n );\n });\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction handleAddFlowResult(\n result: AddFlowExitResult,\n options?: { rendered?: boolean },\n) {\n if (result.status === \"applied\") {\n if (!options?.rendered) {\n console.log(result.message);\n }\n printWarnings(filterAddWarnings(result.warnings));\n return;\n }\n\n if (result.status === \"cancelled\") {\n console.log(result.message);\n return;\n }\n\n printErrors([{ message: result.message }]);\n printWarnings(filterAddWarnings(result.warnings ?? []));\n process.exitCode = 1;\n}\n\nfunction collectOption(value: string, previous: string[]) {\n return [...previous, value];\n}\n", "{\n \"name\": \"skill-flow\",\n \"version\": \"1.3.4\",\n \"description\": \"Workflow-first management for AI agent skills. Group, project, and sync skills across multiple agents with explicit state tracking.\",\n \"type\": \"module\",\n \"main\": \"dist/cli.js\",\n \"bin\": {\n \"skill-flow\": \"dist/cli.js\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"README.zh.md\",\n \"LICENSE\"\n ],\n \"scripts\": {\n \"build\": \"node ../../scripts/release/build-cli-package.mjs\",\n \"dev\": \"tsx src/cli.tsx\",\n \"prepack\": \"node ../../scripts/release/sync-cli-package-files.mjs prepare\",\n \"postpack\": \"node ../../scripts/release/sync-cli-package-files.mjs restore\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/VintLin/skill-flow.git\"\n },\n \"keywords\": [\n \"ai\",\n \"agent\",\n \"skills\",\n \"workflow\",\n \"claude\",\n \"cursor\",\n \"copilot\",\n \"cli\",\n \"management\",\n \"git\"\n ],\n \"author\": \"VintLin\",\n \"license\": \"Apache-2.0\",\n \"bugs\": {\n \"url\": \"https://github.com/VintLin/skill-flow/issues\"\n },\n \"homepage\": \"https://github.com/VintLin/skill-flow#readme\",\n \"engines\": {\n \"node\": \">=20\"\n },\n \"dependencies\": {\n \"@skill-flow/core-engine\": \"1.3.4\",\n \"@skill-flow/domain\": \"1.3.4\",\n \"@skill-flow/integration\": \"1.3.4\",\n \"@skill-flow/query\": \"1.3.4\",\n \"@skill-flow/shared-types\": \"1.3.4\",\n \"@skill-flow/storage\": \"1.3.4\",\n \"@skill-flow/tui\": \"1.3.4\",\n \"commander\": \"^14.0.3\",\n \"ink\": \"^6.8.0\",\n \"react\": \"^19.2.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^25.5.0\",\n \"@types/react\": \"^19.2.14\",\n \"esbuild\": \"^0.27.7\",\n \"tsx\": \"^4.21.0\",\n \"typescript\": \"^5.9.3\",\n \"vitest\": \"^4.1.0\"\n }\n}\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createChannelAdapters, type ChannelAdapter } from \"@skill-flow/integration/adapters/channel-adapters\";\nimport type {\n AddSourceDraftOptions,\n AddSourcePreparation,\n DeploymentTargetId,\n DraftBinding,\n DeploymentAction,\n DeploymentPlan,\n DeploymentTargetName,\n DoctorReport,\n ImportDraft,\n ImportDataCache,\n ImportGroupCandidate,\n ImportRecommendationFeed,\n ImportRecommendationFeedId,\n ImportSearchHit,\n ImportSearchSnapshot,\n ImportPreviewResult,\n ImportReasonCode,\n ImportSourceResult,\n LeafRecord,\n LockFile,\n Manifest,\n ProjectScope,\n ProjectionRecord,\n RecentProject,\n Result,\n SharedPreferences,\n SkillCandidate,\n SourceMetadataResult,\n SourceStats,\n SourceBinding,\n SourceUpdateResult,\n SourceUpdateResultItem,\n TargetBinding,\n UnifiedSourceSnapshot,\n UnifiedSourceTrust,\n Warning,\n WorkflowSummary,\n} from \"@skill-flow/domain/types\";\nimport { getBootstrapImportedTargets, getManagedDeployments } from \"@skill-flow/domain/projection-compat\";\nimport { StateStore } from \"@skill-flow/storage/store\";\nimport {\n isImportDataCacheExpired,\n} from \"@skill-flow/storage/import-data-cache\";\nimport {\n isSourceMetadataCacheExpired,\n sourceMetadataCacheEntryToResult,\n sourceMetadataResultToCacheEntry,\n} from \"@skill-flow/storage/source-metadata-cache\";\nimport {\n ensureDir,\n hashDirectory,\n isPathInside,\n pathExists,\n readJsonFile,\n removePath,\n writeJsonFile,\n} from \"@skill-flow/integration/utils/fs\";\nimport { getBuiltinGitSources } from \"@skill-flow/integration/utils/builtin-git-sources\";\nimport { fetchGitHubSkillPaths } from \"@skill-flow/integration/utils/github-catalog\";\nimport {\n buildProjectedSkillNameCandidates,\n getHostedGitOwner,\n parseGitHubRepo,\n parseHostedGitRepo,\n resolveProjectedSkillNames,\n} from \"@skill-flow/integration/utils/naming\";\nimport {\n getMergedTargetDefinitions,\n resolveDocumentedProjectSkillPath,\n} from \"@skill-flow/integration/utils/constants\";\nimport { fail, ok } from \"@skill-flow/integration/utils/result\";\nimport { searchClawHubSkills } from \"@skill-flow/integration/utils/clawhub\";\nimport { deriveDisplayName, deriveSourceId } from \"@skill-flow/integration/utils/source-id\";\nimport { fetchSourceDetails } from \"@skill-flow/integration/utils/source-details\";\nimport {\n buildFailedSourceMetadataResult,\n buildSourceMetadataResult,\n fetchFreshSourceMetadata,\n fetchSkillsDirectorySourceDetails,\n inferSourceMetadataProvider,\n SOURCE_METADATA_CACHE_TTL_MS,\n} from \"@skill-flow/integration/utils/source-details\";\nimport {\n buildImportGroupCandidate,\n fetchSkillsDirectoryFeedGroups,\n fetchSkillsDirectorySourcePreview,\n fetchSkillsDirectorySourceSnapshot,\n groupSkillsDirectorySearchHits,\n IMPORT_RECOMMENDATION_CACHE_TTL_MS,\n IMPORT_SEARCH_CACHE_TTL_MS,\n IMPORT_SOURCE_CACHE_TTL_MS,\n normalizeImportCanonicalRepo,\n searchSkillsDirectory,\n} from \"@skill-flow/integration/utils/skills-directory\";\nimport { DeploymentApplier } from \"@skill-flow/core-engine/services/deployment-applier\";\nimport { ConfigCoordinator } from \"./config-coordinator.js\";\nimport { DeploymentPlanner } from \"@skill-flow/core-engine/services/deployment-planner\";\nimport { DoctorService } from \"@skill-flow/core-engine/services/doctor-service\";\nimport { InventoryService } from \"@skill-flow/core-engine/services/inventory-service\";\nimport { RecentProjectService } from \"@skill-flow/core-engine/services/recent-project-service\";\nimport { SourceService } from \"@skill-flow/core-engine/services/source-service\";\nimport { WorkflowService } from \"./workflow-service.js\";\nimport type {\n AddSourceOptions,\n SourcePreview,\n SourceSnapshot,\n} from \"@skill-flow/core-engine/services/source-service\";\nimport {\n WorkspaceBootstrapService,\n type BootstrapEvent,\n} from \"@skill-flow/core-engine/services/workspace-bootstrap-service\";\n\nconst EMPTY_DRAFT: DraftBinding = { enabledTargets: [], selectedLeafIds: [] };\n\ntype SkillFlowAddOptions = AddSourceOptions &\n AddSourceDraftOptions & {\n project?: boolean;\n };\n\ntype AddSourceResult = SourceSnapshot & AddSourcePreparation & { projected: boolean };\ntype TargetRootOverrides = Partial<Record<DeploymentTargetId, string>>;\ntype ApplyDraftResult = {\n actions: DeploymentAction[];\n draft: DraftBinding;\n summary?: WorkflowSummary;\n inspect?: {\n summary: WorkflowSummary;\n source: Manifest[\"sources\"][number];\n binding: SourceBinding;\n leafs: LeafRecord[];\n deployments: LockFile[\"deployments\"];\n };\n recentProjects?: RecentProject[];\n selectedProjectScope?: ProjectScope;\n projectDrafts?: SharedPreferences[\"projectDrafts\"];\n};\ntype GroupCardEnrichmentSnapshot = {\n sourceMetadata?: SourceMetadataResult;\n sourceSnapshot?: UnifiedSourceSnapshot;\n groupPath?: string;\n};\ntype AuditMutationName =\n | \"add-source\"\n | \"bootstrap\"\n | \"import-source\"\n | \"apply-draft\"\n | \"update-sources\"\n | \"doctor\"\n | \"uninstall\";\ntype AuditEvent = {\n timestamp: string;\n mutation: AuditMutationName;\n caller: string;\n status: \"ok\" | \"error\" | \"threw\";\n details: Record<string, unknown>;\n warnings: Array<{ code: string; message: string }>;\n errors: Array<{ code: string; message: string }>;\n};\ntype AuditedMutationResult<T> =\n | Result<T>\n | {\n result: Result<T>;\n auditDetails?: Record<string, unknown>;\n };\n\nasync function resolveUsableProjectPath(projectPath: string | undefined): Promise<string | null> {\n const trimmedPath = projectPath?.trim();\n if (!trimmedPath) {\n return null;\n }\n\n try {\n const resolvedPath = await fs.realpath(trimmedPath);\n const stat = await fs.stat(resolvedPath);\n return stat.isDirectory() ? resolvedPath : null;\n } catch {\n return null;\n }\n}\n\nexport class SkillFlowApp {\n private static readonly importGroupResolveConcurrency = 3;\n\n readonly store: StateStore;\n adapters: ChannelAdapter[];\n readonly inventoryService: InventoryService;\n readonly sourceService: SourceService;\n planner: DeploymentPlanner;\n applier: DeploymentApplier;\n readonly doctorService: DoctorService;\n readonly workflowService: WorkflowService;\n readonly recentProjectService: RecentProjectService;\n readonly workspaceBootstrapService: WorkspaceBootstrapService;\n readonly configCoordinator: ConfigCoordinator;\n private mutationQueue: Promise<void> = Promise.resolve();\n private metadataRefreshesBySourceId = new Map<string, Promise<void>>();\n private importSearchRefreshesByQuery = new Map<string, Promise<ImportSearchSnapshot>>();\n private importSourceRefreshesByKey = new Map<string, Promise<UnifiedSourceSnapshot>>();\n private importRecommendationRefreshesByFeed = new Map<ImportRecommendationFeedId, Promise<ImportRecommendationFeed>>();\n\n constructor() {\n this.store = new StateStore();\n const adapters = createChannelAdapters();\n this.adapters = adapters;\n this.inventoryService = new InventoryService();\n this.sourceService = new SourceService(this.store, this.inventoryService);\n this.planner = new DeploymentPlanner(adapters);\n this.applier = new DeploymentApplier(adapters);\n this.doctorService = new DoctorService(this.store);\n this.workflowService = new WorkflowService();\n this.recentProjectService = new RecentProjectService();\n this.workspaceBootstrapService = new WorkspaceBootstrapService(this.store);\n this.configCoordinator = new ConfigCoordinator({\n store: this.store,\n recentProjectService: this.recentProjectService,\n doctorService: this.doctorService,\n workflowService: this.workflowService,\n getAvailableTargets: () => this.getAvailableTargets(),\n pruneMissingCheckouts: () => this.pruneMissingCheckoutsImpl(),\n getConfigData: () => this.getConfigDataImpl(),\n });\n }\n\n private async refreshAdapters(): Promise<ChannelAdapter[]> {\n const preferences = await this.store.readPreferences();\n const targetDefinitions = getMergedTargetDefinitions(\n preferences.customTargets,\n preferences.agentDisplayOrder,\n );\n this.adapters = createChannelAdapters(targetDefinitions);\n this.planner = new DeploymentPlanner(this.adapters);\n this.applier = new DeploymentApplier(this.adapters);\n return this.adapters;\n }\n\n async addSource(\n locator: string,\n options?: SkillFlowAddOptions,\n ): Promise<Result<AddSourceResult>> {\n return this.runAuditedMutation(\n \"add-source\",\n {\n locator,\n project: options?.project !== false,\n requestedPath: options?.path,\n enabledTargets: options?.enabledTargets ?? [],\n sourceIdOverride: options?.sourceIdOverride,\n },\n () => this.addSourceImpl(locator, options),\n );\n }\n\n async prepareAddSource(\n locator: string,\n options?: SkillFlowAddOptions,\n ): Promise<Result<AddSourceResult>> {\n return this.runSerializedMutation(() => this.prepareAddSourceImpl(locator, options));\n }\n\n private async addSourceImpl(\n locator: string,\n options?: SkillFlowAddOptions,\n ): Promise<Result<AddSourceResult>> {\n const prepared = await this.prepareAddSourceImpl(locator, options);\n if (!prepared.ok) {\n return prepared;\n }\n\n const addOptions = options ?? {};\n if (addOptions.project === false) {\n return prepared;\n }\n\n const applied = await this.applyDraftImpl(\n prepared.data.sourceId,\n addOptions.draft ?? prepared.data.draft,\n { kind: \"global\" },\n );\n if (!applied.ok) {\n return fail(applied.errors, [...prepared.warnings, ...applied.warnings]);\n }\n\n return ok(\n {\n ...prepared.data,\n draft: applied.data.draft,\n projected: true,\n },\n [...prepared.warnings, ...applied.warnings],\n );\n }\n\n private async prepareAddSourceImpl(\n locator: string,\n options?: SkillFlowAddOptions,\n ): Promise<Result<AddSourceResult>> {\n const addOptions = options ?? {};\n const result = await this.sourceService.addSource(locator, addOptions);\n if (!result.ok) {\n return fail(result.errors, result.warnings);\n }\n\n const { manifest, lockFile } = await this.store.readState();\n await this.ensureProjectionLedger(manifest, lockFile);\n const source = manifest.sources.find((item) => item.id === result.data.manifest.id);\n if (!source) {\n return fail({\n code: \"SOURCE_NOT_FOUND\",\n message: `Skills group id '${result.data.manifest.id}' is not registered.`,\n });\n }\n\n const requestedPath = this.normalizeRequestedPath(source.requestedPath);\n if (requestedPath) {\n source.requestedPath = requestedPath;\n result.data.manifest.requestedPath = requestedPath;\n } else {\n delete source.requestedPath;\n delete result.data.manifest.requestedPath;\n }\n\n const sourceLeafs = lockFile.leafInventory.filter((leaf) => leaf.sourceId === source.id);\n const availableTargets = addOptions.skipTargetDetection\n ? []\n : await this.getAvailableTargets();\n const preparedDraft = this.buildAddDraft(\n sourceLeafs,\n requestedPath,\n availableTargets,\n addOptions,\n );\n if (!preparedDraft.ok) {\n await this.rollbackPreparedSourceInternal(source.id);\n return fail(preparedDraft.errors, [...result.warnings, ...preparedDraft.warnings]);\n }\n\n source.selectionMode =\n addOptions.selectionMode ??\n (preparedDraft.data.selectedLeafIds.length >= sourceLeafs.length && sourceLeafs.length > 0\n ? \"all\"\n : \"partial\");\n result.data.manifest.selectionMode = source.selectionMode;\n manifest.bindings[source.id] = { targets: {} };\n await this.ensureProjectionLedger(manifest, lockFile);\n await this.store.writeState(manifest, lockFile);\n\n const warnings = [...result.warnings];\n if (\n requestedPath &&\n !addOptions.skillNames?.length &&\n !addOptions.draft &&\n preparedDraft.data.selectedLeafIds.length < sourceLeafs.length\n ) {\n warnings.push({\n code: \"ADD_SELECTION_PRESELECTED\",\n message:\n `Preselected ${preparedDraft.data.selectedLeafIds.length} of ${sourceLeafs.length} ` +\n `skill${sourceLeafs.length === 1 ? \"\" : \"s\"} under '${requestedPath}'; ` +\n \"the full skills group was imported.\",\n });\n }\n\n return ok(\n {\n ...result.data,\n sourceId: source.id,\n availableTargets,\n draft: preparedDraft.data,\n leafs: sourceLeafs,\n projected: false,\n },\n warnings,\n );\n }\n\n async rollbackPreparedSource(sourceId: string): Promise<Result<{ removed: string[] }>> {\n return this.runSerializedMutation(() => this.rollbackPreparedSourceInternal(sourceId));\n }\n\n async findSkills(query: string): Promise<Result<{ candidates: SkillCandidate[] }>> {\n const { manifest, lockFile } = await this.readStateConsistently();\n const normalizedQuery = this.normalizeSearchQuery(query);\n const warnings: Warning[] = [];\n const localKeys = new Set<string>();\n const candidates: SkillCandidate[] = [];\n let remoteSearchSucceeded = false;\n\n for (const candidate of this.buildLocalCandidates(normalizedQuery, manifest, lockFile)) {\n candidates.push(candidate);\n localKeys.add(this.getCandidateKey(candidate));\n }\n\n const builtinResults = await Promise.all(\n getBuiltinGitSources().map(async (builtin) => {\n try {\n const sourceId = deriveSourceId(builtin.locator);\n const displayName = deriveDisplayName(builtin.locator);\n const search = await this.searchBuiltinGitSource(\n builtin.locator,\n builtin.branch,\n sourceId,\n displayName,\n normalizedQuery,\n );\n return {\n ok: true as const,\n candidates: search.candidates,\n warnings: search.warnings,\n };\n } catch (error) {\n return {\n ok: false as const,\n warning: {\n code: \"BUILTIN_SOURCE_UNAVAILABLE\",\n message: `Unable to refresh built-in source '${builtin.locator}': ${String(error)}`,\n },\n };\n }\n }),\n );\n\n for (const result of builtinResults) {\n if (!result.ok) {\n warnings.push(result.warning);\n continue;\n }\n warnings.push(...result.warnings);\n remoteSearchSucceeded = true;\n for (const candidate of result.candidates) {\n if (localKeys.has(this.getCandidateKey(candidate))) {\n continue;\n }\n candidates.push(candidate);\n }\n }\n\n try {\n const results = await searchClawHubSkills(normalizedQuery, 8);\n remoteSearchSucceeded = true;\n for (const result of results) {\n candidates.push({\n id: `clawhub:${result.slug}`,\n title: result.title,\n description: result.title,\n source: \"clawhub\",\n sourceLabel: \"ClawHub\",\n sourceId: deriveSourceId(`clawhub:${result.slug}`),\n sourceKind: \"clawhub\",\n locator: `clawhub:${result.slug}`,\n installed: manifest.sources.some((source) => source.id === deriveSourceId(`clawhub:${result.slug}`)),\n action: {\n type: \"add-clawhub\",\n slug: result.slug,\n },\n });\n }\n } catch (error) {\n warnings.push({\n code: \"CLAWHUB_SEARCH_FAILED\",\n message: `Unable to search ClawHub: ${String(error)}`,\n });\n }\n\n if (candidates.length === 0 && !remoteSearchSucceeded) {\n return fail(\n {\n code: \"FIND_UNAVAILABLE\",\n message: \"Unable to search built-in sources or ClawHub.\",\n },\n warnings,\n );\n }\n\n candidates.sort((left, right) => this.compareCandidates(left, right, normalizedQuery));\n\n return ok({ candidates }, warnings);\n }\n\n async listRecommendedImportGroups(): Promise<Result<{ groups: ImportGroupCandidate[] }>> {\n return this.listRecommendedImportGroupsImpl();\n }\n\n async searchImportGroups(\n query: string,\n ): Promise<Result<{ groups: ImportGroupCandidate[]; exact: boolean }>> {\n return this.searchImportGroupsImpl(query);\n }\n\n async previewImportSource(locator: string): Promise<Result<ImportPreviewResult>> {\n return this.previewImportSourceImpl(locator);\n }\n\n async importSource(\n locator: string,\n draft?: ImportDraft,\n ): Promise<Result<ImportSourceResult>> {\n return this.runAuditedMutation(\n \"import-source\",\n {\n locator,\n selectedSkillIds: draft?.selectedSkillIds ?? [],\n enabledTargets: draft?.enabledTargets ?? [],\n },\n () => this.importSourceImpl(locator, draft),\n );\n }\n\n async listWorkflows(): Promise<\n Result<{\n summaries: WorkflowSummary[];\n pinnedSourceIds: string[];\n recentProjects: RecentProject[];\n selectedProjectScope: ProjectScope;\n customTargets: SharedPreferences[\"customTargets\"];\n agentDisplayOrder: SharedPreferences[\"agentDisplayOrder\"];\n groupCardEnrichmentBySourceId: Record<string, GroupCardEnrichmentSnapshot>;\n }>\n > {\n return this.runSerializedMutation(() => this.listWorkflowsImpl());\n }\n\n async saveSettings(input: {\n customTargets: SharedPreferences[\"customTargets\"];\n agentDisplayOrder: SharedPreferences[\"agentDisplayOrder\"];\n }): Promise<Result<{\n customTargets: SharedPreferences[\"customTargets\"];\n agentDisplayOrder: SharedPreferences[\"agentDisplayOrder\"];\n }>> {\n return this.runSerializedMutation(async () => {\n const preferences = await this.store.readPreferences();\n await this.store.writePreferences({\n ...preferences,\n customTargets: input.customTargets,\n agentDisplayOrder: input.agentDisplayOrder,\n });\n const saved = await this.store.readPreferences();\n await this.refreshAdapters();\n return ok({\n customTargets: saved.customTargets,\n agentDisplayOrder: saved.agentDisplayOrder,\n });\n });\n }\n\n async inspectSource(\n sourceId: string,\n scope: ProjectScope = { kind: \"global\" },\n ): Promise<\n Result<{\n summary: WorkflowSummary;\n source: Manifest[\"sources\"][number];\n binding: SourceBinding;\n leafs: LeafRecord[];\n deployments: LockFile[\"deployments\"];\n }>\n > {\n return this.runSerializedMutation(() => this.inspectSourceImpl(sourceId, scope));\n }\n\n async inspectSourceEnrichment(\n sourceId: string,\n ): Promise<\n Result<{\n sourceMetadata: SourceMetadataResult;\n sourceSnapshot?: UnifiedSourceSnapshot;\n }>\n > {\n return this.inspectSourceEnrichmentImpl(sourceId);\n }\n\n private async inspectSourceImpl(\n sourceId: string,\n scope: ProjectScope,\n ): Promise<\n Result<{\n summary: WorkflowSummary;\n source: Manifest[\"sources\"][number];\n binding: SourceBinding;\n leafs: LeafRecord[];\n deployments: LockFile[\"deployments\"];\n }>\n > {\n const { manifest, lockFile } = await this.store.readState();\n this.normalizeBindings(manifest, lockFile);\n const source = manifest.sources.find((item) => item.id === sourceId);\n if (!source) {\n return fail({\n code: \"SOURCE_NOT_FOUND\",\n message: `Skills group id '${sourceId}' is not registered.`,\n });\n }\n\n const summary = this.workflowService.getSummaries(manifest, lockFile).find((item) => item.source.id === sourceId);\n if (!summary) {\n return fail({\n code: \"SOURCE_NOT_FOUND\",\n message: `Unable to inspect '${sourceId}' because no summary data was found.`,\n });\n }\n\n const binding = manifest.bindings[sourceId] ?? { selectedLeafIds: [], targets: {} };\n const leafs = lockFile.leafInventory.filter((leaf) => leaf.sourceId === sourceId);\n const deployments = getManagedDeployments(lockFile).filter(\n (deployment) => deployment.sourceId === sourceId,\n );\n\n if (scope.kind === \"global\") {\n return ok({ summary, source, binding, leafs, deployments });\n }\n\n const initialDrafts: Record<string, DraftBinding> = {\n [sourceId]: this.draftFromBinding(sourceId, binding, lockFile),\n };\n const preferences = await this.store.readPreferences();\n const scopedDraft = this.resolveDraftForScope(sourceId, initialDrafts, preferences, scope);\n\n const scopedManifest = this.cloneManifest(manifest);\n this.normalizeBindings(scopedManifest, lockFile);\n const prepared = this.prepareManifestForDraft(scopedManifest, lockFile, sourceId, scopedDraft);\n const scopedSource = prepared.manifest.sources.find((item) => item.id === sourceId) ?? source;\n const scopedSummary =\n this.workflowService.getSummaries(prepared.manifest, lockFile).find((item) => item.source.id === sourceId)\n ?? summary;\n const scopedBinding = prepared.manifest.bindings[sourceId] ?? binding;\n const scopedDeployments = scopedDraft.enabledTargets.length === 0\n ? []\n : await this.resolveScopedInspectDeployments(\n prepared.manifest,\n lockFile,\n sourceId,\n scope,\n scopedDraft.enabledTargets,\n );\n\n return ok({\n summary: scopedSummary,\n source: scopedSource,\n binding: scopedBinding,\n leafs,\n deployments: scopedDeployments,\n });\n }\n\n private async inspectSourceEnrichmentImpl(\n sourceId: string,\n ): Promise<\n Result<{\n sourceMetadata: SourceMetadataResult;\n sourceSnapshot?: UnifiedSourceSnapshot;\n }>\n > {\n const localInspect = await this.inspectSource(sourceId);\n if (!localInspect.ok) {\n return fail(localInspect.errors, localInspect.warnings);\n }\n\n const { source, summary, leafs } = localInspect.data;\n const canonicalRepo = normalizeImportCanonicalRepo(source.locator)\n ?? (source.originLocator ? normalizeImportCanonicalRepo(source.originLocator) : undefined);\n const [sourceMetadata, sourceSnapshot] = await Promise.all([\n this.resolveSourceMetadata(source, summary.lock),\n canonicalRepo\n ? this.resolveImportSourceSnapshot(canonicalRepo, {\n enrichSkillIds: leafs.map((leaf) => leaf.linkName),\n }).catch(() => undefined)\n : Promise.resolve(undefined),\n ]);\n\n return ok({ sourceMetadata, ...(sourceSnapshot ? { sourceSnapshot } : {}) });\n }\n\n private async listRecommendedImportGroupsImpl(): Promise<Result<{ groups: ImportGroupCandidate[] }>> {\n const manifest = await this.readManifestConsistently();\n const installedRepos = this.installedCanonicalRepos(manifest);\n const recommendedRepos = await this.resolveRecommendedImportRepos();\n const importCache = await this.store.readImportDataCache();\n const groups = recommendedRepos\n .slice(0, 8)\n .map((canonicalRepo) =>\n this.buildImmediateImportGroupCandidate(importCache, canonicalRepo, {\n installed: installedRepos.has(canonicalRepo),\n }),\n );\n\n return ok({ groups });\n }\n\n private async searchImportGroupsImpl(\n query: string,\n ): Promise<Result<{ groups: ImportGroupCandidate[]; exact: boolean }>> {\n try {\n const normalizedQuery = query.trim();\n if (!normalizedQuery) {\n const recommended = await this.listRecommendedImportGroupsImpl();\n if (!recommended.ok) {\n return fail(recommended.errors, recommended.warnings);\n }\n return ok({ groups: recommended.data.groups, exact: false }, recommended.warnings);\n }\n\n const manifest = await this.readManifestConsistently();\n const installedRepos = this.installedCanonicalRepos(manifest);\n const importCache = await this.store.readImportDataCache();\n const directCandidate = await this.buildDirectImportGroupCandidate(\n normalizedQuery,\n manifest,\n );\n if (directCandidate) {\n return ok({\n groups: [directCandidate],\n exact: true,\n });\n }\n const exactRepo = normalizeImportCanonicalRepo(normalizedQuery);\n if (exactRepo) {\n try {\n const details = await fetchSkillsDirectorySourceDetails(exactRepo);\n return ok({\n groups: [\n {\n id: exactRepo,\n provider: \"skills\",\n locator: exactRepo,\n canonicalRepo: exactRepo,\n aliases: [exactRepo, `https://github.com/${exactRepo}`, `https://github.com/${exactRepo}.git`, `git@github.com:${exactRepo}.git`],\n title: details.repoLabel?.split(\"/\")[1] ?? exactRepo.split(\"/\")[1] ?? exactRepo,\n installed: installedRepos.has(exactRepo),\n ...(details.description ? { summary: details.description } : {}),\n ...(details.sourceUrl ? { sourceUrl: details.sourceUrl } : {}),\n ...(details.repoUrl ? { repoUrl: details.repoUrl } : {}),\n ...(details.starCount !== undefined ? { starCount: details.starCount } : {}),\n ...(details.totalInstalls !== undefined ? { totalInstalls: details.totalInstalls } : {}),\n enrichState: { status: \"ready\" as const },\n previewState: { status: \"idle\" as const },\n },\n ],\n exact: true,\n });\n } catch {\n const exactCandidate = this.buildImmediateImportGroupCandidate(importCache, exactRepo, {\n installed: installedRepos.has(exactRepo),\n });\n\n if (\n exactCandidate.enrichState.status === \"ready\" ||\n exactCandidate.enrichState.status === \"loading\" ||\n exactCandidate.enrichState.status === \"failed\" &&\n exactCandidate.enrichState.reasonCode !== \"provider_data_unavailable\"\n ) {\n return ok({ groups: [exactCandidate], exact: true });\n }\n }\n }\n\n const searchSnapshot = await this.resolveImportSearchSnapshot(normalizedQuery);\n const grouped = groupSkillsDirectorySearchHits(searchSnapshot.hits).slice(0, 8);\n const groups = grouped.map((group) =>\n this.buildImmediateImportGroupCandidate(importCache, group.canonicalRepo, {\n installed: installedRepos.has(group.canonicalRepo),\n matchedSkills: group.matchedSkills,\n }),\n );\n\n return ok({\n groups,\n exact: false,\n });\n } catch (error) {\n return fail({\n code: \"IMPORT_SEARCH_FAILED\",\n message: `Unable to search import groups: ${String(error)}`,\n });\n }\n }\n\n private async previewImportSourceImpl(locator: string): Promise<Result<ImportPreviewResult>> {\n const canonicalRepo = normalizeImportCanonicalRepo(locator);\n if (!canonicalRepo) {\n const localPreview = await this.previewDirectImportSource(locator);\n if (localPreview) {\n return localPreview;\n }\n\n return ok({\n status: \"failed\",\n reasonCode: \"provider_not_supported\",\n retryable: false,\n });\n }\n\n try {\n const snapshot = await this.resolveImportPreviewSnapshot(canonicalRepo);\n const availableTargets = await this.getAvailableTargets();\n return ok({\n status: \"ready\",\n locator: canonicalRepo,\n canonicalRepo,\n snapshot,\n selectedSkillIds: snapshot.skills.map((skill) => skill.skillId),\n enabledTargets: [],\n skills: snapshot.skills.map((skill) => ({\n id: skill.skillId,\n title: skill.title,\n summary: skill.summary ?? \"\",\n selectedByDefault: true,\n })),\n targets: availableTargets.map((target) => ({\n id: target,\n selectedByDefault: false,\n })),\n });\n } catch (error) {\n return ok({\n status: \"failed\",\n reasonCode: this.inferImportReasonCode(error),\n retryable: this.importFailureRetryable(error),\n });\n }\n }\n\n private async importSourceImpl(\n locator: string,\n draft?: ImportDraft,\n ): Promise<Result<ImportSourceResult>> {\n const normalizedLocator = normalizeImportCanonicalRepo(locator) ?? locator.trim();\n const prepared = await this.prepareAddSourceImpl(normalizedLocator, { project: false });\n if (!prepared.ok) {\n return ok({\n status: \"failed\",\n reasonCode: prepared.errors[0]?.code ?? \"IMPORT_PREPARE_FAILED\",\n retryable: true,\n });\n }\n\n const finalDraft = this.resolveImportDraftForPreparedSource(\n prepared.data.leafs,\n prepared.data.availableTargets,\n normalizeImportCanonicalRepo(normalizedLocator),\n draft,\n );\n if (!finalDraft.ok) {\n await this.rollbackPreparedSourceInternal(prepared.data.sourceId);\n return ok({\n status: \"failed\",\n reasonCode: finalDraft.errors[0]?.code ?? \"IMPORT_PREVIEW_INVALID\",\n retryable: true,\n });\n }\n\n const applied = await this.applyDraftImpl(prepared.data.sourceId, finalDraft.data, { kind: \"global\" });\n if (!applied.ok) {\n await this.rollbackPreparedSourceInternal(prepared.data.sourceId);\n return ok({\n status: \"failed\",\n reasonCode: applied.errors[0]?.code ?? \"IMPORT_APPLY_FAILED\",\n retryable: true,\n }, [...finalDraft.warnings, ...applied.warnings]);\n }\n\n return ok({\n status: \"ready\",\n sourceId: prepared.data.sourceId,\n canonicalRepo: normalizeImportCanonicalRepo(normalizedLocator) ?? normalizedLocator,\n }, [...finalDraft.warnings, ...applied.warnings]);\n }\n\n private async resolveSourceMetadata(\n source: Manifest[\"sources\"][number],\n lock: WorkflowSummary[\"lock\"],\n ): Promise<SourceMetadataResult> {\n const cachedEntry = (await this.store.readSourceMetadataCache())[source.id];\n if (cachedEntry) {\n if (!isSourceMetadataCacheExpired(cachedEntry)) {\n return sourceMetadataCacheEntryToResult(cachedEntry);\n }\n\n this.refreshSourceMetadataInBackground(source, lock, cachedEntry.provider);\n return sourceMetadataCacheEntryToResult(cachedEntry);\n }\n\n return this.refreshSourceMetadata(source, lock, inferSourceMetadataProvider(source));\n }\n\n private refreshSourceMetadataInBackground(\n source: Manifest[\"sources\"][number],\n lock: WorkflowSummary[\"lock\"],\n providerHint?: SourceMetadataResult[\"provider\"],\n ): void {\n if (this.metadataRefreshesBySourceId.has(source.id)) {\n return;\n }\n\n const refresh = this.refreshSourceMetadata(source, lock, providerHint)\n .then(() => undefined)\n .catch(() => undefined)\n .finally(() => {\n this.metadataRefreshesBySourceId.delete(source.id);\n });\n\n this.metadataRefreshesBySourceId.set(source.id, refresh);\n }\n\n private async refreshSourceMetadata(\n source: Manifest[\"sources\"][number],\n lock: WorkflowSummary[\"lock\"],\n providerHint?: SourceMetadataResult[\"provider\"],\n ): Promise<SourceMetadataResult> {\n try {\n const sourceMetadata = await fetchFreshSourceMetadata(source, lock, providerHint);\n await this.store.writeSourceMetadataEntry(\n sourceMetadataResultToCacheEntry({\n sourceId: source.id,\n result: sourceMetadata,\n checkedAt: new Date().toISOString(),\n expiresAt: new Date(Date.now() + SOURCE_METADATA_CACHE_TTL_MS).toISOString(),\n }),\n );\n return sourceMetadata;\n } catch (error) {\n const failedMetadata = buildFailedSourceMetadataResult(providerHint, error);\n await this.store.writeSourceMetadataEntry(\n sourceMetadataResultToCacheEntry({\n sourceId: source.id,\n result: failedMetadata,\n checkedAt: new Date().toISOString(),\n expiresAt: new Date(Date.now() + SOURCE_METADATA_CACHE_TTL_MS).toISOString(),\n }),\n );\n return failedMetadata;\n }\n }\n\n private importRecommendationSeedRepos(): string[] {\n return [\n \"anthropics/skills\",\n \"garrytan/gstack\",\n \"vercel-labs/agent-skills\",\n ];\n }\n\n private installedCanonicalRepos(manifest: Manifest): Set<string> {\n return new Set(\n manifest.sources.flatMap((source) => {\n const canonicalRepo = normalizeImportCanonicalRepo(source.locator)\n ?? (source.originLocator ? normalizeImportCanonicalRepo(source.originLocator) : undefined);\n return canonicalRepo ? [canonicalRepo] : [];\n }),\n );\n }\n\n private buildImmediateImportGroupCandidate(\n importCache: ImportDataCache,\n canonicalRepo: string,\n options: {\n installed: boolean;\n matchedSkills?: Array<{\n skillId: string;\n title: string;\n installs?: number;\n }>;\n },\n ): ImportGroupCandidate {\n const normalizedRepo = normalizeImportCanonicalRepo(canonicalRepo) ?? canonicalRepo;\n const cachedRepo = importCache.repos?.[normalizedRepo];\n const cachedSnapshot = cachedRepo?.providers.skills?.snapshot;\n\n if (cachedSnapshot) {\n return buildImportGroupCandidate({\n canonicalRepo: normalizedRepo,\n installed: options.installed,\n snapshot: cachedSnapshot,\n ...(options.matchedSkills ? { matchedSkills: options.matchedSkills } : {}),\n });\n }\n\n if (cachedRepo) {\n return {\n id: normalizedRepo,\n provider: \"skills\",\n locator: normalizedRepo,\n canonicalRepo: normalizedRepo,\n aliases: cachedRepo.identity.aliases,\n title: cachedRepo.resolved.title ?? normalizedRepo.split(\"/\")[1] ?? normalizedRepo,\n installed: options.installed,\n ...(cachedRepo.resolved.summary ? { summary: cachedRepo.resolved.summary } : {}),\n ...(cachedRepo.resolved.sourceUrl ? { sourceUrl: cachedRepo.resolved.sourceUrl } : {}),\n ...(cachedRepo.resolved.githubUrl ? { repoUrl: cachedRepo.resolved.githubUrl } : {}),\n ...(cachedRepo.resolved.starCount !== undefined ? { starCount: cachedRepo.resolved.starCount } : {}),\n ...(cachedRepo.resolved.downloadCount !== undefined ? { totalInstalls: cachedRepo.resolved.downloadCount } : {}),\n ...(cachedRepo.resolved.skillCount !== undefined ? { skillCount: cachedRepo.resolved.skillCount } : {}),\n ...(options.matchedSkills?.length ? { matchedSkillNames: options.matchedSkills.map((skill) => skill.title) } : {}),\n ...(options.matchedSkills?.length ? { matchedSkills: options.matchedSkills } : {}),\n enrichState: { status: \"ready\" },\n previewState: { status: \"idle\" },\n };\n }\n\n return {\n id: normalizedRepo,\n provider: \"skills\",\n locator: normalizedRepo,\n canonicalRepo: normalizedRepo,\n aliases: buildImportGroupCandidate({\n canonicalRepo: normalizedRepo,\n installed: options.installed,\n }).aliases,\n title: normalizedRepo.split(\"/\")[1] ?? normalizedRepo,\n installed: options.installed,\n ...(options.matchedSkills?.length ? { matchedSkillNames: options.matchedSkills.map((skill) => skill.title) } : {}),\n ...(options.matchedSkills?.length ? { matchedSkills: options.matchedSkills } : {}),\n enrichState: { status: \"loading\" },\n previewState: { status: \"idle\" },\n };\n }\n\n private async buildDirectImportGroupCandidate(\n locator: string,\n manifest: Manifest,\n ): Promise<ImportGroupCandidate | null> {\n const resolvedLocator = await this.resolveDirectImportLocator(locator);\n if (!resolvedLocator) {\n return null;\n }\n\n const aliases = [\n locator.trim(),\n resolvedLocator,\n `file://${resolvedLocator}`,\n ].filter((value, index, values) => value && values.indexOf(value) === index);\n\n return {\n id: resolvedLocator,\n provider: \"skills\",\n locator: resolvedLocator,\n canonicalRepo: resolvedLocator,\n aliases,\n title: deriveDisplayName(resolvedLocator),\n installed: manifest.sources.some(\n (source) => source.kind === \"local\" && path.resolve(source.locator) === resolvedLocator,\n ),\n summary: `Import from ${resolvedLocator}`,\n enrichState: { status: \"idle\" },\n previewState: { status: \"idle\" },\n };\n }\n\n private async resolveRecommendedImportRepos(): Promise<string[]> {\n const [seedGroups, officialGroups, hotGroups, trendingGroups] = await Promise.all([\n this.resolveImportRecommendationFeed(\"seed\"),\n this.resolveImportRecommendationFeed(\"official\"),\n this.resolveImportRecommendationFeed(\"hot\"),\n this.resolveImportRecommendationFeed(\"trending\"),\n ]);\n\n return [...new Set([\n ...seedGroups,\n ...officialGroups,\n ...hotGroups,\n ...trendingGroups,\n ])];\n }\n\n private async resolveImportRecommendationFeed(\n feedId: ImportRecommendationFeedId,\n ): Promise<string[]> {\n const cached = (await this.store.readImportDataCache()).recommendations[feedId];\n if (cached) {\n if (!isImportDataCacheExpired(cached)) {\n return cached.groups;\n }\n\n this.refreshImportRecommendationFeedInBackground(feedId);\n return cached.groups;\n }\n\n if (feedId === \"seed\") {\n return (await this.refreshImportRecommendationFeedTracked(feedId)).groups;\n }\n\n this.refreshImportRecommendationFeedInBackground(feedId);\n return [];\n }\n\n private refreshImportRecommendationFeedInBackground(feedId: ImportRecommendationFeedId): void {\n if (this.importRecommendationRefreshesByFeed.has(feedId)) {\n return;\n }\n\n void this.refreshImportRecommendationFeedTracked(feedId).catch(() => undefined);\n }\n\n private async refreshImportRecommendationFeed(\n feedId: ImportRecommendationFeedId,\n ): Promise<ImportRecommendationFeed> {\n const checkedAt = new Date().toISOString();\n const expiresAt = new Date(Date.now() + IMPORT_RECOMMENDATION_CACHE_TTL_MS).toISOString();\n const groups = feedId === \"seed\"\n ? this.importRecommendationSeedRepos()\n : await fetchSkillsDirectoryFeedGroups(feedId);\n const entry: ImportRecommendationFeed = { id: feedId, checkedAt, expiresAt, groups };\n await this.store.writeImportRecommendationFeedEntry(entry);\n return entry;\n }\n\n private async resolveImportSearchSnapshot(query: string): Promise<ImportSearchSnapshot> {\n const normalizedQuery = query.trim().toLowerCase();\n const cached = (await this.store.readImportDataCache()).searches[normalizedQuery];\n if (cached) {\n if (!isImportDataCacheExpired(cached)) {\n return cached;\n }\n\n this.refreshImportSearchSnapshotInBackground(query);\n return cached;\n }\n\n return this.refreshImportSearchSnapshotTracked(normalizedQuery, query);\n }\n\n private refreshImportSearchSnapshotInBackground(query: string): void {\n const normalizedQuery = query.trim().toLowerCase();\n void this.refreshImportSearchSnapshotTracked(normalizedQuery, query).catch(() => undefined);\n }\n\n private async refreshImportSearchSnapshot(query: string): Promise<ImportSearchSnapshot> {\n const hits = await searchSkillsDirectory(query, 20);\n const snapshot: ImportSearchSnapshot = {\n query: query.trim(),\n checkedAt: new Date().toISOString(),\n expiresAt: new Date(Date.now() + IMPORT_SEARCH_CACHE_TTL_MS).toISOString(),\n hits,\n groups: [...new Set(hits.map((hit) => hit.canonicalRepo))],\n };\n await this.store.writeImportSearchSnapshotEntry(query.trim().toLowerCase(), snapshot);\n return snapshot;\n }\n\n private async resolveImportSourceSnapshot(\n canonicalRepo: string,\n options?: {\n enrichSkillIds?: string[];\n includeSkillDetails?: boolean;\n refreshTrustInBackground?: boolean;\n },\n ): Promise<UnifiedSourceSnapshot> {\n const normalizedRepo = normalizeImportCanonicalRepo(canonicalRepo) ?? canonicalRepo;\n const cached = (await this.store.readImportDataCache()).repos?.[normalizedRepo];\n const cachedSnapshot = cached?.providers.skills?.snapshot;\n const requiresSkillRefresh = cachedSnapshot\n ? this.snapshotNeedsSkillRefresh(cachedSnapshot, options?.enrichSkillIds ?? [])\n : false;\n\n if (cached && cachedSnapshot) {\n if (!isImportDataCacheExpired(cached) && !requiresSkillRefresh) {\n return cachedSnapshot;\n }\n\n if (!requiresSkillRefresh) {\n this.refreshImportSourceSnapshotInBackground(normalizedRepo);\n return cachedSnapshot;\n }\n }\n\n try {\n const refreshOptions = {\n ...(options?.enrichSkillIds ? { enrichSkillIds: options.enrichSkillIds } : {}),\n ...(options?.includeSkillDetails !== undefined ? { includeSkillDetails: options.includeSkillDetails } : {}),\n ...(options?.refreshTrustInBackground !== undefined ? { refreshTrustInBackground: options.refreshTrustInBackground } : {}),\n ...(cachedSnapshot ? { cachedSnapshot } : {}),\n };\n return await this.refreshImportSourceSnapshotTracked(normalizedRepo, {\n ...refreshOptions,\n });\n } catch (error) {\n if (cachedSnapshot) {\n return cachedSnapshot;\n }\n throw error;\n }\n }\n\n private async resolveImportPreviewSnapshot(canonicalRepo: string): Promise<UnifiedSourceSnapshot> {\n const normalizedRepo = normalizeImportCanonicalRepo(canonicalRepo) ?? canonicalRepo;\n const cached = (await this.store.readImportDataCache()).repos?.[normalizedRepo];\n const cachedSnapshot = cached?.providers.skills?.snapshot;\n\n if (cached && cachedSnapshot && !isImportDataCacheExpired(cached)) {\n return cachedSnapshot;\n }\n\n try {\n const trust = await this.resolveCachedImportSourceTrust(normalizedRepo, {\n refreshInBackground: false,\n });\n const snapshot = await fetchSkillsDirectorySourcePreview(normalizedRepo, {\n ...(this.hasUnifiedSourceTrust(trust) ? { trust } : {}),\n });\n const mergedSnapshot = cachedSnapshot\n ? this.mergeSourceSnapshots(cachedSnapshot, snapshot)\n : snapshot;\n await this.store.writeImportSourceSnapshotEntry({\n canonicalRepo: normalizedRepo,\n checkedAt: new Date().toISOString(),\n expiresAt: new Date(Date.now() + IMPORT_SOURCE_CACHE_TTL_MS).toISOString(),\n data: mergedSnapshot,\n });\n return mergedSnapshot;\n } catch (error) {\n if (cachedSnapshot) {\n return cachedSnapshot;\n }\n throw error;\n }\n }\n\n private async previewDirectImportSource(\n locator: string,\n ): Promise<Result<ImportPreviewResult> | null> {\n const resolvedLocator = await this.resolveDirectImportLocator(locator);\n if (!resolvedLocator) {\n return null;\n }\n\n const preview = await this.sourceService.previewSource(resolvedLocator);\n if (!preview.ok) {\n return ok({\n status: \"failed\",\n reasonCode: this.inferImportReasonCode(preview.errors[0]),\n retryable: this.importFailureRetryable(preview.errors[0]),\n }, preview.warnings);\n }\n\n const availableTargets = await this.getAvailableTargets();\n\n return ok(\n this.buildDirectImportPreviewResult(resolvedLocator, preview.data, availableTargets),\n preview.warnings,\n );\n }\n\n private buildDirectImportPreviewResult(\n locator: string,\n preview: SourcePreview,\n availableTargets: DeploymentTargetId[],\n ): ImportPreviewResult {\n return {\n status: \"ready\",\n locator,\n canonicalRepo: locator,\n selectedSkillIds: preview.leafs.map((leaf) => leaf.name),\n enabledTargets: [],\n skills: preview.leafs.map((leaf) => ({\n id: leaf.name,\n title: leaf.title,\n summary: leaf.description,\n selectedByDefault: true,\n })),\n targets: availableTargets.map((target) => ({\n id: target,\n selectedByDefault: false,\n })),\n };\n }\n\n private async resolveDirectImportLocator(locator: string): Promise<string | undefined> {\n const trimmed = locator.trim();\n if (!trimmed || normalizeImportCanonicalRepo(trimmed)) {\n return undefined;\n }\n\n const hostedRepo = parseHostedGitRepo(trimmed);\n if (hostedRepo?.host.includes(\"gitlab\")) {\n return trimmed;\n }\n\n const resolvedPath = path.resolve(trimmed.startsWith(\"file://\")\n ? decodeURIComponent(new URL(trimmed).pathname)\n : trimmed);\n if (await pathExists(resolvedPath)) {\n return resolvedPath;\n }\n\n return undefined;\n }\n\n private refreshImportSourceSnapshotInBackground(canonicalRepo: string): void {\n const refreshKey = this.importSourceRefreshKey(canonicalRepo);\n if (this.importSourceRefreshesByKey.has(refreshKey)) {\n return;\n }\n\n void this.refreshImportSourceSnapshotTracked(canonicalRepo).catch(() => undefined);\n }\n\n private refreshImportRecommendationFeedTracked(\n feedId: ImportRecommendationFeedId,\n ): Promise<ImportRecommendationFeed> {\n const inFlight = this.importRecommendationRefreshesByFeed.get(feedId);\n if (inFlight) {\n return inFlight;\n }\n\n const refresh = this.refreshImportRecommendationFeed(feedId).finally(() => {\n this.importRecommendationRefreshesByFeed.delete(feedId);\n });\n this.importRecommendationRefreshesByFeed.set(feedId, refresh);\n return refresh;\n }\n\n private refreshImportSearchSnapshotTracked(\n normalizedQuery: string,\n query: string,\n ): Promise<ImportSearchSnapshot> {\n const inFlight = this.importSearchRefreshesByQuery.get(normalizedQuery);\n if (inFlight) {\n return inFlight;\n }\n\n const refresh = this.refreshImportSearchSnapshot(query).finally(() => {\n this.importSearchRefreshesByQuery.delete(normalizedQuery);\n });\n this.importSearchRefreshesByQuery.set(normalizedQuery, refresh);\n return refresh;\n }\n\n private refreshImportSourceSnapshotTracked(\n canonicalRepo: string,\n options?: {\n enrichSkillIds?: string[];\n includeSkillDetails?: boolean;\n refreshTrustInBackground?: boolean;\n cachedSnapshot?: UnifiedSourceSnapshot;\n },\n ): Promise<UnifiedSourceSnapshot> {\n const refreshKey = this.importSourceRefreshKey(canonicalRepo, options?.enrichSkillIds);\n const inFlight = this.importSourceRefreshesByKey.get(refreshKey);\n if (inFlight) {\n return inFlight;\n }\n\n const refresh = this.refreshImportSourceSnapshot(canonicalRepo, options).finally(() => {\n this.importSourceRefreshesByKey.delete(refreshKey);\n });\n this.importSourceRefreshesByKey.set(refreshKey, refresh);\n return refresh;\n }\n\n private async refreshImportSourceSnapshot(\n canonicalRepo: string,\n options?: {\n enrichSkillIds?: string[];\n includeSkillDetails?: boolean;\n refreshTrustInBackground?: boolean;\n cachedSnapshot?: UnifiedSourceSnapshot;\n },\n ): Promise<UnifiedSourceSnapshot> {\n const includeSkillDetails = options?.includeSkillDetails !== undefined\n ? options.includeSkillDetails\n : (options?.enrichSkillIds?.length ?? 0) > 0;\n const trust = await this.resolveCachedImportSourceTrust(canonicalRepo, {\n refreshInBackground: options?.refreshTrustInBackground ?? includeSkillDetails,\n });\n\n const snapshot = await fetchSkillsDirectorySourceSnapshot(canonicalRepo, {\n includeSkillDetails,\n ...(options?.enrichSkillIds ? { enrichSkillIds: options.enrichSkillIds } : {}),\n ...(this.hasUnifiedSourceTrust(trust) ? { trust } : {}),\n });\n const mergedSnapshot = options?.cachedSnapshot\n ? this.mergeSourceSnapshots(options.cachedSnapshot, snapshot)\n : snapshot;\n await this.store.writeImportSourceSnapshotEntry({\n canonicalRepo,\n checkedAt: new Date().toISOString(),\n expiresAt: new Date(Date.now() + IMPORT_SOURCE_CACHE_TTL_MS).toISOString(),\n data: mergedSnapshot,\n });\n return mergedSnapshot;\n }\n\n private async resolveCachedImportSourceTrust(\n canonicalRepo: string,\n options?: { refreshInBackground?: boolean },\n ): Promise<UnifiedSourceTrust> {\n const recommendations = (await this.store.readImportDataCache()).recommendations;\n const trust: UnifiedSourceTrust = {};\n\n for (const feedId of [\"official\", \"trending\", \"hot\", \"audits\"] as const) {\n const cachedFeed = recommendations[feedId];\n if (cachedFeed && !isImportDataCacheExpired(cachedFeed)) {\n if (cachedFeed.groups.includes(canonicalRepo)) {\n if (feedId === \"official\") {\n trust.official = true;\n } else if (feedId === \"trending\") {\n trust.trending = true;\n } else if (feedId === \"hot\") {\n trust.hot = true;\n } else if (feedId === \"audits\") {\n trust.audited = true;\n }\n }\n continue;\n }\n\n if (options?.refreshInBackground !== false) {\n this.refreshImportRecommendationFeedInBackground(feedId);\n }\n }\n\n return trust;\n }\n\n private snapshotNeedsSkillRefresh(\n snapshot: UnifiedSourceSnapshot,\n skillIds: string[],\n ): boolean {\n if (skillIds.length === 0) {\n return false;\n }\n\n return skillIds.some((skillId) => {\n const skill = snapshot.skills.find((item) => item.skillId === skillId);\n if (!skill) {\n return true;\n }\n return !skill.summary &&\n skill.weeklyInstalls === undefined &&\n !skill.firstSeen &&\n !skill.installedOn?.length &&\n !skill.audits;\n });\n }\n\n private mergeSourceSnapshots(\n previous: UnifiedSourceSnapshot,\n next: UnifiedSourceSnapshot,\n ): UnifiedSourceSnapshot {\n const previousSkillsById = new Map(previous.skills.map((skill) => [skill.skillId, skill]));\n const mergedSkills = next.skills.map((skill) => {\n const previousSkill = previousSkillsById.get(skill.skillId);\n return previousSkill\n ? {\n ...previousSkill,\n ...skill,\n ...(skill.installedOn?.length ? { installedOn: skill.installedOn } : previousSkill.installedOn ? { installedOn: previousSkill.installedOn } : {}),\n ...(skill.audits ? { audits: skill.audits } : previousSkill.audits ? { audits: previousSkill.audits } : {}),\n }\n : skill;\n });\n\n return {\n ...previous,\n ...next,\n owner: {\n ...previous.owner,\n ...next.owner,\n },\n skills: mergedSkills,\n trust: {\n ...(previous.trust ?? {}),\n ...(next.trust ?? {}),\n },\n };\n }\n\n private buildImportSkillSelectorVariants(\n value: string,\n canonicalRepo: string,\n ): string[] {\n const normalized = this.normalizeImportSkillSelector(value);\n if (!normalized) {\n return [];\n }\n\n const repo = parseGitHubRepo(canonicalRepo);\n const variants = new Set<string>([normalized]);\n const prefixes = new Set<string>();\n\n if (repo) {\n const normalizedOwner = this.normalizeImportSkillSelector(repo.owner);\n const ownerHead = this.normalizeImportSkillSelector(repo.owner.split(/[^a-z0-9]+/i)[0] ?? \"\");\n const normalizedRepo = this.normalizeImportSkillSelector(repo.repo);\n\n if (normalizedOwner) {\n prefixes.add(normalizedOwner);\n }\n if (ownerHead) {\n prefixes.add(ownerHead);\n }\n if (normalizedRepo) {\n prefixes.add(normalizedRepo);\n }\n }\n\n for (const prefix of prefixes) {\n if (normalized.startsWith(`${prefix}-`)) {\n variants.add(normalized.slice(prefix.length + 1));\n }\n }\n\n return [...variants];\n }\n\n private normalizeImportSkillSelector(value: string): string {\n return value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .replace(/-+/g, \"-\");\n }\n\n private getImportLeafSelectorRank(relativePath: string): number {\n if (relativePath === \".\") {\n return 0;\n }\n if (/^skills\\/[^/]+$/.test(relativePath)) {\n return 1;\n }\n if (/^skills\\/\\.(curated|experimental|system)\\/[^/]+$/.test(relativePath)) {\n return 2;\n }\n return 3;\n }\n\n private pickPreferredImportLeafMatch(matches: LeafRecord[]): LeafRecord | undefined {\n if (matches.length === 0) {\n return undefined;\n }\n\n const ranked = matches.map((leaf) => ({\n leaf,\n rank: this.getImportLeafSelectorRank(leaf.relativePath),\n }));\n const bestRank = Math.min(...ranked.map((entry) => entry.rank));\n const bestMatches = ranked\n .filter((entry) => entry.rank === bestRank)\n .map((entry) => entry.leaf);\n\n return bestMatches.length === 1 ? bestMatches[0] : undefined;\n }\n\n private importSourceRefreshKey(canonicalRepo: string, enrichSkillIds?: string[]): string {\n const normalizedSkillIds = [...new Set((enrichSkillIds ?? []).filter(Boolean))].sort();\n if (normalizedSkillIds.length === 0) {\n return canonicalRepo;\n }\n return `${canonicalRepo}::${normalizedSkillIds.join(\",\")}`;\n }\n\n private hasUnifiedSourceTrust(trust: UnifiedSourceTrust): boolean {\n return trust.official === true ||\n trust.trending === true ||\n trust.hot === true ||\n trust.audited === true;\n }\n\n private async mapConcurrent<T, R>(\n items: readonly T[],\n concurrency: number,\n worker: (item: T, index: number) => Promise<R>,\n ): Promise<R[]> {\n if (items.length === 0) {\n return [];\n }\n\n const limit = Math.max(1, Math.min(concurrency, items.length));\n const results = new Array<R>(items.length);\n let nextIndex = 0;\n\n await Promise.all(\n Array.from({ length: limit }, async () => {\n while (nextIndex < items.length) {\n const currentIndex = nextIndex;\n nextIndex += 1;\n results[currentIndex] = await worker(items[currentIndex]!, currentIndex);\n }\n }),\n );\n\n return results;\n }\n\n private inferImportReasonCode(error: unknown): ImportReasonCode {\n if (\n this.hasErrorCode(error, \"SKILLS_SEARCH_RATE_LIMITED\") ||\n this.hasErrorCode(error, \"SKILLS_SOURCE_RATE_LIMITED\") ||\n this.hasErrorCode(error, \"SKILLS_FEED_RATE_LIMITED\") ||\n this.hasErrorCode(error, \"GITHUB_RATE_LIMITED\")\n ) {\n return \"provider_rate_limited\";\n }\n\n if (\n this.hasErrorCode(error, \"SKILLS_SEARCH_RESPONSE_INVALID\") ||\n this.hasErrorCode(error, \"SKILLS_SOURCE_PARSE_FAILED\")\n ) {\n return \"provider_response_invalid\";\n }\n\n if (\n this.hasErrorCode(error, \"SKILLS_SOURCE_NOT_SUPPORTED\") ||\n this.hasErrorCode(error, \"SKILLS_SOURCE_NOT_FOUND\") ||\n this.hasErrorCode(error, \"SKILLS_PAGE_NOT_FOUND\")\n ) {\n return \"provider_data_unavailable\";\n }\n\n return \"provider_request_failed\";\n }\n\n private importFailureRetryable(error: unknown): boolean {\n return this.inferImportReasonCode(error) !== \"provider_response_invalid\";\n }\n\n private hasErrorCode(error: unknown, code: string): error is Error & { code: string } {\n return typeof error === \"object\" && error !== null && \"code\" in error && error.code === code;\n }\n\n private async listWorkflowsImpl(): Promise<\n Result<{\n summaries: WorkflowSummary[];\n pinnedSourceIds: string[];\n recentProjects: RecentProject[];\n selectedProjectScope: ProjectScope;\n customTargets: SharedPreferences[\"customTargets\"];\n agentDisplayOrder: SharedPreferences[\"agentDisplayOrder\"];\n groupCardEnrichmentBySourceId: Record<string, GroupCardEnrichmentSnapshot>;\n }>\n > {\n const pruned = await this.pruneMissingCheckoutsImpl();\n if (!pruned.ok) {\n return fail(pruned.errors, pruned.warnings);\n }\n const reconciled = await this.sourceService.reconcileInventory(undefined, {\n force: true,\n });\n if (!reconciled.ok) {\n return fail(reconciled.errors, reconciled.warnings);\n }\n const { manifest, lockFile } = await this.store.readState();\n await this.store.pruneSourceMetadataCache(manifest.sources.map((source) => source.id));\n await this.persistNormalizedBindings(manifest, lockFile);\n const recentProjects = await this.recentProjectService.listRecentProjects().catch(() => []);\n const preferences = await this.store.pruneMissingSourceIds();\n await this.store.writePreferences({\n ...preferences,\n recentProjects,\n });\n const reconciledPreferences = await this.store.readPreferences();\n const groupCardEnrichmentBySourceId = await this.readCachedGroupCardEnrichmentBySourceId(\n manifest,\n lockFile,\n );\n return ok(\n {\n summaries: this.workflowService.getSummaries(manifest, lockFile),\n pinnedSourceIds: reconciledPreferences.pinnedSourceIds,\n recentProjects: reconciledPreferences.recentProjects,\n selectedProjectScope: reconciledPreferences.selectedProjectScope,\n customTargets: reconciledPreferences.customTargets,\n agentDisplayOrder: reconciledPreferences.agentDisplayOrder,\n groupCardEnrichmentBySourceId,\n },\n pruned.warnings,\n );\n }\n\n async getConfigData(): Promise<\n Result<{ manifest: Manifest; lockFile: LockFile; summaries: WorkflowSummary[] }>\n > {\n return this.runSerializedMutation(() => this.getConfigDataImpl());\n }\n\n private async getConfigDataImpl(): Promise<\n Result<{ manifest: Manifest; lockFile: LockFile; summaries: WorkflowSummary[] }>\n > {\n const pruned = await this.pruneMissingCheckoutsImpl();\n if (!pruned.ok) {\n return fail(pruned.errors, pruned.warnings);\n }\n const reconciled = await this.sourceService.reconcileInventory(undefined, {\n force: true,\n });\n if (!reconciled.ok) {\n return fail(reconciled.errors, reconciled.warnings);\n }\n const { manifest, lockFile } = await this.store.readState();\n await this.persistNormalizedBindings(manifest, lockFile);\n return ok(\n {\n manifest,\n lockFile,\n summaries: this.workflowService.getSummaries(manifest, lockFile),\n },\n pruned.warnings,\n );\n }\n\n async bootstrapWorkspaceState(\n onEvent?: (event: BootstrapEvent) => void,\n ): Promise<\n Result<{\n availableTargets: DeploymentTargetId[];\n manifest: Manifest;\n lockFile: LockFile;\n summaries: WorkflowSummary[];\n initialDrafts: Record<string, DraftBinding>;\n audit: DoctorReport;\n importedSourceIds: string[];\n pinnedSourceIds: string[];\n recentProjects: RecentProject[];\n selectedProjectScope: ProjectScope;\n projectDrafts: SharedPreferences[\"projectDrafts\"];\n customTargets: SharedPreferences[\"customTargets\"];\n agentDisplayOrder: SharedPreferences[\"agentDisplayOrder\"];\n groupCardEnrichmentBySourceId: Record<string, GroupCardEnrichmentSnapshot>;\n }>\n > {\n return this.runAuditedMutation(\n \"bootstrap\",\n {},\n () => this.bootstrapWorkspaceStateImpl(onEvent),\n );\n }\n\n private async bootstrapWorkspaceStateImpl(\n onEvent?: (event: BootstrapEvent) => void,\n ): Promise<\n Result<{\n availableTargets: DeploymentTargetId[];\n manifest: Manifest;\n lockFile: LockFile;\n summaries: WorkflowSummary[];\n initialDrafts: Record<string, DraftBinding>;\n audit: DoctorReport;\n importedSourceIds: string[];\n pinnedSourceIds: string[];\n recentProjects: RecentProject[];\n selectedProjectScope: ProjectScope;\n projectDrafts: SharedPreferences[\"projectDrafts\"];\n customTargets: SharedPreferences[\"customTargets\"];\n agentDisplayOrder: SharedPreferences[\"agentDisplayOrder\"];\n groupCardEnrichmentBySourceId: Record<string, GroupCardEnrichmentSnapshot>;\n }>\n > {\n const boot = await this.configCoordinator.bootstrapWorkspaceState(onEvent);\n if (!boot.ok) {\n return fail(boot.errors, boot.warnings);\n }\n const preferences = await this.store.pruneMissingSourceIds();\n const groupCardEnrichmentBySourceId = await this.readCachedGroupCardEnrichmentBySourceId(\n boot.data.manifest,\n boot.data.lockFile,\n );\n\n return ok({\n availableTargets: boot.data.availableTargets,\n manifest: boot.data.manifest,\n lockFile: boot.data.lockFile,\n summaries: boot.data.summaries,\n initialDrafts: boot.data.initialDrafts,\n audit: boot.data.audit,\n importedSourceIds: [],\n pinnedSourceIds: preferences.pinnedSourceIds,\n recentProjects: preferences.recentProjects,\n selectedProjectScope: preferences.selectedProjectScope,\n projectDrafts: preferences.projectDrafts,\n customTargets: preferences.customTargets,\n agentDisplayOrder: preferences.agentDisplayOrder,\n groupCardEnrichmentBySourceId,\n });\n }\n\n private async readCachedGroupCardEnrichmentBySourceId(\n manifest: Manifest,\n lockFile: LockFile,\n ): Promise<Record<string, GroupCardEnrichmentSnapshot>> {\n const [sourceMetadataCache, importDataCache] = await Promise.all([\n this.store.readSourceMetadataCache(),\n this.store.readImportDataCache(),\n ]);\n const entries: Record<string, GroupCardEnrichmentSnapshot> = {};\n\n for (const source of manifest.sources) {\n const entry: GroupCardEnrichmentSnapshot = {};\n const sourceLock = lockFile.sources.find((item) => item.id === source.id);\n const cachedMetadata = sourceMetadataCache[source.id];\n if (cachedMetadata) {\n entry.sourceMetadata = sourceMetadataCacheEntryToResult(cachedMetadata);\n }\n\n const canonicalRepo = normalizeImportCanonicalRepo(source.locator)\n ?? (source.originLocator ? normalizeImportCanonicalRepo(source.originLocator) : undefined);\n const cachedSnapshot = canonicalRepo\n ? importDataCache.repos?.[canonicalRepo]?.providers.skills?.snapshot\n : undefined;\n if (cachedSnapshot) {\n entry.sourceSnapshot = cachedSnapshot;\n }\n\n if (sourceLock?.checkoutPath) {\n entry.groupPath = sourceLock.checkoutPath;\n }\n\n if (entry.sourceMetadata || entry.sourceSnapshot || entry.groupPath) {\n entries[source.id] = entry;\n }\n }\n\n return entries;\n }\n\n async togglePinnedSource(sourceId: string): Promise<Result<{ pinnedSourceIds: string[] }>> {\n return this.runSerializedMutation(() => this.togglePinnedSourceImpl(sourceId));\n }\n\n private async togglePinnedSourceImpl(\n sourceId: string,\n ): Promise<Result<{ pinnedSourceIds: string[] }>> {\n const manifest = await this.store.readManifest();\n if (!manifest.sources.some((source) => source.id === sourceId)) {\n return fail({\n code: \"SOURCE_NOT_FOUND\",\n message: `Skills group id '${sourceId}' is not registered.`,\n });\n }\n\n const preferences = await this.store.togglePinnedSource(sourceId);\n return ok({ pinnedSourceIds: preferences.pinnedSourceIds });\n }\n\n async getAvailableTargets(): Promise<DeploymentTargetId[]> {\n const adapters = await this.refreshAdapters();\n const availableTargets: DeploymentTargetId[] = [];\n\n for (const adapter of adapters) {\n const detection = await adapter.detect();\n if (detection.available) {\n availableTargets.push(adapter.target);\n }\n }\n\n return availableTargets;\n }\n\n async previewDraft(\n sourceId: string,\n draft: DraftBinding,\n ): Promise<Result<{ plan: DeploymentPlan; manifest: Manifest; lockFile: LockFile }>> {\n // config TUI state flow:\n // draft -> previewDraft() -> plan only\n // draft -> applyDraft() -> plan + filesystem + manifest/lock writes\n const { manifest, lockFile } = await this.readStateConsistently();\n this.normalizeBindings(manifest, lockFile);\n const prepared = this.prepareManifestForDraft(manifest, lockFile, sourceId, draft);\n const plan = await this.planForAffectedSources(\n prepared.manifest,\n lockFile,\n sourceId,\n );\n if (!plan.ok) {\n return fail(plan.errors, [...prepared.warnings, ...plan.warnings]);\n }\n\n return ok(\n { plan: plan.data, manifest: prepared.manifest, lockFile },\n [...prepared.warnings, ...plan.warnings],\n );\n }\n\n async applyDraft(\n sourceId: string,\n draft: DraftBinding,\n scope: ProjectScope = { kind: \"global\" },\n ): Promise<Result<ApplyDraftResult>> {\n return this.runAuditedMutation(\n \"apply-draft\",\n {\n sourceId,\n selectedLeafIds: draft.selectedLeafIds,\n enabledTargets: draft.enabledTargets,\n scope,\n },\n () => this.applyDraftAuditedImpl(sourceId, draft, scope),\n );\n }\n\n private async applyDraftAuditedImpl(\n sourceId: string,\n draft: DraftBinding,\n scope: ProjectScope,\n ): Promise<AuditedMutationResult<ApplyDraftResult>> {\n const { manifest, lockFile } = await this.store.readState();\n const before = await this.captureSourceAuditSnapshot(manifest, lockFile, sourceId);\n const result = await this.applyDraftImpl(sourceId, draft, scope);\n const { manifest: nextManifest, lockFile: nextLockFile } = await this.store.readState();\n const after = await this.captureSourceAuditSnapshot(nextManifest, nextLockFile, sourceId);\n\n return {\n result,\n auditDetails: {\n stateTransition: {\n before,\n after,\n },\n actionSummary: this.summarizeDeploymentActions(result.ok ? result.data.actions : []),\n },\n };\n }\n\n private async applyDraftImpl(\n sourceId: string,\n draft: DraftBinding,\n scope: ProjectScope,\n ): Promise<Result<ApplyDraftResult>> {\n if (scope.kind === \"project\") {\n const { manifest, lockFile } = await this.store.readState();\n if (!manifest.sources.some((source) => source.id === sourceId)) {\n return fail({\n code: \"SOURCE_NOT_FOUND\",\n message: `Skills group id '${sourceId}' is not registered.`,\n });\n }\n\n this.normalizeBindings(manifest, lockFile);\n const preferences = await this.store.readPreferences();\n const initialDrafts: Record<string, DraftBinding> = {\n [sourceId]: this.draftFromBinding(\n sourceId,\n manifest.bindings[sourceId] ?? { targets: {} },\n lockFile,\n ),\n };\n const previousDraft = this.resolveDraftForScope(sourceId, initialDrafts, preferences, scope);\n const previousScopedManifest = this.cloneManifest(manifest);\n this.normalizeBindings(previousScopedManifest, lockFile);\n const previousPrepared = this.prepareManifestForDraft(\n previousScopedManifest,\n lockFile,\n sourceId,\n previousDraft,\n );\n const scopedManifest = this.cloneManifest(manifest);\n this.normalizeBindings(scopedManifest, lockFile);\n const prepared = this.prepareManifestForDraft(scopedManifest, lockFile, sourceId, draft);\n const scopedTargets = [...new Set([\n ...previousDraft.enabledTargets,\n ...prepared.draft.enabledTargets,\n ])];\n const targetRootOverrides = scopedTargets.length === 0\n ? ok({} as TargetRootOverrides)\n : await this.resolveProjectTargetRoots(scope, scopedTargets);\n if (!targetRootOverrides.ok) {\n const preferencesAfterFailure = await this.store.readPreferences();\n return {\n ok: false,\n data: {\n actions: [],\n draft: prepared.draft,\n recentProjects: preferencesAfterFailure.recentProjects,\n selectedProjectScope: preferencesAfterFailure.selectedProjectScope,\n projectDrafts: preferencesAfterFailure.projectDrafts,\n },\n warnings: [...prepared.warnings, ...targetRootOverrides.warnings],\n errors: targetRootOverrides.errors,\n };\n }\n const scopedDeployments = scopedTargets.length === 0\n ? []\n : await this.findScopedDeploymentsOnDisk(\n previousPrepared.manifest,\n lockFile,\n sourceId,\n targetRootOverrides.data,\n );\n const nextPreferences: SharedPreferences = {\n ...preferences,\n projectDrafts: {\n ...preferences.projectDrafts,\n [scope.projectId]: {\n ...(preferences.projectDrafts[scope.projectId] ?? {}),\n [sourceId]: prepared.draft,\n },\n },\n };\n\n if (scopedTargets.length > 0) {\n const scopedLockFile = this.cloneLockFileForScopedDeployments(lockFile, scopedDeployments);\n const scopedApply = await this.withScopedTargetRoots<Result<{ actions: DeploymentAction[] }>>(\n targetRootOverrides.data,\n async () => {\n const plan = await this.planForSources(\n prepared.manifest,\n scopedLockFile,\n [sourceId],\n );\n if (!plan.ok) {\n return fail(plan.errors, [...prepared.warnings, ...plan.warnings]);\n }\n\n const applyResult = await this.applier.applyPlan(scopedLockFile, plan.data.actions);\n if (!applyResult.ok) {\n return fail(\n applyResult.errors,\n [...prepared.warnings, ...plan.warnings, ...applyResult.warnings],\n );\n }\n\n return ok(\n { actions: plan.data.actions },\n [...prepared.warnings, ...plan.warnings, ...applyResult.warnings],\n );\n },\n );\n if (!scopedApply.ok) {\n return fail(scopedApply.errors, scopedApply.warnings);\n }\n\n await this.store.writePreferences(nextPreferences);\n const freshState = await this.buildApplyDraftFreshState(sourceId, scope);\n return ok(\n {\n actions: scopedApply.data.actions,\n draft: prepared.draft,\n ...(freshState.summary ? { summary: freshState.summary } : {}),\n ...(freshState.inspect ? { inspect: freshState.inspect } : {}),\n },\n scopedApply.warnings,\n );\n }\n\n await this.store.writePreferences(nextPreferences);\n const freshState = await this.buildApplyDraftFreshState(sourceId, scope);\n return ok(\n {\n actions: [],\n draft: prepared.draft,\n ...(freshState.summary ? { summary: freshState.summary } : {}),\n ...(freshState.inspect ? { inspect: freshState.inspect } : {}),\n },\n prepared.warnings,\n );\n }\n\n const { manifest, lockFile } = await this.store.readState();\n this.normalizeBindings(manifest, lockFile);\n await this.ensureProjectionLedger(manifest, lockFile);\n const previousEnabledTargets = this.getEnabledTargetsForSource(manifest, sourceId);\n const sourceLock = lockFile.sources.find((source) => source.id === sourceId);\n const prepared = this.prepareManifestForDraft(manifest, lockFile, sourceId, draft);\n\n const plan = await this.planForAffectedSources(prepared.manifest, lockFile, sourceId);\n if (!plan.ok) {\n return fail(plan.errors, [...prepared.warnings, ...plan.warnings]);\n }\n\n const applyResult = await this.applier.applyPlan(lockFile, plan.data.actions);\n await this.ensureProjectionLedger(prepared.manifest, lockFile);\n await this.store.writeState(prepared.manifest, lockFile);\n\n if (!applyResult.ok) {\n return fail(\n applyResult.errors,\n [...prepared.warnings, ...plan.warnings, ...applyResult.warnings],\n );\n }\n\n const importedTargets = sourceLock?.importMode === \"bootstrap-detected\"\n ? getBootstrapImportedTargets(lockFile, sourceLock)\n : [];\n const removedImportedTargets = [...new Set([\n ...previousEnabledTargets,\n ...importedTargets,\n ])].filter((target) => !prepared.draft.enabledTargets.includes(target));\n const importedCleanupWarnings = await this.cleanupImportedTargetPaths(\n prepared.manifest,\n lockFile,\n [sourceId],\n removedImportedTargets,\n );\n const detachedWarnings = await this.cleanupDetachedTargetSymlinksForSources(lockFile, [sourceId]);\n const orphanWarnings = await this.cleanupOrphanTargetSymlinks(lockFile);\n await this.store.writeState(prepared.manifest, lockFile);\n\n const freshState = await this.buildApplyDraftFreshState(sourceId, scope);\n return ok(\n {\n actions: plan.data.actions,\n draft: prepared.draft,\n ...(freshState.summary ? { summary: freshState.summary } : {}),\n ...(freshState.inspect ? { inspect: freshState.inspect } : {}),\n },\n [\n ...prepared.warnings,\n ...plan.warnings,\n ...applyResult.warnings,\n ...importedCleanupWarnings,\n ...detachedWarnings,\n ...orphanWarnings,\n ],\n );\n }\n\n private async buildApplyDraftFreshState(\n sourceId: string,\n scope: ProjectScope,\n ): Promise<Pick<ApplyDraftResult, \"summary\" | \"inspect\">> {\n const inspected = await this.inspectSourceImpl(sourceId, scope);\n if (!inspected.ok) {\n return {};\n }\n\n return {\n summary: inspected.data.summary,\n inspect: inspected.data,\n };\n }\n\n async updateSources(sourceIds?: string[]): Promise<\n Result<SourceUpdateResult>\n > {\n return this.runAuditedMutation(\n \"update-sources\",\n { sourceIds: sourceIds ?? [] },\n () => this.updateSourcesImpl(sourceIds),\n );\n }\n\n private async updateSourcesImpl(sourceIds?: string[]): Promise<Result<SourceUpdateResult>> {\n const pruned = await this.pruneMissingCheckoutsImpl();\n if (!pruned.ok) {\n return fail(pruned.errors, pruned.warnings);\n }\n const requestedIds = sourceIds?.filter((sourceId) => !pruned.data.removedSourceIds.includes(sourceId));\n if (sourceIds?.length && requestedIds?.length === 0) {\n return ok({ updated: [] }, pruned.warnings);\n }\n\n const updated = await this.sourceService.updateSources(requestedIds);\n if (!updated.ok) {\n return updated;\n }\n\n const { manifest, lockFile } = await this.store.readState();\n this.applySourceUpdateResults(manifest, lockFile, updated.data.updated);\n await this.persistNormalizedBindings(manifest, lockFile);\n const planSourceIds = manifest.sources\n .map((source) => source.id)\n .filter((id) =>\n updated.data.updated.some((item) => item.sourceId === id) ||\n this.hasActiveTargets(manifest, id) ||\n getManagedDeployments(lockFile).some((deployment) => deployment.sourceId === id),\n );\n const planned = await this.planAndApplySources(manifest, lockFile, planSourceIds);\n if (!planned.ok) {\n return fail(planned.errors, [...pruned.warnings, ...updated.warnings, ...planned.warnings]);\n }\n await this.store.writeState(manifest, lockFile);\n return ok(updated.data, [...pruned.warnings, ...updated.warnings, ...planned.warnings]);\n }\n\n async doctor(): Promise<Result<DoctorReport>> {\n return this.runAuditedMutation(\n \"doctor\",\n {},\n () => this.doctorImpl(),\n );\n }\n\n private async doctorImpl(): Promise<Result<DoctorReport>> {\n const pruned = await this.pruneMissingCheckoutsImpl();\n if (!pruned.ok) {\n return fail(pruned.errors, pruned.warnings);\n }\n const reconciled = await this.sourceService.reconcileInventory();\n if (!reconciled.ok) {\n return fail(reconciled.errors, reconciled.warnings);\n }\n const { manifest, lockFile } = await this.store.readState();\n await this.ensureProjectionLedger(manifest, lockFile);\n await this.persistNormalizedBindings(manifest, lockFile);\n const doctor = await this.doctorService.run(manifest, lockFile);\n if (!doctor.ok) {\n return doctor;\n }\n return ok(doctor.data, [...pruned.warnings, ...doctor.warnings]);\n }\n\n async repairTargets(sourceIds?: string[]): Promise<Result<{ actions: DeploymentAction[] }>> {\n return this.runSerializedMutation(() => this.repairTargetsImpl(sourceIds));\n }\n\n private async repairTargetsImpl(\n sourceIds?: string[],\n ): Promise<Result<{ actions: DeploymentAction[] }>> {\n const { manifest, lockFile } = await this.store.readState();\n this.normalizeBindings(manifest, lockFile);\n await this.ensureProjectionLedger(manifest, lockFile);\n const warnings: Warning[] = await this.cleanupOrphanTargetSymlinks(lockFile);\n\n const requestedIds = sourceIds?.length\n ? sourceIds\n : manifest.sources.map((source) => source.id);\n for (const sourceId of requestedIds) {\n if (!manifest.sources.some((source) => source.id === sourceId)) {\n return fail({\n code: \"SOURCE_NOT_FOUND\",\n message: `Skills group id '${sourceId}' is not registered.`,\n });\n }\n }\n\n const planSourceIds = requestedIds.filter(\n (sourceId) =>\n this.hasActiveTargets(manifest, sourceId) ||\n getManagedDeployments(lockFile).some((deployment) => deployment.sourceId === sourceId),\n );\n for (const sourceId of requestedIds) {\n if (planSourceIds.includes(sourceId)) {\n continue;\n }\n const sourceLock = lockFile.sources.find((source) => source.id === sourceId);\n if (\n sourceLock?.importMode === \"bootstrap-detected\" ||\n (lockFile.projections ?? []).some(\n (projection) =>\n projection.sourceId === sourceId &&\n projection.mode === \"bootstrap-imported\",\n )\n ) {\n warnings.push({\n code: \"REPAIR_TARGETS_SKIPPED_BOOTSTRAP_IMPORTED\",\n message: `Skipped repair for bootstrap-imported source '${sourceId}' because it has no managed target bindings.`,\n });\n }\n }\n const planned = await this.planAndApplySources(manifest, lockFile, planSourceIds);\n if (!planned.ok) {\n return fail(planned.errors, [...warnings, ...planned.warnings]);\n }\n\n await this.store.writeState(manifest, lockFile);\n return ok({ actions: planned.data.actions }, [...warnings, ...planned.warnings]);\n }\n\n async repairSource(sourceIds?: string[]): Promise<Result<SourceUpdateResult>> {\n return this.runSerializedMutation(() => this.repairSourceImpl(sourceIds));\n }\n\n private async repairSourceImpl(sourceIds?: string[]): Promise<Result<SourceUpdateResult>> {\n const pruned = await this.pruneMissingCheckoutsImpl();\n if (!pruned.ok) {\n return fail(pruned.errors, pruned.warnings);\n }\n\n const requestedIds = sourceIds?.filter(\n (sourceId) => !pruned.data.removedSourceIds.includes(sourceId),\n );\n if (sourceIds?.length && requestedIds?.length === 0) {\n return ok({ updated: [] }, pruned.warnings);\n }\n\n const repaired = await this.sourceService.updateSources(requestedIds);\n if (!repaired.ok) {\n return repaired;\n }\n\n const { manifest, lockFile } = await this.store.readState();\n this.applySourceUpdateResults(manifest, lockFile, repaired.data.updated);\n await this.persistNormalizedBindings(manifest, lockFile);\n await this.store.writeState(manifest, lockFile);\n\n return ok(repaired.data, [...pruned.warnings, ...repaired.warnings]);\n }\n\n async repairState(\n sourceIds?: string[],\n ): Promise<Result<{ repairedSourceIds: string[]; removedDeploymentCount: number }>> {\n return this.runSerializedMutation(() => this.repairStateImpl(sourceIds));\n }\n\n private async repairStateImpl(\n sourceIds?: string[],\n ): Promise<Result<{ repairedSourceIds: string[]; removedDeploymentCount: number }>> {\n const pruned = await this.pruneMissingCheckoutsImpl();\n if (!pruned.ok) {\n return fail(pruned.errors, pruned.warnings);\n }\n\n const requestedIds = sourceIds?.filter(\n (sourceId) => !pruned.data.removedSourceIds.includes(sourceId),\n );\n if (sourceIds?.length && requestedIds?.length === 0) {\n return ok(\n { repairedSourceIds: [], removedDeploymentCount: 0 },\n pruned.warnings,\n );\n }\n\n const reconciled = await this.sourceService.reconcileInventory(requestedIds, {\n force: true,\n });\n if (!reconciled.ok) {\n return fail(reconciled.errors, [...pruned.warnings, ...reconciled.warnings]);\n }\n\n const { manifest, lockFile } = await this.store.readState();\n await this.persistNormalizedBindings(manifest, lockFile);\n const removedDeploymentCount = await this.rebuildDeploymentState(\n manifest,\n lockFile,\n requestedIds,\n );\n await this.store.writeState(manifest, lockFile);\n\n return ok(\n {\n repairedSourceIds: reconciled.data.updatedSourceIds,\n removedDeploymentCount,\n },\n [...pruned.warnings, ...reconciled.warnings],\n );\n }\n\n async uninstall(sourceIds: string[]): Promise<\n Result<{\n removed: string[];\n removedRefs: Array<{ id: string; locator: string; displayName: string }>;\n warnings: string[];\n }>\n > {\n return this.runAuditedMutation(\n \"uninstall\",\n { sourceIds },\n () => this.uninstallImpl(sourceIds),\n );\n }\n\n private async uninstallImpl(sourceIds: string[]): Promise<\n Result<{\n removed: string[];\n removedRefs: Array<{ id: string; locator: string; displayName: string }>;\n warnings: string[];\n }>\n > {\n const { manifest, lockFile } = await this.store.readState();\n await this.ensureProjectionLedger(manifest, lockFile);\n const warnings: string[] = [];\n const removedRefs = sourceIds\n .map((sourceId) => manifest.sources.find((source) => source.id === sourceId))\n .filter((source): source is Manifest[\"sources\"][number] => Boolean(source));\n\n for (const sourceId of sourceIds) {\n const projections = (lockFile.projections ?? []).filter(\n (projection) => projection.sourceId === sourceId,\n );\n\n for (const projection of projections) {\n if (!(await pathExists(projection.targetPath))) {\n continue;\n }\n if (!this.isProjectionPathManaged(lockFile, projection)) {\n warnings.push(`Refusing to remove unmanaged target path ${projection.targetPath}.`);\n continue;\n }\n try {\n if (!this.hasPersistentProjectionOwnerForPath(lockFile, projection)) {\n await removePath(projection.targetPath);\n }\n } catch (error) {\n warnings.push(`Unable to remove ${projection.targetPath}: ${String(error)}`);\n }\n }\n\n lockFile.projections = (lockFile.projections ?? []).filter(\n (projection) => projection.sourceId !== sourceId,\n );\n }\n\n const detachedWarnings = await this.cleanupDetachedTargetSymlinksForSources(lockFile, sourceIds);\n const orphanWarnings = await this.cleanupOrphanTargetSymlinks(lockFile);\n warnings.push(...detachedWarnings.map((warning) => warning.message));\n warnings.push(...orphanWarnings.map((warning) => warning.message));\n\n if (warnings.length > 0) {\n return fail(\n {\n code: \"GROUP_DELETE_INCOMPLETE\",\n message: `Unable to fully delete ${warnings.length} managed path${warnings.length === 1 ? \"\" : \"s\"}.`,\n },\n warnings.map((message) => ({\n code: \"GROUP_DELETE_PATH_FAILED\",\n message,\n })),\n );\n }\n\n let removed;\n try {\n removed = await this.sourceService.removeSource(sourceIds);\n } catch (error) {\n return fail({\n code: \"GROUP_DELETE_INCOMPLETE\",\n message: `Unable to fully delete selected skills groups: ${String(error)}`,\n });\n }\n if (!removed.ok) {\n return fail(removed.errors, removed.warnings);\n }\n\n return ok({ removed: removed.data.removed, removedRefs, warnings });\n }\n\n bindingFromDraft(draft: DraftBinding): SourceBinding {\n const targets: Partial<Record<DeploymentTargetId, TargetBinding>> = {};\n for (const target of draft.enabledTargets) {\n targets[target] = {\n enabled: true,\n leafIds: [...draft.selectedLeafIds],\n };\n }\n return {\n selectedLeafIds: [...draft.selectedLeafIds],\n targets,\n };\n }\n\n private resolveDraftForScope(\n sourceId: string,\n initialDrafts: Record<string, DraftBinding>,\n preferences: SharedPreferences,\n scope: ProjectScope,\n ): DraftBinding {\n if (scope.kind === \"global\") {\n return initialDrafts[sourceId] ?? EMPTY_DRAFT;\n }\n\n return (\n preferences.projectDrafts[scope.projectId]?.[sourceId] ??\n initialDrafts[sourceId] ??\n EMPTY_DRAFT\n );\n }\n\n private cloneManifest(manifest: Manifest): Manifest {\n const bindings: Record<string, SourceBinding> = {};\n\n for (const [sourceId, binding] of Object.entries(manifest.bindings)) {\n const targets: SourceBinding[\"targets\"] = {};\n for (const [target, targetBinding] of Object.entries(binding.targets)) {\n if (!targetBinding) {\n continue;\n }\n targets[target as DeploymentTargetName] = {\n enabled: targetBinding.enabled,\n leafIds: [...targetBinding.leafIds],\n };\n }\n\n bindings[sourceId] = {\n ...(binding.selectedLeafIds ? { selectedLeafIds: [...binding.selectedLeafIds] } : {}),\n targets,\n };\n }\n\n return {\n schemaVersion: manifest.schemaVersion,\n sources: manifest.sources.map((source) => ({ ...source })),\n bindings,\n };\n }\n\n private async pruneMissingCheckoutsImpl(): Promise<Result<{ removedSourceIds: string[] }>> {\n const { manifest, lockFile } = await this.store.readState();\n await this.ensureProjectionLedger(manifest, lockFile);\n const orphanWarnings = await this.cleanupOrphanTargetSymlinks(lockFile);\n const removedSourceIds: string[] = [];\n const warnings: Warning[] = [];\n\n for (const source of lockFile.sources) {\n if (await pathExists(source.checkoutPath)) {\n continue;\n }\n\n removedSourceIds.push(source.id);\n warnings.push({\n code: \"SOURCE_CHECKOUT_MISSING\",\n message: `Removed ${source.displayName} because checkout is missing at ${source.checkoutPath}.`,\n });\n\n const projections = (lockFile.projections ?? []).filter(\n (projection) => projection.sourceId === source.id,\n );\n for (const projection of projections) {\n if (!(await pathExists(projection.targetPath))) {\n continue;\n }\n if (!this.isProjectionPathManaged(lockFile, projection)) {\n warnings.push({\n code: \"SOURCE_CHECKOUT_PRUNE_SKIPPED\",\n message: `Skipped unmanaged deployment path ${projection.targetPath} while pruning ${source.displayName}.`,\n });\n continue;\n }\n try {\n if (!this.hasPersistentProjectionOwnerForPath(lockFile, projection)) {\n await removePath(projection.targetPath);\n }\n } catch (error) {\n return fail({\n code: \"SOURCE_CHECKOUT_PRUNE_FAILED\",\n message: `Unable to clean deployment ${projection.targetPath}: ${String(error)}`,\n }, warnings);\n }\n }\n }\n\n if (removedSourceIds.length === 0) {\n if (orphanWarnings.length > 0) {\n await this.store.writeState(manifest, lockFile);\n }\n return ok({ removedSourceIds: [] }, orphanWarnings);\n }\n\n manifest.sources = manifest.sources.filter((source) => !removedSourceIds.includes(source.id));\n for (const sourceId of removedSourceIds) {\n delete manifest.bindings[sourceId];\n }\n lockFile.sources = lockFile.sources.filter((source) => !removedSourceIds.includes(source.id));\n lockFile.leafInventory = lockFile.leafInventory.filter(\n (leaf) => !removedSourceIds.includes(leaf.sourceId),\n );\n lockFile.projections = (lockFile.projections ?? []).filter(\n (projection) => !removedSourceIds.includes(projection.sourceId),\n );\n\n await this.store.writeState(manifest, lockFile);\n await this.store.pruneSourceMetadataCache(manifest.sources.map((source) => source.id));\n\n return ok({ removedSourceIds }, [...orphanWarnings, ...warnings]);\n }\n\n private async cleanupOrphanTargetSymlinks(lockFile: LockFile): Promise<Warning[]> {\n const warnings: Warning[] = [];\n const managedStateRoot = await fs.realpath(this.store.rootPath).catch(() =>\n path.resolve(this.store.rootPath),\n );\n const adapters = await this.refreshAdapters();\n\n for (const adapter of adapters) {\n const detection = await adapter.detect();\n if (!detection.available || !(await pathExists(detection.rootPath))) {\n continue;\n }\n\n const entries = await fs.readdir(detection.rootPath, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n const targetPath = path.join(detection.rootPath, entry.name);\n const resolvedTargetPath = path.resolve(targetPath);\n const realTargetPath = await fs.realpath(targetPath).catch(() => undefined);\n const linkTarget = realTargetPath\n ? realTargetPath\n : await fs.readlink(targetPath)\n .then((value) => path.resolve(path.dirname(targetPath), value))\n .catch(() => undefined);\n if (!linkTarget) {\n continue;\n }\n\n const resolvedLinkTarget = path.resolve(linkTarget);\n if (\n !isPathInside(managedStateRoot, resolvedLinkTarget) &&\n resolvedLinkTarget !== managedStateRoot\n ) {\n continue;\n }\n\n const matchingProjections = (lockFile.projections ?? []).filter(\n (projection) => path.resolve(projection.targetPath) === resolvedTargetPath,\n );\n const hasResolvableProjection = matchingProjections.some((projection) =>\n this.isProjectionStillResolvable(lockFile, projection),\n );\n if (hasResolvableProjection) {\n continue;\n }\n\n await removePath(targetPath);\n lockFile.projections = (lockFile.projections ?? []).filter(\n (projection) => path.resolve(projection.targetPath) !== resolvedTargetPath,\n );\n warnings.push({\n code: \"ORPHAN_TARGET_SYMLINK_REMOVED\",\n message: `Removed orphan target symlink ${targetPath} because it points into managed state without a matching projection.`,\n });\n }\n }\n\n return warnings;\n }\n\n private async cleanupDetachedTargetSymlinksForSources(\n lockFile: LockFile,\n sourceIds: string[],\n ): Promise<Warning[]> {\n const warnings: Warning[] = [];\n const adapters = await this.refreshAdapters();\n const checkoutRoots = new Map<string, string>();\n for (const source of lockFile.sources.filter((item) => sourceIds.includes(item.id))) {\n const resolvedCheckoutPath = await fs.realpath(source.checkoutPath).catch(() =>\n path.resolve(source.checkoutPath),\n );\n checkoutRoots.set(source.id, resolvedCheckoutPath);\n }\n if (checkoutRoots.size === 0) {\n return warnings;\n }\n\n for (const adapter of adapters) {\n const detection = await adapter.detect();\n if (!detection.available || !(await pathExists(detection.rootPath))) {\n continue;\n }\n\n const entries = await fs.readdir(detection.rootPath, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n const targetPath = path.join(detection.rootPath, entry.name);\n const resolvedTargetPath = path.resolve(targetPath);\n const realTargetPath = await fs.realpath(targetPath).catch(() => undefined);\n const linkTarget = realTargetPath\n ? realTargetPath\n : await fs.readlink(targetPath)\n .then((value) => path.resolve(path.dirname(targetPath), value))\n .catch(() => undefined);\n if (!linkTarget) {\n continue;\n }\n\n const resolvedLinkTarget = path.resolve(linkTarget);\n const ownerSourceId = [...checkoutRoots.entries()].find(([, checkoutPath]) =>\n resolvedLinkTarget === checkoutPath || isPathInside(checkoutPath, resolvedLinkTarget),\n )?.[0];\n if (!ownerSourceId) {\n continue;\n }\n\n const matchingProjection = (lockFile.projections ?? []).some(\n (projection) =>\n projection.sourceId === ownerSourceId &&\n path.resolve(projection.targetPath) === resolvedTargetPath,\n );\n if (matchingProjection) {\n continue;\n }\n\n await removePath(targetPath);\n warnings.push({\n code: \"DETACHED_TARGET_SYMLINK_REMOVED\",\n message: `Removed detached target symlink ${targetPath} because it points to source '${ownerSourceId}' without a matching projection.`,\n });\n }\n }\n\n return warnings;\n }\n\n private isProjectionStillResolvable(lockFile: LockFile, projection: ProjectionRecord): boolean {\n if (!lockFile.sources.some((source) => source.id === projection.sourceId)) {\n return false;\n }\n\n if (projection.mode === \"managed\") {\n return lockFile.leafInventory.some((leaf) => leaf.id === projection.leafId);\n }\n\n return true;\n }\n\n private async getTargetRootMap(): Promise<Map<DeploymentTargetId, string>> {\n const adapters = await this.refreshAdapters();\n return new Map(\n await Promise.all(\n adapters.map(async (adapter) => {\n const detection = await adapter.detect();\n return [adapter.target, detection.rootPath] as const;\n }),\n ),\n );\n }\n\n private getEnabledTargetsForSource(\n manifest: Manifest,\n sourceId: string,\n ): DeploymentTargetId[] {\n const binding = manifest.bindings[sourceId];\n if (!binding) {\n return [];\n }\n\n return Object.entries(binding.targets)\n .filter(([, targetBinding]) => targetBinding?.enabled)\n .map(([target]) => target as DeploymentTargetId);\n }\n\n private isPathInsideManagedTargetRoot(\n target: DeploymentTargetId,\n targetPath: string,\n targetRoots: Map<DeploymentTargetId, string>,\n explicitRootPath?: string,\n ): boolean {\n return [explicitRootPath, targetRoots.get(target)]\n .filter((value): value is string => Boolean(value))\n .some((rootPath) => isPathInside(rootPath, targetPath));\n }\n\n private async cleanupImportedTargetPaths(\n manifest: Manifest,\n lockFile: LockFile,\n sourceIds: string[],\n restrictedTargets?: DeploymentTargetId[],\n ): Promise<Warning[]> {\n const warnings: Warning[] = [];\n await this.ensureProjectionLedger(manifest, lockFile);\n const projections = (lockFile.projections ?? []).filter(\n (projection) =>\n projection.mode === \"bootstrap-imported\" &&\n sourceIds.includes(projection.sourceId) &&\n (restrictedTargets ? restrictedTargets.includes(projection.target) : true),\n );\n\n for (const projection of projections) {\n if (\n await pathExists(projection.targetPath) &&\n !this.isProjectionPathManaged(lockFile, projection)\n ) {\n warnings.push({\n code: \"IMPORTED_TARGET_PATH_INVALID\",\n message: `Refusing to remove unmanaged imported target path ${projection.targetPath}.`,\n });\n continue;\n }\n\n if (await pathExists(projection.targetPath)) {\n try {\n if (!this.hasPersistentProjectionOwnerForPath(lockFile, projection)) {\n await removePath(projection.targetPath);\n }\n } catch (error) {\n warnings.push({\n code: \"IMPORTED_TARGET_PATH_REMOVE_FAILED\",\n message: `Unable to remove imported target path ${projection.targetPath}: ${String(error)}`,\n });\n continue;\n }\n }\n\n lockFile.projections = (lockFile.projections ?? []).filter(\n (candidate) =>\n !(\n candidate.mode === \"bootstrap-imported\" &&\n candidate.sourceId === projection.sourceId &&\n candidate.leafId === projection.leafId &&\n candidate.target === projection.target\n ),\n );\n }\n\n return warnings;\n }\n\n private buildImportedTargetPathsForSource(\n manifest: Manifest,\n lockFile: LockFile,\n sourceId: string,\n target: DeploymentTargetId,\n rootPath: string,\n projectedLinkNames: Map<string, string>,\n ): Set<string> {\n const source = manifest.sources.find((item) => item.id === sourceId);\n if (!source) {\n return new Set();\n }\n\n const leafs = lockFile.leafInventory.filter((leaf) => leaf.sourceId === sourceId);\n const groupAuthor =\n getHostedGitOwner(source.locator)\n ?? (source.originLocator ? getHostedGitOwner(source.originLocator) : undefined);\n const candidatePaths = new Set<string>();\n\n for (const leaf of leafs) {\n const projectedLinkName = projectedLinkNames.get(leaf.id) ?? leaf.linkName;\n for (const name of buildProjectedSkillNameCandidates({\n preferredName: projectedLinkName,\n groupId: source.id,\n groupName: source.displayName,\n groupAuthor,\n skillName: leaf.linkName,\n })) {\n candidatePaths.add(path.join(rootPath, name));\n }\n }\n return candidatePaths;\n }\n\n private async ensureProjectionLedger(\n manifest: Manifest,\n lockFile: LockFile,\n ): Promise<void> {\n const targetRoots = await this.getTargetRootMap();\n const projectedNameCache = new Map<DeploymentTargetId, Map<string, string>>();\n const managed: ProjectionRecord[] = getManagedDeployments(lockFile).map((deployment) => ({\n ...deployment,\n mode: \"managed\",\n }));\n const previousBootstrap = (lockFile.projections ?? []).filter(\n (projection) => projection.mode === \"bootstrap-imported\",\n );\n const bootstrap: ProjectionRecord[] = [];\n\n for (const sourceLock of lockFile.sources) {\n const bootstrapTargets = getBootstrapImportedTargets(lockFile, sourceLock);\n if (sourceLock.importMode !== \"bootstrap-detected\" || bootstrapTargets.length === 0) {\n continue;\n }\n\n const leafs = lockFile.leafInventory.filter((leaf) => leaf.sourceId === sourceLock.id);\n const observedByTarget = new Map<DeploymentTargetId, {\n target: DeploymentTargetId;\n rootPath: string;\n targetPath: string;\n }>();\n for (const observed of sourceLock.observedTargets ?? []) {\n observedByTarget.set(observed.target, observed);\n }\n const targetEntries = [\n ...observedByTarget.values(),\n ...bootstrapTargets\n .filter((target) => !observedByTarget.has(target))\n .map((target) => ({ target, rootPath: targetRoots.get(target) ?? \"\", targetPath: \"\" })),\n ];\n\n for (const { target, rootPath: observedRootPath, targetPath: observedTargetPath } of targetEntries) {\n const rootPath = targetRoots.get(target);\n if (!rootPath) {\n continue;\n }\n\n let projectedLinkNames = projectedNameCache.get(target);\n if (!projectedLinkNames) {\n projectedLinkNames = this.buildProjectedLinkNameMap(manifest, lockFile, target);\n projectedNameCache.set(target, projectedLinkNames);\n }\n\n for (const leaf of leafs) {\n const previous = previousBootstrap.find(\n (projection) =>\n projection.sourceId === sourceLock.id &&\n projection.leafId === leaf.id &&\n projection.target === target,\n );\n const targetPath = await this.resolveBootstrapProjectionTargetPath(\n manifest,\n lockFile,\n sourceLock,\n leaf,\n rootPath,\n projectedLinkNames,\n observedRootPath === rootPath ? observedTargetPath : undefined,\n previous?.targetPath,\n );\n if (!targetPath) {\n continue;\n }\n bootstrap.push({\n sourceId: sourceLock.id,\n leafId: leaf.id,\n target,\n targetPath,\n targetRootPath: rootPath,\n strategy: \"symlink\",\n status: \"active\",\n contentHash: leaf.contentHash,\n appliedAt: sourceLock.updatedAt,\n mode: \"bootstrap-imported\",\n });\n }\n }\n }\n\n lockFile.projections = [...managed, ...bootstrap];\n }\n\n private async resolveBootstrapProjectionTargetPath(\n manifest: Manifest,\n _lockFile: LockFile,\n sourceLock: LockFile[\"sources\"][number],\n leaf: LeafRecord,\n rootPath: string,\n projectedLinkNames: Map<string, string>,\n observedTargetPath?: string,\n previousTargetPath?: string,\n ): Promise<string | undefined> {\n if (previousTargetPath && isPathInside(rootPath, previousTargetPath)) {\n return previousTargetPath;\n }\n\n if (observedTargetPath && isPathInside(rootPath, observedTargetPath)) {\n return observedTargetPath;\n }\n\n const scannedObservedTargetPath = await this.findObservedBootstrapTargetPath(\n sourceLock,\n rootPath,\n );\n if (scannedObservedTargetPath) {\n return scannedObservedTargetPath;\n }\n\n const source = manifest.sources.find((item) => item.id === sourceLock.id);\n const groupAuthor =\n getHostedGitOwner(source?.locator ?? \"\")\n ?? (source?.originLocator ? getHostedGitOwner(source.originLocator) : undefined);\n const projectedLinkName = projectedLinkNames.get(leaf.id) ?? leaf.linkName;\n const candidates = buildProjectedSkillNameCandidates({\n preferredName: projectedLinkName,\n groupId: sourceLock.id,\n groupName: source?.displayName ?? sourceLock.id,\n groupAuthor,\n skillName: leaf.linkName,\n }).map((name) => path.join(rootPath, name));\n\n for (const candidate of candidates) {\n if (await pathExists(candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n }\n\n private async findObservedBootstrapTargetPath(\n sourceLock: LockFile[\"sources\"][number],\n rootPath: string,\n ): Promise<string | undefined> {\n if (!(await pathExists(rootPath))) {\n return undefined;\n }\n\n const displayNamePath = path.join(rootPath, sourceLock.displayName);\n if (await pathExists(displayNamePath)) {\n return displayNamePath;\n }\n\n const observedRealpaths = new Set(\n [sourceLock.locator, sourceLock.checkoutPath]\n .filter((value): value is string => Boolean(value))\n .map((value) => path.resolve(value)),\n );\n const entries = await fs.readdir(rootPath, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n const candidatePath = path.join(rootPath, entry.name);\n const isDirectoryLike =\n entry.isDirectory() ||\n (entry.isSymbolicLink() &&\n (await fs.stat(candidatePath).then((stats) => stats.isDirectory()).catch(() => false)));\n if (!isDirectoryLike) {\n continue;\n }\n if (!(await pathExists(path.join(candidatePath, \"SKILL.md\")))) {\n continue;\n }\n const resolvedPath = await fs.realpath(candidatePath).catch(() => path.resolve(candidatePath));\n if (observedRealpaths.has(resolvedPath)) {\n return candidatePath;\n }\n }\n\n return undefined;\n }\n\n private isProjectionPathManaged(\n lockFile: LockFile,\n projection: ProjectionRecord,\n ): boolean {\n return Boolean(\n projection.targetRootPath &&\n isPathInside(projection.targetRootPath, projection.targetPath),\n );\n }\n\n private hasPersistentProjectionOwnerForPath(\n lockFile: LockFile,\n projection: ProjectionRecord,\n ): boolean {\n return (lockFile.projections ?? []).some(\n (candidate) =>\n candidate.targetPath === projection.targetPath &&\n !(\n candidate.mode === projection.mode &&\n candidate.sourceId === projection.sourceId &&\n candidate.leafId === projection.leafId &&\n candidate.target === projection.target\n ),\n );\n }\n\n private async persistNormalizedBindings(\n manifest: Manifest,\n lockFile: LockFile,\n ): Promise<void> {\n if (!this.normalizeBindings(manifest, lockFile)) {\n return;\n }\n\n await this.store.writeState(manifest, lockFile);\n }\n\n private async readManifestConsistently(): Promise<Manifest> {\n return this.runSerializedMutation(() => this.store.readManifest());\n }\n\n private async readStateConsistently(): Promise<{ manifest: Manifest; lockFile: LockFile }> {\n return this.runSerializedMutation(() => this.store.readState());\n }\n\n private async captureSourceAuditSnapshot(\n manifest: Manifest,\n lockFile: LockFile,\n sourceId: string,\n ): Promise<Record<string, unknown>> {\n const source = manifest.sources.find((item) => item.id === sourceId);\n const sourceLock = lockFile.sources.find((item) => item.id === sourceId);\n const binding = manifest.bindings[sourceId];\n const projections = (lockFile.projections ?? []).filter(\n (projection) => projection.sourceId === sourceId,\n );\n\n return {\n sourcePresent: Boolean(source),\n checkoutPath: sourceLock?.checkoutPath,\n checkoutExists: sourceLock ? await pathExists(sourceLock.checkoutPath) : false,\n selectedLeafIds: binding?.selectedLeafIds ?? [],\n enabledTargets: this.getEnabledTargetsForSource(manifest, sourceId),\n projectionCount: projections.length,\n projections: await Promise.all(\n projections.map(async (projection) => ({\n mode: projection.mode,\n target: projection.target,\n leafId: projection.leafId,\n targetPath: projection.targetPath,\n targetPathExists: await pathExists(projection.targetPath),\n })),\n ),\n };\n }\n\n private summarizeDeploymentActions(actions: DeploymentAction[]): Record<string, unknown> {\n return {\n total: actions.length,\n create: actions.filter((action) => action.kind === \"create\").length,\n update: actions.filter((action) => action.kind === \"update\").length,\n remove: actions.filter((action) => action.kind === \"remove\").length,\n noop: actions.filter((action) => action.kind === \"noop\").length,\n blocked: actions.filter((action) => action.kind === \"blocked\").length,\n };\n }\n\n private async runSerializedMutation<T>(task: () => Promise<T>): Promise<T> {\n const run = this.mutationQueue.then(\n () => this.store.withMutationLock(task),\n () => this.store.withMutationLock(task),\n );\n this.mutationQueue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n\n private async runAuditedMutation<T>(\n mutation: AuditMutationName,\n details: Record<string, unknown>,\n task: () => Promise<AuditedMutationResult<T>>,\n ): Promise<Result<T>> {\n try {\n const taskResult = await this.runSerializedMutation(task);\n const normalized = this.normalizeAuditedMutationResult(taskResult);\n const result = normalized.result;\n await this.writeAuditEvent({\n timestamp: new Date().toISOString(),\n mutation,\n caller: this.currentAuditCaller(),\n status: result.ok ? \"ok\" : \"error\",\n details: {\n ...details,\n ...(normalized.auditDetails ?? {}),\n },\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n errors: result.ok\n ? []\n : result.errors.map((error) => ({\n code: error.code,\n message: error.message,\n })),\n });\n return result;\n } catch (error) {\n await this.writeAuditEvent({\n timestamp: new Date().toISOString(),\n mutation,\n caller: this.currentAuditCaller(),\n status: \"threw\",\n details,\n warnings: [],\n errors: [{\n code: \"UNCAUGHT_EXCEPTION\",\n message: error instanceof Error ? error.message : String(error),\n }],\n });\n throw error;\n }\n }\n\n private normalizeAuditedMutationResult<T>(\n taskResult: AuditedMutationResult<T>,\n ): { result: Result<T>; auditDetails?: Record<string, unknown> } {\n if (\"ok\" in taskResult) {\n return { result: taskResult };\n }\n\n return taskResult;\n }\n\n private currentAuditCaller(): string {\n return process.env.SKILL_FLOW_CALLER?.trim()\n ?? \"unknown\";\n }\n\n private async writeAuditEvent(event: AuditEvent): Promise<void> {\n try {\n const store = this.store as StateStore & {\n appendAuditEvent?: (entry: AuditEvent) => Promise<void>;\n };\n await store.appendAuditEvent?.(event);\n } catch {\n // Audit logging must never block the mutation itself.\n }\n }\n\n private normalizeBindings(manifest: Manifest, lockFile: LockFile): boolean {\n let changed = false;\n\n for (const source of manifest.sources) {\n const currentBinding = manifest.bindings[source.id] ?? { targets: {} };\n const normalizedDraft = this.draftFromBinding(source.id, currentBinding, lockFile);\n const normalizedBinding = this.bindingFromDraft(normalizedDraft);\n\n if (JSON.stringify(currentBinding) === JSON.stringify(normalizedBinding)) {\n continue;\n }\n\n manifest.bindings[source.id] = normalizedBinding;\n changed = true;\n }\n\n return changed;\n }\n\n private draftFromBinding(\n sourceId: string,\n binding: SourceBinding,\n lockFile: LockFile,\n ): DraftBinding {\n const leafIds = new Set(\n lockFile.leafInventory\n .filter((leaf) => leaf.sourceId === sourceId)\n .map((leaf) => leaf.id),\n );\n const enabledTargets = Object.entries(binding.targets)\n .filter(([, targetBinding]) => targetBinding?.enabled)\n .map(([target]) => target) as DeploymentTargetName[];\n const selectedLeafIds = [\n ...new Set(\n (binding.selectedLeafIds && binding.selectedLeafIds.length > 0\n ? binding.selectedLeafIds\n : enabledTargets.flatMap((target) => binding.targets[target]?.leafIds ?? [])),\n ),\n ].filter((leafId) => leafIds.has(leafId));\n\n return {\n enabledTargets,\n selectedLeafIds,\n };\n }\n\n private selectLeafIdsForRequestedPath(\n leafs: LeafRecord[],\n requestedPath?: string,\n ): string[] {\n const normalizedPath = this.normalizeRequestedPath(requestedPath);\n if (!normalizedPath) {\n return leafs.map((leaf) => leaf.id);\n }\n\n return leafs\n .filter(\n (leaf) =>\n leaf.relativePath === normalizedPath ||\n leaf.relativePath.startsWith(`${normalizedPath}/`),\n )\n .map((leaf) => leaf.id);\n }\n\n private buildAddDraft(\n sourceLeafs: LeafRecord[],\n requestedPath: string | undefined,\n availableTargets: DeploymentTargetId[],\n options: SkillFlowAddOptions,\n ): Result<DraftBinding> {\n if (options.draft) {\n return ok({\n enabledTargets: [...new Set(options.draft.enabledTargets)],\n selectedLeafIds: [...new Set(options.draft.selectedLeafIds)],\n });\n }\n\n const selectedLeafIdsResult = this.resolveSelectedLeafIds(\n sourceLeafs,\n requestedPath,\n options.skillNames,\n );\n if (!selectedLeafIdsResult.ok) {\n return fail(selectedLeafIdsResult.errors, selectedLeafIdsResult.warnings);\n }\n\n const enabledTargetsResult = this.resolveRequestedTargets(\n availableTargets,\n options.agentTargets ?? options.enabledTargets,\n );\n if (!enabledTargetsResult.ok) {\n return fail(enabledTargetsResult.errors, enabledTargetsResult.warnings);\n }\n\n return ok({\n enabledTargets: enabledTargetsResult.data,\n selectedLeafIds: selectedLeafIdsResult.data,\n });\n }\n\n private resolveImportDraftForPreparedSource(\n sourceLeafs: LeafRecord[],\n availableTargets: DeploymentTargetId[],\n canonicalRepo: string | undefined,\n draft?: ImportDraft,\n ): Result<DraftBinding> {\n if (!draft) {\n return ok({\n selectedLeafIds: sourceLeafs.map((leaf) => leaf.id),\n enabledTargets: [],\n });\n }\n\n const selectedLeafIdsResult = canonicalRepo\n ? this.resolveImportLeafIdsForGitHubSource(\n sourceLeafs,\n draft.selectedSkillIds,\n canonicalRepo,\n )\n : this.resolveSelectedLeafIds(\n sourceLeafs,\n undefined,\n draft.selectedSkillIds,\n canonicalRepo,\n );\n if (!selectedLeafIdsResult.ok) {\n return fail(selectedLeafIdsResult.errors, selectedLeafIdsResult.warnings);\n }\n\n const available = new Set(availableTargets);\n const unsupported = [...new Set(draft.enabledTargets)].filter((target) => !available.has(target));\n if (unsupported.length > 0) {\n return fail({\n code: \"ADD_AGENT_NOT_AVAILABLE\",\n message: `Unknown or unavailable agent(s): ${unsupported.join(\", \")}.`,\n });\n }\n\n return ok({\n selectedLeafIds: selectedLeafIdsResult.data,\n enabledTargets: [...new Set(draft.enabledTargets)],\n }, selectedLeafIdsResult.warnings);\n }\n\n private resolveImportLeafIdsForGitHubSource(\n sourceLeafs: LeafRecord[],\n skillNames: string[],\n canonicalRepo: string,\n ): Result<string[]> {\n const requested = [...new Set(skillNames.map((skillName) => skillName.trim()).filter(Boolean))];\n const matchedLeafIds: string[] = [];\n const skippedSkillIds: string[] = [];\n const warnings: Warning[] = [];\n\n for (const selector of requested) {\n const selectedLeafIdsResult = this.resolveSelectedLeafIds(\n sourceLeafs,\n undefined,\n [selector],\n canonicalRepo,\n );\n\n if (selectedLeafIdsResult.ok) {\n matchedLeafIds.push(...selectedLeafIdsResult.data);\n continue;\n }\n\n const firstError = selectedLeafIdsResult.errors[0];\n if (firstError?.code !== \"ADD_SKILL_NOT_FOUND\") {\n return fail(selectedLeafIdsResult.errors, selectedLeafIdsResult.warnings);\n }\n\n skippedSkillIds.push(selector);\n }\n\n if (matchedLeafIds.length === 0 && requested.length > 0) {\n return fail({\n code: \"ADD_SKILL_NOT_FOUND\",\n message: `Unable to preselect skill(s): ${requested.join(\", \")}.`,\n });\n }\n\n if (skippedSkillIds.length > 0) {\n warnings.push({\n code: \"IMPORT_SKILL_SKIPPED\",\n message:\n `Ignored ${skippedSkillIds.length} skill selector` +\n `${skippedSkillIds.length === 1 ? \"\" : \"s\"} not present in the GitHub repo: ` +\n skippedSkillIds.join(\", \"),\n });\n }\n\n return ok([...new Set(matchedLeafIds)], warnings);\n }\n\n private resolveSelectedLeafIds(\n sourceLeafs: LeafRecord[],\n requestedPath: string | undefined,\n skillNames?: string[],\n canonicalRepo?: string,\n ): Result<string[]> {\n if (!skillNames || skillNames.length === 0) {\n return ok(this.selectLeafIdsForRequestedPath(sourceLeafs, requestedPath));\n }\n\n const requested = [...new Set(skillNames.map((skillName) => skillName.trim()).filter(Boolean))];\n const matchedLeafIds: string[] = [];\n\n for (const selector of requested) {\n const relativePathMatches = sourceLeafs.filter((leaf) => leaf.relativePath === selector);\n if (relativePathMatches.length === 1) {\n matchedLeafIds.push(relativePathMatches[0]!.id);\n continue;\n }\n if (relativePathMatches.length > 1) {\n return fail({\n code: \"ADD_SKILL_SELECTOR_AMBIGUOUS\",\n message: `Skill selector '${selector}' is ambiguous. Use a unique relative path.`,\n });\n }\n\n const fallbackMatches = sourceLeafs.filter((leaf) => {\n if (leaf.linkName === selector || leaf.name === selector) {\n return true;\n }\n\n if (!canonicalRepo) {\n return false;\n }\n\n // skills.sh can prefix repo skill ids, for example `vercel-react-best-practices`,\n // while the GitHub checkout still uses the real directory name `react-best-practices`.\n // Keep the preview data unchanged for the UI, but accept those prefixed ids here so\n // the actual import still resolves against the GitHub checkout.\n const selectorVariants = this.buildImportSkillSelectorVariants(selector, canonicalRepo);\n const leafVariants = new Set([\n ...this.buildImportSkillSelectorVariants(leaf.linkName, canonicalRepo),\n ...this.buildImportSkillSelectorVariants(leaf.name, canonicalRepo),\n ...this.buildImportSkillSelectorVariants(path.posix.basename(leaf.relativePath), canonicalRepo),\n ]);\n\n return selectorVariants.some((variant) => leafVariants.has(variant));\n });\n if (fallbackMatches.length === 1) {\n matchedLeafIds.push(fallbackMatches[0]!.id);\n continue;\n }\n if (fallbackMatches.length > 1) {\n if (canonicalRepo) {\n const preferred = this.pickPreferredImportLeafMatch(fallbackMatches);\n if (preferred) {\n matchedLeafIds.push(preferred.id);\n continue;\n }\n }\n\n return fail({\n code: \"ADD_SKILL_SELECTOR_AMBIGUOUS\",\n message:\n `Skill selector '${selector}' is ambiguous. ` +\n `Use a relative path such as '${fallbackMatches[0]!.relativePath}'.`,\n });\n }\n\n return fail({\n code: \"ADD_SKILL_NOT_FOUND\",\n message: `Unable to preselect skill(s): ${selector}.`,\n });\n }\n\n return ok([...new Set(matchedLeafIds)]);\n }\n\n private resolveRequestedTargets(\n availableTargets: DeploymentTargetId[],\n requestedTargets?: DeploymentTargetId[],\n ): Result<DeploymentTargetId[]> {\n if (!requestedTargets?.length) {\n return ok([...availableTargets]);\n }\n\n const available = new Set(availableTargets);\n const unsupported = [...new Set(requestedTargets)].filter((target) => !available.has(target));\n if (unsupported.length > 0) {\n return fail({\n code: \"ADD_AGENT_NOT_AVAILABLE\",\n message: `Unknown or unavailable agent(s): ${unsupported.join(\", \")}.`,\n });\n }\n\n return ok([...new Set(requestedTargets)]);\n }\n\n private normalizeRequestedPath(requestedPath?: string): string | undefined {\n if (!requestedPath) {\n return undefined;\n }\n\n const normalized = requestedPath.trim().replace(/^\\.\\/+/, \"\").replace(/\\/+$/, \"\");\n return normalized.length > 0 && normalized !== \".\" ? normalized : undefined;\n }\n\n private async rollbackPreparedSourceInternal(\n sourceId: string,\n ): Promise<Result<{ removed: string[] }>> {\n const { lockFile, manifest } = await this.store.readState();\n if (!manifest.sources.some((source) => source.id === sourceId)) {\n return fail({\n code: \"SOURCE_NOT_FOUND\",\n message: `Skills group id '${sourceId}' is not registered.`,\n });\n }\n\n if (getManagedDeployments(lockFile).some((deployment) => deployment.sourceId === sourceId)) {\n return fail({\n code: \"ADD_ROLLBACK_HAS_DEPLOYMENTS\",\n message: `Unable to roll back skills group id '${sourceId}' because deployments already exist.`,\n });\n }\n\n await this.cleanupDetachedTargetSymlinksForSources(lockFile, [sourceId]);\n await this.cleanupOrphanTargetSymlinks(lockFile);\n await this.store.writeState(manifest, lockFile);\n\n return this.sourceService.removeSource([sourceId]);\n }\n\n private prepareManifestForDraft(\n manifest: Manifest,\n lockFile: LockFile,\n sourceId: string,\n draft: DraftBinding,\n ): { manifest: Manifest; draft: DraftBinding; warnings: Warning[] } {\n manifest.bindings[sourceId] = this.bindingFromDraft(draft);\n const source = manifest.sources.find((item) => item.id === sourceId);\n if (source) {\n const sourceLeafCount = lockFile.leafInventory.filter((leaf) => leaf.sourceId === sourceId).length;\n source.selectionMode =\n draft.selectedLeafIds.length >= sourceLeafCount && sourceLeafCount > 0\n ? \"all\"\n : \"partial\";\n }\n\n const conflictingLeafIds = this.findExactDuplicateLeafSelections(\n manifest,\n lockFile,\n sourceId,\n draft.enabledTargets,\n );\n const normalizedDraft: DraftBinding = {\n enabledTargets: [...draft.enabledTargets],\n selectedLeafIds: draft.selectedLeafIds.filter((leafId) => !conflictingLeafIds.has(leafId)),\n };\n manifest.bindings[sourceId] = this.bindingFromDraft(normalizedDraft);\n\n const warnings = [...conflictingLeafIds].map((leafId) => ({\n code: \"DUPLICATE_LEAF_SELECTION_SKIPPED\",\n message: `${lockFile.leafInventory.find((leaf) => leaf.id === leafId)?.linkName ?? leafId} skipped because an identical skill is already selected in another skills group.`,\n }));\n\n return {\n manifest,\n draft: normalizedDraft,\n warnings,\n };\n }\n\n private findExactDuplicateLeafSelections(\n manifest: Manifest,\n lockFile: LockFile,\n currentSourceId: string,\n enabledTargets: DeploymentTargetId[],\n ): Set<string> {\n const conflictingKeys = new Set<string>();\n\n for (const source of manifest.sources) {\n if (source.id === currentSourceId) {\n continue;\n }\n\n const binding = manifest.bindings[source.id];\n if (!binding) {\n continue;\n }\n\n for (const target of enabledTargets) {\n const targetBinding = binding.targets[target];\n if (!targetBinding?.enabled) {\n continue;\n }\n\n for (const leafId of targetBinding.leafIds) {\n const leaf = lockFile.leafInventory.find((item) => item.id === leafId);\n if (!leaf) {\n continue;\n }\n conflictingKeys.add(this.getExactDuplicateKey(leaf));\n }\n }\n }\n\n const currentLeafs = lockFile.leafInventory.filter((leaf) => leaf.sourceId === currentSourceId);\n return new Set(\n currentLeafs\n .filter((leaf) => conflictingKeys.has(this.getExactDuplicateKey(leaf)))\n .map((leaf) => leaf.id),\n );\n }\n\n private getExactDuplicateKey(leaf: LeafRecord): string {\n return `${leaf.linkName}\\n${leaf.name}\\n${leaf.description}`;\n }\n\n private async planForAffectedSources(\n manifest: Manifest,\n lockFile: LockFile,\n primarySourceId: string,\n ): Promise<Result<DeploymentPlan>> {\n await this.refreshAdapters();\n const sourceIds = manifest.sources\n .map((source) => source.id)\n .filter((sourceId) => sourceId === primarySourceId || this.hasActiveTargets(manifest, sourceId));\n\n return this.planForSources(manifest, lockFile, sourceIds);\n }\n\n private async planForSources(\n manifest: Manifest,\n lockFile: LockFile,\n sourceIds: string[],\n ): Promise<Result<DeploymentPlan>> {\n const uniqueSourceIds = [...new Set(sourceIds)];\n\n const actions: DeploymentAction[] = [];\n const warnings: Warning[] = [];\n\n for (const sourceId of uniqueSourceIds) {\n const plan = await this.planner.planForSource(sourceId, manifest, lockFile);\n if (!plan.ok) {\n return fail(plan.errors, [...warnings, ...plan.warnings]);\n }\n\n actions.push(...plan.data.actions);\n warnings.push(...plan.warnings);\n }\n\n return ok({\n actions,\n warnings,\n blocked: actions.filter((action) => action.kind === \"blocked\"),\n }, warnings);\n }\n\n // Project-local path application happens here: scope resolves to concrete target roots\n // before planner/applier mutate the filesystem.\n private async resolveProjectTargetRoots(\n scope: Extract<ProjectScope, { kind: \"project\" }>,\n targets: DeploymentTargetId[],\n ): Promise<Result<TargetRootOverrides>> {\n const preferences = await this.store.readPreferences();\n const projectPath = await resolveUsableProjectPath(preferences.recentProjects.find(\n (project) => project.projectId === scope.projectId,\n )?.projectPath);\n if (!projectPath) {\n await this.removeUnavailableProjectScope(scope.projectId, preferences);\n return fail({\n code: \"PROJECT_SCOPE_PATH_UNAVAILABLE\",\n message: `Project scope '${scope.projectId}' is unavailable because its projectPath is missing or invalid, so project-local skills cannot be mounted.`,\n });\n }\n\n const overrides: TargetRootOverrides = {};\n const mergedTargets = getMergedTargetDefinitions(\n preferences.customTargets,\n preferences.agentDisplayOrder,\n );\n for (const target of [...new Set(targets)]) {\n const mergedTarget = mergedTargets.find((candidate) => candidate.id === target);\n const resolvedPath = mergedTarget?.kind === \"builtin\"\n ? resolveDocumentedProjectSkillPath(target as DeploymentTargetName, projectPath)\n : mergedTarget?.projectPathTemplate\n ? path.join(projectPath, mergedTarget.projectPathTemplate)\n : null;\n if (!resolvedPath) {\n return fail({\n code: \"PROJECT_SCOPE_PATH_UNAVAILABLE\",\n message: `Target '${target}' does not expose a documented project-local skill path for project '${scope.projectId}'.`,\n });\n }\n overrides[target] = resolvedPath;\n }\n\n return ok(overrides);\n }\n\n private async removeUnavailableProjectScope(\n projectId: string,\n preferences?: SharedPreferences,\n ): Promise<void> {\n const currentPreferences = preferences ?? await this.store.readPreferences();\n if (\n !currentPreferences.recentProjects.some((project) => project.projectId === projectId) &&\n !(projectId in currentPreferences.projectDrafts) &&\n !(\n currentPreferences.selectedProjectScope.kind === \"project\" &&\n currentPreferences.selectedProjectScope.projectId === projectId\n )\n ) {\n return;\n }\n\n const { [projectId]: _removedDrafts, ...remainingProjectDrafts } = currentPreferences.projectDrafts;\n await this.store.writePreferences({\n ...currentPreferences,\n selectedProjectScope:\n currentPreferences.selectedProjectScope.kind === \"project\" &&\n currentPreferences.selectedProjectScope.projectId === projectId\n ? { kind: \"global\" }\n : currentPreferences.selectedProjectScope,\n recentProjects: currentPreferences.recentProjects.filter(\n (project) => project.projectId !== projectId,\n ),\n projectDrafts: remainingProjectDrafts,\n });\n }\n\n private cloneLockFileForScopedDeployments(\n lockFile: LockFile,\n deployments: LockFile[\"deployments\"],\n ): LockFile {\n return {\n ...lockFile,\n sources: lockFile.sources.map((source) => ({\n ...source,\n ...(source.observedTargets\n ? { observedTargets: source.observedTargets.map((entry) => ({ ...entry })) }\n : {}),\n })),\n leafInventory: lockFile.leafInventory.map((leaf) => ({ ...leaf })),\n deployments: deployments.map((deployment) => ({ ...deployment })),\n projections: deployments.map((deployment) => ({\n ...deployment,\n mode: \"managed\" as const,\n })),\n };\n }\n\n private async resolveScopedInspectDeployments(\n manifest: Manifest,\n lockFile: LockFile,\n sourceId: string,\n scope: Extract<ProjectScope, { kind: \"project\" }>,\n targets: DeploymentTargetId[],\n ): Promise<LockFile[\"deployments\"]> {\n const targetRootOverrides = await this.resolveProjectTargetRoots(scope, targets);\n if (!targetRootOverrides.ok) {\n return [];\n }\n\n return this.findScopedDeploymentsOnDisk(\n manifest,\n lockFile,\n sourceId,\n targetRootOverrides.data,\n );\n }\n\n private async findScopedDeploymentsOnDisk(\n manifest: Manifest,\n lockFile: LockFile,\n sourceId: string,\n targetRootOverrides: TargetRootOverrides,\n ): Promise<LockFile[\"deployments\"]> {\n const source = manifest.sources.find((item) => item.id === sourceId);\n if (!source) {\n return [];\n }\n\n const binding = manifest.bindings[sourceId] ?? { targets: {} };\n const scopedDeployments: LockFile[\"deployments\"] = [];\n const adapters = await this.refreshAdapters();\n\n for (const [target, rootPath] of Object.entries(targetRootOverrides) as Array<[DeploymentTargetId, string]>) {\n const targetBinding = binding.targets[target];\n if (!targetBinding?.enabled) {\n continue;\n }\n\n const adapter = adapters.find((candidate) => candidate.target === target);\n if (!adapter) {\n continue;\n }\n\n const projectedLinkNames = this.buildProjectedLinkNameMap(manifest, lockFile, target);\n for (const leafId of targetBinding.leafIds) {\n const leaf = lockFile.leafInventory.find(\n (candidate) => candidate.sourceId === sourceId && candidate.id === leafId,\n );\n if (!leaf) {\n continue;\n }\n\n const deployment = await this.findManagedDeploymentOnDisk(\n source,\n leaf,\n target,\n adapter.strategy,\n rootPath,\n projectedLinkNames,\n );\n if (deployment) {\n scopedDeployments.push(deployment);\n }\n }\n }\n\n return scopedDeployments;\n }\n\n private async withScopedTargetRoots<T>(\n targetRootOverrides: TargetRootOverrides,\n operation: () => Promise<T>,\n ): Promise<T> {\n const adapters = await this.refreshAdapters();\n const restores = adapters.map((adapter) => {\n const overrideRootPath = targetRootOverrides[adapter.target]?.trim();\n if (!overrideRootPath) {\n return () => {};\n }\n\n const originalDetect = adapter.detect.bind(adapter);\n adapter.detect = async () => {\n const detection = await originalDetect();\n return {\n ...detection,\n available: true,\n rootPath: overrideRootPath,\n };\n };\n\n return () => {\n adapter.detect = originalDetect;\n };\n });\n\n try {\n return await operation();\n } finally {\n for (const restore of restores.reverse()) {\n restore();\n }\n }\n }\n\n private async planAndApplySources(\n manifest: Manifest,\n lockFile: LockFile,\n sourceIds: string[],\n ): Promise<Result<{ actions: DeploymentAction[] }>> {\n await this.refreshAdapters();\n const planned = await this.planForSources(manifest, lockFile, sourceIds);\n if (!planned.ok) {\n return fail(planned.errors, planned.warnings);\n }\n\n const applyResult = await this.applier.applyPlan(lockFile, planned.data.actions);\n if (!applyResult.ok) {\n return fail(applyResult.errors, [...planned.warnings, ...applyResult.warnings]);\n }\n\n return ok(\n { actions: planned.data.actions },\n [...planned.warnings, ...applyResult.warnings],\n );\n }\n\n private async rebuildDeploymentState(\n manifest: Manifest,\n lockFile: LockFile,\n sourceIds?: string[],\n ): Promise<number> {\n const requested = sourceIds?.length ? new Set(sourceIds) : undefined;\n const previousDeployments = getManagedDeployments(lockFile);\n const previousCount = previousDeployments.length;\n const previousByKey = new Map(\n previousDeployments.map((deployment) => [\n this.getDeploymentKey(deployment.sourceId, deployment.leafId, deployment.target),\n deployment,\n ]),\n );\n const nextDeployments = previousDeployments.filter(\n (deployment) => requested ? !requested.has(deployment.sourceId) : false,\n );\n const preferences = await this.store.readPreferences();\n const adapters = createChannelAdapters(\n getMergedTargetDefinitions(preferences.customTargets, preferences.agentDisplayOrder),\n );\n const detectionCache = new Map<\n DeploymentTargetId,\n Awaited<ReturnType<(typeof adapters)[number][\"detect\"]>>\n >();\n const projectedNameCache = new Map<DeploymentTargetId, Map<string, string>>();\n\n for (const source of manifest.sources) {\n if (requested && !requested.has(source.id)) {\n continue;\n }\n\n const binding = manifest.bindings[source.id] ?? { targets: {} };\n for (const adapter of adapters) {\n const targetBinding = binding.targets[adapter.target];\n if (!targetBinding?.enabled) {\n continue;\n }\n\n let detection = detectionCache.get(adapter.target);\n if (!detection) {\n detection = await adapter.detect();\n detectionCache.set(adapter.target, detection);\n }\n\n for (const leafId of targetBinding.leafIds) {\n const leaf = lockFile.leafInventory.find(\n (candidate) => candidate.sourceId === source.id && candidate.id === leafId,\n );\n if (!leaf) {\n continue;\n }\n\n const existing = previousByKey.get(\n this.getDeploymentKey(source.id, leaf.id, adapter.target),\n );\n if (!detection.available) {\n if (existing) {\n nextDeployments.push({\n ...existing,\n contentHash: leaf.contentHash,\n status: \"active\",\n });\n }\n continue;\n }\n\n let projectedLinkNames = projectedNameCache.get(adapter.target);\n if (!projectedLinkNames) {\n projectedLinkNames = this.buildProjectedLinkNameMap(\n manifest,\n lockFile,\n adapter.target,\n );\n projectedNameCache.set(adapter.target, projectedLinkNames);\n }\n\n const rebuilt = await this.findManagedDeploymentOnDisk(\n source,\n leaf,\n adapter.target,\n adapter.strategy,\n detection.rootPath,\n projectedLinkNames,\n existing,\n );\n if (!rebuilt) {\n continue;\n }\n\n nextDeployments.push(rebuilt);\n }\n }\n }\n\n const bootstrapProjections = (lockFile.projections ?? []).filter(\n (projection) => projection.mode === \"bootstrap-imported\",\n );\n lockFile.projections = [\n ...bootstrapProjections,\n ...nextDeployments.map((deployment) => ({\n ...deployment,\n mode: \"managed\" as const,\n })),\n ];\n return Math.max(0, previousCount - nextDeployments.length);\n }\n\n private buildProjectedLinkNameMap(\n manifest: Manifest,\n lockFile: LockFile,\n target: DeploymentTargetId,\n ): Map<string, string> {\n return resolveProjectedSkillNames(\n manifest.sources.flatMap((source) => {\n const targetBinding = manifest.bindings[source.id]?.targets[target];\n if (!targetBinding?.enabled) {\n return [];\n }\n\n return targetBinding.leafIds\n .map((leafId) => lockFile.leafInventory.find((leaf) => leaf.id === leafId))\n .filter((leaf): leaf is LeafRecord => Boolean(leaf))\n .map((leaf) => ({\n leafId: leaf.id,\n groupId: source.id,\n groupName: source.displayName,\n groupAuthor: getHostedGitOwner(source.locator),\n skillName: leaf.linkName,\n }));\n }),\n );\n }\n\n private async findManagedDeploymentOnDisk(\n source: Manifest[\"sources\"][number],\n leaf: LeafRecord,\n target: DeploymentTargetId,\n strategy: \"symlink\" | \"copy\",\n rootPath: string,\n projectedLinkNames: Map<string, string>,\n existing?: LockFile[\"deployments\"][number],\n ): Promise<LockFile[\"deployments\"][number] | undefined> {\n const projectedLinkName = projectedLinkNames.get(leaf.id) ?? leaf.linkName;\n const candidatePaths = buildProjectedSkillNameCandidates({\n preferredName: projectedLinkName,\n groupId: source.id,\n groupName: source.displayName,\n groupAuthor: getHostedGitOwner(source.locator),\n skillName: leaf.linkName,\n }).map((name) => path.join(rootPath, name));\n\n if (existing?.targetPath && !candidatePaths.includes(existing.targetPath)) {\n candidatePaths.unshift(existing.targetPath);\n }\n\n for (const targetPath of candidatePaths) {\n const matches = await this.matchesManagedProjection(strategy, targetPath, leaf);\n if (!matches) {\n continue;\n }\n\n return {\n sourceId: source.id,\n leafId: leaf.id,\n target,\n targetPath,\n targetRootPath:\n targetPath === existing?.targetPath && existing.targetRootPath\n ? existing.targetRootPath\n : rootPath,\n strategy,\n status: \"active\",\n contentHash: leaf.contentHash,\n appliedAt: existing?.appliedAt ?? new Date().toISOString(),\n };\n }\n\n return undefined;\n }\n\n private async matchesManagedProjection(\n strategy: \"symlink\" | \"copy\",\n targetPath: string,\n leaf: LeafRecord,\n ): Promise<boolean> {\n try {\n const stats = await fs.lstat(targetPath);\n if (strategy === \"symlink\") {\n if (!stats.isSymbolicLink()) {\n return false;\n }\n const linked = await fs.readlink(targetPath);\n const resolved = path.resolve(path.dirname(targetPath), linked);\n return resolved === leaf.absolutePath;\n }\n\n if (!stats.isDirectory()) {\n return false;\n }\n const onDiskHash = await hashDirectory(targetPath);\n return onDiskHash === leaf.contentHash;\n } catch {\n return false;\n }\n }\n\n private getDeploymentKey(\n sourceId: string,\n leafId: string,\n target: DeploymentTargetId,\n ) {\n return `${sourceId}\\n${leafId}\\n${target}`;\n }\n\n private hasActiveTargets(manifest: Manifest, sourceId: string): boolean {\n const binding = manifest.bindings[sourceId];\n if (!binding) {\n return false;\n }\n\n return Object.values(binding.targets).some((target) => target?.enabled);\n }\n\n private buildLocalCandidates(\n query: string,\n manifest: Manifest,\n lockFile: LockFile,\n ): SkillCandidate[] {\n return lockFile.leafInventory\n .filter((leaf) => {\n const source = manifest.sources.find((item) => item.id === leaf.sourceId);\n return this.matchesQuery(query, [\n leaf.name,\n leaf.title,\n leaf.relativePath.split(\"/\").pop() ?? \"\",\n ]);\n })\n .map((leaf) => {\n const source = manifest.sources.find((item) => item.id === leaf.sourceId);\n return {\n id: `local:${leaf.id}`,\n title: this.getCandidateTitle(leaf),\n description: leaf.description,\n source: \"local\",\n sourceLabel: source\n ? this.formatSourceLabel(source.locator, source.displayName)\n : leaf.sourceId,\n sourceId: leaf.sourceId,\n sourceKind: source?.kind ?? \"git\",\n locator: source?.locator ?? leaf.sourceId,\n relativePath: leaf.relativePath,\n installed: true,\n action: { type: \"none\" },\n } satisfies SkillCandidate;\n });\n }\n\n private async searchBuiltinGitSource(\n locator: string,\n branch: string,\n sourceId: string,\n displayName: string,\n query: string,\n ): Promise<{ candidates: SkillCandidate[]; warnings: Warning[] }> {\n const checkoutPath = this.store.getCatalogCheckoutPath(sourceId);\n if (await pathExists(checkoutPath)) {\n const scanned = await this.inventoryService.scanSource(sourceId, checkoutPath, displayName);\n return {\n candidates: scanned.leafs\n .filter((leaf) =>\n this.matchesQuery(query, [\n leaf.name,\n leaf.relativePath.split(\"/\").pop() ?? \"\",\n ]),\n )\n .map((leaf) => ({\n id: `builtin-git:${leaf.id}`,\n title: leaf.relativePath === \".\" ? displayName : leaf.relativePath.split(\"/\").pop() ?? displayName,\n description: leaf.relativePath,\n source: \"builtin-git\",\n sourceLabel: this.formatSourceLabel(locator, displayName),\n sourceId,\n sourceKind: \"git\",\n locator,\n relativePath: leaf.relativePath,\n installed: false,\n action: {\n type: \"add-git\",\n locator,\n requestedPath: leaf.relativePath,\n },\n })),\n warnings: [],\n };\n }\n\n const builtinCatalog = await this.getBuiltinCatalogSkillPaths(locator, branch, sourceId);\n const skillPaths = builtinCatalog.skillPaths;\n const matchedPaths = skillPaths\n .filter((skillFilePath) =>\n this.matchesQuery(query, [\n skillFilePath.replace(/\\/SKILL\\.md$/, \"\").split(\"/\").pop() ?? \"\",\n ]),\n )\n .slice(0, 5);\n\n return {\n candidates: matchedPaths.map((skillFilePath) => {\n const relativePath = skillFilePath.replace(/\\/SKILL\\.md$/, \"\").replace(/^SKILL\\.md$/, \".\");\n const title =\n relativePath === \".\" ? displayName : relativePath.split(\"/\").pop() ?? displayName;\n\n return {\n id: `builtin-git:${sourceId}:${relativePath}`,\n title,\n description: relativePath,\n source: \"builtin-git\",\n sourceLabel: this.formatSourceLabel(locator, displayName),\n sourceId,\n sourceKind: \"git\",\n locator,\n relativePath,\n installed: false,\n action: {\n type: \"add-git\",\n locator,\n requestedPath: relativePath,\n },\n };\n }),\n warnings: builtinCatalog.warnings,\n };\n }\n\n private async getBuiltinCatalogSkillPaths(\n locator: string,\n branch: string,\n sourceId: string,\n ): Promise<{ skillPaths: string[]; warnings: Warning[] }> {\n const indexPath = this.store.getCatalogIndexPath(sourceId);\n const cached = await readJsonFile<{ skillPaths?: string[]; updatedAt?: string }>(indexPath, {});\n const cachedSkillPaths = cached.skillPaths ?? [];\n const cachedUpdatedAt = cached.updatedAt ? Date.parse(cached.updatedAt) : Number.NaN;\n const cacheFresh =\n cachedSkillPaths.length > 0 &&\n Number.isFinite(cachedUpdatedAt) &&\n Date.now() - cachedUpdatedAt < 1000 * 60 * 60 * 6;\n\n if (cacheFresh) {\n return { skillPaths: cachedSkillPaths, warnings: [] };\n }\n\n try {\n const skillPaths = await fetchGitHubSkillPaths(locator, branch);\n await ensureDir(this.store.catalogRoot);\n await writeJsonFile(indexPath, {\n locator,\n branch,\n skillPaths,\n updatedAt: new Date().toISOString(),\n });\n return { skillPaths, warnings: [] };\n } catch (error) {\n if (cachedSkillPaths.length > 0) {\n return {\n skillPaths: cachedSkillPaths,\n warnings: [\n {\n code: \"BUILTIN_SOURCE_STALE_CACHE_USED\",\n message: `Unable to refresh built-in source '${locator}', using stale cached catalog: ${String(error)}`,\n },\n ],\n };\n }\n throw error;\n }\n }\n\n private matchesQuery(query: string, fields: string[]): boolean {\n const tokens = query.split(/\\s+/).filter(Boolean);\n if (tokens.length === 0) {\n return true;\n }\n\n const haystack = this.normalizeSearchQuery(fields.join(\"\\n\"));\n return tokens.every((token) => haystack.includes(token));\n }\n\n private compareCandidates(\n left: SkillCandidate,\n right: SkillCandidate,\n query: string,\n ): number {\n const sourceRank = this.getSourceRank(left.source) - this.getSourceRank(right.source);\n if (sourceRank !== 0) {\n return sourceRank;\n }\n\n const leftScore = this.getQueryScore(left, query);\n const rightScore = this.getQueryScore(right, query);\n if (leftScore !== rightScore) {\n return rightScore - leftScore;\n }\n\n const leftPath = left.relativePath ?? \"\";\n const rightPath = right.relativePath ?? \"\";\n return (\n left.title.localeCompare(right.title) ||\n left.sourceLabel.localeCompare(right.sourceLabel) ||\n leftPath.localeCompare(rightPath)\n );\n }\n\n private getSourceRank(source: SkillCandidate[\"source\"]): number {\n if (source === \"local\") {\n return 0;\n }\n if (source === \"builtin-git\") {\n return 1;\n }\n return 2;\n }\n\n private getQueryScore(candidate: SkillCandidate, query: string): number {\n const tokens = query.split(/\\s+/).filter(Boolean);\n const titleField = this.normalizeSearchQuery(candidate.title);\n const pathTail = this.normalizeSearchQuery(\n (candidate.relativePath ?? \"\").split(\"/\").pop() ?? \"\",\n );\n const fields = [\n titleField,\n pathTail,\n ];\n\n let score = 0;\n for (const token of tokens) {\n if (titleField === token || pathTail === token) {\n score += 12;\n } else if (titleField.startsWith(token) || pathTail.startsWith(token)) {\n score += 8;\n } else if (titleField.includes(token) || pathTail.includes(token)) {\n score += 4;\n }\n\n score += fields.filter((field) => field.includes(token)).length;\n }\n\n return score;\n }\n\n private getCandidateKey(candidate: SkillCandidate): string {\n if (candidate.sourceKind === \"git\") {\n return `${candidate.sourceId}:${candidate.relativePath ?? \".\"}`;\n }\n\n return candidate.locator;\n }\n\n private getCandidateTitle(leaf: LeafRecord): string {\n const title = leaf.title.trim();\n if (title.length === 0 || /^\\{[^}]+\\}$/.test(title)) {\n return leaf.linkName || leaf.name;\n }\n return title;\n }\n\n private normalizeSearchQuery(value: string): string {\n return value.trim().toLowerCase().replace(/[_-]+/g, \" \").replace(/\\s+/g, \" \");\n }\n\n private formatSourceLabel(locator: string, displayName: string): string {\n if (locator.startsWith(\"clawhub:\")) {\n return `${displayName}@clawhub`;\n }\n\n if (path.isAbsolute(locator)) {\n return `${displayName}@local`;\n }\n\n const repo = parseGitHubRepo(locator);\n if (!repo) {\n return displayName;\n }\n return `${displayName}@${repo.owner}`;\n }\n\n private applySourceUpdateResults(\n manifest: Manifest,\n lockFile: LockFile,\n updates: SourceUpdateResultItem[],\n ) {\n for (const update of updates) {\n if (!update.changed) {\n continue;\n }\n const source = manifest.sources.find((item) => item.id === update.sourceId);\n const binding = manifest.bindings[update.sourceId];\n if (!source || !binding) {\n continue;\n }\n\n for (const diff of update.diffs) {\n if (diff.kind !== \"moved\" || !diff.previousLeafId) {\n continue;\n }\n for (const targetBinding of Object.values(binding.targets)) {\n if (!targetBinding?.enabled || !targetBinding.leafIds.includes(diff.previousLeafId)) {\n continue;\n }\n targetBinding.leafIds = targetBinding.leafIds.map((leafId) =>\n leafId === diff.previousLeafId ? diff.leafId : leafId,\n );\n }\n }\n\n if ((update.selectionMode ?? source.selectionMode) !== \"all\") {\n continue;\n }\n\n const addedLeafIds = update.diffs\n .filter((diff) => diff.kind === \"added\")\n .map((diff) => diff.leafId);\n if (addedLeafIds.length === 0) {\n continue;\n }\n\n for (const targetBinding of Object.values(binding.targets)) {\n if (!targetBinding?.enabled) {\n continue;\n }\n const merged = new Set([...targetBinding.leafIds, ...addedLeafIds]);\n targetBinding.leafIds = [...merged].filter((leafId) =>\n lockFile.leafInventory.some((leaf) => leaf.id === leafId && leaf.sourceId === update.sourceId),\n );\n }\n }\n }\n}\n", "import path from \"node:path\";\nimport type {\n ChannelDetection,\n DeploymentStrategy,\n DeploymentTargetName,\n DeploymentTargetId,\n MergedTargetDefinition,\n} from \"@skill-flow/domain/types\";\nimport {\n getTargetDetectionCandidates,\n getBuiltInTargetDefinitions,\n} from \"../utils/constants.js\";\nimport { pathExists } from \"../utils/fs.js\";\n\nexport interface ChannelAdapter {\n readonly target: DeploymentTargetId;\n readonly strategy: DeploymentStrategy;\n detect(): Promise<ChannelDetection>;\n resolveTargetPath(rootPath: string, linkName: string): string;\n}\n\nclass DefaultChannelAdapter implements ChannelAdapter {\n readonly strategy: DeploymentStrategy;\n private readonly definition: MergedTargetDefinition;\n\n constructor(definition: MergedTargetDefinition) {\n this.definition = definition;\n this.target = definition.id;\n this.strategy = definition.strategy;\n }\n\n readonly target: DeploymentTargetId;\n\n async detect(): Promise<ChannelDetection> {\n const candidates = this.definition.kind === \"builtin\"\n ? getTargetDetectionCandidates(this.definition.id as DeploymentTargetName)\n : [this.definition.globalPath];\n const envVar = this.definition.kind === \"builtin\"\n ? ` Set ${this.target} target env override to enable it.`\n : \"\";\n\n if (candidates.length === 0) {\n return {\n target: this.target,\n strategy: this.strategy,\n available: false,\n rootPath: path.resolve(\".\"),\n reason: this.definition.kind === \"builtin\"\n ? \"Target is disabled in explicit target mode.\"\n : \"Custom target has no detection candidates.\",\n };\n }\n\n for (const candidate of candidates) {\n const rootPath = path.resolve(candidate);\n if (await pathExists(rootPath)) {\n return {\n target: this.target,\n strategy: this.strategy,\n available: true,\n rootPath,\n };\n }\n }\n\n return {\n target: this.target,\n strategy: this.strategy,\n available: false,\n rootPath: path.resolve(candidates[0] ?? \".\"),\n reason: this.definition.kind === \"builtin\"\n ? `Target directory not found.${envVar || \" Create the agent directory first.\"}`\n : \"Custom target directory not found. Create the configured global target directory first.\",\n };\n }\n\n resolveTargetPath(rootPath: string, linkName: string): string {\n return path.join(rootPath, linkName);\n }\n}\n\nexport function createChannelAdapters(\n targetDefinitions: MergedTargetDefinition[] = getBuiltInTargetDefinitions(),\n): ChannelAdapter[] {\n return targetDefinitions.map((definition) => new DefaultChannelAdapter(definition));\n}\n", "import os from \"node:os\";\nimport path from \"node:path\";\nimport type {\n CustomTargetDefinition,\n DeploymentStrategy,\n DeploymentTargetName,\n MergedTargetDefinition,\n} from \"@skill-flow/domain/types\";\n\nexport const SCHEMA_VERSION = 1 as const;\n\nexport function getStateRoot(): string {\n return process.env.SKILL_FLOW_STATE_ROOT\n ? path.resolve(process.env.SKILL_FLOW_STATE_ROOT)\n : path.join(os.homedir(), \".skillflow\");\n}\n\nexport type TargetDefinition = {\n label: string;\n strategy: DeploymentStrategy;\n envVar: string;\n writerKey: string;\n writeRootCandidates: string[];\n compatReadRootCandidates: string[];\n // Reserved for future project-scope installs. Current runtime still writes via writeRootCandidates.\n documentedProjectPath?: string;\n // Mirrors the external README contract and may differ from today's runtime write root.\n documentedGlobalPath: string;\n iconAssetName?: string;\n documentedAgentIds?: string[];\n};\n\nexport const TARGET_ORDER: DeploymentTargetName[] = [\n \"claude-code\",\n \"codex\",\n \"cursor\",\n \"github-copilot\",\n \"gemini-cli\",\n \"opencode\",\n \"openclaw\",\n \"pi\",\n \"trae\",\n \"windsurf\",\n \"roo-code\",\n \"cline\",\n \"amp\",\n \"kiro\",\n];\n\nexport const TARGET_DEFINITIONS: Record<DeploymentTargetName, TargetDefinition> = {\n \"claude-code\": {\n label: \"Claude Code\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_CLAUDE_CODE\",\n writerKey: \"claude-home\",\n writeRootCandidates: [path.join(os.homedir(), \".claude\", \"skills\")],\n compatReadRootCandidates: [],\n documentedProjectPath: \".claude/skills/\",\n documentedGlobalPath: \"~/.claude/skills/\",\n iconAssetName: \"claude-code.svg\",\n },\n codex: {\n label: \"Codex\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_CODEX\",\n writerKey: \"agents-skills\",\n writeRootCandidates: [\n path.join(os.homedir(), \".codex\", \"skills\"),\n ],\n compatReadRootCandidates: [\n path.join(os.homedir(), \".agents\", \"skills\"),\n path.join(os.homedir(), \".codex\", \".agents\", \"skills\"),\n path.join(\"/etc\", \"codex\", \"skills\"),\n ],\n documentedProjectPath: \".agents/skills/\",\n documentedGlobalPath: \"~/.codex/skills/\",\n iconAssetName: \"codex.svg\",\n },\n cursor: {\n label: \"Cursor\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_CURSOR\",\n writerKey: \"cursor-home\",\n writeRootCandidates: [path.join(os.homedir(), \".cursor\", \"skills\")],\n compatReadRootCandidates: [\n path.join(os.homedir(), \".agents\", \"skills\"),\n path.join(os.homedir(), \".claude\", \"skills\"),\n path.join(os.homedir(), \".codex\", \"skills\"),\n ],\n documentedProjectPath: \".agents/skills/\",\n documentedGlobalPath: \"~/.cursor/skills/\",\n iconAssetName: \"cursor.svg\",\n },\n \"github-copilot\": {\n label: \"GitHub Copilot\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_GITHUB_COPILOT\",\n writerKey: \"copilot-home\",\n writeRootCandidates: [path.join(os.homedir(), \".copilot\", \"skills\")],\n compatReadRootCandidates: [\n path.join(os.homedir(), \".claude\", \"skills\"),\n path.join(os.homedir(), \".agents\", \"skills\"),\n ],\n documentedProjectPath: \".agents/skills/\",\n documentedGlobalPath: \"~/.copilot/skills/\",\n iconAssetName: \"copilot.svg\",\n },\n \"gemini-cli\": {\n label: \"Gemini CLI\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_GEMINI_CLI\",\n writerKey: \"gemini-home\",\n writeRootCandidates: [path.join(os.homedir(), \".gemini\", \"skills\")],\n compatReadRootCandidates: [path.join(os.homedir(), \".agents\", \"skills\")],\n documentedProjectPath: \".agents/skills/\",\n documentedGlobalPath: \"~/.gemini/skills/\",\n iconAssetName: \"gemini.svg\",\n },\n opencode: {\n label: \"OpenCode\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_OPENCODE\",\n writerKey: \"opencode-home\",\n writeRootCandidates: [\n path.join(os.homedir(), \".config\", \"opencode\", \"skills\"),\n ],\n compatReadRootCandidates: [\n path.join(os.homedir(), \".opencode\", \"skills\"),\n path.join(os.homedir(), \".claude\", \"skills\"),\n path.join(os.homedir(), \".agents\", \"skills\"),\n ],\n documentedProjectPath: \".agents/skills/\",\n documentedGlobalPath: \"~/.config/opencode/skills/\",\n iconAssetName: \"opencode.svg\",\n },\n openclaw: {\n label: \"OpenClaw\",\n strategy: \"copy\",\n envVar: \"SKILL_FLOW_TARGET_OPENCLAW\",\n writerKey: \"openclaw-home\",\n writeRootCandidates: [path.join(os.homedir(), \".openclaw\", \"skills\")],\n compatReadRootCandidates: [],\n documentedProjectPath: \"skills/\",\n documentedGlobalPath: \"~/.openclaw/skills/\",\n iconAssetName: \"clawdbot.svg\",\n },\n pi: {\n label: \"Pi\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_PI\",\n writerKey: \"pi-home\",\n writeRootCandidates: [path.join(os.homedir(), \".pi\", \"agent\", \"skills\")],\n compatReadRootCandidates: [\n path.join(os.homedir(), \".agents\", \"skills\"),\n path.join(os.homedir(), \".claude\", \"skills\"),\n path.join(os.homedir(), \".codex\", \"skills\"),\n ],\n documentedProjectPath: \".pi/skills/\",\n documentedGlobalPath: \"~/.pi/agent/skills/\",\n },\n trae: {\n label: \"Trae\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_TRAE\",\n writerKey: \"trae-home\",\n writeRootCandidates: [path.join(os.homedir(), \".trae\", \"skills\")],\n compatReadRootCandidates: [],\n documentedProjectPath: \".trae/skills/\",\n documentedGlobalPath: \"~/.trae/skills/\",\n iconAssetName: \"trae.svg\",\n },\n windsurf: {\n label: \"Windsurf\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_WINDSURF\",\n writerKey: \"windsurf-home\",\n writeRootCandidates: [path.join(os.homedir(), \".codeium\", \"windsurf\", \"skills\")],\n compatReadRootCandidates: [\n path.join(\"/Library\", \"Application Support\", \"Windsurf\", \"skills\"),\n ],\n documentedProjectPath: \".windsurf/skills/\",\n documentedGlobalPath: \"~/.codeium/windsurf/skills/\",\n iconAssetName: \"windsurf.svg\",\n },\n \"roo-code\": {\n label: \"Roo Code\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_ROO_CODE\",\n writerKey: \"roo-home\",\n writeRootCandidates: [path.join(os.homedir(), \".roo\", \"skills\")],\n compatReadRootCandidates: [],\n documentedProjectPath: \".roo/skills/\",\n documentedGlobalPath: \"~/.roo/skills/\",\n iconAssetName: \"roo.svg\",\n documentedAgentIds: [\"roo\"],\n },\n cline: {\n label: \"Cline\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_CLINE\",\n writerKey: \"cline-home\",\n writeRootCandidates: [path.join(os.homedir(), \".agents\", \"skills\")],\n compatReadRootCandidates: [\n path.join(os.homedir(), \".cline\", \"skills\"),\n path.join(os.homedir(), \".claude\", \"skills\"),\n ],\n documentedProjectPath: \".agents/skills/\",\n documentedGlobalPath: \"~/.agents/skills/\",\n iconAssetName: \"cline.svg\",\n },\n amp: {\n label: \"Amp\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_AMP\",\n writerKey: \"amp-home\",\n writeRootCandidates: [\n path.join(os.homedir(), \".config\", \"agents\", \"skills\"),\n ],\n compatReadRootCandidates: [\n path.join(os.homedir(), \".config\", \"amp\", \"skills\"),\n path.join(os.homedir(), \".claude\", \"skills\"),\n ],\n documentedProjectPath: \".agents/skills/\",\n documentedGlobalPath: \"~/.config/agents/skills/\",\n iconAssetName: \"amp.svg\",\n },\n kiro: {\n label: \"Kiro\",\n strategy: \"symlink\",\n envVar: \"SKILL_FLOW_TARGET_KIRO\",\n writerKey: \"kiro-home\",\n writeRootCandidates: [path.join(os.homedir(), \".kiro\", \"skills\")],\n compatReadRootCandidates: [],\n documentedProjectPath: \".kiro/skills/\",\n documentedGlobalPath: \"~/.kiro/skills/\",\n iconAssetName: \"kiro-cli.svg\",\n documentedAgentIds: [\"kiro-cli\"],\n },\n};\n\nexport function getBuiltInTargetDefinitions(): MergedTargetDefinition[] {\n return TARGET_ORDER.map((target) => {\n const definition = TARGET_DEFINITIONS[target];\n const mergedDefinition: MergedTargetDefinition = {\n id: target,\n label: definition.label,\n strategy: definition.strategy,\n kind: \"builtin\",\n isMutable: false,\n globalPath: definition.documentedGlobalPath,\n };\n\n if (definition.documentedProjectPath) {\n mergedDefinition.projectPathTemplate = definition.documentedProjectPath;\n }\n\n if (definition.iconAssetName) {\n mergedDefinition.iconAssetName = definition.iconAssetName;\n }\n\n return mergedDefinition;\n });\n}\n\nexport function getMergedTargetDefinitions(\n customTargets: CustomTargetDefinition[] = [],\n agentDisplayOrder?: string[],\n): MergedTargetDefinition[] {\n const builtIns = getBuiltInTargetDefinitions();\n const merged = [\n ...builtIns,\n ...customTargets.map<MergedTargetDefinition>((target) => {\n const mergedDefinition: MergedTargetDefinition = {\n id: target.id,\n label: target.name,\n strategy: target.strategy,\n kind: \"custom\",\n isMutable: true,\n globalPath: target.globalPath,\n };\n\n if (target.projectPathTemplate.length > 0) {\n mergedDefinition.projectPathTemplate = target.projectPathTemplate;\n }\n\n return mergedDefinition;\n }),\n ];\n\n const indexById = new Map<string, MergedTargetDefinition>(\n merged.map((definition) => [definition.id, definition]),\n );\n\n if (!agentDisplayOrder || agentDisplayOrder.length === 0) {\n return merged;\n }\n\n const ordered: MergedTargetDefinition[] = [];\n const seen = new Set<string>();\n\n for (const targetId of agentDisplayOrder) {\n const definition = indexById.get(targetId);\n if (!definition || seen.has(targetId)) {\n continue;\n }\n seen.add(targetId);\n ordered.push(definition);\n }\n\n for (const definition of merged) {\n if (!seen.has(definition.id)) {\n seen.add(definition.id);\n ordered.push(definition);\n }\n }\n\n return ordered;\n}\n\nexport function getMergedTargetDefinitionById(\n targetId: string,\n customTargets: CustomTargetDefinition[] = [],\n): MergedTargetDefinition | undefined {\n return getMergedTargetDefinitions(customTargets).find((target) => target.id === targetId);\n}\n\nexport const TARGET_LABELS: Record<DeploymentTargetName, string> = Object.fromEntries(\n TARGET_ORDER.map((target) => [target, TARGET_DEFINITIONS[target].label]),\n) as Record<DeploymentTargetName, string>;\n\nexport const TARGET_STRATEGIES: Record<DeploymentTargetName, DeploymentStrategy> =\n Object.fromEntries(\n TARGET_ORDER.map((target) => [target, TARGET_DEFINITIONS[target].strategy]),\n ) as Record<DeploymentTargetName, DeploymentStrategy>;\n\nexport const TARGET_ENV_VARS: Record<DeploymentTargetName, string> = Object.fromEntries(\n TARGET_ORDER.map((target) => [target, TARGET_DEFINITIONS[target].envVar]),\n) as Record<DeploymentTargetName, string>;\n\nexport const TARGET_WRITER_KEYS: Record<DeploymentTargetName, string> = Object.fromEntries(\n TARGET_ORDER.map((target) => [target, TARGET_DEFINITIONS[target].writerKey]),\n) as Record<DeploymentTargetName, string>;\n\nexport const TARGET_PATH_CANDIDATES: Record<DeploymentTargetName, string[]> =\n Object.fromEntries(\n TARGET_ORDER.map((target) => [target, TARGET_DEFINITIONS[target].writeRootCandidates]),\n ) as Record<DeploymentTargetName, string[]>;\n\nexport const TARGET_COMPAT_READ_CANDIDATES: Record<DeploymentTargetName, string[]> =\n Object.fromEntries(\n TARGET_ORDER.map((target) => [\n target,\n TARGET_DEFINITIONS[target].compatReadRootCandidates,\n ]),\n ) as Record<DeploymentTargetName, string[]>;\n\nexport const TARGET_DOCUMENTED_PROJECT_PATHS: Record<DeploymentTargetName, string | undefined> =\n Object.fromEntries(\n TARGET_ORDER.map((target) => [target, TARGET_DEFINITIONS[target].documentedProjectPath]),\n ) as Record<DeploymentTargetName, string | undefined>;\n\nexport const TARGET_DOCUMENTED_GLOBAL_PATHS: Record<DeploymentTargetName, string> =\n Object.fromEntries(\n TARGET_ORDER.map((target) => [target, TARGET_DEFINITIONS[target].documentedGlobalPath]),\n ) as Record<DeploymentTargetName, string>;\n\nexport function resolveDocumentedProjectSkillPath(\n target: DeploymentTargetName,\n projectPath: string,\n): string | null {\n const normalizedProjectPath = projectPath.trim();\n if (normalizedProjectPath.length === 0) {\n return null;\n }\n\n const documentedProjectPath = TARGET_DEFINITIONS[target].documentedProjectPath?.trim();\n if (!documentedProjectPath) {\n return null;\n }\n\n const resolvedPath = path.join(normalizedProjectPath, documentedProjectPath);\n return resolvedPath.endsWith(path.sep) ? resolvedPath.slice(0, -path.sep.length) : resolvedPath;\n}\n\nexport const TARGET_ICON_ASSET_NAMES: Record<DeploymentTargetName, string | undefined> =\n Object.fromEntries(\n TARGET_ORDER.map((target) => [target, TARGET_DEFINITIONS[target].iconAssetName]),\n ) as Record<DeploymentTargetName, string | undefined>;\n\nexport function getExplicitTargetNames(): DeploymentTargetName[] {\n return TARGET_ORDER.filter((target) => {\n const value = process.env[TARGET_DEFINITIONS[target].envVar]?.trim();\n return Boolean(value);\n });\n}\n\nexport function isExplicitTargetMode(): boolean {\n return getExplicitTargetNames().length > 0;\n}\n\nexport function getTargetDetectionCandidates(target: DeploymentTargetName): string[] {\n const definition = TARGET_DEFINITIONS[target];\n const override = process.env[definition.envVar]?.trim();\n\n if (isExplicitTargetMode()) {\n return override ? [override] : [];\n }\n\n return override ? [override] : definition.writeRootCandidates;\n}\n\nexport function getTargetScanRoots(target: DeploymentTargetName): string[] {\n const definition = TARGET_DEFINITIONS[target];\n const override = process.env[definition.envVar]?.trim();\n\n if (isExplicitTargetMode()) {\n return override ? [override] : [];\n }\n\n return [\n ...new Set([\n ...(override ? [override] : []),\n ...definition.writeRootCandidates,\n ...definition.compatReadRootCandidates,\n ]),\n ];\n}\n", "import crypto from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport async function pathExists(targetPath: string): Promise<boolean> {\n try {\n await fs.lstat(targetPath);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function ensureDir(targetPath: string): Promise<void> {\n await fs.mkdir(targetPath, { recursive: true });\n}\n\nexport async function readJsonFile<T>(filePath: string, fallback: T): Promise<T> {\n try {\n const raw = await fs.readFile(filePath, \"utf8\");\n return JSON.parse(raw) as T;\n } catch {\n return fallback;\n }\n}\n\nexport async function writeJsonFile(filePath: string, value: unknown): Promise<void> {\n await ensureDir(path.dirname(filePath));\n const tempPath = `${filePath}.${process.pid}.${crypto.randomUUID()}.tmp`;\n await fs.writeFile(tempPath, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\n await fs.rename(tempPath, filePath);\n}\n\nexport async function withFileLock<T>(\n lockPath: string,\n task: () => Promise<T>,\n options: { pollMs?: number; staleMs?: number; timeoutMs?: number } = {},\n): Promise<T> {\n const pollMs = options.pollMs ?? 25;\n const staleMs = options.staleMs ?? 5 * 60_000;\n const timeoutMs = options.timeoutMs ?? 120_000;\n const start = Date.now();\n\n while (true) {\n try {\n await fs.mkdir(lockPath);\n break;\n } catch (error) {\n if (!isAlreadyExistsError(error)) {\n throw error;\n }\n\n const stale = await isLockStale(lockPath, staleMs);\n if (stale) {\n await fs.rm(lockPath, { recursive: true, force: true });\n continue;\n }\n\n if (Date.now() - start >= timeoutMs) {\n throw new Error(`Timed out waiting for state lock at ${lockPath}`);\n }\n\n await sleep(pollMs);\n }\n }\n\n try {\n await fs.writeFile(\n path.join(lockPath, \"owner.json\"),\n `${JSON.stringify({ pid: process.pid, acquiredAt: new Date().toISOString() }, null, 2)}\\n`,\n \"utf8\",\n );\n return await task();\n } finally {\n await fs.rm(lockPath, { recursive: true, force: true });\n }\n}\n\nexport async function removePath(targetPath: string): Promise<void> {\n await fs.rm(targetPath, { recursive: true, force: true });\n}\n\nexport function isPathInside(rootPath: string, targetPath: string): boolean {\n const relative = path.relative(path.resolve(rootPath), path.resolve(targetPath));\n return relative.length > 0 && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n}\n\nexport async function copyDirectory(sourcePath: string, targetPath: string): Promise<void> {\n await removePath(targetPath);\n await fs.cp(sourcePath, targetPath, { recursive: true, dereference: false });\n}\n\nexport async function createSymlink(\n sourcePath: string,\n targetPath: string,\n): Promise<void> {\n await removePath(targetPath);\n await ensureDir(path.dirname(targetPath));\n await fs.symlink(sourcePath, targetPath, \"junction\");\n}\n\nexport async function isBrokenSymlink(targetPath: string): Promise<boolean> {\n try {\n const stats = await fs.lstat(targetPath);\n if (!stats.isSymbolicLink()) {\n return false;\n }\n const resolved = await fs.readlink(targetPath);\n const absolute = path.resolve(path.dirname(targetPath), resolved);\n return !(await pathExists(absolute));\n } catch {\n return false;\n }\n}\n\nexport async function hashDirectory(rootPath: string): Promise<string> {\n const hash = crypto.createHash(\"sha256\");\n\n async function walk(currentPath: string): Promise<void> {\n const entries = await fs.readdir(currentPath, { withFileTypes: true });\n entries.sort((left, right) => left.name.localeCompare(right.name));\n\n for (const entry of entries) {\n if (entry.name === \".git\" || entry.name === \"node_modules\") {\n continue;\n }\n\n const entryPath = path.join(currentPath, entry.name);\n const relativePath = path.relative(rootPath, entryPath);\n\n hash.update(relativePath);\n if (entry.isDirectory()) {\n hash.update(\"dir\");\n await walk(entryPath);\n } else if (entry.isFile()) {\n hash.update(\"file\");\n hash.update(await fs.readFile(entryPath));\n }\n }\n }\n\n await walk(rootPath);\n return hash.digest(\"hex\");\n}\n\nexport function slugify(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 80);\n}\n\nasync function isLockStale(lockPath: string, staleMs: number) {\n try {\n const stats = await fs.stat(lockPath);\n return Date.now() - stats.mtimeMs > staleMs;\n } catch {\n return false;\n }\n}\n\nfunction isAlreadyExistsError(error: unknown) {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === \"EEXIST\"\n );\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n", "import type { DeploymentTargetId, LockFile, ProjectionRecord, SourceLockRecord } from \"./types.js\";\n\nexport function getManagedDeployments(lockFile: LockFile): LockFile[\"deployments\"] {\n if (!(lockFile.projections?.length)) {\n return lockFile.deployments ?? [];\n }\n\n return (lockFile.projections ?? [])\n .filter((projection) => projection.mode === \"managed\")\n .map(({ mode: _mode, ...deployment }) => deployment);\n}\n\nexport function getBootstrapImportedTargets(\n lockFile: LockFile,\n sourceLock: SourceLockRecord,\n): DeploymentTargetId[] {\n return [\n ...new Set([\n ...(lockFile.projections ?? [])\n .filter(\n (projection) =>\n projection.mode === \"bootstrap-imported\" &&\n projection.sourceId === sourceLock.id,\n )\n .map((projection) => projection.target),\n ...(sourceLock.observedTargets?.map((item) => item.target) ?? []),\n ...(sourceLock.importedFromTargets ?? []),\n ]),\n ];\n}\n\nexport function normalizeProjectionRecords(lockFile: LockFile): ProjectionRecord[] {\n const explicitProjections = (lockFile.projections ?? []).map((projection) => ({\n ...projection,\n mode: projection.mode ?? \"managed\",\n }));\n const explicitManagedProjections = explicitProjections.filter(\n (projection) => projection.mode === \"managed\",\n );\n const explicitNonManagedProjections = explicitProjections.filter(\n (projection) => projection.mode !== \"managed\",\n );\n const managedProjections = (\n explicitManagedProjections.length > 0\n ? explicitManagedProjections\n : (lockFile.deployments ?? []).map((deployment) => ({\n ...deployment,\n mode: \"managed\" as const,\n }))\n );\n const projectionByKey = new Map<string, ProjectionRecord>();\n\n for (const projection of [...managedProjections, ...explicitNonManagedProjections]) {\n projectionByKey.set(\n [\n projection.mode,\n projection.sourceId,\n projection.leafId,\n projection.target,\n projection.targetPath,\n ].join(\"\\n\"),\n projection,\n );\n }\n\n return [...projectionByKey.values()];\n}\n", "import path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport type {\n ImportDataCache,\n ImportRecommendationFeed,\n LockFile,\n Manifest,\n RepoMetadataCacheEntry,\n SharedPreferences,\n SourceMetadataCache,\n SourceMetadataCacheEntry,\n SourceKind,\n UnifiedSourceSnapshotCacheEntry,\n} from \"@skill-flow/domain/types\";\nimport { normalizeProjectionRecords } from \"@skill-flow/domain/projection-compat\";\nimport {\n createEmptyImportDataCache,\n normalizeImportDataCache,\n} from \"./import-data-cache.js\";\nimport {\n createEmptySharedPreferences,\n normalizeSharedPreferences,\n} from \"./preferences-store.js\";\nimport { createEmptySourceMetadataCache, normalizeSourceMetadataCache } from \"./source-metadata-cache.js\";\nimport { SCHEMA_VERSION, getStateRoot } from \"@skill-flow/integration/utils/constants\";\nimport {\n ensureDir,\n pathExists,\n readJsonFile,\n withFileLock,\n writeJsonFile,\n} from \"@skill-flow/integration/utils/fs\";\n\nexport class StateStore {\n private initPromise: Promise<void> | undefined;\n private ioQueue: Promise<void> = Promise.resolve();\n\n constructor(private readonly stateRoot = getStateRoot()) {}\n\n get rootPath(): string {\n return this.stateRoot;\n }\n\n get sourceRoot(): string {\n return this.getSourceRoot(\"git\");\n }\n\n getSourceRoot(kind: SourceKind): string {\n return path.join(this.stateRoot, \"source\", kind);\n }\n\n getSourceCheckoutPath(kind: SourceKind, sourceId: string): string {\n return path.join(this.getSourceRoot(kind), sourceId);\n }\n\n get catalogRoot(): string {\n return path.join(this.catalogStateRoot, \"git\");\n }\n\n get catalogStateRoot(): string {\n return path.join(this.stateRoot, \"catalog\");\n }\n\n getCatalogCheckoutPath(sourceId: string): string {\n return path.join(this.catalogRoot, sourceId);\n }\n\n getCatalogIndexPath(sourceId: string): string {\n return path.join(this.catalogRoot, `${sourceId}.json`);\n }\n\n get manifestPath(): string {\n return path.join(this.stateRoot, \"manifest.json\");\n }\n\n get lockPath(): string {\n return path.join(this.stateRoot, \"lock.json\");\n }\n\n get preferencesPath(): string {\n return path.join(this.stateRoot, \"preferences.json\");\n }\n\n get auditLogPath(): string {\n return path.join(this.stateRoot, \"audit.log.jsonl\");\n }\n\n get sourceMetadataPath(): string {\n return path.join(this.catalogStateRoot, \"source-metadata.json\");\n }\n\n get importDataPath(): string {\n return path.join(this.catalogStateRoot, \"import-data.json\");\n }\n\n get mutationLockPath(): string {\n return path.join(this.stateRoot, \".mutation.lock\");\n }\n\n async init(): Promise<void> {\n if (!this.initPromise) {\n this.initPromise = this.initializeState();\n }\n await this.initPromise;\n }\n\n async readManifest(): Promise<Manifest> {\n return this.withIoLock(async () => {\n await this.init();\n return this.readManifestRaw();\n });\n }\n\n async writeManifest(manifest: Manifest): Promise<void> {\n await this.withIoLock(async () => {\n await this.init();\n await writeJsonFile(this.manifestPath, manifest);\n });\n }\n\n async readLock(): Promise<LockFile> {\n return this.withIoLock(async () => {\n await this.init();\n return this.normalizeLockFile(await this.readLockRaw());\n });\n }\n\n async readState(): Promise<{ manifest: Manifest; lockFile: LockFile }> {\n return this.withIoLock(async () => {\n await this.init();\n const manifest = await this.readManifestRaw();\n const lockFile = this.normalizeLockFile(await this.readLockRaw());\n return { manifest, lockFile };\n });\n }\n\n async writeLock(lockFile: LockFile): Promise<void> {\n await this.withIoLock(async () => {\n await this.init();\n await writeJsonFile(this.lockPath, this.serializeLockFile(lockFile));\n });\n }\n\n async writeState(manifest: Manifest, lockFile: LockFile): Promise<void> {\n await this.withIoLock(async () => {\n await this.init();\n await writeJsonFile(this.manifestPath, manifest);\n await writeJsonFile(this.lockPath, this.serializeLockFile(lockFile));\n });\n }\n\n async readPreferences(): Promise<SharedPreferences> {\n return this.withIoLock(async () => {\n await this.init();\n return this.readPreferencesRaw();\n });\n }\n\n async writePreferences(preferences: SharedPreferences): Promise<void> {\n await this.withIoLock(async () => {\n await this.init();\n await writeJsonFile(\n this.preferencesPath,\n normalizeSharedPreferences(preferences),\n );\n });\n }\n\n async appendAuditEvent(event: unknown): Promise<void> {\n await this.withIoLock(async () => {\n await this.init();\n await fs.appendFile(this.auditLogPath, `${JSON.stringify(event)}\\n`, \"utf8\");\n });\n }\n\n async togglePinnedSource(sourceId: string): Promise<SharedPreferences> {\n return this.withIoLock(async () => {\n await this.init();\n const preferences = await this.readPreferencesRaw();\n const pinnedSourceIds = preferences.pinnedSourceIds.includes(sourceId)\n ? preferences.pinnedSourceIds.filter((pinnedSourceId) => pinnedSourceId !== sourceId)\n : [...preferences.pinnedSourceIds, sourceId];\n const nextPreferences = normalizeSharedPreferences({\n ...preferences,\n pinnedSourceIds,\n });\n await writeJsonFile(this.preferencesPath, nextPreferences);\n return nextPreferences;\n });\n }\n\n async pruneMissingSourceIds(): Promise<SharedPreferences> {\n return this.withIoLock(async () => {\n await this.init();\n const manifest = await this.readManifestRaw();\n const preferences = await this.readPreferencesRaw();\n const existingSourceIds = new Set(manifest.sources.map((source) => source.id));\n const nextPreferences = normalizeSharedPreferences({\n ...preferences,\n pinnedSourceIds: preferences.pinnedSourceIds.filter((sourceId) =>\n existingSourceIds.has(sourceId),\n ),\n });\n\n if (!hasSameEntries(preferences.pinnedSourceIds, nextPreferences.pinnedSourceIds)) {\n await writeJsonFile(this.preferencesPath, nextPreferences);\n }\n\n return nextPreferences;\n });\n }\n\n async readSourceMetadataCache(): Promise<SourceMetadataCache> {\n return this.withIoLock(async () => {\n await this.init();\n return this.readSourceMetadataCacheRaw();\n });\n }\n\n async readImportDataCache(): Promise<ImportDataCache> {\n return this.withIoLock(async () => {\n await this.init();\n return this.readImportDataCacheRaw();\n });\n }\n\n async writeImportDataCache(cache: ImportDataCache): Promise<void> {\n await this.withIoLock(async () => {\n await this.init();\n await writeJsonFile(this.importDataPath, normalizeImportDataCache(cache));\n });\n }\n\n async writeImportSourceSnapshotEntry(entry: UnifiedSourceSnapshotCacheEntry): Promise<void> {\n await this.withIoLock(async () => {\n await this.init();\n const cache = await this.readImportDataCacheRaw();\n cache.repos[entry.canonicalRepo] = {\n canonicalRepo: entry.canonicalRepo,\n checkedAt: entry.checkedAt,\n expiresAt: entry.expiresAt,\n identity: {\n canonicalRepo: entry.canonicalRepo,\n aliases: entry.data.aliases,\n origins: [\"skills\"],\n },\n providers: {\n skills: {\n provider: \"skills\",\n status: \"ready\",\n checkedAt: entry.checkedAt,\n expiresAt: entry.expiresAt,\n snapshot: entry.data,\n },\n },\n resolved: {\n ...(entry.data.title ? { title: entry.data.title } : {}),\n ...(entry.data.owner.slug ? { author: entry.data.owner.slug } : {}),\n ...(entry.data.description ? { summary: entry.data.description } : {}),\n ...(entry.data.repoUrl ? { githubUrl: entry.data.repoUrl } : {}),\n ...(entry.data.sourceUrl ? { sourceUrl: entry.data.sourceUrl } : {}),\n ...(entry.data.skillCount !== undefined ? { skillCount: entry.data.skillCount } : {}),\n ...(entry.data.totalInstalls !== undefined ? { downloadCount: entry.data.totalInstalls } : {}),\n ...(entry.data.repoStars !== undefined ? { starCount: entry.data.repoStars } : {}),\n fieldSources: {\n ...(entry.data.title ? { title: \"skills\" } : {}),\n ...(entry.data.owner.slug ? { author: \"skills\" } : {}),\n ...(entry.data.description ? { summary: \"skills\" } : {}),\n ...(entry.data.repoUrl ? { githubUrl: \"skills\" } : {}),\n ...(entry.data.sourceUrl ? { sourceUrl: \"skills\" } : {}),\n ...(entry.data.skillCount !== undefined ? { skillCount: \"skills\" } : {}),\n ...(entry.data.totalInstalls !== undefined ? { downloadCount: \"skills\" } : {}),\n ...(entry.data.repoStars !== undefined ? { starCount: \"skills\" } : {}),\n },\n },\n } as RepoMetadataCacheEntry;\n await writeJsonFile(this.importDataPath, cache);\n });\n }\n\n async writeImportSearchSnapshotEntry(\n query: string,\n entry: ImportDataCache[\"searches\"][string],\n ): Promise<void> {\n await this.withIoLock(async () => {\n await this.init();\n const cache = await this.readImportDataCacheRaw();\n cache.searches[query] = entry;\n await writeJsonFile(this.importDataPath, cache);\n });\n }\n\n async writeImportRecommendationFeedEntry(entry: ImportRecommendationFeed): Promise<void> {\n await this.withIoLock(async () => {\n await this.init();\n const cache = await this.readImportDataCacheRaw();\n cache.recommendations[entry.id] = entry;\n await writeJsonFile(this.importDataPath, cache);\n });\n }\n\n async writeSourceMetadataCache(cache: SourceMetadataCache): Promise<void> {\n await this.withIoLock(async () => {\n await this.init();\n await writeJsonFile(\n this.sourceMetadataPath,\n normalizeSourceMetadataCache(cache),\n );\n });\n }\n\n async writeSourceMetadataEntry(entry: SourceMetadataCacheEntry): Promise<void> {\n await this.withIoLock(async () => {\n await this.init();\n const cache = await this.readSourceMetadataCacheRaw();\n cache[entry.sourceId] = entry;\n await writeJsonFile(this.sourceMetadataPath, cache);\n });\n }\n\n async pruneSourceMetadataCache(sourceIds: string[]): Promise<SourceMetadataCache> {\n return this.withIoLock(async () => {\n await this.init();\n const cache = await this.readSourceMetadataCacheRaw();\n const allowedSourceIds = new Set(sourceIds);\n const nextCache = Object.fromEntries(\n Object.entries(cache).filter(([sourceId]) => allowedSourceIds.has(sourceId)),\n ) satisfies SourceMetadataCache;\n\n if (Object.keys(nextCache).length !== Object.keys(cache).length) {\n await writeJsonFile(this.sourceMetadataPath, nextCache);\n }\n\n return nextCache;\n });\n }\n\n async withMutationLock<T>(task: () => Promise<T>): Promise<T> {\n await this.init();\n return withFileLock(this.mutationLockPath, task);\n }\n\n private async initializeState(): Promise<void> {\n await ensureDir(this.getSourceRoot(\"local\"));\n await ensureDir(this.getSourceRoot(\"git\"));\n await ensureDir(this.getSourceRoot(\"clawhub\"));\n await ensureDir(this.catalogStateRoot);\n await ensureDir(this.catalogRoot);\n\n if (!(await pathExists(this.manifestPath))) {\n await writeJsonFile(this.manifestPath, this.createEmptyManifest());\n }\n if (!(await pathExists(this.lockPath))) {\n await writeJsonFile(this.lockPath, this.serializeLockFile(this.createEmptyLockFile()));\n }\n }\n\n private readManifestRaw(): Promise<Manifest> {\n return readJsonFile<Manifest>(this.manifestPath, this.createEmptyManifest());\n }\n\n private readLockRaw(): Promise<LockFile> {\n return readJsonFile<LockFile>(this.lockPath, this.createEmptyLockFile());\n }\n\n private async readPreferencesRaw(): Promise<SharedPreferences> {\n return normalizeSharedPreferences(\n await readJsonFile<unknown>(\n this.preferencesPath,\n createEmptySharedPreferences(),\n ),\n );\n }\n\n private async readSourceMetadataCacheRaw(): Promise<SourceMetadataCache> {\n return normalizeSourceMetadataCache(\n await readJsonFile<unknown>(\n this.sourceMetadataPath,\n createEmptySourceMetadataCache(),\n ),\n );\n }\n\n private async readImportDataCacheRaw(): Promise<ImportDataCache> {\n return normalizeImportDataCache(\n await readJsonFile<unknown>(\n this.importDataPath,\n createEmptyImportDataCache(),\n ),\n );\n }\n\n private normalizeLockFile(lockFile: LockFile): LockFile {\n const projections = normalizeProjectionRecords(lockFile);\n const deployments = projections\n .filter((projection) => projection.mode === \"managed\")\n .map(({ mode: _mode, ...deployment }) => deployment);\n\n return {\n ...lockFile,\n projections,\n deployments,\n leafInventory: lockFile.leafInventory.map((leaf) => ({\n ...leaf,\n linkName:\n leaf.linkName ??\n (leaf.relativePath === \".\"\n ? leaf.name\n : path.basename(leaf.relativePath) || leaf.name),\n metadataWarnings: leaf.metadataWarnings ?? [],\n })),\n };\n }\n\n private serializeLockFile(lockFile: LockFile): unknown {\n const normalized = this.normalizeLockFile(lockFile);\n return {\n ...normalized,\n sources: normalized.sources.map((source) => {\n const hasBootstrapProjection = (normalized.projections ?? []).some(\n (projection) =>\n projection.mode === \"bootstrap-imported\" &&\n projection.sourceId === source.id,\n );\n if (source.importedFromTargets?.length && !hasBootstrapProjection) {\n return source;\n }\n const { importedFromTargets: _importedFromTargets, ...compactSource } = source;\n return compactSource;\n }),\n deployments: undefined,\n };\n }\n\n private createEmptyManifest(): Manifest {\n return {\n schemaVersion: SCHEMA_VERSION,\n sources: [],\n bindings: {},\n };\n }\n\n private createEmptyLockFile(): LockFile {\n return {\n schemaVersion: SCHEMA_VERSION,\n sources: [],\n leafInventory: [],\n projections: [],\n deployments: [],\n };\n }\n\n private async withIoLock<T>(task: () => Promise<T>): Promise<T> {\n const previous = this.ioQueue;\n let release: (() => void) | undefined;\n this.ioQueue = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n await previous;\n try {\n return await task();\n } finally {\n release?.();\n }\n }\n}\n\nfunction hasSameEntries(left: string[], right: string[]): boolean {\n return (\n left.length === right.length &&\n left.every((entry, index) => entry === right[index])\n );\n}\n", "import type {\n ImportDataCache,\n ImportRecommendationFeed,\n ImportRecommendationFeedId,\n ImportSearchHit,\n ImportSearchSnapshot,\n RepoMetadataCacheEntry,\n RepoMetadataIdentity,\n RepoMetadataProvider,\n RepoMetadataProviderEntry,\n ResolvedRepoMetadata,\n ResolvedRepoMetadataField,\n UnifiedSourceOwner,\n UnifiedSourceSkill,\n UnifiedSourceSkillInstalledOn,\n UnifiedSourceSnapshot,\n UnifiedSourceSnapshotCacheEntry,\n UnifiedSourceTrust,\n} from \"@skill-flow/domain/types\";\n\nexport function createEmptyImportDataCache(): ImportDataCache {\n return {\n searches: {},\n repos: {},\n recommendations: {},\n };\n}\n\nexport function normalizeImportDataCache(value: unknown): ImportDataCache {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return createEmptyImportDataCache();\n }\n\n const candidate = value as Record<string, unknown>;\n return {\n searches: normalizeSearchSnapshots(candidate.searches),\n repos: normalizeRepoSnapshots(candidate.repos, candidate.sources),\n recommendations: normalizeRecommendationFeeds(candidate.recommendations),\n };\n}\n\nexport function isImportDataCacheExpired(\n entry: { expiresAt: string },\n now = new Date(),\n): boolean {\n const expiresAt = Date.parse(entry.expiresAt);\n if (!Number.isFinite(expiresAt)) {\n return true;\n }\n return expiresAt <= now.getTime();\n}\n\nfunction normalizeSearchSnapshots(value: unknown): Record<string, ImportSearchSnapshot> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(value).flatMap(([query, snapshot]) => {\n const normalized = normalizeSearchSnapshot(query, snapshot);\n return normalized ? [[query, normalized] as const] : [];\n }),\n );\n}\n\nfunction normalizeRepoSnapshots(\n value: unknown,\n legacySources: unknown,\n): Record<string, RepoMetadataCacheEntry> {\n const repos = typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? Object.fromEntries(\n Object.entries(value).flatMap(([canonicalRepo, entry]) => {\n const normalized = normalizeRepoSnapshotEntry(canonicalRepo, entry);\n return normalized ? [[canonicalRepo, normalized] as const] : [];\n }),\n )\n : {};\n\n const legacy = typeof legacySources === \"object\" && legacySources !== null && !Array.isArray(legacySources)\n ? Object.fromEntries(\n Object.entries(legacySources).flatMap(([canonicalRepo, entry]) => {\n const normalized = normalizeSourceSnapshotEntry(canonicalRepo, entry);\n return normalized ? [[canonicalRepo, legacyRepoEntryFromSourceSnapshot(normalized)] as const] : [];\n }),\n )\n : {};\n\n return {\n ...legacy,\n ...repos,\n };\n}\n\nfunction normalizeRecommendationFeeds(value: unknown): Record<string, ImportRecommendationFeed> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(value).flatMap(([id, feed]) => {\n const normalized = normalizeRecommendationFeed(feed);\n return normalized ? [[id, normalized] as const] : [];\n }),\n );\n}\n\nfunction normalizeSearchSnapshot(\n query: string,\n value: unknown,\n): ImportSearchSnapshot | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n\n const candidate = value as Record<string, unknown>;\n const checkedAt = normalizeString(candidate.checkedAt);\n const expiresAt = normalizeString(candidate.expiresAt);\n if (!checkedAt || !expiresAt) {\n return undefined;\n }\n\n return {\n query,\n checkedAt,\n expiresAt,\n hits: normalizeSearchHits(candidate.hits),\n groups: normalizeStringArray(candidate.groups),\n };\n}\n\nfunction normalizeSourceSnapshotEntry(\n canonicalRepo: string,\n value: unknown,\n): UnifiedSourceSnapshotCacheEntry | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n\n const candidate = value as Record<string, unknown>;\n const checkedAt = normalizeString(candidate.checkedAt);\n const expiresAt = normalizeString(candidate.expiresAt);\n const data = normalizeUnifiedSourceSnapshot(candidate.data);\n if (!checkedAt || !expiresAt || !data) {\n return undefined;\n }\n\n return {\n canonicalRepo,\n checkedAt,\n expiresAt,\n data,\n };\n}\n\nfunction normalizeRepoSnapshotEntry(\n canonicalRepo: string,\n value: unknown,\n): RepoMetadataCacheEntry | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n\n const candidate = value as Record<string, unknown>;\n const checkedAt = normalizeString(candidate.checkedAt);\n const expiresAt = normalizeString(candidate.expiresAt);\n const identity = normalizeRepoIdentity(candidate.identity, canonicalRepo);\n const providers = normalizeRepoProviders(candidate.providers);\n const resolved = normalizeResolvedRepoMetadata(candidate.resolved);\n if (!checkedAt || !expiresAt || !identity || !resolved) {\n return undefined;\n }\n\n return {\n canonicalRepo,\n checkedAt,\n expiresAt,\n identity,\n providers,\n resolved,\n };\n}\n\nfunction normalizeRecommendationFeed(value: unknown): ImportRecommendationFeed | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n\n const candidate = value as Record<string, unknown>;\n const id = normalizeRecommendationFeedId(candidate.id);\n const checkedAt = normalizeString(candidate.checkedAt);\n const expiresAt = normalizeString(candidate.expiresAt);\n if (!id || !checkedAt || !expiresAt) {\n return undefined;\n }\n\n return {\n id,\n checkedAt,\n expiresAt,\n groups: normalizeStringArray(candidate.groups),\n };\n}\n\nfunction normalizeSearchHits(value: unknown): ImportSearchHit[] {\n if (!Array.isArray(value)) {\n return [];\n }\n\n return value.flatMap((item) => {\n if (typeof item !== \"object\" || item === null || Array.isArray(item)) {\n return [];\n }\n\n const candidate = item as Record<string, unknown>;\n const id = normalizeString(candidate.id);\n const skillId = normalizeString(candidate.skillId);\n const title = normalizeString(candidate.title) ?? normalizeString(candidate.name);\n const source = normalizeString(candidate.source);\n const canonicalRepo = normalizeString(candidate.canonicalRepo);\n if (!id || !skillId || !title || !source || !canonicalRepo) {\n return [];\n }\n\n return [{\n id,\n skillId,\n title,\n source,\n canonicalRepo,\n ...(normalizeNumber(candidate.installs) !== undefined\n ? { installs: normalizeNumber(candidate.installs)! }\n : {}),\n }];\n });\n}\n\nfunction normalizeUnifiedSourceSnapshot(value: unknown): UnifiedSourceSnapshot | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n\n const candidate = value as Record<string, unknown>;\n const canonicalRepo = normalizeString(candidate.canonicalRepo);\n const title = normalizeString(candidate.title);\n const sourceUrl = normalizeString(candidate.sourceUrl);\n const repoUrl = normalizeString(candidate.repoUrl);\n const repoLabel = normalizeString(candidate.repoLabel);\n const owner = normalizeSourceOwner(candidate.owner);\n if (!canonicalRepo || !title || !sourceUrl || !repoUrl || !repoLabel || !owner) {\n return undefined;\n }\n\n return {\n canonicalRepo,\n aliases: normalizeStringArray(candidate.aliases),\n title,\n provider: \"skills\",\n sourceUrl,\n repoUrl,\n repoLabel,\n ...(normalizeNumber(candidate.totalInstalls) !== undefined\n ? { totalInstalls: normalizeNumber(candidate.totalInstalls)! }\n : {}),\n ...(normalizeNumber(candidate.skillCount) !== undefined\n ? { skillCount: normalizeNumber(candidate.skillCount)! }\n : {}),\n ...(normalizeNumber(candidate.repoStars) !== undefined\n ? { repoStars: normalizeNumber(candidate.repoStars)! }\n : {}),\n ...(normalizeNumber(candidate.forkCount) !== undefined\n ? { forkCount: normalizeNumber(candidate.forkCount)! }\n : {}),\n ...(normalizeString(candidate.description)\n ? { description: normalizeString(candidate.description)! }\n : {}),\n ...(normalizeStringArray(candidate.topics).length > 0\n ? { topics: normalizeStringArray(candidate.topics) }\n : {}),\n ...(normalizeString(candidate.language)\n ? { language: normalizeString(candidate.language)! }\n : {}),\n ...(normalizeString(candidate.defaultBranch)\n ? { defaultBranch: normalizeString(candidate.defaultBranch)! }\n : {}),\n ...(normalizeString(candidate.pushedAt)\n ? { pushedAt: normalizeString(candidate.pushedAt)! }\n : {}),\n owner,\n skills: normalizeSourceSkills(candidate.skills),\n ...(normalizeSourceTrust(candidate.trust) ? { trust: normalizeSourceTrust(candidate.trust)! } : {}),\n };\n}\n\nfunction legacyRepoEntryFromSourceSnapshot(\n sourceEntry: UnifiedSourceSnapshotCacheEntry,\n): RepoMetadataCacheEntry {\n const snapshot = sourceEntry.data;\n return {\n canonicalRepo: sourceEntry.canonicalRepo,\n checkedAt: sourceEntry.checkedAt,\n expiresAt: sourceEntry.expiresAt,\n identity: {\n canonicalRepo: sourceEntry.canonicalRepo,\n aliases: snapshot.aliases,\n origins: [\"skills\"],\n },\n providers: {\n skills: {\n provider: \"skills\",\n status: \"ready\",\n checkedAt: sourceEntry.checkedAt,\n expiresAt: sourceEntry.expiresAt,\n snapshot,\n },\n },\n resolved: {\n ...(snapshot.title ? { title: snapshot.title } : {}),\n ...(snapshot.owner.slug ? { author: snapshot.owner.slug } : {}),\n ...(snapshot.description ? { summary: snapshot.description } : {}),\n ...(snapshot.repoUrl ? { githubUrl: snapshot.repoUrl } : {}),\n ...(snapshot.sourceUrl ? { sourceUrl: snapshot.sourceUrl } : {}),\n ...(snapshot.skillCount !== undefined ? { skillCount: snapshot.skillCount } : {}),\n ...(snapshot.totalInstalls !== undefined ? { downloadCount: snapshot.totalInstalls } : {}),\n ...(snapshot.repoStars !== undefined ? { starCount: snapshot.repoStars } : {}),\n fieldSources: buildFieldSources({\n title: snapshot.title,\n author: snapshot.owner.slug,\n summary: snapshot.description,\n githubUrl: snapshot.repoUrl,\n sourceUrl: snapshot.sourceUrl,\n skillCount: snapshot.skillCount,\n downloadCount: snapshot.totalInstalls,\n starCount: snapshot.repoStars,\n }, \"skills\"),\n },\n };\n}\n\nfunction normalizeRepoIdentity(\n value: unknown,\n canonicalRepo: string,\n): RepoMetadataIdentity | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n const candidate = value as Record<string, unknown>;\n const normalizedRepo = normalizeString(candidate.canonicalRepo) ?? canonicalRepo;\n if (!normalizedRepo) {\n return undefined;\n }\n return {\n canonicalRepo: normalizedRepo,\n aliases: normalizeStringArray(candidate.aliases),\n origins: normalizeRepoProviderArray(candidate.origins),\n };\n}\n\nfunction normalizeRepoProviders(\n value: unknown,\n): Partial<Record<RepoMetadataProvider, RepoMetadataProviderEntry>> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return {};\n }\n\n const candidate = value as Record<string, unknown>;\n const providers: Partial<Record<RepoMetadataProvider, RepoMetadataProviderEntry>> = {};\n for (const provider of [\"skills\", \"github\", \"clawhub\", \"local\"] as const) {\n const entry = normalizeRepoProviderEntry(candidate[provider], provider);\n if (entry) {\n providers[provider] = entry;\n }\n }\n return providers;\n}\n\nfunction normalizeRepoProviderEntry(\n value: unknown,\n provider: RepoMetadataProvider,\n): RepoMetadataProviderEntry | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n const candidate = value as Record<string, unknown>;\n const status = normalizeString(candidate.status);\n const checkedAt = normalizeString(candidate.checkedAt);\n const expiresAt = normalizeString(candidate.expiresAt);\n if (\n (status !== \"ready\" && status !== \"failed\" && status !== \"unsupported\")\n || !checkedAt\n || !expiresAt\n ) {\n return undefined;\n }\n\n const data = normalizeSourceStats(candidate.data);\n const snapshot = normalizeUnifiedSourceSnapshot(candidate.snapshot);\n\n return {\n provider,\n status,\n checkedAt,\n expiresAt,\n ...(normalizeString(candidate.reasonCode) ? { reasonCode: normalizeString(candidate.reasonCode)! as never } : {}),\n ...(typeof candidate.retryable === \"boolean\" ? { retryable: candidate.retryable } : {}),\n ...(data ? { data } : {}),\n ...(snapshot ? { snapshot } : {}),\n };\n}\n\nfunction normalizeResolvedRepoMetadata(value: unknown): ResolvedRepoMetadata | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n const candidate = value as Record<string, unknown>;\n return {\n ...(normalizeString(candidate.title) ? { title: normalizeString(candidate.title)! } : {}),\n ...(normalizeString(candidate.author) ? { author: normalizeString(candidate.author)! } : {}),\n ...(normalizeString(candidate.summary) ? { summary: normalizeString(candidate.summary)! } : {}),\n ...(normalizeString(candidate.githubUrl) ? { githubUrl: normalizeString(candidate.githubUrl)! } : {}),\n ...(normalizeString(candidate.sourceUrl) ? { sourceUrl: normalizeString(candidate.sourceUrl)! } : {}),\n ...(normalizeNumber(candidate.skillCount) !== undefined ? { skillCount: normalizeNumber(candidate.skillCount)! } : {}),\n ...(normalizeNumber(candidate.downloadCount) !== undefined ? { downloadCount: normalizeNumber(candidate.downloadCount)! } : {}),\n ...(normalizeNumber(candidate.starCount) !== undefined ? { starCount: normalizeNumber(candidate.starCount)! } : {}),\n fieldSources: normalizeFieldSources(candidate.fieldSources),\n };\n}\n\nfunction normalizeFieldSources(\n value: unknown,\n): Partial<Record<ResolvedRepoMetadataField, RepoMetadataProvider>> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return {};\n }\n const candidate = value as Record<string, unknown>;\n const fields: ResolvedRepoMetadataField[] = [\n \"title\",\n \"author\",\n \"summary\",\n \"githubUrl\",\n \"sourceUrl\",\n \"skillCount\",\n \"downloadCount\",\n \"starCount\",\n ];\n return Object.fromEntries(\n fields.flatMap((field) => {\n const provider = normalizeRepoProvider(candidate[field]);\n return provider ? [[field, provider] as const] : [];\n }),\n );\n}\n\nfunction normalizeRepoProviderArray(value: unknown): RepoMetadataProvider[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value.flatMap((item) => {\n const provider = normalizeRepoProvider(item);\n return provider ? [provider] : [];\n });\n}\n\nfunction normalizeRepoProvider(value: unknown): RepoMetadataProvider | undefined {\n const provider = normalizeString(value);\n if (provider === \"skills\" || provider === \"github\" || provider === \"clawhub\" || provider === \"local\") {\n return provider;\n }\n return undefined;\n}\n\nfunction normalizeSourceStats(value: unknown) {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n const candidate = value as Record<string, unknown>;\n const provider = normalizeSourceStatsProvider(candidate.provider);\n return {\n ...(provider ? { provider } : {}),\n ...(normalizeString(candidate.repoLabel) ? { repoLabel: normalizeString(candidate.repoLabel)! } : {}),\n ...(normalizeString(candidate.repoUrl) ? { repoUrl: normalizeString(candidate.repoUrl)! } : {}),\n ...(normalizeString(candidate.sourceUrl) ? { sourceUrl: normalizeString(candidate.sourceUrl)! } : {}),\n ...(normalizeNumber(candidate.starCount) !== undefined ? { starCount: normalizeNumber(candidate.starCount)! } : {}),\n ...(normalizeNumber(candidate.forkCount) !== undefined ? { forkCount: normalizeNumber(candidate.forkCount)! } : {}),\n ...(normalizeNumber(candidate.totalInstalls) !== undefined ? { totalInstalls: normalizeNumber(candidate.totalInstalls)! } : {}),\n ...(normalizeNumber(candidate.weeklyInstalls) !== undefined ? { weeklyInstalls: normalizeNumber(candidate.weeklyInstalls)! } : {}),\n ...(normalizeNumber(candidate.downloadCount) !== undefined ? { downloadCount: normalizeNumber(candidate.downloadCount)! } : {}),\n ...(normalizeString(candidate.ownerHandle) ? { ownerHandle: normalizeString(candidate.ownerHandle)! } : {}),\n ...(normalizeString(candidate.ownerDisplayName) ? { ownerDisplayName: normalizeString(candidate.ownerDisplayName)! } : {}),\n ...(normalizeString(candidate.summary) ? { summary: normalizeString(candidate.summary)! } : {}),\n ...(normalizeString(candidate.description) ? { description: normalizeString(candidate.description)! } : {}),\n ...(normalizeStringArray(candidate.topics).length > 0 ? { topics: normalizeStringArray(candidate.topics) } : {}),\n ...(normalizeString(candidate.language) ? { language: normalizeString(candidate.language)! } : {}),\n ...(normalizeString(candidate.defaultBranch) ? { defaultBranch: normalizeString(candidate.defaultBranch)! } : {}),\n ...(normalizeString(candidate.pushedAt) ? { pushedAt: normalizeString(candidate.pushedAt)! } : {}),\n };\n}\n\nfunction normalizeSourceStatsProvider(value: unknown): \"skills\" | \"github\" | \"clawhub\" | undefined {\n const provider = normalizeString(value);\n if (provider === \"skills\" || provider === \"github\" || provider === \"clawhub\") {\n return provider;\n }\n return undefined;\n}\n\nfunction normalizeSourceOwner(value: unknown): UnifiedSourceOwner | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n\n const candidate = value as Record<string, unknown>;\n const slug = normalizeString(candidate.slug);\n const sourceUrl = normalizeString(candidate.sourceUrl);\n if (!slug || !sourceUrl) {\n return undefined;\n }\n\n return {\n slug,\n sourceUrl,\n ...(normalizeString(candidate.githubUrl) ? { githubUrl: normalizeString(candidate.githubUrl)! } : {}),\n ...(normalizeNumber(candidate.sourceCount) !== undefined\n ? { sourceCount: normalizeNumber(candidate.sourceCount)! }\n : {}),\n ...(normalizeNumber(candidate.skillCount) !== undefined\n ? { skillCount: normalizeNumber(candidate.skillCount)! }\n : {}),\n ...(normalizeNumber(candidate.totalInstalls) !== undefined\n ? { totalInstalls: normalizeNumber(candidate.totalInstalls)! }\n : {}),\n };\n}\n\nfunction normalizeSourceSkills(value: unknown): UnifiedSourceSkill[] {\n if (!Array.isArray(value)) {\n return [];\n }\n\n return value.flatMap((item) => {\n if (typeof item !== \"object\" || item === null || Array.isArray(item)) {\n return [];\n }\n\n const candidate = item as Record<string, unknown>;\n const skillId = normalizeString(candidate.skillId);\n const title = normalizeString(candidate.title);\n if (!skillId || !title) {\n return [];\n }\n\n const installedOn = normalizeInstalledOn(candidate.installedOn);\n const audits = normalizeSkillAudits(candidate.audits);\n\n return [{\n skillId,\n title,\n ...(normalizeNumber(candidate.installs) !== undefined\n ? { installs: normalizeNumber(candidate.installs)! }\n : {}),\n ...(normalizeNumber(candidate.weeklyInstalls) !== undefined\n ? { weeklyInstalls: normalizeNumber(candidate.weeklyInstalls)! }\n : {}),\n ...(normalizeString(candidate.firstSeen)\n ? { firstSeen: normalizeString(candidate.firstSeen)! }\n : {}),\n ...(normalizeString(candidate.summary)\n ? { summary: normalizeString(candidate.summary)! }\n : {}),\n ...(installedOn.length > 0 ? { installedOn } : {}),\n ...(audits ? { audits } : {}),\n }];\n });\n}\n\nfunction normalizeInstalledOn(\n value: unknown,\n): UnifiedSourceSkillInstalledOn[] {\n if (!Array.isArray(value)) {\n return [];\n }\n\n return value.flatMap((item) => {\n if (typeof item !== \"object\" || item === null || Array.isArray(item)) {\n return [];\n }\n\n const candidate = item as Record<string, unknown>;\n const agent = normalizeString(candidate.agent);\n if (!agent) {\n return [];\n }\n\n return [{\n agent,\n ...(normalizeNumber(candidate.installs) !== undefined\n ? { installs: normalizeNumber(candidate.installs)! }\n : {}),\n }];\n });\n}\n\nfunction normalizeSkillAudits(value: unknown): UnifiedSourceSkill[\"audits\"] | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n\n const candidate = value as Record<string, unknown>;\n const normalized = {\n ...(normalizeString(candidate.gen) ? { gen: normalizeString(candidate.gen)! } : {}),\n ...(normalizeString(candidate.socket) ? { socket: normalizeString(candidate.socket)! } : {}),\n ...(normalizeString(candidate.snyk) ? { snyk: normalizeString(candidate.snyk)! } : {}),\n ...(normalizeString(candidate.riskLevel) ? { riskLevel: normalizeString(candidate.riskLevel)! } : {}),\n };\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction normalizeSourceTrust(value: unknown): UnifiedSourceTrust | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n\n const candidate = value as Record<string, unknown>;\n const normalized = {\n ...(typeof candidate.official === \"boolean\" ? { official: candidate.official } : {}),\n ...(typeof candidate.trending === \"boolean\" ? { trending: candidate.trending } : {}),\n ...(typeof candidate.hot === \"boolean\" ? { hot: candidate.hot } : {}),\n ...(typeof candidate.audited === \"boolean\" ? { audited: candidate.audited } : {}),\n };\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction normalizeRecommendationFeedId(value: unknown): ImportRecommendationFeedId | undefined {\n if (\n value === \"seed\"\n || value === \"official\"\n || value === \"trending\"\n || value === \"hot\"\n || value === \"audits\"\n ) {\n return value;\n }\n return undefined;\n}\n\nfunction normalizeString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n}\n\nfunction normalizeStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value.flatMap((item) => {\n const normalized = normalizeString(item);\n return normalized ? [normalized] : [];\n });\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction buildFieldSources(\n values: Partial<Record<ResolvedRepoMetadataField, unknown>>,\n provider: RepoMetadataProvider,\n): Partial<Record<ResolvedRepoMetadataField, RepoMetadataProvider>> {\n return Object.fromEntries(\n Object.entries(values).flatMap(([key, value]) => (value !== undefined && value !== \"\" ? [[key, provider]] : [])),\n ) as Partial<Record<ResolvedRepoMetadataField, RepoMetadataProvider>>;\n}\n", "import { SCHEMA_VERSION } from \"@skill-flow/integration/utils/constants\";\nimport { TARGET_ORDER } from \"@skill-flow/integration/utils/constants\";\nimport path from \"node:path\";\nimport type {\n CustomTargetDefinition,\n DraftBinding,\n ProjectScope,\n RecentProject,\n ScopedSourceDrafts,\n SharedPreferences,\n} from \"@skill-flow/domain/types\";\n\nexport function createEmptySharedPreferences(): SharedPreferences {\n return {\n schemaVersion: SCHEMA_VERSION,\n pinnedSourceIds: [],\n selectedProjectScope: { kind: \"global\" },\n recentProjects: [],\n projectDrafts: {},\n customTargets: [],\n agentDisplayOrder: [...TARGET_ORDER],\n };\n}\n\nexport function normalizeSharedPreferences(value: unknown): SharedPreferences {\n if (!isSharedPreferencesShape(value)) {\n return createEmptySharedPreferences();\n }\n\n const pinnedSourceIds = normalizePinnedSourceIds(value.pinnedSourceIds);\n const recentProjects = normalizeRecentProjects(value.recentProjects);\n const selectedProjectScope = normalizeSelectedProjectScope(value.selectedProjectScope, recentProjects);\n const projectDrafts = normalizeProjectDrafts(value.projectDrafts);\n const customTargets = normalizeCustomTargets(value.customTargets);\n const agentDisplayOrder = normalizeAgentDisplayOrder(value.agentDisplayOrder, customTargets);\n\n return {\n schemaVersion: SCHEMA_VERSION,\n pinnedSourceIds,\n selectedProjectScope,\n recentProjects,\n projectDrafts,\n customTargets,\n agentDisplayOrder,\n };\n}\n\nfunction normalizePinnedSourceIds(pinnedSourceIds: unknown): string[] {\n if (!Array.isArray(pinnedSourceIds)) {\n return [];\n }\n\n const seen = new Set<string>();\n const normalized: string[] = [];\n\n for (const pinnedSourceId of pinnedSourceIds) {\n if (typeof pinnedSourceId !== \"string\" || pinnedSourceId.length === 0 || seen.has(pinnedSourceId)) {\n continue;\n }\n seen.add(pinnedSourceId);\n normalized.push(pinnedSourceId);\n }\n\n return normalized;\n}\n\nfunction normalizeRecentProjects(value: unknown): RecentProject[] {\n if (!Array.isArray(value)) {\n return [];\n }\n\n const normalized: RecentProject[] = [];\n\n for (const entry of value) {\n if (!isRecentProject(entry)) {\n continue;\n }\n\n const recentProject: RecentProject = {\n projectId: entry.projectId,\n title: entry.title,\n lastActivityAt: entry.lastActivityAt,\n };\n\n if (typeof entry.projectPath === \"string\" && entry.projectPath.length > 0) {\n recentProject.projectPath = entry.projectPath;\n }\n\n if (isStringArray(entry.tools)) {\n recentProject.tools = entry.tools;\n }\n\n normalized.push(recentProject);\n }\n\n return normalized;\n}\n\nfunction normalizeSelectedProjectScope(\n scope: unknown,\n recentProjects: RecentProject[],\n): ProjectScope {\n if (isProjectScope(scope)) {\n if (scope.kind === \"global\") {\n return { kind: \"global\" };\n }\n\n if (recentProjects.some((project) => project.projectId === scope.projectId)) {\n return { kind: \"project\", projectId: scope.projectId };\n }\n }\n\n return { kind: \"global\" };\n}\n\nfunction normalizeProjectDrafts(value: unknown): ScopedSourceDrafts {\n if (typeof value !== \"object\" || value === null) {\n return {};\n }\n\n const normalized: ScopedSourceDrafts = {};\n\n for (const [projectId, projectDrafts] of Object.entries(value)) {\n if (typeof projectId !== \"string\" || projectId.length === 0) {\n continue;\n }\n\n if (typeof projectDrafts !== \"object\" || projectDrafts === null) {\n continue;\n }\n\n const projectScope: Record<string, DraftBinding> = {};\n const projectDraftRecord = projectDrafts as Record<string, unknown>;\n\n for (const [sourceId, draft] of Object.entries(projectDraftRecord)) {\n if (typeof sourceId !== \"string\" || sourceId.length === 0) {\n continue;\n }\n\n if (!isDraftBinding(draft)) {\n continue;\n }\n\n projectScope[sourceId] = {\n enabledTargets: draft.enabledTargets,\n selectedLeafIds: draft.selectedLeafIds,\n };\n }\n\n if (Object.keys(projectScope).length > 0) {\n normalized[projectId] = projectScope;\n }\n }\n\n return normalized;\n}\n\nfunction normalizeCustomTargets(value: unknown): CustomTargetDefinition[] {\n if (!Array.isArray(value)) {\n return [];\n }\n\n const normalized: CustomTargetDefinition[] = [];\n const seenIds = new Set<string>();\n const seenNames = new Set<string>();\n const builtinIds = new Set<string>(TARGET_ORDER);\n\n for (const candidate of value) {\n if (!isCustomTargetDefinition(candidate)) {\n continue;\n }\n\n const id = candidate.id.trim();\n const name = candidate.name.trim();\n const globalPath = candidate.globalPath.trim();\n const projectPathTemplate = normalizeRelativeProjectPath(candidate.projectPathTemplate);\n\n if (id.length === 0 || name.length === 0 || globalPath.length === 0 || projectPathTemplate === null) {\n continue;\n }\n\n const foldedName = name.toLocaleLowerCase();\n if (\n builtinIds.has(id) ||\n seenIds.has(id) ||\n seenNames.has(foldedName) ||\n !isSlugLikeId(id) ||\n !path.isAbsolute(globalPath)\n ) {\n continue;\n }\n\n seenIds.add(id);\n seenNames.add(foldedName);\n normalized.push({\n id,\n name,\n globalPath,\n projectPathTemplate,\n strategy: candidate.strategy,\n createdAt: candidate.createdAt,\n updatedAt: candidate.updatedAt,\n });\n }\n\n return normalized;\n}\n\nfunction normalizeAgentDisplayOrder(\n value: unknown,\n customTargets: CustomTargetDefinition[],\n): string[] {\n const knownIds = new Set<string>([...TARGET_ORDER, ...customTargets.map((target) => target.id)]);\n const normalized: string[] = [];\n const seen = new Set<string>();\n\n if (Array.isArray(value)) {\n for (const entry of value) {\n if (typeof entry !== \"string\" || seen.has(entry) || !knownIds.has(entry)) {\n continue;\n }\n seen.add(entry);\n normalized.push(entry);\n }\n }\n\n for (const targetId of TARGET_ORDER) {\n if (!seen.has(targetId)) {\n seen.add(targetId);\n normalized.push(targetId);\n }\n }\n\n for (const target of customTargets) {\n if (!seen.has(target.id)) {\n seen.add(target.id);\n normalized.push(target.id);\n }\n }\n\n return normalized;\n}\n\nfunction isSharedPreferencesShape(value: unknown): value is SharedPreferences {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"schemaVersion\" in value &&\n value.schemaVersion === SCHEMA_VERSION &&\n \"pinnedSourceIds\" in value &&\n Array.isArray(value.pinnedSourceIds)\n );\n}\n\nfunction isRecentProject(value: unknown): value is RecentProject & { tools?: unknown } {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const candidate = value as Partial<RecentProject> & { tools?: unknown };\n\n if (typeof candidate.projectId !== \"string\" || candidate.projectId.length === 0) {\n return false;\n }\n\n if (typeof candidate.title !== \"string\") {\n return false;\n }\n\n if (typeof candidate.lastActivityAt !== \"string\") {\n return false;\n }\n\n return true;\n}\n\nfunction isProjectScope(value: unknown): value is ProjectScope {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const candidate = value as ProjectScope;\n\n if (candidate.kind === \"global\") {\n return true;\n }\n\n return typeof candidate.projectId === \"string\" && candidate.projectId.length > 0;\n}\n\nfunction isDraftBinding(value: unknown): value is DraftBinding {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n return (\n isStringArray((value as DraftBinding).enabledTargets) &&\n isStringArray((value as DraftBinding).selectedLeafIds)\n );\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\");\n}\n\nfunction isCustomTargetDefinition(value: unknown): value is CustomTargetDefinition {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const candidate = value as CustomTargetDefinition;\n\n return (\n typeof candidate.id === \"string\" &&\n typeof candidate.name === \"string\" &&\n typeof candidate.globalPath === \"string\" &&\n typeof candidate.projectPathTemplate === \"string\" &&\n (candidate.strategy === \"symlink\" || candidate.strategy === \"copy\") &&\n typeof candidate.createdAt === \"string\" &&\n typeof candidate.updatedAt === \"string\"\n );\n}\n\nfunction normalizeRelativeProjectPath(value: string): string | null {\n const trimmed = value.trim();\n if (trimmed.length === 0 || path.isAbsolute(trimmed)) {\n return null;\n }\n\n const normalized = path.posix.normalize(trimmed.replaceAll(\"\\\\\", \"/\"));\n if (\n normalized.length === 0 ||\n normalized === \".\" ||\n normalized === \"..\" ||\n normalized.startsWith(\"../\") ||\n normalized === \"/\" ||\n path.posix.isAbsolute(normalized)\n ) {\n return null;\n }\n\n return normalized.startsWith(\"./\") ? normalized.slice(2) : normalized;\n}\n\nfunction isSlugLikeId(value: string): boolean {\n return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value);\n}\n", "import type {\n SourceMetadataCache,\n SourceMetadataCacheEntry,\n SourceMetadataProvider,\n SourceMetadataReasonCode,\n SourceMetadataResult,\n SourceStats,\n} from \"@skill-flow/domain/types\";\n\nexport function createEmptySourceMetadataCache(): SourceMetadataCache {\n return {};\n}\n\nexport function normalizeSourceMetadataCache(value: unknown): SourceMetadataCache {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return {};\n }\n\n const normalizedEntries = Object.entries(value).flatMap(([sourceId, entry]) => {\n const normalizedEntry = normalizeSourceMetadataCacheEntry(sourceId, entry);\n return normalizedEntry ? [[sourceId, normalizedEntry] as const] : [];\n });\n\n return Object.fromEntries(normalizedEntries);\n}\n\nexport function sourceMetadataResultToCacheEntry(args: {\n sourceId: string;\n result: SourceMetadataResult;\n checkedAt: string;\n expiresAt: string;\n}): SourceMetadataCacheEntry {\n const baseEntry = {\n sourceId: args.sourceId,\n checkedAt: args.checkedAt,\n expiresAt: args.expiresAt,\n status: args.result.status,\n } satisfies Pick<\n SourceMetadataCacheEntry,\n \"sourceId\" | \"checkedAt\" | \"expiresAt\" | \"status\"\n >;\n\n switch (args.result.status) {\n case \"ready\": {\n const data = normalizeSourceStats(args.result.data) ?? args.result.data;\n return {\n ...baseEntry,\n provider: args.result.provider,\n data,\n };\n }\n case \"unsupported\":\n return {\n ...baseEntry,\n ...(args.result.provider ? { provider: args.result.provider } : {}),\n reasonCode: args.result.reasonCode,\n };\n case \"failed\":\n return {\n ...baseEntry,\n ...(args.result.provider ? { provider: args.result.provider } : {}),\n reasonCode: args.result.reasonCode,\n retryable: args.result.retryable,\n };\n }\n}\n\nexport function sourceMetadataCacheEntryToResult(\n entry: SourceMetadataCacheEntry,\n): SourceMetadataResult {\n switch (entry.status) {\n case \"ready\": {\n const provider = entry.provider;\n const data = entry.data ? (normalizeSourceStats(entry.data) ?? entry.data) : undefined;\n if (!provider || !data) {\n return {\n status: \"unsupported\",\n reasonCode: \"provider_data_unavailable\",\n };\n }\n return {\n status: \"ready\",\n provider,\n data,\n };\n }\n case \"unsupported\":\n return {\n status: \"unsupported\",\n ...(entry.provider ? { provider: entry.provider } : {}),\n reasonCode: entry.reasonCode ?? \"provider_data_unavailable\",\n };\n case \"failed\":\n return {\n status: \"failed\",\n ...(entry.provider ? { provider: entry.provider } : {}),\n reasonCode: entry.reasonCode ?? \"provider_request_failed\",\n retryable: entry.retryable ?? true,\n };\n }\n}\n\nexport function isSourceMetadataCacheExpired(\n entry: SourceMetadataCacheEntry,\n now = new Date(),\n): boolean {\n const expiresAt = Date.parse(entry.expiresAt);\n if (!Number.isFinite(expiresAt)) {\n return true;\n }\n return expiresAt <= now.getTime();\n}\n\nfunction normalizeSourceMetadataCacheEntry(\n sourceId: string,\n value: unknown,\n): SourceMetadataCacheEntry | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n\n const candidate = value as Record<string, unknown>;\n const status = candidate.status;\n const checkedAt = candidate.checkedAt;\n const expiresAt = candidate.expiresAt;\n if (\n typeof status !== \"string\" ||\n !isCacheStatus(status) ||\n typeof checkedAt !== \"string\" ||\n checkedAt.length === 0 ||\n typeof expiresAt !== \"string\" ||\n expiresAt.length === 0\n ) {\n return undefined;\n }\n\n const provider = isSourceMetadataProvider(candidate.provider)\n ? candidate.provider\n : undefined;\n const reasonCode = isSourceMetadataReasonCode(candidate.reasonCode)\n ? candidate.reasonCode\n : undefined;\n const retryable = typeof candidate.retryable === \"boolean\"\n ? candidate.retryable\n : undefined;\n const data = normalizeSourceStats(candidate.data);\n\n return {\n sourceId,\n status,\n checkedAt,\n expiresAt,\n ...(provider ? { provider } : {}),\n ...(reasonCode ? { reasonCode } : {}),\n ...(retryable !== undefined ? { retryable } : {}),\n ...(data ? { data } : {}),\n };\n}\n\nfunction normalizeSourceStats(value: unknown): SourceStats | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n\n const candidate = value as Record<string, unknown>;\n const provider = isSourceMetadataProvider(candidate.provider)\n ? candidate.provider\n : undefined;\n const repoLabel = normalizeString(candidate.repoLabel);\n const repoUrl = normalizeString(candidate.repoUrl);\n const sourceUrl = normalizeString(candidate.sourceUrl);\n const starCount = normalizeNumber(candidate.starCount);\n const forkCount = normalizeNumber(candidate.forkCount);\n const totalInstalls = normalizeNumber(candidate.totalInstalls);\n const weeklyInstalls = normalizeNumber(candidate.weeklyInstalls);\n const downloadCount = normalizeNumber(candidate.downloadCount);\n const ownerHandle = normalizeString(candidate.ownerHandle);\n const ownerDisplayName = normalizeString(candidate.ownerDisplayName);\n const summary = normalizeString(candidate.summary);\n const description = normalizeString(candidate.description);\n const topics = Array.isArray(candidate.topics)\n ? candidate.topics.filter((item): item is string => typeof item === \"string\" && item.length > 0)\n : [];\n const language = normalizeString(candidate.language);\n const defaultBranch = normalizeString(candidate.defaultBranch);\n const pushedAt = normalizeString(candidate.pushedAt);\n\n const normalized = {\n ...(provider ? { provider } : {}),\n ...(repoLabel ? { repoLabel } : {}),\n ...(repoUrl ? { repoUrl } : {}),\n ...(sourceUrl ? { sourceUrl } : {}),\n ...(starCount !== undefined ? { starCount } : {}),\n ...(forkCount !== undefined ? { forkCount } : {}),\n ...(totalInstalls !== undefined ? { totalInstalls } : {}),\n ...(weeklyInstalls !== undefined ? { weeklyInstalls } : {}),\n ...(downloadCount !== undefined ? { downloadCount } : {}),\n ...(ownerHandle ? { ownerHandle } : {}),\n ...(ownerDisplayName ? { ownerDisplayName } : {}),\n ...(summary ? { summary } : {}),\n ...(description ? { description } : {}),\n ...(topics.length > 0 ? { topics } : {}),\n ...(language ? { language } : {}),\n ...(defaultBranch ? { defaultBranch } : {}),\n ...(pushedAt ? { pushedAt } : {}),\n } satisfies SourceStats;\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction normalizeString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction isCacheStatus(value: string): value is SourceMetadataCacheEntry[\"status\"] {\n return value === \"ready\" || value === \"unsupported\" || value === \"failed\";\n}\n\nfunction isSourceMetadataProvider(value: unknown): value is SourceMetadataProvider {\n return value === \"github\" || value === \"skills\" || value === \"clawhub\";\n}\n\nfunction isSourceMetadataReasonCode(value: unknown): value is SourceMetadataReasonCode {\n return (\n value === \"provider_not_supported\" ||\n value === \"provider_data_unavailable\" ||\n value === \"provider_request_failed\" ||\n value === \"provider_rate_limited\" ||\n value === \"provider_response_invalid\"\n );\n}\n", "export type BuiltinGitSource = {\n locator: string;\n branch: string;\n};\n\nexport function getBuiltinGitSources(): BuiltinGitSource[] {\n return [\n { locator: \"https://github.com/anthropics/skills.git\", branch: \"main\" },\n { locator: \"https://github.com/obra/superpowers.git\", branch: \"main\" },\n { locator: \"https://github.com/affaan-m/everything-claude-code.git\", branch: \"main\" },\n { locator: \"https://github.com/msitarzewski/agency-agents.git\", branch: \"main\" },\n { locator: \"https://github.com/nextlevelbuilder/ui-ux-pro-max-skill.git\", branch: \"main\" },\n { locator: \"https://github.com/sickn33/antigravity-awesome-skills.git\", branch: \"main\" },\n { locator: \"https://github.com/coreyhaines31/marketingskills.git\", branch: \"main\" },\n { locator: \"https://github.com/agentskills/agentskills.git\", branch: \"main\" },\n { locator: \"https://github.com/Leonxlnx/taste-skill.git\", branch: \"main\" },\n { locator: \"https://github.com/Affitor/affiliate-skills.git\", branch: \"main\" },\n { locator: \"https://github.com/luongnv89/skills.git\", branch: \"main\" },\n { locator: \"https://github.com/ComposioHQ/awesome-claude-skills.git\", branch: \"master\" },\n { locator: \"https://github.com/cexll/myclaude.git\", branch: \"master\" },\n { locator: \"https://github.com/JimLiu/baoyu-skills.git\", branch: \"main\" },\n { locator: \"https://github.com/dontbesilent2025/dbskill.git\", branch: \"main\" },\n { locator: \"https://github.com/garrytan/gstack.git\", branch: \"main\" },\n { locator: \"https://github.com/pbakaus/impeccable.git\", branch: \"main\" },\n { locator: \"https://github.com/zarazhangrui/frontend-slides.git\", branch: \"main\" },\n ];\n}\n", "type SourceLike = {\n id: string;\n locator: string;\n displayName: string;\n kind?: \"local\" | \"git\" | \"clawhub\";\n};\n\ntype ProjectedSkillInput = {\n leafId: string;\n groupId: string;\n groupName: string;\n groupAuthor?: string | undefined;\n skillName: string;\n};\n\nexport function parseHostedGitRepo(\n locator: string,\n): { host: string; owner: string; repo: string } | null {\n const trimmed = locator.trim().replace(/\\/+$/, \"\");\n\n if (/^https?:\\/\\//i.test(trimmed)) {\n try {\n const url = new URL(trimmed);\n const host = url.hostname.toLowerCase();\n const parts = url.pathname.split(\"/\").filter(Boolean);\n const [owner, rawRepo] = parts;\n const repo = rawRepo?.replace(/\\.git$/i, \"\");\n const isRepoRoot = parts.length === 2;\n const isTreePath = parts.length >= 4 && parts[2] === \"tree\";\n if (!isRepoRoot && !isTreePath) {\n return null;\n }\n if (!host || !owner || !repo) {\n return null;\n }\n return { host, owner, repo };\n } catch {\n return null;\n }\n }\n\n const sshMatch = trimmed.match(/^git@([^:\\s]+):([^/\\s]+)\\/([^/\\s]+?)(?:\\.git)?$/i);\n if (!sshMatch) {\n return null;\n }\n\n const host = sshMatch[1]?.toLowerCase();\n const owner = sshMatch[2];\n const repo = sshMatch[3];\n if (!host || !owner || !repo) {\n return null;\n }\n\n return { host, owner, repo };\n}\n\nexport function parseGitHubRepo(locator: string): { owner: string; repo: string } | null {\n const hostedRepo = parseHostedGitRepo(locator);\n if (hostedRepo?.host === \"github.com\") {\n return { owner: hostedRepo.owner, repo: hostedRepo.repo };\n }\n\n const trimmed = locator.trim().replace(/\\/+$/, \"\");\n const shorthandMatch = trimmed.match(/^([^/\\s:]+)\\/([^/\\s]+)$/);\n if (shorthandMatch) {\n const owner = shorthandMatch[1];\n const rawRepo = shorthandMatch[2];\n if (!owner || !rawRepo) {\n return null;\n }\n return {\n owner,\n repo: rawRepo.replace(/\\.git$/i, \"\"),\n };\n }\n\n return null;\n}\n\nexport function formatGroupLabel(source: SourceLike): string {\n if (source.kind === \"local\") {\n return `${source.displayName}@local`;\n }\n\n if (source.kind === \"clawhub\") {\n return `${source.displayName}@clawhub`;\n }\n\n const hostedRepo = parseHostedGitRepo(source.locator);\n if (!hostedRepo) {\n return source.displayName;\n }\n return `${source.displayName}@${hostedRepo.owner}`;\n}\n\nexport function getHostedGitOwner(locator: string): string | undefined {\n return parseHostedGitRepo(locator)?.owner ?? parseGitHubRepo(locator)?.owner;\n}\n\nexport function formatGroupRef(source: SourceLike): string {\n return `${formatGroupLabel(source)} [${source.id}]`;\n}\n\nexport function buildProjectedSkillName(\n groupName: string,\n skillName: string,\n groupAuthor?: string,\n): string {\n return `${getPreferredProjectedPrefix(groupName, skillName, groupAuthor)}-${skillName}`;\n}\n\nexport function buildProjectedSkillNameCandidates({\n preferredName,\n groupId,\n groupName,\n groupAuthor,\n skillName,\n}: {\n preferredName: string;\n groupId: string;\n groupName: string;\n groupAuthor?: string | undefined;\n skillName: string;\n}) {\n const candidates = [\n preferredName,\n buildProjectedSkillName(groupName, skillName, groupAuthor),\n buildRepoAuthorProjectedSkillName(groupName, skillName, groupAuthor),\n `${groupId}-${skillName}`,\n ];\n\n return [...new Set(candidates.filter((value): value is string => Boolean(value)))];\n}\n\nexport function resolveProjectedSkillNames(\n items: ProjectedSkillInput[],\n): Map<string, string> {\n const result = new Map<string, string>();\n const bySkillName = new Map<string, ProjectedSkillInput[]>();\n\n for (const item of items) {\n const group = bySkillName.get(item.skillName) ?? [];\n group.push(item);\n bySkillName.set(item.skillName, group);\n }\n\n for (const group of bySkillName.values()) {\n if (group.length <= 1) {\n const item = group[0];\n if (item) {\n result.set(item.leafId, item.skillName);\n }\n continue;\n }\n\n const preferredNames = group.map((item) => ({\n item,\n projectedName: buildProjectedSkillName(\n item.groupName,\n item.skillName,\n item.groupAuthor,\n ),\n }));\n const projectedNameCounts = new Map<string, number>();\n for (const preferred of preferredNames) {\n projectedNameCounts.set(\n preferred.projectedName,\n (projectedNameCounts.get(preferred.projectedName) ?? 0) + 1,\n );\n }\n\n for (const preferred of preferredNames) {\n if ((projectedNameCounts.get(preferred.projectedName) ?? 0) === 1) {\n result.set(preferred.item.leafId, preferred.projectedName);\n continue;\n }\n\n const repoAuthorProjectedName = buildRepoAuthorProjectedSkillName(\n preferred.item.groupName,\n preferred.item.skillName,\n preferred.item.groupAuthor,\n );\n if (\n repoAuthorProjectedName &&\n (projectedNameCounts.get(repoAuthorProjectedName) ?? 0) === 0\n ) {\n result.set(preferred.item.leafId, repoAuthorProjectedName);\n continue;\n }\n\n result.set(preferred.item.leafId, `${preferred.item.groupId}-${preferred.item.skillName}`);\n }\n }\n\n return result;\n}\n\nfunction getPreferredProjectedPrefix(\n groupName: string,\n skillName: string,\n groupAuthor?: string,\n) {\n if (skillName.startsWith(`${groupName}-`) && groupAuthor) {\n return groupAuthor;\n }\n return groupName;\n}\n\nfunction buildRepoAuthorProjectedSkillName(\n groupName: string,\n skillName: string,\n groupAuthor?: string,\n) {\n if (!groupAuthor) {\n return undefined;\n }\n return `${groupName}(${groupAuthor})-${skillName}`;\n}\n", "import type { SourceStats } from \"@skill-flow/domain/types\";\nimport { parseGitHubRepo } from \"./naming.js\";\n\ntype GitHubTreeResponse = {\n tree?: Array<{\n path?: string;\n type?: string;\n }>;\n};\n\ntype GitHubRepoResponse = {\n stargazers_count?: number;\n forks_count?: number;\n html_url?: string;\n description?: string;\n topics?: string[];\n language?: string | null;\n default_branch?: string;\n pushed_at?: string;\n};\n\nexport async function fetchGitHubSkillPaths(\n locator: string,\n branch: string,\n): Promise<string[]> {\n const repo = parseGitHubRepo(locator);\n if (!repo) {\n throw new Error(`Unsupported GitHub locator '${locator}'.`);\n }\n\n const response = await fetch(\n `https://api.github.com/repos/${repo.owner}/${repo.repo}/git/trees/${branch}?recursive=1`,\n { headers: buildGitHubHeaders() },\n );\n\n if (!response.ok) {\n throw new Error(`GitHub tree request failed with ${response.status}.`);\n }\n\n const payload = await response.json() as GitHubTreeResponse;\n return (payload.tree ?? [])\n .filter((entry) => entry.type === \"blob\" && entry.path?.endsWith(\"SKILL.md\"))\n .map((entry) => entry.path!)\n .sort((left, right) => left.localeCompare(right));\n}\n\nexport async function fetchGitHubRepoStarCount(locator: string): Promise<number | undefined> {\n const details = await fetchGitHubRepoDetails(locator);\n return details.starCount;\n}\n\nexport async function fetchGitHubRepoDetails(locator: string): Promise<SourceStats> {\n const repo = parseGitHubRepo(locator);\n if (!repo) {\n return {};\n }\n\n const response = await fetch(\n `https://api.github.com/repos/${repo.owner}/${repo.repo}`,\n { headers: buildGitHubHeaders() },\n );\n\n if (!response.ok) {\n if (response.status === 403) {\n throw createProviderError(\n \"GITHUB_RATE_LIMITED\",\n `GitHub repo request failed with ${response.status}.`,\n );\n }\n\n throw createProviderError(\n \"GITHUB_REPO_REQUEST_FAILED\",\n `GitHub repo request failed with ${response.status}.`,\n );\n }\n\n let payload: GitHubRepoResponse;\n try {\n payload = await response.json() as GitHubRepoResponse;\n } catch {\n throw createProviderError(\n \"GITHUB_REPO_RESPONSE_INVALID\",\n \"GitHub repo response payload was invalid.\",\n );\n }\n\n const starCount = typeof payload.stargazers_count === \"number\"\n ? payload.stargazers_count\n : undefined;\n const forkCount = typeof payload.forks_count === \"number\"\n ? payload.forks_count\n : undefined;\n const repoUrl = typeof payload.html_url === \"string\" && payload.html_url.length > 0\n ? payload.html_url\n : `https://github.com/${repo.owner}/${repo.repo}`;\n\n return {\n provider: \"github\",\n repoLabel: `${repo.owner}/${repo.repo}`,\n repoUrl,\n ...(starCount !== undefined ? { starCount } : {}),\n ...(forkCount !== undefined ? { forkCount } : {}),\n ...(typeof payload.description === \"string\" && payload.description.length > 0\n ? { description: payload.description }\n : {}),\n ...(Array.isArray(payload.topics) ? { topics: payload.topics.filter((item): item is string => typeof item === \"string\" && item.length > 0) } : {}),\n ...(typeof payload.language === \"string\" && payload.language.length > 0\n ? { language: payload.language }\n : {}),\n ...(typeof payload.default_branch === \"string\" && payload.default_branch.length > 0\n ? { defaultBranch: payload.default_branch }\n : {}),\n ...(typeof payload.pushed_at === \"string\" && payload.pushed_at.length > 0\n ? { pushedAt: payload.pushed_at }\n : {}),\n };\n}\n\nfunction buildGitHubHeaders(): Record<string, string> {\n return {\n Accept: \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2026-03-10\",\n ...(process.env.GITHUB_TOKEN\n ? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` }\n : {}),\n };\n}\n\nfunction createProviderError(code: string, message: string): Error & { code: string } {\n return Object.assign(new Error(message), { code });\n}\n", "import type { Failure, Result, Warning } from \"@skill-flow/domain/types\";\n\nexport function ok<T>(data: T, warnings: Warning[] = []): Result<T> {\n return { ok: true, data, warnings, errors: [] };\n}\n\nexport function fail<T>(\n errors: Failure | Failure[],\n warnings: Warning[] = [],\n data?: T,\n): Result<T> {\n const base = {\n ok: false,\n warnings,\n errors: Array.isArray(errors) ? errors : [errors],\n } as const;\n\n return data === undefined ? base : { ...base, data };\n}\n\nexport function mergeWarnings(...warningSets: Warning[][]): Warning[] {\n return warningSets.flat();\n}\n", "import { execFile } from \"node:child_process\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { promisify } from \"node:util\";\n\nconst execFileAsync = promisify(execFile);\n\ntype ClawHubOrigin = {\n slug: string;\n installedVersion: string;\n};\n\nexport class ClawHubSecurityBlockError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ClawHubSecurityBlockError\";\n }\n}\n\nexport type ClawHubInstallResult = {\n workdir: string;\n installedPath: string;\n slug: string;\n resolvedVersion: string;\n};\n\nexport type ClawHubSearchResult = {\n slug: string;\n title: string;\n score: number;\n};\n\nexport type ClawHubInspectResult = {\n skill: {\n slug: string;\n displayName: string;\n summary: string;\n stats?: {\n installsAllTime?: number;\n installsCurrent?: number;\n downloads?: number;\n stars?: number;\n };\n };\n owner?: {\n handle?: string;\n displayName?: string;\n };\n latestVersion?: {\n version: string;\n } | null;\n version?: {\n version: string;\n } | null;\n};\n\nexport async function clawhub(\n args: string[],\n options: { cwd?: string } = {},\n): Promise<string> {\n const { stdout } = await execFileAsync(\n \"npx\",\n [\"-y\", \"clawhub@latest\", ...args],\n {\n cwd: options.cwd,\n encoding: \"utf8\",\n env: process.env,\n },\n );\n\n return stdout.trim();\n}\n\nexport async function installClawHubSkill(\n slug: string,\n version?: string,\n): Promise<ClawHubInstallResult> {\n const workdir = await fs.mkdtemp(path.join(os.tmpdir(), \"skill-flow-clawhub-\"));\n const args = [\"--workdir\", workdir, \"install\", slug];\n if (version) {\n args.push(\"--version\", version);\n }\n\n try {\n await clawhub(args);\n } catch (error) {\n if (isSuspiciousClawHubInstallError(error)) {\n throw new ClawHubSecurityBlockError(\n `ClawHub security block: '${slug}' is flagged as suspicious. Use --force to install suspicious skills in non-interactive mode.`,\n );\n }\n throw error;\n }\n\n const installedPath = path.join(workdir, \"skills\", slug);\n const origin = JSON.parse(\n await fs.readFile(path.join(installedPath, \".clawhub\", \"origin.json\"), \"utf8\"),\n ) as ClawHubOrigin;\n\n return {\n workdir,\n installedPath,\n slug: origin.slug,\n resolvedVersion: origin.installedVersion,\n };\n}\n\nexport async function inspectClawHubSkill(\n slug: string,\n options: { version?: string; files?: boolean } = {},\n): Promise<ClawHubInspectResult> {\n const query = new URLSearchParams();\n if (options.version) {\n query.set(\"version\", options.version);\n }\n if (options.files) {\n query.set(\"files\", \"true\");\n }\n const queryString = query.toString();\n const response = await fetch(\n `https://clawhub.ai/api/v1/skills/${encodeURIComponent(slug)}${queryString ? `?${queryString}` : \"\"}`,\n );\n\n if (!response.ok) {\n if (response.status === 429) {\n throw createProviderError(\n \"CLAWHUB_RATE_LIMITED\",\n `ClawHub skill request failed with ${response.status}.`,\n );\n }\n\n throw createProviderError(\n \"CLAWHUB_SKILL_REQUEST_FAILED\",\n `ClawHub skill request failed with ${response.status}.`,\n );\n }\n\n try {\n return await response.json() as ClawHubInspectResult;\n } catch {\n throw createProviderError(\n \"CLAWHUB_RESPONSE_INVALID\",\n `Unable to parse ClawHub skill payload for '${slug}'.`,\n );\n }\n}\n\nexport async function searchClawHubSkills(\n query: string,\n limit = 10,\n): Promise<ClawHubSearchResult[]> {\n const output = await clawhub([\"search\", query, \"--limit\", String(limit)]);\n return output\n .split(\"\\n\")\n .map((line) => line.trim())\n .map((line) => {\n const match = line.match(/^(?:-\\s+)?([^\\s]+)\\s{2,}(.+?)\\s+\\(([0-9.]+)\\)$/);\n if (!match) {\n return null;\n }\n\n return {\n slug: match[1]!,\n title: match[2]!.trim(),\n score: Number(match[3]!),\n };\n })\n .filter((item): item is ClawHubSearchResult => item !== null);\n}\n\nfunction isSuspiciousClawHubInstallError(error: unknown): boolean {\n const message = getClawHubErrorMessage(error);\n return /use --force to install suspicious skills/i.test(message);\n}\n\nfunction getClawHubErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n const stderr = Reflect.get(error, \"stderr\");\n if (typeof stderr === \"string\" && stderr.trim().length > 0) {\n return stderr.trim();\n }\n\n if (error.message.trim().length > 0) {\n return error.message.trim();\n }\n }\n\n return String(error);\n}\n\nfunction createProviderError(code: string, message: string): Error & { code: string } {\n return Object.assign(new Error(message), { code });\n}\n", "import path from \"node:path\";\nimport { slugify } from \"./fs.js\";\nimport { parseGitHubRepo } from \"./naming.js\";\n\nfunction parseClawHubLocator(locator: string): { slug: string; version?: string } | null {\n const match = locator.trim().match(/^clawhub:([^@\\s]+)(?:@(.+))?$/);\n if (!match) {\n return null;\n }\n\n const slug = match[1];\n const version = match[2];\n if (!slug) {\n return null;\n }\n\n return version ? { slug, version } : { slug };\n}\n\nexport function deriveDisplayName(locator: string): string {\n const clawHubLocator = parseClawHubLocator(locator);\n if (clawHubLocator) {\n return clawHubLocator.slug.split(\"/\").pop() ?? clawHubLocator.slug;\n }\n\n const githubRepo = parseGitHubRepo(locator);\n if (githubRepo) {\n return githubRepo.repo;\n }\n\n const trimmed = locator.replace(/\\/+$/, \"\");\n if (/^[^/\\s]+\\/[^/\\s]+$/.test(trimmed)) {\n return trimmed.split(\"/\")[1] ?? trimmed;\n }\n\n if (trimmed.endsWith(\".git\")) {\n return path.basename(trimmed, \".git\");\n }\n\n return path.basename(trimmed) || slugify(locator);\n}\n\nexport function deriveSourceId(locator: string): string {\n const clawHubLocator = parseClawHubLocator(locator);\n if (clawHubLocator) {\n return slugify(`clawhub-${clawHubLocator.slug}`);\n }\n\n const githubRepo = parseGitHubRepo(locator);\n if (githubRepo) {\n return slugify(`${githubRepo.owner}-${githubRepo.repo}`);\n }\n\n const trimmed = locator.replace(/\\/+$/, \"\");\n if (path.isAbsolute(trimmed)) {\n return slugify(path.basename(trimmed) || locator);\n }\n\n return slugify(deriveDisplayName(locator) || locator);\n}\n", "import type {\n ImportGroupCandidate,\n ImportRecommendationFeedId,\n ImportSearchHit,\n SourceStats,\n UnifiedSourceOwner,\n UnifiedSourceSkill,\n UnifiedSourceSnapshot,\n UnifiedSourceTrust,\n} from \"@skill-flow/domain/types\";\nimport { fetchGitHubRepoDetails } from \"./github-catalog.js\";\nimport { parseGitHubRepo } from \"./naming.js\";\n\nconst SKILLS_DIRECTORY_BASE_URL = \"https://skills.sh\";\nexport const IMPORT_SEARCH_CACHE_TTL_MS = 5 * 60_000;\nexport const IMPORT_SOURCE_CACHE_TTL_MS = 5 * 60_000;\nexport const IMPORT_RECOMMENDATION_CACHE_TTL_MS = 5 * 60_000;\nexport const IMPORT_GITHUB_ENRICH_TTL_MS = 30 * 60_000;\nexport const IMPORT_DIRECTORY_CACHE_TTL_MS = IMPORT_SOURCE_CACHE_TTL_MS;\nconst SKILL_DETAIL_ENRICH_CONCURRENCY = 3;\n\nconst IMPORT_REPO_ALIASES = new Map<string, string>([\n [\"anthropic/skills\", \"anthropics/skills\"],\n]);\n\nconst FEED_PATHS: Record<Exclude<ImportRecommendationFeedId, \"seed\">, string> = {\n official: \"/official\",\n trending: \"/trending\",\n hot: \"/hot\",\n audits: \"/audits\",\n};\n\nexport type SkillsDirectorySearchHit = ImportSearchHit;\n\ntype SkillsDirectorySearchResponse = {\n skills?: Array<{\n id?: string;\n skillId?: string;\n name?: string;\n installs?: number;\n source?: string;\n }>;\n};\n\nexport type SkillsDirectoryGroupedResult = {\n canonicalRepo: string;\n matchedSkillNames: string[];\n matchedSkills: Array<{\n skillId: string;\n title: string;\n installs?: number;\n }>;\n};\n\nexport type SkillsDirectorySourceSkill = {\n skillId: string;\n title: string;\n installs?: number;\n};\n\nexport type SkillsDirectorySourcePage = {\n title?: string;\n skillCount?: number;\n totalInstalls?: number;\n repoUrl?: string;\n repoLabel?: string;\n skills: SkillsDirectorySourceSkill[];\n};\n\nexport type SkillsDirectoryOwnerPage = {\n slug: string;\n sourceUrl: string;\n githubUrl?: string;\n sourceCount?: number;\n skillCount?: number;\n totalInstalls?: number;\n};\n\nexport type SkillsDirectorySkillDetail = {\n skillId: string;\n title: string;\n summary?: string;\n weeklyInstalls?: number;\n repoLabel?: string;\n repoUrl?: string;\n repoStars?: number;\n firstSeen?: string;\n audits?: UnifiedSourceSkill[\"audits\"];\n installedOn?: UnifiedSourceSkill[\"installedOn\"];\n};\n\nexport function normalizeImportCanonicalRepo(input: string): string | undefined {\n const repo = parseGitHubRepo(input);\n if (!repo) {\n return undefined;\n }\n\n return applyImportRepoAlias(`${repo.owner}/${repo.repo}`.toLowerCase());\n}\n\nexport function buildImportRepoAliases(canonicalRepo: string): string[] {\n const repo = normalizeImportCanonicalRepo(canonicalRepo);\n if (!repo) {\n return [];\n }\n\n const aliases = new Set<string>([\n repo,\n `https://github.com/${repo}`,\n `https://github.com/${repo}.git`,\n `git@github.com:${repo}.git`,\n ]);\n\n for (const [alias, target] of IMPORT_REPO_ALIASES.entries()) {\n if (target === repo) {\n aliases.add(alias);\n aliases.add(`https://github.com/${alias}`);\n aliases.add(`https://github.com/${alias}.git`);\n aliases.add(`git@github.com:${alias}.git`);\n }\n }\n\n return [...aliases];\n}\n\nexport async function searchSkillsDirectory(\n query: string,\n limit = 20,\n): Promise<SkillsDirectorySearchHit[]> {\n const normalizedQuery = query.trim();\n if (!normalizedQuery) {\n return [];\n }\n\n const response = await fetch(\n `${SKILLS_DIRECTORY_BASE_URL}/api/search?q=${encodeURIComponent(normalizedQuery)}&limit=${limit}`,\n );\n if (!response.ok) {\n throw createProviderError(\n response.status === 429 ? \"SKILLS_SEARCH_RATE_LIMITED\" : \"SKILLS_SEARCH_REQUEST_FAILED\",\n `skills.sh search request failed with ${response.status}.`,\n );\n }\n\n let payload: SkillsDirectorySearchResponse;\n try {\n payload = await response.json() as SkillsDirectorySearchResponse;\n } catch {\n throw createProviderError(\n \"SKILLS_SEARCH_RESPONSE_INVALID\",\n \"skills.sh search response payload was invalid.\",\n );\n }\n\n return (payload.skills ?? []).flatMap((skill) => {\n if (\n typeof skill.id !== \"string\" ||\n typeof skill.skillId !== \"string\" ||\n typeof skill.name !== \"string\" ||\n typeof skill.source !== \"string\"\n ) {\n return [];\n }\n\n const canonicalRepo = normalizeImportCanonicalRepo(skill.source);\n if (!canonicalRepo) {\n return [];\n }\n\n return [{\n id: skill.id,\n skillId: skill.skillId,\n title: skill.name,\n ...(typeof skill.installs === \"number\" ? { installs: skill.installs } : {}),\n source: skill.source,\n canonicalRepo,\n } satisfies SkillsDirectorySearchHit];\n });\n}\n\nexport function groupSkillsDirectorySearchHits(\n hits: SkillsDirectorySearchHit[],\n): SkillsDirectoryGroupedResult[] {\n const grouped = new Map<string, Map<string, SkillsDirectoryGroupedResult[\"matchedSkills\"][number]>>();\n\n for (const hit of hits) {\n const skillsById = grouped.get(hit.canonicalRepo) ?? new Map();\n skillsById.set(hit.skillId, {\n skillId: hit.skillId,\n title: hit.title,\n ...(hit.installs !== undefined ? { installs: hit.installs } : {}),\n });\n grouped.set(hit.canonicalRepo, skillsById);\n }\n\n return [...grouped.entries()].map(([canonicalRepo, skillsById]) => {\n const matchedSkills = [...skillsById.values()]\n .sort((left, right) => {\n const installDiff = (right.installs ?? -1) - (left.installs ?? -1);\n return installDiff !== 0 ? installDiff : left.title.localeCompare(right.title);\n });\n\n return {\n canonicalRepo,\n matchedSkillNames: matchedSkills.map((skill) => skill.title),\n matchedSkills,\n };\n });\n}\n\nexport async function fetchSkillsDirectorySourceSnapshot(\n locator: string,\n options?: {\n enrichSkillIds?: string[];\n trust?: UnifiedSourceTrust;\n includeSkillDetails?: boolean;\n },\n): Promise<UnifiedSourceSnapshot> {\n const canonicalRepo = normalizeImportCanonicalRepo(locator);\n if (!canonicalRepo) {\n throw createProviderError(\"SKILLS_SOURCE_NOT_SUPPORTED\", `Unsupported locator '${locator}'.`);\n }\n\n const sourceUrl = `${SKILLS_DIRECTORY_BASE_URL}/${canonicalRepo}`;\n const ownerSlug = canonicalRepo.split(\"/\")[0] ?? \"\";\n const ownerUrl = `${SKILLS_DIRECTORY_BASE_URL}/${ownerSlug}`;\n const [sourceHtml, ownerHtml, repoDetails] = await Promise.all([\n fetchSkillsDirectoryHtml(sourceUrl, \"source\"),\n fetchSkillsDirectoryHtml(ownerUrl, \"owner\").catch(() => undefined),\n fetchGitHubRepoDetails(canonicalRepo).catch(() => ({} as SourceStats)),\n ]);\n\n const sourcePage = parseSkillsSourcePage(sourceHtml);\n if (sourcePage.skills.length === 0) {\n throw createProviderError(\n \"SKILLS_SOURCE_PARSE_FAILED\",\n \"skills.sh source page payload was missing skill entries.\",\n );\n }\n\n const owner = ownerHtml\n ? parseSkillsOwnerPage(ownerHtml, ownerSlug)\n : {\n slug: ownerSlug,\n sourceUrl: ownerUrl,\n };\n const includeSkillDetails = options?.includeSkillDetails !== undefined\n ? options.includeSkillDetails\n : true;\n const enrichedSkillMap = includeSkillDetails\n ? new Map(\n (await mapConcurrent(\n resolveSkillIdsToEnrich(sourcePage.skills, options?.enrichSkillIds),\n SKILL_DETAIL_ENRICH_CONCURRENCY,\n async (skillId) => {\n try {\n const html = await fetchSkillsDirectoryHtml(`${sourceUrl}/${encodeURIComponent(skillId)}`, \"skill\");\n return parseSkillsSkillPage(html, canonicalRepo, skillId);\n } catch {\n return undefined;\n }\n },\n )).flatMap((detail) => detail ? [[detail.skillId, detail] as const] : []),\n )\n : new Map<string, SkillsDirectorySkillDetail>();\n\n const skills: UnifiedSourceSkill[] = sourcePage.skills.map((skill) => {\n const detail = enrichedSkillMap.get(skill.skillId);\n return {\n skillId: skill.skillId,\n title: skill.title,\n ...(skill.installs !== undefined ? { installs: skill.installs } : {}),\n ...(detail?.weeklyInstalls !== undefined ? { weeklyInstalls: detail.weeklyInstalls } : {}),\n ...(detail?.firstSeen ? { firstSeen: detail.firstSeen } : {}),\n ...(detail?.summary ? { summary: detail.summary } : {}),\n ...(detail?.installedOn?.length ? { installedOn: detail.installedOn } : {}),\n ...(detail?.audits ? { audits: detail.audits } : {}),\n };\n });\n\n const repoUrl = sourcePage.repoUrl ?? repoDetails.repoUrl ?? `https://github.com/${canonicalRepo}`;\n const repoLabel = sourcePage.repoLabel ?? repoDetails.repoLabel ?? canonicalRepo;\n\n return {\n canonicalRepo,\n aliases: buildImportRepoAliases(canonicalRepo),\n title: sourcePage.title ?? canonicalRepo.split(\"/\")[1] ?? canonicalRepo,\n provider: \"skills\",\n sourceUrl,\n repoUrl,\n repoLabel,\n ...(sourcePage.totalInstalls !== undefined ? { totalInstalls: sourcePage.totalInstalls } : {}),\n ...(sourcePage.skillCount !== undefined ? { skillCount: sourcePage.skillCount } : {}),\n ...(repoDetails.starCount !== undefined ? { repoStars: repoDetails.starCount } : {}),\n ...(repoDetails.forkCount !== undefined ? { forkCount: repoDetails.forkCount } : {}),\n ...(repoDetails.description ? { description: repoDetails.description } : {}),\n ...(repoDetails.topics?.length ? { topics: repoDetails.topics } : {}),\n ...(repoDetails.language ? { language: repoDetails.language } : {}),\n ...(repoDetails.defaultBranch ? { defaultBranch: repoDetails.defaultBranch } : {}),\n ...(repoDetails.pushedAt ? { pushedAt: repoDetails.pushedAt } : {}),\n owner,\n skills,\n ...(options?.trust && hasTrustSignals(options.trust) ? { trust: options.trust } : {}),\n };\n}\n\nexport async function fetchSkillsDirectorySourcePreview(\n locator: string,\n options?: {\n trust?: UnifiedSourceTrust;\n },\n): Promise<UnifiedSourceSnapshot> {\n return fetchSkillsDirectorySourceSnapshot(locator, {\n includeSkillDetails: false,\n ...(options?.trust ? { trust: options.trust } : {}),\n });\n}\n\nexport async function fetchSkillsDirectoryFeedGroups(\n feedId: Exclude<ImportRecommendationFeedId, \"seed\">,\n): Promise<string[]> {\n const response = await fetch(`${SKILLS_DIRECTORY_BASE_URL}${FEED_PATHS[feedId]}`);\n if (!response.ok) {\n throw createProviderError(\n response.status === 429 ? \"SKILLS_FEED_RATE_LIMITED\" : \"SKILLS_FEED_REQUEST_FAILED\",\n `skills.sh feed request failed with ${response.status}.`,\n );\n }\n\n const html = await response.text();\n switch (feedId) {\n case \"official\":\n return extractOfficialFeedRepos(html);\n case \"trending\":\n case \"hot\":\n case \"audits\":\n return extractFeedSourceRepos(html);\n }\n}\n\nexport function buildImportGroupCandidate(\n args: {\n canonicalRepo: string;\n locator?: string;\n installed: boolean;\n matchedSkills?: Array<{\n skillId: string;\n title: string;\n installs?: number;\n }>;\n snapshot?: UnifiedSourceSnapshot;\n },\n): ImportGroupCandidate {\n const canonicalRepo = normalizeImportCanonicalRepo(args.canonicalRepo) ?? args.canonicalRepo;\n const locator = args.locator ?? canonicalRepo;\n const snapshot = args.snapshot;\n const title = snapshot?.title ?? canonicalRepo.split(\"/\")[1] ?? canonicalRepo;\n const matchedSkills = args.matchedSkills?.length ? args.matchedSkills : undefined;\n\n return {\n id: canonicalRepo,\n provider: \"skills\",\n locator,\n canonicalRepo,\n aliases: snapshot?.aliases ?? buildImportRepoAliases(canonicalRepo),\n title,\n installed: args.installed,\n ...(snapshot?.description ? { summary: snapshot.description } : {}),\n ...(snapshot?.sourceUrl ? { sourceUrl: snapshot.sourceUrl } : {}),\n ...(snapshot?.repoUrl ? { repoUrl: snapshot.repoUrl } : {}),\n ...(snapshot?.repoStars !== undefined ? { starCount: snapshot.repoStars } : {}),\n ...(snapshot?.totalInstalls !== undefined ? { totalInstalls: snapshot.totalInstalls } : {}),\n ...(snapshot?.skillCount !== undefined ? { skillCount: snapshot.skillCount } : {}),\n ...(matchedSkills?.length ? { matchedSkillNames: matchedSkills.map((skill) => skill.title) } : {}),\n ...(matchedSkills?.length ? { matchedSkills } : {}),\n ...(snapshot ? { snapshot } : {}),\n enrichState: { status: \"ready\" },\n previewState: { status: \"idle\" },\n };\n}\n\nexport function parseSkillsSourcePage(html: string): SkillsDirectorySourcePage {\n const titleMatch = html.match(/<h1[^>]*>([^<]+)<!-- -->\\/<!-- -->([^<]+)<\\/h1>/i);\n const skillCountMatch = html.match(/>(\\d+)<!-- -->\\s*<!-- -->skills</i);\n const totalInstallsMatch = html.match(/>([\\d.]+[KMB]?)<!-- --> total installs</i);\n const repoUrlMatch = html.match(/href=\"(https:\\/\\/github\\.com\\/[^\"]+)\"/i);\n const repoUrl = repoUrlMatch?.[1];\n const repo = repoUrl ? parseGitHubRepo(repoUrl) : null;\n const title = titleMatch?.[2]?.trim();\n\n return {\n ...(title ? { title } : {}),\n ...(skillCountMatch?.[1] ? { skillCount: Number.parseInt(skillCountMatch[1], 10) } : {}),\n ...(totalInstallsMatch?.[1] ? { totalInstalls: parseCompactNumber(totalInstallsMatch[1]) } : {}),\n ...(repoUrl ? { repoUrl } : {}),\n ...(repo ? { repoLabel: `${repo.owner}/${repo.repo}`.toLowerCase() } : {}),\n skills: parseSkillsSourceSkillList(html, repo?.owner && repo?.repo ? `${repo.owner}/${repo.repo}`.toLowerCase() : undefined),\n };\n}\n\nexport function parseSkillsOwnerPage(\n html: string,\n ownerSlug: string,\n): UnifiedSourceOwner {\n const sourceCountMatch = html.match(/>(\\d+)<!-- -->\\s*<!-- -->sources</i);\n const skillCountMatch = html.match(/>(\\d+)<!-- --> skills</i);\n const totalInstallsMatch = html.match(/>([\\d.]+[KMB]?)<!-- -->\\s*<!-- -->total installs</i);\n const githubUrlMatch = html.match(/href=\"(https:\\/\\/github\\.com\\/[^\"]+)\"[^>]*class=\"flex items-center gap-1 whitespace-nowrap\"/i);\n\n return {\n slug: ownerSlug,\n sourceUrl: `${SKILLS_DIRECTORY_BASE_URL}/${ownerSlug}`,\n ...(githubUrlMatch?.[1] ? { githubUrl: githubUrlMatch[1] } : {}),\n ...(sourceCountMatch?.[1] ? { sourceCount: Number.parseInt(sourceCountMatch[1], 10) } : {}),\n ...(skillCountMatch?.[1] ? { skillCount: Number.parseInt(skillCountMatch[1], 10) } : {}),\n ...(totalInstallsMatch?.[1] ? { totalInstalls: parseCompactNumber(totalInstallsMatch[1]) } : {}),\n };\n}\n\nexport function parseSkillsSkillPage(\n html: string,\n canonicalRepo: string,\n skillId: string,\n): SkillsDirectorySkillDetail {\n const title = html.match(/<h1[^>]*>([^<]+)<\\/h1>/i)?.[1]?.trim() ?? skillId;\n const summary = html.match(/<div class=\"\\[&amp;_.prose\\][^\"]*\"><div class=\"prose[^\"]*\"><p>(.*?)<\\/p>/is)?.[1];\n const weeklyInstalls = html.match(/Weekly Installs<\\/span><\\/div><div class=\"text-3xl[^\"]*\">([^<]+)</i)?.[1];\n const repoLinkMatch = html.match(/title=\"([^\"]+\\/[^\"]+)\"[^>]*>([^<]+\\/[^<]+)<\\/a>/i);\n const starMatch = html.match(/GitHub Stars<\\/span><\\/div><div[^>]*><div[^>]*><svg[^>]*><[^>]+><span>([^<]+)<\\/span>/i);\n const firstSeen = html.match(/First Seen<\\/span><\\/div><div class=\"text-sm font-mono text-foreground\">([^<]+)<\\/div>/i)?.[1];\n\n const installedOn = [...html.matchAll(\n /<div class=\"flex items-center justify-between text-sm py-2\"><span class=\"text-foreground\">([^<]+)<\\/span><span class=\"text-muted-foreground font-mono\">([^<]+)<\\/span><\\/div>/gi,\n )].map((match) => ({\n agent: match[1]!.trim(),\n installs: parseCompactNumber(match[2]!),\n }));\n\n const auditRows = [...html.matchAll(\n /<span class=\"text-sm font-medium text-foreground truncate\">([^<]+)<\\/span><span class=\"text-xs font-mono uppercase[^\"]*\">([^<]+)<\\/span>/gi,\n )];\n const audits = auditRows.reduce<NonNullable<UnifiedSourceSkill[\"audits\"]>>((result, match) => {\n const label = match[1]!.trim();\n const value = match[2]!.trim();\n if (label === \"Gen Agent Trust Hub\") {\n result.gen = value;\n } else if (label === \"Socket\") {\n result.socket = value;\n } else if (label === \"Snyk\") {\n result.snyk = value;\n result.riskLevel = value;\n }\n return result;\n }, {});\n\n return {\n skillId,\n title,\n ...(summary ? { summary: decodeHtml(stripTags(summary)).trim() } : {}),\n ...(weeklyInstalls ? { weeklyInstalls: parseCompactNumber(weeklyInstalls) } : {}),\n ...(repoLinkMatch?.[1] ? { repoLabel: repoLinkMatch[1] } : { repoLabel: canonicalRepo }),\n ...(repoLinkMatch?.[2] ? { repoUrl: `https://github.com/${repoLinkMatch[2]}` } : {}),\n ...(starMatch?.[1] ? { repoStars: parseCompactNumber(starMatch[1]) } : {}),\n ...(firstSeen ? { firstSeen: firstSeen.trim() } : {}),\n ...(Object.keys(audits).length > 0 ? { audits } : {}),\n ...(installedOn.length > 0 ? { installedOn } : {}),\n };\n}\n\nexport function parseSkillsSourceSkillList(\n html: string,\n canonicalRepo?: string,\n): SkillsDirectorySourceSkill[] {\n const escapedRepo = canonicalRepo?.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") ?? \"[^\\\"/]+/[^\\\"/]+\";\n const regex = new RegExp(\n `<a[^>]+href=\"/${escapedRepo}/([^\"/?#]+)\"[^>]*>.*?<h3[^>]*>([^<]+)</h3>(?:.*?<span[^>]*class=\"font-mono text-sm text-foreground\"[^>]*>([^<]+)</span>)?`,\n \"gis\",\n );\n const seen = new Set<string>();\n const skills: SkillsDirectorySourceSkill[] = [];\n\n for (const match of html.matchAll(regex)) {\n const skillId = match[1]?.trim();\n const title = match[2]?.trim();\n const installsValue = match[3]?.trim();\n if (!skillId || !title || skillId === \"opengraph-image\" || seen.has(skillId)) {\n continue;\n }\n\n seen.add(skillId);\n skills.push({\n skillId,\n title,\n ...(installsValue ? { installs: parseCompactNumber(installsValue) } : {}),\n });\n }\n\n return skills;\n}\n\nfunction resolveSkillIdsToEnrich(\n skills: SkillsDirectorySourceSkill[],\n requestedSkillIds?: string[],\n): string[] {\n const prioritized = [...skills]\n .sort((left, right) => {\n const diff = (right.installs ?? -1) - (left.installs ?? -1);\n return diff !== 0 ? diff : left.skillId.localeCompare(right.skillId);\n })\n .slice(0, 3)\n .map((skill) => skill.skillId);\n\n return [...new Set([...(requestedSkillIds ?? []), ...prioritized])];\n}\n\nexport function extractOfficialFeedRepos(html: string): string[] {\n const repos = new Set<string>();\n for (const match of html.matchAll(/\"repo\":\"([^\"]+\\/[^\"]+)\"/g)) {\n const canonicalRepo = normalizeImportCanonicalRepo(match[1]!);\n if (canonicalRepo) {\n repos.add(canonicalRepo);\n }\n }\n return [...repos];\n}\n\nexport function extractFeedSourceRepos(html: string): string[] {\n const repos = new Set<string>();\n for (const match of html.matchAll(/\"source\":\"([^\"]+)\"/g)) {\n const canonicalRepo = normalizeImportCanonicalRepo(decodeJsonString(match[1]!));\n if (canonicalRepo) {\n repos.add(canonicalRepo);\n }\n }\n return [...repos];\n}\n\nasync function fetchSkillsDirectoryHtml(\n url: string,\n kind: \"source\" | \"owner\" | \"skill\",\n): Promise<string> {\n const response = await fetch(url);\n if (!response.ok) {\n if (response.status === 404) {\n throw createProviderError(\n kind === \"source\" ? \"SKILLS_SOURCE_NOT_FOUND\" : \"SKILLS_PAGE_NOT_FOUND\",\n `skills.sh ${kind} page request failed with ${response.status}.`,\n );\n }\n throw createProviderError(\n response.status === 429 ? \"SKILLS_SOURCE_RATE_LIMITED\" : \"SKILLS_SOURCE_REQUEST_FAILED\",\n `skills.sh ${kind} page request failed with ${response.status}.`,\n );\n }\n\n return response.text();\n}\n\nfunction applyImportRepoAlias(repo: string): string {\n return IMPORT_REPO_ALIASES.get(repo) ?? repo;\n}\n\nfunction parseCompactNumber(value: string): number {\n const trimmed = value.trim().toUpperCase();\n const suffix = trimmed.slice(-1);\n const base = Number.parseFloat([\"K\", \"M\", \"B\"].includes(suffix) ? trimmed.slice(0, -1) : trimmed);\n\n if (!Number.isFinite(base)) {\n return 0;\n }\n\n switch (suffix) {\n case \"K\":\n return Math.round(base * 1_000);\n case \"M\":\n return Math.round(base * 1_000_000);\n case \"B\":\n return Math.round(base * 1_000_000_000);\n default:\n return Math.round(base);\n }\n}\n\nfunction stripTags(value: string): string {\n return value.replace(/<[^>]+>/g, \" \");\n}\n\nfunction decodeHtml(value: string): string {\n return value\n .replace(/&amp;/g, \"&\")\n .replace(/&#x26;/g, \"&\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, \"\\\"\")\n .replace(/&#39;/g, \"'\")\n .replace(/\\s+/g, \" \");\n}\n\nfunction decodeJsonString(value: string): string {\n return value.replace(/\\\\\"/g, \"\\\"\").replace(/\\\\u0026/g, \"&\").replace(/\\\\\\\\/g, \"\\\\\");\n}\n\nfunction hasTrustSignals(trust: UnifiedSourceTrust): boolean {\n return trust.official === true || trust.trending === true || trust.hot === true || trust.audited === true;\n}\n\nasync function mapConcurrent<T, R>(\n items: readonly T[],\n concurrency: number,\n worker: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n if (items.length === 0) {\n return [];\n }\n\n const limit = Math.max(1, Math.min(concurrency, items.length));\n const results = new Array<R>(items.length);\n let nextIndex = 0;\n\n await Promise.all(\n Array.from({ length: limit }, async () => {\n while (nextIndex < items.length) {\n const currentIndex = nextIndex;\n nextIndex += 1;\n results[currentIndex] = await worker(items[currentIndex]!, currentIndex);\n }\n }),\n );\n\n return results;\n}\n\nfunction createProviderError(code: string, message: string): Error & { code: string } {\n return Object.assign(new Error(message), { code });\n}\n", "import type {\n SourceManifestRecord,\n SourceMetadataProvider,\n SourceMetadataReasonCode,\n SourceMetadataResult,\n SourceStats,\n WorkflowSummary,\n} from \"@skill-flow/domain/types\";\nimport { inspectClawHubSkill } from \"./clawhub.js\";\nimport { fetchGitHubRepoDetails } from \"./github-catalog.js\";\nimport { parseGitHubRepo } from \"./naming.js\";\nimport {\n parseSkillsSourcePage,\n} from \"./skills-directory.js\";\n\nexport const SOURCE_METADATA_CACHE_TTL_MS = 8 * 60 * 60_000;\n\nexport async function fetchSourceDetails(\n source: SourceManifestRecord,\n lock: WorkflowSummary[\"lock\"],\n): Promise<SourceStats> {\n if (source.kind === \"clawhub\") {\n const slug = lock?.packageSlug ?? parseClawHubSlug(source.locator);\n if (!slug) {\n return {};\n }\n\n const inspected = await inspectClawHubSkill(slug);\n const ownerHandle = inspected.owner?.handle ? `@${inspected.owner.handle}` : undefined;\n return {\n provider: \"clawhub\",\n sourceUrl: `https://clawhub.ai/search?q=${encodeURIComponent(slug)}`,\n ...(inspected.skill.stats?.stars !== undefined ? { starCount: inspected.skill.stats.stars } : {}),\n ...(inspected.skill.stats?.installsAllTime !== undefined\n ? { totalInstalls: inspected.skill.stats.installsAllTime }\n : {}),\n ...(inspected.skill.stats?.installsCurrent !== undefined\n ? { weeklyInstalls: inspected.skill.stats.installsCurrent }\n : {}),\n ...(inspected.skill.stats?.downloads !== undefined\n ? { downloadCount: inspected.skill.stats.downloads }\n : {}),\n ...(ownerHandle ? { ownerHandle } : {}),\n ...(inspected.owner?.displayName ? { ownerDisplayName: inspected.owner.displayName } : {}),\n ...(inspected.skill.summary ? { summary: inspected.skill.summary } : {}),\n };\n }\n\n const githubLocator = resolveGitHubLocatorForMetadata(source);\n if (!githubLocator) {\n return {};\n }\n\n const skillsDetails = await fetchSkillsDirectorySourceDetails(githubLocator);\n return {\n provider: \"skills\",\n ...skillsDetails,\n };\n}\n\nexport async function fetchFreshSourceMetadata(\n source: SourceManifestRecord,\n lock: WorkflowSummary[\"lock\"],\n providerHint?: SourceMetadataProvider,\n): Promise<SourceMetadataResult> {\n if (source.kind === \"clawhub\") {\n try {\n return buildSourceMetadataResult(await fetchSourceDetails(source, lock), \"clawhub\");\n } catch (error) {\n return buildFailedSourceMetadataResult(\"clawhub\", error);\n }\n }\n\n const githubLocator = resolveGitHubLocatorForMetadata(source);\n if (!githubLocator) {\n return {\n status: \"unsupported\",\n reasonCode: \"provider_not_supported\",\n };\n }\n\n if (providerHint === \"skills\") {\n try {\n return buildSourceMetadataResult(\n await fetchSkillsDirectorySourceDetails(githubLocator),\n \"skills\",\n );\n } catch (error) {\n return buildFailedSourceMetadataResult(\"skills\", error);\n }\n }\n\n if (providerHint === \"github\") {\n try {\n return buildSourceMetadataResult(\n await fetchGitHubRepoDetails(githubLocator),\n \"github\",\n );\n } catch (error) {\n return buildFailedSourceMetadataResult(\"github\", error);\n }\n }\n\n try {\n return buildSourceMetadataResult(\n await fetchSkillsDirectorySourceDetails(githubLocator),\n \"skills\",\n );\n } catch (error) {\n if (!isSkillsSourceNotFoundError(error)) {\n return buildFailedSourceMetadataResult(\"skills\", error);\n }\n }\n\n try {\n return buildSourceMetadataResult(\n await fetchGitHubRepoDetails(githubLocator),\n \"github\",\n );\n } catch (error) {\n return buildFailedSourceMetadataResult(\"github\", error);\n }\n}\n\nexport async function fetchSkillsDirectorySourceDetails(locator: string): Promise<SourceStats> {\n const repo = parseGitHubRepo(locator);\n if (!repo) {\n return {};\n }\n\n const canonicalRepo = `${repo.owner}/${repo.repo}`.toLowerCase();\n const sourceUrl = `https://skills.sh/${canonicalRepo}`;\n const response = await fetch(sourceUrl);\n if (!response.ok) {\n if (response.status === 404) {\n throw createProviderError(\n \"SKILLS_SOURCE_NOT_FOUND\",\n `skills.sh source page request failed with ${response.status}.`,\n );\n }\n throw createProviderError(\n response.status === 429 ? \"SKILLS_SOURCE_RATE_LIMITED\" : \"SKILLS_SOURCE_REQUEST_FAILED\",\n `skills.sh source page request failed with ${response.status}.`,\n );\n }\n\n const details = parseSkillsSourcePage(await response.text());\n if (details.totalInstalls === undefined) {\n throw createProviderError(\n \"SKILLS_SOURCE_PARSE_FAILED\",\n \"skills.sh source page payload was missing total installs.\",\n );\n }\n const githubDetails: SourceStats = await fetchGitHubRepoDetails(canonicalRepo)\n .catch(() => ({} as SourceStats));\n return {\n provider: \"skills\",\n ...(details.repoLabel ? { repoLabel: details.repoLabel } : { repoLabel: canonicalRepo }),\n ...(details.repoUrl ? { repoUrl: details.repoUrl } : githubDetails.repoUrl ? { repoUrl: githubDetails.repoUrl } : { repoUrl: `https://github.com/${canonicalRepo}` }),\n sourceUrl,\n ...(details.totalInstalls !== undefined ? { totalInstalls: details.totalInstalls } : {}),\n ...(githubDetails.starCount !== undefined ? { starCount: githubDetails.starCount } : {}),\n ...(githubDetails.forkCount !== undefined ? { forkCount: githubDetails.forkCount } : {}),\n ...(githubDetails.description ? { description: githubDetails.description } : {}),\n ...(githubDetails.topics?.length ? { topics: githubDetails.topics } : {}),\n ...(githubDetails.language ? { language: githubDetails.language } : {}),\n ...(githubDetails.defaultBranch ? { defaultBranch: githubDetails.defaultBranch } : {}),\n ...(githubDetails.pushedAt ? { pushedAt: githubDetails.pushedAt } : {}),\n };\n}\n\nexport function buildSourceMetadataResult(\n sourceStats: SourceStats,\n providerHint?: SourceMetadataProvider,\n): SourceMetadataResult {\n const provider = sourceStats.provider ?? providerHint;\n if (!provider) {\n return {\n status: \"unsupported\",\n reasonCode: \"provider_not_supported\",\n };\n }\n\n const normalizedSourceStats = {\n ...sourceStats,\n provider,\n };\n\n if (!hasSourceStatsData(normalizedSourceStats)) {\n return {\n status: \"unsupported\",\n provider,\n reasonCode: \"provider_data_unavailable\",\n };\n }\n\n return {\n status: \"ready\",\n provider,\n data: normalizedSourceStats,\n };\n}\n\nexport function buildFailedSourceMetadataResult(\n provider: SourceMetadataProvider | undefined,\n error: unknown,\n): SourceMetadataResult {\n const reasonCode = inferFailedReasonCode(error);\n return {\n status: \"failed\",\n ...(provider ? { provider } : {}),\n reasonCode,\n retryable: reasonCode !== \"provider_response_invalid\",\n };\n}\n\nexport function inferSourceMetadataProvider(\n source: SourceManifestRecord,\n): SourceMetadataProvider | undefined {\n if (source.kind === \"clawhub\") {\n return \"clawhub\";\n }\n\n return resolveGitHubLocatorForMetadata(source) ? \"github\" : undefined;\n}\n\nexport function isSkillsSourceNotFoundError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === \"SKILLS_SOURCE_NOT_FOUND\"\n );\n}\n\nfunction resolveGitHubLocatorForMetadata(source: SourceManifestRecord): string | undefined {\n if (parseGitHubRepo(source.locator)) {\n return source.locator;\n }\n\n const originLocator = source.originLocator?.trim();\n if (originLocator && parseGitHubRepo(originLocator)) {\n return originLocator;\n }\n\n return undefined;\n}\n\nfunction inferFailedReasonCode(error: unknown): SourceMetadataReasonCode {\n if (hasProviderErrorCode(error, \"GITHUB_RATE_LIMITED\")) {\n return \"provider_rate_limited\";\n }\n\n if (hasProviderErrorCode(error, \"CLAWHUB_RATE_LIMITED\")) {\n return \"provider_rate_limited\";\n }\n\n if (\n hasProviderErrorCode(error, \"GITHUB_REPO_RESPONSE_INVALID\") ||\n hasProviderErrorCode(error, \"SKILLS_SOURCE_PARSE_FAILED\") ||\n hasProviderErrorCode(error, \"CLAWHUB_RESPONSE_INVALID\")\n ) {\n return \"provider_response_invalid\";\n }\n\n return \"provider_request_failed\";\n}\n\nfunction parseClawHubSlug(locator: string): string | undefined {\n const match = locator.match(/^clawhub:([^@\\s]+)(?:@.+)?$/);\n return match?.[1];\n}\n\nfunction hasSourceStatsData(sourceStats: SourceStats): boolean {\n return Object.entries(sourceStats).some(([key, value]) => key !== \"provider\" && value !== undefined);\n}\n\nfunction hasProviderErrorCode(error: unknown, code: string): error is Error & { code: string } {\n return typeof error === \"object\" && error !== null && \"code\" in error && error.code === code;\n}\n\nfunction createProviderError(code: string, message: string): Error & { code: string } {\n return Object.assign(new Error(message), { code });\n}\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type {\n DeploymentAction,\n DeploymentRecord,\n LockFile,\n ProjectionRecord,\n Result,\n} from \"@skill-flow/domain/types\";\nimport { getManagedDeployments } from \"@skill-flow/domain/projection-compat\";\nimport type { ChannelAdapter } from \"@skill-flow/integration/adapters/channel-adapters\";\nimport { copyDirectory, createSymlink, ensureDir, isPathInside, pathExists, removePath } from \"@skill-flow/integration/utils/fs\";\nimport { ok } from \"@skill-flow/integration/utils/result\";\n\nexport class DeploymentApplier {\n constructor(private readonly adapters: ChannelAdapter[] = []) {}\n\n async applyPlan(\n lockFile: LockFile,\n actions: DeploymentAction[],\n ): Promise<Result<{ applied: DeploymentAction[] }>> {\n const applied: DeploymentAction[] = [];\n const targetRoots = new Map(\n await Promise.all(\n this.adapters.map(async (adapter) => {\n const detection = await adapter.detect();\n return [adapter.target, detection.rootPath] as const;\n }),\n ),\n );\n\n for (const action of actions) {\n if (action.kind === \"blocked\" || action.kind === \"noop\") {\n continue;\n }\n\n this.assertManagedTargetPath(\n action.target,\n action.targetPath,\n targetRoots,\n action.targetRootPath,\n );\n if (action.kind === \"remove\") {\n const removeAction = action;\n if (\n (await pathExists(removeAction.targetPath)) &&\n !(await this.hasPersistentOwnerForPath(lockFile, actions, removeAction))\n ) {\n await removePath(removeAction.targetPath);\n }\n lockFile.projections = (lockFile.projections ?? []).filter(\n (projection) =>\n !(\n projection.mode === \"managed\" &&\n projection.sourceId === removeAction.sourceId &&\n projection.leafId === removeAction.leafId &&\n projection.target === removeAction.target\n ),\n );\n applied.push(removeAction);\n continue;\n }\n\n await ensureDir(path.dirname(action.targetPath));\n if (\n action.previousTargetPath &&\n action.previousTargetPath !== action.targetPath &&\n (await pathExists(action.previousTargetPath))\n ) {\n this.assertManagedTargetPath(\n action.target,\n action.previousTargetPath,\n targetRoots,\n action.previousTargetRootPath,\n );\n if (!(await this.hasPersistentOwnerForPath(lockFile, actions, action, action.previousTargetPath))) {\n await removePath(action.previousTargetPath);\n }\n }\n\n if (\n action.relocateExternalToTargetPath &&\n (await pathExists(action.targetPath))\n ) {\n this.assertManagedTargetPath(\n action.target,\n action.relocateExternalToTargetPath,\n targetRoots,\n action.targetRootPath,\n );\n await ensureDir(path.dirname(action.relocateExternalToTargetPath));\n await fs.rename(action.targetPath, action.relocateExternalToTargetPath);\n }\n\n if (action.strategy === \"symlink\") {\n await createSymlink(action.sourcePath, action.targetPath);\n } else {\n await copyDirectory(action.sourcePath, action.targetPath);\n }\n\n const nextRecord: DeploymentRecord = {\n sourceId: action.sourceId,\n leafId: action.leafId,\n target: action.target,\n targetPath: action.targetPath,\n ...(action.targetRootPath ? { targetRootPath: action.targetRootPath } : {}),\n strategy: action.strategy,\n status: \"active\",\n contentHash: action.contentHash,\n appliedAt: new Date().toISOString(),\n };\n const nextProjection: ProjectionRecord = {\n ...nextRecord,\n mode: \"managed\",\n };\n\n lockFile.projections = [\n ...(lockFile.projections ?? []).filter(\n (projection) =>\n !(\n projection.mode === \"managed\" &&\n projection.sourceId === action.sourceId &&\n projection.leafId === action.leafId &&\n projection.target === action.target\n ),\n ),\n nextProjection,\n ];\n applied.push(action);\n }\n\n return ok({ applied });\n }\n\n private async hasPersistentOwnerForPath(\n lockFile: LockFile,\n actions: DeploymentAction[],\n action: DeploymentAction,\n targetPath = action.targetPath,\n ): Promise<boolean> {\n const samePathDeployments = getManagedDeployments(lockFile).filter(\n (deployment) =>\n deployment.targetPath === targetPath &&\n !(\n deployment.sourceId === action.sourceId &&\n deployment.leafId === action.leafId &&\n deployment.target === action.target\n ),\n );\n if (samePathDeployments.length === 0) {\n return false;\n }\n\n return samePathDeployments.some((deployment) => {\n const plannedAction = actions.find(\n (candidate) =>\n candidate.sourceId === deployment.sourceId &&\n candidate.leafId === deployment.leafId &&\n candidate.target === deployment.target,\n );\n return plannedAction?.kind !== \"remove\";\n });\n }\n\n private assertManagedTargetPath(\n target: DeploymentAction[\"target\"],\n targetPath: string,\n targetRoots: Map<DeploymentAction[\"target\"], string>,\n explicitRootPath?: string,\n ) {\n const roots = [\n explicitRootPath,\n targetRoots.get(target),\n ].filter((value): value is string => Boolean(value));\n if (roots.length === 0) {\n throw new Error(`Managed target root is unavailable for ${target}.`);\n }\n\n if (!roots.some((rootPath) => isPathInside(rootPath, targetPath))) {\n throw new Error(`Refusing to modify path outside managed root for ${target}: ${targetPath}`);\n }\n }\n}\n", "import type {\n ConfigBootStatus,\n DeploymentTargetId,\n DoctorReport,\n DraftBinding,\n LockFile,\n Manifest,\n ProjectScope,\n RecentProject,\n Result,\n ScopedSourceDrafts,\n SharedPreferences,\n SourceUpdateResult,\n WorkflowSummary,\n} from \"@skill-flow/domain/types\";\nimport { formatGroupLabel } from \"@skill-flow/integration/utils/naming\";\nimport { fail, ok } from \"@skill-flow/integration/utils/result\";\nimport type { BootstrapEvent } from \"@skill-flow/core-engine/services/workspace-bootstrap-service\";\n\ntype ConfigCoordinatorDeps = {\n store: {\n init(): Promise<void>;\n readManifest(): Promise<Manifest>;\n readPreferences(): Promise<SharedPreferences>;\n writePreferences(preferences: SharedPreferences): Promise<void>;\n };\n recentProjectService: {\n listRecentProjects(): Promise<RecentProject[]>;\n };\n doctorService: {\n run(manifest: Manifest, lockFile: LockFile): Promise<Result<DoctorReport>>;\n };\n workflowService: {\n getSummaries(\n manifest: Manifest,\n lockFile: LockFile,\n audit?: DoctorReport,\n ): WorkflowSummary[];\n };\n getAvailableTargets(): Promise<DeploymentTargetId[]>;\n pruneMissingCheckouts(): Promise<Result<{ removedSourceIds: string[] }>>;\n getConfigData(): Promise<\n Result<{ manifest: Manifest; lockFile: LockFile; summaries: WorkflowSummary[] }>\n >;\n};\n\nexport type ConfigBootstrapData = {\n availableTargets: DeploymentTargetId[];\n manifest: Manifest;\n lockFile: LockFile;\n summaries: WorkflowSummary[];\n initialDrafts: Record<string, DraftBinding>;\n audit: DoctorReport;\n bootStatus: ConfigBootStatus;\n recentProjects: RecentProject[];\n selectedProjectScope: ProjectScope;\n projectDrafts: ScopedSourceDrafts;\n};\n\nexport class ConfigCoordinator {\n constructor(private readonly deps: ConfigCoordinatorDeps) {}\n\n async bootstrapWorkspaceState(\n onEvent?: (event: BootstrapEvent) => void,\n ): Promise<Result<ConfigBootstrapData>> {\n onEvent?.({\n phase: \"detect-targets\",\n level: \"info\",\n message: \"Detecting available agent targets...\",\n });\n const availableTargets = await this.deps.getAvailableTargets();\n\n const pruned = await this.deps.pruneMissingCheckouts();\n if (!pruned.ok) {\n return fail(pruned.errors, pruned.warnings);\n }\n if (pruned.data.removedSourceIds.length > 0) {\n onEvent?.({\n phase: \"refresh-sources\",\n level: \"warning\",\n message: `Removed ${pruned.data.removedSourceIds.length} missing group${pruned.data.removedSourceIds.length === 1 ? \"\" : \"s\"} from config state.`,\n });\n }\n\n onEvent?.({\n phase: \"normalize-bindings\",\n level: \"info\",\n message: \"Loading config state...\",\n });\n const configData = await this.deps.getConfigData();\n if (!configData.ok) {\n return fail(configData.errors, configData.warnings);\n }\n\n onEvent?.({\n phase: \"audit-projections\",\n level: \"info\",\n message: \"Auditing current projections...\",\n });\n const audit = await this.deps.doctorService.run(\n configData.data.manifest,\n configData.data.lockFile,\n );\n if (!audit.ok) {\n return fail(audit.errors, audit.warnings);\n }\n\n onEvent?.({\n phase: \"build-summaries\",\n level: \"info\",\n message: \"Building config summaries...\",\n });\n const summaries = this.deps.workflowService.getSummaries(\n configData.data.manifest,\n configData.data.lockFile,\n audit.data,\n );\n const bootStatus: ConfigBootStatus = {\n phase: \"success\",\n updatedSourceIds: [],\n failedSources: [],\n };\n\n // Refresh recent projects and reconcile selected scope against them.\n // This is preference-layer state, not part of manifest/lock global config.\n const recentProjects = await this.deps.recentProjectService.listRecentProjects().catch(() => []);\n const currentPreferences = await this.deps.store.readPreferences();\n await this.deps.store.writePreferences({\n ...currentPreferences,\n recentProjects,\n });\n const reconciledPreferences = await this.deps.store.readPreferences();\n\n onEvent?.({\n phase: \"done\",\n level: \"success\",\n message: \"Config bootstrap complete.\",\n });\n\n return ok({\n availableTargets,\n manifest: configData.data.manifest,\n lockFile: configData.data.lockFile,\n summaries,\n initialDrafts: buildInitialDrafts(summaries),\n audit: audit.data,\n bootStatus,\n recentProjects: reconciledPreferences.recentProjects,\n selectedProjectScope: reconciledPreferences.selectedProjectScope,\n projectDrafts: reconciledPreferences.projectDrafts,\n });\n }\n}\n\nfunction buildInitialDrafts(summaries: WorkflowSummary[]): Record<string, DraftBinding> {\n return Object.fromEntries(\n summaries.map((summary) => {\n const enabledTargets = Object.entries(summary.bindings.targets)\n .filter(([, value]) => value?.enabled)\n .map(([target]) => target) as DraftBinding[\"enabledTargets\"];\n const selectedLeafIds = [\n ...new Set(\n (summary.bindings.selectedLeafIds && summary.bindings.selectedLeafIds.length > 0\n ? summary.bindings.selectedLeafIds\n : enabledTargets.flatMap((target) => summary.bindings.targets[target]?.leafIds ?? [])),\n ),\n ];\n return [summary.source.id, { enabledTargets, selectedLeafIds }];\n }),\n );\n}\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type {\n DeploymentAction,\n DeploymentPlan,\n DeploymentRecord,\n DeploymentTargetId,\n LeafRecord,\n LockFile,\n Manifest,\n Result,\n Warning,\n} from \"@skill-flow/domain/types\";\nimport { getManagedDeployments } from \"@skill-flow/domain/projection-compat\";\nimport type { ChannelAdapter } from \"@skill-flow/integration/adapters/channel-adapters\";\nimport {\n buildProjectedSkillNameCandidates,\n getHostedGitOwner,\n resolveProjectedSkillNames,\n} from \"@skill-flow/integration/utils/naming\";\nimport { fail, ok } from \"@skill-flow/integration/utils/result\";\n\nexport class DeploymentPlanner {\n constructor(private readonly adapters: ChannelAdapter[]) {}\n\n async planForSource(\n sourceId: string,\n manifest: Manifest,\n lockFile: LockFile,\n ): Promise<Result<DeploymentPlan>> {\n const binding = manifest.bindings[sourceId] ?? { targets: {} };\n const source = manifest.sources.find((item) => item.id === sourceId);\n const leafs = lockFile.leafInventory.filter((leaf) => leaf.sourceId === sourceId);\n const previousDeployments = getManagedDeployments(lockFile).filter(\n (deployment) => deployment.sourceId === sourceId,\n );\n const actions: DeploymentAction[] = [];\n const warnings: Warning[] = [];\n\n for (const adapter of this.adapters) {\n const detection = await adapter.detect();\n const targetBinding = binding.targets[adapter.target];\n const desiredLeafIds =\n targetBinding?.enabled === true ? new Set(targetBinding.leafIds) : new Set<string>();\n const projectedLinkNames = this.buildProjectedLinkNameMap(\n manifest,\n lockFile,\n adapter.target,\n );\n\n const plannedForTarget = await this.planTarget(\n sourceId,\n adapter,\n detection.available,\n detection.rootPath,\n detection.reason,\n desiredLeafIds,\n leafs,\n previousDeployments,\n lockFile,\n projectedLinkNames,\n {\n id: sourceId,\n displayName: source?.displayName ?? sourceId,\n author: getHostedGitOwner(source?.locator ?? \"\"),\n },\n );\n\n actions.push(...plannedForTarget.actions);\n warnings.push(...plannedForTarget.warnings);\n }\n\n return ok({\n actions,\n warnings,\n blocked: actions.filter((action) => action.kind === \"blocked\"),\n });\n }\n\n // fetch -> scan -> diff -> replan -> reapply\n //\n // desired bindings + lock state + disk state\n // -> create | update | remove | noop | blocked\n private async planTarget(\n sourceId: string,\n adapter: ChannelAdapter,\n targetAvailable: boolean,\n rootPath: string,\n unavailableReason: string | undefined,\n desiredLeafIds: Set<string>,\n leafs: LeafRecord[],\n previousDeployments: DeploymentRecord[],\n lockFile: LockFile,\n projectedLinkNames: Map<string, string>,\n sourceRef: { id: string; displayName: string; author?: string | undefined },\n ): Promise<DeploymentPlan> {\n const actions: DeploymentAction[] = [];\n const warnings: Warning[] = [];\n const desiredLeafs = leafs.filter((leaf) => desiredLeafIds.has(leaf.id));\n const deploymentsForTarget = previousDeployments.filter(\n (deployment) => deployment.target === adapter.target,\n );\n const managedByLeafId = new Map(\n deploymentsForTarget.map((deployment) => [deployment.leafId, deployment]),\n );\n const missingDesiredLeafIds = [...desiredLeafIds].filter(\n (leafId) => !desiredLeafs.some((leaf) => leaf.id === leafId),\n );\n\n for (const missingLeafId of missingDesiredLeafIds) {\n const existing = managedByLeafId.get(missingLeafId);\n warnings.push({\n code: \"MISSING_LEAF_SELECTION\",\n message: `${missingLeafId} no longer exists in source inventory.`,\n });\n if (existing) {\n actions.push({\n kind: \"remove\",\n sourceId,\n leafId: missingLeafId,\n target: existing.target,\n strategy: existing.strategy,\n sourcePath: \"\",\n targetPath: existing.targetPath,\n ...(existing.targetRootPath ? { targetRootPath: existing.targetRootPath } : {}),\n contentHash: existing.contentHash,\n reason: \"Selected leaf no longer exists in source inventory.\",\n });\n }\n }\n\n for (const leaf of desiredLeafs) {\n const existing = managedByLeafId.get(leaf.id);\n const projectedLinkName = projectedLinkNames.get(leaf.id) ?? leaf.linkName;\n const targetPathCandidates = buildProjectedSkillNameCandidates({\n preferredName: projectedLinkName,\n groupId: sourceRef.id,\n groupName: sourceRef.displayName,\n groupAuthor: sourceRef.author,\n skillName: leaf.linkName,\n }).map((linkName) => ({\n linkName,\n targetPath: adapter.resolveTargetPath(rootPath, linkName),\n }));\n const preferredTargetPath = targetPathCandidates[0]?.targetPath ?? adapter.resolveTargetPath(rootPath, projectedLinkName);\n\n if (!targetAvailable) {\n const blockedAction: DeploymentAction = {\n kind: \"blocked\",\n sourceId,\n leafId: leaf.id,\n target: adapter.target,\n strategy: adapter.strategy,\n sourcePath: leaf.absolutePath,\n targetPath: preferredTargetPath,\n contentHash: leaf.contentHash,\n ...(unavailableReason ? { reason: unavailableReason } : {}),\n };\n actions.push(blockedAction);\n continue;\n }\n\n let chosenCandidate:\n | {\n linkName: string;\n targetPath: string;\n diskState: Awaited<ReturnType<DeploymentPlanner[\"inspectTargetPath\"]>>;\n relocateExternalToTargetPath?: string;\n }\n | undefined;\n const inspectedCandidates: Array<{\n linkName: string;\n targetPath: string;\n diskState: Awaited<ReturnType<DeploymentPlanner[\"inspectTargetPath\"]>>;\n }> = [];\n\n for (const candidate of targetPathCandidates) {\n const diskState = await this.inspectTargetPath(\n candidate.targetPath,\n leaf.absolutePath,\n leaf,\n lockFile,\n );\n inspectedCandidates.push({\n ...candidate,\n diskState,\n });\n if (\n diskState.managedBySkillFlow &&\n !(\n (existing &&\n diskState.managedDeployment?.sourceId === existing.sourceId &&\n diskState.managedDeployment?.leafId === existing.leafId &&\n diskState.managedDeployment?.target === existing.target) ||\n (diskState.managedDeployment?.sourceId === sourceId &&\n diskState.managedDeployment?.leafId === leaf.id)\n )\n ) {\n continue;\n }\n\n if (diskState.foreign && !diskState.externalExactMatch) {\n continue;\n }\n\n chosenCandidate = {\n ...candidate,\n diskState,\n };\n break;\n }\n\n if (!chosenCandidate) {\n chosenCandidate = await this.buildExternalRelocationCandidate(\n preferredTargetPath,\n inspectedCandidates,\n leaf,\n rootPath,\n );\n }\n\n if (!chosenCandidate) {\n actions.push({\n kind: \"blocked\",\n sourceId,\n leafId: leaf.id,\n target: adapter.target,\n strategy: adapter.strategy,\n sourcePath: leaf.absolutePath,\n targetPath: preferredTargetPath,\n reason: \"Foreign content already exists at target path and no safe fallback name is available.\",\n contentHash: leaf.contentHash,\n });\n continue;\n }\n\n if (\n chosenCandidate.targetPath !== preferredTargetPath &&\n !chosenCandidate.diskState.externalExactMatch\n ) {\n warnings.push({\n code: \"EXTERNAL_NAME_COLLISION_RENAMED\",\n message: `${leaf.linkName} kept existing target content at ${preferredTargetPath} and will deploy as ${chosenCandidate.linkName}.`,\n });\n }\n if (chosenCandidate.relocateExternalToTargetPath) {\n warnings.push({\n code: \"EXTERNAL_SKILL_RELOCATED\",\n message: `${leaf.linkName} reclaimed ${preferredTargetPath} and moved the external skill to ${chosenCandidate.relocateExternalToTargetPath}.`,\n });\n }\n\n const kind = this.resolveDesiredAction(\n existing,\n chosenCandidate.diskState.matchesExpected,\n leaf,\n );\n actions.push({\n kind,\n sourceId,\n leafId: leaf.id,\n target: adapter.target,\n strategy: adapter.strategy,\n sourcePath: leaf.absolutePath,\n targetPath: chosenCandidate.targetPath,\n ...((chosenCandidate.targetPath === preferredTargetPath ||\n chosenCandidate.targetPath.startsWith(`${rootPath}${path.sep}`))\n ? { targetRootPath: rootPath }\n : (existing?.targetRootPath\n ? { targetRootPath: existing.targetRootPath }\n : {})),\n ...(existing && existing.targetPath !== chosenCandidate.targetPath\n ? {\n previousTargetPath: existing.targetPath,\n ...(existing.targetRootPath\n ? { previousTargetRootPath: existing.targetRootPath }\n : {}),\n }\n : {}),\n ...(chosenCandidate.relocateExternalToTargetPath\n ? { relocateExternalToTargetPath: chosenCandidate.relocateExternalToTargetPath }\n : {}),\n contentHash: leaf.contentHash,\n });\n }\n\n for (const deployment of deploymentsForTarget) {\n if (desiredLeafIds.has(deployment.leafId)) {\n continue;\n }\n\n actions.push({\n kind: \"remove\",\n sourceId,\n leafId: deployment.leafId,\n target: deployment.target,\n strategy: deployment.strategy,\n sourcePath: \"\",\n targetPath: deployment.targetPath,\n ...(deployment.targetRootPath ? { targetRootPath: deployment.targetRootPath } : {}),\n contentHash: deployment.contentHash,\n });\n }\n\n return { actions, warnings, blocked: actions.filter((item) => item.kind === \"blocked\") };\n }\n\n private resolveDesiredAction(\n existing: DeploymentRecord | undefined,\n matchesExpected: boolean,\n leaf: LeafRecord,\n ): DeploymentAction[\"kind\"] {\n if (!existing) {\n return matchesExpected ? \"noop\" : \"create\";\n }\n\n if (!matchesExpected) {\n return \"update\";\n }\n\n return existing.contentHash === leaf.contentHash ? \"noop\" : \"update\";\n }\n\n private async inspectTargetPath(\n targetPath: string,\n expectedSourcePath: string,\n leaf: LeafRecord,\n lockFile: LockFile,\n ): Promise<{\n exists: boolean;\n matchesExpected: boolean;\n foreign: boolean;\n managedBySkillFlow: boolean;\n managedDeployment?: DeploymentRecord;\n externalExactMatch: boolean;\n identity?: { name: string; description: string };\n }> {\n try {\n const managedDeployment = getManagedDeployments(lockFile).find(\n (deployment) => deployment.targetPath === targetPath && deployment.status === \"active\",\n );\n const stats = await fs.lstat(targetPath);\n if (stats.isSymbolicLink()) {\n const linked = await fs.readlink(targetPath);\n const resolved = path.resolve(path.dirname(targetPath), linked);\n const matchesExpected = resolved === expectedSourcePath;\n return {\n exists: true,\n matchesExpected,\n foreign: !matchesExpected,\n managedBySkillFlow: Boolean(managedDeployment),\n ...(managedDeployment ? { managedDeployment } : {}),\n ...(await this.buildExternalIdentityState(targetPath, leaf, managedDeployment)),\n };\n }\n return {\n exists: true,\n matchesExpected: false,\n foreign: true,\n managedBySkillFlow: Boolean(managedDeployment),\n ...(managedDeployment ? { managedDeployment } : {}),\n ...(await this.buildExternalIdentityState(targetPath, leaf, managedDeployment)),\n };\n } catch {\n return {\n exists: false,\n matchesExpected: false,\n foreign: false,\n managedBySkillFlow: false,\n externalExactMatch: false,\n };\n }\n }\n\n private async buildExternalIdentityState(\n targetPath: string,\n leaf: LeafRecord,\n managedDeployment: DeploymentRecord | undefined,\n ) {\n const identity = !managedDeployment ? await this.readSkillIdentity(targetPath) : undefined;\n return {\n externalExactMatch:\n !managedDeployment &&\n identity?.name === leaf.name &&\n identity.description === leaf.description,\n ...(identity ? { identity } : {}),\n };\n }\n\n private async readSkillIdentity(targetPath: string) {\n try {\n const raw = await fs.readFile(path.join(targetPath, \"SKILL.md\"), \"utf8\");\n const lines = raw.split(/\\r?\\n/);\n if (lines[0]?.trim() !== \"---\") {\n return undefined;\n }\n\n const data: Record<string, string> = {};\n let index = 1;\n while (index < lines.length) {\n const line = lines[index] ?? \"\";\n if (line.trim() === \"---\") {\n break;\n }\n\n const pair = line.match(/^([A-Za-z0-9_-]+):\\s*(.*)$/);\n if (!pair) {\n index += 1;\n continue;\n }\n\n const key = pair[1];\n const rest = pair[2];\n if (!key || rest === undefined) {\n index += 1;\n continue;\n }\n\n if (rest === \"|\" || rest === \">\") {\n const blockLines: string[] = [];\n index += 1;\n while (index < lines.length) {\n const blockLine = lines[index] ?? \"\";\n if (blockLine.length === 0) {\n blockLines.push(\"\");\n index += 1;\n continue;\n }\n if (!blockLine.startsWith(\" \")) {\n break;\n }\n blockLines.push(blockLine.slice(2));\n index += 1;\n }\n data[key] = blockLines.join(\"\\n\").trim();\n continue;\n }\n\n data[key] = rest.trim();\n index += 1;\n }\n\n const name = data.name?.trim();\n const description = data.description?.trim();\n if (!name || !description) {\n return undefined;\n }\n return { name, description };\n } catch {\n return undefined;\n }\n }\n\n private async buildExternalRelocationCandidate(\n preferredTargetPath: string,\n inspectedCandidates: Array<{\n linkName: string;\n targetPath: string;\n diskState: Awaited<ReturnType<DeploymentPlanner[\"inspectTargetPath\"]>>;\n }>,\n leaf: LeafRecord,\n rootPath: string,\n ) {\n const preferredCandidate = inspectedCandidates.find(\n (candidate) => candidate.targetPath === preferredTargetPath,\n );\n if (\n !preferredCandidate ||\n !preferredCandidate.diskState.exists ||\n preferredCandidate.diskState.managedBySkillFlow ||\n preferredCandidate.diskState.externalExactMatch\n ) {\n return undefined;\n }\n\n const currentLinkName = path.basename(preferredTargetPath);\n for (const relocationLinkName of this.buildExternalRelocationLinkNames(currentLinkName)) {\n const relocationTargetPath = path.join(rootPath, relocationLinkName);\n const relocationState = await this.inspectExistingTargetPath(relocationTargetPath);\n if (relocationState.exists) {\n continue;\n }\n\n return {\n linkName: currentLinkName,\n targetPath: preferredTargetPath,\n diskState: preferredCandidate.diskState,\n relocateExternalToTargetPath: relocationTargetPath,\n };\n }\n\n return undefined;\n }\n\n private buildExternalRelocationLinkNames(currentLinkName: string) {\n return Array.from({ length: 12 }, (_, index) =>\n index === 0 ? `${currentLinkName}-external` : `${currentLinkName}-external-${index + 1}`,\n );\n }\n\n private async inspectExistingTargetPath(targetPath: string) {\n try {\n await fs.lstat(targetPath);\n return { exists: true };\n } catch {\n return { exists: false };\n }\n }\n\n private buildProjectedLinkNameMap(\n manifest: Manifest,\n lockFile: LockFile,\n target: DeploymentTargetId,\n ): Map<string, string> {\n const selectedLeafs = manifest.sources.flatMap((source) => {\n const targetBinding = manifest.bindings[source.id]?.targets[target];\n if (!targetBinding?.enabled) {\n return [];\n }\n\n return targetBinding.leafIds\n .map((leafId) => lockFile.leafInventory.find((leaf) => leaf.id === leafId))\n .filter((leaf): leaf is LeafRecord => Boolean(leaf));\n });\n const sourcesById = new Map(manifest.sources.map((source) => [source.id, source]));\n return resolveProjectedSkillNames(\n selectedLeafs.map((leaf) => ({\n leafId: leaf.id,\n groupId: leaf.sourceId,\n groupName: sourcesById.get(leaf.sourceId)?.displayName ?? leaf.sourceId,\n groupAuthor: getHostedGitOwner(sourcesById.get(leaf.sourceId)?.locator ?? \"\"),\n skillName: leaf.linkName,\n })),\n );\n }\n}\n", "import path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { createChannelAdapters } from \"@skill-flow/integration/adapters/channel-adapters\";\nimport { getMergedTargetDefinitions } from \"@skill-flow/integration/utils/constants\";\nimport type {\n DoctorIssue,\n DoctorReport,\n LockFile,\n Manifest,\n Result,\n} from \"@skill-flow/domain/types\";\nimport { getManagedDeployments } from \"@skill-flow/domain/projection-compat\";\nimport { hashDirectory, isBrokenSymlink, pathExists } from \"@skill-flow/integration/utils/fs\";\nimport { formatGroupLabel } from \"@skill-flow/integration/utils/naming\";\nimport { ok } from \"@skill-flow/integration/utils/result\";\nimport { StateStore } from \"@skill-flow/storage/store\";\n\nexport class DoctorService {\n constructor(private readonly store = new StateStore()) {}\n\n async run(manifest: Manifest, lockFile: LockFile): Promise<Result<DoctorReport>> {\n const issues: DoctorIssue[] = [];\n const preferences = await this.store.readPreferences();\n const adapters = createChannelAdapters(\n getMergedTargetDefinitions(preferences.customTargets, preferences.agentDisplayOrder),\n );\n\n for (const source of manifest.sources) {\n const binding = manifest.bindings[source.id] ?? { targets: {} };\n const sourceLock = lockFile.sources.find((item) => item.id === source.id);\n const invalidLeafPaths = new Set(\n sourceLock?.invalidLeafs.map((leaf) => leaf.path) ?? [],\n );\n\n for (const adapter of adapters) {\n const configured = binding.targets[adapter.target];\n if (!configured?.enabled) {\n continue;\n }\n\n const detection = await adapter.detect();\n if (!detection.available) {\n issues.push({\n severity: \"error\",\n sourceId: source.id,\n sourceLabel: formatGroupLabel(source),\n target: adapter.target,\n code: \"TARGET_UNAVAILABLE\",\n message: detection.reason ?? \"Target is unavailable.\",\n });\n continue;\n }\n\n for (const leafId of configured.leafIds) {\n const selectedPath = this.getLeafPath(source.id, leafId);\n if (selectedPath && invalidLeafPaths.has(selectedPath)) {\n issues.push({\n severity: \"error\",\n sourceId: source.id,\n sourceLabel: formatGroupLabel(source),\n target: adapter.target,\n leafId,\n leafLabel: path.basename(selectedPath) || selectedPath,\n code: \"INVALIDATED_SELECTED_LEAF\",\n message: \"This selected skill is invalid in the current source inventory.\",\n });\n continue;\n }\n\n const leaf = lockFile.leafInventory.find((item) => item.id === leafId);\n const deployment = getManagedDeployments(lockFile).find(\n (item) =>\n item.sourceId === source.id &&\n item.leafId === leafId &&\n item.target === adapter.target,\n );\n\n if (!leaf) {\n issues.push({\n severity: \"error\",\n sourceId: source.id,\n sourceLabel: formatGroupLabel(source),\n target: adapter.target,\n leafId,\n code: \"LEAF_MISSING\",\n message: \"This saved selection no longer exists in the source inventory.\",\n });\n continue;\n }\n\n const targetPath = deployment?.targetPath ?? adapter.resolveTargetPath(\n detection.rootPath,\n leaf.linkName,\n );\n if (!deployment) {\n issues.push({\n severity: \"warning\",\n sourceId: source.id,\n sourceLabel: formatGroupLabel(source),\n target: adapter.target,\n leafId,\n leafLabel: leaf.linkName,\n code: \"DRIFT_NOT_DEPLOYED\",\n message: \"This selected skill is not currently projected to disk.\",\n });\n continue;\n }\n\n if (!(await pathExists(targetPath))) {\n issues.push({\n severity: \"error\",\n sourceId: source.id,\n sourceLabel: formatGroupLabel(source),\n target: adapter.target,\n leafId,\n leafLabel: leaf.linkName,\n code: \"TARGET_MISSING\",\n message: \"Projected target is missing on disk.\",\n });\n continue;\n }\n\n if (deployment.strategy === \"symlink\") {\n const stats = await fs.lstat(targetPath);\n if (!stats.isSymbolicLink()) {\n issues.push({\n severity: \"warning\",\n sourceId: source.id,\n sourceLabel: formatGroupLabel(source),\n target: adapter.target,\n leafId,\n leafLabel: leaf.linkName,\n code: \"DRIFT_TYPE\",\n message: \"Expected a symlink, but found foreign content.\",\n });\n continue;\n }\n\n if (await isBrokenSymlink(targetPath)) {\n issues.push({\n severity: \"error\",\n sourceId: source.id,\n sourceLabel: formatGroupLabel(source),\n target: adapter.target,\n leafId,\n leafLabel: leaf.linkName,\n code: \"BROKEN_SYMLINK\",\n message: \"Projected symlink is broken.\",\n });\n }\n } else {\n const onDiskHash = await hashDirectory(targetPath);\n if (onDiskHash !== deployment.contentHash) {\n issues.push({\n severity: \"warning\",\n sourceId: source.id,\n sourceLabel: formatGroupLabel(source),\n target: adapter.target,\n leafId,\n leafLabel: leaf.linkName,\n code: \"DRIFT_COPY\",\n message: \"Projected copy no longer matches saved state.\",\n });\n }\n }\n }\n }\n }\n\n await this.reportUnmanagedExternalSkills(lockFile, issues, adapters);\n\n for (const deployment of getManagedDeployments(lockFile)) {\n const sourceStillExists = manifest.sources.some(\n (source) => source.id === deployment.sourceId,\n );\n if (!sourceStillExists) {\n issues.push({\n severity: \"warning\",\n sourceId: deployment.sourceId,\n target: deployment.target,\n leafId: deployment.leafId,\n code: \"STALE_DEPLOYMENT\",\n message: \"Saved deployment exists for a skills group that is no longer registered.\",\n });\n }\n }\n\n const hasError = issues.some((issue) => issue.severity === \"error\");\n const hasWarning = issues.some((issue) => issue.severity === \"warning\");\n const status: DoctorReport[\"status\"] = hasError\n ? \"BLOCKED\"\n : hasWarning\n ? \"PARTIAL\"\n : \"HEALTHY\";\n\n return ok({ status, issues });\n }\n\n private getLeafPath(sourceId: string, leafId: string) {\n const prefix = `${sourceId}:`;\n if (!leafId.startsWith(prefix)) {\n return undefined;\n }\n return leafId.slice(prefix.length);\n }\n\n private async reportUnmanagedExternalSkills(\n lockFile: LockFile,\n issues: DoctorIssue[],\n adapters = createChannelAdapters(),\n ): Promise<void> {\n const managedTargetPaths = new Set(\n getManagedDeployments(lockFile).map((deployment) => path.resolve(deployment.targetPath)),\n );\n const seenPaths = new Set<string>();\n\n for (const adapter of adapters) {\n const detection = await adapter.detect();\n if (!detection.available) {\n continue;\n }\n\n const entries = await fs.readdir(detection.rootPath, { withFileTypes: true });\n for (const entry of entries) {\n const skillDir = path.join(detection.rootPath, entry.name);\n const isDirectoryLike =\n entry.isDirectory() ||\n (entry.isSymbolicLink() &&\n (await fs.stat(skillDir).then((stats) => stats.isDirectory()).catch(() => false)));\n if (!isDirectoryLike) {\n continue;\n }\n\n if (!(await pathExists(path.join(skillDir, \"SKILL.md\")))) {\n continue;\n }\n\n const resolvedPath = await fs.realpath(skillDir).catch(() => path.resolve(skillDir));\n if (managedTargetPaths.has(path.resolve(skillDir)) || seenPaths.has(resolvedPath)) {\n continue;\n }\n\n seenPaths.add(resolvedPath);\n issues.push({\n severity: \"warning\",\n sourceId: `unmanaged:${adapter.target}:${entry.name}`,\n sourceLabel: \"Unmanaged external skill\",\n target: adapter.target,\n leafLabel: entry.name,\n code: \"UNMANAGED_EXTERNAL_TARGET_SKILL\",\n message: `Unmanaged skill discovered at ${resolvedPath}.`,\n });\n }\n }\n }\n}\n", "import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { DuplicateLeafRecord, InvalidLeafRecord, LeafRecord } from \"@skill-flow/domain/types\";\nimport { hashDirectory, pathExists, slugify } from \"@skill-flow/integration/utils/fs\";\n\ntype InventoryScan = {\n leafs: LeafRecord[];\n invalidLeafs: InvalidLeafRecord[];\n duplicateLeafs: DuplicateLeafRecord[];\n skillFileCount: number;\n};\n\ntype ParsedSkillFile =\n | {\n valid: true;\n name: string;\n title: string;\n description: string;\n metadataWarnings: string[];\n }\n | { valid: false; reason: string };\n\nexport class InventoryService {\n private static readonly IGNORED_DIRECTORIES = new Set([\n \".git\",\n \"node_modules\",\n ]);\n private static readonly PRIORITY_SKILL_DIRECTORIES = [\n \"skills\",\n \"skills/.curated\",\n \"skills/.experimental\",\n \"skills/.system\",\n \".agents/skills\",\n \".claude/skills\",\n \".cline/skills\",\n \".codebuddy/skills\",\n \".codex/skills\",\n \".commandcode/skills\",\n \".continue/skills\",\n \".github/skills\",\n \".goose/skills\",\n \".iflow/skills\",\n \".junie/skills\",\n \".kilocode/skills\",\n \".kiro/skills\",\n \".mux/skills\",\n \".neovate/skills\",\n \".opencode/skills\",\n \".openhands/skills\",\n \".pi/skills\",\n \".qoder/skills\",\n \".roo/skills\",\n \".trae/skills\",\n \".windsurf/skills\",\n \".zencoder/skills\",\n ] as const;\n\n async scanSource(\n sourceId: string,\n checkoutPath: string,\n rootLinkName = sourceId,\n ): Promise<InventoryScan> {\n const skillFiles = await this.findSkillFiles(checkoutPath);\n const candidates: Array<LeafRecord & { dedupeKey: string }> = [];\n const invalidLeafs: InvalidLeafRecord[] = [];\n const duplicateLeafs: DuplicateLeafRecord[] = [];\n\n for (const skillFilePath of skillFiles) {\n const leafRoot = path.dirname(skillFilePath);\n const relativePath = path.relative(checkoutPath, leafRoot) || \".\";\n const raw = await fs.readFile(skillFilePath, \"utf8\");\n const linkName =\n relativePath === \".\"\n ? rootLinkName\n : (path.basename(leafRoot) || rootLinkName);\n const parsed = this.parseSkillFile(raw, linkName);\n\n if (!parsed.valid) {\n invalidLeafs.push({\n path: relativePath,\n reason: parsed.reason,\n });\n continue;\n }\n\n const safeName = slugify(parsed.name) || linkName || sourceId;\n\n candidates.push({\n id: `${sourceId}:${relativePath}`,\n sourceId,\n name: safeName,\n linkName,\n title: parsed.title,\n description: parsed.description,\n relativePath,\n absolutePath: leafRoot,\n skillFilePath,\n contentHash: await hashDirectory(leafRoot),\n metadataWarnings: parsed.metadataWarnings,\n valid: true,\n dedupeKey: parsed.name,\n });\n }\n\n const leafs = this.dedupeCandidates(candidates, duplicateLeafs);\n leafs.sort((left, right) => left.relativePath.localeCompare(right.relativePath));\n duplicateLeafs.sort((left, right) => left.path.localeCompare(right.path));\n invalidLeafs.sort((left, right) => left.path.localeCompare(right.path));\n\n return {\n leafs,\n invalidLeafs,\n duplicateLeafs,\n skillFileCount: skillFiles.length,\n };\n }\n\n private async findSkillFiles(rootPath: string): Promise<string[]> {\n const discovered: string[] = [];\n const seen = new Set<string>();\n\n const rootSkillPath = path.join(rootPath, \"SKILL.md\");\n if (await pathExists(rootSkillPath)) {\n discovered.push(rootSkillPath);\n seen.add(rootSkillPath);\n }\n\n await this.collectDirectChildSkillFiles(rootPath, discovered, seen);\n\n for (const relativePath of InventoryService.PRIORITY_SKILL_DIRECTORIES) {\n await this.collectDirectChildSkillFiles(path.join(rootPath, relativePath), discovered, seen);\n }\n\n if (discovered.length > 0) {\n return discovered;\n }\n\n await this.walkSkillTree(rootPath, discovered, seen, 0);\n\n return discovered;\n }\n\n private async collectDirectChildSkillFiles(\n currentPath: string,\n discovered: string[],\n seen: Set<string>,\n ): Promise<void> {\n if (!(await pathExists(currentPath))) {\n return;\n }\n\n const entries = await fs.readdir(currentPath, { withFileTypes: true });\n const directories = entries\n .filter(\n (entry) =>\n entry.isDirectory() &&\n !entry.isSymbolicLink() &&\n !InventoryService.IGNORED_DIRECTORIES.has(entry.name),\n )\n .sort((left, right) => left.name.localeCompare(right.name));\n\n for (const entry of directories) {\n const skillFilePath = path.join(currentPath, entry.name, \"SKILL.md\");\n if (!(await pathExists(skillFilePath)) || seen.has(skillFilePath)) {\n continue;\n }\n seen.add(skillFilePath);\n discovered.push(skillFilePath);\n }\n }\n\n private async walkSkillTree(\n currentPath: string,\n discovered: string[],\n seen: Set<string>,\n depth: number,\n ): Promise<void> {\n if (depth > 5 || !(await pathExists(currentPath))) {\n return;\n }\n\n const entries = await fs.readdir(currentPath, { withFileTypes: true });\n const files = entries\n .filter((entry) => entry.isFile())\n .sort((left, right) => left.name.localeCompare(right.name));\n const visibleDirectories = entries\n .filter(\n (entry) =>\n entry.isDirectory() &&\n !InventoryService.IGNORED_DIRECTORIES.has(entry.name) &&\n !entry.name.startsWith(\".\"),\n )\n .sort((left, right) => left.name.localeCompare(right.name));\n const hiddenDirectories = entries\n .filter(\n (entry) =>\n entry.isDirectory() &&\n !InventoryService.IGNORED_DIRECTORIES.has(entry.name) &&\n entry.name.startsWith(\".\"),\n )\n .sort((left, right) => left.name.localeCompare(right.name));\n\n for (const entry of files) {\n if (entry.name !== \"SKILL.md\") {\n continue;\n }\n\n const skillFilePath = path.join(currentPath, entry.name);\n if (seen.has(skillFilePath)) {\n continue;\n }\n seen.add(skillFilePath);\n discovered.push(skillFilePath);\n }\n\n for (const entry of [...visibleDirectories, ...hiddenDirectories]) {\n await this.walkSkillTree(path.join(currentPath, entry.name), discovered, seen, depth + 1);\n }\n }\n\n private parseSkillFile(raw: string, parentDirName: string): ParsedSkillFile {\n const lines = raw.split(/\\r?\\n/);\n const frontmatter = this.parseFrontmatter(lines);\n if (!frontmatter) {\n return { valid: false, reason: \"SKILL.md must start with YAML frontmatter\" };\n }\n\n if (!Object.hasOwn(frontmatter.data, \"name\")) {\n return {\n valid: false,\n reason: \"SKILL.md frontmatter must include required field 'name'\",\n };\n }\n\n if (!Object.hasOwn(frontmatter.data, \"description\")) {\n return {\n valid: false,\n reason: \"SKILL.md frontmatter must include required field 'description'\",\n };\n }\n\n const bodyLines = lines.slice(frontmatter.bodyStartLine);\n const firstHeading = bodyLines.find((line) => line.trim().startsWith(\"# \"));\n const rawName = (frontmatter.data.name ?? \"\").trim();\n const rawDescription = frontmatter.data.description ?? \"\";\n const metadataWarnings: string[] = [];\n\n if (\n rawName.length < 1 ||\n rawName.length > 64 ||\n !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(rawName)\n ) {\n metadataWarnings.push(\n \"name should be 1-64 chars, lowercase letters/numbers/hyphens only, with no leading/trailing hyphen or consecutive '--'\",\n );\n }\n\n if (rawName !== parentDirName) {\n metadataWarnings.push(\n `name should match parent directory name '${parentDirName}'`,\n );\n }\n\n if (rawDescription.trim().length === 0) {\n metadataWarnings.push(\"description should be non-empty\");\n }\n\n if (rawDescription.length > 1024) {\n metadataWarnings.push(\"description should be at most 1024 characters\");\n }\n\n const title = firstHeading?.trim().slice(2).trim() || rawName || \"Untitled skill\";\n\n return {\n valid: true,\n name: rawName,\n title,\n description: rawDescription.trim(),\n metadataWarnings,\n };\n }\n\n private dedupeCandidates(\n candidates: Array<LeafRecord & { dedupeKey: string }>,\n duplicateLeafs: DuplicateLeafRecord[],\n ): LeafRecord[] {\n const keptByKey = new Map<string, LeafRecord>();\n for (const candidate of candidates) {\n if (keptByKey.has(candidate.dedupeKey)) {\n const kept = keptByKey.get(candidate.dedupeKey)!;\n duplicateLeafs.push({\n path: candidate.relativePath,\n keptPath: kept.relativePath,\n });\n continue;\n }\n const { dedupeKey: _dedupeKey, ...leaf } = candidate;\n keptByKey.set(candidate.dedupeKey, leaf);\n }\n\n return [...keptByKey.values()];\n }\n\n private parseFrontmatter(\n lines: string[],\n ): { data: Record<string, string>; bodyStartLine: number } | undefined {\n if (lines[0]?.trim() !== \"---\") {\n return undefined;\n }\n\n const data: Record<string, string> = {};\n let index = 1;\n\n while (index < lines.length) {\n const line = lines[index] ?? \"\";\n if (line.trim() === \"---\") {\n return { data, bodyStartLine: index + 1 };\n }\n\n const pair = line.match(/^([A-Za-z0-9_-]+):\\s*(.*)$/);\n if (!pair) {\n index += 1;\n continue;\n }\n\n const key = pair[1];\n const rest = pair[2];\n if (!key || rest === undefined) {\n index += 1;\n continue;\n }\n\n if (rest === \"|\" || rest === \">\") {\n const blockLines: string[] = [];\n index += 1;\n while (index < lines.length) {\n const blockLine = lines[index] ?? \"\";\n if (blockLine.length === 0) {\n blockLines.push(\"\");\n index += 1;\n continue;\n }\n if (!blockLine.startsWith(\" \")) {\n break;\n }\n blockLines.push(blockLine.slice(2));\n index += 1;\n }\n data[key] = blockLines.join(\"\\n\").trim();\n continue;\n }\n\n data[key] = rest.trim();\n index += 1;\n }\n\n return undefined;\n }\n}\n", "import fs from \"node:fs/promises\";\nimport type { RecentProject } from \"@skill-flow/domain\";\nimport {\n collectProjectObservations,\n type ProjectObservation,\n} from \"@skill-flow/integration\";\n\nexport function aggregateRecentProjects(\n observations: ProjectObservation[],\n): RecentProject[] {\n const merged = new Map<string, RecentProject>();\n\n for (const observation of observations) {\n const existing = merged.get(observation.projectId);\n if (!existing) {\n merged.set(observation.projectId, {\n projectId: observation.projectId,\n title: observation.title,\n lastActivityAt: observation.observedAt,\n ...(observation.projectPath ? { projectPath: observation.projectPath } : {}),\n tools: [observation.tool],\n });\n continue;\n }\n\n const latest =\n new Date(existing.lastActivityAt).getTime() >=\n new Date(observation.observedAt).getTime()\n ? existing.lastActivityAt\n : observation.observedAt;\n\n const tools = new Set(existing.tools ?? []);\n tools.add(observation.tool);\n\n merged.set(observation.projectId, {\n projectId: existing.projectId,\n title:\n latest === observation.observedAt ? observation.title : existing.title,\n lastActivityAt: latest,\n ...(\n (latest === observation.observedAt\n ? observation.projectPath ?? existing.projectPath\n : existing.projectPath) ?\n {\n projectPath: latest === observation.observedAt\n ? observation.projectPath ?? existing.projectPath\n : existing.projectPath,\n } :\n {}\n ),\n tools: Array.from(tools).sort(),\n });\n }\n\n return Array.from(merged.values())\n .sort(\n (a, b) =>\n new Date(b.lastActivityAt).getTime() -\n new Date(a.lastActivityAt).getTime(),\n )\n .slice(0, 10);\n}\n\nexport async function resolveUsableProjectPath(projectPath: string | undefined): Promise<string | null> {\n const trimmedPath = projectPath?.trim();\n if (!trimmedPath) {\n return null;\n }\n\n try {\n const resolvedPath = await fs.realpath(trimmedPath);\n const stat = await fs.stat(resolvedPath);\n return stat.isDirectory() ? resolvedPath : null;\n } catch {\n return null;\n }\n}\n\nexport class RecentProjectService {\n async listRecentProjects(): Promise<RecentProject[]> {\n const observations = await collectProjectObservations();\n const validatedObservations = (\n await Promise.all(\n observations.map(async (observation) => {\n if (!observation.projectPath) {\n return observation;\n }\n\n const resolvedProjectPath = await resolveUsableProjectPath(observation.projectPath);\n if (!resolvedProjectPath) {\n return null;\n }\n\n return {\n ...observation,\n projectPath: resolvedProjectPath,\n } satisfies ProjectObservation;\n }),\n )\n ).filter((observation): observation is ProjectObservation => observation !== null);\n\n return aggregateRecentProjects(validatedObservations).filter(\n (project): project is RecentProject & { projectPath: string } => Boolean(project.projectPath),\n );\n }\n}\n", "import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nexport type ProjectObservation = {\n tool: \"claude-code\" | \"codex\" | \"gemini-cli\" | \"opencode\";\n projectId: string;\n title: string;\n observedAt: string;\n projectPath?: string;\n};\n\nexport type CodexSessionLike = {\n session_meta?: {\n payload?: {\n cwd?: string;\n git?: { repository_url?: string };\n };\n };\n observedAt?: string;\n};\n\ntype SessionPayload = {\n cwd?: string;\n git?: { repository_url?: string };\n};\n\nfunction normalizeProjectPath(inputPath: string | undefined): string | null {\n if (!inputPath) {\n return null;\n }\n const normalized = path.normalize(inputPath).replace(/[\\\\/]+$/, \"\");\n return normalized || null;\n}\n\nfunction basenameMaybe(inputPath: string | undefined): string | null {\n const normalizedPath = normalizeProjectPath(inputPath);\n if (!normalizedPath) {\n return null;\n }\n const base = path.basename(normalizedPath);\n return base || null;\n}\n\nfunction toIsoString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) {\n return null;\n }\n return date.toISOString();\n}\n\nfunction repositoryUrlToProjectId(repositoryUrl: string): string | null {\n // Accept common Git URL forms and extract the first 2 path segments.\n let rawPath: string | null = null;\n\n if (/^https?:\\/\\//i.test(repositoryUrl)) {\n try {\n const url = new URL(repositoryUrl);\n rawPath = url.pathname;\n } catch {\n rawPath = null;\n }\n } else {\n const scpLike = repositoryUrl.match(/^[^@]+@[^:]+:(.+)$/);\n if (scpLike) {\n rawPath = `/${scpLike[1]}`;\n }\n }\n\n if (!rawPath) {\n return null;\n }\n\n const cleaned = rawPath.replace(/\\.git$/i, \"\").replace(/^\\/+/, \"\");\n const parts = cleaned.split(\"/\").filter(Boolean);\n if (parts.length < 2) {\n return null;\n }\n return `${parts[0]}/${parts[1]}`;\n}\n\nfunction deriveProjectIdentity(args: {\n repositoryUrl: string | undefined;\n projectPath: string | undefined;\n}): { projectId: string; title: string } | null {\n const projectPath = normalizeProjectPath(args.projectPath);\n const repositoryProjectId = args.repositoryUrl\n ? repositoryUrlToProjectId(args.repositoryUrl)\n : null;\n const projectId = repositoryProjectId ?? projectPath;\n\n if (!projectId) {\n return null;\n }\n\n return {\n projectId,\n title: basenameMaybe(projectPath ?? projectId) ?? projectId,\n };\n}\n\nexport function collectProjectObservationsFromCodexSessions(\n codexSessions: CodexSessionLike[],\n): ProjectObservation[] {\n return collectProjectObservationsFromSessionPayloads(\n codexSessions.map((session) => ({\n ...(session.session_meta?.payload\n ? { payload: session.session_meta.payload }\n : {}),\n ...(session.observedAt ? { observedAt: session.observedAt } : {}),\n })),\n \"codex\",\n );\n}\n\nfunction collectProjectObservationsFromSessionPayloads(\n sessions: Array<{ payload?: SessionPayload; observedAt?: string }>,\n tool: ProjectObservation[\"tool\"],\n): ProjectObservation[] {\n return sessions\n .map((session) => {\n const payload = session.payload;\n const observedAt =\n toIsoString(session.observedAt) ?? new Date(0).toISOString();\n const project = deriveProjectIdentity({\n repositoryUrl: payload?.git?.repository_url,\n projectPath: payload?.cwd,\n });\n\n if (!project) {\n return null;\n }\n\n return {\n tool,\n projectId: project.projectId,\n title: project.title,\n observedAt,\n ...(payload?.cwd ? { projectPath: payload.cwd } : {}),\n } satisfies ProjectObservation;\n })\n .filter((observation): observation is ProjectObservation => observation !== null);\n}\n\nasync function readDirSafe(dirPath: string): Promise<string[]> {\n try {\n return await fs.readdir(dirPath);\n } catch {\n return [];\n }\n}\n\nasync function readFileSafe(filePath: string): Promise<string | null> {\n try {\n return await fs.readFile(filePath, \"utf8\");\n } catch {\n return null;\n }\n}\n\nasync function statMtimeIso(filePath: string): Promise<string | null> {\n try {\n const stat = await fs.stat(filePath);\n return stat.mtime.toISOString();\n } catch {\n return null;\n }\n}\n\nasync function collectFilesMatching(\n rootDir: string,\n matcher: (filePath: string) => boolean,\n maxDepth = 4,\n): Promise<string[]> {\n async function visit(currentDir: string, depth: number): Promise<string[]> {\n if (depth > maxDepth) {\n return [];\n }\n\n const entries = await fs.readdir(currentDir, { withFileTypes: true }).catch(() => []);\n const matches: string[] = [];\n\n for (const entry of entries) {\n const entryPath = path.join(currentDir, entry.name);\n if (entry.isDirectory()) {\n matches.push(...(await visit(entryPath, depth + 1)));\n continue;\n }\n if (entry.isFile() && matcher(entryPath)) {\n matches.push(entryPath);\n }\n }\n\n return matches;\n }\n\n return visit(rootDir, 0);\n}\n\nasync function readSessionPayloadFromJsonl(filePath: string): Promise<{\n payload?: SessionPayload;\n observedAt?: string;\n} | null> {\n const content = await readFileSafe(filePath);\n if (!content) {\n return null;\n }\n\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n\n try {\n const parsed = JSON.parse(trimmed) as {\n type?: string;\n payload?: unknown;\n cwd?: string;\n git?: { repository_url?: string };\n timestamp?: string;\n };\n if (parsed.type === \"session_meta\" && parsed.payload && typeof parsed.payload === \"object\") {\n const observedAt = (await statMtimeIso(filePath)) ?? null;\n return {\n payload: parsed.payload as SessionPayload,\n ...(observedAt ? { observedAt } : {}),\n };\n }\n if (typeof parsed.cwd === \"string\" || typeof parsed.git?.repository_url === \"string\") {\n const observedAt = toIsoString(parsed.timestamp) ?? (await statMtimeIso(filePath)) ?? null;\n return {\n payload: {\n ...(typeof parsed.cwd === \"string\" ? { cwd: parsed.cwd } : {}),\n ...(typeof parsed.git?.repository_url === \"string\"\n ? { git: { repository_url: parsed.git.repository_url } }\n : {}),\n },\n ...(observedAt ? { observedAt } : {}),\n };\n }\n } catch {\n // Ignore malformed lines.\n }\n }\n\n return null;\n}\n\nasync function collectCodexObservations(homeDir: string): Promise<ProjectObservation[]> {\n const sessionsDir = path.join(homeDir, \".codex\", \"archived_sessions\");\n const entries = await readDirSafe(sessionsDir);\n const jsonlFiles = entries.filter((entry) => entry.endsWith(\".jsonl\"));\n\n const sessions: Array<{ payload?: SessionPayload; observedAt?: string }> = [];\n for (const fileName of jsonlFiles) {\n const filePath = path.join(sessionsDir, fileName);\n const session = await readSessionPayloadFromJsonl(filePath);\n if (!session?.payload) {\n continue;\n }\n sessions.push(session);\n }\n\n return collectProjectObservationsFromSessionPayloads(sessions, \"codex\");\n}\n\ntype ClaudeLogLine = {\n timestamp?: string;\n cwd?: string;\n git?: { repository_url?: string };\n};\n\nasync function collectClaudeObservations(homeDir: string): Promise<ProjectObservation[]> {\n const projectsRoot = path.join(homeDir, \".claude\", \"projects\");\n const projectDirs = await readDirSafe(projectsRoot);\n\n const observations: ProjectObservation[] = [];\n for (const projectDir of projectDirs) {\n const sessionsDir = path.join(projectsRoot, projectDir);\n const sessionFiles = (await readDirSafe(sessionsDir)).filter((f) => f.endsWith(\".jsonl\"));\n\n for (const fileName of sessionFiles) {\n const filePath = path.join(sessionsDir, fileName);\n const content = await readFileSafe(filePath);\n if (!content) continue;\n\n let lastTimestamp: string | null = null;\n let lastCwd: string | null = null;\n let lastRepoUrl: string | null = null;\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const parsed = JSON.parse(trimmed) as ClaudeLogLine;\n const ts = toIsoString(parsed.timestamp);\n if (ts) lastTimestamp = ts;\n if (typeof parsed.cwd === \"string\") lastCwd = parsed.cwd;\n const repoUrl = parsed.git?.repository_url;\n if (typeof repoUrl === \"string\") lastRepoUrl = repoUrl;\n } catch {\n // Ignore malformed lines.\n }\n }\n\n const observedAt =\n lastTimestamp ?? (await statMtimeIso(filePath)) ?? new Date(0).toISOString();\n const project = deriveProjectIdentity({\n repositoryUrl: lastRepoUrl ?? undefined,\n projectPath: lastCwd ?? undefined,\n });\n if (!project) continue;\n\n observations.push({\n tool: \"claude-code\",\n projectId: project.projectId,\n title: project.title,\n observedAt,\n ...(lastCwd ? { projectPath: lastCwd } : {}),\n });\n }\n }\n\n return observations;\n}\n\nasync function collectGeminiObservations(homeDir: string): Promise<ProjectObservation[]> {\n const historyRoot = path.join(homeDir, \".gemini\", \"history\");\n const entries = await readDirSafe(historyRoot);\n\n const observations: ProjectObservation[] = [];\n for (const entry of entries) {\n const projectRootFile = path.join(historyRoot, entry, \".project_root\");\n const content = await readFileSafe(projectRootFile);\n if (!content) continue;\n\n const projectRoot = normalizeProjectPath(content.trim());\n if (!projectRoot) continue;\n\n observations.push({\n tool: \"gemini-cli\",\n projectId: projectRoot,\n title: basenameMaybe(projectRoot) ?? projectRoot,\n observedAt: (await statMtimeIso(projectRootFile)) ?? new Date(0).toISOString(),\n projectPath: projectRoot,\n });\n }\n\n return observations;\n}\n\nasync function collectOpencodeObservations(_homeDir: string): Promise<ProjectObservation[]> {\n const candidateRoots = [\n path.join(_homeDir, \".config\", \"opencode\"),\n path.join(_homeDir, \".opencode\"),\n ];\n const observations: ProjectObservation[] = [];\n const seen = new Set<string>();\n\n for (const rootDir of candidateRoots) {\n const projectRootFiles = await collectFilesMatching(\n rootDir,\n (filePath) => path.basename(filePath) === \".project_root\",\n );\n\n for (const filePath of projectRootFiles) {\n if (seen.has(filePath)) {\n continue;\n }\n seen.add(filePath);\n\n const content = await readFileSafe(filePath);\n const projectRoot = normalizeProjectPath(content?.trim());\n if (!projectRoot) {\n continue;\n }\n\n observations.push({\n tool: \"opencode\",\n projectId: projectRoot,\n title: basenameMaybe(projectRoot) ?? projectRoot,\n observedAt: (await statMtimeIso(filePath)) ?? new Date(0).toISOString(),\n projectPath: projectRoot,\n });\n }\n\n const jsonlFiles = await collectFilesMatching(\n rootDir,\n (filePath) => filePath.endsWith(\".jsonl\"),\n );\n const sessions = (\n await Promise.all(jsonlFiles.map((filePath) => readSessionPayloadFromJsonl(filePath)))\n ).filter((session): session is { payload?: SessionPayload; observedAt?: string } => session !== null);\n\n observations.push(...collectProjectObservationsFromSessionPayloads(sessions, \"opencode\"));\n }\n\n return observations;\n}\n\nexport async function collectProjectObservations(\n homeDir = os.homedir(),\n): Promise<ProjectObservation[]> {\n return [\n ...(await collectClaudeObservations(homeDir)),\n ...(await collectCodexObservations(homeDir)),\n ...(await collectGeminiObservations(homeDir)),\n ...(await collectOpencodeObservations(homeDir)),\n ];\n}\n", "const GENERATED_DUPLICATE_WARNING =\n /^\\.(?:agents|claude|codex|opencode|openclaw)\\/skills\\/.+: Duplicate skill content skipped because source\\/skills\\/.+ was discovered first$/;\n\nexport function resolveAddSourceLocator(source: string, from?: string): string {\n const trimmedSource = source.trim();\n const trimmedFrom = from?.trim().toLowerCase();\n\n if (!trimmedFrom) {\n return trimmedSource;\n }\n\n if (trimmedFrom !== \"clawhub\") {\n throw new Error(`Unsupported source catalog '${from}'.`);\n }\n\n if (trimmedSource.startsWith(\"clawhub:\")) {\n return trimmedSource;\n }\n\n return `clawhub:${trimmedSource}`;\n}\n\nexport function filterAddWarnings(warnings: string[]): string[] {\n return warnings.filter((warning) => !GENERATED_DUPLICATE_WARNING.test(warning));\n}\n", "import type { SkillCandidate } from \"@skill-flow/domain/types\";\n\nexport function buildFindCommand(candidate: SkillCandidate): string | null {\n if (candidate.action.type === \"none\") {\n return null;\n }\n\n if (candidate.action.type === \"add-clawhub\") {\n const suffix = candidate.action.version ? `@${candidate.action.version}` : \"\";\n return `skill-flow add clawhub:${candidate.action.slug}${suffix}`;\n }\n\n const parts = [\"skill-flow\", \"add\", shellQuote(candidate.action.locator)];\n const requestedPath = normalizeRequestedPath(candidate.action.requestedPath);\n if (requestedPath) {\n parts.push(\"--path\", shellQuote(requestedPath));\n }\n return parts.join(\" \");\n}\n\nfunction normalizeRequestedPath(requestedPath?: string): string | undefined {\n if (!requestedPath) {\n return undefined;\n }\n\n const normalized = requestedPath.trim().replace(/^\\.\\/+/, \"\").replace(/\\/+$/, \"\");\n return normalized.length > 0 && normalized !== \".\" ? normalized : undefined;\n}\n\nfunction shellQuote(value: string): string {\n if (/^[A-Za-z0-9_./:@-]+$/.test(value)) {\n return value;\n }\n\n return `'${value.replace(/'/g, `'\\\"'\\\"'`)}'`;\n}\n", "import type {\n DeploymentAction,\n DeploymentTargetId,\n DoctorIssue,\n SkillCandidate,\n WorkflowSummary,\n} from \"@skill-flow/domain/types\";\nimport { TARGET_LABELS, TARGET_ORDER } from \"./constants.js\";\nimport { buildFindCommand } from \"./find-command.js\";\nimport { formatGroupLabel } from \"./naming.js\";\n\nexport function formatWorkflowList(summaries: WorkflowSummary[]): string {\n if (summaries.length === 0) {\n return [\n \"No skills groups yet\",\n \"Add a source to discover a grouped set of related skills.\",\n ].join(\"\\n\");\n }\n\n return summaries\n .map((summary) => {\n const invalidCount = summary.lock?.invalidLeafs.length ?? 0;\n const warningCount = summary.leafs.reduce(\n (count, leaf) => count + leaf.metadataWarnings.length,\n 0,\n );\n const suffixParts = [];\n if (warningCount > 0) {\n suffixParts.push(`${warningCount} warnings`);\n }\n if (invalidCount > 0) {\n suffixParts.push(`${invalidCount} skipped`);\n }\n const suffix = suffixParts.length > 0 ? `, ${suffixParts.join(\", \")}` : \"\";\n return `${formatGroupLabel(summary.source)} ${summary.health} ${summary.leafs.length} skills ${summary.activeTargetCount} targets${suffix}`;\n })\n .join(\"\\n\");\n}\n\nexport function countActions(actions: DeploymentAction[]): Record<string, number> {\n return actions.reduce<Record<string, number>>((acc, action) => {\n acc[action.kind] = (acc[action.kind] ?? 0) + 1;\n return acc;\n }, {});\n}\n\nexport function formatActionSummary(actions: DeploymentAction[]): string {\n const counts = countActions(actions);\n return [\"create\", \"update\", \"remove\", \"noop\", \"blocked\"]\n .map((kind) => `${kind}:${counts[kind] ?? 0}`)\n .join(\" \");\n}\n\nexport function formatTargetName(target: DeploymentTargetId): string {\n return TARGET_ORDER.includes(target as typeof TARGET_ORDER[number])\n ? TARGET_LABELS[target as typeof TARGET_ORDER[number]]\n : target;\n}\n\nexport function formatDoctorIssue(issue: DoctorIssue): string {\n const target = issue.target ? ` ${formatTargetName(issue.target)}` : \"\";\n const leaf = issue.leafLabel\n ? ` skill:${issue.leafLabel}`\n : issue.leafId\n ? ` skill:${issue.leafId}`\n : \"\";\n return `[${issue.severity.toUpperCase()}] ${issue.sourceLabel ?? issue.sourceId}${target}${leaf} ${issue.message}`;\n}\n\nexport function formatSkillCandidates(candidates: SkillCandidate[]): string {\n if (candidates.length === 0) {\n return \"No matching skills found.\";\n }\n\n return candidates\n .map((candidate, index) => {\n const location = candidate.relativePath ? ` \u00B7 ${candidate.relativePath}` : \"\";\n const next = buildFindCommand(candidate);\n return [\n `${index + 1}. ${candidate.title} ${candidate.source}${candidate.installed ? \" installed\" : \"\"}`,\n candidate.description,\n `${candidate.sourceLabel}${location}`,\n next ? `next: ${next}` : \"next: already installed\",\n ].join(\"\\n\");\n })\n .join(\"\\n\\n\");\n}\n", "import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst execFileAsync = promisify(execFile);\n\nexport async function isGitAvailable(): Promise<boolean> {\n try {\n await execFileAsync(\"git\", [\"--version\"], {\n encoding: \"utf8\",\n env: process.env,\n });\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function git(\n args: string[],\n options: { cwd?: string } = {},\n): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", args, {\n cwd: options.cwd,\n encoding: \"utf8\",\n env: process.env,\n });\n return stdout.trim();\n}\n", "import crypto from \"node:crypto\";\nimport { execFile } from \"node:child_process\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport type {\n DeploymentTargetName,\n LockFile,\n Result,\n SourceUpdateDiff,\n SourceUpdateResult,\n SourceKind,\n SourceLockRecord,\n SourceManifestRecord,\n} from \"@skill-flow/domain/types\";\nimport { getManagedDeployments } from \"@skill-flow/domain/projection-compat\";\nimport { StateStore } from \"@skill-flow/storage/store\";\nimport {\n copyDirectory,\n ensureDir,\n hashDirectory,\n isPathInside,\n pathExists,\n readJsonFile,\n removePath,\n} from \"@skill-flow/integration/utils/fs\";\nimport {\n installClawHubSkill,\n} from \"@skill-flow/integration/utils/clawhub\";\nimport { git, isGitAvailable } from \"@skill-flow/integration/utils/git\";\nimport { parseGitHubRepo, parseHostedGitRepo } from \"@skill-flow/integration/utils/naming\";\nimport { fail, ok } from \"@skill-flow/integration/utils/result\";\nimport { deriveDisplayName, deriveSourceId } from \"@skill-flow/integration/utils/source-id\";\nimport { formatGroupLabel } from \"@skill-flow/integration/utils/naming\";\nimport { InventoryService } from \"./inventory-service.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport type SourceSnapshot = {\n manifest: SourceManifestRecord;\n lock: SourceLockRecord;\n leafCount: number;\n invalidLeafCount: number;\n};\n\nexport type SourcePreview = {\n locator: string;\n displayName: string;\n requestedPath?: string;\n leafs: LockFile[\"leafInventory\"];\n};\n\nexport type AddSourceOptions = {\n path?: string;\n enabledTargets?: DeploymentTargetName[];\n selectionMode?: \"all\" | \"partial\";\n project?: boolean;\n sourceIdOverride?: string;\n displayNameOverride?: string;\n originLocator?: string;\n originRequestedPath?: string;\n originBranch?: string;\n importedFromTargets?: DeploymentTargetName[];\n observedTargets?: Array<{\n target: DeploymentTargetName;\n rootPath: string;\n targetPath: string;\n }>;\n importMode?: \"explicit-add\" | \"bootstrap-detected\";\n};\n\ntype SourceResolution = {\n kind: SourceKind;\n locator: string;\n displayName: string;\n sourceId: string;\n requestedPath?: string;\n gitLocator?: string;\n localPath?: string;\n clawhubSlug?: string;\n requestedVersion?: string;\n versionMode?: \"pinned\" | \"floating\";\n};\n\nexport class SourceService {\n constructor(\n private readonly store: StateStore,\n private readonly inventoryService: InventoryService,\n ) {}\n\n async addSource(\n locator: string,\n options: AddSourceOptions = {},\n ): Promise<Result<SourceSnapshot>> {\n const { manifest, lockFile } = await this.store.readState();\n\n const resolved = this.resolveUniqueLocalSource(\n await this.resolveSource(locator, options),\n manifest.sources,\n );\n\n if (\n manifest.sources.some(\n (source) => source.id === resolved.sourceId && source.locator === resolved.locator,\n )\n ) {\n return fail({\n code: \"SOURCE_EXISTS\",\n message: `Skills group '${formatGroupLabel({ id: resolved.sourceId, locator: resolved.locator, displayName: resolved.displayName })}' is already registered with id '${resolved.sourceId}'.`,\n });\n }\n\n if (manifest.sources.some((source) => source.id === resolved.sourceId)) {\n return fail({\n code: \"SOURCE_EXISTS\",\n message: `Skills group '${formatGroupLabel({ id: resolved.sourceId, locator: resolved.locator, displayName: resolved.displayName })}' is already registered with id '${resolved.sourceId}'.`,\n });\n }\n\n const checkoutPath = this.store.getSourceCheckoutPath(\n resolved.kind,\n resolved.sourceId,\n );\n const tempCheckoutPath = `${checkoutPath}.${process.pid}.${crypto.randomUUID()}.add`;\n await ensureDir(this.store.getSourceRoot(resolved.kind));\n\n try {\n await this.fetchSource(resolved, tempCheckoutPath);\n } catch (error) {\n await removePath(tempCheckoutPath);\n return fail({\n code:\n resolved.kind === \"git\"\n ? \"GIT_CLONE_FAILED\"\n : resolved.kind === \"local\"\n ? \"LOCAL_IMPORT_FAILED\"\n : \"CLAWHUB_FETCH_FAILED\",\n message: `Unable to fetch source '${resolved.locator}': ${String(error)}`,\n });\n }\n\n const snapshot = await this.buildSnapshot(\n resolved.kind,\n resolved.sourceId,\n resolved.locator,\n resolved.displayName,\n tempCheckoutPath,\n resolved.requestedPath,\n options,\n );\n\n if (!snapshot.ok) {\n await removePath(tempCheckoutPath);\n return fail(snapshot.errors, snapshot.warnings);\n }\n\n if (await pathExists(checkoutPath)) {\n await removePath(tempCheckoutPath);\n return fail({\n code: \"SOURCE_CHECKOUT_PATH_EXISTS\",\n message: `Unable to register source '${resolved.locator}' because checkout path already exists at ${checkoutPath}.`,\n });\n }\n\n try {\n await fs.rename(tempCheckoutPath, checkoutPath);\n } catch (error) {\n await removePath(tempCheckoutPath).catch(() => {});\n return fail({\n code: \"SOURCE_CHECKOUT_MOVE_FAILED\",\n message: `Unable to finalize source '${resolved.locator}' at ${checkoutPath}: ${String(error)}`,\n });\n }\n snapshot.data.lock.checkoutPath = checkoutPath;\n snapshot.data.leafs = snapshot.data.leafs.map((leaf) => ({\n ...leaf,\n absolutePath: path.join(checkoutPath, leaf.relativePath),\n skillFilePath: path.join(checkoutPath, leaf.relativePath, \"SKILL.md\"),\n }));\n\n manifest.sources.push(snapshot.data.manifest);\n manifest.bindings[resolved.sourceId] = { targets: {} };\n lockFile.sources.push(snapshot.data.lock);\n lockFile.leafInventory.push(...snapshot.data.leafs);\n\n await this.store.writeState(manifest, lockFile);\n\n return ok({\n manifest: snapshot.data.manifest,\n lock: snapshot.data.lock,\n leafCount: snapshot.data.leafs.length,\n invalidLeafCount: snapshot.data.lock.invalidLeafs.length,\n }, snapshot.warnings);\n }\n\n async previewSource(\n locator: string,\n options: AddSourceOptions = {},\n ): Promise<Result<SourcePreview>> {\n const resolved = await this.resolveSource(locator, options);\n const tempCheckoutPath = path.join(\n this.store.getSourceRoot(resolved.kind),\n `.preview-${process.pid}-${crypto.randomUUID()}`,\n );\n await ensureDir(this.store.getSourceRoot(resolved.kind));\n\n try {\n await this.fetchSource(resolved, tempCheckoutPath);\n const snapshot = await this.buildSnapshot(\n resolved.kind,\n resolved.sourceId,\n resolved.locator,\n resolved.displayName,\n tempCheckoutPath,\n resolved.requestedPath,\n options,\n );\n if (!snapshot.ok) {\n return fail(snapshot.errors, snapshot.warnings);\n }\n\n return ok({\n locator: resolved.locator,\n displayName: resolved.displayName,\n ...(resolved.requestedPath ? { requestedPath: resolved.requestedPath } : {}),\n leafs: snapshot.data.leafs,\n }, snapshot.warnings);\n } catch (error) {\n return fail({\n code:\n resolved.kind === \"git\"\n ? \"GIT_PREVIEW_FAILED\"\n : resolved.kind === \"local\"\n ? \"LOCAL_PREVIEW_FAILED\"\n : \"CLAWHUB_PREVIEW_FAILED\",\n message: `Unable to preview source '${resolved.locator}': ${String(error)}`,\n });\n } finally {\n await removePath(tempCheckoutPath).catch(() => {});\n }\n }\n\n async updateSources(sourceIds?: string[]): Promise<Result<SourceUpdateResult>> {\n const { manifest, lockFile } = await this.store.readState();\n const selectedIds = sourceIds?.length\n ? sourceIds\n : manifest.sources.map((source) => source.id);\n\n const updated: SourceUpdateResult[\"updated\"] = [];\n\n for (const sourceId of selectedIds) {\n const source = manifest.sources.find((item) => item.id === sourceId);\n const currentLock = lockFile.sources.find((item) => item.id === sourceId);\n\n if (!source || !currentLock) {\n return fail({\n code: \"SOURCE_NOT_FOUND\",\n message: `Skills group id '${sourceId}' is not registered.`,\n });\n }\n\n try {\n const sourceChanged = await this.updateSource(source, currentLock);\n const sourceMeta = {\n ...(source.requestedPath ? { requestedPath: source.requestedPath } : {}),\n ...(source.selectionMode ? { selectionMode: source.selectionMode } : {}),\n };\n if (!sourceChanged) {\n updated.push({\n sourceId,\n changed: false,\n addedLeafIds: [],\n removedLeafIds: [],\n invalidatedLeafIds: [],\n diffs: [],\n ...sourceMeta,\n });\n continue;\n }\n\n const snapshot = await this.buildSnapshot(\n source.kind,\n source.id,\n source.locator,\n source.displayName,\n currentLock.checkoutPath,\n source.requestedPath,\n {},\n { allowEmptyLeafs: true },\n );\n\n if (!snapshot.ok) {\n return fail(snapshot.errors, snapshot.warnings);\n }\n\n const diff = this.buildSourceUpdateDiff(\n source,\n lockFile.leafInventory.filter((leaf) => leaf.sourceId === sourceId),\n snapshot.data.leafs,\n snapshot.data.lock.invalidLeafs,\n );\n\n lockFile.sources = lockFile.sources.map((item) =>\n item.id === sourceId\n ? this.mergePersistentLockMetadata(item, snapshot.data.lock)\n : item,\n );\n lockFile.leafInventory = [\n ...lockFile.leafInventory.filter((leaf) => leaf.sourceId !== sourceId),\n ...snapshot.data.leafs,\n ];\n\n updated.push({\n sourceId,\n changed: sourceChanged,\n addedLeafIds: diff.addedLeafIds,\n removedLeafIds: diff.removedLeafIds,\n invalidatedLeafIds: diff.invalidatedLeafIds,\n diffs: diff.diffs,\n ...sourceMeta,\n });\n } catch (error) {\n return fail({\n code:\n source.kind === \"git\"\n ? \"GIT_UPDATE_FAILED\"\n : source.kind === \"local\"\n ? \"LOCAL_UPDATE_FAILED\"\n : \"CLAWHUB_UPDATE_FAILED\",\n message: `Unable to update skills group id '${sourceId}': ${String(error)}`,\n });\n }\n }\n\n await this.store.writeState(manifest, lockFile);\n return ok({ updated });\n }\n\n async removeSource(sourceIds: string[]): Promise<Result<{ removed: string[] }>> {\n const { manifest, lockFile } = await this.store.readState();\n const removed: string[] = [];\n\n for (const sourceId of sourceIds) {\n const currentSource = manifest.sources.find((source) => source.id === sourceId);\n const currentLock = lockFile.sources.find((source) => source.id === sourceId);\n if (!currentSource || !currentLock) {\n return fail({\n code: \"SOURCE_NOT_FOUND\",\n message: `Skills group id '${sourceId}' is not registered.`,\n });\n }\n\n manifest.sources = manifest.sources.filter((source) => source.id !== sourceId);\n delete manifest.bindings[sourceId];\n lockFile.sources = lockFile.sources.filter((source) => source.id !== sourceId);\n lockFile.leafInventory = lockFile.leafInventory.filter(\n (leaf) => leaf.sourceId !== sourceId,\n );\n lockFile.projections = (lockFile.projections ?? []).filter(\n (projection) => projection.sourceId !== sourceId,\n );\n const checkoutRoot = this.store.getSourceRoot(currentSource.kind);\n if (!isPathInside(checkoutRoot, currentLock.checkoutPath)) {\n return fail({\n code: \"SOURCE_CHECKOUT_PATH_INVALID\",\n message: `Refusing to delete checkout outside managed root: ${currentLock.checkoutPath}`,\n });\n }\n if (currentLock && (await pathExists(currentLock.checkoutPath))) {\n await removePath(currentLock.checkoutPath);\n }\n removed.push(sourceId);\n }\n\n await this.store.writeState(manifest, lockFile);\n await this.store.pruneSourceMetadataCache(manifest.sources.map((source) => source.id));\n return ok({ removed });\n }\n\n async reconcileInventory(\n sourceIds?: string[],\n options: { force?: boolean } = {},\n ): Promise<Result<{ updatedSourceIds: string[] }>> {\n const { manifest, lockFile } = await this.store.readState();\n const selectedIds = sourceIds?.length\n ? sourceIds\n : manifest.sources.map((source) => source.id);\n const updatedSourceIds: string[] = [];\n\n for (const sourceId of selectedIds) {\n const source = manifest.sources.find((item) => item.id === sourceId);\n const currentLock = lockFile.sources.find((item) => item.id === sourceId);\n if (!source || !currentLock) {\n continue;\n }\n\n const sourceLeafs = lockFile.leafInventory.filter((leaf) => leaf.sourceId === sourceId);\n const sourceDeployments = getManagedDeployments(lockFile).filter(\n (deployment) => deployment.sourceId === sourceId,\n );\n if (\n !options.force &&\n !this.needsInventoryReconcile(sourceId, sourceLeafs, sourceDeployments)\n ) {\n continue;\n }\n\n const snapshot = await this.buildSnapshot(\n source.kind,\n source.id,\n source.locator,\n source.displayName,\n currentLock.checkoutPath,\n source.requestedPath,\n {},\n { allowEmptyLeafs: true },\n );\n\n if (!snapshot.ok) {\n return fail(snapshot.errors, snapshot.warnings);\n }\n\n const leafIdsChanged =\n JSON.stringify(currentLock.leafIds) !==\n JSON.stringify(snapshot.data.lock.leafIds);\n const invalidLeafsChanged =\n JSON.stringify(currentLock.invalidLeafs) !==\n JSON.stringify(snapshot.data.lock.invalidLeafs);\n const leafInventoryChanged =\n JSON.stringify(sourceLeafs) !== JSON.stringify(snapshot.data.leafs);\n\n if (\n !options.force &&\n !leafIdsChanged &&\n !invalidLeafsChanged &&\n !leafInventoryChanged\n ) {\n continue;\n }\n\n lockFile.sources = lockFile.sources.map((item) =>\n item.id === sourceId\n ? this.mergePersistentLockMetadata(currentLock, snapshot.data.lock)\n : item,\n );\n lockFile.leafInventory = [\n ...lockFile.leafInventory.filter((leaf) => leaf.sourceId !== sourceId),\n ...snapshot.data.leafs,\n ];\n\n const nextLeafIds = new Set(snapshot.data.leafs.map((leaf) => leaf.id));\n const binding = manifest.bindings[sourceId];\n if (binding) {\n for (const targetBinding of Object.values(binding.targets)) {\n if (!targetBinding) {\n continue;\n }\n targetBinding.leafIds = targetBinding.leafIds.filter((leafId) =>\n nextLeafIds.has(leafId),\n );\n }\n }\n\n updatedSourceIds.push(sourceId);\n }\n\n if (updatedSourceIds.length > 0) {\n await this.store.writeState(manifest, lockFile);\n }\n\n return ok({ updatedSourceIds });\n }\n\n private needsInventoryReconcile(\n sourceId: string,\n sourceLeafs: LockFile[\"leafInventory\"],\n sourceDeployments: LockFile[\"deployments\"],\n ): boolean {\n const hasGeneratedLeafs = sourceLeafs.some((leaf) =>\n /^(?:\\.agents|\\.claude|\\.codex|\\.opencode|\\.openclaw)(?:\\/|$)/.test(\n leaf.relativePath,\n ),\n );\n\n const hasLegacyTargetNames = sourceDeployments.some((deployment) =>\n path.basename(deployment.targetPath).startsWith(`${sourceId}--`),\n );\n\n return hasGeneratedLeafs || hasLegacyTargetNames;\n }\n\n private buildSourceUpdateDiff(\n source: SourceManifestRecord,\n previousLeafs: LockFile[\"leafInventory\"],\n nextLeafs: LockFile[\"leafInventory\"],\n nextInvalidLeafs: SourceLockRecord[\"invalidLeafs\"],\n ): {\n diffs: SourceUpdateDiff[];\n addedLeafIds: string[];\n removedLeafIds: string[];\n invalidatedLeafIds: string[];\n } {\n const requestedPath = this.normalizeRequestedPath(source.requestedPath);\n const requestedPathOption = requestedPath ? { requestedPath } : {};\n const diffs: SourceUpdateDiff[] = [];\n const addedLeafIds: string[] = [];\n const removedLeafIds: string[] = [];\n const invalidatedLeafIds: string[] = [];\n const matchedPreviousIds = new Set<string>();\n const matchedNextIds = new Set<string>();\n\n const nextById = new Map(nextLeafs.map((leaf) => [leaf.id, leaf] as const));\n const nextInvalidPaths = new Set(nextInvalidLeafs.map((leaf) => leaf.path));\n\n for (const previousLeaf of previousLeafs) {\n const nextLeaf = nextById.get(previousLeaf.id);\n if (!nextLeaf || previousLeaf.contentHash === nextLeaf.contentHash) {\n continue;\n }\n\n diffs.push(\n this.createDiffItem(\"changed\", source.id, nextLeaf, {\n ...requestedPathOption,\n previousLeafId: previousLeaf.id,\n previousRelativePath: previousLeaf.relativePath,\n previousContentHash: previousLeaf.contentHash,\n }),\n );\n matchedPreviousIds.add(previousLeaf.id);\n matchedNextIds.add(nextLeaf.id);\n }\n\n const previousByHash = new Map<string, LockFile[\"leafInventory\"]>();\n const nextByHash = new Map<string, LockFile[\"leafInventory\"]>();\n for (const previousLeaf of previousLeafs) {\n if (matchedPreviousIds.has(previousLeaf.id)) {\n continue;\n }\n const list = previousByHash.get(previousLeaf.contentHash) ?? [];\n list.push(previousLeaf);\n previousByHash.set(previousLeaf.contentHash, list);\n }\n for (const nextLeaf of nextLeafs) {\n if (matchedNextIds.has(nextLeaf.id)) {\n continue;\n }\n const list = nextByHash.get(nextLeaf.contentHash) ?? [];\n list.push(nextLeaf);\n nextByHash.set(nextLeaf.contentHash, list);\n }\n\n for (const contentHash of [...previousByHash.keys()].sort()) {\n const previousGroup = previousByHash.get(contentHash) ?? [];\n const nextGroup = nextByHash.get(contentHash) ?? [];\n if (previousGroup.length !== 1 || nextGroup.length !== 1) {\n continue;\n }\n\n const previousLeaf = previousGroup[0]!;\n const nextLeaf = nextGroup[0]!;\n if (\n previousLeaf.id === nextLeaf.id ||\n !this.canClassifyAsMoved(requestedPath, previousLeaf.relativePath, nextLeaf.relativePath)\n ) {\n continue;\n }\n\n diffs.push(\n this.createDiffItem(\"moved\", source.id, nextLeaf, {\n ...requestedPathOption,\n previousLeafId: previousLeaf.id,\n previousRelativePath: previousLeaf.relativePath,\n previousContentHash: previousLeaf.contentHash,\n }),\n );\n matchedPreviousIds.add(previousLeaf.id);\n matchedNextIds.add(nextLeaf.id);\n }\n\n for (const previousLeaf of previousLeafs) {\n if (matchedPreviousIds.has(previousLeaf.id)) {\n continue;\n }\n\n if (nextInvalidPaths.has(previousLeaf.relativePath)) {\n diffs.push(\n this.createDiffItem(\"invalidated\", source.id, previousLeaf, {\n ...requestedPathOption,\n previousLeafId: previousLeaf.id,\n previousRelativePath: previousLeaf.relativePath,\n previousContentHash: previousLeaf.contentHash,\n }),\n );\n invalidatedLeafIds.push(previousLeaf.id);\n matchedPreviousIds.add(previousLeaf.id);\n }\n }\n\n for (const previousLeaf of previousLeafs) {\n if (matchedPreviousIds.has(previousLeaf.id)) {\n continue;\n }\n\n diffs.push(\n this.createDiffItem(\"removed\", source.id, previousLeaf, {\n ...requestedPathOption,\n previousLeafId: previousLeaf.id,\n previousRelativePath: previousLeaf.relativePath,\n previousContentHash: previousLeaf.contentHash,\n }),\n );\n removedLeafIds.push(previousLeaf.id);\n matchedPreviousIds.add(previousLeaf.id);\n }\n\n for (const nextLeaf of nextLeafs) {\n if (matchedNextIds.has(nextLeaf.id)) {\n continue;\n }\n\n diffs.push(this.createDiffItem(\"added\", source.id, nextLeaf, requestedPathOption));\n addedLeafIds.push(nextLeaf.id);\n matchedNextIds.add(nextLeaf.id);\n }\n\n return {\n diffs,\n addedLeafIds,\n removedLeafIds,\n invalidatedLeafIds,\n };\n }\n\n private createDiffItem(\n kind: SourceUpdateDiff[\"kind\"],\n sourceId: string,\n leaf: LockFile[\"leafInventory\"][number],\n extras: {\n requestedPath?: string;\n previousLeafId?: string;\n previousRelativePath?: string;\n previousContentHash?: string;\n } = {},\n ): SourceUpdateDiff {\n return {\n kind,\n sourceId,\n leafId: leaf.id,\n relativePath: leaf.relativePath,\n contentHash: leaf.contentHash,\n ...(extras.requestedPath ? { requestedPath: extras.requestedPath } : {}),\n ...(extras.previousLeafId ? { previousLeafId: extras.previousLeafId } : {}),\n ...(extras.previousRelativePath ? { previousRelativePath: extras.previousRelativePath } : {}),\n ...(extras.previousContentHash ? { previousContentHash: extras.previousContentHash } : {}),\n };\n }\n\n private canClassifyAsMoved(\n requestedPath: string | undefined,\n previousRelativePath: string,\n nextRelativePath: string,\n ): boolean {\n if (!requestedPath) {\n return true;\n }\n\n return (\n this.isWithinRequestedPath(previousRelativePath, requestedPath) &&\n this.isWithinRequestedPath(nextRelativePath, requestedPath)\n );\n }\n\n private normalizeRequestedPath(requestedPath?: string): string | undefined {\n if (!requestedPath) {\n return undefined;\n }\n\n const normalized = requestedPath.replace(/^\\.\\/+/, \"\").replace(/\\/+$/, \"\");\n return normalized.length > 0 ? normalized : undefined;\n }\n\n private mergePersistentLockMetadata(\n currentLock: SourceLockRecord,\n nextLock: SourceLockRecord,\n ): SourceLockRecord {\n return {\n ...nextLock,\n ...(currentLock.originBranch ? { originBranch: currentLock.originBranch } : {}),\n ...(currentLock.importMode ? { importMode: currentLock.importMode } : {}),\n ...(currentLock.observedTargets ? { observedTargets: currentLock.observedTargets } : {}),\n ...(currentLock.importedFromTargets ? { importedFromTargets: currentLock.importedFromTargets } : {}),\n };\n }\n\n private isWithinRequestedPath(relativePath: string, requestedPath?: string): boolean {\n const normalizedPath = this.normalizeRequestedPath(requestedPath);\n if (!normalizedPath) {\n return true;\n }\n\n return (\n relativePath === normalizedPath || relativePath.startsWith(`${normalizedPath}/`)\n );\n }\n\n private async buildSnapshot(\n kind: SourceKind,\n sourceId: string,\n locator: string,\n displayName: string,\n checkoutPath: string,\n requestedPathOrOptions: string | { allowEmptyLeafs?: boolean } | undefined = undefined,\n addOptions: AddSourceOptions = {},\n maybeOptions: { allowEmptyLeafs?: boolean } = {},\n ): Promise<\n Result<{\n manifest: SourceManifestRecord;\n lock: SourceLockRecord;\n leafs: LockFile[\"leafInventory\"];\n }>\n > {\n const requestedPath =\n typeof requestedPathOrOptions === \"string\" ? requestedPathOrOptions : undefined;\n const options =\n typeof requestedPathOrOptions === \"string\"\n ? maybeOptions\n : (maybeOptions.allowEmptyLeafs !== undefined\n ? maybeOptions\n : (requestedPathOrOptions ?? {}));\n const sourceMetadata = await this.readSourceSnapshot(kind, checkoutPath);\n const scanned = await this.inventoryService.scanSource(\n sourceId,\n checkoutPath,\n displayName,\n );\n const requestedMatches = this.findRequestedLeafs(scanned.leafs, requestedPath);\n const metadataWarnings = scanned.leafs.flatMap((leaf) =>\n leaf.metadataWarnings.map((message) => ({\n code: \"SKILL_METADATA_WARNING\",\n message: `${leaf.relativePath}: ${message}`,\n })),\n );\n\n if (\n ((requestedPath && requestedMatches.length === 0) || scanned.leafs.length === 0) &&\n !options.allowEmptyLeafs\n ) {\n const emptyReason =\n scanned.skillFileCount === 0\n ? \" No SKILL.md files were found.\"\n : \"\";\n return fail(\n {\n code: requestedPath ? \"SOURCE_PATH_NOT_FOUND\" : \"NO_VALID_LEAFS\",\n message: requestedPath\n ? `Source '${displayName}' does not contain a valid skill at '${requestedPath}'.`\n : `Source '${displayName}' has no valid skills.${emptyReason}`,\n },\n scanned.invalidLeafs.map((leaf) => ({\n code: \"INVALID_LEAF\",\n message: `${leaf.path}: ${leaf.reason}`,\n })),\n );\n }\n\n return ok(\n {\n manifest: {\n id: sourceId,\n locator,\n kind,\n displayName,\n addedAt: new Date().toISOString(),\n ...(requestedPath ? { requestedPath } : {}),\n ...(addOptions.selectionMode ? { selectionMode: addOptions.selectionMode } : {}),\n ...(addOptions.originLocator ? { originLocator: addOptions.originLocator } : {}),\n ...(addOptions.originRequestedPath\n ? { originRequestedPath: addOptions.originRequestedPath }\n : {}),\n },\n lock: {\n id: sourceId,\n locator,\n kind,\n displayName,\n checkoutPath,\n updatedAt: new Date().toISOString(),\n leafIds: scanned.leafs.map((leaf) => leaf.id),\n invalidLeafs: scanned.invalidLeafs,\n ...sourceMetadata,\n ...(addOptions.originBranch ? { originBranch: addOptions.originBranch } : {}),\n ...(addOptions.importedFromTargets\n ? { importedFromTargets: addOptions.importedFromTargets }\n : {}),\n ...(addOptions.observedTargets\n ? { observedTargets: addOptions.observedTargets }\n : {}),\n ...(addOptions.importMode ? { importMode: addOptions.importMode } : {}),\n ...(kind === \"clawhub\"\n ? {\n versionMode: locator.includes(\"@\") ? (\"pinned\" as const) : (\"floating\" as const),\n }\n : {}),\n },\n leafs: scanned.leafs,\n },\n [\n ...metadataWarnings,\n ...scanned.duplicateLeafs.map((leaf) => ({\n code: \"DUPLICATE_LEAF\",\n message: `${leaf.path}: Duplicate skill content skipped because ${leaf.keptPath} was discovered first`,\n })),\n ...scanned.invalidLeafs.map((leaf) => ({\n code: \"INVALID_LEAF\",\n message: `${leaf.path}: ${leaf.reason}`,\n })),\n ],\n );\n }\n\n private async normalizeLocator(locator: string): Promise<string> {\n const trimmed = locator.trim();\n\n if (trimmed.startsWith(\"git@\") || trimmed.startsWith(\"http\")) {\n return trimmed;\n }\n\n if (/^[^/\\s]+\\/[^/\\s]+$/.test(trimmed)) {\n return `https://github.com/${trimmed}.git`;\n }\n\n const resolvedPath = path.resolve(trimmed);\n if (await pathExists(resolvedPath)) {\n return resolvedPath;\n }\n\n return trimmed;\n }\n\n private async resolveSource(\n locator: string,\n options: AddSourceOptions,\n ): Promise<SourceResolution> {\n const trimmed = locator.trim();\n const fileLocatorPath = this.parseFileLocator(trimmed);\n const resolvedPath = path.resolve(fileLocatorPath ?? trimmed);\n if (\n await pathExists(resolvedPath) &&\n (!fileLocatorPath || !(await this.isGitRepositoryPath(resolvedPath)))\n ) {\n return {\n kind: \"local\",\n locator: resolvedPath,\n localPath: resolvedPath,\n displayName: options.displayNameOverride ?? deriveDisplayName(resolvedPath),\n sourceId: options.sourceIdOverride ?? deriveSourceId(resolvedPath),\n ...(options.path ? { requestedPath: options.path } : {}),\n };\n }\n\n const treeLocator = this.parseTreeLocator(trimmed);\n if (treeLocator) {\n const requestedPath = this.joinRequestedPaths(\n treeLocator.requestedPath,\n options.path,\n );\n return {\n kind: \"git\",\n locator: treeLocator.repoLocator,\n gitLocator: await this.normalizeLocator(treeLocator.repoLocator),\n displayName: options.displayNameOverride ?? deriveDisplayName(treeLocator.repoLocator),\n sourceId: options.sourceIdOverride ?? deriveSourceId(treeLocator.repoLocator),\n ...(requestedPath ? { requestedPath } : {}),\n };\n }\n\n const shorthandLocator = this.parseGitHubShorthandSubpath(trimmed);\n if (shorthandLocator) {\n const requestedPath = this.joinRequestedPaths(\n shorthandLocator.requestedPath,\n options.path,\n );\n return {\n kind: \"git\",\n locator: shorthandLocator.repoLocator,\n gitLocator: await this.normalizeLocator(shorthandLocator.repoLocator),\n displayName: options.displayNameOverride ?? deriveDisplayName(shorthandLocator.repoLocator),\n sourceId: options.sourceIdOverride ?? deriveSourceId(shorthandLocator.repoLocator),\n ...(requestedPath ? { requestedPath } : {}),\n };\n }\n\n const clawhubMatch = trimmed.match(/^clawhub:([^@\\s]+)(?:@(.+))?$/);\n if (clawhubMatch) {\n const slug = clawhubMatch[1];\n const version = clawhubMatch[2];\n if (!slug) {\n throw new Error(`Invalid ClawHub locator '${locator}'.`);\n }\n\n return version\n ? {\n kind: \"clawhub\",\n locator: trimmed,\n displayName: options.displayNameOverride ?? deriveDisplayName(trimmed),\n sourceId: options.sourceIdOverride ?? deriveSourceId(trimmed),\n ...(options.path ? { requestedPath: options.path } : {}),\n clawhubSlug: slug,\n requestedVersion: version,\n versionMode: \"pinned\",\n }\n : {\n kind: \"clawhub\",\n locator: trimmed,\n displayName: options.displayNameOverride ?? deriveDisplayName(trimmed),\n sourceId: options.sourceIdOverride ?? deriveSourceId(trimmed),\n ...(options.path ? { requestedPath: options.path } : {}),\n clawhubSlug: slug,\n versionMode: \"floating\",\n };\n }\n\n return {\n kind: \"git\",\n locator,\n gitLocator: await this.normalizeLocator(locator),\n displayName: options.displayNameOverride ?? deriveDisplayName(locator),\n sourceId: options.sourceIdOverride ?? deriveSourceId(locator),\n ...(options.path ? { requestedPath: options.path } : {}),\n };\n }\n\n private resolveUniqueLocalSource(\n resolved: SourceResolution,\n existingSources: SourceManifestRecord[],\n ): SourceResolution {\n if (resolved.kind !== \"local\" || !resolved.localPath) {\n return resolved;\n }\n\n if (\n existingSources.some(\n (source) => source.kind === \"local\" && path.resolve(source.locator) === resolved.localPath,\n )\n ) {\n return resolved;\n }\n\n const folderName = path.basename(resolved.localPath);\n const parentFolderName = path.basename(path.dirname(resolved.localPath));\n const displayCandidates = [\n folderName,\n `${parentFolderName}_${folderName}`,\n ];\n const takenIds = new Set(existingSources.map((source) => source.id));\n const takenLabels = new Set(\n existingSources\n .filter((source) => source.kind === \"local\")\n .map((source) => source.displayName),\n );\n\n for (const candidate of displayCandidates) {\n const sourceId = deriveSourceId(candidate);\n if (!takenIds.has(sourceId) && !takenLabels.has(candidate)) {\n return {\n ...resolved,\n displayName: candidate,\n sourceId,\n };\n }\n }\n\n const baseDisplayName = `${parentFolderName}_${folderName}`;\n let index = 2;\n while (true) {\n const displayName = `${baseDisplayName}_${index}`;\n const sourceId = deriveSourceId(displayName);\n if (!takenIds.has(sourceId) && !takenLabels.has(displayName)) {\n return {\n ...resolved,\n displayName,\n sourceId,\n };\n }\n index += 1;\n }\n }\n\n private parseTreeLocator(\n locator: string,\n ): { repoLocator: string; requestedPath?: string } | null {\n try {\n const url = new URL(locator);\n\n const parts = url.pathname.split(\"/\").filter(Boolean);\n if (url.hostname === \"github.com\") {\n if (parts.length < 5 || parts[2] !== \"tree\") {\n return null;\n }\n\n const owner = parts[0];\n const repo = parts[1];\n const requestedPath = parts.slice(4).join(\"/\");\n if (!owner || !repo || !requestedPath) {\n return null;\n }\n\n return {\n repoLocator: `https://github.com/${owner}/${repo}.git`,\n requestedPath,\n };\n }\n\n if (url.hostname === \"gitlab.com\") {\n const markerIndex = parts.findIndex(\n (segment, index) => segment === \"-\" && parts[index + 1] === \"tree\",\n );\n if (markerIndex < 2) {\n return null;\n }\n\n const requestedPath = parts.slice(markerIndex + 3).join(\"/\");\n\n return {\n repoLocator: `https://gitlab.com/${parts.slice(0, markerIndex).join(\"/\")}.git`,\n ...(requestedPath ? { requestedPath } : {}),\n };\n }\n } catch {\n return null;\n }\n\n return null;\n }\n\n private parseGitHubShorthandSubpath(\n locator: string,\n ): { repoLocator: string; requestedPath: string } | null {\n const trimmed = locator.replace(/\\/+$/, \"\");\n const parts = trimmed.split(\"/\");\n if (parts.length < 3) {\n return null;\n }\n\n const owner = parts[0];\n const rawRepo = parts[1];\n const requestedPath = parts.slice(2).join(\"/\");\n if (!owner || !rawRepo || !requestedPath) {\n return null;\n }\n\n const repo = rawRepo.replace(/\\.git$/i, \"\");\n return {\n repoLocator: `https://github.com/${owner}/${repo}.git`,\n requestedPath,\n };\n }\n\n private parseFileLocator(locator: string): string | null {\n if (!locator.startsWith(\"file://\")) {\n return null;\n }\n\n try {\n const fileUrl = new URL(locator);\n if (fileUrl.protocol !== \"file:\") {\n return null;\n }\n return path.resolve(decodeURIComponent(fileUrl.pathname));\n } catch {\n return null;\n }\n }\n\n private async isGitRepositoryPath(candidatePath: string): Promise<boolean> {\n if (await pathExists(path.join(candidatePath, \".git\"))) {\n return true;\n }\n\n return (\n await pathExists(path.join(candidatePath, \"HEAD\")) &&\n await pathExists(path.join(candidatePath, \"objects\")) &&\n await pathExists(path.join(candidatePath, \"refs\"))\n );\n }\n\n private joinRequestedPaths(basePath?: string, childPath?: string): string | undefined {\n const normalizedBase = this.normalizeRequestedPath(basePath);\n const normalizedChild = this.normalizeRequestedPath(childPath);\n\n if (!normalizedBase) {\n return normalizedChild;\n }\n\n if (!normalizedChild) {\n return normalizedBase;\n }\n\n if (\n normalizedChild === normalizedBase ||\n normalizedChild.startsWith(`${normalizedBase}/`)\n ) {\n return normalizedChild;\n }\n\n return `${normalizedBase}/${normalizedChild}`;\n }\n\n private findRequestedLeafs(\n leafs: LockFile[\"leafInventory\"],\n requestedPath?: string,\n ): LockFile[\"leafInventory\"] {\n const normalizedPath = this.normalizeRequestedPath(requestedPath);\n if (!normalizedPath) {\n return leafs;\n }\n\n return leafs.filter(\n (leaf) =>\n leaf.relativePath === normalizedPath ||\n leaf.relativePath.startsWith(`${normalizedPath}/`),\n );\n }\n\n private async fetchSource(\n source: SourceResolution,\n checkoutPath: string,\n ): Promise<void> {\n if (source.kind === \"local\") {\n await copyDirectory(source.localPath!, checkoutPath);\n return;\n }\n\n if (source.kind === \"git\") {\n if (!(await isGitAvailable())) {\n await this.fetchGitArchive(source.gitLocator!, checkoutPath);\n return;\n }\n try {\n await git([\"clone\", \"--depth\", \"1\", source.gitLocator!, checkoutPath]);\n } catch (error) {\n const fallbackLocator = this.resolveGitCloneFallbackLocator(source.gitLocator!);\n if (!fallbackLocator) {\n throw error;\n }\n await git([\"clone\", \"--depth\", \"1\", fallbackLocator, checkoutPath]);\n }\n return;\n }\n\n if (source.kind === \"clawhub\") {\n const installed = await installClawHubSkill(\n source.clawhubSlug!,\n source.requestedVersion,\n );\n try {\n await copyDirectory(installed.installedPath, checkoutPath);\n } finally {\n await removePath(installed.workdir);\n }\n return;\n }\n }\n\n private async updateSource(\n source: SourceManifestRecord,\n currentLock: SourceLockRecord,\n ): Promise<boolean> {\n if (source.kind === \"local\") {\n return this.refreshLocalSourceCheckout(source, currentLock);\n }\n\n if (source.kind === \"git\") {\n if (!(await isGitAvailable())) {\n return this.refreshGitArchiveCheckout(source, currentLock);\n }\n await git([\"pull\", \"--ff-only\"], { cwd: currentLock.checkoutPath });\n const latestCommitSha = await git([\"rev-parse\", \"HEAD\"], {\n cwd: currentLock.checkoutPath,\n });\n return latestCommitSha !== currentLock.commitSha;\n }\n\n if (source.kind === \"clawhub\") {\n if (currentLock.versionMode === \"pinned\") {\n return false;\n }\n\n const installed = await installClawHubSkill(currentLock.packageSlug ?? currentLock.id);\n try {\n if (installed.resolvedVersion === currentLock.resolvedVersion) {\n return false;\n }\n\n await copyDirectory(installed.installedPath, currentLock.checkoutPath);\n return true;\n } finally {\n await removePath(installed.workdir);\n }\n }\n\n return false;\n }\n\n private async refreshLocalSourceCheckout(\n source: SourceManifestRecord,\n currentLock: SourceLockRecord,\n ): Promise<boolean> {\n const tempCheckoutPath = `${currentLock.checkoutPath}.${process.pid}.${crypto.randomUUID()}.refresh`;\n const backupPath = `${currentLock.checkoutPath}.${process.pid}.${crypto.randomUUID()}.backup`;\n\n try {\n if (!(await pathExists(source.locator))) {\n throw new Error(`Local source origin is missing at ${source.locator}.`);\n }\n\n await copyDirectory(source.locator, tempCheckoutPath);\n const nextHash = await hashDirectory(tempCheckoutPath);\n const checkoutExists = await pathExists(currentLock.checkoutPath);\n const currentHash =\n checkoutExists ? await hashDirectory(currentLock.checkoutPath) : undefined;\n if (checkoutExists && nextHash === currentLock.contentHash && currentHash === nextHash) {\n await removePath(tempCheckoutPath);\n return false;\n }\n\n if (checkoutExists) {\n await fs.rename(currentLock.checkoutPath, backupPath);\n try {\n await fs.rename(tempCheckoutPath, currentLock.checkoutPath);\n } catch (error) {\n await fs.rename(backupPath, currentLock.checkoutPath).catch(() => {});\n throw error;\n } finally {\n await removePath(backupPath).catch(() => {});\n }\n } else {\n await fs.rename(tempCheckoutPath, currentLock.checkoutPath);\n }\n\n return true;\n } catch (error) {\n await removePath(tempCheckoutPath).catch(() => {});\n await removePath(backupPath).catch(() => {});\n throw error;\n }\n }\n\n private async readSourceSnapshot(\n kind: SourceKind,\n checkoutPath: string,\n ): Promise<Partial<SourceLockRecord>> {\n if (kind === \"local\") {\n return {\n contentHash: await hashDirectory(checkoutPath),\n };\n }\n\n if (kind === \"git\") {\n if (!(await pathExists(path.join(checkoutPath, \".git\")))) {\n return {\n contentHash: await hashDirectory(checkoutPath),\n };\n }\n return {\n commitSha: await git([\"rev-parse\", \"HEAD\"], { cwd: checkoutPath }),\n };\n }\n\n if (kind === \"clawhub\") {\n const origin = await readJsonFile<{\n slug?: string;\n installedVersion?: string;\n }>(path.join(checkoutPath, \".clawhub\", \"origin.json\"), {});\n const contentHash = await hashDirectory(checkoutPath);\n return {\n ...(origin.slug ? { packageSlug: origin.slug } : {}),\n ...(origin.installedVersion ? { resolvedVersion: origin.installedVersion } : {}),\n contentHash,\n };\n }\n\n return {};\n }\n\n private async refreshGitArchiveCheckout(\n source: SourceManifestRecord,\n currentLock: SourceLockRecord,\n ): Promise<boolean> {\n const tempCheckoutPath = `${currentLock.checkoutPath}.${process.pid}.${crypto.randomUUID()}.refresh`;\n const backupPath = `${currentLock.checkoutPath}.${process.pid}.${crypto.randomUUID()}.backup`;\n\n try {\n await this.fetchGitArchive(source.locator, tempCheckoutPath, currentLock.originBranch);\n const nextHash = await hashDirectory(tempCheckoutPath);\n const checkoutExists = await pathExists(currentLock.checkoutPath);\n const currentHash =\n checkoutExists ? await hashDirectory(currentLock.checkoutPath) : undefined;\n if (checkoutExists && nextHash === currentLock.contentHash && currentHash === nextHash) {\n await removePath(tempCheckoutPath);\n return false;\n }\n\n if (checkoutExists) {\n await fs.rename(currentLock.checkoutPath, backupPath);\n try {\n await fs.rename(tempCheckoutPath, currentLock.checkoutPath);\n } catch (error) {\n await fs.rename(backupPath, currentLock.checkoutPath).catch(() => {});\n throw error;\n } finally {\n await removePath(backupPath).catch(() => {});\n }\n } else {\n await fs.rename(tempCheckoutPath, currentLock.checkoutPath);\n }\n\n return true;\n } catch (error) {\n await removePath(tempCheckoutPath).catch(() => {});\n await removePath(backupPath).catch(() => {});\n throw error;\n }\n }\n\n private async fetchGitArchive(\n locator: string,\n checkoutPath: string,\n preferredBranch?: string,\n ): Promise<void> {\n const archiveRepo = this.parseArchiveRepo(locator);\n if (!archiveRepo) {\n throw new Error(`Git is unavailable and '${locator}' is not a supported archive source.`);\n }\n\n const tempRoot = `${checkoutPath}.${process.pid}.${crypto.randomUUID()}.archive`;\n const archivePath = path.join(tempRoot, \"repo.zip\");\n const extractPath = path.join(tempRoot, \"extract\");\n\n try {\n await ensureDir(tempRoot);\n\n const branchCandidates = [\n preferredBranch,\n \"main\",\n \"master\",\n ].filter((value, index, values): value is string => Boolean(value) && values.indexOf(value) === index);\n\n let lastError: Error | undefined;\n for (const branch of branchCandidates) {\n try {\n if (archiveRepo.provider === \"github\") {\n await this.downloadGitHubArchive(\n archiveRepo.owner,\n archiveRepo.repo,\n branch,\n archivePath,\n );\n } else {\n await this.downloadGitLabArchive(\n archiveRepo.host,\n archiveRepo.projectPath,\n branch,\n archivePath,\n );\n }\n await this.extractZipArchive(archivePath, extractPath);\n await this.copyExtractedArchive(\n extractPath,\n checkoutPath,\n `${archiveRepo.repo}-${branch}`,\n );\n return;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n await removePath(archivePath).catch(() => {});\n await removePath(extractPath).catch(() => {});\n }\n }\n\n throw lastError ?? new Error(`Unable to download archive for '${locator}'.`);\n } finally {\n await removePath(tempRoot).catch(() => {});\n }\n }\n\n private parseArchiveRepo(\n locator: string,\n ): { provider: \"github\"; owner: string; repo: string }\n | { provider: \"gitlab\"; host: string; projectPath: string; repo: string }\n | null {\n const githubRepo = parseGitHubRepo(locator);\n if (githubRepo) {\n return { provider: \"github\", owner: githubRepo.owner, repo: githubRepo.repo };\n }\n\n const hostedRepo = parseHostedGitRepo(locator);\n if (!hostedRepo || !this.isGitLabHost(hostedRepo.host)) {\n return null;\n }\n\n const projectPath = this.extractGitLabProjectPath(locator);\n if (!projectPath) {\n return null;\n }\n\n return {\n provider: \"gitlab\",\n host: hostedRepo.host,\n projectPath,\n repo: hostedRepo.repo,\n };\n }\n\n private isGitLabHost(host: string): boolean {\n const normalizedHost = host.toLowerCase();\n const configuredHost = process.env.GITLAB_HOST?.trim().toLowerCase();\n return (\n normalizedHost === \"gitlab.com\" ||\n normalizedHost.includes(\"gitlab\") ||\n (configuredHost ? normalizedHost === configuredHost : false)\n );\n }\n\n private extractGitLabProjectPath(locator: string): string | undefined {\n const trimmed = locator.trim().replace(/\\/+$/, \"\");\n if (/^https?:\\/\\//i.test(trimmed)) {\n try {\n const url = new URL(trimmed);\n const parts = url.pathname\n .split(\"/\")\n .filter(Boolean)\n .map((part, index, values) =>\n index === values.length - 1 ? part.replace(/\\.git$/i, \"\") : part\n );\n return parts.length >= 2 ? parts.join(\"/\") : undefined;\n } catch {\n return undefined;\n }\n }\n\n const sshMatch = trimmed.match(/^git@([^:\\s]+):(.+?)(?:\\.git)?$/i);\n if (!sshMatch) {\n return undefined;\n }\n\n const projectPath = sshMatch[2]\n ?.split(\"/\")\n .filter(Boolean)\n .join(\"/\");\n return projectPath || undefined;\n }\n\n private resolveGitCloneFallbackLocator(locator: string): string | undefined {\n const trimmed = locator.trim();\n if (!trimmed.startsWith(\"git@\")) {\n return undefined;\n }\n\n const hostedRepo = parseHostedGitRepo(trimmed);\n if (!hostedRepo || !this.isGitLabHost(hostedRepo.host)) {\n return undefined;\n }\n\n const projectPath = this.extractGitLabProjectPath(trimmed);\n if (!projectPath) {\n return undefined;\n }\n\n return `https://${hostedRepo.host}/${projectPath}.git`;\n }\n\n private async downloadGitHubArchive(\n owner: string,\n repo: string,\n branch: string,\n archivePath: string,\n ): Promise<void> {\n const response = await fetch(\n `https://github.com/${owner}/${repo}/archive/refs/heads/${branch}.zip`,\n );\n if (!response.ok) {\n throw new Error(`GitHub archive download failed with status ${response.status} for branch '${branch}'.`);\n }\n\n const buffer = Buffer.from(await response.arrayBuffer());\n await fs.writeFile(archivePath, buffer);\n }\n\n private async downloadGitLabArchive(\n host: string,\n projectPath: string,\n branch: string,\n archivePath: string,\n ): Promise<void> {\n const response = await fetch(\n `https://${host}/api/v4/projects/${encodeURIComponent(projectPath)}/repository/archive.zip?sha=${encodeURIComponent(branch)}`,\n {\n headers: {\n ...(process.env.GITLAB_TOKEN\n ? { \"PRIVATE-TOKEN\": process.env.GITLAB_TOKEN }\n : {}),\n },\n },\n );\n if (!response.ok) {\n throw new Error(`GitLab archive download failed with status ${response.status} for branch '${branch}'.`);\n }\n\n const buffer = Buffer.from(await response.arrayBuffer());\n await fs.writeFile(archivePath, buffer);\n }\n\n private async extractZipArchive(archivePath: string, extractPath: string): Promise<void> {\n await ensureDir(extractPath);\n const command =\n process.platform === \"darwin\"\n ? { file: \"ditto\", args: [\"-x\", \"-k\", archivePath, extractPath] }\n : { file: \"unzip\", args: [\"-q\", archivePath, \"-d\", extractPath] };\n await execFileAsync(command.file, command.args, {\n encoding: \"utf8\",\n env: process.env,\n });\n }\n\n private async copyExtractedArchive(\n extractPath: string,\n checkoutPath: string,\n expectedArchiveRootName?: string,\n ): Promise<void> {\n const entries = await fs.readdir(extractPath, { withFileTypes: true });\n const visibleEntries = entries.filter((entry) => entry.name !== \"__MACOSX\");\n const visibleDirectories = visibleEntries.filter((entry) => entry.isDirectory());\n const visibleFiles = visibleEntries.filter((entry) => !entry.isDirectory());\n const sourcePath =\n visibleDirectories.length === 1 &&\n visibleFiles.length === 0 &&\n expectedArchiveRootName &&\n visibleDirectories[0]?.name === expectedArchiveRootName\n ? path.join(extractPath, visibleDirectories[0]!.name)\n : extractPath;\n await copyDirectory(sourcePath, checkoutPath);\n }\n}\n", "import type {\n DoctorReport,\n HealthStatus,\n LockFile,\n Manifest,\n SourceBinding,\n WorkflowSummary,\n} from \"@skill-flow/domain/types\";\n\nexport class WorkflowService {\n getSummaries(\n manifest: Manifest,\n lockFile: LockFile,\n audit?: DoctorReport,\n ): WorkflowSummary[] {\n return manifest.sources.map((source) => {\n const lock = lockFile.sources.find((item) => item.id === source.id);\n const leafs = lockFile.leafInventory.filter((leaf) => leaf.sourceId === source.id);\n const bindings = manifest.bindings[source.id] ?? ({ targets: {} } satisfies SourceBinding);\n const activeTargetCount = Object.values(bindings.targets).filter(\n (binding) => binding?.enabled,\n ).length;\n const warningCount = leafs.reduce(\n (count, leaf) => count + leaf.metadataWarnings.length,\n 0,\n );\n const issueCounts = {\n warning: audit?.issues.filter((issue) => issue.sourceId === source.id && issue.severity === \"warning\").length ?? 0,\n error: audit?.issues.filter((issue) => issue.sourceId === source.id && issue.severity === \"error\").length ?? 0,\n };\n\n return {\n source,\n lock,\n leafs,\n bindings,\n activeTargetCount,\n health: this.resolveHealth(\n lock ? lock.invalidLeafs.length : 0,\n warningCount,\n activeTargetCount,\n lock,\n issueCounts,\n ),\n issueCounts,\n ...(issueCounts.error > 0\n ? { healthReason: \"audit errors detected\" }\n : issueCounts.warning > 0\n ? { healthReason: \"audit warnings detected\" }\n : {}),\n };\n });\n }\n\n private resolveHealth(\n invalidLeafCount: number,\n warningCount: number,\n activeTargetCount: number,\n lock?: LockFile[\"sources\"][number],\n issueCounts: { warning: number; error: number } = { warning: 0, error: 0 },\n ): HealthStatus {\n if (!lock) {\n return \"BLOCKED\";\n }\n if (issueCounts.error > 0) {\n return \"BLOCKED\";\n }\n if (invalidLeafCount > 0 || warningCount > 0 || issueCounts.warning > 0) {\n return \"PARTIAL\";\n }\n if (activeTargetCount === 0) {\n return \"INACTIVE\";\n }\n return \"ACTIVE\";\n }\n}\n", "import fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport type { DeploymentTargetName, LockFile, Manifest } from \"@skill-flow/domain/types\";\nimport { getManagedDeployments } from \"@skill-flow/domain/projection-compat\";\nimport { getTargetScanRoots, TARGET_DEFINITIONS, TARGET_ORDER } from \"@skill-flow/integration/utils/constants\";\nimport { hashDirectory, pathExists, readJsonFile } from \"@skill-flow/integration/utils/fs\";\nimport { deriveSourceId } from \"@skill-flow/integration/utils/source-id\";\nimport { StateStore } from \"@skill-flow/storage/store\";\n\nexport type BootstrapEvent = {\n phase:\n | \"detect-targets\"\n | \"scan-external-roots\"\n | \"import-unmanaged-skills\"\n | \"refresh-sources\"\n | \"normalize-bindings\"\n | \"audit-projections\"\n | \"build-summaries\"\n | \"done\";\n level: \"info\" | \"warning\" | \"error\" | \"success\";\n message: string;\n};\n\nexport type DetectedExternalSkill = {\n path: string;\n displayName: string;\n sourceId: string;\n importedFromTargets: DeploymentTargetName[];\n observedTargets: Array<{\n target: DeploymentTargetName;\n rootPath: string;\n targetPath: string;\n }>;\n originLocator?: string;\n originRequestedPath?: string;\n originBranch?: string;\n};\n\ntype AgentsLockFile = {\n skills?: Record<\n string,\n {\n source?: string;\n sourceType?: string;\n sourceUrl?: string;\n skillPath?: string;\n branch?: string;\n sourceBranch?: string;\n }\n >;\n};\n\ntype AgentsOrigin = {\n originLocator: string | undefined;\n originRequestedPath: string | undefined;\n originBranch: string | undefined;\n};\n\nexport class WorkspaceBootstrapService {\n constructor(private readonly store: StateStore) {}\n\n async detectUnmanagedExternalSkills(\n manifest: Manifest,\n lockFile: LockFile,\n onEvent?: (event: BootstrapEvent) => void,\n ): Promise<DetectedExternalSkill[]> {\n const managedLocators = new Set(\n manifest.sources\n .filter((source) => source.kind === \"local\")\n .map((source) => path.resolve(source.locator)),\n );\n const managedCheckouts = new Set(\n lockFile.sources.map((source) => path.resolve(source.checkoutPath)),\n );\n const managedTargetPaths = new Set(\n getManagedDeployments(lockFile).map((deployment) => path.resolve(deployment.targetPath)),\n );\n const agentsOrigins = await this.readAgentsOrigins();\n const grouped = new Map<\n string,\n {\n path: string;\n displayName: string;\n hash: string;\n targets: Set<DeploymentTargetName>;\n observedTargets: Array<{\n target: DeploymentTargetName;\n rootPath: string;\n targetPath: string;\n }>;\n origin: AgentsOrigin | undefined;\n }\n >();\n\n onEvent?.({\n phase: \"scan-external-roots\",\n level: \"info\",\n message: \"Scanning detected agent roots for unmanaged skills...\",\n });\n\n for (const target of TARGET_ORDER) {\n const roots = getTargetScanRoots(target).map((root) => path.resolve(root));\n for (const root of roots) {\n if (!(await pathExists(root))) {\n continue;\n }\n\n const entries = await fs.readdir(root, { withFileTypes: true });\n for (const entry of entries) {\n const skillDir = path.join(root, entry.name);\n const isDirectoryLike =\n entry.isDirectory() ||\n (entry.isSymbolicLink() &&\n (await fs.stat(skillDir).then((stats) => stats.isDirectory()).catch(() => false)));\n if (!isDirectoryLike) {\n continue;\n }\n\n if (!(await pathExists(path.join(skillDir, \"SKILL.md\")))) {\n continue;\n }\n\n const resolvedPath = await fs.realpath(skillDir).catch(() => path.resolve(skillDir));\n if (this.isUnderSkillFlowStore(resolvedPath)) {\n continue;\n }\n if (\n managedLocators.has(resolvedPath) ||\n managedCheckouts.has(resolvedPath) ||\n managedTargetPaths.has(resolvedPath)\n ) {\n continue;\n }\n\n const contentHash = await hashDirectory(resolvedPath);\n const groupKey = `${resolvedPath}\\n${contentHash}`;\n const current = grouped.get(groupKey);\n if (current) {\n current.targets.add(target);\n current.observedTargets.push({\n target,\n rootPath: root,\n targetPath: skillDir,\n });\n continue;\n }\n\n grouped.set(groupKey, {\n path: resolvedPath,\n displayName: entry.name,\n hash: contentHash,\n targets: new Set([target]),\n observedTargets: [{\n target,\n rootPath: root,\n targetPath: skillDir,\n }],\n origin: agentsOrigins.get(entry.name),\n });\n }\n }\n }\n\n const takenSourceIds = new Set(manifest.sources.map((source) => source.id));\n const results: DetectedExternalSkill[] = [];\n\n for (const item of grouped.values()) {\n const baseId = deriveSourceId(item.path);\n const sourceId = this.allocateSourceId(baseId, item.targets, takenSourceIds);\n takenSourceIds.add(sourceId);\n results.push({\n path: item.path,\n displayName: item.displayName,\n sourceId,\n importedFromTargets: TARGET_ORDER.filter((target) => item.targets.has(target)),\n observedTargets: [...item.observedTargets],\n ...(item.origin?.originLocator ? { originLocator: item.origin.originLocator } : {}),\n ...(item.origin?.originRequestedPath\n ? { originRequestedPath: item.origin.originRequestedPath }\n : {}),\n ...(item.origin?.originBranch ? { originBranch: item.origin.originBranch } : {}),\n });\n }\n\n return results.sort((left, right) => left.displayName.localeCompare(right.displayName));\n }\n\n private isUnderSkillFlowStore(candidatePath: string) {\n const relative = path.relative(this.store.rootPath, candidatePath);\n return relative !== \"\" && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n }\n\n private allocateSourceId(\n baseId: string,\n targets: Set<DeploymentTargetName>,\n takenSourceIds: Set<string>,\n ) {\n if (!takenSourceIds.has(baseId)) {\n return baseId;\n }\n\n for (const target of TARGET_ORDER) {\n if (!targets.has(target)) {\n continue;\n }\n const suffixed = `${baseId}-${TARGET_DEFINITIONS[target].writerKey}`;\n if (!takenSourceIds.has(suffixed)) {\n return suffixed;\n }\n }\n\n let index = 2;\n while (takenSourceIds.has(`${baseId}-${index}`)) {\n index += 1;\n }\n return `${baseId}-${index}`;\n }\n\n private async readAgentsOrigins(): Promise<Map<string, AgentsOrigin>> {\n const lockPath = path.join(os.homedir(), \".agents\", \".skill-lock.json\");\n const lockFile = await readJsonFile<AgentsLockFile>(lockPath, {});\n const results = new Map<string, AgentsOrigin>();\n\n for (const [name, record] of Object.entries(lockFile.skills ?? {})) {\n if (!record || record.sourceType !== \"github\") {\n continue;\n }\n results.set(name, {\n originLocator: record.source ? `https://github.com/${record.source}.git` : undefined,\n originRequestedPath: record.skillPath,\n originBranch: record.branch ?? record.sourceBranch ?? this.parseBranchFromSourceUrl(record.sourceUrl),\n });\n }\n\n return results;\n }\n\n private parseBranchFromSourceUrl(sourceUrl?: string) {\n if (!sourceUrl) {\n return undefined;\n }\n const treeIndex = sourceUrl.indexOf(\"/tree/\");\n if (treeIndex === -1) {\n return undefined;\n }\n const tail = sourceUrl.slice(treeIndex + \"/tree/\".length);\n return tail.split(\"/\")[0] || undefined;\n }\n}\n", "import React, { useEffect, useRef, useState } from \"react\";\nimport { Box, Text, useApp, useInput, useStdout } from \"ink\";\nimport type {\n ConfigBootStatus,\n DeploymentAction,\n DeploymentTargetId,\n DoctorReport,\n DraftBinding,\n WorkflowSummary,\n} from \"@skill-flow/domain/types\";\nimport type { SkillFlowApp } from \"@skill-flow/query/runtime\";\nimport { formatTargetName } from \"@skill-flow/integration/utils/format\";\nimport {\n buildProjectedSkillName,\n formatGroupLabel,\n getHostedGitOwner,\n resolveProjectedSkillNames,\n} from \"@skill-flow/integration/utils/naming\";\nimport {\n getParentSelectionState,\n toggleChild,\n toggleParent,\n type TreeSelectionState,\n} from \"./selection-state.js\";\nimport { ADD_BADGE_TEXT } from \"./add-flow.js\";\n\ntype ConfigAppProps = {\n app: SkillFlowApp;\n availableTargets: DeploymentTargetId[];\n summaries: WorkflowSummary[];\n initialDrafts: Record<string, DraftBinding>;\n bootStatus: ConfigBootStatus;\n};\n\ntype ConfigBootstrapState =\n | { phase: \"loading\"; logs: string[] }\n | {\n phase: \"ready\";\n logs: string[];\n availableTargets: DeploymentTargetId[];\n summaries: WorkflowSummary[];\n initialDrafts: Record<string, DraftBinding>;\n audit: DoctorReport;\n bootStatus: ConfigBootStatus;\n }\n | { phase: \"error\"; logs: string[]; message: string };\n\ntype FocusPane = \"groups\" | \"detail.agents\" | \"detail.skills\" | \"detail.actions\";\ntype DetailFocus = Exclude<FocusPane, \"groups\">;\ntype ActionName = \"update\" | \"delete\";\ntype AlertLevel = \"error\" | \"blocked\" | \"warning\";\n\ntype PreviewState = {\n actions: DeploymentAction[];\n blockedCount: number;\n errorMessage: string | undefined;\n loading: boolean;\n requestId: number;\n};\n\ntype SaveState = {\n phase: \"idle\" | \"saving\" | \"saved\" | \"failed\";\n message: string | undefined;\n};\n\ntype UpdateState = {\n phase: \"idle\" | \"updating\" | \"updated\" | \"failed\";\n message: string | undefined;\n};\n\ntype DeleteState = {\n phase: \"idle\" | \"deleting\" | \"failed\";\n sourceId: string | undefined;\n message: string | undefined;\n};\n\ntype StatusKind =\n | \"clean\"\n | \"saving\"\n | \"saved\"\n | \"failed\"\n | \"updating\"\n | \"updated\"\n | \"update-failed\"\n | \"deleting\";\n\ntype StatusDisplay = {\n kind: StatusKind;\n label: string;\n color: \"green\" | \"cyan\" | \"red\" | \"yellow\" | \"gray\";\n};\n\ntype TopBarDisplay = {\n title: string;\n titleColor: \"blue\";\n detail?: string;\n detailColor?: StatusDisplay[\"color\"];\n};\n\ntype PaneRow = {\n key: string;\n text: string;\n active: boolean;\n color: \"cyan\" | \"gray\" | \"green\" | \"red\" | \"white\" | \"yellow\" | undefined;\n bold?: boolean;\n activeColor?: \"cyan\" | \"gray\" | \"green\" | \"red\" | \"white\" | \"yellow\";\n};\n\ntype AlertItem = {\n level: AlertLevel;\n message: string;\n};\n\nexport type ConfigGroup = {\n id: string;\n title: string;\n kind: \"source\" | \"clawhub\";\n summaries: WorkflowSummary[];\n};\n\ntype ConfigSkillRow = {\n summary: WorkflowSummary;\n leaf: WorkflowSummary[\"leafs\"][number];\n};\n\ntype WindowedRows<T> = {\n rows: T[];\n start: number;\n end: number;\n};\n\ntype FocusSnapshot = {\n focus: FocusPane;\n groupIndex: number;\n groupId: string;\n sourceId: string | undefined;\n agentTarget: DeploymentTargetId | undefined;\n skillId: string | undefined;\n action: ActionName;\n};\n\ntype ProjectionWarningMap = Record<string, string[]>;\ntype ProjectionNameMap = Map<string, string>;\n\nconst EMPTY_DRAFT: DraftBinding = {\n enabledTargets: [],\n selectedLeafIds: [],\n};\n\nconst EMPTY_CONFIG_GROUP: ConfigGroup = {\n id: \"__empty__\",\n title: \"\",\n kind: \"source\",\n summaries: [],\n};\n\nconst EMPTY_PREVIEW: PreviewState = {\n actions: [],\n blockedCount: 0,\n errorMessage: undefined,\n loading: false,\n requestId: 0,\n};\n\nconst PANE_CHROME_ROWS = 5;\nconst UPDATED_FEEDBACK_MS = 1_200;\nconst CLAWHUB_GROUP_ID = \"__clawhub_skills__\";\n\nexport function normalizeDraft(draft: DraftBinding): DraftBinding {\n return {\n enabledTargets: [...draft.enabledTargets].sort(),\n selectedLeafIds: [...draft.selectedLeafIds].sort(),\n };\n}\n\nexport function draftsEqual(left: DraftBinding, right: DraftBinding): boolean {\n const nextLeft = normalizeDraft(left);\n const nextRight = normalizeDraft(right);\n return JSON.stringify(nextLeft) === JSON.stringify(nextRight);\n}\n\nexport function buildDraftsFromSummaries(\n summaries: WorkflowSummary[],\n): Record<string, DraftBinding> {\n return Object.fromEntries(\n summaries.map((summary) => {\n const enabledTargets = Object.entries(summary.bindings.targets)\n .filter(([, value]) => value?.enabled)\n .map(([target]) => target) as DraftBinding[\"enabledTargets\"];\n const selectedLeafIds = [\n ...new Set(\n (summary.bindings.selectedLeafIds && summary.bindings.selectedLeafIds.length > 0\n ? summary.bindings.selectedLeafIds\n : enabledTargets.flatMap((target) => summary.bindings.targets[target]?.leafIds ?? [])),\n ),\n ];\n return [summary.source.id, normalizeDraft({ enabledTargets, selectedLeafIds })];\n }),\n );\n}\n\nexport function buildConfigGroups(summaries: WorkflowSummary[]): ConfigGroup[] {\n const clawhubSummaries = summaries.filter((summary) => summary.source.kind === \"clawhub\");\n const groups: ConfigGroup[] = [];\n let clawhubGroupInserted = false;\n\n for (const summary of summaries) {\n if (summary.source.kind === \"clawhub\") {\n if (!clawhubGroupInserted && clawhubSummaries.length > 0) {\n groups.push({\n id: CLAWHUB_GROUP_ID,\n title: \"ClawHub Skills\",\n kind: \"clawhub\",\n summaries: clawhubSummaries,\n });\n clawhubGroupInserted = true;\n }\n continue;\n }\n\n groups.push({\n id: summary.source.id,\n title: formatGroupLabel(summary.source),\n kind: \"source\",\n summaries: [summary],\n });\n }\n\n if (!clawhubGroupInserted && clawhubSummaries.length > 0) {\n groups.push({\n id: CLAWHUB_GROUP_ID,\n title: \"ClawHub Skills\",\n kind: \"clawhub\",\n summaries: clawhubSummaries,\n });\n }\n\n return groups;\n}\n\nexport function buildConfigGroupSkillRows(group: ConfigGroup): ConfigSkillRow[] {\n return group.summaries.flatMap((summary) =>\n summary.leafs.map((leaf) => ({\n summary,\n leaf,\n })),\n );\n}\n\nexport function getPaneViewportCount(paneHeight: number, reservedRows = 0) {\n return Math.max(1, paneHeight - PANE_CHROME_ROWS - reservedRows);\n}\n\nexport function getPaneWidths(terminalColumns: number): [number, number] {\n const available = Math.max(56, terminalColumns - 1);\n const left = Math.max(20, Math.min(30, Math.floor(available * 0.28)));\n return [left, Math.max(32, available - left)];\n}\n\nexport function getActionChangeCount(actions: DeploymentAction[]) {\n return actions.filter((action) => action.kind !== \"noop\").length;\n}\n\nexport function getGroupSelectedLeafCount({\n drafts,\n group,\n}: {\n drafts: Record<string, DraftBinding>;\n group: ConfigGroup;\n}) {\n return group.summaries.reduce(\n (count, summary) => count + (drafts[summary.source.id]?.selectedLeafIds.length ?? 0),\n 0,\n );\n}\n\nexport function getStatusDisplay({\n deleteState,\n isSelectedDelete,\n saveState,\n updateState,\n}: {\n deleteState: DeleteState;\n isSelectedDelete: boolean;\n saveState: SaveState;\n updateState: UpdateState;\n}): StatusDisplay {\n if (isSelectedDelete && deleteState.phase === \"deleting\") {\n return { kind: \"deleting\", label: \"Deleting\", color: \"yellow\" };\n }\n if (updateState.phase === \"updating\") {\n return { kind: \"updating\", label: \"Updating\", color: \"cyan\" };\n }\n if (updateState.phase === \"failed\") {\n return { kind: \"update-failed\", label: \"Update Failed\", color: \"red\" };\n }\n if (saveState.phase === \"saving\") {\n return { kind: \"saving\", label: \"Saving\", color: \"cyan\" };\n }\n if (saveState.phase === \"failed\") {\n return { kind: \"failed\", label: \"Failed\", color: \"red\" };\n }\n if (updateState.phase === \"updated\") {\n return { kind: \"updated\", label: \"Updated\", color: \"green\" };\n }\n if (saveState.phase === \"saved\") {\n return { kind: \"saved\", label: \"Saved\", color: \"green\" };\n }\n return { kind: \"clean\", label: \"Clean\", color: \"gray\" };\n}\n\nexport function buildTopBar({\n width,\n isDirty,\n changeCount,\n showDelete,\n statusLabel,\n}: {\n width: number;\n isDirty: boolean;\n changeCount: number;\n showDelete: boolean;\n statusLabel: string;\n}): TopBarDisplay {\n const topBar: TopBarDisplay = {\n title: \"Skill Flow\",\n titleColor: \"blue\",\n };\n if (changeCount > 0) {\n topBar.detail = `Changes: ${changeCount}`;\n return topBar;\n }\n if (\n statusLabel === \"Saving\" ||\n statusLabel === \"Updating\" ||\n statusLabel === \"Deleting\" ||\n statusLabel === \"Failed\" ||\n statusLabel === \"Update Failed\"\n ) {\n topBar.detail = `Status: ${statusLabel}`;\n topBar.detailColor =\n statusLabel === \"Deleting\"\n ? \"yellow\"\n : statusLabel === \"Saving\" || statusLabel === \"Updating\"\n ? \"cyan\"\n : \"red\";\n }\n return topBar;\n}\n\nexport function prioritizeAlerts(alerts: AlertItem[]): AlertItem[] {\n const seen = new Set<string>();\n const priority: Record<AlertLevel, number> = {\n error: 0,\n blocked: 1,\n warning: 2,\n };\n return alerts\n .filter((alert) => {\n const key = `${alert.level}:${alert.message}`;\n if (seen.has(key)) {\n return false;\n }\n seen.add(key);\n return true;\n })\n .sort((left, right) => priority[left.level] - priority[right.level])\n .slice(0, 2);\n}\n\nexport function getInitialDetailFocus({\n hasAgents,\n hasSkills,\n}: {\n hasAgents: boolean;\n hasSkills: boolean;\n}): DetailFocus {\n if (hasAgents) {\n return \"detail.agents\";\n }\n if (hasSkills) {\n return \"detail.skills\";\n }\n return \"detail.actions\";\n}\n\nexport function moveDetailFocus({\n actionCursor,\n actionCount,\n agentCount,\n agentCursor,\n direction,\n focus,\n skillCount,\n skillCursor,\n}: {\n actionCursor: number;\n actionCount: number;\n agentCount: number;\n agentCursor: number;\n direction: -1 | 1;\n focus: DetailFocus;\n skillCount: number;\n skillCursor: number;\n}): {\n focus: DetailFocus;\n agentCursor: number;\n skillCursor: number;\n actionCursor: number;\n} {\n if (focus === \"detail.agents\") {\n if (direction === -1) {\n if (agentCount > 0 && agentCursor > 0) {\n return { focus, agentCursor: agentCursor - 1, skillCursor, actionCursor };\n }\n return { focus, agentCursor, skillCursor, actionCursor };\n }\n\n if (agentCount > 0 && agentCursor < agentCount - 1) {\n return { focus, agentCursor: agentCursor + 1, skillCursor, actionCursor };\n }\n if (skillCount > 0) {\n return { focus: \"detail.skills\", agentCursor, skillCursor: 0, actionCursor };\n }\n return {\n focus: \"detail.actions\",\n agentCursor,\n skillCursor,\n actionCursor: Math.min(actionCursor, Math.max(0, actionCount - 1)),\n };\n }\n\n if (focus === \"detail.skills\") {\n if (direction === -1) {\n if (skillCount > 0 && skillCursor > 0) {\n return { focus, agentCursor, skillCursor: skillCursor - 1, actionCursor };\n }\n if (agentCount > 0) {\n return {\n focus: \"detail.agents\",\n agentCursor: Math.max(0, agentCount - 1),\n skillCursor,\n actionCursor,\n };\n }\n return { focus, agentCursor, skillCursor, actionCursor };\n }\n\n if (skillCount > 0 && skillCursor < skillCount - 1) {\n return { focus, agentCursor, skillCursor: skillCursor + 1, actionCursor };\n }\n return {\n focus: \"detail.actions\",\n agentCursor,\n skillCursor,\n actionCursor: Math.min(actionCursor, Math.max(0, actionCount - 1)),\n };\n }\n\n if (direction === 1) {\n if (actionCursor < actionCount - 1) {\n return { focus, agentCursor, skillCursor, actionCursor: actionCursor + 1 };\n }\n return { focus, agentCursor, skillCursor, actionCursor };\n }\n\n if (actionCursor > 0) {\n return { focus, agentCursor, skillCursor, actionCursor: actionCursor - 1 };\n }\n if (skillCount > 0) {\n return {\n focus: \"detail.skills\",\n agentCursor,\n skillCursor: Math.max(0, skillCount - 1),\n actionCursor,\n };\n }\n if (agentCount > 0) {\n return {\n focus: \"detail.agents\",\n agentCursor: Math.max(0, agentCount - 1),\n skillCursor,\n actionCursor,\n };\n }\n return { focus, agentCursor, skillCursor, actionCursor };\n}\n\nexport function getNextSelectionIndexAfterDelete(currentIndex: number, nextCount: number) {\n if (nextCount <= 0) {\n return -1;\n }\n return Math.min(currentIndex, nextCount - 1);\n}\n\nexport function captureFocusSnapshot({\n actionCursor,\n agentCursor,\n availableTargets,\n focus,\n groupId,\n selectedGroupIndex,\n selectedSummary,\n skillCursor,\n}: {\n actionCursor: number;\n agentCursor: number;\n availableTargets: DeploymentTargetId[];\n focus: FocusPane;\n groupId: string;\n selectedGroupIndex: number;\n selectedSummary: WorkflowSummary | undefined;\n skillCursor: number;\n}): FocusSnapshot {\n return {\n focus,\n groupIndex: selectedGroupIndex,\n groupId,\n sourceId: selectedSummary?.source.id,\n agentTarget: agentCursor > 0 ? availableTargets[agentCursor - 1] : undefined,\n skillId:\n selectedSummary && skillCursor > 0\n ? selectedSummary.leafs[skillCursor - 1]?.id\n : undefined,\n action: actionCursor === 1 ? \"delete\" : \"update\",\n };\n}\n\nexport function reconcileFocusAfterReload({\n availableTargets,\n nextGroups,\n snapshot,\n}: {\n availableTargets: DeploymentTargetId[];\n nextGroups: ConfigGroup[];\n snapshot: FocusSnapshot;\n}) {\n const selectedGroupIndex = nextGroups.findIndex((group) => group.id === snapshot.groupId);\n const fallbackGroupIndex = Math.min(\n snapshot.groupIndex,\n Math.max(0, nextGroups.length - 1),\n );\n const resolvedGroupIndex =\n nextGroups.length === 0\n ? -1\n : selectedGroupIndex >= 0 && nextGroups[selectedGroupIndex]\n ? selectedGroupIndex\n : fallbackGroupIndex;\n\n const group = resolvedGroupIndex >= 0 ? nextGroups[resolvedGroupIndex] : undefined;\n const skillRows = group ? buildConfigGroupSkillRows(group) : [];\n const hasAgents = availableTargets.length > 0;\n const hasSkills = skillRows.length > 0;\n\n let focus = snapshot.focus;\n let agentCursor = 0;\n let skillCursor = 0;\n let actionCursor = snapshot.action === \"delete\" && group?.kind !== \"clawhub\" ? 1 : 0;\n\n if (focus === \"detail.agents\") {\n if (hasAgents) {\n const nextAgentIndex = snapshot.agentTarget\n ? availableTargets.indexOf(snapshot.agentTarget)\n : -1;\n agentCursor = nextAgentIndex >= 0 ? nextAgentIndex + 1 : 0;\n } else {\n focus = getInitialDetailFocus({ hasAgents, hasSkills });\n }\n }\n\n if (focus === \"detail.skills\") {\n if (hasSkills) {\n const nextSkillIndex =\n snapshot.sourceId && snapshot.skillId\n ? skillRows.findIndex(\n (row) =>\n row.summary.source.id === snapshot.sourceId && row.leaf.id === snapshot.skillId,\n )\n : -1;\n skillCursor = nextSkillIndex >= 0 ? nextSkillIndex + 1 : 0;\n } else {\n focus = getInitialDetailFocus({ hasAgents, hasSkills });\n }\n }\n\n if (focus === \"detail.actions\") {\n focus = \"detail.actions\";\n }\n\n return {\n actionCursor,\n agentCursor,\n focus: resolvedGroupIndex >= 0 ? focus : \"groups\",\n groupCursor: resolvedGroupIndex,\n selectedGroupIndex: resolvedGroupIndex,\n skillCursor,\n };\n}\n\nexport function getRequestedAction({\n actionCursor,\n canDelete,\n focus,\n input,\n keyReturn,\n}: {\n actionCursor: number;\n canDelete: boolean;\n focus: FocusPane;\n input: string;\n keyReturn: boolean;\n}): ActionName | undefined {\n if (input === \"u\") {\n return \"update\";\n }\n if (input === \"d\" && canDelete) {\n return \"delete\";\n }\n if (focus === \"detail.actions\" && keyReturn) {\n return actionCursor === 1 && canDelete ? \"delete\" : \"update\";\n }\n return undefined;\n}\n\nexport function buildProjectionWarningMap({\n drafts,\n summaries,\n sourceId,\n}: {\n drafts: Record<string, DraftBinding>;\n summaries: WorkflowSummary[];\n sourceId: string;\n}): ProjectionWarningMap {\n const currentDraft = drafts[sourceId] ?? EMPTY_DRAFT;\n const currentSummary = summaries.find((summary) => summary.source.id === sourceId);\n if (!currentSummary || currentDraft.enabledTargets.length === 0) {\n return {};\n }\n\n const currentSelectedLeafIds = new Set(currentDraft.selectedLeafIds);\n const currentEnabledTargets = new Set(currentDraft.enabledTargets);\n const otherSelectedLeafs = summaries.flatMap((summary) => {\n if (summary.source.id === sourceId) {\n return [];\n }\n\n const otherDraft = drafts[summary.source.id] ?? EMPTY_DRAFT;\n const hasTargetOverlap = otherDraft.enabledTargets.some((target) =>\n currentEnabledTargets.has(target),\n );\n if (!hasTargetOverlap) {\n return [];\n }\n\n return otherDraft.selectedLeafIds\n .map((leafId) => summary.leafs.find((leaf) => leaf.id === leafId))\n .filter((leaf): leaf is WorkflowSummary[\"leafs\"][number] => Boolean(leaf))\n .map((leaf) => ({\n source: summary.source,\n leaf,\n exactKey: getExactDuplicateKey(leaf.linkName, leaf.name, leaf.description),\n }));\n });\n const projectedNames = resolveProjectedSkillNames([\n ...otherSelectedLeafs.map((candidate) => ({\n leafId: candidate.leaf.id,\n groupId: candidate.source.id,\n groupName: candidate.source.displayName,\n groupAuthor: getHostedGitOwner(candidate.source.locator),\n skillName: candidate.leaf.linkName,\n })),\n ...currentSummary.leafs\n .filter((leaf) => currentSelectedLeafIds.has(leaf.id))\n .map((leaf) => ({\n leafId: leaf.id,\n groupId: currentSummary.source.id,\n groupName: currentSummary.source.displayName,\n groupAuthor: getHostedGitOwner(currentSummary.source.locator),\n skillName: leaf.linkName,\n })),\n ]);\n\n const warningsByLeafId: ProjectionWarningMap = {};\n for (const leaf of currentSummary.leafs) {\n if (!currentSelectedLeafIds.has(leaf.id)) {\n continue;\n }\n\n const exactKey = getExactDuplicateKey(leaf.linkName, leaf.name, leaf.description);\n const exactDuplicate = otherSelectedLeafs.find((candidate) => candidate.exactKey === exactKey);\n if (exactDuplicate) {\n warningsByLeafId[leaf.id] = [\n `identical skill already selected in ${formatGroupLabel(exactDuplicate.source)}, this one will be skipped`,\n ];\n continue;\n }\n\n const renameConflict = otherSelectedLeafs.find(\n (candidate) => candidate.leaf.linkName === leaf.linkName,\n );\n if (renameConflict) {\n const projectedName =\n projectedNames.get(leaf.id) ??\n buildProjectedSkillName(\n currentSummary.source.displayName,\n leaf.linkName,\n getHostedGitOwner(currentSummary.source.locator),\n );\n warningsByLeafId[leaf.id] = [\n `conflicts with ${formatGroupLabel(renameConflict.source)}, will deploy as ${projectedName}`,\n ];\n }\n }\n\n return warningsByLeafId;\n}\n\nfunction buildProjectionNameMap({\n drafts,\n summaries,\n sourceId,\n}: {\n drafts: Record<string, DraftBinding>;\n summaries: WorkflowSummary[];\n sourceId: string;\n}): ProjectionNameMap {\n const currentDraft = drafts[sourceId] ?? EMPTY_DRAFT;\n const currentSummary = summaries.find((summary) => summary.source.id === sourceId);\n if (!currentSummary || currentDraft.enabledTargets.length === 0) {\n return new Map();\n }\n\n const currentEnabledTargets = new Set(currentDraft.enabledTargets);\n const selectedLeafIds = new Set(currentDraft.selectedLeafIds);\n\n return resolveProjectedSkillNames([\n ...summaries.flatMap((summary) => {\n if (summary.source.id === sourceId) {\n return [];\n }\n\n const draft = drafts[summary.source.id] ?? EMPTY_DRAFT;\n const hasTargetOverlap = draft.enabledTargets.some((target) =>\n currentEnabledTargets.has(target),\n );\n if (!hasTargetOverlap) {\n return [];\n }\n\n return draft.selectedLeafIds\n .map((leafId) => summary.leafs.find((leaf) => leaf.id === leafId))\n .filter((leaf): leaf is WorkflowSummary[\"leafs\"][number] => Boolean(leaf))\n .map((leaf) => ({\n leafId: leaf.id,\n groupId: summary.source.id,\n groupName: summary.source.displayName,\n groupAuthor: getHostedGitOwner(summary.source.locator),\n skillName: leaf.linkName,\n }));\n }),\n ...currentSummary.leafs\n .filter((leaf) => selectedLeafIds.has(leaf.id))\n .map((leaf) => ({\n leafId: leaf.id,\n groupId: currentSummary.source.id,\n groupName: currentSummary.source.displayName,\n groupAuthor: getHostedGitOwner(currentSummary.source.locator),\n skillName: leaf.linkName,\n })),\n ]);\n}\n\nexport function buildScrollableRows<T extends PaneRow>(\n items: T[],\n cursorIndex: number,\n visibleCount: number,\n keyPrefix = \"scroll\",\n reserveHintSlots = false,\n): WindowedRows<T | PaneRow> {\n const safeVisibleCount = Math.max(1, visibleCount);\n const needsHints = items.length > safeVisibleCount;\n const hasHintSlots = needsHints || (reserveHintSlots && safeVisibleCount >= 3);\n const adjustedVisibleCount = hasHintSlots ? Math.max(1, safeVisibleCount - 2) : safeVisibleCount;\n const windowed = getWindowedRows(items, cursorIndex, adjustedVisibleCount);\n const hasUp = windowed.start > 0;\n const hasDown = windowed.end < items.length;\n\n const rows: Array<T | PaneRow> = [];\n if (hasHintSlots) {\n rows.push({\n key: `__scroll_up__:${keyPrefix}`,\n text: hasUp ? \"\u2191 more\" : \"\",\n active: false,\n color: \"gray\",\n });\n }\n rows.push(...windowed.rows);\n if (hasHintSlots) {\n rows.push({\n key: `__scroll_down__:${keyPrefix}`,\n text: hasDown ? \"\u2193 more\" : \"\",\n active: false,\n color: \"gray\",\n });\n }\n\n return {\n rows,\n start: windowed.start,\n end: windowed.end,\n };\n}\n\nexport function ConfigApp({\n app,\n availableTargets,\n summaries,\n initialDrafts,\n bootStatus,\n}: ConfigAppProps) {\n const { exit } = useApp();\n const { stdout } = useStdout();\n const terminalSize = useTerminalSize(stdout);\n const previewRequestIds = useRef<Record<string, number>>({});\n const saveRequestIds = useRef<Record<string, number>>({});\n const updateRequestIds = useRef<Record<string, number>>({});\n const updatedTimers = useRef<Record<string, NodeJS.Timeout | undefined>>({});\n const [summaryList, setSummaryList] = useState(summaries);\n const groupViews = buildConfigGroups(summaryList);\n const [selectedGroupIndex, setSelectedGroupIndex] = useState(\n groupViews.length > 0 ? 0 : -1,\n );\n const [groupCursor, setGroupCursor] = useState(groupViews.length > 0 ? 0 : -1);\n const [focus, setFocus] = useState<FocusPane>(\"groups\");\n const [skillCursor, setSkillCursor] = useState(0);\n const [targetCursor, setTargetCursor] = useState(0);\n const [actionCursor, setActionCursor] = useState(0);\n const [drafts, setDrafts] = useState<Record<string, DraftBinding>>(initialDrafts);\n const [savedDrafts, setSavedDrafts] = useState<Record<string, DraftBinding>>(initialDrafts);\n const [previewBySourceId, setPreviewBySourceId] = useState<Record<string, PreviewState>>({});\n const [saveStateBySourceId, setSaveStateBySourceId] = useState<Record<string, SaveState>>({});\n const [updateStateBySourceId, setUpdateStateBySourceId] = useState<\n Record<string, UpdateState>\n >({});\n const [deleteState, setDeleteState] = useState<DeleteState>({\n phase: \"idle\",\n sourceId: undefined,\n message: undefined,\n });\n\n const selectedGroup = groupViews[selectedGroupIndex] ?? EMPTY_CONFIG_GROUP;\n const selectedSkillRows = buildConfigGroupSkillRows(selectedGroup);\n const selectedSkillRow = skillCursor > 0 ? selectedSkillRows[skillCursor - 1] : undefined;\n const activeSummary = selectedSkillRow?.summary ?? selectedGroup.summaries[0];\n const selectedSourceId = activeSummary?.source.id ?? \"\";\n const selectedDraft = drafts[selectedSourceId] ?? EMPTY_DRAFT;\n const savedDraft = savedDrafts[selectedSourceId] ?? EMPTY_DRAFT;\n const isDirty = !draftsEqual(selectedDraft, savedDraft);\n const leafIds = activeSummary?.leafs.map((leaf) => leaf.id) ?? [];\n const groupSelectedLeafCount = getGroupSelectedLeafCount({\n drafts,\n group: selectedGroup,\n });\n const visibleTargets = availableTargets;\n const agentInteractiveCount = visibleTargets.length > 0 ? visibleTargets.length + 1 : 0;\n const skillInteractiveCount = selectedSkillRows.length > 0 ? selectedSkillRows.length + 1 : 0;\n const treeState: TreeSelectionState =\n selectedGroup.kind === \"clawhub\"\n ? {\n allLeafIds: selectedSkillRows.map((row) => row.leaf.id),\n selectedLeafIds: selectedGroup.summaries.flatMap(\n (summary) => drafts[summary.source.id]?.selectedLeafIds ?? [],\n ),\n }\n : {\n allLeafIds: leafIds,\n selectedLeafIds: selectedDraft.selectedLeafIds,\n };\n const parentSelectionState = getParentSelectionState(treeState);\n const visibleEnabledTargets = visibleTargets.filter((target) =>\n selectedDraft.enabledTargets.includes(target),\n );\n const allTargetsSelected =\n visibleTargets.length > 0 && visibleEnabledTargets.length === visibleTargets.length;\n const projectionWarningsByLeafId = buildProjectionWarningMap({\n drafts,\n summaries: summaryList,\n sourceId: selectedSourceId,\n });\n const projectedNamesByLeafId = buildProjectionNameMap({\n drafts,\n summaries: summaryList,\n sourceId: selectedSourceId,\n });\n const failedBootBySourceId = new Map(\n bootStatus.failedSources.map((item) => [item.sourceId, item.message]),\n );\n const previewState = previewBySourceId[selectedSourceId] ?? EMPTY_PREVIEW;\n const changeCount = getActionChangeCount(previewState.actions);\n const saveState = saveStateBySourceId[selectedSourceId] ?? {\n phase: \"idle\" as const,\n message: undefined,\n };\n const updateState = updateStateBySourceId[selectedSourceId] ?? {\n phase: \"idle\" as const,\n message: undefined,\n };\n const isSelectedDelete = deleteState.sourceId === selectedSourceId;\n const canDelete =\n selectedGroup.kind === \"clawhub\" ? focus === \"detail.skills\" && skillCursor > 0 : true;\n const showDeleteAction = selectedGroup.kind !== \"clawhub\";\n const actionCount = showDeleteAction ? 2 : 1;\n const statusDisplay = getStatusDisplay({\n deleteState,\n isSelectedDelete,\n saveState,\n updateState,\n });\n const canEditSelected =\n activeSummary !== undefined &&\n updateState.phase !== \"updating\" &&\n deleteState.phase !== \"deleting\";\n const canRunActions =\n activeSummary !== undefined &&\n saveState.phase !== \"saving\" &&\n updateState.phase !== \"updating\" &&\n deleteState.phase !== \"deleting\";\n\n useEffect(() => {\n return () => {\n for (const timer of Object.values(updatedTimers.current)) {\n if (timer) {\n clearTimeout(timer);\n }\n }\n };\n }, []);\n\n useEffect(() => {\n if (!activeSummary) {\n return;\n }\n\n const sourceId = activeSummary.source.id;\n const requestId = (previewRequestIds.current[sourceId] ?? 0) + 1;\n previewRequestIds.current[sourceId] = requestId;\n\n setPreviewBySourceId((current) => ({\n ...current,\n [sourceId]: {\n ...(current[sourceId] ?? EMPTY_PREVIEW),\n errorMessage: undefined,\n loading: true,\n requestId,\n },\n }));\n\n let disposed = false;\n\n void app.previewDraft(sourceId, selectedDraft).then((result) => {\n if (disposed) {\n return;\n }\n\n setPreviewBySourceId((current) => {\n const currentState = current[sourceId] ?? EMPTY_PREVIEW;\n if (currentState.requestId !== requestId) {\n return current;\n }\n\n if (!result.ok) {\n return {\n ...current,\n [sourceId]: {\n actions: [],\n blockedCount: 0,\n errorMessage: firstErrorMessage(result),\n loading: false,\n requestId,\n },\n };\n }\n\n return {\n ...current,\n [sourceId]: {\n actions: result.data.plan.actions,\n blockedCount: result.data.plan.blocked.length,\n errorMessage: undefined,\n loading: false,\n requestId,\n },\n };\n });\n });\n\n return () => {\n disposed = true;\n };\n }, [app, activeSummary, selectedDraft]);\n\n useEffect(() => {\n if (!activeSummary || draftsEqual(selectedDraft, savedDraft)) {\n return;\n }\n if (saveState.phase === \"saving\" || saveState.phase === \"failed\") {\n return;\n }\n\n const sourceId = activeSummary.source.id;\n const requestId = (saveRequestIds.current[sourceId] ?? 0) + 1;\n saveRequestIds.current[sourceId] = requestId;\n const draftToSave = normalizeDraft(selectedDraft);\n\n setSaveStateBySourceId((current) => ({\n ...current,\n [sourceId]: {\n phase: \"saving\",\n message: \"saving changes...\",\n },\n }));\n\n void app.applyDraft(sourceId, draftToSave).then((result) => {\n setSaveStateBySourceId((current) => {\n if ((saveRequestIds.current[sourceId] ?? 0) !== requestId) {\n return current;\n }\n\n if (!result.ok) {\n return {\n ...current,\n [sourceId]: {\n phase: \"failed\",\n message: firstErrorMessage(result),\n },\n };\n }\n\n const appliedDraft = normalizeDraft(result.data.draft);\n setDrafts((draftsCurrent) => ({\n ...draftsCurrent,\n [sourceId]: appliedDraft,\n }));\n setSavedDrafts((savedCurrent) => ({\n ...savedCurrent,\n [sourceId]: appliedDraft,\n }));\n setPreviewBySourceId((previewCurrent) => ({\n ...previewCurrent,\n [sourceId]: {\n actions: result.data.actions,\n blockedCount: result.data.actions.filter((action) => action.kind === \"blocked\")\n .length,\n errorMessage: undefined,\n loading: false,\n requestId: previewRequestIds.current[sourceId] ?? 0,\n },\n }));\n\n return {\n ...current,\n [sourceId]: {\n phase: \"saved\",\n message: \"saved\",\n },\n };\n });\n });\n }, [app, saveState.phase, savedDraft, selectedDraft, activeSummary]);\n\n const updateSelectedDraft = (\n updater: (currentDraft: DraftBinding) => DraftBinding,\n ) => {\n if (!activeSummary || !canEditSelected) {\n return;\n }\n\n const sourceId = activeSummary.source.id;\n setDrafts((current) => {\n const currentDraft = current[sourceId] ?? EMPTY_DRAFT;\n const nextDraft = normalizeDraft(updater(currentDraft));\n if (draftsEqual(currentDraft, nextDraft)) {\n return current;\n }\n return {\n ...current,\n [sourceId]: nextDraft,\n };\n });\n setSaveStateBySourceId((current) => {\n const state = current[sourceId];\n if (!state || state.phase === \"idle\") {\n return current;\n }\n return {\n ...current,\n [sourceId]: {\n phase: \"idle\",\n message: undefined,\n },\n };\n });\n };\n\n const handleUpdate = () => {\n if (!activeSummary || !selectedGroup || !canRunActions) {\n return;\n }\n\n const sourceId = activeSummary.source.id;\n const sourceIds =\n selectedGroup.kind === \"clawhub\"\n ? selectedGroup.summaries.map((summary) => summary.source.id)\n : [sourceId];\n const requestId = (updateRequestIds.current[sourceId] ?? 0) + 1;\n updateRequestIds.current[sourceId] = requestId;\n for (const id of sourceIds) {\n previewRequestIds.current[id] = (previewRequestIds.current[id] ?? 0) + 1;\n saveRequestIds.current[id] = (saveRequestIds.current[id] ?? 0) + 1;\n }\n\n if (updatedTimers.current[sourceId]) {\n clearTimeout(updatedTimers.current[sourceId]);\n updatedTimers.current[sourceId] = undefined;\n }\n\n const snapshot = captureFocusSnapshot({\n actionCursor,\n agentCursor: targetCursor,\n availableTargets,\n focus,\n groupId: selectedGroup.id,\n selectedGroupIndex,\n selectedSummary: activeSummary,\n skillCursor,\n });\n\n setUpdateStateBySourceId((current) => ({\n ...current,\n [sourceId]: {\n phase: \"updating\",\n message: `updating ${selectedGroup.title}...`,\n },\n }));\n\n void app.updateSources(sourceIds).then(async (result) => {\n if ((updateRequestIds.current[sourceId] ?? 0) !== requestId) {\n return;\n }\n\n if (!result.ok) {\n setUpdateStateBySourceId((current) => ({\n ...current,\n [sourceId]: {\n phase: \"failed\",\n message: firstErrorMessage(result),\n },\n }));\n return;\n }\n\n const configResult = await app.getConfigData();\n if ((updateRequestIds.current[sourceId] ?? 0) !== requestId) {\n return;\n }\n if (!configResult.ok) {\n setUpdateStateBySourceId((current) => ({\n ...current,\n [sourceId]: {\n phase: \"failed\",\n message: firstErrorMessage(configResult),\n },\n }));\n return;\n }\n\n const nextSummaries = configResult.data.summaries;\n const nextDrafts = buildDraftsFromSummaries(nextSummaries);\n const nextIds = new Set(nextSummaries.map((summary) => summary.source.id));\n const nextGroups = buildConfigGroups(nextSummaries);\n const nextFocusState = reconcileFocusAfterReload({\n availableTargets,\n nextGroups,\n snapshot,\n });\n\n setSummaryList(nextSummaries);\n setDrafts(nextDrafts);\n setSavedDrafts(nextDrafts);\n setPreviewBySourceId((current) => pruneSourceMap(current, nextIds));\n setSaveStateBySourceId((current) => ({\n ...pruneSourceMap(current, nextIds),\n [sourceId]: {\n phase: \"saved\",\n message: \"saved\",\n },\n }));\n setSelectedGroupIndex(nextFocusState.selectedGroupIndex);\n setGroupCursor(nextFocusState.groupCursor);\n setFocus(nextFocusState.focus);\n setTargetCursor(nextFocusState.agentCursor);\n setSkillCursor(nextFocusState.skillCursor);\n setActionCursor(nextFocusState.actionCursor);\n setUpdateStateBySourceId((current) => ({\n ...pruneSourceMap(current, nextIds),\n [sourceId]: {\n phase: \"updated\",\n message: \"updated\",\n },\n }));\n\n updatedTimers.current[sourceId] = setTimeout(() => {\n if ((updateRequestIds.current[sourceId] ?? 0) !== requestId) {\n return;\n }\n setUpdateStateBySourceId((current) => {\n const state = current[sourceId];\n if (!state || state.phase !== \"updated\") {\n return current;\n }\n return {\n ...current,\n [sourceId]: {\n phase: \"idle\",\n message: undefined,\n },\n };\n });\n updatedTimers.current[sourceId] = undefined;\n }, UPDATED_FEEDBACK_MS);\n });\n };\n\n const handleDelete = () => {\n if (!activeSummary || !canRunActions) {\n return;\n }\n\n const sourceId = activeSummary.source.id;\n previewRequestIds.current[sourceId] = (previewRequestIds.current[sourceId] ?? 0) + 1;\n saveRequestIds.current[sourceId] = (saveRequestIds.current[sourceId] ?? 0) + 1;\n updateRequestIds.current[sourceId] = (updateRequestIds.current[sourceId] ?? 0) + 1;\n\n if (updatedTimers.current[sourceId]) {\n clearTimeout(updatedTimers.current[sourceId]);\n updatedTimers.current[sourceId] = undefined;\n }\n\n setDeleteState({\n phase: \"deleting\",\n sourceId,\n message: `deleting ${formatGroupLabel(activeSummary.source)}...`,\n });\n\n void app.uninstall([sourceId]).then((result) => {\n if (!result.ok) {\n setDeleteState({\n phase: \"failed\",\n sourceId,\n message: firstErrorMessage(result),\n });\n return;\n }\n\n const nextSummaries = summaryList.filter((summary) => summary.source.id !== sourceId);\n const nextGroups = buildConfigGroups(nextSummaries);\n const nextSelectedGroupIndex = getNextSelectionIndexAfterDelete(\n selectedGroupIndex,\n nextGroups.length,\n );\n\n setSummaryList(nextSummaries);\n setDrafts((current) => removeSourceFromMap(current, sourceId));\n setSavedDrafts((current) => removeSourceFromMap(current, sourceId));\n setPreviewBySourceId((current) => removeSourceFromMap(current, sourceId));\n setSaveStateBySourceId((current) => removeSourceFromMap(current, sourceId));\n setUpdateStateBySourceId((current) => removeSourceFromMap(current, sourceId));\n setDeleteState({\n phase: \"idle\",\n sourceId: undefined,\n message: undefined,\n });\n setSelectedGroupIndex(nextSelectedGroupIndex);\n setGroupCursor(nextSelectedGroupIndex);\n setFocus(\"groups\");\n setTargetCursor(0);\n setSkillCursor(0);\n setActionCursor(0);\n });\n };\n\n useInput((input, key) => {\n if (!activeSummary) {\n if (input === \"q\" || key.escape || (input === \"c\" && key.ctrl)) {\n exit();\n }\n return;\n }\n\n if (input === \"c\" && key.ctrl) {\n exit();\n return;\n }\n\n const requestedAction = getRequestedAction({\n actionCursor,\n canDelete,\n focus,\n input,\n keyReturn: Boolean(key.return),\n });\n if (requestedAction === \"update\") {\n handleUpdate();\n return;\n }\n if (requestedAction === \"delete\") {\n handleDelete();\n return;\n }\n\n if (input === \"q\" || key.escape) {\n if (focus !== \"groups\") {\n setFocus(\"groups\");\n return;\n }\n exit();\n return;\n }\n\n if (key.tab) {\n if (focus === \"groups\") {\n setFocus(\n getInitialDetailFocus({\n hasAgents: agentInteractiveCount > 0,\n hasSkills: skillInteractiveCount > 0,\n }),\n );\n return;\n }\n setFocus(\"groups\");\n return;\n }\n\n if (key.rightArrow && focus === \"groups\") {\n setFocus(\n getInitialDetailFocus({\n hasAgents: agentInteractiveCount > 0,\n hasSkills: skillInteractiveCount > 0,\n }),\n );\n return;\n }\n\n if (key.leftArrow && focus !== \"groups\") {\n setFocus(\"groups\");\n return;\n }\n\n if (focus === \"groups\") {\n if (key.downArrow) {\n const next = Math.min(groupCursor + 1, Math.max(0, groupViews.length - 1));\n setGroupCursor(next);\n setSelectedGroupIndex(next);\n setTargetCursor(0);\n setSkillCursor(0);\n setActionCursor(0);\n }\n if (key.upArrow) {\n const next = Math.max(groupCursor - 1, 0);\n setGroupCursor(next);\n setSelectedGroupIndex(next);\n setTargetCursor(0);\n setSkillCursor(0);\n setActionCursor(0);\n }\n return;\n }\n\n if (key.downArrow || key.upArrow) {\n const next = moveDetailFocus({\n actionCursor,\n actionCount,\n agentCount: agentInteractiveCount,\n agentCursor: targetCursor,\n direction: key.downArrow ? 1 : -1,\n focus: focus as DetailFocus,\n skillCount: skillInteractiveCount,\n skillCursor,\n });\n setFocus(next.focus);\n setTargetCursor(next.agentCursor);\n setSkillCursor(next.skillCursor);\n setActionCursor(next.actionCursor);\n return;\n }\n\n if (focus === \"detail.agents\" && input === \" \" && agentInteractiveCount > 0) {\n updateSelectedDraft((currentDraft) => {\n if (targetCursor === 0) {\n const enabledTargets = new Set(currentDraft.enabledTargets);\n const nextSelectAll = !visibleTargets.every((target) => enabledTargets.has(target));\n for (const target of visibleTargets) {\n if (nextSelectAll) {\n enabledTargets.add(target);\n } else {\n enabledTargets.delete(target);\n }\n }\n return {\n ...currentDraft,\n enabledTargets: availableTargets.filter((target) => enabledTargets.has(target)),\n };\n }\n\n const target = visibleTargets[targetCursor - 1];\n if (!target) {\n return currentDraft;\n }\n\n const enabledTargets = new Set(currentDraft.enabledTargets);\n if (enabledTargets.has(target)) {\n enabledTargets.delete(target);\n } else {\n enabledTargets.add(target);\n }\n return {\n ...currentDraft,\n enabledTargets: availableTargets.filter((item) => enabledTargets.has(item)),\n };\n });\n return;\n }\n\n if (focus === \"detail.skills\" && input === \" \" && skillInteractiveCount > 0) {\n updateSelectedDraft((currentDraft) => {\n if (selectedGroup.kind === \"clawhub\") {\n if (skillCursor === 0) {\n return currentDraft;\n }\n\n const row = selectedSkillRows[skillCursor - 1];\n if (!row) {\n return currentDraft;\n }\n\n if (row.summary.source.id !== selectedSourceId) {\n return currentDraft;\n }\n\n const baseState: TreeSelectionState = {\n allLeafIds: row.summary.leafs.map((leaf) => leaf.id),\n selectedLeafIds: currentDraft.selectedLeafIds,\n };\n const nextState = toggleChild(baseState, row.leaf.id);\n\n return {\n ...currentDraft,\n selectedLeafIds: nextState.selectedLeafIds,\n };\n }\n\n const baseState: TreeSelectionState = {\n allLeafIds: leafIds,\n selectedLeafIds: currentDraft.selectedLeafIds,\n };\n const nextState =\n skillCursor === 0\n ? toggleParent(baseState)\n : toggleChild(baseState, leafIds[skillCursor - 1]!);\n\n return {\n ...currentDraft,\n selectedLeafIds: nextState.selectedLeafIds,\n };\n });\n }\n });\n\n if (groupViews.length === 0) {\n return (\n <Box flexDirection=\"column\">\n <Text bold>No skills groups yet</Text>\n <Text>Run skill-flow add &lt;source&gt; to install your first group.</Text>\n <Text dimColor>{deleteState.message ?? \"Press q or esc to exit.\"}</Text>\n </Box>\n );\n }\n\n const renderSummary = activeSummary!;\n\n const terminalRows = terminalSize.rows;\n const terminalColumns = terminalSize.columns;\n const paneHeight = Math.max(12, terminalRows - 3);\n const [groupsWidth, detailWidth] = getPaneWidths(terminalColumns);\n const bodyRowCount = getPaneViewportCount(paneHeight);\n const groupRows = buildScrollableRows(\n groupViews.map((group, index) => {\n const isCursor = groupCursor === index;\n const isSelected = selectedGroupIndex === index;\n return {\n key: group.id,\n text: `${group.title}${\n group.kind === \"clawhub\"\n ? group.summaries.some((summary) => failedBootBySourceId.has(summary.source.id))\n ? \" !\"\n : \"\"\n : failedBootBySourceId.has(group.summaries[0]?.source.id ?? \"\")\n ? \" !\"\n : \"\"\n }`,\n active: focus === \"groups\" && isCursor,\n activeColor: \"cyan\" as const,\n bold: isSelected,\n color: isSelected ? (\"white\" as const) : (\"gray\" as const),\n };\n }),\n Math.max(0, groupCursor),\n bodyRowCount,\n \"groups\",\n );\n\n const agentRows: PaneRow[] =\n visibleTargets.length > 0\n ? [\n {\n key: \"__all_targets__\",\n text: `${selectionMarker(\n allTargetsSelected ? \"full\" : visibleEnabledTargets.length > 0 ? \"partial\" : \"empty\",\n )} All Agents`,\n active: focus === \"detail.agents\" && targetCursor === 0,\n bold: true,\n color: undefined,\n },\n ...visibleTargets.map((target, index) => ({\n key: target,\n text: `${selectionMarker(\n selectedDraft.enabledTargets.includes(target) ? \"full\" : \"empty\",\n )} ${formatTargetName(target)}`,\n active: focus === \"detail.agents\" && targetCursor === index + 1,\n color: \"gray\" as const,\n })),\n ]\n : [\n {\n key: \"__no_targets__\",\n text: \"No detected agent targets\",\n active: false,\n color: \"gray\" as const,\n },\n ];\n\n const skillRows: PaneRow[] =\n selectedSkillRows.length > 0\n ? [\n {\n key: \"__all__\",\n text: `${selectionMarker(parentSelectionState)} All Skills`,\n active: focus === \"detail.skills\" && skillCursor === 0,\n bold: true,\n color: undefined,\n },\n ...selectedSkillRows.map((row, index) => {\n const rowDraft = drafts[row.summary.source.id] ?? EMPTY_DRAFT;\n const rowSelected = rowDraft.selectedLeafIds.includes(row.leaf.id);\n const warnings = [\n ...row.leaf.metadataWarnings,\n ...(row.summary.source.id === selectedSourceId\n ? (projectionWarningsByLeafId[row.leaf.id] ?? [])\n : []),\n ];\n const inlineWarning = warnings[0] ? ` (${warnings[0]})` : \"\";\n const projectedLabel =\n row.summary.source.id === selectedSourceId && rowSelected\n ? (projectedNamesByLeafId.get(row.leaf.id) ?? row.leaf.linkName)\n : row.leaf.linkName;\n const label =\n selectedGroup.kind === \"clawhub\"\n ? `${projectedLabel} \u00B7 ${formatGroupLabel(row.summary.source)}`\n : projectedLabel;\n return {\n key: row.leaf.id,\n text: `${selectionMarker(\n rowSelected ? \"full\" : \"empty\",\n )} ${label}${inlineWarning}`,\n active: focus === \"detail.skills\" && skillCursor === index + 1,\n color: warnings.length > 0 ? (\"yellow\" as const) : (\"gray\" as const),\n };\n }),\n ]\n : [\n {\n key: \"__no_skills__\",\n text: \"No skills in this group\",\n active: false,\n color: \"gray\" as const,\n },\n ];\n\n const previewLabel = buildPreviewLabel({\n blockedCount: previewState.blockedCount,\n changeCount,\n errorMessage: previewState.errorMessage,\n loading: previewState.loading,\n });\n const metadataRows = buildDetailMetadataRows({\n detailWidth,\n group: selectedGroup,\n summary: renderSummary,\n });\n const actionRows = buildActionRows({\n actionCursor,\n canRunActions,\n deleteState,\n focus,\n isSelectedDelete,\n showDeleteAction,\n updateState,\n });\n const fixedRows =\n metadataRows.length +\n 4 +\n actionRows.length;\n const sectionBudget = Math.max(2, bodyRowCount - fixedRows);\n const hasAgentSection = visibleTargets.length > 0;\n const hasSkillSection = selectedSkillRows.length > 0;\n const agentBudget =\n hasAgentSection && hasSkillSection\n ? Math.min(\n Math.max(1, sectionBudget - 1),\n Math.max(4, Math.floor(sectionBudget * 0.4)),\n )\n : sectionBudget;\n const skillBudget =\n hasAgentSection && hasSkillSection ? Math.max(1, sectionBudget - agentBudget) : sectionBudget;\n const visibleAgentRows = buildScrollableRows(\n agentRows,\n Math.min(targetCursor, Math.max(0, agentRows.length - 1)),\n Math.max(1, agentBudget),\n \"agents\",\n true,\n );\n const visibleSkillRows = buildScrollableRows(\n skillRows,\n Math.min(skillCursor, Math.max(0, skillRows.length - 1)),\n Math.max(1, skillBudget),\n \"skills\",\n true,\n );\n const filledSkillRows = [...visibleSkillRows.rows];\n const skillPaddingCount = Math.max(0, skillBudget - filledSkillRows.length);\n for (let index = 0; index < skillPaddingCount; index += 1) {\n filledSkillRows.push({\n key: `__skills_fill__:${index}`,\n text: \"\",\n active: false,\n color: undefined,\n });\n }\n const detailRows: PaneRow[] = [\n ...metadataRows,\n {\n key: \"__agents_gap__\",\n text: \"\",\n active: false,\n color: undefined,\n },\n {\n key: \"__agents_header__\",\n text: `Select Agents (${visibleEnabledTargets.length}/${availableTargets.length})`,\n active: false,\n bold: true,\n color: undefined,\n },\n ...visibleAgentRows.rows,\n {\n key: \"__skills_gap__\",\n text: \"\",\n active: false,\n color: undefined,\n },\n {\n key: \"__skills_header__\",\n text: `Select Skills (${selectedGroup.kind === \"clawhub\" ? groupSelectedLeafCount : selectedDraft.selectedLeafIds.length}/${selectedSkillRows.length})`,\n active: false,\n bold: true,\n color: undefined,\n },\n ...filledSkillRows,\n ];\n\n const topBar = buildTopBar({\n width: terminalColumns,\n isDirty,\n changeCount,\n showDelete: canDelete,\n statusLabel: statusDisplay.label,\n });\n\n return (\n <Box flexDirection=\"column\" height={terminalRows}>\n <ConfigHeader />\n <Box>\n <Pane\n active={focus === \"groups\"}\n footer={`${groupViews.length} groups`}\n gapAfter\n height={paneHeight}\n title=\"Skills Groups\"\n width={groupsWidth}\n >\n {renderPaneRows(groupRows.rows, bodyRowCount, groupsWidth)}\n </Pane>\n <Pane\n active={focus !== \"groups\"}\n footer={buildCommandBar(focus)}\n height={paneHeight}\n title=\"Group Detail\"\n width={detailWidth}\n >\n {renderPaneRows(detailRows, bodyRowCount, detailWidth, actionRows)}\n </Pane>\n </Box>\n <Text dimColor wrap=\"truncate-end\">\n {buildFooterHints(focus, canDelete)}\n </Text>\n </Box>\n );\n}\n\nexport function ConfigBootstrapApp({ app }: { app: SkillFlowApp }) {\n const { exit } = useApp();\n const { stdout } = useStdout();\n const terminalSize = useTerminalSize(stdout);\n const [state, setState] = useState<ConfigBootstrapState>({\n phase: \"loading\",\n logs: [\"Booting config...\"],\n });\n\n useEffect(() => {\n let cancelled = false;\n void app.configCoordinator.bootstrapWorkspaceState((event) => {\n if (cancelled) {\n return;\n }\n setState((current) => {\n const nextLogs = [...current.logs, event.message].slice(-6);\n return {\n ...current,\n logs: nextLogs,\n };\n });\n }).then((result) => {\n if (cancelled) {\n return;\n }\n if (!result.ok) {\n setState((current) => ({\n phase: \"error\",\n logs: current.logs,\n message: firstErrorMessage(result),\n }));\n return;\n }\n setState((current) => ({\n phase: \"ready\",\n logs: current.logs,\n availableTargets: result.data.availableTargets,\n summaries: result.data.summaries,\n initialDrafts: result.data.initialDrafts,\n audit: result.data.audit,\n bootStatus: result.data.bootStatus,\n }));\n });\n\n return () => {\n cancelled = true;\n };\n }, [app]);\n\n useInput((input, key) => {\n if (state.phase === \"ready\") {\n return;\n }\n if (input === \"q\" || key.escape || (input === \"c\" && key.ctrl)) {\n exit();\n }\n });\n\n if (state.phase === \"ready\") {\n return (\n <ConfigApp\n app={app}\n availableTargets={state.availableTargets}\n summaries={state.summaries}\n initialDrafts={state.initialDrafts}\n bootStatus={state.bootStatus}\n />\n );\n }\n\n const rows = terminalSize.rows;\n const bootLogs = state.logs.slice(-4);\n\n return (\n <Box flexDirection=\"column\" height={rows}>\n <Box flexGrow={1} flexDirection=\"column\">\n <ConfigHeader title=\"Skill Flow Config\" />\n <Text color=\"gray\">\n {state.phase === \"loading\"\n ? \"Checking groups, skills, targets, and current paths...\"\n : \"Bootstrap failed\"}\n </Text>\n {state.phase === \"error\" ? <Text color=\"red\">{state.message}</Text> : null}\n </Box>\n <Box flexDirection=\"column\">\n <Text bold>BOOT LOG</Text>\n {bootLogs.map((log) => (\n <Text key={log} color=\"gray\">\n {log}\n </Text>\n ))}\n <Text color=\"gray\">Press q or Esc to exit.</Text>\n </Box>\n </Box>\n );\n}\n\nfunction ConfigHeader({ title }: { title?: string }) {\n return (\n <Box flexDirection=\"column\">\n <Text backgroundColor=\"cyan\" color=\"black\">\n {ADD_BADGE_TEXT}\n </Text>\n {title ? <Text bold>{title}</Text> : null}\n </Box>\n );\n}\n\nfunction useTerminalSize(stdout: NodeJS.WriteStream) {\n const [size, setSize] = useState(() => ({\n rows: stdout.rows ?? 24,\n columns: stdout.columns ?? 120,\n }));\n\n useEffect(() => {\n const handleResize = () => {\n setSize({\n rows: stdout.rows ?? 24,\n columns: stdout.columns ?? 120,\n });\n };\n\n handleResize();\n stdout.on(\"resize\", handleResize);\n\n return () => {\n stdout.off(\"resize\", handleResize);\n };\n }, [stdout]);\n\n return size;\n}\n\nfunction buildSaveStatusLabel(saveState: SaveState) {\n if (saveState.phase === \"saving\") {\n return \"Saving\";\n }\n if (saveState.phase === \"saved\") {\n return \"Saved\";\n }\n if (saveState.phase === \"failed\") {\n return \"Failed\";\n }\n return \"Clean\";\n}\n\nfunction buildPreviewLabel({\n blockedCount,\n changeCount,\n errorMessage,\n loading,\n}: {\n blockedCount: number;\n changeCount: number;\n errorMessage: string | undefined;\n loading: boolean;\n}) {\n if (loading) {\n return \"planning...\";\n }\n if (errorMessage) {\n return \"failed\";\n }\n if (blockedCount > 0 && changeCount > 0) {\n return `${changeCount} changes, ${blockedCount} blocked`;\n }\n if (blockedCount > 0) {\n return `${blockedCount} blocked`;\n }\n return `${changeCount} changes`;\n}\n\nfunction buildAlerts({\n deleteState,\n failedBootMessages,\n isSelectedDelete,\n previewState,\n projectionWarningsByLeafId,\n saveState,\n selectedDraft,\n selectedSummary,\n updateState,\n}: {\n deleteState: DeleteState;\n failedBootMessages: string[];\n isSelectedDelete: boolean;\n previewState: PreviewState;\n projectionWarningsByLeafId: ProjectionWarningMap;\n saveState: SaveState;\n selectedDraft: DraftBinding;\n selectedSummary: WorkflowSummary;\n updateState: UpdateState;\n}) {\n const alerts: AlertItem[] = [];\n\n if (updateState.phase === \"failed\" && updateState.message) {\n alerts.push({ level: \"error\", message: `Update failed: ${updateState.message}` });\n }\n if (isSelectedDelete && deleteState.phase === \"failed\" && deleteState.message) {\n alerts.push({ level: \"error\", message: `Delete failed: ${deleteState.message}` });\n }\n if (saveState.phase === \"failed\" && saveState.message) {\n alerts.push({ level: \"error\", message: `Save failed: ${saveState.message}` });\n }\n if (previewState.errorMessage) {\n alerts.push({ level: \"error\", message: `Preview failed: ${previewState.errorMessage}` });\n }\n for (const failedBootMessage of failedBootMessages) {\n alerts.push({ level: \"error\", message: `Boot issue: ${failedBootMessage}` });\n }\n\n for (const action of previewState.actions) {\n if (action.kind === \"blocked\" && action.reason) {\n alerts.push({ level: \"blocked\", message: action.reason });\n }\n }\n\n for (const leaf of selectedSummary.leafs) {\n if (!selectedDraft.selectedLeafIds.includes(leaf.id)) {\n continue;\n }\n for (const warning of leaf.metadataWarnings) {\n alerts.push({ level: \"warning\", message: warning });\n }\n for (const warning of projectionWarningsByLeafId[leaf.id] ?? []) {\n alerts.push({ level: \"warning\", message: warning });\n }\n }\n\n if ((selectedSummary.lock?.invalidLeafs.length ?? 0) > 0) {\n alerts.push({\n level: \"warning\",\n message: `${selectedSummary.lock?.invalidLeafs.length ?? 0} invalid skill entries skipped`,\n });\n }\n\n return alerts;\n}\n\nexport function buildDetailMetadataRows({\n detailWidth,\n group,\n summary,\n}: {\n detailWidth: number;\n group: ConfigGroup;\n summary: WorkflowSummary;\n}) {\n const sourceSummary =\n group.kind === \"clawhub\"\n ? `Sources: ${group.summaries.length} clawhub source${group.summaries.length === 1 ? \"\" : \"s\"}`\n : `Source: ${summary.source.locator}`;\n const rows: PaneRow[] = [\n {\n key: \"__title__\",\n text: group.title,\n active: false,\n bold: true,\n color: undefined,\n },\n {\n key: \"__source__\",\n text: fitPaneLine(sourceSummary, getPaneInnerWidth(detailWidth) - 2),\n active: false,\n color: \"gray\",\n },\n ];\n\n if (summary.lock?.checkoutPath) {\n rows.push({\n key: \"__local_path__\",\n text: fitPaneLine(\n `Local Path: ${summary.lock.checkoutPath}`,\n getPaneInnerWidth(detailWidth) - 2,\n ),\n active: false,\n color: \"gray\",\n });\n }\n\n if (group.kind === \"clawhub\") {\n rows.push({\n key: \"__focused_source__\",\n text: fitPaneLine(\n `Focused Source: ${formatGroupLabel(summary.source)}`,\n getPaneInnerWidth(detailWidth) - 2,\n ),\n active: false,\n color: \"gray\",\n });\n }\n\n return rows;\n}\n\nexport function buildActionRows({\n actionCursor,\n canRunActions,\n deleteState,\n focus,\n isSelectedDelete,\n showDeleteAction,\n updateState,\n}: {\n actionCursor: number;\n canRunActions: boolean;\n deleteState: DeleteState;\n focus: FocusPane;\n isSelectedDelete: boolean;\n showDeleteAction: boolean;\n updateState: UpdateState;\n}) {\n const updateText =\n updateState.phase === \"updating\"\n ? \"Update \u00B7 UPDATING...\"\n : updateState.phase === \"failed\"\n ? \"Update \u00B7 FAILED\"\n : \"Update\";\n const rows: PaneRow[] = [\n {\n key: \"__actions_separator__\",\n text: \"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\",\n active: false,\n color: \"gray\" as const,\n },\n {\n key: \"__action_update__\",\n text: `[${updateText}]`,\n active: focus === \"detail.actions\" && actionCursor === 0,\n color: canRunActions || updateState.phase !== \"idle\" ? undefined : (\"gray\" as const),\n bold: true,\n },\n ];\n if (showDeleteAction) {\n const deleteText =\n isSelectedDelete && deleteState.phase === \"deleting\"\n ? \"Delete \u00B7 DELETING...\"\n : isSelectedDelete && deleteState.phase === \"failed\"\n ? \"Delete \u00B7 FAILED\"\n : \"Delete\";\n rows.push({\n key: \"__action_delete__\",\n text: `[${deleteText}]`,\n active: focus === \"detail.actions\" && actionCursor === 1,\n color:\n isSelectedDelete && deleteState.phase === \"failed\"\n ? (\"red\" as const)\n : canRunActions || (isSelectedDelete && deleteState.phase !== \"idle\")\n ? (\"red\" as const)\n : (\"gray\" as const),\n bold: true,\n });\n }\n return rows;\n}\n\nexport function buildCommandBar(focus: FocusPane) {\n if (focus === \"groups\") {\n return \"[Tab/\u2192] Edit\";\n }\n if (focus === \"detail.actions\") {\n return \"[Enter] Action\";\n }\n return \"[Space] Toggle\";\n}\n\nexport function buildFooterHints(focus: FocusPane, canDelete: boolean) {\n if (focus === \"groups\") {\n return canDelete\n ? \"[\u2191\u2193] Move [Tab/\u2192] Switch pane [u] Update [d] Delete [q] Exit\"\n : \"[\u2191\u2193] Move [Tab/\u2192] Switch pane [u] Update [q] Exit\";\n }\n if (focus === \"detail.actions\") {\n return canDelete\n ? \"[\u2191\u2193] Move [Enter] Action [Tab/\u2190/Esc] Back [u] Update [d] Delete\"\n : \"[\u2191\u2193] Move [Enter] Action [Tab/\u2190/Esc] Back [u] Update\";\n }\n return canDelete\n ? \"[\u2191\u2193] Move [Space] Toggle [Tab/\u2190/Esc] Back [u] Update [d] Delete\"\n : \"[\u2191\u2193] Move [Space] Toggle [Tab/\u2190/Esc] Back [u] Update\";\n}\n\nfunction RowText({ row, width }: { row: PaneRow; width: number }) {\n const color = row.active ? row.activeColor ?? \"cyan\" : row.color;\n const prefix = row.active ? \"\u276F \" : \" \";\n const contentWidth = Math.max(1, getPaneInnerWidth(width) - prefix.length);\n const content = fitPaneLine(row.text, contentWidth);\n return (\n <Text\n wrap=\"truncate-end\"\n {...(color ? { color } : {})}\n {...(row.bold ? { bold: true } : {})}\n >\n {prefix}\n {content}\n </Text>\n );\n}\n\nfunction Pane({\n title,\n active,\n width,\n children,\n height,\n footer,\n gapAfter = false,\n}: {\n title: string;\n active: boolean;\n width: number;\n height: number;\n footer: string;\n gapAfter?: boolean;\n children: React.ReactNode;\n}) {\n return (\n <Box\n flexDirection=\"column\"\n width={width}\n height={height}\n marginRight={gapAfter ? 1 : 0}\n paddingX={1}\n borderStyle=\"round\"\n borderColor={active ? \"cyan\" : \"gray\"}\n >\n <Text bold wrap=\"truncate-end\">\n {fitPaneLine(title, getPaneInnerWidth(width))}\n </Text>\n <Text> </Text>\n {children}\n <Text dimColor wrap=\"truncate-middle\">\n {fitPaneLine(footer, getPaneInnerWidth(width))}\n </Text>\n </Box>\n );\n}\n\nfunction renderPaneRows(\n rows: PaneRow[],\n bodyRowCount: number,\n paneWidth: number,\n tailRows: PaneRow[] = [],\n) {\n const items: React.ReactNode[] = rows.map((row) => (\n <RowText key={row.key} row={row} width={paneWidth} />\n ));\n const blankCount = Math.max(0, bodyRowCount - rows.length - tailRows.length);\n for (let index = 0; index < blankCount; index += 1) {\n items.push(<Text key={`__blank__:${index}`}> </Text>);\n }\n for (const row of tailRows) {\n items.push(<RowText key={row.key} row={row} width={paneWidth} />);\n }\n return items;\n}\n\nfunction fitPaneLine(text: string, width: number) {\n if (text.length <= width) {\n return text.padEnd(width, \" \");\n }\n if (width <= 1) {\n return \"\u2026\";\n }\n return `${text.slice(0, width - 1)}\u2026`;\n}\n\nfunction getPaneInnerWidth(width: number) {\n return Math.max(1, width - 4);\n}\n\nexport function selectionMarker(state: \"empty\" | \"partial\" | \"full\") {\n if (state === \"full\") {\n return \"\u25CF\";\n }\n if (state === \"partial\") {\n return \"\u25D0\";\n }\n return \"\u25CB\";\n}\n\nfunction getExactDuplicateKey(linkName: string, name: string, description: string) {\n return `${linkName}\\n${name}\\n${description}`;\n}\n\nfunction getWindowedRows<T>(\n items: T[],\n cursorIndex: number,\n visibleCount: number,\n): { rows: T[]; start: number; end: number } {\n const safeVisibleCount = Math.max(1, visibleCount);\n const maxStart = Math.max(0, items.length - safeVisibleCount);\n const start = Math.min(\n Math.max(0, cursorIndex - Math.floor(safeVisibleCount / 2)),\n maxStart,\n );\n const end = Math.min(items.length, start + safeVisibleCount);\n return {\n rows: items.slice(start, end),\n start,\n end,\n };\n}\n\nfunction pruneSourceMap<T>(sourceMap: Record<string, T>, allowedIds: Set<string>) {\n return Object.fromEntries(\n Object.entries(sourceMap).filter(([sourceId]) => allowedIds.has(sourceId)),\n ) as Record<string, T>;\n}\n\nfunction removeSourceFromMap<T>(sourceMap: Record<string, T>, sourceId: string) {\n const next = { ...sourceMap };\n delete next[sourceId];\n return next;\n}\n\nfunction firstErrorMessage(result: { errors: Array<{ message: string }> }) {\n return result.errors[0]?.message ?? \"operation failed\";\n}\n", "export type ParentSelectionState = \"empty\" | \"partial\" | \"full\";\n\nexport type TreeSelectionState = {\n allLeafIds: string[];\n selectedLeafIds: string[];\n};\n\nexport function getParentSelectionState(\n state: TreeSelectionState,\n): ParentSelectionState {\n if (state.selectedLeafIds.length === 0) {\n return \"empty\";\n }\n if (state.selectedLeafIds.length === state.allLeafIds.length) {\n return \"full\";\n }\n return \"partial\";\n}\n\n// parent\n// [ ] -> [x] -> [-] transitions come from child toggles\n// children\n// toggle child recalculates parent from current selected set\nexport function toggleParent(state: TreeSelectionState): TreeSelectionState {\n return getParentSelectionState(state) === \"full\"\n ? { ...state, selectedLeafIds: [] }\n : { ...state, selectedLeafIds: [...state.allLeafIds] };\n}\n\nexport function toggleChild(\n state: TreeSelectionState,\n leafId: string,\n): TreeSelectionState {\n const selected = new Set(state.selectedLeafIds);\n if (selected.has(leafId)) {\n selected.delete(leafId);\n } else {\n selected.add(leafId);\n }\n\n return {\n ...state,\n selectedLeafIds: state.allLeafIds.filter((id) => selected.has(id)),\n };\n}\n", "import React, { useEffect, useMemo, useState } from \"react\";\nimport { Box, Text, useApp, useInput } from \"ink\";\nimport type { DeploymentPlan, DeploymentTargetId, DraftBinding } from \"@skill-flow/domain/types\";\nimport type { SkillFlowApp } from \"@skill-flow/query/runtime\";\nimport { filterAddWarnings } from \"@skill-flow/integration/utils/cli\";\nimport {\n ALL_AGENTS_CHOICE_ID,\n ALL_SKILLS_CHOICE_ID,\n type AddChoice,\n type AddFlowPrepared,\n type AddFlowRequest,\n areAllSelected,\n buildAddCompletionMessage,\n buildInitialDraft,\n buildLeafChoices,\n buildSummaryLines,\n buildTargetChoices,\n filterChoices,\n toggleAllSelections,\n withAllChoice,\n} from \"./add-flow-model.js\";\n\nexport type AddFlowExitResult =\n | { status: \"applied\"; message: string; warnings: string[] }\n | { status: \"cancelled\"; message: string }\n | { status: \"error\"; message: string; warnings?: string[] };\n\ntype AddFlowAppProps = {\n app: SkillFlowApp;\n request: AddFlowRequest;\n onExit?: (result: AddFlowExitResult) => void;\n};\n\ntype Phase =\n | \"loading\"\n | \"skills\"\n | \"agents-loading\"\n | \"agents\"\n | \"applying\"\n | \"rolling-back\"\n | \"done\"\n | \"error\";\n\ntype PreparedSession = AddFlowPrepared & {\n sourceId: string;\n};\n\ntype SelectionStep = \"skills\" | \"agents\";\ntype InputKey = {\n upArrow?: boolean;\n downArrow?: boolean;\n return?: boolean;\n leftArrow?: boolean;\n backspace?: boolean;\n delete?: boolean;\n ctrl?: boolean;\n meta?: boolean;\n};\n\nconst SPINNER_FRAMES = [\"\u280B\", \"\u2819\", \"\u2839\", \"\u2838\", \"\u283C\", \"\u2834\", \"\u2826\", \"\u2827\", \"\u2807\", \"\u280F\"] as const;\nexport const ADD_BADGE_TEXT = \" skill flow \";\n\nexport function getAddLoadingLabel(phase: Phase): string | undefined {\n switch (phase) {\n case \"loading\":\n return \"Preparing source and discovering skills...\";\n case \"agents-loading\":\n return \"Loading available agents...\";\n case \"applying\":\n return \"Applying selected skills and agents...\";\n case \"rolling-back\":\n return \"Rolling back imported source...\";\n default:\n return undefined;\n }\n}\n\nexport function AddFlowApp({ app, request, onExit }: AddFlowAppProps) {\n const { exit } = useApp();\n const [phase, setPhase] = useState<Phase>(\"loading\");\n const [session, setSession] = useState<PreparedSession | undefined>();\n const [draft, setDraft] = useState<DraftBinding | undefined>();\n const [preview, setPreview] = useState<DeploymentPlan | undefined>();\n const [message, setMessage] = useState<string>(\"\");\n const [warnings, setWarnings] = useState<string[]>([]);\n const [currentStep, setCurrentStep] = useState<SelectionStep>(\"skills\");\n const [skillQuery, setSkillQuery] = useState(\"\");\n const [agentQuery, setAgentQuery] = useState(\"\");\n const [skillCursor, setSkillCursor] = useState(0);\n const [agentCursor, setAgentCursor] = useState(0);\n const [inlineError, setInlineError] = useState<string | undefined>();\n const [lastResult, setLastResult] = useState<AddFlowExitResult | undefined>();\n const spinnerFrame = useSpinnerFrame(\n phase === \"loading\" ||\n phase === \"agents-loading\" ||\n phase === \"applying\" ||\n phase === \"rolling-back\",\n );\n\n const leafChoices = useMemo(\n () => (session ? buildLeafChoices(session.leafs) : []),\n [session],\n );\n const targetChoices = useMemo(\n () => (session ? buildTargetChoices(session.availableTargets) : []),\n [session],\n );\n const visibleLeafChoices = useMemo(\n () => filterChoices(leafChoices, skillQuery),\n [leafChoices, skillQuery],\n );\n const skillChoicesWithAll = useMemo(\n () => withAllChoice(visibleLeafChoices, \"All skills\", ALL_SKILLS_CHOICE_ID),\n [visibleLeafChoices],\n );\n const visibleTargetChoices = useMemo(\n () => filterChoices(targetChoices, agentQuery),\n [targetChoices, agentQuery],\n );\n const targetChoicesWithAll = useMemo(\n () => withAllChoice(visibleTargetChoices, \"All agents\", ALL_AGENTS_CHOICE_ID),\n [visibleTargetChoices],\n );\n\n useEffect(() => {\n if (\n !session ||\n request.yes ||\n request.all ||\n request.requestedAgents?.length ||\n session.availableTargets.length > 0\n ) {\n return;\n }\n\n let cancelled = false;\n void app.getAvailableTargets().then((targets) => {\n if (cancelled) {\n return;\n }\n setSession((current) => (current ? { ...current, availableTargets: targets } : current));\n setDraft((current) => {\n if (!current || current.enabledTargets.length > 0) {\n return current;\n }\n return {\n ...current,\n enabledTargets: [...targets],\n };\n });\n });\n\n return () => {\n cancelled = true;\n };\n }, [app, request.all, request.requestedAgents, request.yes, session]);\n\n useEffect(() => {\n let cancelled = false;\n\n void prepareAddSession(app, request).then(async (result) => {\n if (cancelled) {\n return;\n }\n\n if (!result.ok) {\n setPhase(\"error\");\n setMessage(result.message);\n setWarnings(result.warnings ?? []);\n setLastResult({\n status: \"error\",\n message: result.message,\n ...(result.warnings ? { warnings: result.warnings } : {}),\n });\n return;\n }\n\n const nextSession = result.value;\n const nextDraft = nextSession.draft;\n setSession(nextSession);\n setDraft(nextDraft);\n setWarnings(nextSession.importWarnings);\n\n if (request.yes || request.all) {\n await applyDraftAndFinish(\n app,\n nextSession,\n nextDraft,\n setPhase,\n setPreview,\n setMessage,\n setWarnings,\n setLastResult,\n );\n return;\n }\n\n const shouldPromptSkills =\n !(request.requestedSkills?.length) && nextSession.leafs.length > 1;\n const shouldPromptAgents =\n !(request.requestedAgents?.length) && nextSession.availableTargets.length > 1;\n\n if (shouldPromptSkills) {\n setPhase(\"skills\");\n setCurrentStep(\"skills\");\n return;\n }\n\n if (shouldPromptAgents) {\n setPhase(\"agents\");\n setCurrentStep(\"agents\");\n return;\n }\n\n await applyDraftAndFinish(\n app,\n nextSession,\n nextDraft,\n setPhase,\n setPreview,\n setMessage,\n setWarnings,\n setLastResult,\n );\n });\n\n return () => {\n cancelled = true;\n };\n }, [app, request]);\n\n useInput((input, key) => {\n if (phase === \"loading\" || phase === \"agents-loading\" || phase === \"applying\" || phase === \"rolling-back\") {\n return;\n }\n\n if (phase === \"done\" || phase === \"error\") {\n if (key.return || key.escape || input === \"q\") {\n closeFlow(lastResult, onExit, exit);\n }\n return;\n }\n\n if (key.escape || input === \"q\") {\n if (!session) {\n closeFlow({ status: \"cancelled\", message: \"Add cancelled.\" }, onExit, exit);\n return;\n }\n void rollbackAndExit(app, session.sourceId, setPhase, setMessage, setLastResult, onExit, exit);\n return;\n }\n\n if (!session || !draft) {\n return;\n }\n\n if (phase === \"skills\") {\n handleSelectionInput({\n input,\n key,\n choices: skillChoicesWithAll,\n cursor: skillCursor,\n setCursor: setSkillCursor,\n query: skillQuery,\n setQuery: setSkillQuery,\n selectedIds: draft.selectedLeafIds,\n allChoiceId: ALL_SKILLS_CHOICE_ID,\n allSelectableIds: leafChoices.map((choice) => choice.id),\n setSelectedIds: (selectedLeafIds) => {\n setDraft({ ...draft, selectedLeafIds });\n },\n onConfirm: async () => {\n setInlineError(undefined);\n const resolvedSession = await ensureTargetsLoaded(\n app,\n session,\n request,\n setPhase,\n setSession,\n setDraft,\n );\n if (!resolvedSession) {\n setPhase(\"error\");\n setMessage(\"Unable to detect available agents.\");\n return;\n }\n if (!(request.requestedAgents?.length) && resolvedSession.availableTargets.length > 1) {\n setPhase(\"agents\");\n setCurrentStep(\"agents\");\n return;\n }\n await applyDraftAndFinish(\n app,\n resolvedSession,\n draft,\n setPhase,\n setPreview,\n setMessage,\n setWarnings,\n setLastResult,\n );\n },\n });\n return;\n }\n\n if (phase === \"agents\") {\n handleSelectionInput({\n input,\n key,\n choices: targetChoicesWithAll,\n cursor: agentCursor,\n setCursor: setAgentCursor,\n query: agentQuery,\n setQuery: setAgentQuery,\n selectedIds: draft.enabledTargets,\n allChoiceId: ALL_AGENTS_CHOICE_ID,\n allSelectableIds: targetChoices.map((choice) => choice.id),\n setSelectedIds: (enabledTargets) => {\n setDraft({\n ...draft,\n enabledTargets: enabledTargets as DeploymentTargetId[],\n });\n },\n ...(session.leafs.length > 1 && !(request.requestedSkills?.length)\n ? {\n onBack: () => {\n setInlineError(undefined);\n setPhase(\"skills\");\n setCurrentStep(\"skills\");\n },\n }\n : {}),\n onConfirm: async () => {\n setInlineError(undefined);\n await applyDraftAndFinish(\n app,\n session,\n draft,\n setPhase,\n setPreview,\n setMessage,\n setWarnings,\n setLastResult,\n );\n },\n });\n return;\n }\n });\n\n if (phase === \"loading\") {\n return (\n <Box flexDirection=\"column\">\n <AddFlowHeader />\n <Text bold>\n {spinnerFrame} {getAddLoadingLabel(\"loading\")}\n </Text>\n <Text color=\"gray\">q or Esc cancel after discovery</Text>\n </Box>\n );\n }\n\n if (phase === \"agents-loading\") {\n return (\n <Box flexDirection=\"column\">\n <AddFlowHeader />\n <Text color=\"gray\">Source: {session?.source.displayName ?? \"loading...\"}</Text>\n <Text bold>\n {spinnerFrame} {getAddLoadingLabel(\"agents-loading\")}\n </Text>\n <Text color=\"gray\">Skills are ready. Agent targets are loading in the background...</Text>\n </Box>\n );\n }\n\n if (phase === \"error\") {\n return (\n <Box flexDirection=\"column\">\n <AddFlowHeader />\n <Text color=\"red\">{message}</Text>\n {filterAddWarnings(warnings).map((warning) => (\n <Text key={warning} color=\"yellow\">\n warning: {warning}\n </Text>\n ))}\n <Text color=\"gray\">Enter, q, or Esc exit</Text>\n </Box>\n );\n }\n\n if (!session || !draft) {\n return null;\n }\n\n return (\n <Box flexDirection=\"column\">\n <AddFlowHeader />\n <Text color=\"gray\">Source: {session.source.displayName}</Text>\n <Text color=\"gray\">\n Skills: {draft.selectedLeafIds.length}/{session.leafs.length} \u00B7 Agents: {draft.enabledTargets.length}\n </Text>\n {filterAddWarnings(warnings).map((warning) => (\n <Text key={warning} color=\"yellow\">\n warning: {warning}\n </Text>\n ))}\n {phase === \"skills\"\n ? renderSelectionStep({\n title: \"\u25C6 Select skills to enable\",\n query: skillQuery,\n choices: skillChoicesWithAll,\n cursor: skillCursor,\n selectedIds: draft.selectedLeafIds,\n allChoiceId: ALL_SKILLS_CHOICE_ID,\n allSelectableIds: leafChoices.map((choice) => choice.id),\n footer: \"Type to filter \u00B7 Space toggle \u00B7 Enter continue \u00B7 Esc cancel\",\n emptyMessage: \"No skills match the current filter.\",\n selectedSummary: summarizeSelectedChoices(leafChoices, draft.selectedLeafIds),\n ...(inlineError ? { inlineError } : {}),\n })\n : null}\n {phase === \"agents\"\n ? renderSelectionStep({\n title: \"\u25C6 Select agents to project to\",\n query: agentQuery,\n choices: targetChoicesWithAll,\n cursor: agentCursor,\n selectedIds: draft.enabledTargets,\n allChoiceId: ALL_AGENTS_CHOICE_ID,\n allSelectableIds: targetChoices.map((choice) => choice.id),\n footer:\n currentStep === \"agents\" && session.leafs.length > 1 && !(request.requestedSkills?.length)\n ? \"Type to filter \u00B7 Space toggle \u00B7 Enter install \u00B7 \u2190 back \u00B7 Esc cancel\"\n : \"Type to filter \u00B7 Space toggle \u00B7 Enter install \u00B7 Esc cancel\",\n emptyMessage:\n session.availableTargets.length === 0\n ? \"No agents detected. Continue to install the source without projections.\"\n : \"No agents match the current filter.\",\n selectedSummary: summarizeSelectedChoices(targetChoices, draft.enabledTargets),\n ...(inlineError ? { inlineError } : {}),\n })\n : null}\n {phase === \"applying\" ? (\n <Box flexDirection=\"column\" marginTop={1}>\n <Text bold>\u25C6 Installation Summary</Text>\n {preview && session && draft\n ? buildSummaryLines(\n {\n source: session.source,\n leafs: session.leafs,\n availableTargets: session.availableTargets,\n draft,\n importWarnings: session.importWarnings,\n ...(session.requestedPath ? { requestedPath: session.requestedPath } : {}),\n },\n preview,\n ).map((line) => <Text key={line}>{line}</Text>)\n : null}\n <Text> </Text>\n <Text bold>\n {spinnerFrame} Installing\n </Text>\n <Text color=\"gray\">{getAddLoadingLabel(\"applying\")}</Text>\n </Box>\n ) : null}\n {phase === \"rolling-back\" ? (\n <Box flexDirection=\"column\" marginTop={1}>\n <Text bold>\n {spinnerFrame} Cancelling\n </Text>\n <Text color=\"gray\">{getAddLoadingLabel(\"rolling-back\")}</Text>\n </Box>\n ) : null}\n {phase === \"done\" ? (\n <Box flexDirection=\"column\" marginTop={1}>\n {preview && session && draft\n ? buildSummaryLines(\n {\n source: session.source,\n leafs: session.leafs,\n availableTargets: session.availableTargets,\n draft,\n importWarnings: session.importWarnings,\n ...(session.requestedPath ? { requestedPath: session.requestedPath } : {}),\n },\n preview,\n ).map((line) => <Text key={line}>{line}</Text>)\n : null}\n {preview ? <Text> </Text> : null}\n <Text color=\"green\">{message}</Text>\n <Text color=\"gray\">Enter, q, or Esc exit</Text>\n </Box>\n ) : null}\n </Box>\n );\n}\n\nfunction AddFlowHeader() {\n return (\n <Box flexDirection=\"column\" marginBottom={1}>\n <Text backgroundColor=\"cyan\" color=\"black\">\n {ADD_BADGE_TEXT}\n </Text>\n <Text bold>Add Skills Group</Text>\n </Box>\n );\n}\n\nexport async function runAddFlowNonInteractive(\n app: SkillFlowApp,\n request: AddFlowRequest,\n): Promise<AddFlowExitResult> {\n const prepared = await prepareAddSession(app, request);\n if (!prepared.ok) {\n return {\n status: \"error\",\n message: prepared.message,\n ...(prepared.warnings ? { warnings: prepared.warnings } : {}),\n };\n }\n\n const applyResult = await app.applyDraft(prepared.value.sourceId, prepared.value.draft);\n if (!applyResult.ok) {\n return {\n status: \"error\",\n message: applyResult.errors[0]?.message ?? \"Install failed.\",\n warnings: [...prepared.value.importWarnings, ...applyResult.warnings.map((warning) => warning.message)],\n };\n }\n\n return {\n status: \"applied\",\n message: buildAddCompletionMessage(\n prepared.value.source,\n applyResult.data.draft,\n prepared.value.leafs,\n ),\n warnings: [...prepared.value.importWarnings, ...applyResult.warnings.map((warning) => warning.message)],\n };\n}\n\nasync function prepareAddSession(\n app: SkillFlowApp,\n request: AddFlowRequest,\n): Promise<\n | { ok: true; value: PreparedSession }\n | { ok: false; message: string; warnings?: string[] }\n> {\n const added = await app.prepareAddSource(request.locator, {\n ...(request.path ? { path: request.path } : {}),\n ...(!request.yes && !request.all && !request.requestedAgents?.length\n ? { skipTargetDetection: true }\n : {}),\n ...(!request.all && request.requestedSkills?.length\n ? { skillNames: request.requestedSkills }\n : {}),\n ...(!request.all && request.requestedAgents?.length\n ? { agentTargets: request.requestedAgents as DeploymentTargetId[] }\n : {}),\n });\n if (!added.ok) {\n return {\n ok: false,\n message: added.errors[0]?.message ?? \"Unable to add source.\",\n warnings: added.warnings.map((warning) => warning.message),\n };\n }\n\n const sourceId = added.data.sourceId;\n const initialDraft =\n request.all || request.yes\n ? buildInitialDraft(added.data.leafs, added.data.availableTargets, {\n ...(added.data.manifest.requestedPath\n ? { requestedPath: added.data.manifest.requestedPath }\n : {}),\n ...(request.yes ? { yes: true } : {}),\n ...(request.all ? { all: true } : {}),\n })\n : { ok: true as const, value: added.data.draft };\n if (!initialDraft.ok) {\n await app.rollbackPreparedSource(sourceId).catch(() => {});\n return {\n ok: false,\n message: initialDraft.message,\n warnings: added.warnings.map((warning) => warning.message),\n };\n }\n\n return {\n ok: true,\n value: {\n sourceId,\n source: added.data.manifest,\n leafs: added.data.leafs,\n availableTargets: added.data.availableTargets,\n draft: initialDraft.value,\n importWarnings: added.warnings.map((warning) => warning.message),\n ...(added.data.manifest.requestedPath\n ? { requestedPath: added.data.manifest.requestedPath }\n : {}),\n },\n };\n}\n\nasync function ensureTargetsLoaded(\n app: SkillFlowApp,\n session: PreparedSession,\n request: AddFlowRequest,\n setPhase: (phase: Phase) => void,\n setSession: (session: PreparedSession | ((current: PreparedSession | undefined) => PreparedSession | undefined)) => void,\n setDraft: (draft: DraftBinding | ((current: DraftBinding | undefined) => DraftBinding | undefined)) => void,\n): Promise<PreparedSession | undefined> {\n if (\n request.yes ||\n request.all ||\n request.requestedAgents?.length ||\n session.availableTargets.length > 0\n ) {\n return session;\n }\n\n setPhase(\"agents-loading\");\n const targets = await app.getAvailableTargets();\n const nextSession = { ...session, availableTargets: targets };\n setSession(nextSession);\n setDraft((current) => {\n if (!current || current.enabledTargets.length > 0) {\n return current;\n }\n return {\n ...current,\n enabledTargets: [...targets],\n };\n });\n return nextSession;\n}\n\nasync function applyDraftAndFinish(\n app: SkillFlowApp,\n session: PreparedSession,\n draft: DraftBinding,\n setPhase: (phase: Phase) => void,\n setPreview: (plan: DeploymentPlan) => void,\n setMessage: (message: string) => void,\n setWarnings: (warnings: string[]) => void,\n setLastResult: (result: AddFlowExitResult) => void,\n) {\n const preview = await app.previewDraft(session.sourceId, draft);\n if (!preview.ok) {\n const nextWarnings = [...session.importWarnings, ...preview.warnings.map((warning) => warning.message)];\n setWarnings(nextWarnings);\n setMessage(preview.errors[0]?.message ?? \"Unable to build installation summary.\");\n setLastResult({\n status: \"error\",\n message: preview.errors[0]?.message ?? \"Unable to build installation summary.\",\n warnings: nextWarnings,\n });\n setPhase(\"error\");\n return;\n }\n\n setPreview(preview.data.plan);\n setWarnings([...session.importWarnings, ...preview.warnings.map((warning) => warning.message)]);\n setPhase(\"applying\");\n const applied = await app.applyDraft(session.sourceId, draft);\n if (!applied.ok) {\n const nextWarnings = [\n ...session.importWarnings,\n ...preview.warnings.map((warning) => warning.message),\n ...applied.warnings.map((warning) => warning.message),\n ];\n setWarnings(nextWarnings);\n setMessage(applied.errors[0]?.message ?? \"Install failed.\");\n setLastResult({\n status: \"error\",\n message: applied.errors[0]?.message ?? \"Install failed.\",\n warnings: nextWarnings,\n });\n setPhase(\"error\");\n return;\n }\n\n const nextWarnings = [\n ...session.importWarnings,\n ...preview.warnings.map((warning) => warning.message),\n ...applied.warnings.map((warning) => warning.message),\n ];\n const nextMessage = buildAddCompletionMessage(session.source, applied.data.draft, session.leafs);\n setWarnings(nextWarnings);\n setMessage(nextMessage);\n setLastResult({\n status: \"applied\",\n message: nextMessage,\n warnings: nextWarnings,\n });\n setPhase(\"done\");\n}\n\nasync function rollbackAndExit(\n app: SkillFlowApp,\n sourceId: string,\n setPhase: (phase: Phase) => void,\n setMessage: (message: string) => void,\n setLastResult: (result: AddFlowExitResult) => void,\n onExit: AddFlowAppProps[\"onExit\"],\n exit: () => void,\n) {\n setPhase(\"rolling-back\");\n const removed = await app.rollbackPreparedSource(sourceId);\n if (!removed.ok) {\n const message = removed.errors[0]?.message ?? \"Unable to roll back cancelled add.\";\n setMessage(message);\n setLastResult({ status: \"error\", message });\n setPhase(\"error\");\n return;\n }\n\n const result: AddFlowExitResult = {\n status: \"cancelled\",\n message: \"Add cancelled.\",\n };\n setMessage(result.message);\n setLastResult(result);\n if (onExit) {\n onExit(result);\n return;\n }\n exit();\n}\n\nfunction handleSelectionInput({\n input,\n key,\n choices,\n cursor,\n setCursor,\n query,\n setQuery,\n selectedIds,\n allChoiceId,\n allSelectableIds,\n setSelectedIds,\n onBack,\n onConfirm,\n}: {\n input: string;\n key: InputKey;\n choices: AddChoice[];\n cursor: number;\n setCursor: (cursor: number | ((cursor: number) => number)) => void;\n query: string;\n setQuery: (query: string) => void;\n selectedIds: string[];\n allChoiceId?: string;\n allSelectableIds: string[];\n setSelectedIds: (selectedIds: string[]) => void;\n onBack?: () => void;\n onConfirm: () => void | Promise<void>;\n}) {\n if (key.upArrow) {\n setCursor((current) => Math.max(0, current - 1));\n return;\n }\n\n if (key.downArrow) {\n setCursor((current) => Math.min(Math.max(choices.length - 1, 0), current + 1));\n return;\n }\n\n if (key.leftArrow) {\n onBack?.();\n return;\n }\n\n if (key.return) {\n void onConfirm();\n return;\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1));\n setCursor(0);\n return;\n }\n\n if (input === \" \") {\n const current = choices[cursor];\n if (!current) {\n return;\n }\n if (allChoiceId && current.id === allChoiceId) {\n setSelectedIds(toggleAllSelections(selectedIds, allSelectableIds));\n return;\n }\n const selected = new Set(selectedIds);\n if (selected.has(current.id)) {\n selected.delete(current.id);\n } else {\n selected.add(current.id);\n }\n setSelectedIds(choices.map((choice) => choice.id).filter((id) => selected.has(id)).concat(\n selectedIds.filter((id) => !choices.some((choice) => choice.id === id)),\n ));\n return;\n }\n\n if (!key.ctrl && !key.meta && input.length === 1 && /[^\\s]/.test(input)) {\n setQuery(`${query}${input}`);\n setCursor(0);\n }\n}\n\nfunction renderSelectionStep({\n title,\n query,\n choices,\n cursor,\n selectedIds,\n allChoiceId,\n allSelectableIds,\n footer,\n emptyMessage,\n selectedSummary,\n inlineError,\n}: {\n title: string;\n query: string;\n choices: AddChoice[];\n cursor: number;\n selectedIds: readonly string[];\n allChoiceId?: string;\n allSelectableIds: readonly string[];\n footer: string;\n emptyMessage: string;\n selectedSummary: string;\n inlineError?: string;\n}) {\n return (\n <Box flexDirection=\"column\" marginTop={1}>\n <Text bold>{title}</Text>\n <Text color=\"gray\">Search: {query || \" \"}</Text>\n <Text color=\"gray\">{footer}</Text>\n <Box flexDirection=\"column\" marginTop={1}>\n {choices.length === 0 ? (\n <Text color=\"gray\">{emptyMessage}</Text>\n ) : (\n choices.map((choice, index) => {\n const active = index === cursor;\n const selected =\n choice.id === allChoiceId\n ? areAllSelected(selectedIds, allSelectableIds)\n : selectedIds.includes(choice.id);\n return (\n <Text key={choice.id} {...(active ? { color: \"cyan\" as const } : {})}>\n {active ? \"\u276F\" : \" \"} {selected ? \"\u25CF\" : \"\u25CB\"} {choice.label}\n {choice.hint ? <Text color=\"gray\"> {choice.hint}</Text> : null}\n </Text>\n );\n })\n )}\n </Box>\n <Text color=\"gray\">Selected: {selectedSummary}</Text>\n {inlineError ? <Text color=\"red\">{inlineError}</Text> : null}\n </Box>\n );\n}\n\nfunction summarizeSelectedChoices(choices: AddChoice[], selectedIds: readonly string[]) {\n const labels = choices\n .filter((choice) => selectedIds.includes(choice.id))\n .map((choice) => choice.label);\n\n if (labels.length === 0) {\n return \"none\";\n }\n\n if (labels.length <= 4) {\n return labels.join(\", \");\n }\n\n return `${labels.slice(0, 4).join(\", \")}, +${labels.length - 4} more`;\n}\n\nfunction closeFlow(\n result: AddFlowExitResult | undefined,\n onExit: AddFlowAppProps[\"onExit\"],\n exit: () => void,\n) {\n if (result && onExit) {\n onExit(result);\n return;\n }\n\n exit();\n}\n\nfunction useSpinnerFrame(active: boolean) {\n const [frameIndex, setFrameIndex] = useState(0);\n\n useEffect(() => {\n if (!active) {\n setFrameIndex(0);\n return;\n }\n\n const timer = setInterval(() => {\n setFrameIndex((current) => (current + 1) % SPINNER_FRAMES.length);\n }, 80);\n\n return () => {\n clearInterval(timer);\n };\n }, [active]);\n\n return SPINNER_FRAMES[frameIndex] ?? SPINNER_FRAMES[0];\n}\n", "import type {\n DeploymentPlan,\n DeploymentTargetId,\n DraftBinding,\n LeafRecord,\n SourceManifestRecord,\n} from \"@skill-flow/domain/types\";\nimport { getMergedTargetDefinitionById } from \"@skill-flow/integration/utils/constants\";\nimport { countActions, formatActionSummary, formatTargetName } from \"@skill-flow/integration/utils/format\";\nimport { formatGroupRef } from \"@skill-flow/integration/utils/naming\";\n\nexport type AddFlowRequest = {\n locator: string;\n path?: string;\n requestedSkills?: string[];\n requestedAgents?: string[];\n yes?: boolean;\n all?: boolean;\n};\n\nexport type AddChoice = {\n id: string;\n label: string;\n hint?: string;\n description?: string;\n};\n\nexport const ALL_SKILLS_CHOICE_ID = \"__all_skills__\";\nexport const ALL_AGENTS_CHOICE_ID = \"__all_agents__\";\n\nexport type AddFlowPrepared = {\n source: SourceManifestRecord;\n leafs: LeafRecord[];\n availableTargets: DeploymentTargetId[];\n draft: DraftBinding;\n importWarnings: string[];\n requestedPath?: string;\n};\n\nexport function normalizeRequestedPath(requestedPath?: string): string | undefined {\n if (!requestedPath) {\n return undefined;\n }\n\n const normalized = requestedPath.trim().replace(/^\\.\\/+/, \"\").replace(/\\/+$/, \"\");\n return normalized.length > 0 && normalized !== \".\" ? normalized : undefined;\n}\n\nexport function buildDefaultSelectedLeafIds(\n leafs: LeafRecord[],\n requestedPath?: string,\n): string[] {\n const normalizedPath = normalizeRequestedPath(requestedPath);\n if (!normalizedPath) {\n return leafs.map((leaf) => leaf.id);\n }\n\n return leafs\n .filter(\n (leaf) =>\n leaf.relativePath === normalizedPath ||\n leaf.relativePath.startsWith(`${normalizedPath}/`),\n )\n .map((leaf) => leaf.id);\n}\n\nexport function buildLeafChoices(leafs: LeafRecord[]): AddChoice[] {\n return leafs.map((leaf) => ({\n id: leaf.id,\n label: leaf.linkName,\n hint: leaf.relativePath,\n description: leaf.description,\n }));\n}\n\nexport function buildTargetChoices(\n targets: DeploymentTargetId[],\n): AddChoice[] {\n return targets.map((target) => {\n const definition = getMergedTargetDefinitionById(target);\n return {\n id: target,\n label: formatTargetName(target),\n ...(definition?.globalPath\n ? { hint: definition.globalPath }\n : {}),\n };\n });\n}\n\nexport function withAllChoice(choices: AddChoice[], label: string, id: string): AddChoice[] {\n return [{ id, label }, ...choices];\n}\n\nexport function filterChoices(choices: AddChoice[], query: string): AddChoice[] {\n const normalizedQuery = normalizeSearch(query);\n if (!normalizedQuery) {\n return choices;\n }\n\n return choices.filter((choice) => {\n const haystack = normalizeSearch(\n [choice.label, choice.hint, choice.description, choice.id].filter(Boolean).join(\" \"),\n );\n return haystack.includes(normalizedQuery);\n });\n}\n\nexport function resolveRequestedLeafIds(\n leafs: LeafRecord[],\n requestedSkills: string[],\n): { ok: true; value: string[] } | { ok: false; message: string } {\n const resolvedIds: string[] = [];\n\n for (const requestedSkill of requestedSkills) {\n const match = resolveLeafToken(leafs, requestedSkill);\n if (!match.ok) {\n return match;\n }\n resolvedIds.push(match.value);\n }\n\n return { ok: true, value: [...new Set(resolvedIds)] };\n}\n\nexport function resolveRequestedTargets(\n availableTargets: DeploymentTargetId[],\n requestedAgents: string[],\n) : { ok: true; value: DeploymentTargetId[] } | { ok: false; message: string } {\n const availableSet = new Set(availableTargets);\n const resolvedTargets: DeploymentTargetId[] = [];\n\n for (const requestedAgent of requestedAgents) {\n const normalized = normalizeSearch(requestedAgent);\n const matches = availableTargets.filter((target) => {\n if (!availableSet.has(target)) {\n return false;\n }\n\n return [\n target,\n formatTargetName(target),\n ].some((value) => normalizeSearch(value) === normalized);\n });\n\n if (matches.length === 0) {\n return {\n ok: false,\n message: `Unknown or unavailable agent '${requestedAgent}'.`,\n };\n }\n\n resolvedTargets.push(matches[0]!);\n }\n\n return { ok: true, value: [...new Set(resolvedTargets)] };\n}\n\nexport function buildInitialDraft(\n leafs: LeafRecord[],\n availableTargets: DeploymentTargetId[],\n options: {\n requestedPath?: string;\n requestedSkills?: string[];\n requestedAgents?: string[];\n yes?: boolean;\n all?: boolean;\n },\n): { ok: true; value: DraftBinding } | { ok: false; message: string } {\n const selectedLeafIds = options.requestedSkills?.length\n ? resolveRequestedLeafIds(leafs, options.requestedSkills)\n : {\n ok: true as const,\n value:\n options.all || options.yes\n ? leafs.map((leaf) => leaf.id)\n : buildDefaultSelectedLeafIds(leafs, options.requestedPath),\n };\n if (!selectedLeafIds.ok) {\n return selectedLeafIds;\n }\n\n const enabledTargets = options.requestedAgents?.length\n ? resolveRequestedTargets(availableTargets, options.requestedAgents)\n : {\n ok: true as const,\n value: [...availableTargets],\n };\n if (!enabledTargets.ok) {\n return enabledTargets;\n }\n\n return {\n ok: true,\n value: {\n selectedLeafIds: selectedLeafIds.value,\n enabledTargets: enabledTargets.value,\n },\n };\n}\n\nexport function buildAddCompletionMessage(\n source: SourceManifestRecord,\n draft: DraftBinding,\n leafs: LeafRecord[],\n): string {\n const selectedCount = draft.selectedLeafIds.length;\n const targetCount = draft.enabledTargets.length;\n const importedCount = leafs.length;\n const targetSummary =\n targetCount === 0\n ? \"no agents enabled\"\n : `${targetCount} agent${targetCount === 1 ? \"\" : \"s\"} selected`;\n\n return `Added ${formatGroupRef(source)} with ${selectedCount}/${importedCount} skills enabled, ${targetSummary}.`;\n}\n\nexport function areAllSelected(selectedIds: readonly string[], allIds: readonly string[]): boolean {\n return allIds.length > 0 && allIds.every((id) => selectedIds.includes(id));\n}\n\nexport function toggleAllSelections(\n selectedIds: readonly string[],\n allIds: readonly string[],\n): string[] {\n const current = new Set(selectedIds);\n if (areAllSelected(selectedIds, allIds)) {\n for (const id of allIds) {\n current.delete(id);\n }\n return [...current];\n }\n\n for (const id of allIds) {\n current.add(id);\n }\n return [...current];\n}\n\nexport function buildSummaryLines(\n prepared: AddFlowPrepared,\n preview: DeploymentPlan,\n): string[] {\n const counts = countActions(preview.actions);\n const selectedLeafLabels = prepared.leafs\n .filter((leaf) => prepared.draft.selectedLeafIds.includes(leaf.id))\n .map((leaf) => leaf.linkName)\n .sort((left, right) => left.localeCompare(right));\n const selectedTargetLabels = prepared.draft.enabledTargets.map((target) => formatTargetName(target));\n\n return [\n `Source ${formatGroupRef(prepared.source)}`,\n `Skills ${prepared.draft.selectedLeafIds.length}/${prepared.leafs.length} enabled`,\n `Agents ${prepared.draft.enabledTargets.length} selected`,\n ...(prepared.requestedPath\n ? [`Default preselected from ${prepared.requestedPath}`]\n : []),\n `Plan ${formatActionSummary(preview.actions)}`,\n ...(selectedLeafLabels.length > 0\n ? [`Enabled ${truncateSummary(selectedLeafLabels)}`]\n : []),\n ...(selectedTargetLabels.length > 0\n ? [`Targets ${truncateSummary(selectedTargetLabels)}`]\n : []),\n ...(counts.blocked ? [`Blocked ${counts.blocked}`] : []),\n ];\n}\n\nfunction resolveLeafToken(\n leafs: LeafRecord[],\n requestedSkill: string,\n): { ok: true; value: string } | { ok: false; message: string } {\n const normalized = normalizeSearch(requestedSkill);\n const relativePathMatches = leafs.filter(\n (leaf) => normalizeSearch(leaf.relativePath) === normalized,\n );\n if (relativePathMatches.length === 1) {\n return { ok: true, value: relativePathMatches[0]!.id };\n }\n if (relativePathMatches.length > 1) {\n return {\n ok: false,\n message: `Skill selector '${requestedSkill}' is ambiguous. Use a unique relative path.`,\n };\n }\n\n const fallbackMatches = leafs.filter((leaf) =>\n [leaf.linkName, leaf.name].some((value) => normalizeSearch(value) === normalized),\n );\n\n if (fallbackMatches.length === 1) {\n return { ok: true, value: fallbackMatches[0]!.id };\n }\n\n if (fallbackMatches.length > 1) {\n return {\n ok: false,\n message: `Skill selector '${requestedSkill}' is ambiguous. Use a relative path such as '${fallbackMatches[0]!.relativePath}'.`,\n };\n }\n\n return {\n ok: false,\n message: `Unknown skill selector '${requestedSkill}'.`,\n };\n}\n\nfunction normalizeSearch(value: string | undefined): string {\n return (value ?? \"\")\n .toLowerCase()\n .replace(/[_\\s-]+/g, \" \")\n .trim();\n}\n\nfunction truncateSummary(values: string[]): string {\n if (values.length <= 4) {\n return values.join(\", \");\n }\n\n return `${values.slice(0, 4).join(\", \")}, +${values.length - 4} more`;\n}\n", "import React, { useEffect, useMemo, useState } from \"react\";\nimport { Box, Text, useApp, useInput, useStdout } from \"ink\";\nimport type { SkillCandidate } from \"@skill-flow/domain/types\";\nimport type { SkillFlowApp } from \"@skill-flow/query/runtime\";\nimport { AddFlowApp, type AddFlowExitResult } from \"./add-flow.js\";\nimport { buildFindCommand } from \"@skill-flow/integration/utils/find-command\";\n\ntype FindAppProps = {\n app: SkillFlowApp;\n query: string;\n candidates?: SkillCandidate[];\n};\n\ntype InstallState =\n | { phase: \"list\" }\n | { phase: \"confirm\" }\n | { phase: \"installing\"; candidate: SkillCandidate }\n | { phase: \"done\"; message: string; warnings: string[] }\n | { phase: \"error\"; message: string };\n\nexport function FindApp({ app, query, candidates }: FindAppProps) {\n const { exit } = useApp();\n const { stdout } = useStdout();\n const [loadedCandidates, setLoadedCandidates] = useState<SkillCandidate[] | undefined>(candidates);\n const [loadError, setLoadError] = useState<string | undefined>();\n const [loadWarnings, setLoadWarnings] = useState<string[]>([]);\n const [cursor, setCursor] = useState(0);\n const [state, setState] = useState<InstallState>({ phase: \"list\" });\n const visibleCandidates = useMemo(\n () => (loadedCandidates ?? []).slice(0, 30),\n [loadedCandidates],\n );\n const selected = visibleCandidates[cursor];\n const columns = getColumns(stdout?.columns ?? 100);\n\n useEffect(() => {\n if (candidates) {\n setLoadedCandidates(candidates);\n return;\n }\n\n let cancelled = false;\n void app.findSkills(query).then((result) => {\n if (cancelled) {\n return;\n }\n if (!result.ok) {\n setLoadError(result.errors[0]?.message ?? \"Search failed.\");\n return;\n }\n setLoadedCandidates(result.data.candidates);\n setLoadWarnings(result.warnings.map((warning) => warning.message));\n });\n\n return () => {\n cancelled = true;\n };\n }, [app, candidates, query]);\n\n useInput((input, key) => {\n if (key.escape || input === \"q\") {\n if (state.phase === \"confirm\" || state.phase === \"error\") {\n setState({ phase: \"list\" });\n return;\n }\n exit();\n return;\n }\n\n if (state.phase === \"installing\") {\n return;\n }\n\n if (state.phase === \"done\") {\n exit();\n return;\n }\n\n if (key.upArrow) {\n setCursor((current) => Math.max(0, current - 1));\n return;\n }\n\n if (key.downArrow) {\n setCursor((current) => Math.min(visibleCandidates.length - 1, current + 1));\n return;\n }\n\n if (!key.return) {\n return;\n }\n\n if (!selected) {\n exit();\n return;\n }\n\n if (state.phase === \"list\") {\n setState({ phase: \"confirm\" });\n return;\n }\n\n if (state.phase === \"confirm\") {\n if (selected.action.type === \"none\") {\n setState({ phase: \"error\", message: \"This skill is already installed.\" });\n return;\n }\n\n setState({ phase: \"installing\", candidate: selected });\n }\n });\n\n if (!loadedCandidates && !loadError) {\n return (\n <Box flexDirection=\"column\">\n <Text bold>Find Skills</Text>\n <Text color=\"gray\">query: {query}</Text>\n <Text color=\"yellow\">Searching local, Git catalogs, and ClawHub...</Text>\n <Text color=\"gray\">Press q or Esc to exit.</Text>\n </Box>\n );\n }\n\n if (loadError) {\n return (\n <Box flexDirection=\"column\">\n <Text bold>Find Skills</Text>\n <Text color=\"red\">{loadError}</Text>\n <Text color=\"gray\">Press q or Esc to exit.</Text>\n </Box>\n );\n }\n\n if (visibleCandidates.length === 0) {\n return (\n <Box flexDirection=\"column\">\n <Text>No matching skills found for \"{query}\".</Text>\n <Text color=\"gray\">Press q or Esc to exit.</Text>\n </Box>\n );\n }\n\n if (state.phase === \"installing\") {\n return (\n <AddFlowApp\n app={app}\n request={buildAddFlowRequest(state.candidate)}\n onExit={(result) => {\n setState(mapAddFlowResult(result));\n }}\n />\n );\n }\n\n return (\n <Box flexDirection=\"column\">\n <Text bold>Find Skills</Text>\n <Text color=\"gray\">\n query: {query} \u00B7 results: {visibleCandidates.length}\n {(loadedCandidates?.length ?? 0) > visibleCandidates.length\n ? ` / ${loadedCandidates?.length ?? 0}`\n : \"\"}\n </Text>\n {loadWarnings.map((warning) => (\n <Text key={warning} color=\"yellow\">\n warning: {warning}\n </Text>\n ))}\n <Box marginTop={1}>\n <Text bold>{pad(\"No.\", columns.index)}</Text>\n <Text bold>{pad(\"Skill\", columns.name)}</Text>\n <Text bold>Repository</Text>\n </Box>\n {visibleCandidates.map((candidate, index) => {\n const active = index === cursor;\n return (\n <Box key={candidate.id}>\n <Text {...(active ? { color: \"cyan\" as const } : {})}>\n {pad(`${index + 1}.`, columns.index)}\n {pad(candidate.installed ? `${candidate.title} *` : candidate.title, columns.name)}\n {candidate.sourceLabel}\n </Text>\n </Box>\n );\n })}\n\n {selected ? (\n <Box flexDirection=\"column\" marginTop={1}>\n <Text>\n selected: <Text color=\"cyan\">{selected.title}</Text> \u00B7 {selected.sourceLabel}\n </Text>\n {state.phase === \"list\" ? (\n <Text color=\"gray\">Enter preview add command \u00B7 Up/Down move \u00B7 Esc/q exit</Text>\n ) : null}\n {state.phase === \"confirm\" ? (\n <>\n <Text>next: {buildFindCommand(selected) ?? \"already installed\"}</Text>\n <Text color=\"gray\">Enter install \u00B7 Esc back</Text>\n </>\n ) : null}\n {state.phase === \"done\" ? (\n <>\n <Text color=\"green\">{state.message}</Text>\n {state.warnings.map((warning) => (\n <Text key={warning} color=\"yellow\">\n warning: {warning}\n </Text>\n ))}\n <Text color=\"gray\">Press Enter, q, or Esc to exit.</Text>\n </>\n ) : null}\n {state.phase === \"error\" ? (\n <>\n <Text color=\"red\">{state.message}</Text>\n <Text color=\"gray\">Esc back</Text>\n </>\n ) : null}\n </Box>\n ) : null}\n </Box>\n );\n}\n\nfunction getColumns(total: number) {\n const usable = Math.max(72, total);\n return {\n index: 5,\n name: Math.max(18, Math.floor(usable * 0.26)),\n source: Math.max(12, Math.floor(usable * 0.14)),\n };\n}\n\nfunction pad(value: string, width: number) {\n const trimmed = value.length > width - 1 ? `${value.slice(0, width - 2)}\u2026` : value;\n return trimmed.padEnd(width, \" \");\n}\n\nfunction buildAddFlowRequest(candidate: SkillCandidate) {\n if (candidate.action.type === \"add-clawhub\") {\n return {\n locator: candidate.action.version\n ? `clawhub:${candidate.action.slug}@${candidate.action.version}`\n : `clawhub:${candidate.action.slug}`,\n };\n }\n\n if (candidate.action.type === \"add-git\") {\n return {\n locator: candidate.action.locator,\n ...(candidate.action.requestedPath\n ? { path: candidate.action.requestedPath }\n : {}),\n };\n }\n\n return {\n locator: candidate.locator,\n };\n}\n\nfunction mapAddFlowResult(result: AddFlowExitResult): InstallState {\n if (result.status === \"applied\") {\n return {\n phase: \"done\",\n message: result.message,\n warnings: result.warnings,\n };\n }\n\n if (result.status === \"cancelled\") {\n return { phase: \"list\" };\n }\n\n return {\n phase: \"error\",\n message: result.message,\n };\n}\n", "export const PROTOCOL_VERSION = \"1.0\" as const;\n\nexport type BridgeCommandName =\n | \"bootstrap\"\n | \"list\"\n | \"inspect\"\n | \"inspect-enrichment\"\n | \"search-import-groups\"\n | \"preview-import-source\"\n | \"import-source\"\n | \"toggle-pin\"\n | \"doctor\"\n | \"add\"\n | \"apply\"\n | \"update\"\n | \"uninstall\"\n | \"save-settings\";\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\nexport type JsonObject = { [key: string]: JsonValue };\n\nexport type BridgeRequest = {\n protocolVersion: string;\n requestId?: string;\n command: BridgeCommandName;\n payload?: JsonValue;\n};\n\nexport type BridgeError = {\n code: string;\n message: string;\n};\n\nexport type BridgeResponse = {\n protocolVersion: string;\n requestId?: string;\n command: BridgeCommandName;\n ok: boolean;\n data?: JsonValue;\n warnings: BridgeError[];\n errors: BridgeError[];\n};\n\nexport function parseBridgeRequest(input: unknown): BridgeRequest {\n if (!isJsonObject(input)) {\n throw new Error(\"Bridge request must be a JSON object.\");\n }\n const protocolVersion = input.protocolVersion;\n const command = input.command;\n const requestId = input.requestId;\n\n if (typeof protocolVersion !== \"string\" || protocolVersion.length === 0) {\n throw new Error(\"Bridge request requires a non-empty 'protocolVersion'.\");\n }\n if (protocolVersion !== PROTOCOL_VERSION) {\n throw new Error(\n `Protocol version mismatch. Expected '${PROTOCOL_VERSION}', received '${protocolVersion}'.`,\n );\n }\n\n if (!isBridgeCommandName(command)) {\n throw new Error(\n \"Bridge request 'command' must be one of: bootstrap, list, inspect, inspect-enrichment, search-import-groups, preview-import-source, import-source, toggle-pin, doctor, add, apply, update, uninstall, save-settings.\",\n );\n }\n\n if (requestId !== undefined && typeof requestId !== \"string\") {\n throw new Error(\"Bridge request 'requestId' must be a string when provided.\");\n }\n\n if (\"payload\" in input && !isJsonValue(input.payload)) {\n throw new Error(\"Bridge request 'payload' must be valid JSON.\");\n }\n\n return {\n protocolVersion,\n command,\n ...(requestId ? { requestId } : {}),\n ...(\"payload\" in input ? { payload: input.payload } : {}),\n };\n}\n\nexport function buildBridgeResponse(args: {\n command: BridgeCommandName;\n requestId?: string;\n ok: boolean;\n data?: JsonValue;\n warnings?: BridgeError[];\n errors?: BridgeError[];\n}): BridgeResponse {\n return {\n protocolVersion: PROTOCOL_VERSION,\n command: args.command,\n ...(args.requestId ? { requestId: args.requestId } : {}),\n ok: args.ok,\n ...(args.data !== undefined ? { data: args.data } : {}),\n warnings: args.warnings ?? [],\n errors: args.errors ?? [],\n };\n}\n\nexport function isJsonObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function isJsonValue(value: unknown): value is JsonValue {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every((item) => isJsonValue(item));\n }\n if (isJsonObject(value)) {\n return Object.values(value).every((item) => isJsonValue(item));\n }\n return false;\n}\n\nexport function isBridgeCommandName(value: unknown): value is BridgeCommandName {\n return (\n value === \"bootstrap\" ||\n value === \"list\" ||\n value === \"inspect\" ||\n value === \"inspect-enrichment\" ||\n value === \"search-import-groups\" ||\n value === \"preview-import-source\" ||\n value === \"import-source\" ||\n value === \"toggle-pin\" ||\n value === \"doctor\" ||\n value === \"add\" ||\n value === \"apply\" ||\n value === \"update\" ||\n value === \"uninstall\" ||\n value === \"save-settings\"\n );\n}\n", "import {\n buildBridgeResponse,\n type BridgeRequest,\n type BridgeResponse,\n isJsonObject,\n type JsonObject,\n type JsonValue,\n} from \"@skill-flow/shared-types/protocol\";\nimport type { DraftBinding, ImportDraft, ProjectScope } from \"@skill-flow/domain/types\";\nimport type { SkillFlowApp } from \"@skill-flow/query/runtime\";\n\ntype BridgeFailure = {\n code: string;\n message: string;\n};\n\nexport async function executeBridgeRequest(\n app: SkillFlowApp,\n request: BridgeRequest,\n): Promise<BridgeResponse> {\n try {\n const previousCaller = process.env.SKILL_FLOW_CALLER;\n process.env.SKILL_FLOW_CALLER = previousCaller?.trim() || \"bridge\";\n try {\n switch (request.command) {\n case \"bootstrap\": {\n const result = await app.bootstrapWorkspaceState();\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"list\": {\n const result = await app.listWorkflows();\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"inspect\": {\n const payload = expectObjectPayload(request.payload, \"inspect\");\n const sourceId = expectString(payload.sourceId, \"sourceId\", \"inspect\");\n const scope = expectProjectScope(payload.scope);\n const result = await app.inspectSource(sourceId, scope);\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"inspect-enrichment\": {\n const payload = expectObjectPayload(request.payload, \"inspect-enrichment\");\n const sourceId = expectString(payload.sourceId, \"sourceId\", \"inspect-enrichment\");\n const result = await app.inspectSourceEnrichment(sourceId);\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"search-import-groups\": {\n const payload = expectOptionalObject(request.payload, \"search-import-groups\");\n const query = payload ? expectOptionalString(payload.query, \"query\", \"search-import-groups\") : undefined;\n const result = await app.searchImportGroups(query ?? \"\");\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"preview-import-source\": {\n const payload = expectObjectPayload(request.payload, \"preview-import-source\");\n const locator = expectString(payload.locator, \"locator\", \"preview-import-source\");\n const result = await app.previewImportSource(locator);\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"import-source\": {\n const payload = expectObjectPayload(request.payload, \"import-source\");\n const locator = expectString(payload.locator, \"locator\", \"import-source\");\n const draft = expectOptionalImportDraft(payload.draft);\n const result = await app.importSource(locator, draft);\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"toggle-pin\": {\n const payload = expectObjectPayload(request.payload, \"toggle-pin\");\n const sourceId = expectString(payload.sourceId, \"sourceId\", \"toggle-pin\");\n const result = await app.togglePinnedSource(sourceId);\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"doctor\": {\n const result = await app.doctor();\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"add\": {\n const payload = expectObjectPayload(request.payload, \"add\");\n const locator = expectString(payload.locator, \"locator\", \"add\");\n const options = expectOptionalObject(payload.options, \"add.options\");\n const applyNow = payload.applyNow === true;\n const result = applyNow\n ? await app.addSource(locator, options as Parameters<SkillFlowApp[\"addSource\"]>[1])\n : await app.prepareAddSource(locator, options as Parameters<SkillFlowApp[\"prepareAddSource\"]>[1]);\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"apply\": {\n const payload = expectObjectPayload(request.payload, \"apply\");\n const sourceId = expectString(payload.sourceId, \"sourceId\", \"apply\");\n const draft = expectDraftBinding(payload.draft);\n const scope = expectProjectScope(payload.scope);\n const result = await app.applyDraft(sourceId, draft, scope);\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"update\": {\n const payload = expectOptionalObject(request.payload, \"update\");\n const sourceIds = parseOptionalStringArray(payload?.sourceIds, \"update.sourceIds\");\n const result = await app.updateSources(sourceIds);\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n case \"uninstall\": {\n const payload = expectObjectPayload(request.payload, \"uninstall\");\n const sourceIds = parseRequiredStringArray(payload.sourceIds, \"uninstall.sourceIds\");\n const result = await app.uninstall(sourceIds);\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n });\n }\n case \"save-settings\": {\n const payload = expectObjectPayload(request.payload, \"save-settings\");\n const customTargets = expectCustomTargets(payload.customTargets);\n const agentDisplayOrder = parseOptionalStringArray(\n payload.agentDisplayOrder,\n \"save-settings.agentDisplayOrder\",\n ) ?? [];\n const result = await app.saveSettings({ customTargets, agentDisplayOrder });\n if (!result.ok) {\n return toFailureResponse(request, result.errors, result.warnings);\n }\n return buildResponseWithRequest({\n request,\n ok: true,\n data: sanitizeForJson(result.data),\n warnings: result.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n });\n }\n default:\n return buildResponseWithRequest({\n request,\n ok: false,\n errors: [\n {\n code: \"UNSUPPORTED_COMMAND\",\n message: `Bridge command '${request.command}' is not supported.`,\n },\n ],\n });\n }\n } finally {\n if (previousCaller === undefined) {\n delete process.env.SKILL_FLOW_CALLER;\n } else {\n process.env.SKILL_FLOW_CALLER = previousCaller;\n }\n }\n } catch (error) {\n return buildResponseWithRequest({\n request,\n ok: false,\n errors: [\n {\n code: \"BRIDGE_REQUEST_INVALID\",\n message: error instanceof Error ? error.message : String(error),\n },\n ],\n });\n }\n}\n\nfunction toFailureResponse(\n request: BridgeRequest,\n errors: Array<{ code: string; message: string }>,\n warnings: Array<{ code: string; message: string }>,\n): BridgeResponse {\n return buildResponseWithRequest({\n request,\n ok: false,\n warnings: warnings.map((warning) => ({ code: warning.code, message: warning.message })),\n errors: errors.map((error) => ({ code: error.code, message: error.message })),\n });\n}\n\nfunction buildResponseWithRequest(\n args: Omit<Parameters<typeof buildBridgeResponse>[0], \"command\" | \"requestId\"> & {\n request: BridgeRequest;\n },\n): BridgeResponse {\n return buildBridgeResponse({\n command: args.request.command,\n ...(args.request.requestId ? { requestId: args.request.requestId } : {}),\n ok: args.ok,\n ...(args.data !== undefined ? { data: args.data } : {}),\n ...(args.warnings ? { warnings: args.warnings } : {}),\n ...(args.errors ? { errors: args.errors } : {}),\n });\n}\n\nfunction expectObjectPayload(payload: JsonValue | undefined, command: string): JsonObject {\n if (!isJsonObject(payload)) {\n throw new Error(`Bridge command '${command}' requires an object payload.`);\n }\n return payload;\n}\n\nfunction expectOptionalObject(value: JsonValue | undefined, field: string): JsonObject | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (!isJsonObject(value)) {\n throw new Error(`Field '${field}' must be a JSON object when provided.`);\n }\n return value;\n}\n\nfunction expectString(value: JsonValue | undefined, field: string, command: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(`Bridge command '${command}' requires a non-empty string field '${field}'.`);\n }\n return value;\n}\n\nfunction expectOptionalString(\n value: JsonValue | undefined,\n field: string,\n command: string,\n): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== \"string\") {\n throw new Error(`Bridge command '${command}' requires string field '${field}' when provided.`);\n }\n return value;\n}\n\nfunction parseRequiredStringArray(value: JsonValue | undefined, field: string): string[] {\n const parsed = parseOptionalStringArray(value, field);\n if (!parsed || parsed.length === 0) {\n throw new Error(`Field '${field}' must be a non-empty string array.`);\n }\n return parsed;\n}\n\nfunction parseOptionalStringArray(value: JsonValue | undefined, field: string): string[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\" || item.length === 0)) {\n throw new Error(`Field '${field}' must be a string array.`);\n }\n return value as string[];\n}\n\nfunction expectDraftBinding(value: JsonValue | undefined): DraftBinding {\n if (!isJsonObject(value)) {\n throw new Error(\"Bridge command 'apply' requires object field 'draft'.\");\n }\n const selectedLeafIds = parseOptionalStringArray(value.selectedLeafIds, \"draft.selectedLeafIds\");\n if (!selectedLeafIds) {\n throw new Error(\"Field 'draft.selectedLeafIds' must be a string array.\");\n }\n const enabledTargets = parseOptionalStringArray(value.enabledTargets, \"draft.enabledTargets\") ?? [];\n return {\n selectedLeafIds,\n enabledTargets: enabledTargets as DraftBinding[\"enabledTargets\"],\n };\n}\n\nfunction expectOptionalImportDraft(value: JsonValue | undefined): ImportDraft | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (!isJsonObject(value)) {\n throw new Error(\"Field 'draft' must be a JSON object when provided.\");\n }\n\n const selectedSkillIds = parseOptionalStringArray(value.selectedSkillIds, \"draft.selectedSkillIds\");\n if (!selectedSkillIds) {\n throw new Error(\"Field 'draft.selectedSkillIds' must be a string array.\");\n }\n\n const enabledTargets = parseOptionalStringArray(value.enabledTargets, \"draft.enabledTargets\") ?? [];\n\n return {\n selectedSkillIds,\n enabledTargets: enabledTargets as ImportDraft[\"enabledTargets\"],\n };\n}\n\nfunction expectCustomTargets(value: JsonValue | undefined) {\n if (!Array.isArray(value)) {\n throw new Error(\"Field 'customTargets' must be an array.\");\n }\n\n return value.map((entry, index) => {\n if (!isJsonObject(entry)) {\n throw new Error(`Field 'customTargets[${index}]' must be an object.`);\n }\n\n return {\n id: expectString(entry.id, `customTargets[${index}].id`, \"save-settings\"),\n name: expectString(entry.name, `customTargets[${index}].name`, \"save-settings\"),\n globalPath: expectString(entry.globalPath, `customTargets[${index}].globalPath`, \"save-settings\"),\n projectPathTemplate: expectString(entry.projectPathTemplate, `customTargets[${index}].projectPathTemplate`, \"save-settings\"),\n strategy: expectString(entry.strategy, `customTargets[${index}].strategy`, \"save-settings\") as \"symlink\" | \"copy\",\n createdAt: expectString(entry.createdAt, `customTargets[${index}].createdAt`, \"save-settings\"),\n updatedAt: expectString(entry.updatedAt, `customTargets[${index}].updatedAt`, \"save-settings\"),\n };\n });\n}\n\nfunction expectProjectScope(value: JsonValue | undefined): ProjectScope {\n if (value === undefined) {\n return { kind: \"global\" };\n }\n\n if (!isJsonObject(value) || typeof value.kind !== \"string\") {\n throw new Error(\n \"Field 'scope' must be a JSON object with kind 'global' or kind 'project' and a non-empty string 'projectId'.\",\n );\n }\n\n if (value.kind === \"global\") {\n return { kind: \"global\" };\n }\n\n if (value.kind === \"project\") {\n if (typeof value.projectId === \"string\" && value.projectId.length > 0) {\n return { kind: \"project\", projectId: value.projectId };\n }\n\n throw new Error(\"Field 'scope.projectId' must be a non-empty string when scope.kind is 'project'.\");\n }\n\n throw new Error(\"Field 'scope.kind' must be either 'global' or 'project'.\");\n}\n\nfunction sanitizeForJson<T>(value: T): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n}\n\nexport function buildBridgeParseFailure(command: string, failure: BridgeFailure): BridgeResponse {\n return buildBridgeResponse({\n command: command as BridgeRequest[\"command\"],\n ok: false,\n errors: [failure],\n });\n}\n"],
5
+ "mappings": ";;;AAEA,SAAS,eAAe;AACxB,SAAS,cAAc;;;ACHvB;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,MAAQ;AAAA,EACR,MAAQ;AAAA,EACR,KAAO;AAAA,IACL,cAAc;AAAA,EAChB;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,KAAO;AAAA,IACP,SAAW;AAAA,IACX,UAAY;AAAA,IACZ,MAAQ;AAAA,IACR,cAAc;AAAA,EAChB;AAAA,EACA,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,QAAU;AAAA,EACV,SAAW;AAAA,EACX,MAAQ;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,EACZ,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,cAAgB;AAAA,IACd,2BAA2B;AAAA,IAC3B,sBAAsB;AAAA,IACtB,2BAA2B;AAAA,IAC3B,qBAAqB;AAAA,IACrB,4BAA4B;AAAA,IAC5B,uBAAuB;AAAA,IACvB,mBAAmB;AAAA,IACnB,WAAa;AAAA,IACb,KAAO;AAAA,IACP,OAAS;AAAA,EACX;AAAA,EACA,iBAAmB;AAAA,IACjB,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,SAAW;AAAA,IACX,KAAO;AAAA,IACP,YAAc;AAAA,IACd,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Q,CAAC,WAAW;AAClB,oBAAQ,MAAM;AACd,qBAAS,QAAQ;AAAA,UACnB;AAAA;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAEA,eAAe,YAA6B;AAC1C,QAAM,SAAmB,CAAC;AAC1B,mBAAiB,SAAS,QAAQ,OAAO;AACvC,WAAO,KAAK,OAAO,SAAS,KAAK,IAAI,QAAQ,OAAO,KAAK,KAAK,CAAC;AAAA,EACjE;AACA,SAAO,OAAO,OAAO,MAAM,EAAE,SAAS,MAAM;AAC9C;AAEA,SAAS,oBACP,QACA,SACA;AACA,MAAI,OAAO,WAAW,WAAW;AAC/B,QAAI,CAAC,SAAS,UAAU;AACtB,cAAQ,IAAI,OAAO,OAAO;AAAA,IAC5B;AACA,kBAAc,kBAAkB,OAAO,QAAQ,CAAC;AAChD;AAAA,EACF;AAEA,MAAI,OAAO,WAAW,aAAa;AACjC,YAAQ,IAAI,OAAO,OAAO;AAC1B;AAAA,EACF;AAEA,cAAY,CAAC,EAAE,SAAS,OAAO,QAAQ,CAAC,CAAC;AACzC,gBAAc,kBAAkB,OAAO,YAAY,CAAC,CAAC,CAAC;AACtD,UAAQ,WAAW;AACrB;AAEA,SAAS,cAAc,OAAe,UAAoB;AACxD,SAAO,CAAC,GAAG,UAAU,KAAK;AAC5B;",
6
+ "names": ["fs", "path", "path", "path", "path", "path", "fs", "path", "normalizeSourceStats", "normalizeString", "normalizeNumber", "path", "fs", "host", "owner", "repo", "os", "path", "fs", "createProviderError", "path", "path", "createProviderError", "createProviderError", "fs", "path", "path", "fs", "fs", "path", "path", "fs", "path", "fs", "path", "fs", "fs", "path", "path", "fs", "fs", "fs", "os", "path", "fs", "path", "os", "execFile", "promisify", "execFileAsync", "fs", "crypto", "execFile", "fs", "path", "promisify", "execFileAsync", "promisify", "execFile", "crypto", "fs", "path", "fs", "os", "path", "path", "fs", "os", "resolveUsableProjectPath", "fs", "path", "manifest", "lockFile", "prepared", "plan", "applyResult", "freshState", "useEffect", "useState", "Box", "Text", "useApp", "useInput", "normalizeRequestedPath", "app", "nextWarnings", "EMPTY_DRAFT", "group", "EMPTY_DRAFT", "app", "useApp", "useState", "useEffect", "useInput", "enabledTargets", "target", "baseState", "nextState", "_jsxs", "Box", "_jsx", "Text", "_jsxs", "Text", "Box", "_jsx", "useEffect", "useMemo", "useState", "Box", "Text", "useApp", "useInput", "useStdout", "app", "useApp", "useStdout", "useState", "useMemo", "useEffect", "useInput", "_jsxs", "Box", "_jsx", "Text", "app", "result", "summary", "app"]
7
+ }