@cleocode/caamp 1.9.0 → 2026.3.74
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/README.md +2 -2
- package/dist/{chunk-ER3FIOTM.js → chunk-J7UN457C.js} +2 -2
- package/dist/chunk-J7UN457C.js.map +1 -0
- package/dist/{chunk-MFWBR2NY.js → chunk-O7IVK5JY.js} +2 -2
- package/dist/chunk-O7IVK5JY.js.map +1 -0
- package/dist/{chunk-TRIXT4T7.js → chunk-TI6WOJDG.js} +1 -1
- package/dist/chunk-TI6WOJDG.js.map +1 -0
- package/dist/{chunk-OLJZ23W3.js → chunk-ZF4W3K5H.js} +36 -3
- package/dist/chunk-ZF4W3K5H.js.map +1 -0
- package/dist/cli.d.ts +0 -0
- package/dist/cli.js +18 -12
- package/dist/cli.js.map +1 -1
- package/dist/{hooks-LV6VU7QJ.js → hooks-E2XQ7TQG.js} +3 -3
- package/dist/{hooks-LV6VU7QJ.js.map → hooks-E2XQ7TQG.js.map} +0 -0
- package/dist/index.d.ts +3492 -198
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/{injector-P2OL6RK3.js → injector-NSDP5Z2P.js} +3 -3
- package/dist/{injector-P2OL6RK3.js.map → injector-NSDP5Z2P.js.map} +0 -0
- package/package.json +2 -2
- package/providers/hook-mappings.json +0 -0
- package/providers/registry.json +0 -0
- package/dist/chunk-ER3FIOTM.js.map +0 -1
- package/dist/chunk-MFWBR2NY.js.map +0 -1
- package/dist/chunk-OLJZ23W3.js.map +0 -1
- package/dist/chunk-TRIXT4T7.js.map +0 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/commands/advanced/common.ts","../src/commands/advanced/lafs.ts","../src/commands/advanced/providers.ts","../src/commands/advanced/batch.ts","../src/commands/advanced/conflicts.ts","../src/commands/advanced/apply.ts","../src/commands/advanced/instructions.ts","../src/commands/advanced/configure.ts","../src/commands/advanced/index.ts","../src/commands/config.ts","../src/core/lafs.ts","../src/commands/doctor.ts","../src/core/version.ts","../src/commands/instructions/inject.ts","../src/commands/instructions/check.ts","../src/commands/instructions/update.ts","../src/commands/instructions/index.ts","../src/commands/mcp/cleo.ts","../src/commands/mcp/detect.ts","../src/commands/mcp/install.ts","../src/commands/mcp/list.ts","../src/commands/mcp/remove.ts","../src/commands/mcp/index.ts","../src/commands/providers.ts","../src/commands/skills/install.ts","../src/core/sources/github.ts","../src/core/sources/gitlab.ts","../src/commands/skills/remove.ts","../src/commands/skills/list.ts","../src/commands/skills/find.ts","../src/commands/skills/check.ts","../src/commands/skills/update.ts","../src/commands/skills/init.ts","../src/commands/skills/audit.ts","../src/commands/skills/validate.ts","../src/commands/skills/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * CAAMP CLI - Central AI Agent Managed Packages\n */\n\nimport { Command } from \"commander\";\nimport { registerAdvancedCommands } from \"./commands/advanced/index.js\";\nimport { registerConfigCommand } from \"./commands/config.js\";\nimport { registerDoctorCommand } from \"./commands/doctor.js\";\nimport { registerInstructionsCommands } from \"./commands/instructions/index.js\";\nimport { registerCleoCommands } from \"./commands/mcp/cleo.js\";\nimport { registerMcpCommands } from \"./commands/mcp/index.js\";\nimport { registerProvidersCommand } from \"./commands/providers.js\";\nimport { registerSkillsCommands } from \"./commands/skills/index.js\";\nimport { isVerbose, setHuman, setQuiet, setVerbose } from \"./core/logger.js\";\nimport { getCaampVersion } from \"./core/version.js\";\n\nconst program = new Command();\n\nprogram\n .name(\"caamp\")\n .description(\"Central AI Agent Managed Packages - unified provider registry and package manager\")\n .version(getCaampVersion())\n .option(\"-v, --verbose\", \"Show debug output\")\n .option(\"-q, --quiet\", \"Suppress non-error output\")\n .option(\"--human\", \"Output in human-readable format (default: JSON for LLM agents)\");\n\nprogram.hook(\"preAction\", (thisCommand) => {\n const opts = thisCommand.optsWithGlobals();\n if (opts.verbose) setVerbose(true);\n if (opts.quiet) setQuiet(true);\n if (opts.human) setHuman(true);\n});\n\n// Register command groups\nregisterProvidersCommand(program);\nregisterSkillsCommands(program);\nregisterMcpCommands(program);\nregisterCleoCommands(program);\nregisterInstructionsCommands(program);\nregisterConfigCommand(program);\nregisterDoctorCommand(program);\nregisterAdvancedCommands(program);\n\nfunction toError(error: unknown): Error {\n if (error instanceof Error) return error;\n return new Error(String(error));\n}\n\nfunction handleFatal(error: unknown, source: \"uncaughtException\" | \"unhandledRejection\" | \"cli\"): void {\n const normalized = toError(error);\n console.error(`Fatal error (${source}): ${normalized.message}`);\n if (isVerbose() && normalized.stack) {\n console.error(normalized.stack);\n }\n}\n\nprocess.on(\"uncaughtException\", (error) => {\n handleFatal(error, \"uncaughtException\");\n process.exit(1);\n});\n\nprocess.on(\"unhandledRejection\", (reason) => {\n handleFatal(reason, \"unhandledRejection\");\n process.exit(1);\n});\n\nasync function main(): Promise<void> {\n await program.parseAsync(process.argv);\n}\n\nmain().catch((error) => {\n handleFatal(error, \"cli\");\n process.exit(1);\n});\n","/**\n * Shared helpers for advanced command input parsing and validation.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport type {\n McpBatchOperation,\n SkillBatchOperation,\n} from \"../../core/advanced/orchestration.js\";\nimport type { Provider, ProviderPriority } from \"../../types.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getAllProviders, getProvider } from \"../../core/registry/providers.js\";\nimport { LAFSCommandError } from \"./lafs.js\";\n\nconst VALID_PRIORITIES = new Set<ProviderPriority>([\"high\", \"medium\", \"low\"]);\n\nexport interface ProviderTargetOptions {\n all?: boolean;\n agent?: string[];\n}\n\nexport function parsePriority(value: string): ProviderPriority {\n if (!VALID_PRIORITIES.has(value as ProviderPriority)) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_PRIORITY\",\n `Invalid tier: ${value}`,\n \"Use one of: high, medium, low.\",\n );\n }\n return value as ProviderPriority;\n}\n\nexport function resolveProviders(options: ProviderTargetOptions): Provider[] {\n if (options.all) {\n return getAllProviders();\n }\n\n const targetAgents = options.agent ?? [];\n if (targetAgents.length === 0) {\n return getInstalledProviders();\n }\n\n const providers = targetAgents\n .map((id) => getProvider(id))\n .filter((provider): provider is Provider => provider !== undefined);\n\n if (providers.length !== targetAgents.length) {\n const found = new Set(providers.map((provider) => provider.id));\n const missing = targetAgents.filter((id) => !found.has(id));\n throw new LAFSCommandError(\n \"E_ADVANCED_PROVIDER_NOT_FOUND\",\n `Unknown provider(s): ${missing.join(\", \")}`,\n \"Check `caamp providers list` for valid provider IDs/aliases.\",\n );\n }\n\n return providers;\n}\n\nexport async function readJsonFile(path: string): Promise<unknown> {\n try {\n const raw = await readFile(path, \"utf-8\");\n return JSON.parse(raw) as unknown;\n } catch (error) {\n throw new LAFSCommandError(\n \"E_ADVANCED_INPUT_JSON\",\n `Failed to read JSON file: ${path}`,\n \"Confirm the path exists and contains valid JSON.\",\n true,\n { reason: error instanceof Error ? error.message : String(error) },\n );\n }\n}\n\nexport async function readMcpOperations(path: string): Promise<McpBatchOperation[]> {\n const value = await readJsonFile(path);\n if (!Array.isArray(value)) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_MCP_ARRAY\",\n `MCP operations file must be a JSON array: ${path}`,\n \"Provide an array of objects with serverName and config fields.\",\n );\n }\n\n const operations: McpBatchOperation[] = [];\n for (const [index, item] of value.entries()) {\n if (!item || typeof item !== \"object\") {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_MCP_ITEM\",\n `Invalid MCP operation at index ${index}`,\n \"Each operation must be an object with serverName and config.\",\n );\n }\n\n const obj = item as Record<string, unknown>;\n const serverName = obj.serverName;\n const config = obj.config;\n const scope = obj.scope;\n\n if (typeof serverName !== \"string\" || serverName.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_MCP_NAME\",\n `Invalid serverName at index ${index}`,\n \"Set serverName to a non-empty string.\",\n );\n }\n\n if (!config || typeof config !== \"object\" || Array.isArray(config)) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_MCP_CONFIG\",\n `Invalid config at index ${index}`,\n \"Set config to an object matching McpServerConfig.\",\n );\n }\n\n if (scope !== undefined && scope !== \"project\" && scope !== \"global\") {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SCOPE\",\n `Invalid scope at index ${index}: ${String(scope)}`,\n \"Use scope value 'project' or 'global'.\",\n );\n }\n\n operations.push({\n serverName,\n config: config as McpBatchOperation[\"config\"],\n ...(scope ? { scope: scope as \"project\" | \"global\" } : {}),\n });\n }\n\n return operations;\n}\n\nexport async function readSkillOperations(path: string): Promise<SkillBatchOperation[]> {\n const value = await readJsonFile(path);\n if (!Array.isArray(value)) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SKILL_ARRAY\",\n `Skill operations file must be a JSON array: ${path}`,\n \"Provide an array of objects with sourcePath and skillName fields.\",\n );\n }\n\n const operations: SkillBatchOperation[] = [];\n for (const [index, item] of value.entries()) {\n if (!item || typeof item !== \"object\") {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SKILL_ITEM\",\n `Invalid skill operation at index ${index}`,\n \"Each operation must be an object with sourcePath and skillName.\",\n );\n }\n\n const obj = item as Record<string, unknown>;\n const sourcePath = obj.sourcePath;\n const skillName = obj.skillName;\n const isGlobal = obj.isGlobal;\n\n if (typeof sourcePath !== \"string\" || sourcePath.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SKILL_SOURCE\",\n `Invalid sourcePath at index ${index}`,\n \"Set sourcePath to a non-empty string.\",\n );\n }\n\n if (typeof skillName !== \"string\" || skillName.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SKILL_NAME\",\n `Invalid skillName at index ${index}`,\n \"Set skillName to a non-empty string.\",\n );\n }\n\n if (isGlobal !== undefined && typeof isGlobal !== \"boolean\") {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SKILL_SCOPE\",\n `Invalid isGlobal value at index ${index}`,\n \"Set isGlobal to true or false when provided.\",\n );\n }\n\n operations.push({\n sourcePath,\n skillName,\n ...(isGlobal !== undefined ? { isGlobal } : {}),\n });\n }\n\n return operations;\n}\n\nexport async function readTextInput(\n inlineContent: string | undefined,\n filePath: string | undefined,\n): Promise<string | undefined> {\n if (inlineContent && filePath) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_INPUT_MODE\",\n \"Provide either inline content or a content file, not both.\",\n \"Use --content OR --content-file.\",\n );\n }\n\n if (inlineContent) return inlineContent;\n if (!filePath) return undefined;\n\n try {\n return await readFile(filePath, \"utf-8\");\n } catch (error) {\n throw new LAFSCommandError(\n \"E_ADVANCED_INPUT_TEXT\",\n `Failed to read content file: ${filePath}`,\n \"Confirm the file exists and is readable.\",\n true,\n { reason: error instanceof Error ? error.message : String(error) },\n );\n }\n}\n","/**\n * LAFS-compliant output helpers for advanced CLI commands.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n isRegisteredErrorCode,\n type LAFSErrorCategory,\n type LAFSMeta,\n type LAFSError,\n type LAFSPage,\n} from \"@cleocode/lafs-protocol\";\nimport type { MVILevel } from \"../../core/lafs.js\";\n\n/**\n * Generic LAFS result envelope for advanced commands.\n * Uses protocol types directly for full compliance.\n */\ntype LAFSResultEnvelope<T> = {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\";\n _meta: LAFSMeta;\n success: boolean;\n result: T | null;\n error: LAFSError | null;\n page: LAFSPage | null;\n};\n\nexport class LAFSCommandError extends Error {\n code: string;\n category: LAFSErrorCategory;\n recoverable: boolean;\n suggestion: string;\n retryAfterMs: number | null;\n details?: unknown;\n\n constructor(\n code: string,\n message: string,\n suggestion: string,\n recoverable = true,\n details?: unknown,\n ) {\n super(message);\n this.name = \"LAFSCommandError\";\n this.code = code;\n this.category = inferErrorCategory(code);\n this.recoverable = recoverable;\n this.suggestion = suggestion;\n this.retryAfterMs = null;\n this.details = details;\n }\n}\n\nfunction inferErrorCategory(code: string): LAFSErrorCategory {\n if (code.includes(\"VALIDATION\")) return \"VALIDATION\";\n if (code.includes(\"NOT_FOUND\")) return \"NOT_FOUND\";\n if (code.includes(\"CONFLICT\")) return \"CONFLICT\";\n if (code.includes(\"AUTH\")) return \"AUTH\";\n if (code.includes(\"PERMISSION\")) return \"PERMISSION\";\n if (code.includes(\"RATE_LIMIT\")) return \"RATE_LIMIT\";\n if (code.includes(\"MIGRATION\")) return \"MIGRATION\";\n if (code.includes(\"CONTRACT\")) return \"CONTRACT\";\n return \"INTERNAL\";\n}\n\nfunction baseMeta(operation: string, mvi: MVILevel): LAFSMeta {\n return {\n specVersion: \"1.0.0\",\n schemaVersion: \"1.0.0\",\n timestamp: new Date().toISOString(),\n operation,\n requestId: randomUUID(),\n transport: \"cli\",\n strict: true,\n mvi,\n contextVersion: 0,\n };\n}\n\nexport function emitSuccess<T>(operation: string, result: T, mvi: MVILevel = \"standard\"): void {\n const envelope: LAFSResultEnvelope<T> = {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\",\n _meta: {\n ...baseMeta(operation, mvi),\n },\n success: true,\n result,\n error: null,\n page: null,\n };\n console.log(JSON.stringify(envelope, null, 2));\n}\n\nexport function emitError(operation: string, error: unknown, mvi: MVILevel = \"standard\"): void {\n let envelope: LAFSResultEnvelope<null>;\n\n if (error instanceof LAFSCommandError) {\n envelope = {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\",\n _meta: {\n ...baseMeta(operation, mvi),\n },\n success: false,\n result: null,\n error: {\n code: isRegisteredErrorCode(error.code) ? error.code : \"E_INTERNAL_UNEXPECTED\",\n message: error.message,\n category: error.category,\n retryable: error.recoverable,\n retryAfterMs: error.retryAfterMs,\n details: {\n hint: error.suggestion,\n ...(error.details !== undefined ? { payload: error.details } : {}),\n },\n },\n page: null,\n };\n } else {\n envelope = {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\",\n _meta: {\n ...baseMeta(operation, mvi),\n },\n success: false,\n result: null,\n error: {\n code: \"E_INTERNAL_UNEXPECTED\",\n message: error instanceof Error ? error.message : String(error),\n category: \"INTERNAL\",\n retryable: false,\n retryAfterMs: null,\n details: {\n hint: \"Rerun with --verbose and validate your inputs.\",\n },\n },\n page: null,\n };\n }\n\n console.error(JSON.stringify(envelope, null, 2));\n}\n\nexport async function runLafsCommand<T>(\n command: string,\n mvi: MVILevel,\n action: () => Promise<T>,\n): Promise<void> {\n try {\n const result = await action();\n emitSuccess(command, result, mvi);\n } catch (error) {\n emitError(command, error, mvi);\n process.exit(1);\n }\n}\n","/**\n * advanced providers command\n */\n\nimport type { Command } from \"commander\";\nimport { selectProvidersByMinimumPriority } from \"../../core/advanced/orchestration.js\";\nimport { parsePriority, resolveProviders } from \"./common.js\";\nimport { runLafsCommand } from \"./lafs.js\";\n\nexport function registerAdvancedProviders(parent: Command): void {\n parent\n .command(\"providers\")\n .description(\"Select providers by priority using advanced wrapper logic\")\n .option(\"-a, --agent <name>\", \"Target specific provider(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--all\", \"Use all registry providers (not only detected)\")\n .option(\"--min-tier <tier>\", \"Minimum priority tier: high|medium|low\", \"low\")\n .option(\"--details\", \"Include full provider objects\")\n .action(async (opts: {\n agent: string[];\n all?: boolean;\n minTier: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.providers\", opts.details ? \"full\" : \"standard\", async () => {\n const providers = resolveProviders({ all: opts.all, agent: opts.agent });\n const minTier = parsePriority(opts.minTier);\n const selected = selectProvidersByMinimumPriority(providers, minTier);\n\n return {\n objective: \"Filter providers by minimum priority tier\",\n constraints: {\n minTier,\n selectionMode: opts.all ? \"registry\" : \"detected-or-explicit\",\n },\n acceptanceCriteria: {\n selectedCount: selected.length,\n orderedByPriority: true,\n },\n data: opts.details\n ? selected\n : selected.map((provider) => ({\n id: provider.id,\n priority: provider.priority,\n status: provider.status,\n configFormat: provider.configFormat,\n })),\n };\n }));\n}\n","/**\n * advanced batch command\n */\n\nimport type { Command } from \"commander\";\nimport { installBatchWithRollback, selectProvidersByMinimumPriority } from \"../../core/advanced/orchestration.js\";\nimport { parsePriority, readMcpOperations, readSkillOperations, resolveProviders } from \"./common.js\";\nimport { LAFSCommandError, runLafsCommand } from \"./lafs.js\";\n\nexport function registerAdvancedBatch(parent: Command): void {\n parent\n .command(\"batch\")\n .description(\"Run rollback-capable batch install for MCP + skills\")\n .option(\"-a, --agent <name>\", \"Target specific provider(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--all\", \"Use all registry providers (not only detected)\")\n .option(\"--min-tier <tier>\", \"Minimum priority tier: high|medium|low\", \"low\")\n .option(\"--mcp-file <path>\", \"JSON file containing McpBatchOperation[]\")\n .option(\"--skills-file <path>\", \"JSON file containing SkillBatchOperation[]\")\n .option(\"--project-dir <path>\", \"Project directory to resolve project-scope paths\")\n .option(\"--details\", \"Include detailed operation result\")\n .action(async (opts: {\n agent: string[];\n all?: boolean;\n minTier: string;\n mcpFile?: string;\n skillsFile?: string;\n projectDir?: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.batch\", opts.details ? \"full\" : \"standard\", async () => {\n const baseProviders = resolveProviders({ all: opts.all, agent: opts.agent });\n const minimumPriority = parsePriority(opts.minTier);\n const providers = selectProvidersByMinimumPriority(baseProviders, minimumPriority);\n\n const mcp = opts.mcpFile ? await readMcpOperations(opts.mcpFile) : [];\n const skills = opts.skillsFile ? await readSkillOperations(opts.skillsFile) : [];\n\n if (mcp.length === 0 && skills.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_NO_OPS\",\n \"No operations provided.\",\n \"Provide --mcp-file and/or --skills-file.\",\n );\n }\n\n if (providers.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_NO_TARGET_PROVIDERS\",\n \"No target providers resolved for this batch operation.\",\n \"Use --all or pass provider IDs with --agent.\",\n );\n }\n\n const result = await installBatchWithRollback({\n providers,\n minimumPriority,\n mcp,\n skills,\n projectDir: opts.projectDir,\n });\n\n if (!result.success) {\n throw new LAFSCommandError(\n \"E_ADVANCED_BATCH_FAILED\",\n result.error ?? \"Batch operation failed.\",\n \"Check rollbackErrors and input configs, then retry.\",\n true,\n result,\n );\n }\n\n return {\n objective: \"Install MCP and skills with rollback safety\",\n constraints: {\n minimumPriority,\n providerCount: providers.length,\n mcpOps: mcp.length,\n skillOps: skills.length,\n },\n acceptanceCriteria: {\n success: result.success,\n rollbackPerformed: result.rollbackPerformed,\n },\n data: opts.details\n ? result\n : {\n providerCount: result.providerIds.length,\n mcpApplied: result.mcpApplied,\n skillsApplied: result.skillsApplied,\n rollbackPerformed: result.rollbackPerformed,\n },\n };\n }));\n}\n","/**\n * advanced conflicts command\n */\n\nimport type { Command } from \"commander\";\nimport { detectMcpConfigConflicts, selectProvidersByMinimumPriority } from \"../../core/advanced/orchestration.js\";\nimport { parsePriority, readMcpOperations, resolveProviders } from \"./common.js\";\nimport { LAFSCommandError, runLafsCommand } from \"./lafs.js\";\n\nexport function registerAdvancedConflicts(parent: Command): void {\n parent\n .command(\"conflicts\")\n .description(\"Preflight MCP conflict detection across providers\")\n .requiredOption(\"--mcp-file <path>\", \"JSON file containing McpBatchOperation[]\")\n .option(\"-a, --agent <name>\", \"Target specific provider(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--all\", \"Use all registry providers (not only detected)\")\n .option(\"--min-tier <tier>\", \"Minimum priority tier: high|medium|low\", \"low\")\n .option(\"--project-dir <path>\", \"Project directory to resolve project-scope paths\")\n .option(\"--details\", \"Include full conflict list\")\n .action(async (opts: {\n mcpFile: string;\n agent: string[];\n all?: boolean;\n minTier: string;\n projectDir?: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.conflicts\", opts.details ? \"full\" : \"standard\", async () => {\n const baseProviders = resolveProviders({ all: opts.all, agent: opts.agent });\n const minimumPriority = parsePriority(opts.minTier);\n const providers = selectProvidersByMinimumPriority(baseProviders, minimumPriority);\n const operations = await readMcpOperations(opts.mcpFile);\n\n if (providers.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_NO_TARGET_PROVIDERS\",\n \"No target providers resolved for conflict detection.\",\n \"Use --all or pass provider IDs with --agent.\",\n );\n }\n\n const conflicts = await detectMcpConfigConflicts(\n providers,\n operations,\n opts.projectDir,\n );\n\n const countByCode = conflicts.reduce<Record<string, number>>((acc, conflict) => {\n acc[conflict.code] = (acc[conflict.code] ?? 0) + 1;\n return acc;\n }, {});\n\n return {\n objective: \"Detect MCP configuration conflicts before mutation\",\n constraints: {\n minimumPriority,\n providerCount: providers.length,\n operationCount: operations.length,\n },\n acceptanceCriteria: {\n conflictCount: conflicts.length,\n },\n data: opts.details\n ? conflicts\n : {\n conflictCount: conflicts.length,\n countByCode,\n sample: conflicts.slice(0, 5),\n },\n };\n }));\n}\n","/**\n * advanced apply command\n */\n\nimport type { Command } from \"commander\";\nimport {\n applyMcpInstallWithPolicy,\n selectProvidersByMinimumPriority,\n type ConflictPolicy,\n} from \"../../core/advanced/orchestration.js\";\nimport { parsePriority, readMcpOperations, resolveProviders } from \"./common.js\";\nimport { LAFSCommandError, runLafsCommand } from \"./lafs.js\";\n\nconst VALID_POLICIES = new Set<ConflictPolicy>([\"fail\", \"skip\", \"overwrite\"]);\n\nfunction parsePolicy(value: string): ConflictPolicy {\n if (!VALID_POLICIES.has(value as ConflictPolicy)) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_POLICY\",\n `Invalid policy: ${value}`,\n \"Use one of: fail, skip, overwrite.\",\n );\n }\n return value as ConflictPolicy;\n}\n\nexport function registerAdvancedApply(parent: Command): void {\n parent\n .command(\"apply\")\n .description(\"Apply MCP operations with configurable conflict policy\")\n .requiredOption(\"--mcp-file <path>\", \"JSON file containing McpBatchOperation[]\")\n .option(\"--policy <policy>\", \"Conflict policy: fail|skip|overwrite\", \"fail\")\n .option(\"-a, --agent <name>\", \"Target specific provider(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--all\", \"Use all registry providers (not only detected)\")\n .option(\"--min-tier <tier>\", \"Minimum priority tier: high|medium|low\", \"low\")\n .option(\"--project-dir <path>\", \"Project directory to resolve project-scope paths\")\n .option(\"--details\", \"Include detailed apply result\")\n .action(async (opts: {\n mcpFile: string;\n policy: string;\n agent: string[];\n all?: boolean;\n minTier: string;\n projectDir?: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.apply\", opts.details ? \"full\" : \"standard\", async () => {\n const baseProviders = resolveProviders({ all: opts.all, agent: opts.agent });\n const minimumPriority = parsePriority(opts.minTier);\n const providers = selectProvidersByMinimumPriority(baseProviders, minimumPriority);\n const operations = await readMcpOperations(opts.mcpFile);\n const policy = parsePolicy(opts.policy);\n\n if (providers.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_NO_TARGET_PROVIDERS\",\n \"No target providers resolved for apply operation.\",\n \"Use --all or pass provider IDs with --agent.\",\n );\n }\n\n const result = await applyMcpInstallWithPolicy(\n providers,\n operations,\n policy,\n opts.projectDir,\n );\n\n if (policy === \"fail\" && result.conflicts.length > 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_CONFLICTS_BLOCKING\",\n \"Conflicts detected and policy is set to fail.\",\n \"Run `caamp advanced conflicts` to inspect, or rerun with --policy skip/overwrite.\",\n true,\n result,\n );\n }\n\n const failedWrites = result.applied.filter((entry) => !entry.success);\n if (failedWrites.length > 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_APPLY_WRITE_FAILED\",\n \"One or more MCP writes failed.\",\n \"Check result details, fix provider config issues, and retry.\",\n true,\n result,\n );\n }\n\n return {\n objective: \"Apply MCP operations with policy-driven conflict handling\",\n constraints: {\n policy,\n minimumPriority,\n providerCount: providers.length,\n operationCount: operations.length,\n },\n acceptanceCriteria: {\n conflicts: result.conflicts.length,\n writesSucceeded: result.applied.length,\n },\n data: opts.details\n ? result\n : {\n conflicts: result.conflicts.length,\n applied: result.applied.length,\n skipped: result.skipped.length,\n },\n };\n }));\n}\n","/**\n * advanced instructions command\n */\n\nimport type { Command } from \"commander\";\nimport {\n selectProvidersByMinimumPriority,\n updateInstructionsSingleOperation,\n} from \"../../core/advanced/orchestration.js\";\nimport { parsePriority, readTextInput, resolveProviders } from \"./common.js\";\nimport { LAFSCommandError, runLafsCommand } from \"./lafs.js\";\n\nexport function registerAdvancedInstructions(parent: Command): void {\n parent\n .command(\"instructions\")\n .description(\"Single-operation instruction update across providers\")\n .option(\"-a, --agent <name>\", \"Target specific provider(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--all\", \"Use all registry providers (not only detected)\")\n .option(\"--min-tier <tier>\", \"Minimum priority tier: high|medium|low\", \"low\")\n .option(\"--scope <scope>\", \"Instruction scope: project|global\", \"project\")\n .option(\"--content <text>\", \"Inline content to inject\")\n .option(\"--content-file <path>\", \"File containing content to inject\")\n .option(\"--project-dir <path>\", \"Project directory to resolve project-scope paths\")\n .option(\"--details\", \"Include detailed per-file actions\")\n .action(async (opts: {\n agent: string[];\n all?: boolean;\n minTier: string;\n scope: string;\n content?: string;\n contentFile?: string;\n projectDir?: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.instructions\", opts.details ? \"full\" : \"standard\", async () => {\n const minimumPriority = parsePriority(opts.minTier);\n const baseProviders = resolveProviders({ all: opts.all, agent: opts.agent });\n const providers = selectProvidersByMinimumPriority(baseProviders, minimumPriority);\n\n const scope = opts.scope === \"global\" ? \"global\" : opts.scope === \"project\" ? \"project\" : null;\n if (!scope) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SCOPE\",\n `Invalid scope: ${opts.scope}`,\n \"Use --scope project or --scope global.\",\n );\n }\n\n const content = await readTextInput(opts.content, opts.contentFile);\n if (!content || content.trim().length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_CONTENT\",\n \"Instruction content is required.\",\n \"Provide --content or --content-file with non-empty text.\",\n );\n }\n\n if (providers.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_NO_TARGET_PROVIDERS\",\n \"No target providers resolved for instruction update.\",\n \"Use --all or pass provider IDs with --agent.\",\n );\n }\n\n const summary = await updateInstructionsSingleOperation(\n providers,\n content,\n scope,\n opts.projectDir,\n );\n\n return {\n objective: \"Update instruction files across providers in one operation\",\n constraints: {\n scope,\n minimumPriority,\n providerCount: providers.length,\n },\n acceptanceCriteria: {\n updatedFiles: summary.updatedFiles,\n },\n data: opts.details\n ? summary\n : {\n updatedFiles: summary.updatedFiles,\n files: summary.actions.map((entry) => ({\n file: entry.file,\n action: entry.action,\n })),\n },\n };\n }));\n}\n","/**\n * advanced configure command\n */\n\nimport type { Command } from \"commander\";\nimport { configureProviderGlobalAndProject } from \"../../core/advanced/orchestration.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport { readMcpOperations, readTextInput } from \"./common.js\";\nimport { LAFSCommandError, runLafsCommand } from \"./lafs.js\";\n\nexport function registerAdvancedConfigure(parent: Command): void {\n parent\n .command(\"configure\")\n .description(\"Configure global + project scope for one provider in one operation\")\n .requiredOption(\"-a, --agent <name>\", \"Target provider ID or alias\")\n .option(\"--global-mcp-file <path>\", \"JSON file for global MCP operations\")\n .option(\"--project-mcp-file <path>\", \"JSON file for project MCP operations\")\n .option(\"--instruction <text>\", \"Instruction content for both scopes\")\n .option(\"--instruction-file <path>\", \"Instruction content file for both scopes\")\n .option(\"--instruction-global <text>\", \"Instruction content for global scope\")\n .option(\"--instruction-global-file <path>\", \"Instruction content file for global scope\")\n .option(\"--instruction-project <text>\", \"Instruction content for project scope\")\n .option(\"--instruction-project-file <path>\", \"Instruction content file for project scope\")\n .option(\"--project-dir <path>\", \"Project directory to resolve project-scope paths\")\n .option(\"--details\", \"Include detailed write results\")\n .action(async (opts: {\n agent: string;\n globalMcpFile?: string;\n projectMcpFile?: string;\n instruction?: string;\n instructionFile?: string;\n instructionGlobal?: string;\n instructionGlobalFile?: string;\n instructionProject?: string;\n instructionProjectFile?: string;\n projectDir?: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.configure\", opts.details ? \"full\" : \"standard\", async () => {\n const provider = getProvider(opts.agent);\n if (!provider) {\n throw new LAFSCommandError(\n \"E_ADVANCED_PROVIDER_NOT_FOUND\",\n `Unknown provider: ${opts.agent}`,\n \"Check `caamp providers list` for valid provider IDs/aliases.\",\n );\n }\n\n const globalMcp = opts.globalMcpFile\n ? await readMcpOperations(opts.globalMcpFile)\n : [];\n const projectMcp = opts.projectMcpFile\n ? await readMcpOperations(opts.projectMcpFile)\n : [];\n\n const sharedInstruction = await readTextInput(opts.instruction, opts.instructionFile);\n const globalInstruction = await readTextInput(\n opts.instructionGlobal,\n opts.instructionGlobalFile,\n );\n const projectInstruction = await readTextInput(\n opts.instructionProject,\n opts.instructionProjectFile,\n );\n\n let instructionContent:\n | string\n | { global?: string; project?: string }\n | undefined;\n\n if (globalInstruction || projectInstruction) {\n instructionContent = {\n ...(globalInstruction ? { global: globalInstruction } : {}),\n ...(projectInstruction ? { project: projectInstruction } : {}),\n };\n } else if (sharedInstruction) {\n instructionContent = sharedInstruction;\n }\n\n if (globalMcp.length === 0 && projectMcp.length === 0 && !instructionContent) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_NO_OPS\",\n \"No configuration operations were provided.\",\n \"Provide MCP files and/or instruction content.\",\n );\n }\n\n const result = await configureProviderGlobalAndProject(provider, {\n globalMcp: globalMcp.map((entry) => ({\n serverName: entry.serverName,\n config: entry.config,\n })),\n projectMcp: projectMcp.map((entry) => ({\n serverName: entry.serverName,\n config: entry.config,\n })),\n instructionContent,\n projectDir: opts.projectDir,\n });\n\n const globalFailures = result.mcp.global.filter((entry) => !entry.success);\n const projectFailures = result.mcp.project.filter((entry) => !entry.success);\n\n if (globalFailures.length > 0 || projectFailures.length > 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_CONFIGURE_FAILED\",\n \"One or more MCP writes failed during configure operation.\",\n \"Inspect the failed write entries and provider config paths, then retry.\",\n true,\n result,\n );\n }\n\n return {\n objective: \"Configure global and project settings in one operation\",\n constraints: {\n provider: provider.id,\n globalMcpOps: globalMcp.length,\n projectMcpOps: projectMcp.length,\n instructionMode: instructionContent\n ? typeof instructionContent === \"string\"\n ? \"shared\"\n : \"scoped\"\n : \"none\",\n },\n acceptanceCriteria: {\n globalWrites: result.mcp.global.length,\n projectWrites: result.mcp.project.length,\n },\n data: opts.details\n ? result\n : {\n providerId: result.providerId,\n configPaths: result.configPaths,\n globalWrites: result.mcp.global.length,\n projectWrites: result.mcp.project.length,\n instructionUpdates: {\n global: result.instructions.global?.size ?? 0,\n project: result.instructions.project?.size ?? 0,\n },\n },\n };\n }));\n}\n","/**\n * Advanced command group registration.\n */\n\nimport type { Command } from \"commander\";\nimport { registerAdvancedProviders } from \"./providers.js\";\nimport { registerAdvancedBatch } from \"./batch.js\";\nimport { registerAdvancedConflicts } from \"./conflicts.js\";\nimport { registerAdvancedApply } from \"./apply.js\";\nimport { registerAdvancedInstructions } from \"./instructions.js\";\nimport { registerAdvancedConfigure } from \"./configure.js\";\n\nexport function registerAdvancedCommands(program: Command): void {\n const advanced = program\n .command(\"advanced\")\n .description(\"LAFS-compliant wrappers for advanced orchestration APIs\");\n\n registerAdvancedProviders(advanced);\n registerAdvancedBatch(advanced);\n registerAdvancedConflicts(advanced);\n registerAdvancedApply(advanced);\n registerAdvancedInstructions(advanced);\n registerAdvancedConfigure(advanced);\n}\n","/**\n * config show|path commands - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { readConfig } from \"../core/formats/index.js\";\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../core/lafs.js\";\nimport { resolveProviderConfigPath } from \"../core/paths/standard.js\";\nimport { getProvider } from \"../core/registry/providers.js\";\n\nexport function registerConfigCommand(program: Command): void {\n const config = program\n .command(\"config\")\n .description(\"View provider configuration\");\n\n config\n .command(\"show\")\n .description(\"Show provider configuration\")\n .argument(\"<provider>\", \"Provider ID or alias\")\n .option(\"-g, --global\", \"Show global config\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (providerId: string, opts: { global?: boolean; json?: boolean; human?: boolean }) => {\n const operation = \"config.show\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const provider = getProvider(providerId);\n\n if (!provider) {\n const message = `Provider not found: ${providerId}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n providerId,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const scope = opts.global ? \"global\" : \"project\";\n const configPath = resolveProviderConfigPath(provider, scope) ?? provider.configPathGlobal;\n\n if (!existsSync(configPath)) {\n const message = `No config file at: ${configPath}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.FILE_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n configPath,\n scope,\n });\n } else {\n console.log(pc.dim(message));\n }\n process.exit(1);\n }\n\n try {\n const data = await readConfig(configPath, provider.configFormat);\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n provider: provider.id,\n config: data,\n format: provider.configFormat,\n scope,\n });\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\n${provider.toolName} config (${configPath}):\\n`));\n console.log(JSON.stringify(data, null, 2));\n } catch (err) {\n const message = `Error reading config: ${err instanceof Error ? err.message : String(err)}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.FILE_SYSTEM_ERROR, message, ErrorCategories.INTERNAL);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n });\n\n config\n .command(\"path\")\n .description(\"Show config file path (outputs raw path for piping)\")\n .argument(\"<provider>\", \"Provider ID or alias\")\n .argument(\"[scope]\", \"Scope: project (default) or global\", \"project\")\n .action((providerId: string, scope: string) => {\n // NOTE: This command intentionally outputs raw paths for shell scripting\n // It does NOT use LAFS envelopes to remain pipe-friendly\n const provider = getProvider(providerId);\n\n if (!provider) {\n console.error(pc.red(`Provider not found: ${providerId}`));\n process.exit(1);\n }\n\n if (scope === \"global\") {\n console.log(provider.configPathGlobal);\n } else {\n const projectPath = resolveProviderConfigPath(provider, \"project\");\n if (projectPath) {\n console.log(projectPath);\n } else {\n console.log(pc.dim(`${provider.toolName} has no project-level config`));\n console.log(provider.configPathGlobal);\n }\n }\n });\n}\n","/**\n * Shared LAFS utilities for CAAMP commands\n * \n * Provides standardized LAFS envelope creation, error handling, and format resolution\n * to ensure all commands follow the LAFS (Language-Agnostic Format Specification) protocol.\n * \n * @module lafs\n * @requires @cleocode/lafs-protocol\n * @requires ../logger.js\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type {\n LAFSErrorCategory,\n LAFSError,\n LAFSMeta,\n LAFSPage,\n Warning,\n} from \"@cleocode/lafs-protocol\";\nimport { resolveOutputFormat } from \"@cleocode/lafs-protocol\";\nimport { isHuman, isQuiet } from \"./logger.js\";\n\n/** LAFS MVI disclosure level - defined locally to avoid CI module resolution issues with re-exported types */\nexport type MVILevel = \"minimal\" | \"standard\" | \"full\" | \"custom\";\n\n// Re-export protocol types under CAAMP's naming conventions\nexport type { LAFSMeta };\n\n/** LAFS Error structure - re-exported from protocol as LAFSErrorShape for CAAMP compatibility */\nexport type LAFSErrorShape = LAFSError;\n\n/** LAFS Warning structure - re-exported from protocol */\nexport type LAFSWarning = Warning;\n\n/**\n * Generic LAFS Envelope structure for type-safe command results.\n * Extends the protocol's envelope with TypeScript generics.\n */\nexport interface LAFSEnvelope<T> {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\";\n _meta: LAFSMeta;\n success: boolean;\n result: T | null;\n error: LAFSErrorShape | null;\n page: LAFSPage | null;\n}\n\n/**\n * Format resolution options\n */\nexport interface FormatOptions {\n jsonFlag?: boolean;\n humanFlag?: boolean;\n projectDefault?: \"json\" | \"human\";\n}\n\n/**\n * Resolves output format based on flags and defaults\n * \n * @param options - Format resolution options\n * @returns \"json\" | \"human\"\n * @throws Error if format flags conflict\n * \n * @example\n * ```typescript\n * const format = resolveFormat({\n * jsonFlag: opts.json,\n * humanFlag: opts.human,\n * projectDefault: \"json\"\n * });\n * ```\n */\nexport function resolveFormat(options: FormatOptions): \"json\" | \"human\" {\n return resolveOutputFormat({\n jsonFlag: options.jsonFlag ?? false,\n humanFlag: (options.humanFlag ?? false) || isHuman(),\n projectDefault: options.projectDefault ?? \"json\",\n }).format;\n}\n\n/**\n * Builds a standard LAFS envelope\n * \n * @param operation - Operation identifier (e.g., \"skills.list\", \"doctor.check\")\n * @param mvi - Machine-Verified Instruction flag\n * @param result - Operation result data (null if error)\n * @param error - Error details (null if success)\n * @param page - Pagination info (null if not applicable)\n * @returns LAFS-compliant envelope\n * \n * @example\n * ```typescript\n * const envelope = buildEnvelope(\n * \"skills.list\",\n * true,\n * { skills: [...], count: 5 },\n * null\n * );\n * ```\n */\nexport function buildEnvelope<T>(\n operation: string,\n mvi: MVILevel,\n result: T | null,\n error: LAFSErrorShape | null,\n page: LAFSPage | null = null,\n sessionId?: string,\n warnings?: LAFSWarning[],\n): LAFSEnvelope<T> {\n return {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\",\n _meta: {\n specVersion: \"1.0.0\",\n schemaVersion: \"1.0.0\",\n timestamp: new Date().toISOString(),\n operation,\n requestId: randomUUID(),\n transport: \"cli\",\n strict: true,\n mvi,\n contextVersion: 0,\n ...(sessionId && { sessionId }),\n ...(warnings && warnings.length > 0 && { warnings }),\n },\n success: error === null,\n result,\n error,\n page,\n };\n}\n\n/**\n * Emits a JSON error envelope to stderr and exits\n * \n * @param operation - Operation identifier\n * @param mvi - Machine-Verified Instruction flag\n * @param code - Error code\n * @param message - Error message\n * @param category - Error category from LAFS protocol\n * @param details - Additional error details\n * @param exitCode - Process exit code (default: 1)\n * \n * @example\n * ```typescript\n * emitError(\n * \"skills.install\",\n * true,\n * \"E_SKILL_NOT_FOUND\",\n * \"Skill not found\",\n * \"NOT_FOUND\",\n * { skillName: \"my-skill\" }\n * );\n * ```\n */\nexport function emitError(\n operation: string,\n mvi: MVILevel,\n code: string,\n message: string,\n category: LAFSErrorCategory,\n details: Record<string, unknown> = {},\n exitCode: number = 1,\n): never {\n const envelope = buildEnvelope(operation, mvi, null, {\n code,\n message,\n category,\n retryable: category === \"TRANSIENT\" || category === \"RATE_LIMIT\",\n retryAfterMs: null,\n details,\n });\n console.error(JSON.stringify(envelope, null, 2));\n process.exit(exitCode);\n}\n\n/**\n * Emits a JSON error envelope without exiting (for catch blocks)\n * \n * @param operation - Operation identifier\n * @param mvi - Machine-Verified Instruction flag\n * @param code - Error code\n * @param message - Error message\n * @param category - Error category from LAFS protocol\n * @param details - Additional error details\n * \n * @example\n * ```typescript\n * try {\n * await riskyOperation();\n * } catch (error) {\n * emitJsonError(\"operation\", true, \"E_FAILED\", \"Operation failed\", \"INTERNAL\");\n * process.exit(1);\n * }\n * ```\n */\nexport function emitJsonError(\n operation: string,\n mvi: MVILevel,\n code: string,\n message: string,\n category: LAFSErrorCategory,\n details: Record<string, unknown> = {},\n): void {\n const envelope = buildEnvelope(operation, mvi, null, {\n code,\n message,\n category,\n retryable: category === \"TRANSIENT\" || category === \"RATE_LIMIT\",\n retryAfterMs: null,\n details,\n });\n console.error(JSON.stringify(envelope, null, 2));\n}\n\n/**\n * Outputs a successful LAFS envelope\n * \n * @param operation - Operation identifier\n * @param mvi - Machine-Verified Instruction flag\n * @param result - Operation result data\n * @param page - Optional pagination info\n * \n * @example\n * ```typescript\n * outputSuccess(\"skills.list\", true, { skills: [...], count: 5 });\n * ```\n */\nexport function outputSuccess<T>(\n operation: string,\n mvi: MVILevel,\n result: T,\n page?: LAFSPage,\n sessionId?: string,\n warnings?: LAFSWarning[],\n): void {\n const envelope = buildEnvelope(operation, mvi, result, null, page ?? null, sessionId, warnings);\n \n // In quiet mode, only output if there's an error or if explicitly requested\n if (isQuiet() && !envelope.error) {\n // Suppress non-essential output in quiet mode\n return;\n }\n \n console.log(JSON.stringify(envelope, null, 2));\n}\n\n/**\n * Standard command options interface for LAFS-compliant commands\n */\nexport interface LAFSCommandOptions {\n json?: boolean;\n human?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Handles format resolution errors consistently\n * \n * @param error - The error that occurred during format resolution\n * @param operation - Operation identifier\n * @param mvi - Machine-Verified Instruction flag\n * @param jsonFlag - Whether --json flag was explicitly set\n * @returns never (exits process)\n * \n * @example\n * ```typescript\n * try {\n * format = resolveFormat({ jsonFlag: opts.json, humanFlag: opts.human });\n * } catch (error) {\n * handleFormatError(error, \"skills.list\", true, opts.json);\n * }\n * ```\n */\nexport function handleFormatError(\n error: unknown,\n operation: string,\n mvi: MVILevel,\n jsonFlag: boolean | undefined,\n): never {\n const message = error instanceof Error ? error.message : String(error);\n \n if (jsonFlag) {\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n } else {\n // eslint-disable-next-line no-console\n console.error(message);\n }\n process.exit(1);\n}\n\n/**\n * Common error categories mapping for convenience\n */\nexport const ErrorCategories = {\n VALIDATION: \"VALIDATION\" as LAFSErrorCategory,\n AUTH: \"AUTH\" as LAFSErrorCategory,\n PERMISSION: \"PERMISSION\" as LAFSErrorCategory,\n NOT_FOUND: \"NOT_FOUND\" as LAFSErrorCategory,\n CONFLICT: \"CONFLICT\" as LAFSErrorCategory,\n RATE_LIMIT: \"RATE_LIMIT\" as LAFSErrorCategory,\n TRANSIENT: \"TRANSIENT\" as LAFSErrorCategory,\n INTERNAL: \"INTERNAL\" as LAFSErrorCategory,\n CONTRACT: \"CONTRACT\" as LAFSErrorCategory,\n MIGRATION: \"MIGRATION\" as LAFSErrorCategory,\n} as const;\n\n/**\n * Common error codes for consistency\n */\nexport const ErrorCodes = {\n // Format errors\n FORMAT_CONFLICT: \"E_FORMAT_CONFLICT\",\n INVALID_JSON: \"E_INVALID_JSON\",\n \n // Not found errors\n SKILL_NOT_FOUND: \"E_SKILL_NOT_FOUND\",\n PROVIDER_NOT_FOUND: \"E_PROVIDER_NOT_FOUND\",\n MCP_SERVER_NOT_FOUND: \"E_MCP_SERVER_NOT_FOUND\",\n FILE_NOT_FOUND: \"E_FILE_NOT_FOUND\",\n \n // Validation errors\n INVALID_INPUT: \"E_INVALID_INPUT\",\n INVALID_CONSTRAINT: \"E_INVALID_CONSTRAINT\",\n INVALID_FORMAT: \"E_INVALID_FORMAT\",\n \n // Operation errors\n INSTALL_FAILED: \"E_INSTALL_FAILED\",\n REMOVE_FAILED: \"E_REMOVE_FAILED\",\n UPDATE_FAILED: \"E_UPDATE_FAILED\",\n VALIDATION_FAILED: \"E_VALIDATION_FAILED\",\n AUDIT_FAILED: \"E_AUDIT_FAILED\",\n \n // System errors\n NETWORK_ERROR: \"E_NETWORK_ERROR\",\n FILE_SYSTEM_ERROR: \"E_FILE_SYSTEM_ERROR\",\n PERMISSION_DENIED: \"E_PERMISSION_DENIED\",\n INTERNAL_ERROR: \"E_INTERNAL_ERROR\",\n} as const;\n","/**\n * doctor command - diagnose configuration issues and health\n * LAFS-compliant with JSON-first output\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync, lstatSync, readdirSync, readlinkSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { readConfig } from \"../core/formats/index.js\";\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n handleFormatError,\n type LAFSErrorShape,\n outputSuccess,\n resolveFormat,\n} from \"../core/lafs.js\";\nimport { resolveChannelFromServerName } from \"../core/mcp/cleo.js\";\nimport { readLockFile } from \"../core/mcp/lock.js\";\nimport { listMcpServers } from \"../core/mcp/reader.js\";\nimport { CANONICAL_SKILLS_DIR } from \"../core/paths/agents.js\";\nimport { detectAllProviders } from \"../core/registry/detection.js\";\nimport { getAllProviders, getProviderCount } from \"../core/registry/providers.js\";\nimport { getCaampVersion } from \"../core/version.js\";\nimport type { Provider } from \"../types.js\";\n\ninterface CheckResult {\n label: string;\n status: \"pass\" | \"warn\" | \"fail\";\n detail?: string;\n}\n\ninterface SectionResult {\n name: string;\n checks: CheckResult[];\n}\n\ninterface DoctorResult {\n environment: {\n node: string;\n npm: string;\n caamp: string;\n platform: string;\n };\n registry: {\n loaded: boolean;\n count: number;\n valid: boolean;\n };\n providers: {\n installed: number;\n list: string[];\n };\n skills: {\n canonical: number;\n brokenLinks: number;\n staleLinks: number;\n };\n mcpServers: {\n tracked: number;\n untracked: number;\n orphaned: number;\n };\n checks: Array<{\n label: string;\n status: \"pass\" | \"fail\" | \"warn\";\n message?: string;\n }>;\n}\n\nfunction getNodeVersion(): string {\n return process.version;\n}\n\nfunction getNpmVersion(): string | null {\n try {\n return execFileSync(\"npm\", [\"--version\"], { stdio: \"pipe\", encoding: \"utf-8\" }).trim();\n } catch {\n return null;\n }\n}\n\nfunction checkEnvironment(): SectionResult {\n const checks: CheckResult[] = [];\n\n checks.push({ label: `Node.js ${getNodeVersion()}`, status: \"pass\" });\n\n const npmVersion = getNpmVersion();\n if (npmVersion) {\n checks.push({ label: `npm ${npmVersion}`, status: \"pass\" });\n } else {\n checks.push({ label: \"npm not found\", status: \"warn\" });\n }\n\n checks.push({ label: `CAAMP v${getCaampVersion()}`, status: \"pass\" });\n checks.push({ label: `${process.platform} ${process.arch}`, status: \"pass\" });\n\n return { name: \"Environment\", checks };\n}\n\nfunction checkRegistry(): SectionResult {\n const checks: CheckResult[] = [];\n\n try {\n const providers = getAllProviders();\n const count = getProviderCount();\n checks.push({ label: `${count} providers loaded`, status: \"pass\" });\n\n const malformed: string[] = [];\n for (const p of providers) {\n if (!p.id || !p.toolName || !p.configKey || !p.configFormat) {\n malformed.push(p.id || \"(unknown)\");\n }\n }\n\n if (malformed.length === 0) {\n checks.push({ label: \"All entries valid\", status: \"pass\" });\n } else {\n checks.push({\n label: `${malformed.length} malformed entries`,\n status: \"fail\",\n detail: malformed.join(\", \"),\n });\n }\n } catch (err) {\n checks.push({\n label: \"Failed to load registry\",\n status: \"fail\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n\n return { name: \"Registry\", checks };\n}\n\nfunction checkInstalledProviders(): SectionResult {\n const checks: CheckResult[] = [];\n\n try {\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n\n checks.push({ label: `${installed.length} found`, status: \"pass\" });\n\n for (const r of installed) {\n const methods = r.methods.join(\", \");\n checks.push({ label: `${r.provider.toolName} (${methods})`, status: \"pass\" });\n }\n } catch (err) {\n checks.push({\n label: \"Detection failed\",\n status: \"fail\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n\n return { name: \"Installed Providers\", checks };\n}\n\nfunction checkSkillSymlinks(): SectionResult {\n const checks: CheckResult[] = [];\n\n const canonicalDir = CANONICAL_SKILLS_DIR;\n\n if (!existsSync(canonicalDir)) {\n checks.push({ label: \"0 canonical skills\", status: \"pass\" });\n checks.push({ label: \"No broken symlinks\", status: \"pass\" });\n return { name: \"Skills\", checks };\n }\n\n let canonicalCount = 0;\n let canonicalNames: string[] = [];\n try {\n canonicalNames = readdirSync(canonicalDir).filter((name) => {\n const full = join(canonicalDir, name);\n try {\n const stat = lstatSync(full);\n return stat.isDirectory() || stat.isSymbolicLink();\n } catch {\n return false;\n }\n });\n canonicalCount = canonicalNames.length;\n checks.push({ label: `${canonicalCount} canonical skills`, status: \"pass\" });\n } catch {\n checks.push({ label: \"Cannot read skills directory\", status: \"warn\" });\n return { name: \"Skills\", checks };\n }\n\n // Check symlinks in installed provider skill directories\n const broken: string[] = [];\n const stale: string[] = [];\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n\n for (const r of installed) {\n const provider = r.provider;\n const skillDir = provider.pathSkills;\n if (!existsSync(skillDir)) continue;\n\n try {\n const entries = readdirSync(skillDir);\n for (const entry of entries) {\n const fullPath = join(skillDir, entry);\n try {\n const stat = lstatSync(fullPath);\n if (!stat.isSymbolicLink()) continue;\n\n if (!existsSync(fullPath)) {\n broken.push(`${provider.id}/${entry}`);\n } else {\n // Check if symlink points to canonical location\n const target = readlinkSync(fullPath);\n const isCanonical =\n target.includes(\"/.agents/skills/\") ||\n target.includes(\"\\\\.agents\\\\skills\\\\\");\n if (!isCanonical) {\n stale.push(`${provider.id}/${entry}`);\n }\n }\n } catch {\n // skip unreadable entries\n }\n }\n } catch {\n // skip unreadable dirs\n }\n }\n\n if (broken.length === 0) {\n checks.push({ label: \"No broken symlinks\", status: \"pass\" });\n } else {\n checks.push({\n label: `${broken.length} broken symlink${broken.length !== 1 ? \"s\" : \"\"}`,\n status: \"warn\",\n detail: broken.join(\", \"),\n });\n }\n\n if (stale.length === 0) {\n checks.push({ label: \"No stale symlinks\", status: \"pass\" });\n } else {\n checks.push({\n label: `${stale.length} stale symlink${stale.length !== 1 ? \"s\" : \"\"} (not pointing to ~/.agents/skills/)`,\n status: \"warn\",\n detail: stale.join(\", \"),\n });\n }\n\n return { name: \"Skills\", checks };\n}\n\nasync function checkLockFile(): Promise<SectionResult> {\n const checks: CheckResult[] = [];\n\n try {\n const lock = await readLockFile();\n checks.push({ label: \"Lock file valid\", status: \"pass\" });\n\n const lockSkillNames = Object.keys(lock.skills);\n checks.push({ label: `${lockSkillNames.length} skill entries`, status: \"pass\" });\n\n // Check for orphaned skill entries (canonical path no longer exists)\n const orphaned: string[] = [];\n for (const [name, entry] of Object.entries(lock.skills)) {\n if (entry.canonicalPath && !existsSync(entry.canonicalPath)) {\n orphaned.push(name);\n }\n }\n\n if (orphaned.length === 0) {\n checks.push({ label: \"0 orphaned entries\", status: \"pass\" });\n } else {\n checks.push({\n label: `${orphaned.length} orphaned skill${orphaned.length !== 1 ? \"s\" : \"\"} (in lock, missing from disk)`,\n status: \"warn\",\n detail: orphaned.join(\", \"),\n });\n }\n\n // Check for untracked skills (on disk but not in lock)\n const canonicalDir = CANONICAL_SKILLS_DIR;\n if (existsSync(canonicalDir)) {\n const onDisk = readdirSync(canonicalDir).filter((name) => {\n try {\n const stat = lstatSync(join(canonicalDir, name));\n return stat.isDirectory() || stat.isSymbolicLink();\n } catch {\n return false;\n }\n });\n const untracked = onDisk.filter((name) => !lock.skills[name]);\n\n if (untracked.length === 0) {\n checks.push({ label: \"0 untracked skills\", status: \"pass\" });\n } else {\n checks.push({\n label: `${untracked.length} untracked skill${untracked.length !== 1 ? \"s\" : \"\"} (on disk, not in lock)`,\n status: \"warn\",\n detail: untracked.join(\", \"),\n });\n }\n }\n\n // Check lock agent-list vs actual symlinks\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n const mismatches: string[] = [];\n\n for (const [name, entry] of Object.entries(lock.skills)) {\n if (!entry.agents || entry.agents.length === 0) continue;\n\n for (const agentId of entry.agents) {\n const provider = installed.find((r) => r.provider.id === agentId);\n if (!provider) continue;\n\n const linkPath = join(provider.provider.pathSkills, name);\n if (!existsSync(linkPath)) {\n mismatches.push(`${name} missing from ${agentId}`);\n }\n }\n }\n\n if (mismatches.length === 0) {\n checks.push({ label: \"Lock agent-lists match symlinks\", status: \"pass\" });\n } else {\n checks.push({\n label: `${mismatches.length} agent-list mismatch${mismatches.length !== 1 ? \"es\" : \"\"}`,\n status: \"warn\",\n detail: mismatches.slice(0, 5).join(\", \") + (mismatches.length > 5 ? ` (+${mismatches.length - 5} more)` : \"\"),\n });\n }\n } catch (err) {\n checks.push({\n label: \"Failed to read lock file\",\n status: \"fail\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n\n return { name: \"Lock File\", checks };\n}\n\nasync function checkMcpLockEntries(): Promise<SectionResult> {\n const checks: CheckResult[] = [];\n\n try {\n const lock = await readLockFile();\n const lockNames = Object.keys(lock.mcpServers);\n checks.push({ label: `${lockNames.length} MCP server entries in lock`, status: \"pass\" });\n\n // Detect untracked CLEO servers (in config, not in lock)\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n const liveCleoNames = new Set<string>();\n let untrackedCount = 0;\n\n for (const scope of [\"project\", \"global\"] as const) {\n for (const r of installed) {\n try {\n const entries = await listMcpServers(r.provider, scope);\n for (const entry of entries) {\n const channel = resolveChannelFromServerName(entry.name);\n if (!channel) continue;\n liveCleoNames.add(entry.name);\n\n if (!lock.mcpServers[entry.name]) {\n untrackedCount++;\n }\n }\n } catch {\n // skip unreadable configs\n }\n }\n }\n\n if (untrackedCount === 0) {\n checks.push({ label: \"All CLEO servers tracked in lock\", status: \"pass\" });\n } else {\n checks.push({\n label: `${untrackedCount} untracked CLEO server${untrackedCount !== 1 ? \"s\" : \"\"} (in config, not in lock)`,\n status: \"warn\",\n detail: \"Run `caamp cleo repair` to backfill lock entries\",\n });\n }\n\n // Detect orphaned CLEO entries (in lock, not in any config)\n let orphanedCount = 0;\n const orphanedNames: string[] = [];\n\n for (const serverName of lockNames) {\n const channel = resolveChannelFromServerName(serverName);\n if (!channel) continue;\n\n if (!liveCleoNames.has(serverName)) {\n orphanedCount++;\n orphanedNames.push(serverName);\n }\n }\n\n if (orphanedCount === 0) {\n checks.push({ label: \"No orphaned CLEO lock entries\", status: \"pass\" });\n } else {\n checks.push({\n label: `${orphanedCount} orphaned CLEO lock entr${orphanedCount !== 1 ? \"ies\" : \"y\"} (in lock, not in any config)`,\n status: \"warn\",\n detail: orphanedNames.join(\", \") + \" — Run `caamp cleo repair --prune` to clean up\",\n });\n }\n } catch (err) {\n checks.push({\n label: \"Failed to check MCP lock entries\",\n status: \"fail\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n\n return { name: \"MCP Lock\", checks };\n}\n\nasync function checkConfigFiles(): Promise<SectionResult> {\n const checks: CheckResult[] = [];\n\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n\n for (const r of installed) {\n const provider = r.provider;\n const configPath = provider.configPathGlobal;\n\n if (!existsSync(configPath)) {\n checks.push({\n label: `${provider.id}: no config file found`,\n status: \"warn\",\n detail: configPath,\n });\n continue;\n }\n\n try {\n await readConfig(configPath, provider.configFormat);\n const relPath = configPath.replace(homedir(), \"~\");\n checks.push({\n label: `${provider.id}: ${relPath} readable`,\n status: \"pass\",\n });\n } catch (err) {\n checks.push({\n label: `${provider.id}: config parse error`,\n status: \"fail\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n if (installed.length === 0) {\n checks.push({ label: \"No installed providers to check\", status: \"pass\" });\n }\n\n return { name: \"Config Files\", checks };\n}\n\nfunction formatSection(section: SectionResult): string {\n const lines: string[] = [];\n lines.push(` ${pc.bold(section.name)}`);\n\n for (const check of section.checks) {\n const icon =\n check.status === \"pass\"\n ? pc.green(\"✓\")\n : check.status === \"warn\"\n ? pc.yellow(\"⚠\")\n : pc.red(\"✗\");\n\n lines.push(` ${icon} ${check.label}`);\n\n if (check.detail) {\n lines.push(` ${pc.dim(check.detail)}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function registerDoctorCommand(program: Command): void {\n program\n .command(\"doctor\")\n .description(\"Diagnose configuration issues and health\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { json?: boolean; human?: boolean }) => {\n const operation = \"doctor.check\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n handleFormatError(error, operation, mvi, opts.json);\n }\n\n try {\n const sections: SectionResult[] = [];\n\n sections.push(checkEnvironment());\n sections.push(checkRegistry());\n sections.push(checkInstalledProviders());\n sections.push(checkSkillSymlinks());\n sections.push(await checkLockFile());\n sections.push(await checkMcpLockEntries());\n sections.push(await checkConfigFiles());\n\n // Tally results\n let passed = 0;\n let warnings = 0;\n let errors = 0;\n\n for (const section of sections) {\n for (const check of section.checks) {\n if (check.status === \"pass\") passed++;\n else if (check.status === \"warn\") warnings++;\n else errors++;\n }\n }\n\n // Build result for LAFS envelope\n const npmVersion = getNpmVersion() ?? \"not found\";\n const allProviders = getAllProviders();\n const malformedCount = allProviders.filter(\n (p) => !p.id || !p.toolName || !p.configKey || !p.configFormat\n ).length;\n const detectionResults = detectAllProviders();\n const installedProviders = detectionResults.filter((r) => r.installed);\n const { canonicalCount, brokenCount, staleCount } = countSkillIssues();\n\n const { tracked: mcpTracked, untracked: mcpUntracked, orphaned: mcpOrphaned } = countMcpLockIssues(sections);\n\n const result: DoctorResult = {\n environment: {\n node: getNodeVersion(),\n npm: npmVersion,\n caamp: getCaampVersion(),\n platform: `${process.platform} ${process.arch}`,\n },\n registry: {\n loaded: true,\n count: getProviderCount(),\n valid: malformedCount === 0,\n },\n providers: {\n installed: installedProviders.length,\n list: installedProviders.map((r) => r.provider.id),\n },\n skills: {\n canonical: canonicalCount,\n brokenLinks: brokenCount,\n staleLinks: staleCount,\n },\n mcpServers: {\n tracked: mcpTracked,\n untracked: mcpUntracked,\n orphaned: mcpOrphaned,\n },\n checks: sections.flatMap((s) =>\n s.checks.map((c) => ({\n label: `${s.name}: ${c.label}`,\n status: c.status,\n message: c.detail,\n }))\n ),\n };\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, result);\n \n if (errors > 0) {\n process.exit(1);\n }\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(\"\\ncaamp doctor\\n\"));\n\n for (const section of sections) {\n console.log(formatSection(section));\n console.log();\n }\n\n // Summary line\n const parts: string[] = [];\n parts.push(pc.green(`${passed} checks passed`));\n if (warnings > 0) parts.push(pc.yellow(`${warnings} warning${warnings !== 1 ? \"s\" : \"\"}`));\n if (errors > 0) parts.push(pc.red(`${errors} error${errors !== 1 ? \"s\" : \"\"}`));\n\n console.log(` ${pc.bold(\"Summary\")}: ${parts.join(\", \")}`);\n console.log();\n\n if (errors > 0) {\n process.exit(1);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (format === \"json\") {\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.INTERNAL_ERROR,\n message,\n ErrorCategories.INTERNAL\n );\n } else {\n console.error(pc.red(`Error: ${message}`));\n }\n process.exit(1);\n }\n });\n}\n\nfunction countSkillIssues(): { canonicalCount: number; brokenCount: number; staleCount: number } {\n const canonicalDir = CANONICAL_SKILLS_DIR;\n let canonicalCount = 0;\n\n if (existsSync(canonicalDir)) {\n try {\n const names = readdirSync(canonicalDir).filter((name) => {\n const full = join(canonicalDir, name);\n try {\n const stat = lstatSync(full);\n return stat.isDirectory() || stat.isSymbolicLink();\n } catch {\n return false;\n }\n });\n canonicalCount = names.length;\n } catch {\n // ignore\n }\n }\n\n let brokenCount = 0;\n let staleCount = 0;\n\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n\n for (const r of installed) {\n const provider = r.provider;\n const skillDir = provider.pathSkills;\n if (!existsSync(skillDir)) continue;\n\n try {\n const entries = readdirSync(skillDir);\n for (const entry of entries) {\n const fullPath = join(skillDir, entry);\n try {\n const stat = lstatSync(fullPath);\n if (!stat.isSymbolicLink()) continue;\n\n if (!existsSync(fullPath)) {\n brokenCount++;\n } else {\n const target = readlinkSync(fullPath);\n const isCanonical =\n target.includes(\"/.agents/skills/\") ||\n target.includes(\"\\\\.agents\\\\skills\\\\\");\n if (!isCanonical) {\n staleCount++;\n }\n }\n } catch {\n // skip unreadable entries\n }\n }\n } catch {\n // skip unreadable dirs\n }\n }\n\n return { canonicalCount, brokenCount, staleCount };\n}\n\nfunction countMcpLockIssues(sections: SectionResult[]): {\n tracked: number;\n untracked: number;\n orphaned: number;\n} {\n const mcpSection = sections.find((s) => s.name === \"MCP Lock\");\n if (!mcpSection) return { tracked: 0, untracked: 0, orphaned: 0 };\n\n let tracked = 0;\n let untracked = 0;\n let orphaned = 0;\n\n for (const check of mcpSection.checks) {\n const countMatch = check.label.match(/^(\\d+)/);\n if (!countMatch?.[1]) continue;\n\n const count = Number.parseInt(countMatch[1], 10);\n if (check.label.includes(\"MCP server entries in lock\")) {\n tracked = count;\n } else if (check.label.includes(\"untracked\")) {\n untracked = count;\n } else if (check.label.includes(\"orphaned\")) {\n orphaned = count;\n }\n }\n\n return { tracked, untracked, orphaned };\n}\n","import { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nlet cachedVersion: string | null = null;\n\nexport function getCaampVersion(): string {\n if (cachedVersion) return cachedVersion;\n\n try {\n const currentDir = dirname(fileURLToPath(import.meta.url));\n const packageJsonPath = join(currentDir, \"..\", \"package.json\");\n const packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf-8\")) as { version?: string };\n cachedVersion = packageJson.version ?? \"0.0.0\";\n } catch {\n cachedVersion = \"0.0.0\";\n }\n\n return cachedVersion;\n}\n","/**\n * instructions inject command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { injectAll } from \"../../core/instructions/injector.js\";\nimport { generateInjectionContent, groupByInstructFile } from \"../../core/instructions/templates.js\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getAllProviders, getProvider } from \"../../core/registry/providers.js\";\nimport type { Provider } from \"../../types.js\";\n\nexport function registerInstructionsInject(parent: Command): void {\n parent\n .command(\"inject\")\n .description(\"Inject instruction blocks into all provider files\")\n .option(\"-a, --agent <name>\", \"Target specific agent(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-g, --global\", \"Inject into global instruction files\")\n .option(\"--content <text>\", \"Custom content to inject\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--all\", \"Target all known providers\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: {\n agent: string[];\n global?: boolean;\n content?: string;\n dryRun?: boolean;\n all?: boolean;\n json?: boolean;\n human?: boolean;\n }) => {\n const operation = \"instructions.inject\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n let providers: Provider[];\n\n if (opts.all) {\n providers = getAllProviders();\n } else if (opts.agent.length > 0) {\n providers = opts.agent\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else {\n providers = getInstalledProviders();\n }\n\n if (providers.length === 0) {\n const message = \"No providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const content = opts.content ?? generateInjectionContent();\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n\n // Show grouped preview\n const groups = groupByInstructFile(providers);\n\n if (opts.dryRun) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n injected: [],\n providers: providers.map((p) => p.id),\n count: 0,\n dryRun: true,\n wouldInject: Array.from(groups.entries()).map(([file, group]) => ({\n file,\n providers: group.map((p) => p.id),\n })),\n });\n } else {\n console.log(pc.bold(\"Dry run - would inject into:\\n\"));\n for (const [file, group] of groups) {\n console.log(` ${pc.bold(file)}: ${group.map((p) => p.id).join(\", \")}`);\n }\n console.log(pc.dim(`\\n Scope: ${scope}`));\n console.log(pc.dim(` Content length: ${content.length} chars`));\n }\n return;\n }\n\n const results = await injectAll(providers, process.cwd(), scope, content);\n\n const injected: string[] = [];\n for (const [file] of results) {\n injected.push(file);\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n injected,\n providers: providers.map((p) => p.id),\n count: results.size,\n });\n } else {\n for (const [file, action] of results) {\n const icon = action === \"created\" ? pc.green(\"+\")\n : action === \"updated\" ? pc.yellow(\"~\")\n : pc.blue(\"^\");\n console.log(` ${icon} ${file} (${action})`);\n }\n console.log(pc.bold(`\\n${results.size} file(s) processed.`));\n }\n });\n}\n","/**\n * instructions check command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { checkAllInjections } from \"../../core/instructions/injector.js\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getAllProviders, getProvider } from \"../../core/registry/providers.js\";\nimport type { Provider } from \"../../types.js\";\n\nexport function registerInstructionsCheck(parent: Command): void {\n parent\n .command(\"check\")\n .description(\"Check injection status across providers\")\n .option(\"-a, --agent <name>\", \"Check specific agent(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-g, --global\", \"Check global instruction files\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--all\", \"Check all known providers\")\n .action(async (opts: {\n agent: string[];\n global?: boolean;\n json?: boolean;\n human?: boolean;\n all?: boolean;\n }) => {\n const operation = \"instructions.check\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n let providers: Provider[];\n\n if (opts.all) {\n providers = getAllProviders();\n } else if (opts.agent.length > 0) {\n providers = opts.agent\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else {\n providers = getInstalledProviders();\n }\n\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n const results = await checkAllInjections(providers, process.cwd(), scope);\n\n // Build provider status for result\n const providerStatus = results.map((r) => ({\n id: r.provider,\n present: r.status === \"current\" || r.status === \"outdated\",\n path: r.file,\n }));\n\n const present = providerStatus.filter((p) => p.present).length;\n const missing = providerStatus.filter((p) => !p.present).length;\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n providers: providerStatus,\n present,\n missing,\n });\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\nInstruction file status (${scope}):\\n`));\n\n for (const r of results) {\n let icon: string;\n let label: string;\n\n switch (r.status) {\n case \"current\":\n icon = pc.green(\"✓\");\n label = \"current\";\n break;\n case \"outdated\":\n icon = pc.yellow(\"~\");\n label = \"outdated\";\n break;\n case \"missing\":\n icon = pc.red(\"✗\");\n label = \"missing\";\n break;\n case \"none\":\n icon = pc.dim(\"-\");\n label = \"no injection\";\n break;\n }\n\n console.log(` ${icon} ${r.file.padEnd(40)} ${label}`);\n }\n\n console.log();\n });\n}\n","/**\n * instructions update command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { checkAllInjections, injectAll } from \"../../core/instructions/injector.js\";\nimport { generateInjectionContent } from \"../../core/instructions/templates.js\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\n\nexport function registerInstructionsUpdate(parent: Command): void {\n parent\n .command(\"update\")\n .description(\"Update all instruction file injections\")\n .option(\"-g, --global\", \"Update global instruction files\")\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { global?: boolean; yes?: boolean; json?: boolean; human?: boolean }) => {\n const operation = \"instructions.update\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const providers = getInstalledProviders();\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n const content = generateInjectionContent();\n\n // Check current state\n const checks = await checkAllInjections(providers, process.cwd(), scope, content);\n const needsUpdate = checks.filter((c) => c.status !== \"current\");\n\n if (needsUpdate.length === 0) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n updated: [],\n failed: [],\n count: { updated: 0, failed: 0 },\n });\n } else {\n console.log(pc.green(\"All instruction files are up to date.\"));\n }\n return;\n }\n\n if (format === \"human\") {\n console.log(pc.bold(`${needsUpdate.length} file(s) need updating:\\n`));\n for (const c of needsUpdate) {\n console.log(` ${c.file} (${c.status})`);\n }\n }\n\n // Filter providers to only those needing updates\n const providerIds = new Set(needsUpdate.map((c) => c.provider));\n const toUpdate = providers.filter((p) => providerIds.has(p.id));\n\n const results = await injectAll(toUpdate, process.cwd(), scope, content);\n\n const updated: string[] = [];\n for (const [file] of results) {\n updated.push(file);\n }\n\n if (format === \"human\") {\n console.log();\n for (const [file, action] of results) {\n console.log(` ${pc.green(\"✓\")} ${file} (${action})`);\n }\n console.log(pc.bold(`\\n${results.size} file(s) updated.`));\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n updated,\n failed: [],\n count: { updated: updated.length, failed: 0 },\n });\n }\n });\n}\n","/**\n * Instructions command group registration\n */\n\nimport type { Command } from \"commander\";\nimport { registerInstructionsInject } from \"./inject.js\";\nimport { registerInstructionsCheck } from \"./check.js\";\nimport { registerInstructionsUpdate } from \"./update.js\";\n\nexport function registerInstructionsCommands(program: Command): void {\n const instructions = program\n .command(\"instructions\")\n .description(\"Manage instruction file injections\");\n\n registerInstructionsInject(instructions);\n registerInstructionsCheck(instructions);\n registerInstructionsUpdate(instructions);\n}\n","/**\n * CLEO MCP channel commands and compatibility wrappers.\n */\n\nimport { createInterface } from \"node:readline/promises\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport {\n buildCleoProfile,\n type CleoChannel,\n checkCommandReachability,\n extractVersionTag,\n normalizeCleoChannel,\n parseEnvAssignments,\n resolveChannelFromServerName,\n resolveCleoServerName,\n} from \"../../core/mcp/cleo.js\";\nimport { installMcpServerToAll } from \"../../core/mcp/installer.js\";\nimport { getTrackedMcpServers, recordMcpInstall, removeMcpFromLock } from \"../../core/mcp/lock.js\";\nimport { listMcpServers, removeMcpServer } from \"../../core/mcp/reader.js\";\nimport { reconcileCleoLock } from \"../../core/mcp/reconcile.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport type { Provider } from \"../../types.js\";\n\ninterface CleoInstallOptions {\n channel?: string;\n provider: string[];\n all?: boolean;\n global?: boolean;\n version?: string;\n command?: string;\n arg: string[];\n env: string[];\n cleoDir?: string;\n dryRun?: boolean;\n yes?: boolean;\n interactive?: boolean;\n json?: boolean;\n human?: boolean;\n}\n\ninterface CleoUninstallOptions {\n channel?: string;\n provider: string[];\n all?: boolean;\n global?: boolean;\n dryRun?: boolean;\n json?: boolean;\n human?: boolean;\n}\n\ninterface CleoShowOptions {\n provider: string[];\n all?: boolean;\n global?: boolean;\n project?: boolean;\n channel?: string;\n json?: boolean;\n human?: boolean;\n}\n\ninterface CleoRepairOptions {\n provider: string[];\n all?: boolean;\n global?: boolean;\n project?: boolean;\n prune?: boolean;\n dryRun?: boolean;\n json?: boolean;\n human?: boolean;\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nfunction collectTargetProviders(providerIds: string[], all?: boolean): Provider[] {\n if (all) {\n return getInstalledProviders();\n }\n\n if (providerIds.length > 0) {\n return providerIds\n .map((id) => getProvider(id))\n .filter((provider): provider is Provider => provider !== undefined);\n }\n\n return getInstalledProviders();\n}\n\nasync function validateProfile(\n provider: Provider,\n scope: \"project\" | \"global\",\n serverName: string,\n): Promise<{ valid: boolean; reason?: string }> {\n const entries = await listMcpServers(provider, scope);\n const entry = entries.find((candidate) => candidate.name === serverName);\n if (!entry) {\n return { valid: false, reason: \"server missing after write\" };\n }\n\n const command = typeof entry.config.command === \"string\" ? entry.config.command : undefined;\n if (!command) {\n return { valid: true };\n }\n\n const reachability = checkCommandReachability(command);\n if (!reachability.reachable) {\n return {\n valid: false,\n reason: `command not reachable (${reachability.method}: ${reachability.detail})`,\n };\n }\n\n return { valid: true };\n}\n\nasync function detectServerConflicts(\n providers: Provider[],\n scope: \"project\" | \"global\",\n targetServerName: string,\n): Promise<Array<{ providerId: string; message: string }>> {\n const warnings: Array<{ providerId: string; message: string }> = [];\n\n for (const provider of providers) {\n const entries = await listMcpServers(provider, scope);\n const existing = entries.find((entry) => entry.name === targetServerName);\n if (!existing) continue;\n\n const command = typeof existing.config.command === \"string\" ? existing.config.command : \"\";\n const args = Array.isArray(existing.config.args)\n ? existing.config.args.filter((value): value is string => typeof value === \"string\")\n : [];\n const flat = `${command} ${args.join(\" \")}`.toLowerCase();\n\n if (!flat.includes(\"cleo\")) {\n warnings.push({\n providerId: provider.id,\n message: `Server name '${targetServerName}' already exists with a non-CLEO command in ${provider.id}.`,\n });\n }\n }\n\n return warnings;\n}\n\nfunction formatInstallResultHuman(\n mode: \"install\" | \"update\",\n channel: CleoChannel,\n serverName: string,\n scope: \"project\" | \"global\",\n results: Awaited<ReturnType<typeof installMcpServerToAll>>,\n validations: Array<{ providerId: string; valid: boolean; reason?: string }>,\n): void {\n console.log(pc.bold(`${mode === \"install\" ? \"Install\" : \"Update\"} CLEO channel: ${channel}`));\n console.log(pc.dim(`Server: ${serverName} Scope: ${scope}`));\n console.log();\n\n for (const result of results) {\n const validation = validations.find((entry) => entry.providerId === result.provider.id);\n if (result.success) {\n const validationLabel = validation?.valid\n ? pc.green(\"validated\")\n : pc.yellow(`validation warning: ${validation?.reason ?? \"unknown\"}`);\n console.log(` ${pc.green(\"+\")} ${result.provider.toolName.padEnd(22)} ${pc.dim(result.configPath)} ${validationLabel}`);\n } else {\n console.log(` ${pc.red(\"x\")} ${result.provider.toolName.padEnd(22)} ${pc.red(result.error ?? \"failed\")}`);\n console.log(pc.dim(\" Recovery: verify config path permissions and retry with --dry-run.\"));\n }\n }\n console.log();\n}\n\nasync function runInteractiveInstall(\n opts: CleoInstallOptions,\n): Promise<CleoInstallOptions> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n const discovered = getInstalledProviders();\n if (discovered.length === 0) {\n throw new Error(\"No installed providers were detected for interactive setup.\");\n }\n\n console.log(pc.bold(\"CLEO MCP Setup\"));\n console.log(pc.dim(\"Step 1/6 - Select provider(s)\"));\n for (const [index, provider] of discovered.entries()) {\n console.log(` ${index + 1}. ${provider.id} (${provider.toolName})`);\n }\n const providerAnswer = await rl.question(pc.dim(\"Choose providers (e.g. 1,2 or all): \"));\n const selectedProviders = providerAnswer.trim().toLowerCase() === \"all\"\n ? discovered.map((provider) => provider.id)\n : providerAnswer\n .split(\",\")\n .map((part) => Number(part.trim()))\n .filter((value) => Number.isFinite(value) && value > 0 && value <= discovered.length)\n .map((index) => discovered[index - 1]?.id)\n .filter((id): id is string => Boolean(id));\n\n if (selectedProviders.length === 0) {\n throw new Error(\"No providers selected.\");\n }\n\n console.log();\n console.log(pc.dim(\"Step 2/6 - Select channel\"));\n const channelAnswer = await rl.question(pc.dim(\"Channel [stable/beta/dev] (stable): \"));\n const selectedChannel = normalizeCleoChannel(channelAnswer || \"stable\");\n\n let command = opts.command;\n let args = [...opts.arg];\n let env = [...opts.env];\n let cleoDir = opts.cleoDir;\n if (selectedChannel === \"dev\") {\n command = await rl.question(pc.dim(\"Dev command (required): \"));\n const argsAnswer = await rl.question(pc.dim(\"Dev args (space-separated, optional): \"));\n args = argsAnswer.trim() === \"\" ? [] : argsAnswer.trim().split(/\\s+/);\n const dirAnswer = await rl.question(pc.dim(\"CLEO_DIR (~/.cleo-dev default): \"));\n cleoDir = dirAnswer.trim() === \"\" ? \"~/.cleo-dev\" : dirAnswer.trim();\n if (cleoDir.trim() !== \"\") {\n env = [\n ...env.filter((entry) => !entry.startsWith(\"CLEO_DIR=\")),\n `CLEO_DIR=${cleoDir}`,\n ];\n }\n }\n\n const profile = buildCleoProfile({\n channel: selectedChannel,\n version: opts.version,\n command,\n args,\n env: parseEnvAssignments(env),\n cleoDir,\n });\n\n console.log();\n console.log(pc.dim(\"Step 3/6 - Preview profile diff\"));\n console.log(` Server: ${pc.bold(profile.serverName)}`);\n console.log(` Channel: ${selectedChannel}`);\n console.log(` Config: ${JSON.stringify(profile.config)}`);\n\n console.log();\n console.log(pc.dim(\"Step 4/6 - Confirm apply\"));\n const confirm = await rl.question(pc.dim(\"Apply this configuration? [y/N] \"));\n if (![\"y\", \"yes\"].includes(confirm.trim().toLowerCase())) {\n throw new Error(\"Cancelled by user.\");\n }\n\n return {\n ...opts,\n provider: selectedProviders,\n channel: selectedChannel,\n command,\n arg: args,\n env,\n cleoDir,\n yes: true,\n };\n } finally {\n rl.close();\n }\n}\n\nexport async function executeCleoInstall(\n mode: \"install\" | \"update\",\n opts: CleoInstallOptions,\n operation: string,\n): Promise<void> {\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const interactive = (opts.interactive ?? false) && format === \"human\";\n const resolvedOpts = interactive ? await runInteractiveInstall(opts) : opts;\n\n const channel = normalizeCleoChannel(resolvedOpts.channel);\n const providers = collectTargetProviders(resolvedOpts.provider, resolvedOpts.all);\n if (providers.length === 0) {\n const message = \"No target providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const envMap = parseEnvAssignments(resolvedOpts.env);\n const profile = buildCleoProfile({\n channel,\n version: resolvedOpts.version,\n command: resolvedOpts.command,\n args: resolvedOpts.arg,\n env: envMap,\n cleoDir: resolvedOpts.cleoDir,\n });\n\n const scope = resolvedOpts.global ? \"global\" as const : \"project\" as const;\n\n if (resolvedOpts.dryRun) {\n if (format === \"human\") {\n console.log(pc.bold(`Dry run: ${mode} CLEO (${channel})`));\n console.log(pc.dim(`Server: ${profile.serverName} Scope: ${scope}`));\n console.log(pc.dim(`Providers: ${providers.map((provider) => provider.id).join(\", \")}`));\n console.log(pc.dim(`Command: ${profile.config.command ?? \"(none)\"} ${(profile.config.args ?? []).join(\" \")}`));\n if (profile.config.env && Object.keys(profile.config.env).length > 0) {\n console.log(pc.dim(`Env: ${JSON.stringify(profile.config.env)}`));\n }\n } else {\n outputSuccess(operation, mvi, {\n action: mode,\n channel,\n serverName: profile.serverName,\n providers: providers.map((provider) => provider.id),\n scope,\n command: profile.config.command,\n args: profile.config.args ?? [],\n env: profile.config.env ?? {},\n packageSpec: profile.packageSpec,\n dryRun: true,\n });\n }\n return;\n }\n\n const conflictWarnings = await detectServerConflicts(providers, scope, profile.serverName);\n if (format === \"human\" && conflictWarnings.length > 0) {\n console.log(pc.yellow(\"Warning: potential server name conflicts detected.\"));\n for (const warning of conflictWarnings) {\n console.log(pc.yellow(` - ${warning.message}`));\n }\n console.log(pc.dim(\"Recovery: run with --dry-run, inspect provider config, then retry with explicit channel/profile.\"));\n console.log();\n }\n\n const results = await installMcpServerToAll(providers, profile.serverName, profile.config, scope);\n const succeeded = results.filter((result) => result.success);\n\n const validations: Array<{ providerId: string; valid: boolean; reason?: string }> = [];\n for (const result of succeeded) {\n const validation = await validateProfile(result.provider, scope, profile.serverName);\n validations.push({ providerId: result.provider.id, valid: validation.valid, reason: validation.reason });\n }\n\n if (succeeded.length > 0) {\n await recordMcpInstall(\n profile.serverName,\n profile.packageSpec ?? resolvedOpts.command ?? \"cleo-dev\",\n channel === \"dev\" ? \"command\" : \"package\",\n succeeded.map((result) => result.provider.id),\n resolvedOpts.global ?? false,\n resolvedOpts.version ?? extractVersionTag(profile.packageSpec),\n );\n }\n\n if (format === \"human\") {\n formatInstallResultHuman(mode, channel, profile.serverName, scope, results, validations);\n }\n\n const validationFailures = validations.filter((entry) => !entry.valid);\n if (interactive && validationFailures.length > 0 && format === \"human\") {\n console.log(pc.dim(\"Step 5/6 - Validation\"));\n console.log(pc.yellow(`Validation found ${validationFailures.length} issue(s).`));\n\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n console.log(pc.dim(\"Step 6/6 - Rollback\"));\n const answer = await rl.question(pc.dim(\"Rollback failed validations? [y/N] \"));\n if ([\"y\", \"yes\"].includes(answer.trim().toLowerCase())) {\n for (const failure of validationFailures) {\n const provider = providers.find((candidate) => candidate.id === failure.providerId);\n if (!provider) continue;\n await removeMcpServer(provider, profile.serverName, scope);\n }\n console.log(pc.yellow(\"Rollback completed for failed provider validations.\"));\n }\n } finally {\n rl.close();\n }\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n action: mode,\n channel,\n serverName: profile.serverName,\n scope,\n command: profile.config.command,\n args: profile.config.args ?? [],\n env: profile.config.env ?? {},\n packageSpec: profile.packageSpec,\n providers: results.map((result) => ({\n id: result.provider.id,\n success: result.success,\n configPath: result.configPath,\n error: result.error,\n validation: validations.find((entry) => entry.providerId === result.provider.id) ?? null,\n })),\n conflicts: conflictWarnings,\n validationStatus: validationFailures.length === 0 ? \"ok\" : \"warning\",\n });\n }\n}\n\nexport async function executeCleoUninstall(\n opts: CleoUninstallOptions,\n operation: string,\n): Promise<void> {\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const channel = normalizeCleoChannel(opts.channel);\n const serverName = resolveCleoServerName(channel);\n const providers = collectTargetProviders(opts.provider, opts.all);\n\n if (providers.length === 0) {\n const message = \"No target providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n if (opts.dryRun) {\n if (format === \"human\") {\n console.log(pc.bold(\"Dry run: uninstall CLEO profile\"));\n console.log(pc.dim(`Server: ${serverName} Channel: ${channel} Scope: ${scope}`));\n console.log(pc.dim(`Providers: ${providers.map((provider) => provider.id).join(\", \")}`));\n } else {\n outputSuccess(operation, mvi, {\n action: \"uninstall\",\n channel,\n serverName,\n providers: providers.map((provider) => provider.id),\n scope,\n dryRun: true,\n });\n }\n return;\n }\n\n const removed: string[] = [];\n for (const provider of providers) {\n const success = await removeMcpServer(provider, serverName, scope);\n if (success) removed.push(provider.id);\n }\n\n if (removed.length > 0) {\n await removeMcpFromLock(serverName);\n }\n\n if (format === \"human\") {\n const prefix = removed.length > 0 ? pc.green(\"Removed\") : pc.yellow(\"No matching profile found for\");\n console.log(`${prefix} ${pc.bold(serverName)} (${channel}) on ${removed.length}/${providers.length} providers.`);\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n action: \"uninstall\",\n channel,\n serverName,\n scope,\n removed,\n providerCount: providers.length,\n dryRun: false,\n });\n }\n}\n\nexport type CleoHealthStatus = \"healthy\" | \"degraded\" | \"broken\";\n\nexport interface CleoEntryHealth {\n commandReachable: boolean;\n commandDetail: string;\n configPresent: boolean;\n lockTracked: boolean;\n status: CleoHealthStatus;\n}\n\nexport function checkCleoEntryHealth(\n command: string | undefined,\n lockTracked: boolean,\n): CleoEntryHealth {\n if (!command) {\n return {\n commandReachable: true,\n commandDetail: \"(no command)\",\n configPresent: true,\n lockTracked,\n status: lockTracked ? \"healthy\" : \"degraded\",\n };\n }\n\n const reachability = checkCommandReachability(command);\n if (!reachability.reachable) {\n return {\n commandReachable: false,\n commandDetail: reachability.detail,\n configPresent: true,\n lockTracked,\n status: \"broken\",\n };\n }\n\n return {\n commandReachable: true,\n commandDetail: reachability.detail,\n configPresent: true,\n lockTracked,\n status: lockTracked ? \"healthy\" : \"degraded\",\n };\n}\n\nexport async function executeCleoShow(\n opts: CleoShowOptions,\n operation: string,\n): Promise<void> {\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const providers = collectTargetProviders(opts.provider, opts.all);\n if (providers.length === 0) {\n const message = \"No target providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const channelFilter = opts.channel ? normalizeCleoChannel(opts.channel) : null;\n\n // Determine which scopes to scan\n const scopes: Array<\"project\" | \"global\"> = [];\n if (opts.global && !opts.project) {\n scopes.push(\"global\");\n } else if (opts.project && !opts.global) {\n scopes.push(\"project\");\n } else {\n scopes.push(\"project\", \"global\");\n }\n\n // Load lock file data\n const lockEntries = await getTrackedMcpServers();\n\n interface EnrichedProfile {\n provider: string;\n providerName: string;\n serverName: string;\n channel: CleoChannel;\n scope: \"project\" | \"global\";\n command?: string;\n args: string[];\n env: Record<string, string>;\n version: string | null;\n source: string | null;\n sourceType: string | null;\n installedAt: string | null;\n updatedAt: string | null;\n health: CleoEntryHealth;\n }\n\n const entries: EnrichedProfile[] = [];\n const warnings: import(\"../../core/lafs.js\").LAFSWarning[] = [];\n\n for (const scope of scopes) {\n for (const provider of providers) {\n const providerEntries = await listMcpServers(provider, scope);\n for (const entry of providerEntries) {\n const channel = resolveChannelFromServerName(entry.name);\n if (!channel) continue;\n if (channelFilter && channel !== channelFilter) continue;\n\n const command = typeof entry.config.command === \"string\" ? entry.config.command : undefined;\n const args = Array.isArray(entry.config.args)\n ? entry.config.args.filter((value): value is string => typeof value === \"string\")\n : [];\n const env = typeof entry.config.env === \"object\" && entry.config.env !== null\n ? entry.config.env as Record<string, string>\n : {};\n\n const lockEntry = lockEntries[entry.name];\n const lockTracked = lockEntry !== undefined;\n const health = checkCleoEntryHealth(command, lockTracked);\n\n entries.push({\n provider: provider.id,\n providerName: provider.toolName,\n serverName: entry.name,\n channel,\n scope,\n command,\n args,\n env,\n version: lockEntry?.version ?? null,\n source: lockEntry?.source ?? null,\n sourceType: lockEntry?.sourceType ?? null,\n installedAt: lockEntry?.installedAt ?? null,\n updatedAt: lockEntry?.updatedAt ?? null,\n health,\n });\n\n if (health.status === \"broken\") {\n warnings.push({\n code: \"W_COMMAND_UNREACHABLE\",\n message: `${entry.name} command not reachable on ${provider.toolName} (${health.commandDetail})`,\n });\n } else if (health.status === \"degraded\") {\n warnings.push({\n code: \"W_NOT_TRACKED\",\n message: `${entry.name} on ${provider.toolName} is not tracked in lock file`,\n });\n }\n }\n }\n }\n\n const issueCount = entries.filter((e) => e.health.status !== \"healthy\").length;\n\n if (format === \"human\") {\n if (entries.length === 0) {\n console.log(pc.dim(\"No CLEO channel profiles found.\"));\n } else {\n console.log(pc.bold(\"CLEO Channel Profiles\"));\n console.log();\n\n // Column headers\n const header = [\n \"Channel\".padEnd(10),\n \"Version\".padEnd(10),\n \"Provider\".padEnd(22),\n \"Scope\".padEnd(9),\n \"Command\".padEnd(33),\n \"Status\".padEnd(10),\n \"Installed\".padEnd(12),\n ].join(\"\");\n console.log(` ${pc.dim(header)}`);\n console.log(` ${pc.dim(\"-\".repeat(106))}`);\n\n for (const entry of entries) {\n const commandStr = entry.command\n ? `${entry.command} ${entry.args.join(\" \")}`.slice(0, 31).padEnd(33)\n : pc.dim(\"-\").padEnd(33);\n const versionStr = (entry.version ?? \"-\").padEnd(10);\n const installedStr = entry.installedAt\n ? entry.installedAt.slice(0, 10).padEnd(12)\n : \"-\".padEnd(12);\n\n let statusStr: string;\n if (entry.health.status === \"healthy\") {\n statusStr = pc.green(\"healthy\".padEnd(10));\n } else if (entry.health.status === \"degraded\") {\n statusStr = pc.yellow(\"degraded\".padEnd(10));\n } else {\n statusStr = pc.red(\"broken\".padEnd(10));\n }\n\n console.log(\n ` ${entry.channel.padEnd(10)}${versionStr}${entry.providerName.padEnd(22)}${entry.scope.padEnd(9)}${commandStr}${statusStr}${installedStr}`,\n );\n }\n\n console.log();\n const summary = ` ${entries.length} profile${entries.length !== 1 ? \"s\" : \"\"}`;\n if (issueCount > 0) {\n console.log(`${summary} | ${pc.yellow(`${issueCount} issue${issueCount !== 1 ? \"s\" : \"\"}`)}`);\n console.log();\n console.log(\" Issues:\");\n for (const w of warnings) {\n console.log(` ${pc.yellow(\"!\")} ${w.message}`);\n }\n } else {\n console.log(summary);\n }\n }\n }\n\n if (format === \"json\") {\n outputSuccess(\n operation,\n mvi,\n {\n providers: providers.map((provider) => provider.id),\n scopes,\n channel: channelFilter,\n profiles: entries,\n count: entries.length,\n },\n undefined,\n undefined,\n warnings.length > 0 ? warnings : undefined,\n );\n }\n}\n\nexport async function executeCleoRepair(\n opts: CleoRepairOptions,\n operation: string,\n): Promise<void> {\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const providerIds = opts.provider.length > 0 ? opts.provider : undefined;\n\n const result = await reconcileCleoLock({\n providerIds,\n all: opts.all,\n global: opts.global,\n project: opts.project,\n prune: opts.prune,\n dryRun: opts.dryRun,\n });\n\n if (format === \"human\") {\n const prefix = opts.dryRun ? \"CLEO Lock Repair (dry run)\" : \"CLEO Lock Repair\";\n console.log(pc.bold(prefix));\n console.log();\n\n if (result.backfilled.length > 0) {\n for (const entry of result.backfilled) {\n const agents = entry.agents.join(\", \");\n const versionStr = entry.version ? `(${entry.version})` : \"\";\n console.log(\n ` ${pc.green(\"+\")} ${entry.serverName.padEnd(12)}${entry.channel.padEnd(10)}${agents.padEnd(22)}${entry.scope.padEnd(10)}${entry.source} ${pc.dim(versionStr)}`,\n );\n }\n }\n\n if (result.pruned.length > 0) {\n for (const name of result.pruned) {\n console.log(` ${pc.red(\"-\")} ${name} (removed from lock)`);\n }\n }\n\n if (result.backfilled.length === 0 && result.pruned.length === 0) {\n console.log(pc.dim(\" No changes needed. All CLEO entries are tracked.\"));\n }\n\n console.log();\n console.log(\n ` ${result.backfilled.length} backfilled | ${result.pruned.length} pruned | ${result.alreadyTracked} already tracked`,\n );\n\n if (result.errors.length > 0) {\n console.log();\n for (const err of result.errors) {\n console.log(` ${pc.red(\"!\")} ${err.message}`);\n }\n }\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n backfilled: result.backfilled,\n pruned: result.pruned,\n alreadyTracked: result.alreadyTracked,\n dryRun: opts.dryRun ?? false,\n errors: result.errors,\n });\n }\n}\n\nfunction buildInstallOptions(command: Command): Command {\n return command\n .requiredOption(\"--channel <channel>\", \"CLEO channel: stable|beta|dev\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Apply to all detected providers\")\n .option(\"-g, --global\", \"Use global scope\")\n .option(\"--version <tag>\", \"Tag/version for stable or beta\")\n .option(\"--command <command>\", \"Dev channel command\")\n .option(\"--arg <arg>\", \"Dev command arg (repeatable)\", collect, [])\n .option(\"--env <kv>\", \"Environment assignment KEY=value (repeatable)\", collect, [])\n .option(\"--cleo-dir <path>\", \"CLEO_DIR override for dev channel\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--interactive\", \"Guided interactive setup\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\");\n}\n\nexport function registerMcpCleoCommands(parent: Command): void {\n const cleo = parent\n .command(\"cleo\")\n .description(\"Manage CLEO MCP channel profiles\");\n\n buildInstallOptions(\n cleo\n .command(\"install\")\n .description(\"Install CLEO MCP profile by channel\"),\n ).action(async (opts: CleoInstallOptions) => {\n await executeCleoInstall(\"install\", opts, \"mcp.cleo.install\");\n });\n\n buildInstallOptions(\n cleo\n .command(\"update\")\n .description(\"Update CLEO MCP profile by channel\"),\n ).action(async (opts: CleoInstallOptions) => {\n await executeCleoInstall(\"update\", opts, \"mcp.cleo.update\");\n });\n\n cleo\n .command(\"uninstall\")\n .description(\"Uninstall CLEO MCP profile for a channel\")\n .requiredOption(\"--channel <channel>\", \"CLEO channel: stable|beta|dev\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Apply to all detected providers\")\n .option(\"-g, --global\", \"Use global scope\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoUninstallOptions) => {\n await executeCleoUninstall(opts, \"mcp.cleo.uninstall\");\n });\n\n cleo\n .command(\"show\")\n .description(\"Show installed CLEO MCP channel profiles\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Inspect all detected providers\")\n .option(\"-g, --global\", \"Global scope only\")\n .option(\"-p, --project\", \"Project scope only\")\n .option(\"--channel <channel>\", \"Filter channel: stable|beta|dev\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoShowOptions) => {\n await executeCleoShow(opts, \"mcp.cleo.show\");\n });\n\n cleo\n .command(\"repair\")\n .description(\"Repair lock file by backfilling untracked CLEO entries\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Scan all detected providers\")\n .option(\"-g, --global\", \"Global scope only\")\n .option(\"-p, --project\", \"Project scope only\")\n .option(\"--prune\", \"Remove orphaned lock entries not in any config\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoRepairOptions) => {\n await executeCleoRepair(opts, \"mcp.cleo.repair\");\n });\n}\n\nexport function registerMcpCleoCompatibilityCommands(parent: Command): void {\n parent\n .command(\"update\")\n .description(\"Update channel-managed MCP profile\")\n .argument(\"<name>\", \"Managed MCP profile name (cleo)\")\n .requiredOption(\"--channel <channel>\", \"CLEO channel: stable|beta|dev\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Apply to all detected providers\")\n .option(\"-g, --global\", \"Use global scope\")\n .option(\"--version <tag>\", \"Tag/version for stable or beta\")\n .option(\"--command <command>\", \"Dev channel command\")\n .option(\"--arg <arg>\", \"Dev command arg (repeatable)\", collect, [])\n .option(\"--env <kv>\", \"Environment assignment KEY=value (repeatable)\", collect, [])\n .option(\"--cleo-dir <path>\", \"CLEO_DIR override for dev channel\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string, opts: CleoInstallOptions) => {\n if (name !== \"cleo\") {\n emitJsonError(\"mcp.update\", \"standard\", ErrorCodes.INVALID_INPUT, \"Only managed profile 'cleo' is supported by mcp update.\", ErrorCategories.VALIDATION, { name });\n process.exit(1);\n }\n await executeCleoInstall(\"update\", opts, \"mcp.update\");\n });\n\n parent\n .command(\"uninstall\")\n .description(\"Uninstall channel-managed MCP profile\")\n .argument(\"<name>\", \"Managed MCP profile name (cleo)\")\n .requiredOption(\"--channel <channel>\", \"CLEO channel: stable|beta|dev\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Apply to all detected providers\")\n .option(\"-g, --global\", \"Use global scope\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string, opts: CleoUninstallOptions) => {\n if (name !== \"cleo\") {\n emitJsonError(\"mcp.uninstall\", \"standard\", ErrorCodes.INVALID_INPUT, \"Only managed profile 'cleo' is supported by mcp uninstall.\", ErrorCategories.VALIDATION, { name });\n process.exit(1);\n }\n await executeCleoUninstall(opts, \"mcp.uninstall\");\n });\n\n parent\n .command(\"show\")\n .description(\"Show channel-managed MCP profile\")\n .argument(\"<name>\", \"Managed MCP profile name (cleo)\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Inspect all detected providers\")\n .option(\"-g, --global\", \"Global scope only\")\n .option(\"-p, --project\", \"Project scope only\")\n .option(\"--channel <channel>\", \"Filter channel: stable|beta|dev\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string, opts: CleoShowOptions) => {\n if (name !== \"cleo\") {\n emitJsonError(\"mcp.show\", \"standard\", ErrorCodes.INVALID_INPUT, \"Only managed profile 'cleo' is supported by mcp show.\", ErrorCategories.VALIDATION, { name });\n process.exit(1);\n }\n await executeCleoShow(opts, \"mcp.show\");\n });\n}\n\nexport function mapCompatibilityInstallOptions(\n opts: {\n channel?: string;\n provider?: string[];\n agent?: string[];\n all?: boolean;\n global?: boolean;\n version?: string;\n command?: string;\n arg?: string[];\n env?: string[];\n cleoDir?: string;\n dryRun?: boolean;\n yes?: boolean;\n interactive?: boolean;\n json?: boolean;\n human?: boolean;\n },\n): CleoInstallOptions {\n return {\n channel: opts.channel,\n provider: [...(opts.provider ?? []), ...(opts.agent ?? [])],\n all: opts.all,\n global: opts.global,\n version: opts.version,\n command: opts.command,\n arg: opts.arg ?? [],\n env: opts.env ?? [],\n cleoDir: opts.cleoDir,\n dryRun: opts.dryRun,\n yes: opts.yes,\n interactive: opts.interactive,\n json: opts.json,\n human: opts.human,\n };\n}\n\nexport function shouldUseCleoCompatibilityInstall(source: string, channel?: string): boolean {\n if (source.trim().toLowerCase() !== \"cleo\") return false;\n return typeof channel === \"string\" && channel.trim() !== \"\";\n}\n\nexport function registerCleoCommands(program: Command): void {\n const cleo = program\n .command(\"cleo\")\n .description(\"Manage CLEO channel profiles\");\n\n buildInstallOptions(\n cleo\n .command(\"install\")\n .description(\"Install CLEO profile by channel\"),\n ).action(async (opts: CleoInstallOptions) => {\n await executeCleoInstall(\"install\", opts, \"cleo.install\");\n });\n\n buildInstallOptions(\n cleo\n .command(\"update\")\n .description(\"Update CLEO profile by channel\"),\n ).action(async (opts: CleoInstallOptions) => {\n await executeCleoInstall(\"update\", opts, \"cleo.update\");\n });\n\n cleo\n .command(\"uninstall\")\n .description(\"Uninstall CLEO profile for a channel\")\n .requiredOption(\"--channel <channel>\", \"CLEO channel: stable|beta|dev\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Apply to all detected providers\")\n .option(\"-g, --global\", \"Use global scope\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoUninstallOptions) => {\n await executeCleoUninstall(opts, \"cleo.uninstall\");\n });\n\n cleo\n .command(\"show\")\n .description(\"Show installed CLEO channel profiles\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Inspect all detected providers\")\n .option(\"-g, --global\", \"Global scope only\")\n .option(\"-p, --project\", \"Project scope only\")\n .option(\"--channel <channel>\", \"Filter channel: stable|beta|dev\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoShowOptions) => {\n await executeCleoShow(opts, \"cleo.show\");\n });\n\n cleo\n .command(\"repair\")\n .description(\"Repair lock file by backfilling untracked CLEO entries\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Scan all detected providers\")\n .option(\"-g, --global\", \"Global scope only\")\n .option(\"-p, --project\", \"Project scope only\")\n .option(\"--prune\", \"Remove orphaned lock entries not in any config\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoRepairOptions) => {\n await executeCleoRepair(opts, \"cleo.repair\");\n });\n}\n\nexport { resolveCleoServerName };\n","/**\n * mcp detect command - auto-detect installed MCP tools - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { listMcpServers, resolveConfigPath } from \"../../core/mcp/reader.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\n\nexport function registerMcpDetect(parent: Command): void {\n parent\n .command(\"detect\")\n .description(\"Auto-detect installed MCP tools and their configurations\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { json?: boolean; human?: boolean }) => {\n const operation = \"mcp.detect\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const providers = getInstalledProviders();\n\n const providersResult: Array<{\n id: string;\n configsFound: number;\n servers: string[];\n }> = [];\n let totalConfigs = 0;\n\n for (const provider of providers) {\n const globalPath = resolveConfigPath(provider, \"global\");\n const projectPath = resolveConfigPath(provider, \"project\");\n\n const globalEntries = await listMcpServers(provider, \"global\");\n const projectEntries = await listMcpServers(provider, \"project\");\n\n const configsFound = \n (globalPath && existsSync(globalPath) ? 1 : 0) +\n (projectPath && existsSync(projectPath) ? 1 : 0);\n \n totalConfigs += configsFound;\n\n const allServers = [...globalEntries.map(e => e.name), ...projectEntries.map(e => e.name)];\n\n providersResult.push({\n id: provider.id,\n configsFound,\n servers: allServers,\n });\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n providers: providersResult,\n totalConfigs,\n });\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\n${providers.length} provider(s) with MCP support:\\n`));\n\n for (const provider of providersResult) {\n const globalPath = resolveConfigPath(providers.find(p => p.id === provider.id)!, \"global\");\n const projectPath = resolveConfigPath(providers.find(p => p.id === provider.id)!, \"project\");\n \n const hasGlobal = globalPath && existsSync(globalPath);\n const hasProject = projectPath && existsSync(projectPath);\n \n const globalIcon = hasGlobal ? pc.green(\"G\") : pc.dim(\"-\");\n const projectIcon = hasProject ? pc.green(\"P\") : pc.dim(\"-\");\n const serverList = provider.servers.length > 0 ? pc.dim(provider.servers.join(\", \")) : pc.dim(\"no servers\");\n\n console.log(` [${globalIcon}${projectIcon}] ${pc.bold(provider.id.padEnd(20))} ${serverList}`);\n }\n\n console.log(pc.dim(\"\\nG = global config, P = project config\"));\n console.log();\n });\n}\n","/**\n * mcp install command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { buildServerConfig, installMcpServerToAll } from \"../../core/mcp/installer.js\";\nimport { recordMcpInstall } from \"../../core/mcp/lock.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport { parseSource } from \"../../core/sources/parser.js\";\nimport type { Provider } from \"../../types.js\";\nimport {\n executeCleoInstall,\n mapCompatibilityInstallOptions,\n shouldUseCleoCompatibilityInstall,\n} from \"./cleo.js\";\n\nexport function registerMcpInstall(parent: Command): void {\n parent\n .command(\"install\")\n .description(\"Install MCP server to agent configs\")\n .argument(\"<source>\", \"MCP server source (URL, npm package, or command)\")\n .option(\"-a, --agent <name>\", \"Target specific agent(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--provider <id>\", \"Target provider ID (alias for --agent)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-g, --global\", \"Install to global/user config\")\n .option(\"-n, --name <name>\", \"Override inferred server name\")\n .option(\"--channel <channel>\", \"Managed channel profile (stable|beta|dev)\")\n .option(\"--version <tag>\", \"Managed profile tag/version for stable or beta\")\n .option(\"--command <command>\", \"Managed dev profile command\")\n .option(\"--arg <arg>\", \"Managed dev command arg (repeatable)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--env <kv>\", \"Managed env assignment KEY=value (repeatable)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--cleo-dir <path>\", \"Managed dev CLEO_DIR override\")\n .option(\"-t, --transport <type>\", \"Transport type: http (default) or sse\", \"http\")\n .option(\"--header <header>\", \"HTTP header (Key: Value)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--all\", \"Install to all detected agents\")\n .option(\"--interactive\", \"Guided interactive setup for managed profiles\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (source: string, opts: {\n agent: string[];\n provider: string[];\n global?: boolean;\n name?: string;\n channel?: string;\n version?: string;\n command?: string;\n arg: string[];\n env: string[];\n cleoDir?: string;\n transport: string;\n header: string[];\n yes?: boolean;\n all?: boolean;\n interactive?: boolean;\n dryRun?: boolean;\n json?: boolean;\n human?: boolean;\n }) => {\n const operation = \"mcp.install\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n if (shouldUseCleoCompatibilityInstall(source, opts.channel)) {\n const cleoOpts = mapCompatibilityInstallOptions(opts);\n await executeCleoInstall(\"install\", cleoOpts, operation);\n return;\n }\n\n const parsed = parseSource(source);\n const serverName = opts.name ?? parsed.inferredName;\n\n // Parse headers\n const headers: Record<string, string> = {};\n for (const h of opts.header) {\n const idx = h.indexOf(\":\");\n if (idx > 0) {\n headers[h.slice(0, idx).trim()] = h.slice(idx + 1).trim();\n }\n }\n\n const config = buildServerConfig(parsed, opts.transport, headers);\n\n // Determine target providers\n let providers: Provider[];\n\n if (opts.all) {\n providers = getInstalledProviders();\n } else if (opts.agent.length > 0) {\n providers = opts.agent\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else if (opts.provider.length > 0) {\n providers = opts.provider\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else {\n providers = getInstalledProviders();\n }\n\n if (providers.length === 0) {\n const message = \"No target providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n\n if (opts.dryRun) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n installed: [{\n name: serverName,\n providers: providers.map((p) => p.id),\n config,\n }],\n dryRun: true,\n });\n } else {\n console.log(pc.bold(\"Dry run - would install:\"));\n console.log(` Server: ${pc.bold(serverName)}`);\n console.log(` Config: ${JSON.stringify(config, null, 2)}`);\n console.log(` Scope: ${scope}`);\n console.log(` Providers: ${providers.map((p) => p.id).join(\", \")}`);\n }\n return;\n }\n\n if (format === \"human\") {\n console.log(pc.dim(`Installing \"${serverName}\" to ${providers.length} provider(s)...\\n`));\n }\n\n const results = await installMcpServerToAll(\n providers,\n serverName,\n config,\n scope,\n );\n\n const succeeded = results.filter((r) => r.success);\n const failed = results.filter((r) => !r.success);\n\n if (format === \"human\") {\n for (const r of results) {\n if (r.success) {\n console.log(` ${pc.green(\"✓\")} ${r.provider.toolName.padEnd(22)} ${pc.dim(r.configPath)}`);\n } else {\n console.log(` ${pc.red(\"✗\")} ${r.provider.toolName.padEnd(22)} ${pc.red(r.error ?? \"failed\")}`);\n }\n }\n }\n\n if (succeeded.length > 0) {\n await recordMcpInstall(\n serverName,\n source,\n parsed.type,\n succeeded.map((r) => r.provider.id),\n opts.global ?? false,\n );\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n installed: succeeded.map((r) => ({\n name: serverName,\n providers: [r.provider.id],\n config,\n })),\n dryRun: false,\n });\n } else {\n console.log(pc.bold(`\\n${succeeded.length}/${results.length} providers configured.`));\n }\n });\n}\n","/**\n * mcp list command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { listMcpServers } from \"../../core/mcp/reader.js\";\nimport { resolvePreferredConfigScope } from \"../../core/paths/standard.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport type { McpServerEntry } from \"../../types.js\";\n\nexport function registerMcpList(parent: Command): void {\n parent\n .command(\"list\")\n .description(\"List configured MCP servers\")\n .option(\"-a, --agent <name>\", \"List for specific agent\")\n .option(\"--provider <id>\", \"Provider ID alias for --agent\")\n .option(\"-g, --global\", \"List global config\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { agent?: string; provider?: string; global?: boolean; json?: boolean; human?: boolean }) => {\n const operation = \"mcp.list\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const selectedProvider = opts.provider ?? opts.agent;\n\n const providers = selectedProvider\n ? [getProvider(selectedProvider)].filter((p): p is NonNullable<typeof p> => p !== undefined)\n : getInstalledProviders();\n\n if (selectedProvider && providers.length === 0) {\n const message = `Provider not found: ${selectedProvider}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n provider: selectedProvider,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const allEntries: Array<{\n name: string;\n command?: string;\n scope: \"global\" | \"project\";\n }> = [];\n\n for (const provider of providers) {\n const scope = resolvePreferredConfigScope(provider, opts.global);\n\n const entries = await listMcpServers(provider, scope);\n for (const entry of entries) {\n allEntries.push({\n name: entry.name,\n command: typeof entry.config.command === \"string\" ? entry.config.command : undefined,\n scope,\n });\n }\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n servers: allEntries,\n count: allEntries.length,\n scope: opts.global ? \"global\" : selectedProvider ? `agent:${selectedProvider}` : \"project\",\n });\n return;\n }\n\n // Human-readable output\n if (allEntries.length === 0) {\n console.log(pc.dim(\"No MCP servers configured.\"));\n return;\n }\n\n console.log(pc.bold(`\\n${allEntries.length} MCP server(s) configured:\\n`));\n\n for (const entry of allEntries) {\n const scopeIndicator = entry.scope === \"global\" ? pc.dim(\"[G] \") : pc.dim(\"[P] \");\n console.log(` ${scopeIndicator}${pc.bold(entry.name.padEnd(25))} ${entry.command ? pc.dim(entry.command) : \"\"}`);\n }\n\n console.log();\n console.log(pc.dim(\"G = global config, P = project config\"));\n console.log();\n });\n}\n","/**\n * mcp remove command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { removeMcpFromLock } from \"../../core/mcp/lock.js\";\nimport { removeMcpServer } from \"../../core/mcp/reader.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport type { Provider } from \"../../types.js\";\n\nexport function registerMcpRemove(parent: Command): void {\n parent\n .command(\"remove\")\n .description(\"Remove MCP server from agent configs\")\n .argument(\"<name>\", \"MCP server name to remove\")\n .option(\"-a, --agent <name>\", \"Target specific agent(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--provider <id>\", \"Target provider ID (alias for --agent)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-g, --global\", \"Remove from global config\")\n .option(\"--all\", \"Remove from all detected agents\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string, opts: {\n agent: string[];\n provider: string[];\n global?: boolean;\n all?: boolean;\n json?: boolean;\n human?: boolean;\n }) => {\n const operation = \"mcp.remove\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n let providers: Provider[];\n\n if (opts.all) {\n providers = getInstalledProviders();\n } else if (opts.agent.length > 0) {\n providers = opts.agent\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else if (opts.provider.length > 0) {\n providers = opts.provider\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else {\n providers = getInstalledProviders();\n }\n\n if (providers.length === 0) {\n const message = \"No target providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n const removed: string[] = [];\n const notFound: string[] = [];\n\n for (const provider of providers) {\n const success = await removeMcpServer(provider, name, scope);\n if (success) {\n removed.push(provider.id);\n if (format === \"human\") {\n console.log(` ${pc.green(\"✓\")} Removed from ${provider.toolName}`);\n }\n } else {\n notFound.push(provider.id);\n }\n }\n\n if (removed.length > 0) {\n await removeMcpFromLock(name);\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n removed,\n providers: removed,\n notFound: notFound.length > 0 ? notFound : undefined,\n });\n } else {\n if (removed.length > 0) {\n console.log(pc.green(`\\n✓ Removed \"${name}\" from ${removed.length} provider(s).`));\n } else {\n console.log(pc.yellow(`Server \"${name}\" not found in any provider config.`));\n }\n }\n });\n}\n","/**\n * MCP command group registration\n */\n\nimport type { Command } from \"commander\";\nimport { registerMcpCleoCommands, registerMcpCleoCompatibilityCommands } from \"./cleo.js\";\nimport { registerMcpDetect } from \"./detect.js\";\nimport { registerMcpInstall } from \"./install.js\";\nimport { registerMcpList } from \"./list.js\";\nimport { registerMcpRemove } from \"./remove.js\";\n\nexport function registerMcpCommands(program: Command): void {\n const mcp = program\n .command(\"mcp\")\n .description(\"Manage MCP server configurations\");\n\n registerMcpInstall(mcp);\n registerMcpRemove(mcp);\n registerMcpList(mcp);\n registerMcpDetect(mcp);\n registerMcpCleoCommands(mcp);\n registerMcpCleoCompatibilityCommands(mcp);\n}\n","/**\n * providers list|detect|show commands - LAFS-compliant with JSON-first output\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { LAFSErrorCategory } from \"@cleocode/lafs-protocol\";\nimport { resolveOutputFormat } from \"@cleocode/lafs-protocol\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { isHuman } from \"../core/logger.js\";\nimport {\n CANONICAL_HOOK_EVENTS,\n buildHookMatrix,\n getCommonEvents,\n getHookMappingsVersion,\n getHookSupport,\n getProviderSummary,\n getSupportedEvents,\n toNative,\n translateToAll,\n} from \"../core/hooks/index.js\";\nimport type { CanonicalHookEvent } from \"../core/hooks/types.js\";\nimport { detectAllProviders, detectProjectProviders } from \"../core/registry/detection.js\";\nimport {\n buildSkillsMap,\n getAllProviders,\n getCommonHookEvents,\n getProvider,\n getProviderCount,\n getProvidersByHookEvent,\n getProvidersByPriority,\n getRegistryVersion,\n providerSupports,\n} from \"../core/registry/providers.js\";\nimport type { HookEvent } from \"../core/registry/types.js\";\n\ninterface LAFSErrorShape {\n code: string;\n message: string;\n category: LAFSErrorCategory;\n retryable: boolean;\n retryAfterMs: number | null;\n details: Record<string, unknown>;\n}\n\nexport function registerProvidersCommand(program: Command): void {\n const providers = program\n .command(\"providers\")\n .description(\"Manage AI agent providers\");\n\n providers\n .command(\"list\")\n .description(\"List all supported providers\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--tier <tier>\", \"Filter by priority tier (high, medium, low)\")\n .action(async (opts: { json?: boolean; human?: boolean; tier?: string }) => {\n const operation = \"providers.list\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n const all = opts.tier\n ? getProvidersByPriority(opts.tier as \"high\" | \"medium\" | \"low\")\n : getAllProviders();\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n providers: all,\n count: all.length,\n version: getRegistryVersion(),\n tier: opts.tier || null,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\nCAMP Provider Registry v${getRegistryVersion()}`));\n console.log(pc.dim(`${getProviderCount()} providers\\n`));\n\n // Group by priority\n const tiers = [\"high\", \"medium\", \"low\"] as const;\n for (const tier of tiers) {\n const tierProviders = all.filter((p) => p.priority === tier);\n if (tierProviders.length === 0) continue;\n\n const tierLabel = tier === \"high\" ? pc.green(\"HIGH\") : tier === \"medium\" ? pc.yellow(\"MEDIUM\") : pc.dim(\"LOW\");\n console.log(`${tierLabel} priority:`);\n\n for (const p of tierProviders) {\n const status = p.status === \"active\"\n ? pc.green(\"active\")\n : p.status === \"beta\"\n ? pc.yellow(\"beta\")\n : pc.dim(p.status);\n\n console.log(` ${pc.bold(p.agentFlag.padEnd(20))} ${p.toolName.padEnd(22)} ${p.vendor.padEnd(16)} [${status}]`);\n }\n console.log();\n }\n });\n\n providers\n .command(\"detect\")\n .description(\"Auto-detect installed providers\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--project\", \"Include project-level detection\")\n .action(async (opts: { json?: boolean; human?: boolean; project?: boolean }) => {\n const operation = \"providers.detect\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n const results = opts.project\n ? detectProjectProviders(process.cwd())\n : detectAllProviders();\n\n const installed = results.filter((r) => r.installed);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n installed: installed.map((r) => ({\n id: r.provider.id,\n toolName: r.provider.toolName,\n methods: r.methods,\n projectDetected: r.projectDetected,\n })),\n notInstalled: results.filter((r) => !r.installed).map((r) => r.provider.id),\n count: {\n installed: installed.length,\n total: results.length,\n },\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\nDetected ${installed.length} installed providers:\\n`));\n\n for (const r of installed) {\n const methods = r.methods.join(\", \");\n const project = r.projectDetected ? pc.green(\" [project]\") : \"\";\n console.log(` ${pc.green(\"✓\")} ${pc.bold(r.provider.toolName.padEnd(22))} via ${pc.dim(methods)}${project}`);\n }\n\n const notInstalled = results.filter((r) => !r.installed);\n if (notInstalled.length > 0) {\n console.log(pc.dim(`\\n ${notInstalled.length} providers not detected`));\n }\n\n console.log();\n });\n\n providers\n .command(\"show\")\n .description(\"Show provider details\")\n .argument(\"<id>\", \"Provider ID or alias\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (id: string, opts: { json?: boolean; human?: boolean }) => {\n const operation = \"providers.show\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n const provider = getProvider(id);\n\n if (!provider) {\n const message = `Provider not found: ${id}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_PROVIDER_NOT_FOUND\", message, \"NOT_FOUND\", {\n id,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n provider,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\n${provider.toolName}`));\n console.log(pc.dim(`by ${provider.vendor}\\n`));\n\n console.log(` ID: ${provider.id}`);\n console.log(` Flag: --agent ${provider.agentFlag}`);\n if (provider.aliases.length > 0) {\n console.log(` Aliases: ${provider.aliases.join(\", \")}`);\n }\n console.log(` Status: ${provider.status}`);\n console.log(` Priority: ${provider.priority}`);\n console.log();\n console.log(` Instruction: ${provider.instructFile}`);\n console.log(` Config format: ${provider.configFormat}`);\n console.log(` Config key: ${provider.configKey}`);\n console.log(` Transports: ${provider.supportedTransports.join(\", \")}`);\n console.log(` Headers: ${provider.supportsHeaders ? \"yes\" : \"no\"}`);\n console.log();\n console.log(pc.dim(\" Paths:\"));\n console.log(` Global dir: ${provider.pathGlobal}`);\n console.log(` Project dir: ${provider.pathProject || \"(none)\"}`);\n console.log(` Global config: ${provider.configPathGlobal}`);\n console.log(` Project config: ${provider.configPathProject || \"(none)\"}`);\n console.log(` Global skills: ${provider.pathSkills}`);\n console.log(` Project skills: ${provider.pathProjectSkills || \"(none)\"}`);\n console.log();\n });\n\n providers\n .command(\"skills-map\")\n .description(\"Show skills path map for all providers\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--provider <id>\", \"Filter to a specific provider\")\n .action(async (opts: { json?: boolean; human?: boolean; provider?: string }) => {\n const operation = \"providers.skills-map\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n let map = buildSkillsMap();\n\n if (opts.provider) {\n map = map.filter((entry) => entry.providerId === opts.provider);\n if (map.length === 0) {\n const message = `Provider not found: ${opts.provider}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_PROVIDER_NOT_FOUND\", message, \"NOT_FOUND\", {\n id: opts.provider,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n }\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n skillsMap: map,\n count: map.length,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(\"\\nProvider Skills Map\\n\"));\n\n // Table header\n console.log(\n ` ${pc.bold(\"Provider\".padEnd(22))} ${pc.bold(\"Precedence\".padEnd(30))} ${pc.bold(\"Global Path\".padEnd(40))} ${pc.bold(\"Project Path\")}`,\n );\n console.log(` ${\"─\".repeat(22)} ${\"─\".repeat(30)} ${\"─\".repeat(40)} ${\"─\".repeat(30)}`);\n\n for (const entry of map) {\n console.log(\n ` ${entry.toolName.padEnd(22)} ${entry.precedence.padEnd(30)} ${(entry.paths.global ?? \"-\").padEnd(40)} ${entry.paths.project ?? \"-\"}`,\n );\n }\n\n console.log(pc.dim(`\\n ${map.length} providers shown`));\n console.log();\n });\n\n // ── hooks subcommand group ─────────────────────────────────────────\n const hooks = providers\n .command(\"hooks\")\n .description(\"Show provider hook event support\");\n\n // hooks list (default)\n hooks\n .command(\"list\", { isDefault: true })\n .description(\"Show all providers with their hook support summary\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { json?: boolean; human?: boolean }) => {\n const operation = \"providers.hooks.list\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n const all = getAllProviders();\n const summaries = all\n .map((p) => getProviderSummary(p.id))\n .filter((s) => s !== undefined);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n mappingsVersion: getHookMappingsVersion(),\n canonicalEventCount: CANONICAL_HOOK_EVENTS.length,\n providers: summaries,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n console.log(pc.bold(`\\nCAMP Hook Support (mappings v${getHookMappingsVersion()})\\n`));\n console.log(pc.dim(` ${CANONICAL_HOOK_EVENTS.length} canonical events defined\\n`));\n\n // Table header\n console.log(\n ` ${pc.bold(\"Provider\".padEnd(22))} ${pc.bold(\"System\".padEnd(10))} ${pc.bold(\"Coverage\".padEnd(12))} ${pc.bold(\"Supported\".padEnd(12))} ${pc.bold(\"Provider-Only\")}`,\n );\n console.log(` ${\"─\".repeat(22)} ${\"─\".repeat(10)} ${\"─\".repeat(12)} ${\"─\".repeat(12)} ${\"─\".repeat(20)}`);\n\n for (const s of summaries) {\n if (!s) continue;\n const system = s.hookSystem === \"none\"\n ? pc.dim(\"none\")\n : s.experimental\n ? pc.yellow(s.hookSystem + \"*\")\n : pc.green(s.hookSystem);\n const coverage = s.coverage > 0\n ? (s.coverage >= 75 ? pc.green : s.coverage >= 40 ? pc.yellow : pc.dim)(`${s.coverage}%`)\n : pc.dim(\"0%\");\n const supported = s.supportedCount > 0\n ? `${s.supportedCount}/${s.totalCanonical}`\n : pc.dim(\"0\");\n const provOnly = s.providerOnly.length > 0 ? String(s.providerOnly.length) : pc.dim(\"-\");\n\n const provider = getProvider(s.providerId);\n const name = provider?.toolName ?? s.providerId;\n\n console.log(\n ` ${name.padEnd(22)} ${system.padEnd(20)} ${coverage.padEnd(22)} ${supported.padEnd(22)} ${provOnly}`,\n );\n }\n\n const withHooks = summaries.filter((s) => s && s.supportedCount > 0);\n console.log(pc.dim(`\\n ${withHooks.length} providers with hook support, ${summaries.length - withHooks.length} without`));\n if (summaries.some((s) => s?.experimental)) {\n console.log(pc.dim(\" * = experimental hook system\"));\n }\n console.log();\n });\n\n // hooks matrix\n hooks\n .command(\"matrix\")\n .description(\"Show cross-provider hook support matrix\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--provider <ids>\", \"Comma-separated provider IDs to compare\")\n .action(async (opts: { json?: boolean; human?: boolean; provider?: string }) => {\n const operation = \"providers.hooks.matrix\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n const ids = opts.provider?.split(\",\").map((s) => s.trim());\n const matrix = buildHookMatrix(ids);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(operation, mvi, { matrix }, null);\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable matrix\n const providerNames = matrix.providers.map((id) => {\n const p = getProvider(id);\n return (p?.toolName ?? id).slice(0, 14);\n });\n\n console.log(pc.bold(\"\\nHook Support Matrix\\n\"));\n\n // Header\n const eventCol = \"CAAMP Event\".padEnd(22);\n const provCols = providerNames.map((n) => pc.bold(n.padEnd(16))).join(\"\");\n console.log(` ${pc.bold(eventCol)} ${provCols}`);\n console.log(` ${\"─\".repeat(22)} ${providerNames.map(() => \"─\".repeat(16)).join(\"\")}`);\n\n for (const event of matrix.events) {\n const cells = matrix.providers.map((id) => {\n const m = matrix.matrix[event][id];\n if (!m?.supported) return pc.dim(\"·\".padEnd(16));\n return pc.green((m.nativeName ?? \"?\").slice(0, 14).padEnd(16));\n }).join(\"\");\n\n console.log(` ${event.padEnd(22)} ${cells}`);\n }\n\n // Common events\n const commonEvents = getCommonEvents(matrix.providers);\n console.log(pc.dim(`\\n Common events: ${commonEvents.length > 0 ? commonEvents.join(\", \") : \"none\"}`));\n console.log();\n });\n\n // hooks translate\n hooks\n .command(\"translate\")\n .description(\"Translate a hook event name between CAAMP canonical and provider-native\")\n .argument(\"<event>\", \"Hook event name (canonical or native)\")\n .option(\"--to <provider>\", \"Target provider ID for canonical→native translation\")\n .option(\"--from <provider>\", \"Source provider ID for native→canonical translation\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (event: string, opts: { to?: string; from?: string; json?: boolean; human?: boolean }) => {\n const operation = \"providers.hooks.translate\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n if (opts.to) {\n // Canonical → native\n const canonical = event as CanonicalHookEvent;\n if (!CANONICAL_HOOK_EVENTS.includes(canonical)) {\n const msg = `Unknown canonical event: ${event}. Valid: ${CANONICAL_HOOK_EVENTS.join(\", \")}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_UNKNOWN_EVENT\", msg, \"VALIDATION\");\n } else {\n console.error(pc.red(msg));\n }\n process.exit(1);\n }\n\n const result = getHookSupport(canonical, opts.to);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(operation, mvi, {\n direction: \"canonical-to-native\",\n providerId: opts.to,\n ...result,\n }, null);\n console.log(JSON.stringify(envelope, null, 2));\n } else {\n if (result.supported) {\n console.log(`\\n ${pc.green(event)} → ${pc.bold(result.native!)} (${opts.to})`);\n if (result.notes) console.log(pc.dim(` Note: ${result.notes}`));\n } else {\n console.log(`\\n ${pc.red(event)} → ${pc.dim(\"not supported\")} (${opts.to})`);\n }\n console.log();\n }\n return;\n }\n\n if (opts.from) {\n // Native → canonical (import at top of file)\n const { toCanonical } = await import(\"../core/hooks/index.js\");\n const canonical = toCanonical(event, opts.from);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(operation, mvi, {\n direction: \"native-to-canonical\",\n native: event,\n providerId: opts.from,\n canonical,\n supported: canonical !== null,\n }, null);\n console.log(JSON.stringify(envelope, null, 2));\n } else {\n if (canonical) {\n console.log(`\\n ${pc.bold(event)} (${opts.from}) → ${pc.green(canonical)}`);\n } else {\n console.log(`\\n ${pc.bold(event)} (${opts.from}) → ${pc.dim(\"no canonical mapping (provider-only event)\")}`);\n }\n console.log();\n }\n return;\n }\n\n // No --to or --from: translate canonical event to all providers\n const canonical = event as CanonicalHookEvent;\n if (!CANONICAL_HOOK_EVENTS.includes(canonical)) {\n const msg = `Unknown canonical event: ${event}. Use --from <provider> for native names, or valid canonical: ${CANONICAL_HOOK_EVENTS.join(\", \")}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_UNKNOWN_EVENT\", msg, \"VALIDATION\");\n } else {\n console.error(pc.red(msg));\n }\n process.exit(1);\n }\n\n const { getMappedProviderIds } = await import(\"../core/hooks/index.js\");\n const allIds = getMappedProviderIds();\n const translations = translateToAll(canonical, allIds);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(operation, mvi, {\n direction: \"canonical-to-all\",\n canonical: event,\n translations,\n supportedCount: Object.keys(translations).length,\n totalProviders: allIds.length,\n }, null);\n console.log(JSON.stringify(envelope, null, 2));\n } else {\n console.log(pc.bold(`\\n ${event} across providers:\\n`));\n for (const id of allIds) {\n const native = translations[id];\n const provider = getProvider(id);\n const name = (provider?.toolName ?? id).padEnd(22);\n if (native) {\n console.log(` ${pc.green(\"✓\")} ${name} ${pc.bold(native)}`);\n } else {\n console.log(` ${pc.dim(\"·\")} ${name} ${pc.dim(\"not supported\")}`);\n }\n }\n console.log();\n }\n });\n\n providers\n .command(\"capabilities\")\n .description(\"Show provider capability matrix\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--filter <path>\", \"Filter to providers supporting a capability dot-path (e.g. spawn.supportsSubagents)\")\n .action(async (opts: { json?: boolean; human?: boolean; filter?: string }) => {\n const operation = \"providers.capabilities\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n let all = getAllProviders();\n\n if (opts.filter) {\n all = all.filter((p) => providerSupports(p, opts.filter!));\n }\n\n const matrix = all.map((p) => ({\n id: p.id,\n toolName: p.toolName,\n skillsPrecedence: p.capabilities.skills.precedence,\n hooksCount: p.capabilities.hooks.supported.length,\n spawnMechanism: p.capabilities.spawn.spawnMechanism,\n spawnFlags: {\n supportsSubagents: p.capabilities.spawn.supportsSubagents,\n supportsProgrammaticSpawn: p.capabilities.spawn.supportsProgrammaticSpawn,\n supportsInterAgentComms: p.capabilities.spawn.supportsInterAgentComms,\n supportsParallelSpawn: p.capabilities.spawn.supportsParallelSpawn,\n },\n }));\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n capabilities: matrix,\n count: matrix.length,\n filter: opts.filter || null,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(\"\\nProvider Capability Matrix\\n\"));\n\n if (opts.filter) {\n console.log(pc.dim(` Filter: ${opts.filter}\\n`));\n }\n\n // Table header\n console.log(\n ` ${pc.bold(\"Provider\".padEnd(22))} ${pc.bold(\"Skills Precedence\".padEnd(20))} ${pc.bold(\"Hooks\".padEnd(8))} ${pc.bold(\"Spawn\")}`,\n );\n console.log(` ${\"─\".repeat(22)} ${\"─\".repeat(20)} ${\"─\".repeat(8)} ${\"─\".repeat(20)}`);\n\n for (const row of matrix) {\n const hooks = row.hooksCount > 0 ? String(row.hooksCount) : \"-\";\n const spawn = row.spawnMechanism ?? \"-\";\n console.log(\n ` ${row.toolName.padEnd(22)} ${row.skillsPrecedence.padEnd(20)} ${hooks.padEnd(8)} ${spawn}`,\n );\n }\n\n console.log(pc.dim(`\\n ${matrix.length} providers shown`));\n console.log();\n });\n}\n\nfunction buildEnvelope<T>(\n operation: string,\n mvi: import(\"../core/lafs.js\").MVILevel,\n result: T | null,\n error: LAFSErrorShape | null,\n) {\n return {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\" as const,\n _meta: {\n specVersion: \"1.0.0\",\n schemaVersion: \"1.0.0\",\n timestamp: new Date().toISOString(),\n operation,\n requestId: randomUUID(),\n transport: \"cli\" as const,\n strict: true,\n mvi,\n contextVersion: 0,\n },\n success: error === null,\n result,\n error,\n page: null,\n };\n}\n\nfunction emitJsonError(\n operation: string,\n mvi: import(\"../core/lafs.js\").MVILevel,\n code: string,\n message: string,\n category: LAFSErrorCategory,\n details: Record<string, unknown> = {},\n): void {\n const envelope = buildEnvelope(operation, mvi, null, {\n code,\n message,\n category,\n retryable: false,\n retryAfterMs: null,\n details,\n });\n console.error(JSON.stringify(envelope, null, 2));\n}\n","/**\n * skills install command - LAFS-compliant with JSON-first output\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport type { LAFSErrorCategory } from \"@cleocode/lafs-protocol\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitError,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n type MVILevel,\n} from \"../../core/lafs.js\";\nimport { MarketplaceClient } from \"../../core/marketplace/client.js\";\nimport type { MarketplaceResult } from \"../../core/marketplace/types.js\";\nimport { formatNetworkError } from \"../../core/network/fetch.js\";\nimport { buildSkillSubPathCandidates } from \"../../core/paths/standard.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport * as catalog from \"../../core/skills/catalog.js\";\nimport { discoverSkill } from \"../../core/skills/discovery.js\";\nimport { installSkill } from \"../../core/skills/installer.js\";\nimport { recordSkillInstall } from \"../../core/skills/lock.js\";\nimport { cloneRepo } from \"../../core/sources/github.js\";\nimport { cloneGitLabRepo } from \"../../core/sources/gitlab.js\";\nimport { isMarketplaceScoped, parseSource } from \"../../core/sources/parser.js\";\nimport type { Provider, SourceType } from \"../../types.js\";\n\ninterface InstallResultItem {\n name: string;\n scopedName: string;\n canonicalPath: string;\n providers: string[];\n}\n\ninterface FailedResultItem {\n name: string;\n error: string;\n}\n\ninterface InstallSummary {\n installed: InstallResultItem[];\n failed: FailedResultItem[];\n count: {\n installed: number;\n failed: number;\n total: number;\n };\n}\n\nexport function registerSkillsInstall(parent: Command): void {\n parent\n .command(\"install\")\n .description(\"Install a skill from GitHub, URL, marketplace, or registered skill library\")\n .argument(\"[source]\", \"Skill source (GitHub URL, owner/repo, @author/name, skill-name)\")\n .option(\"-a, --agent <name>\", \"Target specific agent(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-g, --global\", \"Install globally\")\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--all\", \"Install to all detected agents\")\n .option(\"--profile <name>\", \"Install a skill library profile (minimal, core, recommended, full)\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (source: string | undefined, opts: {\n agent: string[];\n global?: boolean;\n yes?: boolean;\n all?: boolean;\n profile?: string;\n json?: boolean;\n human?: boolean;\n }) => {\n const operation = \"skills.install\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n // Determine target providers\n let providers: Provider[];\n\n if (opts.all) {\n providers = getInstalledProviders();\n } else if (opts.agent.length > 0) {\n providers = opts.agent\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else {\n providers = getInstalledProviders();\n }\n\n if (providers.length === 0) {\n const message = \"No target providers found. Use --agent or --all.\";\n if (format === \"json\") {\n emitError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n\n // Handle --profile: install an entire skill library profile\n if (opts.profile) {\n await handleProfileInstall(opts.profile, providers, opts.global ?? false, format, operation, mvi);\n return;\n }\n\n // Require source when not using --profile\n if (!source) {\n const message = \"Missing required argument: source\";\n if (format === \"json\") {\n emitError(operation, mvi, ErrorCodes.INVALID_INPUT, message, ErrorCategories.VALIDATION);\n }\n console.error(pc.red(message));\n console.log(pc.dim(\"Usage: caamp skills install <source> or caamp skills install --profile <name>\"));\n process.exit(1);\n }\n\n if (format === \"human\") {\n console.log(pc.dim(`Installing to ${providers.length} provider(s)...`));\n }\n\n let localPath: string | undefined;\n let cleanup: (() => Promise<void>) | undefined;\n let skillName: string;\n let sourceValue: string;\n let sourceType: SourceType;\n\n // Handle marketplace scoped names\n if (isMarketplaceScoped(source)) {\n const sourceResult = await handleMarketplaceSource(\n source,\n providers,\n opts.global ?? false,\n format,\n operation,\n mvi,\n );\n\n if (sourceResult.success) {\n localPath = sourceResult.localPath;\n cleanup = sourceResult.cleanup;\n skillName = sourceResult.skillName;\n sourceValue = sourceResult.sourceValue;\n sourceType = sourceResult.sourceType;\n } else {\n process.exit(1);\n }\n } else {\n // Parse source\n const parsed = parseSource(source);\n skillName = parsed.inferredName;\n sourceValue = parsed.value;\n sourceType = parsed.type;\n\n if (parsed.type === \"github\" && parsed.owner && parsed.repo) {\n try {\n const result = await cloneRepo(parsed.owner, parsed.repo, parsed.ref, parsed.path);\n localPath = result.localPath;\n cleanup = result.cleanup;\n } catch (error) {\n const message = `Failed to clone GitHub repository: ${formatNetworkError(error)}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.NETWORK_ERROR, message, ErrorCategories.TRANSIENT);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n } else if (parsed.type === \"gitlab\" && parsed.owner && parsed.repo) {\n try {\n const result = await cloneGitLabRepo(parsed.owner, parsed.repo, parsed.ref, parsed.path);\n localPath = result.localPath;\n cleanup = result.cleanup;\n } catch (error) {\n const message = `Failed to clone GitLab repository: ${formatNetworkError(error)}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.NETWORK_ERROR, message, ErrorCategories.TRANSIENT);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n } else if (parsed.type === \"local\") {\n localPath = parsed.value;\n // Read SKILL.md for the authoritative name\n const discovered = await discoverSkill(localPath);\n if (discovered) {\n skillName = discovered.name;\n }\n } else if (parsed.type === \"package\") {\n // Check registered skill library for this skill name\n if (!catalog.isCatalogAvailable()) {\n const message = \"No skill library registered. Register one with registerSkillLibraryFromPath() or set CAAMP_SKILL_LIBRARY env var.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.INVALID_INPUT, message, ErrorCategories.VALIDATION);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n const catalogSkill = catalog.getSkill(parsed.inferredName);\n if (catalogSkill) {\n localPath = catalog.getSkillDir(catalogSkill.name);\n skillName = catalogSkill.name;\n sourceValue = `library:${catalogSkill.name}`;\n sourceType = \"library\";\n if (format === \"human\") {\n console.log(` Found in catalog: ${pc.bold(catalogSkill.name)} v${catalogSkill.version} (${pc.dim(catalogSkill.category)})`);\n }\n } else {\n const message = `Skill not found in catalog: ${parsed.inferredName}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.SKILL_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n availableSkills: catalog.listSkills(),\n });\n }\n console.error(pc.red(message));\n console.log(pc.dim(\"Available skills: \" + catalog.listSkills().join(\", \")));\n process.exit(1);\n }\n } else {\n const message = `Unsupported source type: ${parsed.type}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.INVALID_FORMAT, message, ErrorCategories.VALIDATION);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n }\n\n try {\n if (!localPath) {\n const message = \"No local skill path resolved for installation\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.INTERNAL_ERROR, message, ErrorCategories.INTERNAL);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n\n const result = await installSkill(\n localPath,\n skillName!,\n providers,\n opts.global ?? false,\n );\n\n if (result.success) {\n // Record in lock file\n const isGlobal = (sourceType === \"library\" || sourceType === \"package\") ? true : (opts.global ?? false);\n await recordSkillInstall(\n skillName!,\n sourceValue,\n sourceValue,\n sourceType,\n result.linkedAgents,\n result.canonicalPath,\n isGlobal,\n );\n\n const installedItem: InstallResultItem = {\n name: skillName!,\n scopedName: sourceValue,\n canonicalPath: result.canonicalPath,\n providers: result.linkedAgents,\n };\n\n const summary: InstallSummary = {\n installed: [installedItem],\n failed: [],\n count: {\n installed: 1,\n failed: 0,\n total: 1,\n },\n };\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, summary);\n } else {\n console.log(pc.green(`\\n✓ Installed ${pc.bold(skillName)}`));\n console.log(` Canonical: ${pc.dim(result.canonicalPath)}`);\n console.log(` Linked to: ${result.linkedAgents.join(\", \")}`);\n\n if (result.errors.length > 0) {\n console.log(pc.yellow(\"\\nWarnings:\"));\n for (const err of result.errors) {\n console.log(` ${pc.yellow(\"!\")} ${err}`);\n }\n }\n }\n } else {\n const summary: InstallSummary = {\n installed: [],\n failed: [{\n name: skillName!,\n error: result.errors.join(\", \"),\n }],\n count: {\n installed: 0,\n failed: 1,\n total: 1,\n },\n };\n\n if (format === \"json\") {\n const envelope = buildEnvelope(operation, mvi, summary, {\n code: ErrorCodes.INSTALL_FAILED,\n message: result.errors.join(\", \"),\n category: ErrorCategories.INTERNAL,\n retryable: false,\n retryAfterMs: null,\n details: { skillName, sourceValue },\n });\n console.error(JSON.stringify(envelope, null, 2));\n } else {\n console.log(pc.yellow(`\\n✗ Failed to install ${pc.bold(skillName)}`));\n console.log(pc.yellow(\"Errors:\"));\n for (const err of result.errors) {\n console.log(` ${pc.yellow(\"!\")} ${err}`);\n }\n }\n process.exit(1);\n }\n } finally {\n if (cleanup) await cleanup();\n }\n });\n}\n\nasync function handleProfileInstall(\n profileName: string,\n providers: Provider[],\n isGlobal: boolean,\n format: \"json\" | \"human\",\n operation: string,\n mvi: MVILevel,\n): Promise<void> {\n if (!catalog.isCatalogAvailable()) {\n const message = \"No skill library registered. Register one with registerSkillLibraryFromPath() or set CAAMP_SKILL_LIBRARY env var.\";\n if (format === \"json\") {\n emitError(operation, mvi, ErrorCodes.INVALID_INPUT, message, ErrorCategories.VALIDATION);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n\n const profileSkills = catalog.resolveProfile(profileName);\n if (profileSkills.length === 0) {\n const message = `Profile not found: ${profileName}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.SKILL_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n availableProfiles: catalog.listProfiles(),\n });\n }\n console.error(pc.red(message));\n const available = catalog.listProfiles();\n if (available.length > 0) {\n console.log(pc.dim(\"Available profiles: \" + available.join(\", \")));\n }\n process.exit(1);\n }\n\n if (format === \"human\") {\n console.log(`Installing profile ${pc.bold(profileName)} (${profileSkills.length} skill(s))...`);\n console.log(pc.dim(`Target: ${providers.length} provider(s)`));\n }\n\n const installed: InstallResultItem[] = [];\n const failed: FailedResultItem[] = [];\n\n for (const name of profileSkills) {\n const skillDir = catalog.getSkillDir(name);\n try {\n const result = await installSkill(\n skillDir,\n name,\n providers,\n isGlobal,\n );\n\n if (result.success) {\n if (format === \"human\") {\n console.log(pc.green(` + ${name}`));\n }\n await recordSkillInstall(\n name,\n `library:${name}`,\n `library:${name}`,\n \"library\",\n result.linkedAgents,\n result.canonicalPath,\n true,\n );\n installed.push({\n name,\n scopedName: `library:${name}`,\n canonicalPath: result.canonicalPath,\n providers: result.linkedAgents,\n });\n } else {\n if (format === \"human\") {\n console.log(pc.yellow(` ! ${name}: ${result.errors.join(\", \")}`));\n }\n failed.push({\n name,\n error: result.errors.join(\", \"),\n });\n }\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (format === \"human\") {\n console.log(pc.red(` x ${name}: ${errorMsg}`));\n }\n failed.push({\n name,\n error: errorMsg,\n });\n }\n }\n\n const summary: InstallSummary = {\n installed,\n failed,\n count: {\n installed: installed.length,\n failed: failed.length,\n total: profileSkills.length,\n },\n };\n\n if (format === \"json\") {\n if (failed.length > 0) {\n const envelope = buildEnvelope(operation, mvi, summary, {\n code: ErrorCodes.INSTALL_FAILED,\n message: `${failed.length} skill(s) failed to install`,\n category: ErrorCategories.INTERNAL,\n retryable: false,\n retryAfterMs: null,\n details: { failed: failed.map(f => f.name) },\n });\n console.error(JSON.stringify(envelope, null, 2));\n process.exit(1);\n } else {\n outputSuccess(operation, mvi, summary);\n }\n } else {\n console.log(`\\n${pc.green(`${installed.length} installed`)}, ${failed.length > 0 ? pc.yellow(`${failed.length} failed`) : \"0 failed\"}`);\n if (failed.length > 0) {\n process.exit(1);\n }\n }\n}\n\ninterface MarketplaceSourceSuccess {\n success: true;\n localPath: string;\n cleanup: () => Promise<void>;\n skillName: string;\n sourceValue: string;\n sourceType: SourceType;\n}\n\ninterface MarketplaceSourceError {\n success: false;\n}\n\ntype MarketplaceSourceResult = MarketplaceSourceSuccess | MarketplaceSourceError;\n\nasync function handleMarketplaceSource(\n source: string,\n _providers: Provider[],\n _isGlobal: boolean,\n format: \"json\" | \"human\",\n operation: string,\n mvi: MVILevel,\n): Promise<MarketplaceSourceResult> {\n if (format === \"human\") {\n console.log(pc.dim(`Searching marketplace for ${source}...`));\n }\n\n const client = new MarketplaceClient();\n let skill: import(\"../../core/marketplace/types.js\").MarketplaceResult | null;\n\n try {\n skill = await client.getSkill(source);\n } catch (error) {\n const message = `Marketplace lookup failed: ${formatNetworkError(error)}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.NETWORK_ERROR, message, ErrorCategories.TRANSIENT);\n }\n console.error(pc.red(message));\n return { success: false };\n }\n\n if (!skill) {\n const message = `Skill not found: ${source}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.SKILL_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n }\n console.error(pc.red(message));\n return { success: false };\n }\n\n if (format === \"human\") {\n console.log(` Found: ${pc.bold(skill.name)} by ${skill.author} (${pc.dim(skill.repoFullName)})`);\n }\n\n const parsed = parseSource(skill.githubUrl);\n if (parsed.type !== \"github\" || !parsed.owner || !parsed.repo) {\n const message = \"Could not resolve GitHub source\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.INVALID_FORMAT, message, ErrorCategories.VALIDATION);\n }\n console.error(pc.red(message));\n return { success: false };\n }\n\n try {\n const subPathCandidates = buildSkillSubPathCandidates(skill.path, parsed.path);\n let cloneError: unknown;\n let cloned = false;\n let localPath: string | undefined;\n let cleanup: (() => Promise<void>) | undefined;\n\n for (const subPath of subPathCandidates) {\n try {\n const result = await cloneRepo(parsed.owner, parsed.repo, parsed.ref, subPath);\n if (subPath && !existsSync(result.localPath)) {\n await result.cleanup();\n continue;\n }\n localPath = result.localPath;\n cleanup = result.cleanup;\n cloned = true;\n break;\n } catch (error) {\n cloneError = error;\n }\n }\n\n if (!cloned) {\n throw cloneError ?? new Error(\"Unable to resolve skill path from marketplace metadata\");\n }\n\n return {\n success: true,\n localPath: localPath!,\n cleanup: cleanup!,\n skillName: skill.name,\n sourceValue: skill.githubUrl,\n sourceType: parsed.type,\n };\n } catch (error) {\n const message = `Failed to fetch source repository: ${formatNetworkError(error)}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.NETWORK_ERROR, message, ErrorCategories.TRANSIENT);\n }\n console.error(pc.red(message));\n return { success: false };\n }\n}\n","/**\n * GitHub fetcher for skill/MCP sources\n *\n * Clones repos or fetches specific paths via simple-git.\n */\n\nimport { simpleGit } from \"simple-git\";\nimport { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { fetchWithTimeout } from \"../network/fetch.js\";\n\nexport interface GitFetchResult {\n localPath: string;\n cleanup: () => Promise<void>;\n}\n\n/** Clone a GitHub repo to a temp directory */\nexport async function cloneRepo(\n owner: string,\n repo: string,\n ref?: string,\n subPath?: string,\n): Promise<GitFetchResult> {\n const tmpDir = await mkdtemp(join(tmpdir(), \"caamp-\"));\n const repoUrl = `https://github.com/${owner}/${repo}.git`;\n\n const git = simpleGit();\n\n const cloneOptions = [\"--depth\", \"1\"];\n if (ref) {\n cloneOptions.push(\"--branch\", ref);\n }\n\n await git.clone(repoUrl, tmpDir, cloneOptions);\n\n const localPath = subPath ? join(tmpDir, subPath) : tmpDir;\n\n return {\n localPath,\n cleanup: async () => {\n try {\n await rm(tmpDir, { recursive: true });\n } catch {\n // Ignore cleanup errors\n }\n },\n };\n}\n\n/** Fetch a specific file from GitHub using the raw API */\nexport async function fetchRawFile(\n owner: string,\n repo: string,\n path: string,\n ref = \"main\",\n): Promise<string | null> {\n const url = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${path}`;\n\n try {\n const response = await fetchWithTimeout(url);\n if (!response.ok) return null;\n return await response.text();\n } catch {\n return null;\n }\n}\n\n/** Check if a GitHub repo exists */\nexport async function repoExists(owner: string, repo: string): Promise<boolean> {\n try {\n const response = await fetchWithTimeout(`https://api.github.com/repos/${owner}/${repo}`, {\n method: \"HEAD\",\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n","/**\n * GitLab fetcher for skill/MCP sources\n */\n\nimport { simpleGit } from \"simple-git\";\nimport { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { GitFetchResult } from \"./github.js\";\nimport { fetchWithTimeout } from \"../network/fetch.js\";\n\n/** Clone a GitLab repo to a temp directory */\nexport async function cloneGitLabRepo(\n owner: string,\n repo: string,\n ref?: string,\n subPath?: string,\n): Promise<GitFetchResult> {\n const tmpDir = await mkdtemp(join(tmpdir(), \"caamp-gl-\"));\n const repoUrl = `https://gitlab.com/${owner}/${repo}.git`;\n\n const git = simpleGit();\n\n const cloneOptions = [\"--depth\", \"1\"];\n if (ref) {\n cloneOptions.push(\"--branch\", ref);\n }\n\n await git.clone(repoUrl, tmpDir, cloneOptions);\n\n const localPath = subPath ? join(tmpDir, subPath) : tmpDir;\n\n return {\n localPath,\n cleanup: async () => {\n try {\n await rm(tmpDir, { recursive: true });\n } catch {\n // Ignore cleanup errors\n }\n },\n };\n}\n\n/** Fetch a specific file from GitLab using the raw API */\nexport async function fetchGitLabRawFile(\n owner: string,\n repo: string,\n path: string,\n ref = \"main\",\n): Promise<string | null> {\n const encodedPath = encodeURIComponent(path);\n const url = `https://gitlab.com/${owner}/${repo}/-/raw/${ref}/${encodedPath}`;\n\n try {\n const response = await fetchWithTimeout(url);\n if (!response.ok) return null;\n return await response.text();\n } catch {\n return null;\n }\n}\n","/**\n * skills remove command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { listCanonicalSkills, removeSkill } from \"../../core/skills/installer.js\";\nimport { removeSkillFromLock } from \"../../core/skills/lock.js\";\n\nexport function registerSkillsRemove(parent: Command): void {\n parent\n .command(\"remove\")\n .description(\"Remove installed skill(s)\")\n .argument(\"[name]\", \"Skill name to remove\")\n .option(\"-g, --global\", \"Remove from global scope\")\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string | undefined, opts: { global?: boolean; yes?: boolean; json?: boolean; human?: boolean }) => {\n const operation = \"skills.remove\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const providers = getInstalledProviders();\n\n if (name) {\n const result = await removeSkill(name, providers, opts.global ?? false);\n\n const removed = result.removed;\n const count = {\n removed: removed.length,\n total: providers.length,\n };\n\n if (format === \"json\") {\n if (removed.length > 0) {\n await removeSkillFromLock(name);\n }\n\n const errors = result.errors.length > 0\n ? result.errors.map((err) => ({ message: err }))\n : undefined;\n\n outputSuccess(operation, mvi, {\n removed,\n providers: providers.map((p) => p.id),\n count,\n ...(errors && { errors }),\n });\n return;\n }\n\n // Human-readable output\n if (removed.length > 0) {\n console.log(pc.green(`✓ Removed ${pc.bold(name)} from: ${removed.join(\", \")}`));\n await removeSkillFromLock(name);\n } else {\n console.log(pc.yellow(`Skill ${name} not found in any provider.`));\n }\n\n if (result.errors.length > 0) {\n for (const err of result.errors) {\n console.log(pc.red(` ${err}`));\n }\n }\n } else {\n // Interactive mode - list and select\n const skills = await listCanonicalSkills();\n if (skills.length === 0) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n removed: [],\n providers: [],\n count: { removed: 0, total: 0 },\n });\n } else {\n console.log(pc.dim(\"No skills installed.\"));\n }\n return;\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n removed: [],\n providers: [],\n count: { removed: 0, total: 0 },\n available: skills,\n });\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(\"Installed skills:\"));\n for (const s of skills) {\n console.log(` ${s}`);\n }\n console.log(pc.dim(\"\\nUse: caamp skills remove <name>\"));\n }\n });\n}\n","/**\n * skills list command - LAFS-compliant with JSON-first output\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { LAFSErrorCategory } from \"@cleocode/lafs-protocol\";\nimport { resolveOutputFormat } from \"@cleocode/lafs-protocol\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { resolveProviderSkillsDir } from \"../../core/paths/standard.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport { discoverSkillsMulti } from \"../../core/skills/discovery.js\";\n\ninterface SkillsListOptions {\n global?: boolean;\n agent?: string;\n json?: boolean;\n human?: boolean;\n}\n\ninterface LAFSErrorShape {\n code: string;\n message: string;\n category: LAFSErrorCategory;\n retryable: boolean;\n retryAfterMs: number | null;\n details: Record<string, unknown>;\n}\n\nexport function registerSkillsList(parent: Command): void {\n parent\n .command(\"list\")\n .description(\"List installed skills\")\n .option(\"-g, --global\", \"List global skills\")\n .option(\"-a, --agent <name>\", \"List skills for specific agent\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: SkillsListOptions) => {\n const operation = \"skills.list\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n let dirs: string[] = [];\n\n if (opts.agent) {\n const provider = getProvider(opts.agent);\n if (!provider) {\n const message = `Provider not found: ${opts.agent}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_PROVIDER_NOT_FOUND\", message, \"NOT_FOUND\", {\n agent: opts.agent,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n dirs = opts.global\n ? [resolveProviderSkillsDir(provider, \"global\")]\n : [resolveProviderSkillsDir(provider, \"project\")];\n } else if (opts.global) {\n const providers = getInstalledProviders();\n dirs = providers.map((p) => resolveProviderSkillsDir(p, \"global\")).filter(Boolean);\n } else {\n const providers = getInstalledProviders();\n dirs = providers\n .map((p) => resolveProviderSkillsDir(p, \"project\"))\n .filter(Boolean);\n }\n\n const skills = await discoverSkillsMulti(dirs);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n skills,\n count: skills.length,\n scope: opts.global ? \"global\" : opts.agent ? `agent:${opts.agent}` : \"project\",\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n if (skills.length === 0) {\n console.log(pc.dim(\"No skills found.\"));\n return;\n }\n\n console.log(pc.bold(`\\n${skills.length} skill(s) found:\\n`));\n\n skills.forEach((skill, index) => {\n const num = (index + 1).toString().padStart(2);\n console.log(` ${pc.cyan(num)}. ${pc.bold(skill.name.padEnd(30))} ${pc.dim(skill.metadata?.description ?? \"\")}`);\n });\n\n console.log(pc.dim(`\\nInstall with: caamp skills install <name>`));\n console.log(pc.dim(`Remove with: caamp skills remove <name>`));\n });\n}\n\nfunction buildEnvelope<T>(\n operation: string,\n mvi: import(\"../../core/lafs.js\").MVILevel,\n result: T | null,\n error: LAFSErrorShape | null,\n) {\n return {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\" as const,\n _meta: {\n specVersion: \"1.0.0\",\n schemaVersion: \"1.0.0\",\n timestamp: new Date().toISOString(),\n operation,\n requestId: randomUUID(),\n transport: \"cli\" as const,\n strict: true,\n mvi,\n contextVersion: 0,\n },\n success: error === null,\n result,\n error,\n page: null,\n };\n}\n\nfunction emitJsonError(\n operation: string,\n mvi: import(\"../../core/lafs.js\").MVILevel,\n code: string,\n message: string,\n category: LAFSErrorCategory,\n details: Record<string, unknown> = {},\n): void {\n const envelope = buildEnvelope(operation, mvi, null, {\n code,\n message,\n category,\n retryable: false,\n retryAfterMs: null,\n details,\n });\n console.error(JSON.stringify(envelope, null, 2));\n}\n","/**\n * skills find command - marketplace search + recommendation mode\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n type LAFSErrorCategory,\n resolveOutputFormat,\n} from \"@cleocode/lafs-protocol\";\nimport type { MVILevel } from \"../../core/lafs.js\";\nimport { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { MarketplaceClient } from \"../../core/marketplace/client.js\";\nimport type { MarketplaceResult } from \"../../core/marketplace/types.js\";\nimport { formatNetworkError } from \"../../core/network/fetch.js\";\nimport {\n type RankedSkillRecommendation,\n RECOMMENDATION_ERROR_CODES,\n tokenizeCriteriaValue,\n} from \"../../core/skills/recommendation.js\";\nimport {\n formatSkillRecommendations,\n recommendSkills as recommendSkillsByQuery,\n} from \"../../core/skills/recommendation-api.js\";\n\ninterface SkillsFindOptions {\n json?: boolean;\n human?: boolean;\n limit: string;\n recommend?: boolean;\n top: string;\n details?: boolean;\n mustHave: string[];\n prefer: string[];\n exclude: string[];\n select?: string;\n}\n\nimport type { LAFSErrorShape } from \"../../core/lafs.js\";\n\nclass SkillsFindValidationError extends Error {\n code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.code = code;\n this.name = \"SkillsFindValidationError\";\n }\n}\n\ninterface RecommendationOption {\n rank: number;\n scopedName: string;\n description: string;\n score: number;\n why: string;\n source: string;\n evidence?: {\n reasons: RankedSkillRecommendation[\"reasons\"];\n breakdown?: RankedSkillRecommendation[\"breakdown\"];\n };\n}\n\nexport function registerSkillsFind(parent: Command): void {\n parent\n .command(\"find\")\n .description(\"Search marketplace for skills\")\n .argument(\"[query]\", \"Search query\")\n .option(\"--recommend\", \"Recommend skills from constraints\")\n .option(\"--top <n>\", \"Number of recommendation candidates\", \"3\")\n .option(\"--must-have <term>\", \"Required criteria term\", (value, previous: string[]) => [...previous, value], [])\n .option(\"--prefer <term>\", \"Preferred criteria term\", (value, previous: string[]) => [...previous, value], [])\n .option(\"--exclude <term>\", \"Excluded criteria term\", (value, previous: string[]) => [...previous, value], [])\n .option(\"--details\", \"Include expanded machine output\")\n .option(\"--human\", \"Force human-readable output\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--select <indexes>\", \"Pre-select recommendation ranks (comma-separated)\")\n .option(\"-l, --limit <n>\", \"Max results\", \"20\")\n .action(async (query: string | undefined, opts: SkillsFindOptions) => {\n const operation = opts.recommend ? \"skills.find.recommend\" : \"skills.find.search\";\n const details = Boolean(opts.details);\n const mvi: MVILevel = details ? \"full\" : \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (opts.json) {\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n if (opts.recommend) {\n try {\n const top = parseTop(opts.top);\n const mustHave = parseConstraintList(opts.mustHave);\n const prefer = parseConstraintList(opts.prefer);\n const exclude = parseConstraintList(opts.exclude);\n validateCriteriaConflicts(mustHave, prefer, exclude);\n const selectedRanks = parseSelectList(opts.select);\n const seedQuery = buildSeedQuery(query, mustHave, prefer, exclude);\n\n const recommendation = await recommendSkillsByQuery(\n seedQuery,\n {\n mustHave,\n prefer,\n exclude,\n },\n {\n top,\n includeDetails: details,\n },\n );\n const options = normalizeRecommendationOptions(recommendation.ranking, details);\n validateSelectedRanks(selectedRanks, options.length);\n const selected = selectedRanks.length > 0\n ? options.filter((option) => selectedRanks.includes(option.rank))\n : [];\n\n if (format === \"json\") {\n const result = formatSkillRecommendations(recommendation, { mode: \"json\", details }) as Record<string, unknown>;\n const resultOptions = Array.isArray(result.options)\n ? result.options as Array<Record<string, unknown>>\n : [];\n const selectedObjects = resultOptions.filter((option) =>\n selectedRanks.includes(Number(option.rank ?? 0))\n );\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n ...result,\n selected: selectedObjects,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n const human = formatSkillRecommendations(recommendation, { mode: \"human\", details }) as string;\n console.log(human);\n if (selected.length > 0) {\n console.log(`Selected: ${selected.map((option) => option.scopedName).join(\", \")}`);\n }\n return;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const errorCode =\n error instanceof SkillsFindValidationError\n ? error.code\n : (error as { code?: string }).code ?? RECOMMENDATION_ERROR_CODES.SOURCE_UNAVAILABLE;\n const category: LAFSErrorCategory =\n errorCode === RECOMMENDATION_ERROR_CODES.CRITERIA_CONFLICT\n ? \"CONFLICT\"\n : errorCode === RECOMMENDATION_ERROR_CODES.NO_MATCHES\n ? \"NOT_FOUND\"\n : errorCode === RECOMMENDATION_ERROR_CODES.QUERY_INVALID\n ? \"VALIDATION\"\n : \"INTERNAL\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, errorCode, message, category, {\n query: query ?? null,\n });\n } else {\n console.error(pc.red(`Recommendation failed: ${message}`));\n }\n process.exit(1);\n }\n }\n\n if (!query) {\n console.log(pc.dim(\"Usage: caamp skills find <query>\"));\n return;\n }\n\n const limit = parseInt(opts.limit, 10);\n const client = new MarketplaceClient();\n\n if (format === \"human\") {\n console.log(pc.dim(`Searching marketplaces for \"${query}\"...\\n`));\n }\n\n let results: MarketplaceResult[];\n try {\n results = await client.search(query, limit);\n } catch (error) {\n const message = formatNetworkError(error);\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_SEARCH_FAILED\", message, \"TRANSIENT\", {\n query,\n limit,\n });\n } else {\n console.error(pc.red(`Marketplace search failed: ${message}`));\n }\n process.exit(1);\n }\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n query,\n results,\n count: results.length,\n limit,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n if (results.length === 0) {\n console.log(pc.yellow(\"No results found.\"));\n return;\n }\n\n console.log(pc.dim(`Found ${results.length} result(s) for \"${query}\":\\n`));\n\n results.forEach((skill, index) => {\n const num = (index + 1).toString().padStart(2);\n const stars = skill.stars > 0 ? pc.yellow(`★ ${formatStars(skill.stars)}`) : \"\";\n console.log(` ${pc.cyan(num)}. ${pc.bold(skill.scopedName)} ${stars}`);\n console.log(` ${pc.dim(skill.description?.slice(0, 80) ?? \"\")}`);\n console.log(` ${pc.dim(`from ${skill.source}`)}`);\n console.log();\n });\n\n console.log(pc.dim(\"Install with: caamp skills install <name>\"));\n console.log(pc.dim(\"Or select by number: caamp skills install <n>\"));\n });\n}\n\nfunction formatStars(n: number): string {\n if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;\n return String(n);\n}\n\nfunction parseConstraintList(values: string[]): string[] {\n const normalized = values.flatMap((value) => tokenizeCriteriaValue(value));\n return Array.from(new Set(normalized));\n}\n\nfunction parseTop(value: string): number {\n const parsed = Number.parseInt(value, 10);\n if (!Number.isInteger(parsed) || parsed < 1 || parsed > 20) {\n throw new SkillsFindValidationError(RECOMMENDATION_ERROR_CODES.QUERY_INVALID, \"--top must be an integer between 1 and 20\");\n }\n return parsed;\n}\n\nfunction parseSelectList(value: string | undefined): number[] {\n if (!value) return [];\n const parsed = value\n .split(\",\")\n .map((entry) => Number.parseInt(entry.trim(), 10))\n .filter((entry) => Number.isInteger(entry) && entry > 0);\n return Array.from(new Set(parsed));\n}\n\nfunction buildSeedQuery(query: string | undefined, mustHave: string[], prefer: string[], exclude: string[]): string {\n if (query && query.trim().length > 0) {\n return query;\n }\n\n const seedTerms = [...mustHave, ...prefer, ...exclude].filter((term) => term.length > 0);\n if (seedTerms.length > 0) {\n return seedTerms.join(\" \");\n }\n\n throw new SkillsFindValidationError(\n RECOMMENDATION_ERROR_CODES.QUERY_INVALID,\n \"Recommendation mode requires a query or at least one criteria flag.\",\n );\n}\n\nfunction normalizeRecommendationOptions(ranking: RankedSkillRecommendation[], details: boolean): RecommendationOption[] {\n return ranking.map((entry, index) => {\n const whyCodes = entry.reasons.map((reason) => reason.code);\n return {\n rank: index + 1,\n scopedName: entry.skill.scopedName,\n description: entry.skill.description,\n score: entry.score,\n why: whyCodes.length > 0 ? whyCodes.join(\", \") : \"score-based match\",\n source: entry.skill.source,\n ...(details\n ? {\n evidence: {\n reasons: entry.reasons,\n breakdown: entry.breakdown,\n },\n }\n : {}),\n };\n });\n}\n\nfunction validateCriteriaConflicts(mustHave: string[], prefer: string[], exclude: string[]): void {\n const overlap = mustHave.filter((term) => exclude.includes(term));\n if (overlap.length > 0) {\n throw new SkillsFindValidationError(\n RECOMMENDATION_ERROR_CODES.CRITERIA_CONFLICT,\n \"A criteria term cannot be both required and excluded.\",\n );\n }\n\n const preferOverlap = prefer.filter((term) => exclude.includes(term));\n if (preferOverlap.length > 0) {\n throw new SkillsFindValidationError(\n RECOMMENDATION_ERROR_CODES.CRITERIA_CONFLICT,\n \"A criteria term cannot be both preferred and excluded.\",\n );\n }\n}\n\nfunction validateSelectedRanks(selectedRanks: number[], total: number): void {\n for (const rank of selectedRanks) {\n if (rank < 1 || rank > total) {\n throw new SkillsFindValidationError(\n RECOMMENDATION_ERROR_CODES.QUERY_INVALID,\n `--select rank ${rank} is out of range (1-${total}).`,\n );\n }\n }\n}\n\nfunction buildEnvelope<T>(operation: string, mvi: MVILevel, result: T | null, error: LAFSErrorShape | null) {\n return {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\" as const,\n _meta: {\n specVersion: \"1.0.0\",\n schemaVersion: \"1.0.0\",\n timestamp: new Date().toISOString(),\n operation,\n requestId: randomUUID(),\n transport: \"cli\" as const,\n strict: true,\n mvi,\n contextVersion: 0,\n },\n success: error === null,\n result,\n error,\n page: null,\n };\n}\n\nfunction emitJsonError(\n operation: string,\n mvi: MVILevel,\n code: string,\n message: string,\n category: LAFSErrorCategory,\n details: Record<string, unknown> = {},\n): void {\n const envelope = buildEnvelope(operation, mvi, null, {\n code,\n message,\n category,\n retryable: false,\n retryAfterMs: null,\n details,\n });\n console.error(JSON.stringify(envelope, null, 2));\n}\n","/**\n * skills check command - check for updates - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { checkSkillUpdate, getTrackedSkills } from \"../../core/skills/lock.js\";\n\nexport function registerSkillsCheck(parent: Command): void {\n parent\n .command(\"check\")\n .description(\"Check for available skill updates\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { json?: boolean; human?: boolean }) => {\n const operation = \"skills.check\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const tracked = await getTrackedSkills();\n const entries = Object.entries(tracked);\n\n if (entries.length === 0) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n skills: [],\n outdated: 0,\n total: 0,\n });\n } else {\n console.log(pc.dim(\"No tracked skills.\"));\n }\n return;\n }\n\n if (format === \"human\") {\n console.log(pc.dim(`Checking ${entries.length} skill(s) for updates...\\n`));\n }\n\n const skillResults = [];\n let updatesAvailable = 0;\n\n for (const [name, entry] of entries) {\n const update = await checkSkillUpdate(name);\n const hasUpdate = update.hasUpdate ?? false;\n\n if (hasUpdate) {\n updatesAvailable++;\n }\n\n skillResults.push({\n name,\n currentVersion: update.currentVersion ?? entry.version ?? \"unknown\",\n latestVersion: update.latestVersion ?? \"unknown\",\n hasUpdate,\n source: entry.source,\n agents: entry.agents,\n });\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n skills: skillResults.map((s) => ({\n name: s.name,\n currentVersion: s.currentVersion,\n latestVersion: s.latestVersion,\n hasUpdate: s.hasUpdate,\n })),\n outdated: updatesAvailable,\n total: entries.length,\n });\n return;\n }\n\n // Human-readable output\n for (const r of skillResults) {\n let statusLabel: string;\n if (r.hasUpdate) {\n statusLabel = pc.yellow(\"update available\");\n } else if (r.currentVersion !== \"unknown\") {\n statusLabel = pc.green(\"up to date\");\n } else {\n statusLabel = pc.dim(\"unknown\");\n }\n\n console.log(` ${pc.bold(r.name.padEnd(30))} ${statusLabel}`);\n\n if (r.currentVersion !== \"unknown\" || r.latestVersion !== \"unknown\") {\n const current = r.currentVersion !== \"unknown\" ? r.currentVersion.slice(0, 12) : \"?\";\n const latest = r.latestVersion !== \"unknown\" ? r.latestVersion : \"?\";\n if (r.hasUpdate) {\n console.log(` ${pc.dim(\"current:\")} ${current} ${pc.dim(\"->\")} ${pc.cyan(latest)}`);\n } else {\n console.log(` ${pc.dim(\"version:\")} ${current}`);\n }\n }\n\n console.log(` ${pc.dim(`source: ${r.source}`)}`);\n console.log(` ${pc.dim(`agents: ${r.agents.join(\", \")}`)}`);\n console.log();\n }\n\n if (updatesAvailable > 0) {\n console.log(pc.yellow(`${updatesAvailable} update(s) available.`));\n console.log(pc.dim(\"Run `caamp skills update` to update all.\"));\n } else {\n console.log(pc.green(\"All skills are up to date.\"));\n }\n });\n}\n","/**\n * skills update command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport { installSkill } from \"../../core/skills/installer.js\";\nimport { checkSkillUpdate, getTrackedSkills, recordSkillInstall } from \"../../core/skills/lock.js\";\nimport { cloneRepo } from \"../../core/sources/github.js\";\nimport { cloneGitLabRepo } from \"../../core/sources/gitlab.js\";\nimport { parseSource } from \"../../core/sources/parser.js\";\nimport type { Provider } from \"../../types.js\";\n\nexport function registerSkillsUpdate(parent: Command): void {\n parent\n .command(\"update\")\n .description(\"Update all outdated skills\")\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { yes?: boolean; json?: boolean; human?: boolean }) => {\n const operation = \"skills.update\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const tracked = await getTrackedSkills();\n const entries = Object.entries(tracked);\n\n if (entries.length === 0) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n updated: [],\n failed: [],\n skipped: [],\n count: { updated: 0, failed: 0, skipped: 0 },\n });\n } else {\n console.log(pc.dim(\"No tracked skills to update.\"));\n }\n return;\n }\n\n if (format === \"human\") {\n console.log(pc.dim(`Checking ${entries.length} skill(s) for updates...`));\n }\n\n // Check all skills for updates\n const outdated: Array<{\n name: string;\n currentVersion?: string;\n latestVersion?: string;\n }> = [];\n\n for (const [name] of entries) {\n const result = await checkSkillUpdate(name);\n if (result.hasUpdate) {\n outdated.push({\n name,\n currentVersion: result.currentVersion,\n latestVersion: result.latestVersion,\n });\n }\n }\n\n if (outdated.length === 0) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n updated: [],\n failed: [],\n skipped: [],\n count: { updated: 0, failed: 0, skipped: 0 },\n });\n } else {\n console.log(pc.green(\"\\nAll skills are up to date.\"));\n }\n return;\n }\n\n if (format === \"human\") {\n console.log(pc.yellow(`\\n${outdated.length} skill(s) have updates available:\\n`));\n\n for (const skill of outdated) {\n const current = skill.currentVersion?.slice(0, 12) ?? \"?\";\n const latest = skill.latestVersion ?? \"?\";\n console.log(` ${pc.bold(skill.name)} ${pc.dim(current)} ${pc.dim(\"->\")} ${pc.cyan(latest)}`);\n }\n }\n\n // Confirm unless --yes\n if (!opts.yes && format === \"human\") {\n const readline = await import(\"node:readline\");\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const answer = await new Promise<string>((resolve) => {\n rl.question(pc.dim(\"\\nProceed with update? [y/N] \"), resolve);\n });\n rl.close();\n\n if (answer.toLowerCase() !== \"y\" && answer.toLowerCase() !== \"yes\") {\n console.log(pc.dim(\"Update cancelled.\"));\n return;\n }\n }\n\n if (format === \"human\") {\n console.log();\n }\n\n // Track results for JSON output\n const updated: string[] = [];\n const failed: Array<{ name: string; error: string }> = [];\n const skipped: string[] = [];\n\n // Update each outdated skill\n for (const skill of outdated) {\n const entry = tracked[skill.name];\n if (!entry) continue;\n\n if (format === \"human\") {\n console.log(pc.dim(`Updating ${pc.bold(skill.name)}...`));\n }\n\n try {\n const parsed = parseSource(entry.source);\n let localPath: string;\n let cleanup: (() => Promise<void>) | undefined;\n\n if (parsed.type === \"github\" && parsed.owner && parsed.repo) {\n const result = await cloneRepo(parsed.owner, parsed.repo, parsed.ref, parsed.path);\n localPath = result.localPath;\n cleanup = result.cleanup;\n } else if (parsed.type === \"gitlab\" && parsed.owner && parsed.repo) {\n const result = await cloneGitLabRepo(parsed.owner, parsed.repo, parsed.ref, parsed.path);\n localPath = result.localPath;\n cleanup = result.cleanup;\n } else {\n if (format === \"human\") {\n console.log(pc.yellow(` Skipped ${skill.name}: source type \"${parsed.type}\" does not support auto-update`));\n }\n skipped.push(skill.name);\n continue;\n }\n\n try {\n // Resolve providers from the lock entry's agent list\n const providers = entry.agents\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n\n if (providers.length === 0) {\n if (format === \"human\") {\n console.log(pc.yellow(` Skipped ${skill.name}: no valid providers found`));\n }\n skipped.push(skill.name);\n continue;\n }\n\n const installResult = await installSkill(\n localPath,\n skill.name,\n providers,\n entry.isGlobal,\n entry.projectDir,\n );\n\n if (installResult.success) {\n // Record the updated version in the lock file\n await recordSkillInstall(\n skill.name,\n entry.scopedName,\n entry.source,\n entry.sourceType,\n installResult.linkedAgents,\n installResult.canonicalPath,\n entry.isGlobal,\n entry.projectDir,\n skill.latestVersion,\n );\n\n if (format === \"human\") {\n console.log(pc.green(` Updated ${pc.bold(skill.name)}`));\n }\n updated.push(skill.name);\n } else {\n if (format === \"human\") {\n console.log(pc.red(` Failed to update ${skill.name}: no agents linked`));\n }\n failed.push({ name: skill.name, error: \"no agents linked\" });\n }\n\n if (installResult.errors.length > 0 && format === \"human\") {\n for (const err of installResult.errors) {\n console.log(pc.yellow(` ${err}`));\n }\n }\n } finally {\n if (cleanup) await cleanup();\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (format === \"human\") {\n console.log(pc.red(` Failed to update ${skill.name}: ${msg}`));\n }\n failed.push({ name: skill.name, error: msg });\n }\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n updated,\n failed,\n skipped,\n count: {\n updated: updated.length,\n failed: failed.length,\n skipped: skipped.length,\n },\n });\n return;\n }\n\n // Human-readable output\n console.log();\n if (updated.length > 0) {\n console.log(pc.green(`Updated ${updated.length} skill(s).`));\n }\n if (failed.length > 0) {\n console.log(pc.red(`Failed to update ${failed.length} skill(s).`));\n }\n });\n}\n","/**\n * skills init command - scaffold a new skill - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync } from \"node:fs\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\n\nexport function registerSkillsInit(parent: Command): void {\n parent\n .command(\"init\")\n .description(\"Create a new SKILL.md template\")\n .argument(\"[name]\", \"Skill name\")\n .option(\"-d, --dir <path>\", \"Output directory\", \".\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string | undefined, opts: { dir: string; json?: boolean; human?: boolean }) => {\n const operation = \"skills.init\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const skillName = name ?? \"my-skill\";\n const skillDir = join(opts.dir, skillName);\n\n if (existsSync(skillDir)) {\n const message = `Directory already exists: ${skillDir}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.INVALID_CONSTRAINT, message, ErrorCategories.CONFLICT, {\n path: skillDir,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n await mkdir(skillDir, { recursive: true });\n\n const template = `---\nname: ${skillName}\ndescription: Describe what this skill does and when to use it\nlicense: MIT\nmetadata:\n author: your-name\n version: \"1.0\"\n---\n\n# ${skillName}\n\n## When to use this skill\n\nDescribe the conditions under which an AI agent should activate this skill.\n\n## Instructions\n\nProvide detailed instructions for the AI agent here.\n\n## Examples\n\nShow example inputs and expected outputs.\n`;\n\n await writeFile(join(skillDir, \"SKILL.md\"), template, \"utf-8\");\n\n const result = {\n name: skillName,\n directory: skillDir,\n template: \"SKILL.md\",\n created: true,\n };\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, result);\n return;\n }\n\n // Human-readable output\n console.log(pc.green(`✓ Created skill template: ${skillDir}/SKILL.md`));\n console.log(pc.dim(\"\\nNext steps:\"));\n console.log(pc.dim(\" 1. Edit SKILL.md with your instructions\"));\n console.log(pc.dim(` 2. Validate: caamp skills validate ${join(skillDir, \"SKILL.md\")}`));\n console.log(pc.dim(` 3. Install: caamp skills install ${skillDir}`));\n });\n}\n","/**\n * skills audit command - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync, statSync } from \"node:fs\";\nimport type { LAFSErrorCategory } from \"@cleocode/lafs-protocol\";\nimport { resolveOutputFormat } from \"@cleocode/lafs-protocol\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n type LAFSErrorShape,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { scanDirectory, scanFile, toSarif } from \"../../core/skills/audit/scanner.js\";\nimport type { AuditResult } from \"../../types.js\";\n\ninterface SkillsAuditOptions {\n sarif?: boolean;\n json?: boolean;\n human?: boolean;\n}\n\ninterface AuditFileResult {\n path: string;\n score: number;\n findings: Array<{\n level: \"critical\" | \"high\" | \"medium\" | \"low\";\n code: string;\n message: string;\n line?: number;\n }>;\n}\n\ninterface AuditSummary {\n scanned: number;\n findings: number;\n files: AuditFileResult[];\n}\n\nexport function registerSkillsAudit(parent: Command): void {\n parent\n .command(\"audit\")\n .description(\"Security scan skill files (46+ rules, SARIF output)\")\n .argument(\"[path]\", \"Path to SKILL.md or directory\", \".\")\n .option(\"--sarif\", \"Output in SARIF format (raw SARIF, not LAFS envelope)\")\n .option(\"--json\", \"Output as JSON (LAFS envelope)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (path: string, opts: SkillsAuditOptions) => {\n const operation = \"skills.audit\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n // Check if path exists\n if (!existsSync(path)) {\n const message = `Path not found: ${path}`;\n \n // Check if --sarif was explicitly requested\n if (opts.sarif) {\n // For SARIF mode on error, output minimal SARIF with error\n console.error(JSON.stringify({\n $schema: \"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json\",\n version: \"2.1.0\",\n runs: [{\n tool: { driver: { name: \"caamp-skills-audit\" } },\n invocations: [{\n executionSuccessful: false,\n exitCode: 1,\n exitCodeDescription: message,\n }],\n results: [],\n }],\n }, null, 2));\n } else {\n // LAFS envelope error\n emitJsonError(operation, mvi, ErrorCodes.FILE_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n path,\n });\n }\n process.exit(1);\n }\n\n // Resolve output format (SARIF is a special case - outputs raw SARIF, not LAFS envelope)\n let format: \"json\" | \"human\" | \"sarif\";\n try {\n if (opts.sarif) {\n // SARIF is handled separately - it outputs raw SARIF format\n format = \"sarif\";\n } else {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n // Perform the scan\n const stat = statSync(path);\n let results: AuditResult[];\n\n try {\n if (stat.isFile()) {\n results = [await scanFile(path)];\n } else {\n results = await scanDirectory(path);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n \n if (format === \"sarif\") {\n console.error(JSON.stringify({\n $schema: \"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json\",\n version: \"2.1.0\",\n runs: [{\n tool: { driver: { name: \"caamp-skills-audit\" } },\n invocations: [{\n executionSuccessful: false,\n exitCode: 1,\n exitCodeDescription: message,\n }],\n results: [],\n }],\n }, null, 2));\n } else {\n emitJsonError(operation, mvi, ErrorCodes.AUDIT_FAILED, message, ErrorCategories.INTERNAL, {\n path,\n });\n }\n process.exit(1);\n }\n\n // Handle no results case\n if (results.length === 0) {\n if (format === \"sarif\") {\n console.log(JSON.stringify(toSarif([]), null, 2));\n return;\n }\n\n if (format === \"json\") {\n const summary: AuditSummary = {\n scanned: 0,\n findings: 0,\n files: [],\n };\n outputSuccess(operation, mvi, summary);\n return;\n }\n\n // Human-readable\n console.log(pc.dim(\"No SKILL.md files found to scan.\"));\n return;\n }\n\n // Calculate summary\n const summary: AuditSummary = {\n scanned: results.length,\n findings: results.reduce((acc, r) => acc + r.findings.length, 0),\n files: results.map((r) => ({\n path: r.file,\n score: r.score,\n findings: r.findings.map((f) => ({\n level: f.rule.severity as \"critical\" | \"high\" | \"medium\" | \"low\",\n code: f.rule.id,\n message: `${f.rule.name}: ${f.rule.description}`,\n line: f.line,\n })),\n })),\n };\n\n // Check if all passed\n const allPassed = results.every((r) => r.passed);\n\n // SARIF output (raw SARIF format, not LAFS envelope)\n if (format === \"sarif\") {\n console.log(JSON.stringify(toSarif(results), null, 2));\n if (!allPassed) {\n process.exit(1);\n }\n return;\n }\n\n // LAFS JSON output\n if (format === \"json\") {\n outputSuccess(operation, mvi, summary);\n if (!allPassed) {\n process.exit(1);\n }\n return;\n }\n\n // Human-readable output\n let totalFindings = 0;\n\n for (const result of results) {\n const icon = result.passed ? pc.green(\"✓\") : pc.red(\"✗\");\n console.log(`\\n${icon} ${pc.bold(result.file)} (score: ${result.score}/100)`);\n\n if (result.findings.length === 0) {\n console.log(pc.dim(\" No issues found.\"));\n continue;\n }\n\n totalFindings += result.findings.length;\n\n for (const f of result.findings) {\n const sev = f.rule.severity === \"critical\" ? pc.red(f.rule.severity)\n : f.rule.severity === \"high\" ? pc.red(f.rule.severity)\n : f.rule.severity === \"medium\" ? pc.yellow(f.rule.severity)\n : pc.dim(f.rule.severity);\n\n console.log(` ${sev.padEnd(20)} ${f.rule.id} ${f.rule.name}`);\n console.log(` ${pc.dim(`L${f.line}: ${f.context.slice(0, 80)}`)}`);\n }\n }\n\n console.log(pc.bold(`\\n${results.length} file(s) scanned, ${totalFindings} finding(s)`));\n\n if (!allPassed) {\n process.exit(1);\n }\n });\n}\n","/**\n * skills validate command - LAFS-compliant with JSON-first output\n */\n\nimport type { LAFSErrorCategory } from \"@cleocode/lafs-protocol\";\nimport { resolveOutputFormat } from \"@cleocode/lafs-protocol\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { validateSkill } from \"../../core/skills/validator.js\";\n\ninterface LAFSErrorShape {\n code: string;\n message: string;\n category: LAFSErrorCategory;\n retryable: boolean;\n retryAfterMs: number | null;\n details: Record<string, unknown>;\n}\n\nexport function registerSkillsValidate(parent: Command): void {\n parent\n .command(\"validate\")\n .description(\"Validate SKILL.md format\")\n .argument(\"[path]\", \"Path to SKILL.md\", \"SKILL.md\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (path: string, opts: { json?: boolean; human?: boolean }) => {\n const operation = \"skills.validate\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n let result;\n try {\n result = await validateSkill(path);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.FILE_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n path,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n valid: result.valid,\n file: path,\n issues: result.issues.map((issue) => ({\n level: issue.level === \"error\" ? \"error\" : \"warn\",\n field: issue.field,\n message: issue.message,\n })),\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n } else {\n // Human-readable output\n if (result.valid) {\n console.log(pc.green(`✓ ${path} is valid`));\n } else {\n console.log(pc.red(`✗ ${path} has validation errors`));\n }\n\n for (const issue of result.issues) {\n const icon = issue.level === \"error\" ? pc.red(\"✗\") : pc.yellow(\"!\");\n console.log(` ${icon} [${issue.field}] ${issue.message}`);\n }\n }\n\n if (!result.valid) {\n process.exit(1);\n }\n });\n}\n","/**\n * Skills command group registration\n */\n\nimport type { Command } from \"commander\";\nimport { registerSkillsInstall } from \"./install.js\";\nimport { registerSkillsRemove } from \"./remove.js\";\nimport { registerSkillsList } from \"./list.js\";\nimport { registerSkillsFind } from \"./find.js\";\nimport { registerSkillsCheck } from \"./check.js\";\nimport { registerSkillsUpdate } from \"./update.js\";\nimport { registerSkillsInit } from \"./init.js\";\nimport { registerSkillsAudit } from \"./audit.js\";\nimport { registerSkillsValidate } from \"./validate.js\";\n\nexport function registerSkillsCommands(program: Command): void {\n const skills = program\n .command(\"skills\")\n .description(\"Manage AI agent skills\");\n\n registerSkillsInstall(skills);\n registerSkillsRemove(skills);\n registerSkillsList(skills);\n registerSkillsFind(skills);\n registerSkillsCheck(skills);\n registerSkillsUpdate(skills);\n registerSkillsInit(skills);\n registerSkillsAudit(skills);\n registerSkillsValidate(skills);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,eAAe;;;ACFxB,SAAS,gBAAgB;;;ACAzB,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,OAKK;AAgBA,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YACE,MACA,SACA,YACA,cAAc,MACd,SACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW,mBAAmB,IAAI;AACvC,SAAK,c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O;AAChC,uBAAuB,OAAO;AAC9B,oBAAoB,OAAO;AAC3B,qBAAqB,OAAO;AAC5B,6BAA6B,OAAO;AACpC,sBAAsB,OAAO;AAC7B,sBAAsB,OAAO;AAC7B,yBAAyB,OAAO;AAEhC,SAAS,QAAQ,OAAuB;AACtC,MAAI,iBAAiB,MAAO,QAAO;AACnC,SAAO,IAAI,MAAM,OAAO,KAAK,CAAC;AAChC;AAEA,SAAS,YAAY,OAAgB,QAAkE;AACrG,QAAM,aAAa,QAAQ,KAAK;AAChC,UAAQ,MAAM,gBAAgB,MAAM,MAAM,WAAW,OAAO,EAAE;AAC9D,MAAI,UAAU,KAAK,WAAW,OAAO;AACnC,YAAQ,MAAM,WAAW,KAAK;AAAA,EAChC;AACF;AAEA,QAAQ,GAAG,qBAAqB,CAAC,UAAU;AACzC,cAAY,OAAO,mBAAmB;AACtC,UAAQ,KAAK,CAAC;AAChB,CAAC;AAED,QAAQ,GAAG,sBAAsB,CAAC,WAAW;AAC3C,cAAY,QAAQ,oBAAoB;AACxC,UAAQ,KAAK,CAAC;AAChB,CAAC;AAED,eAAe,OAAsB;AACnC,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,cAAY,OAAO,KAAK;AACxB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["program","randomUUID","randomUUID","emitError","program","existsSync","join","pc","existsSync","join","pc","program","pc","pc","pc","pc","pc","pc","program","pc","pc","program","existsSync","pc","existsSync","pc","pc","pc","pc","pc","pc","pc","program","randomUUID","resolveOutputFormat","pc","program","resolveOutputFormat","emitJsonError","buildEnvelope","pc","canonical","hooks","randomUUID","existsSync","pc","join","join","simpleGit","mkdtemp","rm","tmpdir","join","mkdtemp","join","tmpdir","simpleGit","rm","emitError","pc","existsSync","pc","pc","randomUUID","resolveOutputFormat","pc","resolveOutputFormat","emitJsonError","pc","buildEnvelope","randomUUID","randomUUID","resolveOutputFormat","pc","resolveOutputFormat","emitJsonError","pc","buildEnvelope","randomUUID","pc","pc","pc","pc","existsSync","join","pc","join","existsSync","pc","existsSync","pc","existsSync","summary","pc","resolveOutputFormat","pc","resolveOutputFormat","pc","program"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/commands/advanced/common.ts","../src/commands/advanced/lafs.ts","../src/commands/advanced/providers.ts","../src/commands/advanced/batch.ts","../src/commands/advanced/conflicts.ts","../src/commands/advanced/apply.ts","../src/commands/advanced/instructions.ts","../src/commands/advanced/configure.ts","../src/commands/advanced/index.ts","../src/commands/config.ts","../src/core/lafs.ts","../src/commands/doctor.ts","../src/core/version.ts","../src/commands/instructions/inject.ts","../src/commands/instructions/check.ts","../src/commands/instructions/update.ts","../src/commands/instructions/index.ts","../src/commands/mcp/cleo.ts","../src/commands/mcp/detect.ts","../src/commands/mcp/install.ts","../src/commands/mcp/list.ts","../src/commands/mcp/remove.ts","../src/commands/mcp/index.ts","../src/commands/providers.ts","../src/commands/skills/install.ts","../src/core/sources/github.ts","../src/core/sources/gitlab.ts","../src/commands/skills/remove.ts","../src/commands/skills/list.ts","../src/commands/skills/find.ts","../src/commands/skills/check.ts","../src/commands/skills/update.ts","../src/commands/skills/init.ts","../src/commands/skills/audit.ts","../src/commands/skills/validate.ts","../src/commands/skills/index.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * CAAMP CLI - Central AI Agent Managed Packages\n */\n\nimport { Command } from \"commander\";\nimport { registerAdvancedCommands } from \"./commands/advanced/index.js\";\nimport { registerConfigCommand } from \"./commands/config.js\";\nimport { registerDoctorCommand } from \"./commands/doctor.js\";\nimport { registerInstructionsCommands } from \"./commands/instructions/index.js\";\nimport { registerCleoCommands } from \"./commands/mcp/cleo.js\";\nimport { registerMcpCommands } from \"./commands/mcp/index.js\";\nimport { registerProvidersCommand } from \"./commands/providers.js\";\nimport { registerSkillsCommands } from \"./commands/skills/index.js\";\nimport { isVerbose, setHuman, setQuiet, setVerbose } from \"./core/logger.js\";\nimport { getCaampVersion } from \"./core/version.js\";\n\nconst program = new Command();\n\nprogram\n .name(\"caamp\")\n .description(\"Central AI Agent Managed Packages - unified provider registry and package manager\")\n .version(getCaampVersion())\n .option(\"-v, --verbose\", \"Show debug output\")\n .option(\"-q, --quiet\", \"Suppress non-error output\")\n .option(\"--human\", \"Output in human-readable format (default: JSON for LLM agents)\");\n\nprogram.hook(\"preAction\", (thisCommand) => {\n const opts = thisCommand.optsWithGlobals();\n if (opts.verbose) setVerbose(true);\n if (opts.quiet) setQuiet(true);\n if (opts.human) setHuman(true);\n});\n\n// Register command groups\nregisterProvidersCommand(program);\nregisterSkillsCommands(program);\nregisterMcpCommands(program);\nregisterCleoCommands(program);\nregisterInstructionsCommands(program);\nregisterConfigCommand(program);\nregisterDoctorCommand(program);\nregisterAdvancedCommands(program);\n\nfunction toError(error: unknown): Error {\n if (error instanceof Error) return error;\n return new Error(String(error));\n}\n\nfunction handleFatal(error: unknown, source: \"uncaughtException\" | \"unhandledRejection\" | \"cli\"): void {\n const normalized = toError(error);\n console.error(`Fatal error (${source}): ${normalized.message}`);\n if (isVerbose() && normalized.stack) {\n console.error(normalized.stack);\n }\n}\n\nprocess.on(\"uncaughtException\", (error) => {\n handleFatal(error, \"uncaughtException\");\n process.exit(1);\n});\n\nprocess.on(\"unhandledRejection\", (reason) => {\n handleFatal(reason, \"unhandledRejection\");\n process.exit(1);\n});\n\nasync function main(): Promise<void> {\n await program.parseAsync(process.argv);\n}\n\nmain().catch((error) => {\n handleFatal(error, \"cli\");\n process.exit(1);\n});\n","/**\n * Shared helpers for advanced command input parsing and validation.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport type {\n McpBatchOperation,\n SkillBatchOperation,\n} from \"../../core/advanced/orchestration.js\";\nimport type { Provider, ProviderPriority } from \"../../types.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getAllProviders, getProvider } from \"../../core/registry/providers.js\";\nimport { LAFSCommandError } from \"./lafs.js\";\n\nconst VALID_PRIORITIES = new Set<ProviderPriority>([\"high\", \"medium\", \"low\"]);\n\n/**\n * Options for resolving which providers to target in advanced commands.\n *\n * @remarks\n * Used by resolveProviders to determine the set of providers from CLI flags.\n *\n * @public\n */\nexport interface ProviderTargetOptions {\n /** When true, target all registry providers including undetected ones. */\n all?: boolean;\n /** Specific provider IDs or aliases to target. */\n agent?: string[];\n}\n\n/**\n * Parses and validates a provider priority tier string.\n *\n * @remarks\n * Throws a LAFSCommandError if the value is not one of the valid priorities (high, medium, low).\n *\n * @param value - The priority string to parse\n * @returns The validated ProviderPriority value\n *\n * @example\n * ```typescript\n * const tier = parsePriority(\"high\"); // \"high\"\n * ```\n *\n * @public\n */\nexport function parsePriority(value: string): ProviderPriority {\n if (!VALID_PRIORITIES.has(value as ProviderPriority)) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_PRIORITY\",\n `Invalid tier: ${value}`,\n \"Use one of: high, medium, low.\",\n );\n }\n return value as ProviderPriority;\n}\n\n/**\n * Resolves the set of target providers from CLI targeting options.\n *\n * @remarks\n * When `all` is true, returns all registry providers. When agent IDs are specified, resolves\n * and validates them. Otherwise falls back to auto-detected installed providers.\n *\n * @param options - The provider targeting options from the CLI\n * @returns An array of resolved Provider objects\n *\n * @example\n * ```typescript\n * const providers = resolveProviders({ all: true });\n * ```\n *\n * @public\n */\nexport function resolveProviders(options: ProviderTargetOptions): Provider[] {\n if (options.all) {\n return getAllProviders();\n }\n\n const targetAgents = options.agent ?? [];\n if (targetAgents.length === 0) {\n return getInstalledProviders();\n }\n\n const providers = targetAgents\n .map((id) => getProvider(id))\n .filter((provider): provider is Provider => provider !== undefined);\n\n if (providers.length !== targetAgents.length) {\n const found = new Set(providers.map((provider) => provider.id));\n const missing = targetAgents.filter((id) => !found.has(id));\n throw new LAFSCommandError(\n \"E_ADVANCED_PROVIDER_NOT_FOUND\",\n `Unknown provider(s): ${missing.join(\", \")}`,\n \"Check `caamp providers list` for valid provider IDs/aliases.\",\n );\n }\n\n return providers;\n}\n\n/**\n * Reads and parses a JSON file from disk.\n *\n * @remarks\n * Throws a LAFSCommandError with a recovery suggestion if the file cannot be read or parsed.\n *\n * @param path - Absolute or relative path to the JSON file\n * @returns The parsed JSON value\n *\n * @example\n * ```typescript\n * const data = await readJsonFile(\"./operations.json\");\n * ```\n *\n * @public\n */\nexport async function readJsonFile(path: string): Promise<unknown> {\n try {\n const raw = await readFile(path, \"utf-8\");\n return JSON.parse(raw) as unknown;\n } catch (error) {\n throw new LAFSCommandError(\n \"E_ADVANCED_INPUT_JSON\",\n `Failed to read JSON file: ${path}`,\n \"Confirm the path exists and contains valid JSON.\",\n true,\n { reason: error instanceof Error ? error.message : String(error) },\n );\n }\n}\n\n/**\n * Reads and validates a JSON file containing MCP batch operations.\n *\n * @remarks\n * Parses the file and validates each entry has required fields (serverName, config) with proper types.\n * Throws LAFSCommandError on any validation failure with specific error codes.\n *\n * @param path - Path to the JSON file containing an array of MCP operations\n * @returns An array of validated McpBatchOperation objects\n *\n * @example\n * ```typescript\n * const ops = await readMcpOperations(\"./mcp-ops.json\");\n * ```\n *\n * @public\n */\nexport async function readMcpOperations(path: string): Promise<McpBatchOperation[]> {\n const value = await readJsonFile(path);\n if (!Array.isArray(value)) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_MCP_ARRAY\",\n `MCP operations file must be a JSON array: ${path}`,\n \"Provide an array of objects with serverName and config fields.\",\n );\n }\n\n const operations: McpBatchOperation[] = [];\n for (const [index, item] of value.entries()) {\n if (!item || typeof item !== \"object\") {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_MCP_ITEM\",\n `Invalid MCP operation at index ${index}`,\n \"Each operation must be an object with serverName and config.\",\n );\n }\n\n const obj = item as Record<string, unknown>;\n const serverName = obj.serverName;\n const config = obj.config;\n const scope = obj.scope;\n\n if (typeof serverName !== \"string\" || serverName.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_MCP_NAME\",\n `Invalid serverName at index ${index}`,\n \"Set serverName to a non-empty string.\",\n );\n }\n\n if (!config || typeof config !== \"object\" || Array.isArray(config)) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_MCP_CONFIG\",\n `Invalid config at index ${index}`,\n \"Set config to an object matching McpServerConfig.\",\n );\n }\n\n if (scope !== undefined && scope !== \"project\" && scope !== \"global\") {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SCOPE\",\n `Invalid scope at index ${index}: ${String(scope)}`,\n \"Use scope value 'project' or 'global'.\",\n );\n }\n\n operations.push({\n serverName,\n config: config as McpBatchOperation[\"config\"],\n ...(scope ? { scope: scope as \"project\" | \"global\" } : {}),\n });\n }\n\n return operations;\n}\n\n/**\n * Reads and validates a JSON file containing skill batch operations.\n *\n * @remarks\n * Parses the file and validates each entry has required fields (sourcePath, skillName) with proper types.\n * Throws LAFSCommandError on any validation failure with specific error codes.\n *\n * @param path - Path to the JSON file containing an array of skill operations\n * @returns An array of validated SkillBatchOperation objects\n *\n * @example\n * ```typescript\n * const ops = await readSkillOperations(\"./skill-ops.json\");\n * ```\n *\n * @public\n */\nexport async function readSkillOperations(path: string): Promise<SkillBatchOperation[]> {\n const value = await readJsonFile(path);\n if (!Array.isArray(value)) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SKILL_ARRAY\",\n `Skill operations file must be a JSON array: ${path}`,\n \"Provide an array of objects with sourcePath and skillName fields.\",\n );\n }\n\n const operations: SkillBatchOperation[] = [];\n for (const [index, item] of value.entries()) {\n if (!item || typeof item !== \"object\") {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SKILL_ITEM\",\n `Invalid skill operation at index ${index}`,\n \"Each operation must be an object with sourcePath and skillName.\",\n );\n }\n\n const obj = item as Record<string, unknown>;\n const sourcePath = obj.sourcePath;\n const skillName = obj.skillName;\n const isGlobal = obj.isGlobal;\n\n if (typeof sourcePath !== \"string\" || sourcePath.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SKILL_SOURCE\",\n `Invalid sourcePath at index ${index}`,\n \"Set sourcePath to a non-empty string.\",\n );\n }\n\n if (typeof skillName !== \"string\" || skillName.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SKILL_NAME\",\n `Invalid skillName at index ${index}`,\n \"Set skillName to a non-empty string.\",\n );\n }\n\n if (isGlobal !== undefined && typeof isGlobal !== \"boolean\") {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SKILL_SCOPE\",\n `Invalid isGlobal value at index ${index}`,\n \"Set isGlobal to true or false when provided.\",\n );\n }\n\n operations.push({\n sourcePath,\n skillName,\n ...(isGlobal !== undefined ? { isGlobal } : {}),\n });\n }\n\n return operations;\n}\n\n/**\n * Reads text input from either inline content or a file path, enforcing mutual exclusivity.\n *\n * @remarks\n * Throws LAFSCommandError if both inline content and a file path are provided simultaneously.\n * Returns undefined if neither is provided.\n *\n * @param inlineContent - Inline text content from the --content flag, or undefined\n * @param filePath - Path to a content file from the --content-file flag, or undefined\n * @returns The text content string, or undefined if no input was provided\n *\n * @example\n * ```typescript\n * const content = await readTextInput(undefined, \"./content.txt\");\n * ```\n *\n * @public\n */\nexport async function readTextInput(\n inlineContent: string | undefined,\n filePath: string | undefined,\n): Promise<string | undefined> {\n if (inlineContent && filePath) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_INPUT_MODE\",\n \"Provide either inline content or a content file, not both.\",\n \"Use --content OR --content-file.\",\n );\n }\n\n if (inlineContent) return inlineContent;\n if (!filePath) return undefined;\n\n try {\n return await readFile(filePath, \"utf-8\");\n } catch (error) {\n throw new LAFSCommandError(\n \"E_ADVANCED_INPUT_TEXT\",\n `Failed to read content file: ${filePath}`,\n \"Confirm the file exists and is readable.\",\n true,\n { reason: error instanceof Error ? error.message : String(error) },\n );\n }\n}\n","/**\n * LAFS-compliant output helpers for advanced CLI commands.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n isRegisteredErrorCode,\n type LAFSErrorCategory,\n type LAFSMeta,\n type LAFSError,\n type LAFSPage,\n} from \"@cleocode/lafs\";\nimport type { MVILevel } from \"../../core/lafs.js\";\n\n/**\n * Generic LAFS result envelope for advanced commands.\n * Uses protocol types directly for full compliance.\n */\ntype LAFSResultEnvelope<T> = {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\";\n _meta: LAFSMeta;\n success: boolean;\n result: T | null;\n error: LAFSError | null;\n page: LAFSPage | null;\n};\n\n/**\n * Structured error class for LAFS-compliant command failures with error codes and recovery hints.\n *\n * @remarks\n * Automatically infers the LAFS error category from the error code string pattern.\n * Used by advanced commands to produce machine-readable error envelopes.\n *\n * @public\n */\nexport class LAFSCommandError extends Error {\n /** LAFS error code identifying the failure type. */\n code: string;\n /** LAFS error category inferred from the error code. */\n category: LAFSErrorCategory;\n /** Whether the operation can be retried after fixing the root cause. */\n recoverable: boolean;\n /** Human-readable suggestion for resolving the error. */\n suggestion: string;\n /** Optional delay in milliseconds before retrying, or null. */\n retryAfterMs: number | null;\n /** Optional additional error details payload. */\n details?: unknown;\n\n constructor(\n code: string,\n message: string,\n suggestion: string,\n recoverable = true,\n details?: unknown,\n ) {\n super(message);\n this.name = \"LAFSCommandError\";\n this.code = code;\n this.category = inferErrorCategory(code);\n this.recoverable = recoverable;\n this.suggestion = suggestion;\n this.retryAfterMs = null;\n this.details = details;\n }\n}\n\nfunction inferErrorCategory(code: string): LAFSErrorCategory {\n if (code.includes(\"VALIDATION\")) return \"VALIDATION\";\n if (code.includes(\"NOT_FOUND\")) return \"NOT_FOUND\";\n if (code.includes(\"CONFLICT\")) return \"CONFLICT\";\n if (code.includes(\"AUTH\")) return \"AUTH\";\n if (code.includes(\"PERMISSION\")) return \"PERMISSION\";\n if (code.includes(\"RATE_LIMIT\")) return \"RATE_LIMIT\";\n if (code.includes(\"MIGRATION\")) return \"MIGRATION\";\n if (code.includes(\"CONTRACT\")) return \"CONTRACT\";\n return \"INTERNAL\";\n}\n\nfunction baseMeta(operation: string, mvi: MVILevel): LAFSMeta {\n return {\n specVersion: \"1.0.0\",\n schemaVersion: \"1.0.0\",\n timestamp: new Date().toISOString(),\n operation,\n requestId: randomUUID(),\n transport: \"cli\",\n strict: true,\n mvi,\n contextVersion: 0,\n };\n}\n\n/**\n * Emits a successful LAFS result envelope to stdout.\n *\n * @remarks\n * Wraps the result in a fully compliant LAFS envelope with auto-generated metadata including\n * requestId, timestamp, and transport identifiers.\n *\n * @typeParam T - The type of the result payload\n * @param operation - The LAFS operation identifier\n * @param result - The result payload to include in the envelope\n * @param mvi - The minimum viable information level, defaults to \"standard\"\n *\n * @example\n * ```typescript\n * emitSuccess(\"advanced.providers\", { providers: [...] });\n * ```\n *\n * @public\n */\nexport function emitSuccess<T>(operation: string, result: T, mvi: MVILevel = \"standard\"): void {\n const envelope: LAFSResultEnvelope<T> = {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\",\n _meta: {\n ...baseMeta(operation, mvi),\n },\n success: true,\n result,\n error: null,\n page: null,\n };\n console.log(JSON.stringify(envelope, null, 2));\n}\n\n/**\n * Emits a failed LAFS error envelope to stderr.\n *\n * @remarks\n * Handles both LAFSCommandError instances (with structured codes and categories) and generic\n * errors (wrapped as E_INTERNAL_UNEXPECTED). Registered error codes are preserved; unregistered\n * codes are normalized to the internal fallback.\n *\n * @param operation - The LAFS operation identifier\n * @param error - The error to serialize, either a LAFSCommandError or generic Error/unknown\n * @param mvi - The minimum viable information level, defaults to \"standard\"\n *\n * @example\n * ```typescript\n * emitError(\"advanced.apply\", new LAFSCommandError(\"E_VALIDATION\", \"bad input\", \"fix it\"));\n * ```\n *\n * @public\n */\nexport function emitError(operation: string, error: unknown, mvi: MVILevel = \"standard\"): void {\n let envelope: LAFSResultEnvelope<null>;\n\n if (error instanceof LAFSCommandError) {\n envelope = {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\",\n _meta: {\n ...baseMeta(operation, mvi),\n },\n success: false,\n result: null,\n error: {\n code: isRegisteredErrorCode(error.code) ? error.code : \"E_INTERNAL_UNEXPECTED\",\n message: error.message,\n category: error.category,\n retryable: error.recoverable,\n retryAfterMs: error.retryAfterMs,\n details: {\n hint: error.suggestion,\n ...(error.details !== undefined ? { payload: error.details } : {}),\n },\n },\n page: null,\n };\n } else {\n envelope = {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\",\n _meta: {\n ...baseMeta(operation, mvi),\n },\n success: false,\n result: null,\n error: {\n code: \"E_INTERNAL_UNEXPECTED\",\n message: error instanceof Error ? error.message : String(error),\n category: \"INTERNAL\",\n retryable: false,\n retryAfterMs: null,\n details: {\n hint: \"Rerun with --verbose and validate your inputs.\",\n },\n },\n page: null,\n };\n }\n\n console.error(JSON.stringify(envelope, null, 2));\n}\n\n/**\n * Runs an async action and emits the result as a LAFS success or error envelope.\n *\n * @remarks\n * Wraps the action in a try/catch. On success, calls emitSuccess. On failure, calls emitError\n * and exits with code 1. This is the standard execution wrapper for all advanced commands.\n *\n * @typeParam T - The type of the result returned by the action\n * @param command - The LAFS operation identifier\n * @param mvi - The minimum viable information level\n * @param action - The async function to execute\n * @returns Resolves when the action completes and output is emitted\n *\n * @example\n * ```typescript\n * await runLafsCommand(\"advanced.batch\", \"standard\", async () => {\n * return { installed: 3 };\n * });\n * ```\n *\n * @public\n */\nexport async function runLafsCommand<T>(\n command: string,\n mvi: MVILevel,\n action: () => Promise<T>,\n): Promise<void> {\n try {\n const result = await action();\n emitSuccess(command, result, mvi);\n } catch (error) {\n emitError(command, error, mvi);\n process.exit(1);\n }\n}\n","/**\n * advanced providers command\n */\n\nimport type { Command } from \"commander\";\nimport { selectProvidersByMinimumPriority } from \"../../core/advanced/orchestration.js\";\nimport { parsePriority, resolveProviders } from \"./common.js\";\nimport { runLafsCommand } from \"./lafs.js\";\n\n/**\n * Registers the `advanced providers` subcommand for selecting providers by priority tier.\n *\n * @remarks\n * Resolves and filters providers using the advanced wrapper logic, outputting the selected\n * provider set as a LAFS-compliant JSON envelope. Useful for scripted orchestration pipelines.\n *\n * @param parent - The parent `advanced` Command to attach the providers subcommand to\n *\n * @example\n * ```bash\n * caamp advanced providers --min-tier high\n * caamp advanced providers --all --details\n * ```\n *\n * @public\n */\nexport function registerAdvancedProviders(parent: Command): void {\n parent\n .command(\"providers\")\n .description(\"Select providers by priority using advanced wrapper logic\")\n .option(\"-a, --agent <name>\", \"Target specific provider(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--all\", \"Use all registry providers (not only detected)\")\n .option(\"--min-tier <tier>\", \"Minimum priority tier: high|medium|low\", \"low\")\n .option(\"--details\", \"Include full provider objects\")\n .action(async (opts: {\n agent: string[];\n all?: boolean;\n minTier: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.providers\", opts.details ? \"full\" : \"standard\", async () => {\n const providers = resolveProviders({ all: opts.all, agent: opts.agent });\n const minTier = parsePriority(opts.minTier);\n const selected = selectProvidersByMinimumPriority(providers, minTier);\n\n return {\n objective: \"Filter providers by minimum priority tier\",\n constraints: {\n minTier,\n selectionMode: opts.all ? \"registry\" : \"detected-or-explicit\",\n },\n acceptanceCriteria: {\n selectedCount: selected.length,\n orderedByPriority: true,\n },\n data: opts.details\n ? selected\n : selected.map((provider) => ({\n id: provider.id,\n priority: provider.priority,\n status: provider.status,\n configFormat: provider.configFormat,\n })),\n };\n }));\n}\n","/**\n * advanced batch command\n */\n\nimport type { Command } from \"commander\";\nimport { installBatchWithRollback, selectProvidersByMinimumPriority } from \"../../core/advanced/orchestration.js\";\nimport { parsePriority, readMcpOperations, readSkillOperations, resolveProviders } from \"./common.js\";\nimport { LAFSCommandError, runLafsCommand } from \"./lafs.js\";\n\n/**\n * Registers the `advanced batch` subcommand for rollback-capable batch install of MCP and skills.\n *\n * @remarks\n * Installs MCP servers and skills from JSON files in a single atomic operation with automatic\n * rollback on failure. Supports minimum priority tier filtering and project directory resolution.\n *\n * @param parent - The parent `advanced` Command to attach the batch subcommand to\n *\n * @example\n * ```bash\n * caamp advanced batch --mcp-file mcp.json --skills-file skills.json\n * caamp advanced batch --mcp-file mcp.json --min-tier medium\n * ```\n *\n * @public\n */\nexport function registerAdvancedBatch(parent: Command): void {\n parent\n .command(\"batch\")\n .description(\"Run rollback-capable batch install for MCP + skills\")\n .option(\"-a, --agent <name>\", \"Target specific provider(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--all\", \"Use all registry providers (not only detected)\")\n .option(\"--min-tier <tier>\", \"Minimum priority tier: high|medium|low\", \"low\")\n .option(\"--mcp-file <path>\", \"JSON file containing McpBatchOperation[]\")\n .option(\"--skills-file <path>\", \"JSON file containing SkillBatchOperation[]\")\n .option(\"--project-dir <path>\", \"Project directory to resolve project-scope paths\")\n .option(\"--details\", \"Include detailed operation result\")\n .action(async (opts: {\n agent: string[];\n all?: boolean;\n minTier: string;\n mcpFile?: string;\n skillsFile?: string;\n projectDir?: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.batch\", opts.details ? \"full\" : \"standard\", async () => {\n const baseProviders = resolveProviders({ all: opts.all, agent: opts.agent });\n const minimumPriority = parsePriority(opts.minTier);\n const providers = selectProvidersByMinimumPriority(baseProviders, minimumPriority);\n\n const mcp = opts.mcpFile ? await readMcpOperations(opts.mcpFile) : [];\n const skills = opts.skillsFile ? await readSkillOperations(opts.skillsFile) : [];\n\n if (mcp.length === 0 && skills.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_NO_OPS\",\n \"No operations provided.\",\n \"Provide --mcp-file and/or --skills-file.\",\n );\n }\n\n if (providers.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_NO_TARGET_PROVIDERS\",\n \"No target providers resolved for this batch operation.\",\n \"Use --all or pass provider IDs with --agent.\",\n );\n }\n\n const result = await installBatchWithRollback({\n providers,\n minimumPriority,\n mcp,\n skills,\n projectDir: opts.projectDir,\n });\n\n if (!result.success) {\n throw new LAFSCommandError(\n \"E_ADVANCED_BATCH_FAILED\",\n result.error ?? \"Batch operation failed.\",\n \"Check rollbackErrors and input configs, then retry.\",\n true,\n result,\n );\n }\n\n return {\n objective: \"Install MCP and skills with rollback safety\",\n constraints: {\n minimumPriority,\n providerCount: providers.length,\n mcpOps: mcp.length,\n skillOps: skills.length,\n },\n acceptanceCriteria: {\n success: result.success,\n rollbackPerformed: result.rollbackPerformed,\n },\n data: opts.details\n ? result\n : {\n providerCount: result.providerIds.length,\n mcpApplied: result.mcpApplied,\n skillsApplied: result.skillsApplied,\n rollbackPerformed: result.rollbackPerformed,\n },\n };\n }));\n}\n","/**\n * advanced conflicts command\n */\n\nimport type { Command } from \"commander\";\nimport { detectMcpConfigConflicts, selectProvidersByMinimumPriority } from \"../../core/advanced/orchestration.js\";\nimport { parsePriority, readMcpOperations, resolveProviders } from \"./common.js\";\nimport { LAFSCommandError, runLafsCommand } from \"./lafs.js\";\n\n/**\n * Registers the `advanced conflicts` subcommand for preflight MCP conflict detection.\n *\n * @remarks\n * Scans existing provider configurations for naming conflicts with proposed MCP operations\n * before applying them. Reports conflicts without making any changes.\n *\n * @param parent - The parent `advanced` Command to attach the conflicts subcommand to\n *\n * @example\n * ```bash\n * caamp advanced conflicts --mcp-file ops.json --all\n * caamp advanced conflicts --mcp-file ops.json --min-tier high\n * ```\n *\n * @public\n */\nexport function registerAdvancedConflicts(parent: Command): void {\n parent\n .command(\"conflicts\")\n .description(\"Preflight MCP conflict detection across providers\")\n .requiredOption(\"--mcp-file <path>\", \"JSON file containing McpBatchOperation[]\")\n .option(\"-a, --agent <name>\", \"Target specific provider(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--all\", \"Use all registry providers (not only detected)\")\n .option(\"--min-tier <tier>\", \"Minimum priority tier: high|medium|low\", \"low\")\n .option(\"--project-dir <path>\", \"Project directory to resolve project-scope paths\")\n .option(\"--details\", \"Include full conflict list\")\n .action(async (opts: {\n mcpFile: string;\n agent: string[];\n all?: boolean;\n minTier: string;\n projectDir?: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.conflicts\", opts.details ? \"full\" : \"standard\", async () => {\n const baseProviders = resolveProviders({ all: opts.all, agent: opts.agent });\n const minimumPriority = parsePriority(opts.minTier);\n const providers = selectProvidersByMinimumPriority(baseProviders, minimumPriority);\n const operations = await readMcpOperations(opts.mcpFile);\n\n if (providers.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_NO_TARGET_PROVIDERS\",\n \"No target providers resolved for conflict detection.\",\n \"Use --all or pass provider IDs with --agent.\",\n );\n }\n\n const conflicts = await detectMcpConfigConflicts(\n providers,\n operations,\n opts.projectDir,\n );\n\n const countByCode = conflicts.reduce<Record<string, number>>((acc, conflict) => {\n acc[conflict.code] = (acc[conflict.code] ?? 0) + 1;\n return acc;\n }, {});\n\n return {\n objective: \"Detect MCP configuration conflicts before mutation\",\n constraints: {\n minimumPriority,\n providerCount: providers.length,\n operationCount: operations.length,\n },\n acceptanceCriteria: {\n conflictCount: conflicts.length,\n },\n data: opts.details\n ? conflicts\n : {\n conflictCount: conflicts.length,\n countByCode,\n sample: conflicts.slice(0, 5),\n },\n };\n }));\n}\n","/**\n * advanced apply command\n */\n\nimport type { Command } from \"commander\";\nimport {\n applyMcpInstallWithPolicy,\n selectProvidersByMinimumPriority,\n type ConflictPolicy,\n} from \"../../core/advanced/orchestration.js\";\nimport { parsePriority, readMcpOperations, resolveProviders } from \"./common.js\";\nimport { LAFSCommandError, runLafsCommand } from \"./lafs.js\";\n\nconst VALID_POLICIES = new Set<ConflictPolicy>([\"fail\", \"skip\", \"overwrite\"]);\n\nfunction parsePolicy(value: string): ConflictPolicy {\n if (!VALID_POLICIES.has(value as ConflictPolicy)) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_POLICY\",\n `Invalid policy: ${value}`,\n \"Use one of: fail, skip, overwrite.\",\n );\n }\n return value as ConflictPolicy;\n}\n\n/**\n * Registers the `advanced apply` subcommand for applying MCP operations with configurable conflict policy.\n *\n * @remarks\n * Applies MCP batch operations from a JSON file to targeted providers with fail, skip, or overwrite\n * conflict resolution policies. Supports minimum priority tier filtering.\n *\n * @param parent - The parent `advanced` Command to attach the apply subcommand to\n *\n * @example\n * ```bash\n * caamp advanced apply --mcp-file ops.json --policy overwrite\n * caamp advanced apply --mcp-file ops.json --min-tier high\n * ```\n *\n * @public\n */\nexport function registerAdvancedApply(parent: Command): void {\n parent\n .command(\"apply\")\n .description(\"Apply MCP operations with configurable conflict policy\")\n .requiredOption(\"--mcp-file <path>\", \"JSON file containing McpBatchOperation[]\")\n .option(\"--policy <policy>\", \"Conflict policy: fail|skip|overwrite\", \"fail\")\n .option(\"-a, --agent <name>\", \"Target specific provider(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--all\", \"Use all registry providers (not only detected)\")\n .option(\"--min-tier <tier>\", \"Minimum priority tier: high|medium|low\", \"low\")\n .option(\"--project-dir <path>\", \"Project directory to resolve project-scope paths\")\n .option(\"--details\", \"Include detailed apply result\")\n .action(async (opts: {\n mcpFile: string;\n policy: string;\n agent: string[];\n all?: boolean;\n minTier: string;\n projectDir?: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.apply\", opts.details ? \"full\" : \"standard\", async () => {\n const baseProviders = resolveProviders({ all: opts.all, agent: opts.agent });\n const minimumPriority = parsePriority(opts.minTier);\n const providers = selectProvidersByMinimumPriority(baseProviders, minimumPriority);\n const operations = await readMcpOperations(opts.mcpFile);\n const policy = parsePolicy(opts.policy);\n\n if (providers.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_NO_TARGET_PROVIDERS\",\n \"No target providers resolved for apply operation.\",\n \"Use --all or pass provider IDs with --agent.\",\n );\n }\n\n const result = await applyMcpInstallWithPolicy(\n providers,\n operations,\n policy,\n opts.projectDir,\n );\n\n if (policy === \"fail\" && result.conflicts.length > 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_CONFLICTS_BLOCKING\",\n \"Conflicts detected and policy is set to fail.\",\n \"Run `caamp advanced conflicts` to inspect, or rerun with --policy skip/overwrite.\",\n true,\n result,\n );\n }\n\n const failedWrites = result.applied.filter((entry) => !entry.success);\n if (failedWrites.length > 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_APPLY_WRITE_FAILED\",\n \"One or more MCP writes failed.\",\n \"Check result details, fix provider config issues, and retry.\",\n true,\n result,\n );\n }\n\n return {\n objective: \"Apply MCP operations with policy-driven conflict handling\",\n constraints: {\n policy,\n minimumPriority,\n providerCount: providers.length,\n operationCount: operations.length,\n },\n acceptanceCriteria: {\n conflicts: result.conflicts.length,\n writesSucceeded: result.applied.length,\n },\n data: opts.details\n ? result\n : {\n conflicts: result.conflicts.length,\n applied: result.applied.length,\n skipped: result.skipped.length,\n },\n };\n }));\n}\n","/**\n * advanced instructions command\n */\n\nimport type { Command } from \"commander\";\nimport {\n selectProvidersByMinimumPriority,\n updateInstructionsSingleOperation,\n} from \"../../core/advanced/orchestration.js\";\nimport { parsePriority, readTextInput, resolveProviders } from \"./common.js\";\nimport { LAFSCommandError, runLafsCommand } from \"./lafs.js\";\n\n/**\n * Registers the `advanced instructions` subcommand for single-operation instruction updates.\n *\n * @remarks\n * Updates instruction file injections across multiple providers in a single LAFS-compliant\n * operation. Supports inline content, content files, and minimum priority tier filtering.\n *\n * @param parent - The parent `advanced` Command to attach the instructions subcommand to\n *\n * @example\n * ```bash\n * caamp advanced instructions --content \"Custom block\" --all\n * caamp advanced instructions --content-file block.md --min-tier high\n * ```\n *\n * @public\n */\nexport function registerAdvancedInstructions(parent: Command): void {\n parent\n .command(\"instructions\")\n .description(\"Single-operation instruction update across providers\")\n .option(\"-a, --agent <name>\", \"Target specific provider(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--all\", \"Use all registry providers (not only detected)\")\n .option(\"--min-tier <tier>\", \"Minimum priority tier: high|medium|low\", \"low\")\n .option(\"--scope <scope>\", \"Instruction scope: project|global\", \"project\")\n .option(\"--content <text>\", \"Inline content to inject\")\n .option(\"--content-file <path>\", \"File containing content to inject\")\n .option(\"--project-dir <path>\", \"Project directory to resolve project-scope paths\")\n .option(\"--details\", \"Include detailed per-file actions\")\n .action(async (opts: {\n agent: string[];\n all?: boolean;\n minTier: string;\n scope: string;\n content?: string;\n contentFile?: string;\n projectDir?: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.instructions\", opts.details ? \"full\" : \"standard\", async () => {\n const minimumPriority = parsePriority(opts.minTier);\n const baseProviders = resolveProviders({ all: opts.all, agent: opts.agent });\n const providers = selectProvidersByMinimumPriority(baseProviders, minimumPriority);\n\n const scope = opts.scope === \"global\" ? \"global\" : opts.scope === \"project\" ? \"project\" : null;\n if (!scope) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_SCOPE\",\n `Invalid scope: ${opts.scope}`,\n \"Use --scope project or --scope global.\",\n );\n }\n\n const content = await readTextInput(opts.content, opts.contentFile);\n if (!content || content.trim().length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_CONTENT\",\n \"Instruction content is required.\",\n \"Provide --content or --content-file with non-empty text.\",\n );\n }\n\n if (providers.length === 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_NO_TARGET_PROVIDERS\",\n \"No target providers resolved for instruction update.\",\n \"Use --all or pass provider IDs with --agent.\",\n );\n }\n\n const summary = await updateInstructionsSingleOperation(\n providers,\n content,\n scope,\n opts.projectDir,\n );\n\n return {\n objective: \"Update instruction files across providers in one operation\",\n constraints: {\n scope,\n minimumPriority,\n providerCount: providers.length,\n },\n acceptanceCriteria: {\n updatedFiles: summary.updatedFiles,\n },\n data: opts.details\n ? summary\n : {\n updatedFiles: summary.updatedFiles,\n files: summary.actions.map((entry) => ({\n file: entry.file,\n action: entry.action,\n })),\n },\n };\n }));\n}\n","/**\n * advanced configure command\n */\n\nimport type { Command } from \"commander\";\nimport { configureProviderGlobalAndProject } from \"../../core/advanced/orchestration.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport { readMcpOperations, readTextInput } from \"./common.js\";\nimport { LAFSCommandError, runLafsCommand } from \"./lafs.js\";\n\n/**\n * Registers the `advanced configure` subcommand for configuring global and project scope in one operation.\n *\n * @remarks\n * Combines MCP operations and instruction content for both global and project scopes into a single\n * command targeting one provider. Reduces multiple CLI invocations to a single atomic operation.\n *\n * @param parent - The parent `advanced` Command to attach the configure subcommand to\n *\n * @example\n * ```bash\n * caamp advanced configure --agent claude-code --global-mcp-file global.json\n * ```\n *\n * @public\n */\nexport function registerAdvancedConfigure(parent: Command): void {\n parent\n .command(\"configure\")\n .description(\"Configure global + project scope for one provider in one operation\")\n .requiredOption(\"-a, --agent <name>\", \"Target provider ID or alias\")\n .option(\"--global-mcp-file <path>\", \"JSON file for global MCP operations\")\n .option(\"--project-mcp-file <path>\", \"JSON file for project MCP operations\")\n .option(\"--instruction <text>\", \"Instruction content for both scopes\")\n .option(\"--instruction-file <path>\", \"Instruction content file for both scopes\")\n .option(\"--instruction-global <text>\", \"Instruction content for global scope\")\n .option(\"--instruction-global-file <path>\", \"Instruction content file for global scope\")\n .option(\"--instruction-project <text>\", \"Instruction content for project scope\")\n .option(\"--instruction-project-file <path>\", \"Instruction content file for project scope\")\n .option(\"--project-dir <path>\", \"Project directory to resolve project-scope paths\")\n .option(\"--details\", \"Include detailed write results\")\n .action(async (opts: {\n agent: string;\n globalMcpFile?: string;\n projectMcpFile?: string;\n instruction?: string;\n instructionFile?: string;\n instructionGlobal?: string;\n instructionGlobalFile?: string;\n instructionProject?: string;\n instructionProjectFile?: string;\n projectDir?: string;\n details?: boolean;\n }) => runLafsCommand(\"advanced.configure\", opts.details ? \"full\" : \"standard\", async () => {\n const provider = getProvider(opts.agent);\n if (!provider) {\n throw new LAFSCommandError(\n \"E_ADVANCED_PROVIDER_NOT_FOUND\",\n `Unknown provider: ${opts.agent}`,\n \"Check `caamp providers list` for valid provider IDs/aliases.\",\n );\n }\n\n const globalMcp = opts.globalMcpFile\n ? await readMcpOperations(opts.globalMcpFile)\n : [];\n const projectMcp = opts.projectMcpFile\n ? await readMcpOperations(opts.projectMcpFile)\n : [];\n\n const sharedInstruction = await readTextInput(opts.instruction, opts.instructionFile);\n const globalInstruction = await readTextInput(\n opts.instructionGlobal,\n opts.instructionGlobalFile,\n );\n const projectInstruction = await readTextInput(\n opts.instructionProject,\n opts.instructionProjectFile,\n );\n\n let instructionContent:\n | string\n | { global?: string; project?: string }\n | undefined;\n\n if (globalInstruction || projectInstruction) {\n instructionContent = {\n ...(globalInstruction ? { global: globalInstruction } : {}),\n ...(projectInstruction ? { project: projectInstruction } : {}),\n };\n } else if (sharedInstruction) {\n instructionContent = sharedInstruction;\n }\n\n if (globalMcp.length === 0 && projectMcp.length === 0 && !instructionContent) {\n throw new LAFSCommandError(\n \"E_ADVANCED_VALIDATION_NO_OPS\",\n \"No configuration operations were provided.\",\n \"Provide MCP files and/or instruction content.\",\n );\n }\n\n const result = await configureProviderGlobalAndProject(provider, {\n globalMcp: globalMcp.map((entry) => ({\n serverName: entry.serverName,\n config: entry.config,\n })),\n projectMcp: projectMcp.map((entry) => ({\n serverName: entry.serverName,\n config: entry.config,\n })),\n instructionContent,\n projectDir: opts.projectDir,\n });\n\n const globalFailures = result.mcp.global.filter((entry) => !entry.success);\n const projectFailures = result.mcp.project.filter((entry) => !entry.success);\n\n if (globalFailures.length > 0 || projectFailures.length > 0) {\n throw new LAFSCommandError(\n \"E_ADVANCED_CONFIGURE_FAILED\",\n \"One or more MCP writes failed during configure operation.\",\n \"Inspect the failed write entries and provider config paths, then retry.\",\n true,\n result,\n );\n }\n\n return {\n objective: \"Configure global and project settings in one operation\",\n constraints: {\n provider: provider.id,\n globalMcpOps: globalMcp.length,\n projectMcpOps: projectMcp.length,\n instructionMode: instructionContent\n ? typeof instructionContent === \"string\"\n ? \"shared\"\n : \"scoped\"\n : \"none\",\n },\n acceptanceCriteria: {\n globalWrites: result.mcp.global.length,\n projectWrites: result.mcp.project.length,\n },\n data: opts.details\n ? result\n : {\n providerId: result.providerId,\n configPaths: result.configPaths,\n globalWrites: result.mcp.global.length,\n projectWrites: result.mcp.project.length,\n instructionUpdates: {\n global: result.instructions.global?.size ?? 0,\n project: result.instructions.project?.size ?? 0,\n },\n },\n };\n }));\n}\n","/**\n * Advanced orchestration command group providing LAFS-compliant wrappers for batch operations,\n * conflict detection, policy-based apply, provider selection, and cross-scope configuration.\n *\n * @packageDocumentation\n */\n\nimport type { Command } from \"commander\";\nimport { registerAdvancedProviders } from \"./providers.js\";\nimport { registerAdvancedBatch } from \"./batch.js\";\nimport { registerAdvancedConflicts } from \"./conflicts.js\";\nimport { registerAdvancedApply } from \"./apply.js\";\nimport { registerAdvancedInstructions } from \"./instructions.js\";\nimport { registerAdvancedConfigure } from \"./configure.js\";\n\n/**\n * Registers the `advanced` command group with providers, batch, conflicts, apply, instructions, and configure subcommands.\n *\n * @remarks\n * Provides LAFS-compliant wrappers for advanced orchestration operations that operate across\n * multiple providers and scopes in a single invocation.\n *\n * @param program - The root Commander program to attach the advanced command group to\n *\n * @example\n * ```bash\n * caamp advanced batch --mcp-file ops.json --skills-file skills.json\n * caamp advanced apply --mcp-file ops.json --policy overwrite\n * ```\n *\n * @public\n */\nexport function registerAdvancedCommands(program: Command): void {\n const advanced = program\n .command(\"advanced\")\n .description(\"LAFS-compliant wrappers for advanced orchestration APIs\");\n\n registerAdvancedProviders(advanced);\n registerAdvancedBatch(advanced);\n registerAdvancedConflicts(advanced);\n registerAdvancedApply(advanced);\n registerAdvancedInstructions(advanced);\n registerAdvancedConfigure(advanced);\n}\n","/**\n * config show|path commands - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { readConfig } from \"../core/formats/index.js\";\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../core/lafs.js\";\nimport { resolveProviderConfigPath } from \"../core/paths/standard.js\";\nimport { getProvider } from \"../core/registry/providers.js\";\n\n/**\n * Registers the `config` command group with show and path subcommands for viewing provider configurations.\n *\n * @remarks\n * The show subcommand outputs LAFS-compliant JSON envelopes by default. The path subcommand\n * intentionally outputs raw paths for shell scripting and does not use LAFS envelopes.\n *\n * @param program - The root Commander program to attach the config command group to\n *\n * @example\n * ```bash\n * caamp config show claude-code --global\n * caamp config path cursor project\n * ```\n *\n * @public\n */\nexport function registerConfigCommand(program: Command): void {\n const config = program\n .command(\"config\")\n .description(\"View provider configuration\");\n\n config\n .command(\"show\")\n .description(\"Show provider configuration\")\n .argument(\"<provider>\", \"Provider ID or alias\")\n .option(\"-g, --global\", \"Show global config\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (providerId: string, opts: { global?: boolean; json?: boolean; human?: boolean }) => {\n const operation = \"config.show\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const provider = getProvider(providerId);\n\n if (!provider) {\n const message = `Provider not found: ${providerId}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n providerId,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const scope = opts.global ? \"global\" : \"project\";\n const configPath = resolveProviderConfigPath(provider, scope) ?? provider.configPathGlobal;\n\n if (!existsSync(configPath)) {\n const message = `No config file at: ${configPath}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.FILE_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n configPath,\n scope,\n });\n } else {\n console.log(pc.dim(message));\n }\n process.exit(1);\n }\n\n try {\n const data = await readConfig(configPath, provider.configFormat);\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n provider: provider.id,\n config: data,\n format: provider.configFormat,\n scope,\n });\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\n${provider.toolName} config (${configPath}):\\n`));\n console.log(JSON.stringify(data, null, 2));\n } catch (err) {\n const message = `Error reading config: ${err instanceof Error ? err.message : String(err)}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.FILE_SYSTEM_ERROR, message, ErrorCategories.INTERNAL);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n });\n\n config\n .command(\"path\")\n .description(\"Show config file path (outputs raw path for piping)\")\n .argument(\"<provider>\", \"Provider ID or alias\")\n .argument(\"[scope]\", \"Scope: project (default) or global\", \"project\")\n .action((providerId: string, scope: string) => {\n // NOTE: This command intentionally outputs raw paths for shell scripting\n // It does NOT use LAFS envelopes to remain pipe-friendly\n const provider = getProvider(providerId);\n\n if (!provider) {\n console.error(pc.red(`Provider not found: ${providerId}`));\n process.exit(1);\n }\n\n if (scope === \"global\") {\n console.log(provider.configPathGlobal);\n } else {\n const projectPath = resolveProviderConfigPath(provider, \"project\");\n if (projectPath) {\n console.log(projectPath);\n } else {\n console.log(pc.dim(`${provider.toolName} has no project-level config`));\n console.log(provider.configPathGlobal);\n }\n }\n });\n}\n","/**\n * Shared LAFS utilities for CAAMP commands\n * \n * Provides standardized LAFS envelope creation, error handling, and format resolution\n * to ensure all commands follow the LAFS (Language-Agnostic Format Specification) protocol.\n * \n * @module lafs\n * @requires @cleocode/lafs\n * @requires ../logger.js\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type {\n LAFSErrorCategory,\n LAFSError,\n LAFSMeta,\n LAFSPage,\n Warning,\n} from \"@cleocode/lafs\";\nimport { resolveOutputFormat } from \"@cleocode/lafs\";\nimport { isHuman, isQuiet } from \"./logger.js\";\n\n/**\n * LAFS MVI disclosure level - defined locally to avoid CI module resolution issues with re-exported types.\n *\n * @public\n */\nexport type MVILevel = \"minimal\" | \"standard\" | \"full\" | \"custom\";\n\n// Re-export protocol types under CAAMP's naming conventions\nexport type { LAFSMeta };\n\n/**\n * LAFS Error structure - re-exported from protocol as LAFSErrorShape for CAAMP compatibility.\n *\n * @public\n */\nexport type LAFSErrorShape = LAFSError;\n\n/**\n * LAFS Warning structure - re-exported from protocol.\n *\n * @public\n */\nexport type LAFSWarning = Warning;\n\n/**\n * Generic LAFS Envelope structure for type-safe command results.\n *\n * @remarks\n * Extends the protocol's envelope with TypeScript generics for compile-time\n * safety when constructing or consuming command results.\n *\n * @public\n */\nexport interface LAFSEnvelope<T> {\n /** JSON Schema URI for envelope validation. */\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\";\n /** Envelope metadata (timestamps, request IDs, MVI level). */\n _meta: LAFSMeta;\n /** Whether the operation succeeded. */\n success: boolean;\n /** Operation result payload, or `null` on error. */\n result: T | null;\n /** Error details, or `null` on success. */\n error: LAFSErrorShape | null;\n /** Pagination metadata, or `null` when not applicable. */\n page: LAFSPage | null;\n}\n\n/**\n * Format resolution options.\n *\n * @public\n */\nexport interface FormatOptions {\n /** Whether `--json` was explicitly passed. @defaultValue `false` */\n jsonFlag?: boolean;\n /** Whether `--human` was explicitly passed. @defaultValue `false` */\n humanFlag?: boolean;\n /** Project-level default format when no flag is given. @defaultValue `\"json\"` */\n projectDefault?: \"json\" | \"human\";\n}\n\n/**\n * Resolves output format based on flags and defaults.\n *\n * @remarks\n * Delegates to the LAFS protocol's `resolveOutputFormat` function, layering\n * in the global `isHuman()` state so that `--human` set at the CLI root\n * propagates to all subcommands.\n *\n * @param options - Format resolution options\n * @returns `\"json\"` or `\"human\"`\n * @throws Error if format flags conflict\n *\n * @example\n * ```typescript\n * const format = resolveFormat({ jsonFlag: true });\n * ```\n *\n * @public\n */\nexport function resolveFormat(options: FormatOptions): \"json\" | \"human\" {\n return resolveOutputFormat({\n jsonFlag: options.jsonFlag ?? false,\n humanFlag: (options.humanFlag ?? false) || isHuman(),\n projectDefault: options.projectDefault ?? \"json\",\n }).format;\n}\n\n/**\n * Builds a standard LAFS envelope.\n *\n * @remarks\n * Populates `_meta` with a fresh UUID, ISO timestamp, and the provided\n * operation/MVI values. The `success` flag is derived from whether `error`\n * is `null`.\n *\n * @param operation - Operation identifier (e.g., `\"skills.list\"`, `\"doctor.check\"`)\n * @param mvi - Machine-Verified Instruction disclosure level\n * @param result - Operation result data (`null` if error)\n * @param error - Error details (`null` if success)\n * @param page - Pagination info (`null` if not applicable)\n * @param sessionId - Optional session identifier\n * @param warnings - Optional array of warnings to attach\n * @typeParam T - The type of the result data payload\n * @returns LAFS-compliant envelope\n *\n * @example\n * ```typescript\n * const envelope = buildEnvelope(\n * \"skills.list\",\n * \"full\",\n * { skills: [], count: 0 },\n * null,\n * );\n * ```\n *\n * @public\n */\nexport function buildEnvelope<T>(\n operation: string,\n mvi: MVILevel,\n result: T | null,\n error: LAFSErrorShape | null,\n page: LAFSPage | null = null,\n sessionId?: string,\n warnings?: LAFSWarning[],\n): LAFSEnvelope<T> {\n return {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\",\n _meta: {\n specVersion: \"1.0.0\",\n schemaVersion: \"1.0.0\",\n timestamp: new Date().toISOString(),\n operation,\n requestId: randomUUID(),\n transport: \"cli\",\n strict: true,\n mvi,\n contextVersion: 0,\n ...(sessionId && { sessionId }),\n ...(warnings && warnings.length > 0 && { warnings }),\n },\n success: error === null,\n result,\n error,\n page,\n };\n}\n\n/**\n * Emits a JSON error envelope to stderr and exits the process.\n *\n * @remarks\n * Wraps the error in a full LAFS envelope and writes it to stderr as\n * pretty-printed JSON before calling `process.exit`. The `retryable` flag\n * is automatically set for `TRANSIENT` and `RATE_LIMIT` categories.\n *\n * @param operation - Operation identifier\n * @param mvi - Machine-Verified Instruction disclosure level\n * @param code - Error code\n * @param message - Error message\n * @param category - Error category from LAFS protocol\n * @param details - Additional error details\n * @param exitCode - Process exit code (default: 1)\n *\n * @example\n * ```typescript\n * emitError(\n * \"skills.install\",\n * \"full\",\n * \"E_SKILL_NOT_FOUND\",\n * \"Skill not found\",\n * \"NOT_FOUND\",\n * { skillName: \"my-skill\" },\n * 1,\n * );\n * ```\n *\n * @public\n */\nexport function emitError(\n operation: string,\n mvi: MVILevel,\n code: string,\n message: string,\n category: LAFSErrorCategory,\n details: Record<string, unknown> = {},\n exitCode: number = 1,\n): never {\n const envelope = buildEnvelope(operation, mvi, null, {\n code,\n message,\n category,\n retryable: category === \"TRANSIENT\" || category === \"RATE_LIMIT\",\n retryAfterMs: null,\n details,\n });\n console.error(JSON.stringify(envelope, null, 2));\n process.exit(exitCode);\n}\n\n/**\n * Emits a JSON error envelope without exiting (for catch blocks).\n *\n * @remarks\n * Identical to {@link emitError} except it does not call `process.exit`,\n * allowing callers to perform cleanup or additional logging before exiting.\n *\n * @param operation - Operation identifier\n * @param mvi - Machine-Verified Instruction disclosure level\n * @param code - Error code\n * @param message - Error message\n * @param category - Error category from LAFS protocol\n * @param details - Additional error details\n *\n * @example\n * ```typescript\n * try {\n * await riskyOperation();\n * } catch (err) {\n * emitJsonError(\"operation\", \"full\", \"E_FAILED\", \"Operation failed\", \"INTERNAL\", {});\n * process.exit(1);\n * }\n * ```\n *\n * @public\n */\nexport function emitJsonError(\n operation: string,\n mvi: MVILevel,\n code: string,\n message: string,\n category: LAFSErrorCategory,\n details: Record<string, unknown> = {},\n): void {\n const envelope = buildEnvelope(operation, mvi, null, {\n code,\n message,\n category,\n retryable: category === \"TRANSIENT\" || category === \"RATE_LIMIT\",\n retryAfterMs: null,\n details,\n });\n console.error(JSON.stringify(envelope, null, 2));\n}\n\n/**\n * Outputs a successful LAFS envelope to stdout.\n *\n * @remarks\n * In quiet mode the output is suppressed unless there is an error. The\n * envelope is serialized as pretty-printed JSON.\n *\n * @param operation - Operation identifier\n * @param mvi - Machine-Verified Instruction disclosure level\n * @param result - Operation result data\n * @param page - Optional pagination info\n * @param sessionId - Optional session identifier\n * @param warnings - Optional warnings to attach\n * @typeParam T - The type of the result data payload\n *\n * @example\n * ```typescript\n * outputSuccess(\"skills.list\", \"full\", { skills: [], count: 0 });\n * ```\n *\n * @public\n */\nexport function outputSuccess<T>(\n operation: string,\n mvi: MVILevel,\n result: T,\n page?: LAFSPage,\n sessionId?: string,\n warnings?: LAFSWarning[],\n): void {\n const envelope = buildEnvelope(operation, mvi, result, null, page ?? null, sessionId, warnings);\n \n // In quiet mode, only output if there's an error or if explicitly requested\n if (isQuiet() && !envelope.error) {\n // Suppress non-essential output in quiet mode\n return;\n }\n \n console.log(JSON.stringify(envelope, null, 2));\n}\n\n/**\n * Standard command options interface for LAFS-compliant commands.\n *\n * @public\n */\nexport interface LAFSCommandOptions {\n /** Whether to force JSON output. @defaultValue `false` */\n json?: boolean;\n /** Whether to force human-readable output. @defaultValue `false` */\n human?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Handles format resolution errors consistently.\n *\n * @remarks\n * When `jsonFlag` is true the error is emitted as a LAFS JSON envelope to\n * stderr; otherwise a plain text message is written. The process always\n * exits with code 1.\n *\n * @param error - The error that occurred during format resolution\n * @param operation - Operation identifier\n * @param mvi - Machine-Verified Instruction disclosure level\n * @param jsonFlag - Whether `--json` flag was explicitly set\n * @returns never (exits process)\n *\n * @example\n * ```typescript\n * try {\n * format = resolveFormat({ jsonFlag: opts.json, humanFlag: opts.human });\n * } catch (error) {\n * handleFormatError(error, \"skills.list\", \"full\", opts.json);\n * }\n * ```\n *\n * @public\n */\nexport function handleFormatError(\n error: unknown,\n operation: string,\n mvi: MVILevel,\n jsonFlag: boolean | undefined,\n): never {\n const message = error instanceof Error ? error.message : String(error);\n \n if (jsonFlag) {\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n } else {\n // eslint-disable-next-line no-console\n console.error(message);\n }\n process.exit(1);\n}\n\n/**\n * Common error categories mapping for convenience.\n *\n * @public\n */\nexport const ErrorCategories = {\n VALIDATION: \"VALIDATION\" as LAFSErrorCategory,\n AUTH: \"AUTH\" as LAFSErrorCategory,\n PERMISSION: \"PERMISSION\" as LAFSErrorCategory,\n NOT_FOUND: \"NOT_FOUND\" as LAFSErrorCategory,\n CONFLICT: \"CONFLICT\" as LAFSErrorCategory,\n RATE_LIMIT: \"RATE_LIMIT\" as LAFSErrorCategory,\n TRANSIENT: \"TRANSIENT\" as LAFSErrorCategory,\n INTERNAL: \"INTERNAL\" as LAFSErrorCategory,\n CONTRACT: \"CONTRACT\" as LAFSErrorCategory,\n MIGRATION: \"MIGRATION\" as LAFSErrorCategory,\n} as const;\n\n/**\n * Common error codes for consistency.\n *\n * @public\n */\nexport const ErrorCodes = {\n // Format errors\n FORMAT_CONFLICT: \"E_FORMAT_CONFLICT\",\n INVALID_JSON: \"E_INVALID_JSON\",\n \n // Not found errors\n SKILL_NOT_FOUND: \"E_SKILL_NOT_FOUND\",\n PROVIDER_NOT_FOUND: \"E_PROVIDER_NOT_FOUND\",\n MCP_SERVER_NOT_FOUND: \"E_MCP_SERVER_NOT_FOUND\",\n FILE_NOT_FOUND: \"E_FILE_NOT_FOUND\",\n \n // Validation errors\n INVALID_INPUT: \"E_INVALID_INPUT\",\n INVALID_CONSTRAINT: \"E_INVALID_CONSTRAINT\",\n INVALID_FORMAT: \"E_INVALID_FORMAT\",\n \n // Operation errors\n INSTALL_FAILED: \"E_INSTALL_FAILED\",\n REMOVE_FAILED: \"E_REMOVE_FAILED\",\n UPDATE_FAILED: \"E_UPDATE_FAILED\",\n VALIDATION_FAILED: \"E_VALIDATION_FAILED\",\n AUDIT_FAILED: \"E_AUDIT_FAILED\",\n \n // System errors\n NETWORK_ERROR: \"E_NETWORK_ERROR\",\n FILE_SYSTEM_ERROR: \"E_FILE_SYSTEM_ERROR\",\n PERMISSION_DENIED: \"E_PERMISSION_DENIED\",\n INTERNAL_ERROR: \"E_INTERNAL_ERROR\",\n} as const;\n","/**\n * doctor command - diagnose configuration issues and health\n * LAFS-compliant with JSON-first output\n */\n\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync, lstatSync, readdirSync, readlinkSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { readConfig } from \"../core/formats/index.js\";\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n handleFormatError,\n type LAFSErrorShape,\n outputSuccess,\n resolveFormat,\n} from \"../core/lafs.js\";\nimport { resolveChannelFromServerName } from \"../core/mcp/cleo.js\";\nimport { readLockFile } from \"../core/mcp/lock.js\";\nimport { listMcpServers } from \"../core/mcp/reader.js\";\nimport { CANONICAL_SKILLS_DIR } from \"../core/paths/agents.js\";\nimport { detectAllProviders } from \"../core/registry/detection.js\";\nimport { getAllProviders, getProviderCount } from \"../core/registry/providers.js\";\nimport { getCaampVersion } from \"../core/version.js\";\nimport type { Provider } from \"../types.js\";\n\ninterface CheckResult {\n label: string;\n status: \"pass\" | \"warn\" | \"fail\";\n detail?: string;\n}\n\ninterface SectionResult {\n name: string;\n checks: CheckResult[];\n}\n\ninterface DoctorResult {\n environment: {\n node: string;\n npm: string;\n caamp: string;\n platform: string;\n };\n registry: {\n loaded: boolean;\n count: number;\n valid: boolean;\n };\n providers: {\n installed: number;\n list: string[];\n };\n skills: {\n canonical: number;\n brokenLinks: number;\n staleLinks: number;\n };\n mcpServers: {\n tracked: number;\n untracked: number;\n orphaned: number;\n };\n checks: Array<{\n label: string;\n status: \"pass\" | \"fail\" | \"warn\";\n message?: string;\n }>;\n}\n\nfunction getNodeVersion(): string {\n return process.version;\n}\n\nfunction getNpmVersion(): string | null {\n try {\n return execFileSync(\"npm\", [\"--version\"], { stdio: \"pipe\", encoding: \"utf-8\" }).trim();\n } catch {\n return null;\n }\n}\n\nfunction checkEnvironment(): SectionResult {\n const checks: CheckResult[] = [];\n\n checks.push({ label: `Node.js ${getNodeVersion()}`, status: \"pass\" });\n\n const npmVersion = getNpmVersion();\n if (npmVersion) {\n checks.push({ label: `npm ${npmVersion}`, status: \"pass\" });\n } else {\n checks.push({ label: \"npm not found\", status: \"warn\" });\n }\n\n checks.push({ label: `CAAMP v${getCaampVersion()}`, status: \"pass\" });\n checks.push({ label: `${process.platform} ${process.arch}`, status: \"pass\" });\n\n return { name: \"Environment\", checks };\n}\n\nfunction checkRegistry(): SectionResult {\n const checks: CheckResult[] = [];\n\n try {\n const providers = getAllProviders();\n const count = getProviderCount();\n checks.push({ label: `${count} providers loaded`, status: \"pass\" });\n\n const malformed: string[] = [];\n for (const p of providers) {\n if (!p.id || !p.toolName || !p.configKey || !p.configFormat) {\n malformed.push(p.id || \"(unknown)\");\n }\n }\n\n if (malformed.length === 0) {\n checks.push({ label: \"All entries valid\", status: \"pass\" });\n } else {\n checks.push({\n label: `${malformed.length} malformed entries`,\n status: \"fail\",\n detail: malformed.join(\", \"),\n });\n }\n } catch (err) {\n checks.push({\n label: \"Failed to load registry\",\n status: \"fail\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n\n return { name: \"Registry\", checks };\n}\n\nfunction checkInstalledProviders(): SectionResult {\n const checks: CheckResult[] = [];\n\n try {\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n\n checks.push({ label: `${installed.length} found`, status: \"pass\" });\n\n for (const r of installed) {\n const methods = r.methods.join(\", \");\n checks.push({ label: `${r.provider.toolName} (${methods})`, status: \"pass\" });\n }\n } catch (err) {\n checks.push({\n label: \"Detection failed\",\n status: \"fail\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n\n return { name: \"Installed Providers\", checks };\n}\n\nfunction checkSkillSymlinks(): SectionResult {\n const checks: CheckResult[] = [];\n\n const canonicalDir = CANONICAL_SKILLS_DIR;\n\n if (!existsSync(canonicalDir)) {\n checks.push({ label: \"0 canonical skills\", status: \"pass\" });\n checks.push({ label: \"No broken symlinks\", status: \"pass\" });\n return { name: \"Skills\", checks };\n }\n\n let canonicalCount = 0;\n let canonicalNames: string[] = [];\n try {\n canonicalNames = readdirSync(canonicalDir).filter((name) => {\n const full = join(canonicalDir, name);\n try {\n const stat = lstatSync(full);\n return stat.isDirectory() || stat.isSymbolicLink();\n } catch {\n return false;\n }\n });\n canonicalCount = canonicalNames.length;\n checks.push({ label: `${canonicalCount} canonical skills`, status: \"pass\" });\n } catch {\n checks.push({ label: \"Cannot read skills directory\", status: \"warn\" });\n return { name: \"Skills\", checks };\n }\n\n // Check symlinks in installed provider skill directories\n const broken: string[] = [];\n const stale: string[] = [];\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n\n for (const r of installed) {\n const provider = r.provider;\n const skillDir = provider.pathSkills;\n if (!existsSync(skillDir)) continue;\n\n try {\n const entries = readdirSync(skillDir);\n for (const entry of entries) {\n const fullPath = join(skillDir, entry);\n try {\n const stat = lstatSync(fullPath);\n if (!stat.isSymbolicLink()) continue;\n\n if (!existsSync(fullPath)) {\n broken.push(`${provider.id}/${entry}`);\n } else {\n // Check if symlink points to canonical location\n const target = readlinkSync(fullPath);\n const isCanonical =\n target.includes(\"/.agents/skills/\") ||\n target.includes(\"\\\\.agents\\\\skills\\\\\");\n if (!isCanonical) {\n stale.push(`${provider.id}/${entry}`);\n }\n }\n } catch {\n // skip unreadable entries\n }\n }\n } catch {\n // skip unreadable dirs\n }\n }\n\n if (broken.length === 0) {\n checks.push({ label: \"No broken symlinks\", status: \"pass\" });\n } else {\n checks.push({\n label: `${broken.length} broken symlink${broken.length !== 1 ? \"s\" : \"\"}`,\n status: \"warn\",\n detail: broken.join(\", \"),\n });\n }\n\n if (stale.length === 0) {\n checks.push({ label: \"No stale symlinks\", status: \"pass\" });\n } else {\n checks.push({\n label: `${stale.length} stale symlink${stale.length !== 1 ? \"s\" : \"\"} (not pointing to ~/.agents/skills/)`,\n status: \"warn\",\n detail: stale.join(\", \"),\n });\n }\n\n return { name: \"Skills\", checks };\n}\n\nasync function checkLockFile(): Promise<SectionResult> {\n const checks: CheckResult[] = [];\n\n try {\n const lock = await readLockFile();\n checks.push({ label: \"Lock file valid\", status: \"pass\" });\n\n const lockSkillNames = Object.keys(lock.skills);\n checks.push({ label: `${lockSkillNames.length} skill entries`, status: \"pass\" });\n\n // Check for orphaned skill entries (canonical path no longer exists)\n const orphaned: string[] = [];\n for (const [name, entry] of Object.entries(lock.skills)) {\n if (entry.canonicalPath && !existsSync(entry.canonicalPath)) {\n orphaned.push(name);\n }\n }\n\n if (orphaned.length === 0) {\n checks.push({ label: \"0 orphaned entries\", status: \"pass\" });\n } else {\n checks.push({\n label: `${orphaned.length} orphaned skill${orphaned.length !== 1 ? \"s\" : \"\"} (in lock, missing from disk)`,\n status: \"warn\",\n detail: orphaned.join(\", \"),\n });\n }\n\n // Check for untracked skills (on disk but not in lock)\n const canonicalDir = CANONICAL_SKILLS_DIR;\n if (existsSync(canonicalDir)) {\n const onDisk = readdirSync(canonicalDir).filter((name) => {\n try {\n const stat = lstatSync(join(canonicalDir, name));\n return stat.isDirectory() || stat.isSymbolicLink();\n } catch {\n return false;\n }\n });\n const untracked = onDisk.filter((name) => !lock.skills[name]);\n\n if (untracked.length === 0) {\n checks.push({ label: \"0 untracked skills\", status: \"pass\" });\n } else {\n checks.push({\n label: `${untracked.length} untracked skill${untracked.length !== 1 ? \"s\" : \"\"} (on disk, not in lock)`,\n status: \"warn\",\n detail: untracked.join(\", \"),\n });\n }\n }\n\n // Check lock agent-list vs actual symlinks\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n const mismatches: string[] = [];\n\n for (const [name, entry] of Object.entries(lock.skills)) {\n if (!entry.agents || entry.agents.length === 0) continue;\n\n for (const agentId of entry.agents) {\n const provider = installed.find((r) => r.provider.id === agentId);\n if (!provider) continue;\n\n const linkPath = join(provider.provider.pathSkills, name);\n if (!existsSync(linkPath)) {\n mismatches.push(`${name} missing from ${agentId}`);\n }\n }\n }\n\n if (mismatches.length === 0) {\n checks.push({ label: \"Lock agent-lists match symlinks\", status: \"pass\" });\n } else {\n checks.push({\n label: `${mismatches.length} agent-list mismatch${mismatches.length !== 1 ? \"es\" : \"\"}`,\n status: \"warn\",\n detail: mismatches.slice(0, 5).join(\", \") + (mismatches.length > 5 ? ` (+${mismatches.length - 5} more)` : \"\"),\n });\n }\n } catch (err) {\n checks.push({\n label: \"Failed to read lock file\",\n status: \"fail\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n\n return { name: \"Lock File\", checks };\n}\n\nasync function checkMcpLockEntries(): Promise<SectionResult> {\n const checks: CheckResult[] = [];\n\n try {\n const lock = await readLockFile();\n const lockNames = Object.keys(lock.mcpServers);\n checks.push({ label: `${lockNames.length} MCP server entries in lock`, status: \"pass\" });\n\n // Detect untracked CLEO servers (in config, not in lock)\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n const liveCleoNames = new Set<string>();\n let untrackedCount = 0;\n\n for (const scope of [\"project\", \"global\"] as const) {\n for (const r of installed) {\n try {\n const entries = await listMcpServers(r.provider, scope);\n for (const entry of entries) {\n const channel = resolveChannelFromServerName(entry.name);\n if (!channel) continue;\n liveCleoNames.add(entry.name);\n\n if (!lock.mcpServers[entry.name]) {\n untrackedCount++;\n }\n }\n } catch {\n // skip unreadable configs\n }\n }\n }\n\n if (untrackedCount === 0) {\n checks.push({ label: \"All CLEO servers tracked in lock\", status: \"pass\" });\n } else {\n checks.push({\n label: `${untrackedCount} untracked CLEO server${untrackedCount !== 1 ? \"s\" : \"\"} (in config, not in lock)`,\n status: \"warn\",\n detail: \"Run `caamp cleo repair` to backfill lock entries\",\n });\n }\n\n // Detect orphaned CLEO entries (in lock, not in any config)\n let orphanedCount = 0;\n const orphanedNames: string[] = [];\n\n for (const serverName of lockNames) {\n const channel = resolveChannelFromServerName(serverName);\n if (!channel) continue;\n\n if (!liveCleoNames.has(serverName)) {\n orphanedCount++;\n orphanedNames.push(serverName);\n }\n }\n\n if (orphanedCount === 0) {\n checks.push({ label: \"No orphaned CLEO lock entries\", status: \"pass\" });\n } else {\n checks.push({\n label: `${orphanedCount} orphaned CLEO lock entr${orphanedCount !== 1 ? \"ies\" : \"y\"} (in lock, not in any config)`,\n status: \"warn\",\n detail: orphanedNames.join(\", \") + \" — Run `caamp cleo repair --prune` to clean up\",\n });\n }\n } catch (err) {\n checks.push({\n label: \"Failed to check MCP lock entries\",\n status: \"fail\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n\n return { name: \"MCP Lock\", checks };\n}\n\nasync function checkConfigFiles(): Promise<SectionResult> {\n const checks: CheckResult[] = [];\n\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n\n for (const r of installed) {\n const provider = r.provider;\n const configPath = provider.configPathGlobal;\n\n if (!existsSync(configPath)) {\n checks.push({\n label: `${provider.id}: no config file found`,\n status: \"warn\",\n detail: configPath,\n });\n continue;\n }\n\n try {\n await readConfig(configPath, provider.configFormat);\n const relPath = configPath.replace(homedir(), \"~\");\n checks.push({\n label: `${provider.id}: ${relPath} readable`,\n status: \"pass\",\n });\n } catch (err) {\n checks.push({\n label: `${provider.id}: config parse error`,\n status: \"fail\",\n detail: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n if (installed.length === 0) {\n checks.push({ label: \"No installed providers to check\", status: \"pass\" });\n }\n\n return { name: \"Config Files\", checks };\n}\n\nfunction formatSection(section: SectionResult): string {\n const lines: string[] = [];\n lines.push(` ${pc.bold(section.name)}`);\n\n for (const check of section.checks) {\n const icon =\n check.status === \"pass\"\n ? pc.green(\"✓\")\n : check.status === \"warn\"\n ? pc.yellow(\"⚠\")\n : pc.red(\"✗\");\n\n lines.push(` ${icon} ${check.label}`);\n\n if (check.detail) {\n lines.push(` ${pc.dim(check.detail)}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Registers the `doctor` command for diagnosing configuration issues and overall system health.\n *\n * @remarks\n * Runs checks across environment, registry, installed providers, skill symlinks, lock file\n * integrity, MCP lock entries, and config file parseability. Returns a structured result\n * with pass/warn/fail status for each check.\n *\n * @param program - The root Commander program to attach the doctor command to\n *\n * @example\n * ```bash\n * caamp doctor --human\n * caamp doctor --json\n * ```\n *\n * @public\n */\nexport function registerDoctorCommand(program: Command): void {\n program\n .command(\"doctor\")\n .description(\"Diagnose configuration issues and health\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { json?: boolean; human?: boolean }) => {\n const operation = \"doctor.check\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n handleFormatError(error, operation, mvi, opts.json);\n }\n\n try {\n const sections: SectionResult[] = [];\n\n sections.push(checkEnvironment());\n sections.push(checkRegistry());\n sections.push(checkInstalledProviders());\n sections.push(checkSkillSymlinks());\n sections.push(await checkLockFile());\n sections.push(await checkMcpLockEntries());\n sections.push(await checkConfigFiles());\n\n // Tally results\n let passed = 0;\n let warnings = 0;\n let errors = 0;\n\n for (const section of sections) {\n for (const check of section.checks) {\n if (check.status === \"pass\") passed++;\n else if (check.status === \"warn\") warnings++;\n else errors++;\n }\n }\n\n // Build result for LAFS envelope\n const npmVersion = getNpmVersion() ?? \"not found\";\n const allProviders = getAllProviders();\n const malformedCount = allProviders.filter(\n (p) => !p.id || !p.toolName || !p.configKey || !p.configFormat\n ).length;\n const detectionResults = detectAllProviders();\n const installedProviders = detectionResults.filter((r) => r.installed);\n const { canonicalCount, brokenCount, staleCount } = countSkillIssues();\n\n const { tracked: mcpTracked, untracked: mcpUntracked, orphaned: mcpOrphaned } = countMcpLockIssues(sections);\n\n const result: DoctorResult = {\n environment: {\n node: getNodeVersion(),\n npm: npmVersion,\n caamp: getCaampVersion(),\n platform: `${process.platform} ${process.arch}`,\n },\n registry: {\n loaded: true,\n count: getProviderCount(),\n valid: malformedCount === 0,\n },\n providers: {\n installed: installedProviders.length,\n list: installedProviders.map((r) => r.provider.id),\n },\n skills: {\n canonical: canonicalCount,\n brokenLinks: brokenCount,\n staleLinks: staleCount,\n },\n mcpServers: {\n tracked: mcpTracked,\n untracked: mcpUntracked,\n orphaned: mcpOrphaned,\n },\n checks: sections.flatMap((s) =>\n s.checks.map((c) => ({\n label: `${s.name}: ${c.label}`,\n status: c.status,\n message: c.detail,\n }))\n ),\n };\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, result);\n \n if (errors > 0) {\n process.exit(1);\n }\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(\"\\ncaamp doctor\\n\"));\n\n for (const section of sections) {\n console.log(formatSection(section));\n console.log();\n }\n\n // Summary line\n const parts: string[] = [];\n parts.push(pc.green(`${passed} checks passed`));\n if (warnings > 0) parts.push(pc.yellow(`${warnings} warning${warnings !== 1 ? \"s\" : \"\"}`));\n if (errors > 0) parts.push(pc.red(`${errors} error${errors !== 1 ? \"s\" : \"\"}`));\n\n console.log(` ${pc.bold(\"Summary\")}: ${parts.join(\", \")}`);\n console.log();\n\n if (errors > 0) {\n process.exit(1);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (format === \"json\") {\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.INTERNAL_ERROR,\n message,\n ErrorCategories.INTERNAL\n );\n } else {\n console.error(pc.red(`Error: ${message}`));\n }\n process.exit(1);\n }\n });\n}\n\nfunction countSkillIssues(): { canonicalCount: number; brokenCount: number; staleCount: number } {\n const canonicalDir = CANONICAL_SKILLS_DIR;\n let canonicalCount = 0;\n\n if (existsSync(canonicalDir)) {\n try {\n const names = readdirSync(canonicalDir).filter((name) => {\n const full = join(canonicalDir, name);\n try {\n const stat = lstatSync(full);\n return stat.isDirectory() || stat.isSymbolicLink();\n } catch {\n return false;\n }\n });\n canonicalCount = names.length;\n } catch {\n // ignore\n }\n }\n\n let brokenCount = 0;\n let staleCount = 0;\n\n const results = detectAllProviders();\n const installed = results.filter((r) => r.installed);\n\n for (const r of installed) {\n const provider = r.provider;\n const skillDir = provider.pathSkills;\n if (!existsSync(skillDir)) continue;\n\n try {\n const entries = readdirSync(skillDir);\n for (const entry of entries) {\n const fullPath = join(skillDir, entry);\n try {\n const stat = lstatSync(fullPath);\n if (!stat.isSymbolicLink()) continue;\n\n if (!existsSync(fullPath)) {\n brokenCount++;\n } else {\n const target = readlinkSync(fullPath);\n const isCanonical =\n target.includes(\"/.agents/skills/\") ||\n target.includes(\"\\\\.agents\\\\skills\\\\\");\n if (!isCanonical) {\n staleCount++;\n }\n }\n } catch {\n // skip unreadable entries\n }\n }\n } catch {\n // skip unreadable dirs\n }\n }\n\n return { canonicalCount, brokenCount, staleCount };\n}\n\nfunction countMcpLockIssues(sections: SectionResult[]): {\n tracked: number;\n untracked: number;\n orphaned: number;\n} {\n const mcpSection = sections.find((s) => s.name === \"MCP Lock\");\n if (!mcpSection) return { tracked: 0, untracked: 0, orphaned: 0 };\n\n let tracked = 0;\n let untracked = 0;\n let orphaned = 0;\n\n for (const check of mcpSection.checks) {\n const countMatch = check.label.match(/^(\\d+)/);\n if (!countMatch?.[1]) continue;\n\n const count = Number.parseInt(countMatch[1], 10);\n if (check.label.includes(\"MCP server entries in lock\")) {\n tracked = count;\n } else if (check.label.includes(\"untracked\")) {\n untracked = count;\n } else if (check.label.includes(\"orphaned\")) {\n orphaned = count;\n }\n }\n\n return { tracked, untracked, orphaned };\n}\n","import { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nlet cachedVersion: string | null = null;\n\n/**\n * Retrieve the current CAAMP package version from the nearest `package.json`.\n *\n * @remarks\n * The version string is read once from `package.json` relative to this module\n * and cached for the lifetime of the process. Returns `\"0.0.0\"` when the file\n * cannot be found or parsed.\n *\n * @returns The semver version string (e.g. `\"1.8.1\"`)\n *\n * @example\n * ```typescript\n * const version = getCaampVersion();\n * console.log(`CAAMP v${version}`);\n * ```\n *\n * @public\n */\nexport function getCaampVersion(): string {\n if (cachedVersion) return cachedVersion;\n\n try {\n const currentDir = dirname(fileURLToPath(import.meta.url));\n const packageJsonPath = join(currentDir, \"..\", \"package.json\");\n const packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf-8\")) as { version?: string };\n cachedVersion = packageJson.version ?? \"0.0.0\";\n } catch {\n cachedVersion = \"0.0.0\";\n }\n\n return cachedVersion;\n}\n","/**\n * instructions inject command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { injectAll } from \"../../core/instructions/injector.js\";\nimport { generateInjectionContent, groupByInstructFile } from \"../../core/instructions/templates.js\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getAllProviders, getProvider } from \"../../core/registry/providers.js\";\nimport type { Provider } from \"../../types.js\";\n\n/**\n * Registers the `instructions inject` subcommand for injecting instruction blocks into provider files.\n *\n * @remarks\n * Writes CAAMP-managed instruction blocks into provider instruction files using marker-based\n * injection. Supports custom content, dry-run preview, and targeting specific or all providers.\n *\n * @param parent - The parent `instructions` Command to attach the inject subcommand to\n *\n * @example\n * ```bash\n * caamp instructions inject --all --global\n * caamp instructions inject --agent claude-code --dry-run\n * ```\n *\n * @public\n */\nexport function registerInstructionsInject(parent: Command): void {\n parent\n .command(\"inject\")\n .description(\"Inject instruction blocks into all provider files\")\n .option(\"-a, --agent <name>\", \"Target specific agent(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-g, --global\", \"Inject into global instruction files\")\n .option(\"--content <text>\", \"Custom content to inject\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--all\", \"Target all known providers\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: {\n agent: string[];\n global?: boolean;\n content?: string;\n dryRun?: boolean;\n all?: boolean;\n json?: boolean;\n human?: boolean;\n }) => {\n const operation = \"instructions.inject\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n let providers: Provider[];\n\n if (opts.all) {\n providers = getAllProviders();\n } else if (opts.agent.length > 0) {\n providers = opts.agent\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else {\n providers = getInstalledProviders();\n }\n\n if (providers.length === 0) {\n const message = \"No providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const content = opts.content ?? generateInjectionContent();\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n\n // Show grouped preview\n const groups = groupByInstructFile(providers);\n\n if (opts.dryRun) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n injected: [],\n providers: providers.map((p) => p.id),\n count: 0,\n dryRun: true,\n wouldInject: Array.from(groups.entries()).map(([file, group]) => ({\n file,\n providers: group.map((p) => p.id),\n })),\n });\n } else {\n console.log(pc.bold(\"Dry run - would inject into:\\n\"));\n for (const [file, group] of groups) {\n console.log(` ${pc.bold(file)}: ${group.map((p) => p.id).join(\", \")}`);\n }\n console.log(pc.dim(`\\n Scope: ${scope}`));\n console.log(pc.dim(` Content length: ${content.length} chars`));\n }\n return;\n }\n\n const results = await injectAll(providers, process.cwd(), scope, content);\n\n const injected: string[] = [];\n for (const [file] of results) {\n injected.push(file);\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n injected,\n providers: providers.map((p) => p.id),\n count: results.size,\n });\n } else {\n for (const [file, action] of results) {\n const icon = action === \"created\" ? pc.green(\"+\")\n : action === \"updated\" ? pc.yellow(\"~\")\n : pc.blue(\"^\");\n console.log(` ${icon} ${file} (${action})`);\n }\n console.log(pc.bold(`\\n${results.size} file(s) processed.`));\n }\n });\n}\n","/**\n * instructions check command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { checkAllInjections } from \"../../core/instructions/injector.js\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getAllProviders, getProvider } from \"../../core/registry/providers.js\";\nimport type { Provider } from \"../../types.js\";\n\n/**\n * Registers the `instructions check` subcommand for verifying injection status across providers.\n *\n * @remarks\n * Checks whether CAAMP injection markers are present and up-to-date in provider instruction files.\n * Reports missing, outdated, or current injection status for each provider.\n *\n * @param parent - The parent `instructions` Command to attach the check subcommand to\n *\n * @example\n * ```bash\n * caamp instructions check --human\n * caamp instructions check --agent claude-code\n * ```\n *\n * @public\n */\nexport function registerInstructionsCheck(parent: Command): void {\n parent\n .command(\"check\")\n .description(\"Check injection status across providers\")\n .option(\"-a, --agent <name>\", \"Check specific agent(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-g, --global\", \"Check global instruction files\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--all\", \"Check all known providers\")\n .action(async (opts: {\n agent: string[];\n global?: boolean;\n json?: boolean;\n human?: boolean;\n all?: boolean;\n }) => {\n const operation = \"instructions.check\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n let providers: Provider[];\n\n if (opts.all) {\n providers = getAllProviders();\n } else if (opts.agent.length > 0) {\n providers = opts.agent\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else {\n providers = getInstalledProviders();\n }\n\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n const results = await checkAllInjections(providers, process.cwd(), scope);\n\n // Build provider status for result\n const providerStatus = results.map((r) => ({\n id: r.provider,\n present: r.status === \"current\" || r.status === \"outdated\",\n path: r.file,\n }));\n\n const present = providerStatus.filter((p) => p.present).length;\n const missing = providerStatus.filter((p) => !p.present).length;\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n providers: providerStatus,\n present,\n missing,\n });\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\nInstruction file status (${scope}):\\n`));\n\n for (const r of results) {\n let icon: string;\n let label: string;\n\n switch (r.status) {\n case \"current\":\n icon = pc.green(\"✓\");\n label = \"current\";\n break;\n case \"outdated\":\n icon = pc.yellow(\"~\");\n label = \"outdated\";\n break;\n case \"missing\":\n icon = pc.red(\"✗\");\n label = \"missing\";\n break;\n case \"none\":\n icon = pc.dim(\"-\");\n label = \"no injection\";\n break;\n }\n\n console.log(` ${icon} ${r.file.padEnd(40)} ${label}`);\n }\n\n console.log();\n });\n}\n","/**\n * instructions update command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { checkAllInjections, injectAll } from \"../../core/instructions/injector.js\";\nimport { generateInjectionContent } from \"../../core/instructions/templates.js\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\n\n/**\n * Registers the `instructions update` subcommand for refreshing all instruction file injections.\n *\n * @remarks\n * Re-generates and updates CAAMP injection blocks in all detected provider instruction files.\n * Checks for stale injections first and only updates those that have changed.\n *\n * @param parent - The parent `instructions` Command to attach the update subcommand to\n *\n * @example\n * ```bash\n * caamp instructions update --yes\n * caamp instructions update --global --json\n * ```\n *\n * @public\n */\nexport function registerInstructionsUpdate(parent: Command): void {\n parent\n .command(\"update\")\n .description(\"Update all instruction file injections\")\n .option(\"-g, --global\", \"Update global instruction files\")\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { global?: boolean; yes?: boolean; json?: boolean; human?: boolean }) => {\n const operation = \"instructions.update\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const providers = getInstalledProviders();\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n const content = generateInjectionContent();\n\n // Check current state\n const checks = await checkAllInjections(providers, process.cwd(), scope, content);\n const needsUpdate = checks.filter((c) => c.status !== \"current\");\n\n if (needsUpdate.length === 0) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n updated: [],\n failed: [],\n count: { updated: 0, failed: 0 },\n });\n } else {\n console.log(pc.green(\"All instruction files are up to date.\"));\n }\n return;\n }\n\n if (format === \"human\") {\n console.log(pc.bold(`${needsUpdate.length} file(s) need updating:\\n`));\n for (const c of needsUpdate) {\n console.log(` ${c.file} (${c.status})`);\n }\n }\n\n // Filter providers to only those needing updates\n const providerIds = new Set(needsUpdate.map((c) => c.provider));\n const toUpdate = providers.filter((p) => providerIds.has(p.id));\n\n const results = await injectAll(toUpdate, process.cwd(), scope, content);\n\n const updated: string[] = [];\n for (const [file] of results) {\n updated.push(file);\n }\n\n if (format === \"human\") {\n console.log();\n for (const [file, action] of results) {\n console.log(` ${pc.green(\"✓\")} ${file} (${action})`);\n }\n console.log(pc.bold(`\\n${results.size} file(s) updated.`));\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n updated,\n failed: [],\n count: { updated: updated.length, failed: 0 },\n });\n }\n });\n}\n","/**\n * Instruction file management command group for injecting, checking, and updating CAAMP-managed\n * instruction blocks in provider instruction files (CLAUDE.md, AGENTS.md, GEMINI.md).\n *\n * @packageDocumentation\n */\n\nimport type { Command } from \"commander\";\nimport { registerInstructionsInject } from \"./inject.js\";\nimport { registerInstructionsCheck } from \"./check.js\";\nimport { registerInstructionsUpdate } from \"./update.js\";\n\n/**\n * Registers the `instructions` command group with inject, check, and update subcommands.\n *\n * @remarks\n * Manages CAAMP marker-based injection blocks within provider instruction files.\n * Supports inject (create), check (verify status), and update (refresh) operations.\n *\n * @param program - The root Commander program to attach the instructions command group to\n *\n * @example\n * ```bash\n * caamp instructions inject --all\n * caamp instructions check --human\n * caamp instructions update --yes\n * ```\n *\n * @public\n */\nexport function registerInstructionsCommands(program: Command): void {\n const instructions = program\n .command(\"instructions\")\n .description(\"Manage instruction file injections\");\n\n registerInstructionsInject(instructions);\n registerInstructionsCheck(instructions);\n registerInstructionsUpdate(instructions);\n}\n","/**\n * CLEO MCP channel commands and compatibility wrappers.\n */\n\nimport { createInterface } from \"node:readline/promises\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport {\n buildCleoProfile,\n type CleoChannel,\n checkCommandReachability,\n extractVersionTag,\n normalizeCleoChannel,\n parseEnvAssignments,\n resolveChannelFromServerName,\n resolveCleoServerName,\n} from \"../../core/mcp/cleo.js\";\nimport { installMcpServerToAll } from \"../../core/mcp/installer.js\";\nimport { getTrackedMcpServers, recordMcpInstall, removeMcpFromLock } from \"../../core/mcp/lock.js\";\nimport { listMcpServers, removeMcpServer } from \"../../core/mcp/reader.js\";\nimport { reconcileCleoLock } from \"../../core/mcp/reconcile.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport type { Provider } from \"../../types.js\";\n\ninterface CleoInstallOptions {\n channel?: string;\n provider: string[];\n all?: boolean;\n global?: boolean;\n version?: string;\n command?: string;\n arg: string[];\n env: string[];\n cleoDir?: string;\n dryRun?: boolean;\n yes?: boolean;\n interactive?: boolean;\n json?: boolean;\n human?: boolean;\n}\n\ninterface CleoUninstallOptions {\n channel?: string;\n provider: string[];\n all?: boolean;\n global?: boolean;\n dryRun?: boolean;\n json?: boolean;\n human?: boolean;\n}\n\ninterface CleoShowOptions {\n provider: string[];\n all?: boolean;\n global?: boolean;\n project?: boolean;\n channel?: string;\n json?: boolean;\n human?: boolean;\n}\n\ninterface CleoRepairOptions {\n provider: string[];\n all?: boolean;\n global?: boolean;\n project?: boolean;\n prune?: boolean;\n dryRun?: boolean;\n json?: boolean;\n human?: boolean;\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nfunction collectTargetProviders(providerIds: string[], all?: boolean): Provider[] {\n if (all) {\n return getInstalledProviders();\n }\n\n if (providerIds.length > 0) {\n return providerIds\n .map((id) => getProvider(id))\n .filter((provider): provider is Provider => provider !== undefined);\n }\n\n return getInstalledProviders();\n}\n\nasync function validateProfile(\n provider: Provider,\n scope: \"project\" | \"global\",\n serverName: string,\n): Promise<{ valid: boolean; reason?: string }> {\n const entries = await listMcpServers(provider, scope);\n const entry = entries.find((candidate) => candidate.name === serverName);\n if (!entry) {\n return { valid: false, reason: \"server missing after write\" };\n }\n\n const command = typeof entry.config.command === \"string\" ? entry.config.command : undefined;\n if (!command) {\n return { valid: true };\n }\n\n const reachability = checkCommandReachability(command);\n if (!reachability.reachable) {\n return {\n valid: false,\n reason: `command not reachable (${reachability.method}: ${reachability.detail})`,\n };\n }\n\n return { valid: true };\n}\n\nasync function detectServerConflicts(\n providers: Provider[],\n scope: \"project\" | \"global\",\n targetServerName: string,\n): Promise<Array<{ providerId: string; message: string }>> {\n const warnings: Array<{ providerId: string; message: string }> = [];\n\n for (const provider of providers) {\n const entries = await listMcpServers(provider, scope);\n const existing = entries.find((entry) => entry.name === targetServerName);\n if (!existing) continue;\n\n const command = typeof existing.config.command === \"string\" ? existing.config.command : \"\";\n const args = Array.isArray(existing.config.args)\n ? existing.config.args.filter((value): value is string => typeof value === \"string\")\n : [];\n const flat = `${command} ${args.join(\" \")}`.toLowerCase();\n\n if (!flat.includes(\"cleo\")) {\n warnings.push({\n providerId: provider.id,\n message: `Server name '${targetServerName}' already exists with a non-CLEO command in ${provider.id}.`,\n });\n }\n }\n\n return warnings;\n}\n\nfunction formatInstallResultHuman(\n mode: \"install\" | \"update\",\n channel: CleoChannel,\n serverName: string,\n scope: \"project\" | \"global\",\n results: Awaited<ReturnType<typeof installMcpServerToAll>>,\n validations: Array<{ providerId: string; valid: boolean; reason?: string }>,\n): void {\n console.log(pc.bold(`${mode === \"install\" ? \"Install\" : \"Update\"} CLEO channel: ${channel}`));\n console.log(pc.dim(`Server: ${serverName} Scope: ${scope}`));\n console.log();\n\n for (const result of results) {\n const validation = validations.find((entry) => entry.providerId === result.provider.id);\n if (result.success) {\n const validationLabel = validation?.valid\n ? pc.green(\"validated\")\n : pc.yellow(`validation warning: ${validation?.reason ?? \"unknown\"}`);\n console.log(` ${pc.green(\"+\")} ${result.provider.toolName.padEnd(22)} ${pc.dim(result.configPath)} ${validationLabel}`);\n } else {\n console.log(` ${pc.red(\"x\")} ${result.provider.toolName.padEnd(22)} ${pc.red(result.error ?? \"failed\")}`);\n console.log(pc.dim(\" Recovery: verify config path permissions and retry with --dry-run.\"));\n }\n }\n console.log();\n}\n\nasync function runInteractiveInstall(\n opts: CleoInstallOptions,\n): Promise<CleoInstallOptions> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n const discovered = getInstalledProviders();\n if (discovered.length === 0) {\n throw new Error(\"No installed providers were detected for interactive setup.\");\n }\n\n console.log(pc.bold(\"CLEO MCP Setup\"));\n console.log(pc.dim(\"Step 1/6 - Select provider(s)\"));\n for (const [index, provider] of discovered.entries()) {\n console.log(` ${index + 1}. ${provider.id} (${provider.toolName})`);\n }\n const providerAnswer = await rl.question(pc.dim(\"Choose providers (e.g. 1,2 or all): \"));\n const selectedProviders = providerAnswer.trim().toLowerCase() === \"all\"\n ? discovered.map((provider) => provider.id)\n : providerAnswer\n .split(\",\")\n .map((part) => Number(part.trim()))\n .filter((value) => Number.isFinite(value) && value > 0 && value <= discovered.length)\n .map((index) => discovered[index - 1]?.id)\n .filter((id): id is string => Boolean(id));\n\n if (selectedProviders.length === 0) {\n throw new Error(\"No providers selected.\");\n }\n\n console.log();\n console.log(pc.dim(\"Step 2/6 - Select channel\"));\n const channelAnswer = await rl.question(pc.dim(\"Channel [stable/beta/dev] (stable): \"));\n const selectedChannel = normalizeCleoChannel(channelAnswer || \"stable\");\n\n let command = opts.command;\n let args = [...opts.arg];\n let env = [...opts.env];\n let cleoDir = opts.cleoDir;\n if (selectedChannel === \"dev\") {\n command = await rl.question(pc.dim(\"Dev command (required): \"));\n const argsAnswer = await rl.question(pc.dim(\"Dev args (space-separated, optional): \"));\n args = argsAnswer.trim() === \"\" ? [] : argsAnswer.trim().split(/\\s+/);\n const dirAnswer = await rl.question(pc.dim(\"CLEO_DIR (~/.cleo-dev default): \"));\n cleoDir = dirAnswer.trim() === \"\" ? \"~/.cleo-dev\" : dirAnswer.trim();\n if (cleoDir.trim() !== \"\") {\n env = [\n ...env.filter((entry) => !entry.startsWith(\"CLEO_DIR=\")),\n `CLEO_DIR=${cleoDir}`,\n ];\n }\n }\n\n const profile = buildCleoProfile({\n channel: selectedChannel,\n version: opts.version,\n command,\n args,\n env: parseEnvAssignments(env),\n cleoDir,\n });\n\n console.log();\n console.log(pc.dim(\"Step 3/6 - Preview profile diff\"));\n console.log(` Server: ${pc.bold(profile.serverName)}`);\n console.log(` Channel: ${selectedChannel}`);\n console.log(` Config: ${JSON.stringify(profile.config)}`);\n\n console.log();\n console.log(pc.dim(\"Step 4/6 - Confirm apply\"));\n const confirm = await rl.question(pc.dim(\"Apply this configuration? [y/N] \"));\n if (![\"y\", \"yes\"].includes(confirm.trim().toLowerCase())) {\n throw new Error(\"Cancelled by user.\");\n }\n\n return {\n ...opts,\n provider: selectedProviders,\n channel: selectedChannel,\n command,\n arg: args,\n env,\n cleoDir,\n yes: true,\n };\n } finally {\n rl.close();\n }\n}\n\n/**\n * Executes a CLEO MCP channel install or update operation across targeted providers.\n *\n * @remarks\n * Builds a CLEO profile from the resolved options, writes configuration to all targeted providers,\n * validates the result, and records the install in the lock file. Supports interactive mode and\n * dry-run previews.\n *\n * @param mode - Whether to install a new profile or update an existing one\n * @param opts - CLEO install options including channel, providers, and env configuration\n * @param operation - The LAFS operation identifier for envelope metadata\n * @returns Resolves when the install/update operation completes\n *\n * @example\n * ```bash\n * caamp cleo install --channel stable --all\n * caamp mcp cleo update --channel dev --command ./my-cleo\n * ```\n *\n * @public\n */\nexport async function executeCleoInstall(\n mode: \"install\" | \"update\",\n opts: CleoInstallOptions,\n operation: string,\n): Promise<void> {\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const interactive = (opts.interactive ?? false) && format === \"human\";\n const resolvedOpts = interactive ? await runInteractiveInstall(opts) : opts;\n\n const channel = normalizeCleoChannel(resolvedOpts.channel);\n const providers = collectTargetProviders(resolvedOpts.provider, resolvedOpts.all);\n if (providers.length === 0) {\n const message = \"No target providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const envMap = parseEnvAssignments(resolvedOpts.env);\n const profile = buildCleoProfile({\n channel,\n version: resolvedOpts.version,\n command: resolvedOpts.command,\n args: resolvedOpts.arg,\n env: envMap,\n cleoDir: resolvedOpts.cleoDir,\n });\n\n const scope = resolvedOpts.global ? \"global\" as const : \"project\" as const;\n\n if (resolvedOpts.dryRun) {\n if (format === \"human\") {\n console.log(pc.bold(`Dry run: ${mode} CLEO (${channel})`));\n console.log(pc.dim(`Server: ${profile.serverName} Scope: ${scope}`));\n console.log(pc.dim(`Providers: ${providers.map((provider) => provider.id).join(\", \")}`));\n console.log(pc.dim(`Command: ${profile.config.command ?? \"(none)\"} ${(profile.config.args ?? []).join(\" \")}`));\n if (profile.config.env && Object.keys(profile.config.env).length > 0) {\n console.log(pc.dim(`Env: ${JSON.stringify(profile.config.env)}`));\n }\n } else {\n outputSuccess(operation, mvi, {\n action: mode,\n channel,\n serverName: profile.serverName,\n providers: providers.map((provider) => provider.id),\n scope,\n command: profile.config.command,\n args: profile.config.args ?? [],\n env: profile.config.env ?? {},\n packageSpec: profile.packageSpec,\n dryRun: true,\n });\n }\n return;\n }\n\n const conflictWarnings = await detectServerConflicts(providers, scope, profile.serverName);\n if (format === \"human\" && conflictWarnings.length > 0) {\n console.log(pc.yellow(\"Warning: potential server name conflicts detected.\"));\n for (const warning of conflictWarnings) {\n console.log(pc.yellow(` - ${warning.message}`));\n }\n console.log(pc.dim(\"Recovery: run with --dry-run, inspect provider config, then retry with explicit channel/profile.\"));\n console.log();\n }\n\n const results = await installMcpServerToAll(providers, profile.serverName, profile.config, scope);\n const succeeded = results.filter((result) => result.success);\n\n const validations: Array<{ providerId: string; valid: boolean; reason?: string }> = [];\n for (const result of succeeded) {\n const validation = await validateProfile(result.provider, scope, profile.serverName);\n validations.push({ providerId: result.provider.id, valid: validation.valid, reason: validation.reason });\n }\n\n if (succeeded.length > 0) {\n await recordMcpInstall(\n profile.serverName,\n profile.packageSpec ?? resolvedOpts.command ?? \"cleo-dev\",\n channel === \"dev\" ? \"command\" : \"package\",\n succeeded.map((result) => result.provider.id),\n resolvedOpts.global ?? false,\n resolvedOpts.version ?? extractVersionTag(profile.packageSpec),\n );\n }\n\n if (format === \"human\") {\n formatInstallResultHuman(mode, channel, profile.serverName, scope, results, validations);\n }\n\n const validationFailures = validations.filter((entry) => !entry.valid);\n if (interactive && validationFailures.length > 0 && format === \"human\") {\n console.log(pc.dim(\"Step 5/6 - Validation\"));\n console.log(pc.yellow(`Validation found ${validationFailures.length} issue(s).`));\n\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n console.log(pc.dim(\"Step 6/6 - Rollback\"));\n const answer = await rl.question(pc.dim(\"Rollback failed validations? [y/N] \"));\n if ([\"y\", \"yes\"].includes(answer.trim().toLowerCase())) {\n for (const failure of validationFailures) {\n const provider = providers.find((candidate) => candidate.id === failure.providerId);\n if (!provider) continue;\n await removeMcpServer(provider, profile.serverName, scope);\n }\n console.log(pc.yellow(\"Rollback completed for failed provider validations.\"));\n }\n } finally {\n rl.close();\n }\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n action: mode,\n channel,\n serverName: profile.serverName,\n scope,\n command: profile.config.command,\n args: profile.config.args ?? [],\n env: profile.config.env ?? {},\n packageSpec: profile.packageSpec,\n providers: results.map((result) => ({\n id: result.provider.id,\n success: result.success,\n configPath: result.configPath,\n error: result.error,\n validation: validations.find((entry) => entry.providerId === result.provider.id) ?? null,\n })),\n conflicts: conflictWarnings,\n validationStatus: validationFailures.length === 0 ? \"ok\" : \"warning\",\n });\n }\n}\n\n/**\n * Executes a CLEO MCP channel uninstall operation across targeted providers.\n *\n * @remarks\n * Removes the CLEO server entry matching the resolved channel from all targeted provider\n * configurations and cleans up the corresponding lock file entry.\n *\n * @param opts - CLEO uninstall options including channel, providers, and scope\n * @param operation - The LAFS operation identifier for envelope metadata\n * @returns Resolves when the uninstall operation completes\n *\n * @example\n * ```bash\n * caamp cleo uninstall --channel beta --all\n * ```\n *\n * @public\n */\nexport async function executeCleoUninstall(\n opts: CleoUninstallOptions,\n operation: string,\n): Promise<void> {\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const channel = normalizeCleoChannel(opts.channel);\n const serverName = resolveCleoServerName(channel);\n const providers = collectTargetProviders(opts.provider, opts.all);\n\n if (providers.length === 0) {\n const message = \"No target providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n if (opts.dryRun) {\n if (format === \"human\") {\n console.log(pc.bold(\"Dry run: uninstall CLEO profile\"));\n console.log(pc.dim(`Server: ${serverName} Channel: ${channel} Scope: ${scope}`));\n console.log(pc.dim(`Providers: ${providers.map((provider) => provider.id).join(\", \")}`));\n } else {\n outputSuccess(operation, mvi, {\n action: \"uninstall\",\n channel,\n serverName,\n providers: providers.map((provider) => provider.id),\n scope,\n dryRun: true,\n });\n }\n return;\n }\n\n const removed: string[] = [];\n for (const provider of providers) {\n const success = await removeMcpServer(provider, serverName, scope);\n if (success) removed.push(provider.id);\n }\n\n if (removed.length > 0) {\n await removeMcpFromLock(serverName);\n }\n\n if (format === \"human\") {\n const prefix = removed.length > 0 ? pc.green(\"Removed\") : pc.yellow(\"No matching profile found for\");\n console.log(`${prefix} ${pc.bold(serverName)} (${channel}) on ${removed.length}/${providers.length} providers.`);\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n action: \"uninstall\",\n channel,\n serverName,\n scope,\n removed,\n providerCount: providers.length,\n dryRun: false,\n });\n }\n}\n\n/**\n * Health status of a CLEO MCP entry: healthy, degraded (untracked), or broken (command unreachable).\n *\n * @remarks\n * Used by the show and repair commands to classify the state of each CLEO profile entry.\n *\n * @public\n */\nexport type CleoHealthStatus = \"healthy\" | \"degraded\" | \"broken\";\n\n/**\n * Health assessment result for a single CLEO MCP entry.\n *\n * @remarks\n * Combines command reachability, config presence, and lock tracking status into an overall health classification.\n *\n * @public\n */\nexport interface CleoEntryHealth {\n /** Whether the entry's command binary is reachable on the system PATH. */\n commandReachable: boolean;\n /** Detail string describing the reachability check result. */\n commandDetail: string;\n /** Whether the config file containing this entry exists. */\n configPresent: boolean;\n /** Whether this entry is tracked in the CAAMP lock file. */\n lockTracked: boolean;\n /** Overall health status derived from the individual checks. */\n status: CleoHealthStatus;\n}\n\n/**\n * Checks the health of a CLEO MCP entry by verifying command reachability and lock tracking.\n *\n * @remarks\n * Returns \"healthy\" when the command is reachable and the entry is tracked, \"degraded\" when\n * untracked, and \"broken\" when the command is not reachable on the system PATH.\n *\n * @param command - The command binary string to check for reachability, or undefined if no command\n * @param lockTracked - Whether this entry is tracked in the CAAMP lock file\n * @returns A health assessment object with status and detail information\n *\n * @example\n * ```typescript\n * const health = checkCleoEntryHealth(\"npx\", true);\n * // health.status === \"healthy\"\n * ```\n *\n * @public\n */\nexport function checkCleoEntryHealth(\n command: string | undefined,\n lockTracked: boolean,\n): CleoEntryHealth {\n if (!command) {\n return {\n commandReachable: true,\n commandDetail: \"(no command)\",\n configPresent: true,\n lockTracked,\n status: lockTracked ? \"healthy\" : \"degraded\",\n };\n }\n\n const reachability = checkCommandReachability(command);\n if (!reachability.reachable) {\n return {\n commandReachable: false,\n commandDetail: reachability.detail,\n configPresent: true,\n lockTracked,\n status: \"broken\",\n };\n }\n\n return {\n commandReachable: true,\n commandDetail: reachability.detail,\n configPresent: true,\n lockTracked,\n status: lockTracked ? \"healthy\" : \"degraded\",\n };\n}\n\n/**\n * Executes the CLEO show operation to display installed channel profiles across providers.\n *\n * @remarks\n * Scans provider configurations for CLEO entries, enriches them with lock file metadata and\n * health checks, and outputs a tabular or JSON view of all discovered profiles.\n *\n * @param opts - Show options including provider filter, scope, and channel filter\n * @param operation - The LAFS operation identifier for envelope metadata\n * @returns Resolves when the show output is complete\n *\n * @example\n * ```bash\n * caamp cleo show --channel stable --human\n * ```\n *\n * @public\n */\nexport async function executeCleoShow(\n opts: CleoShowOptions,\n operation: string,\n): Promise<void> {\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const providers = collectTargetProviders(opts.provider, opts.all);\n if (providers.length === 0) {\n const message = \"No target providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const channelFilter = opts.channel ? normalizeCleoChannel(opts.channel) : null;\n\n // Determine which scopes to scan\n const scopes: Array<\"project\" | \"global\"> = [];\n if (opts.global && !opts.project) {\n scopes.push(\"global\");\n } else if (opts.project && !opts.global) {\n scopes.push(\"project\");\n } else {\n scopes.push(\"project\", \"global\");\n }\n\n // Load lock file data\n const lockEntries = await getTrackedMcpServers();\n\n interface EnrichedProfile {\n provider: string;\n providerName: string;\n serverName: string;\n channel: CleoChannel;\n scope: \"project\" | \"global\";\n command?: string;\n args: string[];\n env: Record<string, string>;\n version: string | null;\n source: string | null;\n sourceType: string | null;\n installedAt: string | null;\n updatedAt: string | null;\n health: CleoEntryHealth;\n }\n\n const entries: EnrichedProfile[] = [];\n const warnings: import(\"../../core/lafs.js\").LAFSWarning[] = [];\n\n for (const scope of scopes) {\n for (const provider of providers) {\n const providerEntries = await listMcpServers(provider, scope);\n for (const entry of providerEntries) {\n const channel = resolveChannelFromServerName(entry.name);\n if (!channel) continue;\n if (channelFilter && channel !== channelFilter) continue;\n\n const command = typeof entry.config.command === \"string\" ? entry.config.command : undefined;\n const args = Array.isArray(entry.config.args)\n ? entry.config.args.filter((value): value is string => typeof value === \"string\")\n : [];\n const env = typeof entry.config.env === \"object\" && entry.config.env !== null\n ? entry.config.env as Record<string, string>\n : {};\n\n const lockEntry = lockEntries[entry.name];\n const lockTracked = lockEntry !== undefined;\n const health = checkCleoEntryHealth(command, lockTracked);\n\n entries.push({\n provider: provider.id,\n providerName: provider.toolName,\n serverName: entry.name,\n channel,\n scope,\n command,\n args,\n env,\n version: lockEntry?.version ?? null,\n source: lockEntry?.source ?? null,\n sourceType: lockEntry?.sourceType ?? null,\n installedAt: lockEntry?.installedAt ?? null,\n updatedAt: lockEntry?.updatedAt ?? null,\n health,\n });\n\n if (health.status === \"broken\") {\n warnings.push({\n code: \"W_COMMAND_UNREACHABLE\",\n message: `${entry.name} command not reachable on ${provider.toolName} (${health.commandDetail})`,\n });\n } else if (health.status === \"degraded\") {\n warnings.push({\n code: \"W_NOT_TRACKED\",\n message: `${entry.name} on ${provider.toolName} is not tracked in lock file`,\n });\n }\n }\n }\n }\n\n const issueCount = entries.filter((e) => e.health.status !== \"healthy\").length;\n\n if (format === \"human\") {\n if (entries.length === 0) {\n console.log(pc.dim(\"No CLEO channel profiles found.\"));\n } else {\n console.log(pc.bold(\"CLEO Channel Profiles\"));\n console.log();\n\n // Column headers\n const header = [\n \"Channel\".padEnd(10),\n \"Version\".padEnd(10),\n \"Provider\".padEnd(22),\n \"Scope\".padEnd(9),\n \"Command\".padEnd(33),\n \"Status\".padEnd(10),\n \"Installed\".padEnd(12),\n ].join(\"\");\n console.log(` ${pc.dim(header)}`);\n console.log(` ${pc.dim(\"-\".repeat(106))}`);\n\n for (const entry of entries) {\n const commandStr = entry.command\n ? `${entry.command} ${entry.args.join(\" \")}`.slice(0, 31).padEnd(33)\n : pc.dim(\"-\").padEnd(33);\n const versionStr = (entry.version ?? \"-\").padEnd(10);\n const installedStr = entry.installedAt\n ? entry.installedAt.slice(0, 10).padEnd(12)\n : \"-\".padEnd(12);\n\n let statusStr: string;\n if (entry.health.status === \"healthy\") {\n statusStr = pc.green(\"healthy\".padEnd(10));\n } else if (entry.health.status === \"degraded\") {\n statusStr = pc.yellow(\"degraded\".padEnd(10));\n } else {\n statusStr = pc.red(\"broken\".padEnd(10));\n }\n\n console.log(\n ` ${entry.channel.padEnd(10)}${versionStr}${entry.providerName.padEnd(22)}${entry.scope.padEnd(9)}${commandStr}${statusStr}${installedStr}`,\n );\n }\n\n console.log();\n const summary = ` ${entries.length} profile${entries.length !== 1 ? \"s\" : \"\"}`;\n if (issueCount > 0) {\n console.log(`${summary} | ${pc.yellow(`${issueCount} issue${issueCount !== 1 ? \"s\" : \"\"}`)}`);\n console.log();\n console.log(\" Issues:\");\n for (const w of warnings) {\n console.log(` ${pc.yellow(\"!\")} ${w.message}`);\n }\n } else {\n console.log(summary);\n }\n }\n }\n\n if (format === \"json\") {\n outputSuccess(\n operation,\n mvi,\n {\n providers: providers.map((provider) => provider.id),\n scopes,\n channel: channelFilter,\n profiles: entries,\n count: entries.length,\n },\n undefined,\n undefined,\n warnings.length > 0 ? warnings : undefined,\n );\n }\n}\n\n/**\n * Executes the CLEO repair operation to reconcile lock file entries with actual configurations.\n *\n * @remarks\n * Backfills untracked CLEO entries found in provider configs into the lock file and optionally\n * prunes orphaned lock entries that no longer exist in any config. Supports dry-run mode.\n *\n * @param opts - Repair options including provider filter, scope, prune flag, and dry-run\n * @param operation - The LAFS operation identifier for envelope metadata\n * @returns Resolves when the repair operation completes\n *\n * @example\n * ```bash\n * caamp cleo repair --prune --dry-run\n * ```\n *\n * @public\n */\nexport async function executeCleoRepair(\n opts: CleoRepairOptions,\n operation: string,\n): Promise<void> {\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const providerIds = opts.provider.length > 0 ? opts.provider : undefined;\n\n const result = await reconcileCleoLock({\n providerIds,\n all: opts.all,\n global: opts.global,\n project: opts.project,\n prune: opts.prune,\n dryRun: opts.dryRun,\n });\n\n if (format === \"human\") {\n const prefix = opts.dryRun ? \"CLEO Lock Repair (dry run)\" : \"CLEO Lock Repair\";\n console.log(pc.bold(prefix));\n console.log();\n\n if (result.backfilled.length > 0) {\n for (const entry of result.backfilled) {\n const agents = entry.agents.join(\", \");\n const versionStr = entry.version ? `(${entry.version})` : \"\";\n console.log(\n ` ${pc.green(\"+\")} ${entry.serverName.padEnd(12)}${entry.channel.padEnd(10)}${agents.padEnd(22)}${entry.scope.padEnd(10)}${entry.source} ${pc.dim(versionStr)}`,\n );\n }\n }\n\n if (result.pruned.length > 0) {\n for (const name of result.pruned) {\n console.log(` ${pc.red(\"-\")} ${name} (removed from lock)`);\n }\n }\n\n if (result.backfilled.length === 0 && result.pruned.length === 0) {\n console.log(pc.dim(\" No changes needed. All CLEO entries are tracked.\"));\n }\n\n console.log();\n console.log(\n ` ${result.backfilled.length} backfilled | ${result.pruned.length} pruned | ${result.alreadyTracked} already tracked`,\n );\n\n if (result.errors.length > 0) {\n console.log();\n for (const err of result.errors) {\n console.log(` ${pc.red(\"!\")} ${err.message}`);\n }\n }\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n backfilled: result.backfilled,\n pruned: result.pruned,\n alreadyTracked: result.alreadyTracked,\n dryRun: opts.dryRun ?? false,\n errors: result.errors,\n });\n }\n}\n\nfunction buildInstallOptions(command: Command): Command {\n return command\n .requiredOption(\"--channel <channel>\", \"CLEO channel: stable|beta|dev\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Apply to all detected providers\")\n .option(\"-g, --global\", \"Use global scope\")\n .option(\"--version <tag>\", \"Tag/version for stable or beta\")\n .option(\"--command <command>\", \"Dev channel command\")\n .option(\"--arg <arg>\", \"Dev command arg (repeatable)\", collect, [])\n .option(\"--env <kv>\", \"Environment assignment KEY=value (repeatable)\", collect, [])\n .option(\"--cleo-dir <path>\", \"CLEO_DIR override for dev channel\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--interactive\", \"Guided interactive setup\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\");\n}\n\n/**\n * Registers the `mcp cleo` subcommand group with install, update, uninstall, show, and repair.\n *\n * @remarks\n * Provides the nested `mcp cleo` command tree for managing CLEO channel profiles within\n * the MCP command group.\n *\n * @param parent - The parent `mcp` Command to attach the cleo subcommand group to\n *\n * @example\n * ```bash\n * caamp mcp cleo install --channel stable --all\n * caamp mcp cleo show --human\n * ```\n *\n * @public\n */\nexport function registerMcpCleoCommands(parent: Command): void {\n const cleo = parent\n .command(\"cleo\")\n .description(\"Manage CLEO MCP channel profiles\");\n\n buildInstallOptions(\n cleo\n .command(\"install\")\n .description(\"Install CLEO MCP profile by channel\"),\n ).action(async (opts: CleoInstallOptions) => {\n await executeCleoInstall(\"install\", opts, \"mcp.cleo.install\");\n });\n\n buildInstallOptions(\n cleo\n .command(\"update\")\n .description(\"Update CLEO MCP profile by channel\"),\n ).action(async (opts: CleoInstallOptions) => {\n await executeCleoInstall(\"update\", opts, \"mcp.cleo.update\");\n });\n\n cleo\n .command(\"uninstall\")\n .description(\"Uninstall CLEO MCP profile for a channel\")\n .requiredOption(\"--channel <channel>\", \"CLEO channel: stable|beta|dev\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Apply to all detected providers\")\n .option(\"-g, --global\", \"Use global scope\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoUninstallOptions) => {\n await executeCleoUninstall(opts, \"mcp.cleo.uninstall\");\n });\n\n cleo\n .command(\"show\")\n .description(\"Show installed CLEO MCP channel profiles\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Inspect all detected providers\")\n .option(\"-g, --global\", \"Global scope only\")\n .option(\"-p, --project\", \"Project scope only\")\n .option(\"--channel <channel>\", \"Filter channel: stable|beta|dev\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoShowOptions) => {\n await executeCleoShow(opts, \"mcp.cleo.show\");\n });\n\n cleo\n .command(\"repair\")\n .description(\"Repair lock file by backfilling untracked CLEO entries\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Scan all detected providers\")\n .option(\"-g, --global\", \"Global scope only\")\n .option(\"-p, --project\", \"Project scope only\")\n .option(\"--prune\", \"Remove orphaned lock entries not in any config\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoRepairOptions) => {\n await executeCleoRepair(opts, \"mcp.cleo.repair\");\n });\n}\n\n/**\n * Registers backward-compatible update, uninstall, and show commands directly on the `mcp` parent.\n *\n * @remarks\n * Provides `mcp update cleo`, `mcp uninstall cleo`, and `mcp show cleo` as aliases for the\n * nested `mcp cleo` subcommands. Only the \"cleo\" managed profile name is supported.\n *\n * @param parent - The parent `mcp` Command to attach the compatibility commands to\n *\n * @example\n * ```bash\n * caamp mcp update cleo --channel stable\n * caamp mcp uninstall cleo --channel dev\n * ```\n *\n * @public\n */\nexport function registerMcpCleoCompatibilityCommands(parent: Command): void {\n parent\n .command(\"update\")\n .description(\"Update channel-managed MCP profile\")\n .argument(\"<name>\", \"Managed MCP profile name (cleo)\")\n .requiredOption(\"--channel <channel>\", \"CLEO channel: stable|beta|dev\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Apply to all detected providers\")\n .option(\"-g, --global\", \"Use global scope\")\n .option(\"--version <tag>\", \"Tag/version for stable or beta\")\n .option(\"--command <command>\", \"Dev channel command\")\n .option(\"--arg <arg>\", \"Dev command arg (repeatable)\", collect, [])\n .option(\"--env <kv>\", \"Environment assignment KEY=value (repeatable)\", collect, [])\n .option(\"--cleo-dir <path>\", \"CLEO_DIR override for dev channel\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string, opts: CleoInstallOptions) => {\n if (name !== \"cleo\") {\n emitJsonError(\"mcp.update\", \"standard\", ErrorCodes.INVALID_INPUT, \"Only managed profile 'cleo' is supported by mcp update.\", ErrorCategories.VALIDATION, { name });\n process.exit(1);\n }\n await executeCleoInstall(\"update\", opts, \"mcp.update\");\n });\n\n parent\n .command(\"uninstall\")\n .description(\"Uninstall channel-managed MCP profile\")\n .argument(\"<name>\", \"Managed MCP profile name (cleo)\")\n .requiredOption(\"--channel <channel>\", \"CLEO channel: stable|beta|dev\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Apply to all detected providers\")\n .option(\"-g, --global\", \"Use global scope\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string, opts: CleoUninstallOptions) => {\n if (name !== \"cleo\") {\n emitJsonError(\"mcp.uninstall\", \"standard\", ErrorCodes.INVALID_INPUT, \"Only managed profile 'cleo' is supported by mcp uninstall.\", ErrorCategories.VALIDATION, { name });\n process.exit(1);\n }\n await executeCleoUninstall(opts, \"mcp.uninstall\");\n });\n\n parent\n .command(\"show\")\n .description(\"Show channel-managed MCP profile\")\n .argument(\"<name>\", \"Managed MCP profile name (cleo)\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Inspect all detected providers\")\n .option(\"-g, --global\", \"Global scope only\")\n .option(\"-p, --project\", \"Project scope only\")\n .option(\"--channel <channel>\", \"Filter channel: stable|beta|dev\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string, opts: CleoShowOptions) => {\n if (name !== \"cleo\") {\n emitJsonError(\"mcp.show\", \"standard\", ErrorCodes.INVALID_INPUT, \"Only managed profile 'cleo' is supported by mcp show.\", ErrorCategories.VALIDATION, { name });\n process.exit(1);\n }\n await executeCleoShow(opts, \"mcp.show\");\n });\n}\n\n/**\n * Maps generic MCP install CLI options to CLEO-specific install options for compatibility routing.\n *\n * @remarks\n * Merges the `--agent` and `--provider` flags into a single provider list and provides defaults\n * for array fields. Used when `mcp install cleo --channel ...` is detected.\n *\n * @param opts - The raw CLI options from the mcp install command\n * @returns A normalized CleoInstallOptions object ready for executeCleoInstall\n *\n * @example\n * ```typescript\n * const cleoOpts = mapCompatibilityInstallOptions(rawOpts);\n * await executeCleoInstall(\"install\", cleoOpts, \"mcp.install\");\n * ```\n *\n * @public\n */\nexport function mapCompatibilityInstallOptions(\n opts: {\n channel?: string;\n provider?: string[];\n agent?: string[];\n all?: boolean;\n global?: boolean;\n version?: string;\n command?: string;\n arg?: string[];\n env?: string[];\n cleoDir?: string;\n dryRun?: boolean;\n yes?: boolean;\n interactive?: boolean;\n json?: boolean;\n human?: boolean;\n },\n): CleoInstallOptions {\n return {\n channel: opts.channel,\n provider: [...(opts.provider ?? []), ...(opts.agent ?? [])],\n all: opts.all,\n global: opts.global,\n version: opts.version,\n command: opts.command,\n arg: opts.arg ?? [],\n env: opts.env ?? [],\n cleoDir: opts.cleoDir,\n dryRun: opts.dryRun,\n yes: opts.yes,\n interactive: opts.interactive,\n json: opts.json,\n human: opts.human,\n };\n}\n\n/**\n * Determines whether an MCP install command should be routed to the CLEO compatibility handler.\n *\n * @remarks\n * Returns true when the source argument is \"cleo\" (case-insensitive) and a non-empty channel flag is provided.\n *\n * @param source - The source argument from the mcp install command\n * @param channel - The optional channel flag value\n * @returns True if the install should be handled by the CLEO compatibility path\n *\n * @example\n * ```typescript\n * shouldUseCleoCompatibilityInstall(\"cleo\", \"stable\"); // true\n * shouldUseCleoCompatibilityInstall(\"https://example.com\", \"stable\"); // false\n * ```\n *\n * @public\n */\nexport function shouldUseCleoCompatibilityInstall(source: string, channel?: string): boolean {\n if (source.trim().toLowerCase() !== \"cleo\") return false;\n return typeof channel === \"string\" && channel.trim() !== \"\";\n}\n\n/**\n * Registers the top-level `cleo` command group with install, update, uninstall, show, and repair.\n *\n * @remarks\n * Provides `caamp cleo ...` as a top-level alternative to `caamp mcp cleo ...` for convenience.\n * Both command paths delegate to the same underlying execution functions.\n *\n * @param program - The root Commander program to attach the cleo command group to\n *\n * @example\n * ```bash\n * caamp cleo install --channel stable --all\n * caamp cleo show --human\n * caamp cleo repair --prune\n * ```\n *\n * @public\n */\nexport function registerCleoCommands(program: Command): void {\n const cleo = program\n .command(\"cleo\")\n .description(\"Manage CLEO channel profiles\");\n\n buildInstallOptions(\n cleo\n .command(\"install\")\n .description(\"Install CLEO profile by channel\"),\n ).action(async (opts: CleoInstallOptions) => {\n await executeCleoInstall(\"install\", opts, \"cleo.install\");\n });\n\n buildInstallOptions(\n cleo\n .command(\"update\")\n .description(\"Update CLEO profile by channel\"),\n ).action(async (opts: CleoInstallOptions) => {\n await executeCleoInstall(\"update\", opts, \"cleo.update\");\n });\n\n cleo\n .command(\"uninstall\")\n .description(\"Uninstall CLEO profile for a channel\")\n .requiredOption(\"--channel <channel>\", \"CLEO channel: stable|beta|dev\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Apply to all detected providers\")\n .option(\"-g, --global\", \"Use global scope\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoUninstallOptions) => {\n await executeCleoUninstall(opts, \"cleo.uninstall\");\n });\n\n cleo\n .command(\"show\")\n .description(\"Show installed CLEO channel profiles\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Inspect all detected providers\")\n .option(\"-g, --global\", \"Global scope only\")\n .option(\"-p, --project\", \"Project scope only\")\n .option(\"--channel <channel>\", \"Filter channel: stable|beta|dev\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoShowOptions) => {\n await executeCleoShow(opts, \"cleo.show\");\n });\n\n cleo\n .command(\"repair\")\n .description(\"Repair lock file by backfilling untracked CLEO entries\")\n .option(\"--provider <id>\", \"Target provider (repeatable)\", collect, [])\n .option(\"--all\", \"Scan all detected providers\")\n .option(\"-g, --global\", \"Global scope only\")\n .option(\"-p, --project\", \"Project scope only\")\n .option(\"--prune\", \"Remove orphaned lock entries not in any config\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: CleoRepairOptions) => {\n await executeCleoRepair(opts, \"cleo.repair\");\n });\n}\n\nexport { resolveCleoServerName };\n","/**\n * mcp detect command - auto-detect installed MCP tools - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { listMcpServers, resolveConfigPath } from \"../../core/mcp/reader.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\n\n/**\n * Registers the `mcp detect` subcommand for auto-detecting installed MCP tools and their configurations.\n *\n * @remarks\n * Scans all installed providers for existing MCP configuration files at both global and project\n * scopes, reporting which servers are configured for each provider.\n *\n * @param parent - The parent `mcp` Command to attach the detect subcommand to\n *\n * @example\n * ```bash\n * caamp mcp detect --human\n * caamp mcp detect --json\n * ```\n *\n * @public\n */\nexport function registerMcpDetect(parent: Command): void {\n parent\n .command(\"detect\")\n .description(\"Auto-detect installed MCP tools and their configurations\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { json?: boolean; human?: boolean }) => {\n const operation = \"mcp.detect\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const providers = getInstalledProviders();\n\n const providersResult: Array<{\n id: string;\n configsFound: number;\n servers: string[];\n }> = [];\n let totalConfigs = 0;\n\n for (const provider of providers) {\n const globalPath = resolveConfigPath(provider, \"global\");\n const projectPath = resolveConfigPath(provider, \"project\");\n\n const globalEntries = await listMcpServers(provider, \"global\");\n const projectEntries = await listMcpServers(provider, \"project\");\n\n const configsFound = \n (globalPath && existsSync(globalPath) ? 1 : 0) +\n (projectPath && existsSync(projectPath) ? 1 : 0);\n \n totalConfigs += configsFound;\n\n const allServers = [...globalEntries.map(e => e.name), ...projectEntries.map(e => e.name)];\n\n providersResult.push({\n id: provider.id,\n configsFound,\n servers: allServers,\n });\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n providers: providersResult,\n totalConfigs,\n });\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\n${providers.length} provider(s) with MCP support:\\n`));\n\n for (const provider of providersResult) {\n const globalPath = resolveConfigPath(providers.find(p => p.id === provider.id)!, \"global\");\n const projectPath = resolveConfigPath(providers.find(p => p.id === provider.id)!, \"project\");\n \n const hasGlobal = globalPath && existsSync(globalPath);\n const hasProject = projectPath && existsSync(projectPath);\n \n const globalIcon = hasGlobal ? pc.green(\"G\") : pc.dim(\"-\");\n const projectIcon = hasProject ? pc.green(\"P\") : pc.dim(\"-\");\n const serverList = provider.servers.length > 0 ? pc.dim(provider.servers.join(\", \")) : pc.dim(\"no servers\");\n\n console.log(` [${globalIcon}${projectIcon}] ${pc.bold(provider.id.padEnd(20))} ${serverList}`);\n }\n\n console.log(pc.dim(\"\\nG = global config, P = project config\"));\n console.log();\n });\n}\n","/**\n * mcp install command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { buildServerConfig, installMcpServerToAll } from \"../../core/mcp/installer.js\";\nimport { recordMcpInstall } from \"../../core/mcp/lock.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport { parseSource } from \"../../core/sources/parser.js\";\nimport type { Provider } from \"../../types.js\";\nimport {\n executeCleoInstall,\n mapCompatibilityInstallOptions,\n shouldUseCleoCompatibilityInstall,\n} from \"./cleo.js\";\n\n/**\n * Registers the `mcp install` subcommand for installing MCP servers to agent configurations.\n *\n * @remarks\n * Supports URL, npm package, and command sources with per-agent transforms. Automatically\n * delegates to CLEO compatibility install when the source is \"cleo\" with a channel flag.\n * Records installations in the lock file for tracking.\n *\n * @param parent - The parent `mcp` Command to attach the install subcommand to\n *\n * @example\n * ```bash\n * caamp mcp install https://example.com/server --agent claude-code\n * caamp mcp install my-server --all --global\n * ```\n *\n * @public\n */\nexport function registerMcpInstall(parent: Command): void {\n parent\n .command(\"install\")\n .description(\"Install MCP server to agent configs\")\n .argument(\"<source>\", \"MCP server source (URL, npm package, or command)\")\n .option(\"-a, --agent <name>\", \"Target specific agent(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--provider <id>\", \"Target provider ID (alias for --agent)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-g, --global\", \"Install to global/user config\")\n .option(\"-n, --name <name>\", \"Override inferred server name\")\n .option(\"--channel <channel>\", \"Managed channel profile (stable|beta|dev)\")\n .option(\"--version <tag>\", \"Managed profile tag/version for stable or beta\")\n .option(\"--command <command>\", \"Managed dev profile command\")\n .option(\"--arg <arg>\", \"Managed dev command arg (repeatable)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--env <kv>\", \"Managed env assignment KEY=value (repeatable)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--cleo-dir <path>\", \"Managed dev CLEO_DIR override\")\n .option(\"-t, --transport <type>\", \"Transport type: http (default) or sse\", \"http\")\n .option(\"--header <header>\", \"HTTP header (Key: Value)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--all\", \"Install to all detected agents\")\n .option(\"--interactive\", \"Guided interactive setup for managed profiles\")\n .option(\"--dry-run\", \"Preview without writing\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (source: string, opts: {\n agent: string[];\n provider: string[];\n global?: boolean;\n name?: string;\n channel?: string;\n version?: string;\n command?: string;\n arg: string[];\n env: string[];\n cleoDir?: string;\n transport: string;\n header: string[];\n yes?: boolean;\n all?: boolean;\n interactive?: boolean;\n dryRun?: boolean;\n json?: boolean;\n human?: boolean;\n }) => {\n const operation = \"mcp.install\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n if (shouldUseCleoCompatibilityInstall(source, opts.channel)) {\n const cleoOpts = mapCompatibilityInstallOptions(opts);\n await executeCleoInstall(\"install\", cleoOpts, operation);\n return;\n }\n\n const parsed = parseSource(source);\n const serverName = opts.name ?? parsed.inferredName;\n\n // Parse headers\n const headers: Record<string, string> = {};\n for (const h of opts.header) {\n const idx = h.indexOf(\":\");\n if (idx > 0) {\n headers[h.slice(0, idx).trim()] = h.slice(idx + 1).trim();\n }\n }\n\n const config = buildServerConfig(parsed, opts.transport, headers);\n\n // Determine target providers\n let providers: Provider[];\n\n if (opts.all) {\n providers = getInstalledProviders();\n } else if (opts.agent.length > 0) {\n providers = opts.agent\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else if (opts.provider.length > 0) {\n providers = opts.provider\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else {\n providers = getInstalledProviders();\n }\n\n if (providers.length === 0) {\n const message = \"No target providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n\n if (opts.dryRun) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n installed: [{\n name: serverName,\n providers: providers.map((p) => p.id),\n config,\n }],\n dryRun: true,\n });\n } else {\n console.log(pc.bold(\"Dry run - would install:\"));\n console.log(` Server: ${pc.bold(serverName)}`);\n console.log(` Config: ${JSON.stringify(config, null, 2)}`);\n console.log(` Scope: ${scope}`);\n console.log(` Providers: ${providers.map((p) => p.id).join(\", \")}`);\n }\n return;\n }\n\n if (format === \"human\") {\n console.log(pc.dim(`Installing \"${serverName}\" to ${providers.length} provider(s)...\\n`));\n }\n\n const results = await installMcpServerToAll(\n providers,\n serverName,\n config,\n scope,\n );\n\n const succeeded = results.filter((r) => r.success);\n const failed = results.filter((r) => !r.success);\n\n if (format === \"human\") {\n for (const r of results) {\n if (r.success) {\n console.log(` ${pc.green(\"✓\")} ${r.provider.toolName.padEnd(22)} ${pc.dim(r.configPath)}`);\n } else {\n console.log(` ${pc.red(\"✗\")} ${r.provider.toolName.padEnd(22)} ${pc.red(r.error ?? \"failed\")}`);\n }\n }\n }\n\n if (succeeded.length > 0) {\n await recordMcpInstall(\n serverName,\n source,\n parsed.type,\n succeeded.map((r) => r.provider.id),\n opts.global ?? false,\n );\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n installed: succeeded.map((r) => ({\n name: serverName,\n providers: [r.provider.id],\n config,\n })),\n dryRun: false,\n });\n } else {\n console.log(pc.bold(`\\n${succeeded.length}/${results.length} providers configured.`));\n }\n });\n}\n","/**\n * mcp list command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { listMcpServers } from \"../../core/mcp/reader.js\";\nimport { resolvePreferredConfigScope } from \"../../core/paths/standard.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport type { McpServerEntry } from \"../../types.js\";\n\n/**\n * Registers the `mcp list` subcommand for listing configured MCP servers across providers.\n *\n * @remarks\n * Queries installed provider configurations and lists all MCP server entries with scope indicators.\n * Supports filtering by specific agent and global/project scope.\n *\n * @param parent - The parent `mcp` Command to attach the list subcommand to\n *\n * @example\n * ```bash\n * caamp mcp list --agent claude-code\n * caamp mcp list --global --human\n * ```\n *\n * @public\n */\nexport function registerMcpList(parent: Command): void {\n parent\n .command(\"list\")\n .description(\"List configured MCP servers\")\n .option(\"-a, --agent <name>\", \"List for specific agent\")\n .option(\"--provider <id>\", \"Provider ID alias for --agent\")\n .option(\"-g, --global\", \"List global config\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { agent?: string; provider?: string; global?: boolean; json?: boolean; human?: boolean }) => {\n const operation = \"mcp.list\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const selectedProvider = opts.provider ?? opts.agent;\n\n const providers = selectedProvider\n ? [getProvider(selectedProvider)].filter((p): p is NonNullable<typeof p> => p !== undefined)\n : getInstalledProviders();\n\n if (selectedProvider && providers.length === 0) {\n const message = `Provider not found: ${selectedProvider}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n provider: selectedProvider,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const allEntries: Array<{\n name: string;\n command?: string;\n scope: \"global\" | \"project\";\n }> = [];\n\n for (const provider of providers) {\n const scope = resolvePreferredConfigScope(provider, opts.global);\n\n const entries = await listMcpServers(provider, scope);\n for (const entry of entries) {\n allEntries.push({\n name: entry.name,\n command: typeof entry.config.command === \"string\" ? entry.config.command : undefined,\n scope,\n });\n }\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n servers: allEntries,\n count: allEntries.length,\n scope: opts.global ? \"global\" : selectedProvider ? `agent:${selectedProvider}` : \"project\",\n });\n return;\n }\n\n // Human-readable output\n if (allEntries.length === 0) {\n console.log(pc.dim(\"No MCP servers configured.\"));\n return;\n }\n\n console.log(pc.bold(`\\n${allEntries.length} MCP server(s) configured:\\n`));\n\n for (const entry of allEntries) {\n const scopeIndicator = entry.scope === \"global\" ? pc.dim(\"[G] \") : pc.dim(\"[P] \");\n console.log(` ${scopeIndicator}${pc.bold(entry.name.padEnd(25))} ${entry.command ? pc.dim(entry.command) : \"\"}`);\n }\n\n console.log();\n console.log(pc.dim(\"G = global config, P = project config\"));\n console.log();\n });\n}\n","/**\n * mcp remove command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { removeMcpFromLock } from \"../../core/mcp/lock.js\";\nimport { removeMcpServer } from \"../../core/mcp/reader.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport type { Provider } from \"../../types.js\";\n\n/**\n * Registers the `mcp remove` subcommand for removing MCP servers from agent configurations.\n *\n * @remarks\n * Removes the named MCP server from targeted provider configs and cleans up the lock file entry.\n * Supports targeting specific agents or all detected providers.\n *\n * @param parent - The parent `mcp` Command to attach the remove subcommand to\n *\n * @example\n * ```bash\n * caamp mcp remove my-server --agent claude-code\n * caamp mcp remove my-server --all --global\n * ```\n *\n * @public\n */\nexport function registerMcpRemove(parent: Command): void {\n parent\n .command(\"remove\")\n .description(\"Remove MCP server from agent configs\")\n .argument(\"<name>\", \"MCP server name to remove\")\n .option(\"-a, --agent <name>\", \"Target specific agent(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"--provider <id>\", \"Target provider ID (alias for --agent)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-g, --global\", \"Remove from global config\")\n .option(\"--all\", \"Remove from all detected agents\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string, opts: {\n agent: string[];\n provider: string[];\n global?: boolean;\n all?: boolean;\n json?: boolean;\n human?: boolean;\n }) => {\n const operation = \"mcp.remove\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n let providers: Provider[];\n\n if (opts.all) {\n providers = getInstalledProviders();\n } else if (opts.agent.length > 0) {\n providers = opts.agent\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else if (opts.provider.length > 0) {\n providers = opts.provider\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else {\n providers = getInstalledProviders();\n }\n\n if (providers.length === 0) {\n const message = \"No target providers found.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n const scope = opts.global ? \"global\" as const : \"project\" as const;\n const removed: string[] = [];\n const notFound: string[] = [];\n\n for (const provider of providers) {\n const success = await removeMcpServer(provider, name, scope);\n if (success) {\n removed.push(provider.id);\n if (format === \"human\") {\n console.log(` ${pc.green(\"✓\")} Removed from ${provider.toolName}`);\n }\n } else {\n notFound.push(provider.id);\n }\n }\n\n if (removed.length > 0) {\n await removeMcpFromLock(name);\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n removed,\n providers: removed,\n notFound: notFound.length > 0 ? notFound : undefined,\n });\n } else {\n if (removed.length > 0) {\n console.log(pc.green(`\\n✓ Removed \"${name}\" from ${removed.length} provider(s).`));\n } else {\n console.log(pc.yellow(`Server \"${name}\" not found in any provider config.`));\n }\n }\n });\n}\n","/**\n * MCP server management command group for installing, removing, listing, and detecting MCP server configurations across AI agent providers.\n *\n * @packageDocumentation\n */\n\nimport type { Command } from \"commander\";\nimport { registerMcpCleoCommands, registerMcpCleoCompatibilityCommands } from \"./cleo.js\";\nimport { registerMcpDetect } from \"./detect.js\";\nimport { registerMcpInstall } from \"./install.js\";\nimport { registerMcpList } from \"./list.js\";\nimport { registerMcpRemove } from \"./remove.js\";\n\n/**\n * Registers the `mcp` command group with install, remove, list, detect, and cleo subcommands.\n *\n * @remarks\n * Orchestrates registration of all MCP-related subcommands under a unified `mcp` parent command.\n * Includes both direct MCP operations and CLEO channel profile management.\n *\n * @param program - The root Commander program to attach the mcp command group to\n *\n * @example\n * ```bash\n * caamp mcp install https://example.com/server --agent claude-code\n * caamp mcp list --global\n * ```\n *\n * @public\n */\nexport function registerMcpCommands(program: Command): void {\n const mcp = program\n .command(\"mcp\")\n .description(\"Manage MCP server configurations\");\n\n registerMcpInstall(mcp);\n registerMcpRemove(mcp);\n registerMcpList(mcp);\n registerMcpDetect(mcp);\n registerMcpCleoCommands(mcp);\n registerMcpCleoCompatibilityCommands(mcp);\n}\n","/**\n * providers list|detect|show commands - LAFS-compliant with JSON-first output\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { LAFSErrorCategory } from \"@cleocode/lafs\";\nimport { resolveOutputFormat } from \"@cleocode/lafs\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { isHuman } from \"../core/logger.js\";\nimport {\n CANONICAL_HOOK_EVENTS,\n buildHookMatrix,\n getCommonEvents,\n getHookMappingsVersion,\n getHookSupport,\n getProviderSummary,\n getSupportedEvents,\n toNative,\n translateToAll,\n} from \"../core/hooks/index.js\";\nimport type { CanonicalHookEvent } from \"../core/hooks/types.js\";\nimport { detectAllProviders, detectProjectProviders } from \"../core/registry/detection.js\";\nimport {\n buildSkillsMap,\n getAllProviders,\n getCommonHookEvents,\n getProvider,\n getProviderCount,\n getProvidersByHookEvent,\n getProvidersByPriority,\n getRegistryVersion,\n providerSupports,\n} from \"../core/registry/providers.js\";\nimport type { HookEvent } from \"../core/registry/types.js\";\n\ninterface LAFSErrorShape {\n code: string;\n message: string;\n category: LAFSErrorCategory;\n retryable: boolean;\n retryAfterMs: number | null;\n details: Record<string, unknown>;\n}\n\n/**\n * Registers the `providers` command group with list, detect, show, skills-map, hooks, and capabilities subcommands.\n *\n * @remarks\n * All subcommands support both JSON (default) and human-readable output formats via LAFS-compliant envelopes.\n * The providers command group is the primary interface for querying the provider registry.\n *\n * @param program - The root Commander program to attach the providers command group to\n *\n * @example\n * ```bash\n * caamp providers list --tier high\n * caamp providers detect --project\n * caamp providers show claude-code\n * ```\n *\n * @public\n */\nexport function registerProvidersCommand(program: Command): void {\n const providers = program\n .command(\"providers\")\n .description(\"Manage AI agent providers\");\n\n providers\n .command(\"list\")\n .description(\"List all supported providers\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--tier <tier>\", \"Filter by priority tier (high, medium, low)\")\n .action(async (opts: { json?: boolean; human?: boolean; tier?: string }) => {\n const operation = \"providers.list\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n const all = opts.tier\n ? getProvidersByPriority(opts.tier as \"high\" | \"medium\" | \"low\")\n : getAllProviders();\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n providers: all,\n count: all.length,\n version: getRegistryVersion(),\n tier: opts.tier || null,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\nCAMP Provider Registry v${getRegistryVersion()}`));\n console.log(pc.dim(`${getProviderCount()} providers\\n`));\n\n // Group by priority\n const tiers = [\"high\", \"medium\", \"low\"] as const;\n for (const tier of tiers) {\n const tierProviders = all.filter((p) => p.priority === tier);\n if (tierProviders.length === 0) continue;\n\n const tierLabel = tier === \"high\" ? pc.green(\"HIGH\") : tier === \"medium\" ? pc.yellow(\"MEDIUM\") : pc.dim(\"LOW\");\n console.log(`${tierLabel} priority:`);\n\n for (const p of tierProviders) {\n const status = p.status === \"active\"\n ? pc.green(\"active\")\n : p.status === \"beta\"\n ? pc.yellow(\"beta\")\n : pc.dim(p.status);\n\n console.log(` ${pc.bold(p.agentFlag.padEnd(20))} ${p.toolName.padEnd(22)} ${p.vendor.padEnd(16)} [${status}]`);\n }\n console.log();\n }\n });\n\n providers\n .command(\"detect\")\n .description(\"Auto-detect installed providers\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--project\", \"Include project-level detection\")\n .action(async (opts: { json?: boolean; human?: boolean; project?: boolean }) => {\n const operation = \"providers.detect\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n const results = opts.project\n ? detectProjectProviders(process.cwd())\n : detectAllProviders();\n\n const installed = results.filter((r) => r.installed);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n installed: installed.map((r) => ({\n id: r.provider.id,\n toolName: r.provider.toolName,\n methods: r.methods,\n projectDetected: r.projectDetected,\n })),\n notInstalled: results.filter((r) => !r.installed).map((r) => r.provider.id),\n count: {\n installed: installed.length,\n total: results.length,\n },\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\nDetected ${installed.length} installed providers:\\n`));\n\n for (const r of installed) {\n const methods = r.methods.join(\", \");\n const project = r.projectDetected ? pc.green(\" [project]\") : \"\";\n console.log(` ${pc.green(\"✓\")} ${pc.bold(r.provider.toolName.padEnd(22))} via ${pc.dim(methods)}${project}`);\n }\n\n const notInstalled = results.filter((r) => !r.installed);\n if (notInstalled.length > 0) {\n console.log(pc.dim(`\\n ${notInstalled.length} providers not detected`));\n }\n\n console.log();\n });\n\n providers\n .command(\"show\")\n .description(\"Show provider details\")\n .argument(\"<id>\", \"Provider ID or alias\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (id: string, opts: { json?: boolean; human?: boolean }) => {\n const operation = \"providers.show\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n const provider = getProvider(id);\n\n if (!provider) {\n const message = `Provider not found: ${id}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_PROVIDER_NOT_FOUND\", message, \"NOT_FOUND\", {\n id,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n provider,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(`\\n${provider.toolName}`));\n console.log(pc.dim(`by ${provider.vendor}\\n`));\n\n console.log(` ID: ${provider.id}`);\n console.log(` Flag: --agent ${provider.agentFlag}`);\n if (provider.aliases.length > 0) {\n console.log(` Aliases: ${provider.aliases.join(\", \")}`);\n }\n console.log(` Status: ${provider.status}`);\n console.log(` Priority: ${provider.priority}`);\n console.log();\n console.log(` Instruction: ${provider.instructFile}`);\n console.log(` Config format: ${provider.configFormat}`);\n console.log(` Config key: ${provider.configKey}`);\n console.log(` Transports: ${provider.supportedTransports.join(\", \")}`);\n console.log(` Headers: ${provider.supportsHeaders ? \"yes\" : \"no\"}`);\n console.log();\n console.log(pc.dim(\" Paths:\"));\n console.log(` Global dir: ${provider.pathGlobal}`);\n console.log(` Project dir: ${provider.pathProject || \"(none)\"}`);\n console.log(` Global config: ${provider.configPathGlobal}`);\n console.log(` Project config: ${provider.configPathProject || \"(none)\"}`);\n console.log(` Global skills: ${provider.pathSkills}`);\n console.log(` Project skills: ${provider.pathProjectSkills || \"(none)\"}`);\n console.log();\n });\n\n providers\n .command(\"skills-map\")\n .description(\"Show skills path map for all providers\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--provider <id>\", \"Filter to a specific provider\")\n .action(async (opts: { json?: boolean; human?: boolean; provider?: string }) => {\n const operation = \"providers.skills-map\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n let map = buildSkillsMap();\n\n if (opts.provider) {\n map = map.filter((entry) => entry.providerId === opts.provider);\n if (map.length === 0) {\n const message = `Provider not found: ${opts.provider}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_PROVIDER_NOT_FOUND\", message, \"NOT_FOUND\", {\n id: opts.provider,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n }\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n skillsMap: map,\n count: map.length,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(\"\\nProvider Skills Map\\n\"));\n\n // Table header\n console.log(\n ` ${pc.bold(\"Provider\".padEnd(22))} ${pc.bold(\"Precedence\".padEnd(30))} ${pc.bold(\"Global Path\".padEnd(40))} ${pc.bold(\"Project Path\")}`,\n );\n console.log(` ${\"─\".repeat(22)} ${\"─\".repeat(30)} ${\"─\".repeat(40)} ${\"─\".repeat(30)}`);\n\n for (const entry of map) {\n console.log(\n ` ${entry.toolName.padEnd(22)} ${entry.precedence.padEnd(30)} ${(entry.paths.global ?? \"-\").padEnd(40)} ${entry.paths.project ?? \"-\"}`,\n );\n }\n\n console.log(pc.dim(`\\n ${map.length} providers shown`));\n console.log();\n });\n\n // ── hooks subcommand group ─────────────────────────────────────────\n const hooks = providers\n .command(\"hooks\")\n .description(\"Show provider hook event support\");\n\n // hooks list (default)\n hooks\n .command(\"list\", { isDefault: true })\n .description(\"Show all providers with their hook support summary\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { json?: boolean; human?: boolean }) => {\n const operation = \"providers.hooks.list\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n const all = getAllProviders();\n const summaries = all\n .map((p) => getProviderSummary(p.id))\n .filter((s) => s !== undefined);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n mappingsVersion: getHookMappingsVersion(),\n canonicalEventCount: CANONICAL_HOOK_EVENTS.length,\n providers: summaries,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n console.log(pc.bold(`\\nCAMP Hook Support (mappings v${getHookMappingsVersion()})\\n`));\n console.log(pc.dim(` ${CANONICAL_HOOK_EVENTS.length} canonical events defined\\n`));\n\n // Table header\n console.log(\n ` ${pc.bold(\"Provider\".padEnd(22))} ${pc.bold(\"System\".padEnd(10))} ${pc.bold(\"Coverage\".padEnd(12))} ${pc.bold(\"Supported\".padEnd(12))} ${pc.bold(\"Provider-Only\")}`,\n );\n console.log(` ${\"─\".repeat(22)} ${\"─\".repeat(10)} ${\"─\".repeat(12)} ${\"─\".repeat(12)} ${\"─\".repeat(20)}`);\n\n for (const s of summaries) {\n if (!s) continue;\n const system = s.hookSystem === \"none\"\n ? pc.dim(\"none\")\n : s.experimental\n ? pc.yellow(s.hookSystem + \"*\")\n : pc.green(s.hookSystem);\n const coverage = s.coverage > 0\n ? (s.coverage >= 75 ? pc.green : s.coverage >= 40 ? pc.yellow : pc.dim)(`${s.coverage}%`)\n : pc.dim(\"0%\");\n const supported = s.supportedCount > 0\n ? `${s.supportedCount}/${s.totalCanonical}`\n : pc.dim(\"0\");\n const provOnly = s.providerOnly.length > 0 ? String(s.providerOnly.length) : pc.dim(\"-\");\n\n const provider = getProvider(s.providerId);\n const name = provider?.toolName ?? s.providerId;\n\n console.log(\n ` ${name.padEnd(22)} ${system.padEnd(20)} ${coverage.padEnd(22)} ${supported.padEnd(22)} ${provOnly}`,\n );\n }\n\n const withHooks = summaries.filter((s) => s && s.supportedCount > 0);\n console.log(pc.dim(`\\n ${withHooks.length} providers with hook support, ${summaries.length - withHooks.length} without`));\n if (summaries.some((s) => s?.experimental)) {\n console.log(pc.dim(\" * = experimental hook system\"));\n }\n console.log();\n });\n\n // hooks matrix\n hooks\n .command(\"matrix\")\n .description(\"Show cross-provider hook support matrix\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--provider <ids>\", \"Comma-separated provider IDs to compare\")\n .action(async (opts: { json?: boolean; human?: boolean; provider?: string }) => {\n const operation = \"providers.hooks.matrix\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n const ids = opts.provider?.split(\",\").map((s) => s.trim());\n const matrix = buildHookMatrix(ids);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(operation, mvi, { matrix }, null);\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable matrix\n const providerNames = matrix.providers.map((id) => {\n const p = getProvider(id);\n return (p?.toolName ?? id).slice(0, 14);\n });\n\n console.log(pc.bold(\"\\nHook Support Matrix\\n\"));\n\n // Header\n const eventCol = \"CAAMP Event\".padEnd(22);\n const provCols = providerNames.map((n) => pc.bold(n.padEnd(16))).join(\"\");\n console.log(` ${pc.bold(eventCol)} ${provCols}`);\n console.log(` ${\"─\".repeat(22)} ${providerNames.map(() => \"─\".repeat(16)).join(\"\")}`);\n\n for (const event of matrix.events) {\n const cells = matrix.providers.map((id) => {\n const m = matrix.matrix[event][id];\n if (!m?.supported) return pc.dim(\"·\".padEnd(16));\n return pc.green((m.nativeName ?? \"?\").slice(0, 14).padEnd(16));\n }).join(\"\");\n\n console.log(` ${event.padEnd(22)} ${cells}`);\n }\n\n // Common events\n const commonEvents = getCommonEvents(matrix.providers);\n console.log(pc.dim(`\\n Common events: ${commonEvents.length > 0 ? commonEvents.join(\", \") : \"none\"}`));\n console.log();\n });\n\n // hooks translate\n hooks\n .command(\"translate\")\n .description(\"Translate a hook event name between CAAMP canonical and provider-native\")\n .argument(\"<event>\", \"Hook event name (canonical or native)\")\n .option(\"--to <provider>\", \"Target provider ID for canonical→native translation\")\n .option(\"--from <provider>\", \"Source provider ID for native→canonical translation\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (event: string, opts: { to?: string; from?: string; json?: boolean; human?: boolean }) => {\n const operation = \"providers.hooks.translate\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n if (opts.to) {\n // Canonical → native\n const canonical = event as CanonicalHookEvent;\n if (!CANONICAL_HOOK_EVENTS.includes(canonical)) {\n const msg = `Unknown canonical event: ${event}. Valid: ${CANONICAL_HOOK_EVENTS.join(\", \")}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_UNKNOWN_EVENT\", msg, \"VALIDATION\");\n } else {\n console.error(pc.red(msg));\n }\n process.exit(1);\n }\n\n const result = getHookSupport(canonical, opts.to);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(operation, mvi, {\n direction: \"canonical-to-native\",\n providerId: opts.to,\n ...result,\n }, null);\n console.log(JSON.stringify(envelope, null, 2));\n } else {\n if (result.supported) {\n console.log(`\\n ${pc.green(event)} → ${pc.bold(result.native!)} (${opts.to})`);\n if (result.notes) console.log(pc.dim(` Note: ${result.notes}`));\n } else {\n console.log(`\\n ${pc.red(event)} → ${pc.dim(\"not supported\")} (${opts.to})`);\n }\n console.log();\n }\n return;\n }\n\n if (opts.from) {\n // Native → canonical (import at top of file)\n const { toCanonical } = await import(\"../core/hooks/index.js\");\n const canonical = toCanonical(event, opts.from);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(operation, mvi, {\n direction: \"native-to-canonical\",\n native: event,\n providerId: opts.from,\n canonical,\n supported: canonical !== null,\n }, null);\n console.log(JSON.stringify(envelope, null, 2));\n } else {\n if (canonical) {\n console.log(`\\n ${pc.bold(event)} (${opts.from}) → ${pc.green(canonical)}`);\n } else {\n console.log(`\\n ${pc.bold(event)} (${opts.from}) → ${pc.dim(\"no canonical mapping (provider-only event)\")}`);\n }\n console.log();\n }\n return;\n }\n\n // No --to or --from: translate canonical event to all providers\n const canonical = event as CanonicalHookEvent;\n if (!CANONICAL_HOOK_EVENTS.includes(canonical)) {\n const msg = `Unknown canonical event: ${event}. Use --from <provider> for native names, or valid canonical: ${CANONICAL_HOOK_EVENTS.join(\", \")}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_UNKNOWN_EVENT\", msg, \"VALIDATION\");\n } else {\n console.error(pc.red(msg));\n }\n process.exit(1);\n }\n\n const { getMappedProviderIds } = await import(\"../core/hooks/index.js\");\n const allIds = getMappedProviderIds();\n const translations = translateToAll(canonical, allIds);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(operation, mvi, {\n direction: \"canonical-to-all\",\n canonical: event,\n translations,\n supportedCount: Object.keys(translations).length,\n totalProviders: allIds.length,\n }, null);\n console.log(JSON.stringify(envelope, null, 2));\n } else {\n console.log(pc.bold(`\\n ${event} across providers:\\n`));\n for (const id of allIds) {\n const native = translations[id];\n const provider = getProvider(id);\n const name = (provider?.toolName ?? id).padEnd(22);\n if (native) {\n console.log(` ${pc.green(\"✓\")} ${name} ${pc.bold(native)}`);\n } else {\n console.log(` ${pc.dim(\"·\")} ${name} ${pc.dim(\"not supported\")}`);\n }\n }\n console.log();\n }\n });\n\n providers\n .command(\"capabilities\")\n .description(\"Show provider capability matrix\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .option(\"--filter <path>\", \"Filter to providers supporting a capability dot-path (e.g. spawn.supportsSubagents)\")\n .action(async (opts: { json?: boolean; human?: boolean; filter?: string }) => {\n const operation = \"providers.capabilities\";\n const mvi: import(\"../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n let all = getAllProviders();\n\n if (opts.filter) {\n all = all.filter((p) => providerSupports(p, opts.filter!));\n }\n\n const matrix = all.map((p) => ({\n id: p.id,\n toolName: p.toolName,\n skillsPrecedence: p.capabilities.skills.precedence,\n hooksCount: p.capabilities.hooks.supported.length,\n spawnMechanism: p.capabilities.spawn.spawnMechanism,\n spawnFlags: {\n supportsSubagents: p.capabilities.spawn.supportsSubagents,\n supportsProgrammaticSpawn: p.capabilities.spawn.supportsProgrammaticSpawn,\n supportsInterAgentComms: p.capabilities.spawn.supportsInterAgentComms,\n supportsParallelSpawn: p.capabilities.spawn.supportsParallelSpawn,\n },\n }));\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n capabilities: matrix,\n count: matrix.length,\n filter: opts.filter || null,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(\"\\nProvider Capability Matrix\\n\"));\n\n if (opts.filter) {\n console.log(pc.dim(` Filter: ${opts.filter}\\n`));\n }\n\n // Table header\n console.log(\n ` ${pc.bold(\"Provider\".padEnd(22))} ${pc.bold(\"Skills Precedence\".padEnd(20))} ${pc.bold(\"Hooks\".padEnd(8))} ${pc.bold(\"Spawn\")}`,\n );\n console.log(` ${\"─\".repeat(22)} ${\"─\".repeat(20)} ${\"─\".repeat(8)} ${\"─\".repeat(20)}`);\n\n for (const row of matrix) {\n const hooks = row.hooksCount > 0 ? String(row.hooksCount) : \"-\";\n const spawn = row.spawnMechanism ?? \"-\";\n console.log(\n ` ${row.toolName.padEnd(22)} ${row.skillsPrecedence.padEnd(20)} ${hooks.padEnd(8)} ${spawn}`,\n );\n }\n\n console.log(pc.dim(`\\n ${matrix.length} providers shown`));\n console.log();\n });\n}\n\nfunction buildEnvelope<T>(\n operation: string,\n mvi: import(\"../core/lafs.js\").MVILevel,\n result: T | null,\n error: LAFSErrorShape | null,\n) {\n return {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\" as const,\n _meta: {\n specVersion: \"1.0.0\",\n schemaVersion: \"1.0.0\",\n timestamp: new Date().toISOString(),\n operation,\n requestId: randomUUID(),\n transport: \"cli\" as const,\n strict: true,\n mvi,\n contextVersion: 0,\n },\n success: error === null,\n result,\n error,\n page: null,\n };\n}\n\nfunction emitJsonError(\n operation: string,\n mvi: import(\"../core/lafs.js\").MVILevel,\n code: string,\n message: string,\n category: LAFSErrorCategory,\n details: Record<string, unknown> = {},\n): void {\n const envelope = buildEnvelope(operation, mvi, null, {\n code,\n message,\n category,\n retryable: false,\n retryAfterMs: null,\n details,\n });\n console.error(JSON.stringify(envelope, null, 2));\n}\n","/**\n * skills install command - LAFS-compliant with JSON-first output\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport type { LAFSErrorCategory } from \"@cleocode/lafs\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitError,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n type MVILevel,\n} from \"../../core/lafs.js\";\nimport { MarketplaceClient } from \"../../core/marketplace/client.js\";\nimport type { MarketplaceResult } from \"../../core/marketplace/types.js\";\nimport { formatNetworkError } from \"../../core/network/fetch.js\";\nimport { buildSkillSubPathCandidates } from \"../../core/paths/standard.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport * as catalog from \"../../core/skills/catalog.js\";\nimport { discoverSkill } from \"../../core/skills/discovery.js\";\nimport { installSkill } from \"../../core/skills/installer.js\";\nimport { recordSkillInstall } from \"../../core/skills/lock.js\";\nimport { cloneRepo } from \"../../core/sources/github.js\";\nimport { cloneGitLabRepo } from \"../../core/sources/gitlab.js\";\nimport { isMarketplaceScoped, parseSource } from \"../../core/sources/parser.js\";\nimport type { Provider, SourceType } from \"../../types.js\";\n\ninterface InstallResultItem {\n name: string;\n scopedName: string;\n canonicalPath: string;\n providers: string[];\n}\n\ninterface FailedResultItem {\n name: string;\n error: string;\n}\n\ninterface InstallSummary {\n installed: InstallResultItem[];\n failed: FailedResultItem[];\n count: {\n installed: number;\n failed: number;\n total: number;\n };\n}\n\n/**\n * Registers the `skills install` subcommand for installing skills from various sources.\n *\n * @remarks\n * Supports GitHub URLs, owner/repo shorthand, marketplace scoped names, and skill library profiles.\n * Uses the canonical+symlink model to store skills once and symlink to each targeted agent.\n *\n * @param parent - The parent `skills` Command to attach the install subcommand to\n *\n * @example\n * ```bash\n * caamp skills install owner/repo\n * caamp skills install @author/skill-name --agent claude-code\n * caamp skills install --profile recommended --all\n * ```\n *\n * @public\n */\nexport function registerSkillsInstall(parent: Command): void {\n parent\n .command(\"install\")\n .description(\"Install a skill from GitHub, URL, marketplace, or registered skill library\")\n .argument(\"[source]\", \"Skill source (GitHub URL, owner/repo, @author/name, skill-name)\")\n .option(\"-a, --agent <name>\", \"Target specific agent(s)\", (v, prev: string[]) => [...prev, v], [])\n .option(\"-g, --global\", \"Install globally\")\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--all\", \"Install to all detected agents\")\n .option(\"--profile <name>\", \"Install a skill library profile (minimal, core, recommended, full)\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (source: string | undefined, opts: {\n agent: string[];\n global?: boolean;\n yes?: boolean;\n all?: boolean;\n profile?: string;\n json?: boolean;\n human?: boolean;\n }) => {\n const operation = \"skills.install\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: opts.human ?? false,\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n // Determine target providers\n let providers: Provider[];\n\n if (opts.all) {\n providers = getInstalledProviders();\n } else if (opts.agent.length > 0) {\n providers = opts.agent\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n } else {\n providers = getInstalledProviders();\n }\n\n if (providers.length === 0) {\n const message = \"No target providers found. Use --agent or --all.\";\n if (format === \"json\") {\n emitError(operation, mvi, ErrorCodes.PROVIDER_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n\n // Handle --profile: install an entire skill library profile\n if (opts.profile) {\n await handleProfileInstall(opts.profile, providers, opts.global ?? false, format, operation, mvi);\n return;\n }\n\n // Require source when not using --profile\n if (!source) {\n const message = \"Missing required argument: source\";\n if (format === \"json\") {\n emitError(operation, mvi, ErrorCodes.INVALID_INPUT, message, ErrorCategories.VALIDATION);\n }\n console.error(pc.red(message));\n console.log(pc.dim(\"Usage: caamp skills install <source> or caamp skills install --profile <name>\"));\n process.exit(1);\n }\n\n if (format === \"human\") {\n console.log(pc.dim(`Installing to ${providers.length} provider(s)...`));\n }\n\n let localPath: string | undefined;\n let cleanup: (() => Promise<void>) | undefined;\n let skillName: string;\n let sourceValue: string;\n let sourceType: SourceType;\n\n // Handle marketplace scoped names\n if (isMarketplaceScoped(source)) {\n const sourceResult = await handleMarketplaceSource(\n source,\n providers,\n opts.global ?? false,\n format,\n operation,\n mvi,\n );\n\n if (sourceResult.success) {\n localPath = sourceResult.localPath;\n cleanup = sourceResult.cleanup;\n skillName = sourceResult.skillName;\n sourceValue = sourceResult.sourceValue;\n sourceType = sourceResult.sourceType;\n } else {\n process.exit(1);\n }\n } else {\n // Parse source\n const parsed = parseSource(source);\n skillName = parsed.inferredName;\n sourceValue = parsed.value;\n sourceType = parsed.type;\n\n if (parsed.type === \"github\" && parsed.owner && parsed.repo) {\n try {\n const result = await cloneRepo(parsed.owner, parsed.repo, parsed.ref, parsed.path);\n localPath = result.localPath;\n cleanup = result.cleanup;\n } catch (error) {\n const message = `Failed to clone GitHub repository: ${formatNetworkError(error)}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.NETWORK_ERROR, message, ErrorCategories.TRANSIENT);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n } else if (parsed.type === \"gitlab\" && parsed.owner && parsed.repo) {\n try {\n const result = await cloneGitLabRepo(parsed.owner, parsed.repo, parsed.ref, parsed.path);\n localPath = result.localPath;\n cleanup = result.cleanup;\n } catch (error) {\n const message = `Failed to clone GitLab repository: ${formatNetworkError(error)}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.NETWORK_ERROR, message, ErrorCategories.TRANSIENT);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n } else if (parsed.type === \"local\") {\n localPath = parsed.value;\n // Read SKILL.md for the authoritative name\n const discovered = await discoverSkill(localPath);\n if (discovered) {\n skillName = discovered.name;\n }\n } else if (parsed.type === \"package\") {\n // Check registered skill library for this skill name\n if (!catalog.isCatalogAvailable()) {\n const message = \"No skill library registered. Register one with registerSkillLibraryFromPath() or set CAAMP_SKILL_LIBRARY env var.\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.INVALID_INPUT, message, ErrorCategories.VALIDATION);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n const catalogSkill = catalog.getSkill(parsed.inferredName);\n if (catalogSkill) {\n localPath = catalog.getSkillDir(catalogSkill.name);\n skillName = catalogSkill.name;\n sourceValue = `library:${catalogSkill.name}`;\n sourceType = \"library\";\n if (format === \"human\") {\n console.log(` Found in catalog: ${pc.bold(catalogSkill.name)} v${catalogSkill.version} (${pc.dim(catalogSkill.category)})`);\n }\n } else {\n const message = `Skill not found in catalog: ${parsed.inferredName}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.SKILL_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n availableSkills: catalog.listSkills(),\n });\n }\n console.error(pc.red(message));\n console.log(pc.dim(\"Available skills: \" + catalog.listSkills().join(\", \")));\n process.exit(1);\n }\n } else {\n const message = `Unsupported source type: ${parsed.type}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.INVALID_FORMAT, message, ErrorCategories.VALIDATION);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n }\n\n try {\n if (!localPath) {\n const message = \"No local skill path resolved for installation\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.INTERNAL_ERROR, message, ErrorCategories.INTERNAL);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n\n const result = await installSkill(\n localPath,\n skillName!,\n providers,\n opts.global ?? false,\n );\n\n if (result.success) {\n // Record in lock file\n const isGlobal = (sourceType === \"library\" || sourceType === \"package\") ? true : (opts.global ?? false);\n await recordSkillInstall(\n skillName!,\n sourceValue,\n sourceValue,\n sourceType,\n result.linkedAgents,\n result.canonicalPath,\n isGlobal,\n );\n\n const installedItem: InstallResultItem = {\n name: skillName!,\n scopedName: sourceValue,\n canonicalPath: result.canonicalPath,\n providers: result.linkedAgents,\n };\n\n const summary: InstallSummary = {\n installed: [installedItem],\n failed: [],\n count: {\n installed: 1,\n failed: 0,\n total: 1,\n },\n };\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, summary);\n } else {\n console.log(pc.green(`\\n✓ Installed ${pc.bold(skillName)}`));\n console.log(` Canonical: ${pc.dim(result.canonicalPath)}`);\n console.log(` Linked to: ${result.linkedAgents.join(\", \")}`);\n\n if (result.errors.length > 0) {\n console.log(pc.yellow(\"\\nWarnings:\"));\n for (const err of result.errors) {\n console.log(` ${pc.yellow(\"!\")} ${err}`);\n }\n }\n }\n } else {\n const summary: InstallSummary = {\n installed: [],\n failed: [{\n name: skillName!,\n error: result.errors.join(\", \"),\n }],\n count: {\n installed: 0,\n failed: 1,\n total: 1,\n },\n };\n\n if (format === \"json\") {\n const envelope = buildEnvelope(operation, mvi, summary, {\n code: ErrorCodes.INSTALL_FAILED,\n message: result.errors.join(\", \"),\n category: ErrorCategories.INTERNAL,\n retryable: false,\n retryAfterMs: null,\n details: { skillName, sourceValue },\n });\n console.error(JSON.stringify(envelope, null, 2));\n } else {\n console.log(pc.yellow(`\\n✗ Failed to install ${pc.bold(skillName)}`));\n console.log(pc.yellow(\"Errors:\"));\n for (const err of result.errors) {\n console.log(` ${pc.yellow(\"!\")} ${err}`);\n }\n }\n process.exit(1);\n }\n } finally {\n if (cleanup) await cleanup();\n }\n });\n}\n\nasync function handleProfileInstall(\n profileName: string,\n providers: Provider[],\n isGlobal: boolean,\n format: \"json\" | \"human\",\n operation: string,\n mvi: MVILevel,\n): Promise<void> {\n if (!catalog.isCatalogAvailable()) {\n const message = \"No skill library registered. Register one with registerSkillLibraryFromPath() or set CAAMP_SKILL_LIBRARY env var.\";\n if (format === \"json\") {\n emitError(operation, mvi, ErrorCodes.INVALID_INPUT, message, ErrorCategories.VALIDATION);\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n\n const profileSkills = catalog.resolveProfile(profileName);\n if (profileSkills.length === 0) {\n const message = `Profile not found: ${profileName}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.SKILL_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n availableProfiles: catalog.listProfiles(),\n });\n }\n console.error(pc.red(message));\n const available = catalog.listProfiles();\n if (available.length > 0) {\n console.log(pc.dim(\"Available profiles: \" + available.join(\", \")));\n }\n process.exit(1);\n }\n\n if (format === \"human\") {\n console.log(`Installing profile ${pc.bold(profileName)} (${profileSkills.length} skill(s))...`);\n console.log(pc.dim(`Target: ${providers.length} provider(s)`));\n }\n\n const installed: InstallResultItem[] = [];\n const failed: FailedResultItem[] = [];\n\n for (const name of profileSkills) {\n const skillDir = catalog.getSkillDir(name);\n try {\n const result = await installSkill(\n skillDir,\n name,\n providers,\n isGlobal,\n );\n\n if (result.success) {\n if (format === \"human\") {\n console.log(pc.green(` + ${name}`));\n }\n await recordSkillInstall(\n name,\n `library:${name}`,\n `library:${name}`,\n \"library\",\n result.linkedAgents,\n result.canonicalPath,\n true,\n );\n installed.push({\n name,\n scopedName: `library:${name}`,\n canonicalPath: result.canonicalPath,\n providers: result.linkedAgents,\n });\n } else {\n if (format === \"human\") {\n console.log(pc.yellow(` ! ${name}: ${result.errors.join(\", \")}`));\n }\n failed.push({\n name,\n error: result.errors.join(\", \"),\n });\n }\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n if (format === \"human\") {\n console.log(pc.red(` x ${name}: ${errorMsg}`));\n }\n failed.push({\n name,\n error: errorMsg,\n });\n }\n }\n\n const summary: InstallSummary = {\n installed,\n failed,\n count: {\n installed: installed.length,\n failed: failed.length,\n total: profileSkills.length,\n },\n };\n\n if (format === \"json\") {\n if (failed.length > 0) {\n const envelope = buildEnvelope(operation, mvi, summary, {\n code: ErrorCodes.INSTALL_FAILED,\n message: `${failed.length} skill(s) failed to install`,\n category: ErrorCategories.INTERNAL,\n retryable: false,\n retryAfterMs: null,\n details: { failed: failed.map(f => f.name) },\n });\n console.error(JSON.stringify(envelope, null, 2));\n process.exit(1);\n } else {\n outputSuccess(operation, mvi, summary);\n }\n } else {\n console.log(`\\n${pc.green(`${installed.length} installed`)}, ${failed.length > 0 ? pc.yellow(`${failed.length} failed`) : \"0 failed\"}`);\n if (failed.length > 0) {\n process.exit(1);\n }\n }\n}\n\ninterface MarketplaceSourceSuccess {\n success: true;\n localPath: string;\n cleanup: () => Promise<void>;\n skillName: string;\n sourceValue: string;\n sourceType: SourceType;\n}\n\ninterface MarketplaceSourceError {\n success: false;\n}\n\ntype MarketplaceSourceResult = MarketplaceSourceSuccess | MarketplaceSourceError;\n\nasync function handleMarketplaceSource(\n source: string,\n _providers: Provider[],\n _isGlobal: boolean,\n format: \"json\" | \"human\",\n operation: string,\n mvi: MVILevel,\n): Promise<MarketplaceSourceResult> {\n if (format === \"human\") {\n console.log(pc.dim(`Searching marketplace for ${source}...`));\n }\n\n const client = new MarketplaceClient();\n let skill: import(\"../../core/marketplace/types.js\").MarketplaceResult | null;\n\n try {\n skill = await client.getSkill(source);\n } catch (error) {\n const message = `Marketplace lookup failed: ${formatNetworkError(error)}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.NETWORK_ERROR, message, ErrorCategories.TRANSIENT);\n }\n console.error(pc.red(message));\n return { success: false };\n }\n\n if (!skill) {\n const message = `Skill not found: ${source}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.SKILL_NOT_FOUND, message, ErrorCategories.NOT_FOUND);\n }\n console.error(pc.red(message));\n return { success: false };\n }\n\n if (format === \"human\") {\n console.log(` Found: ${pc.bold(skill.name)} by ${skill.author} (${pc.dim(skill.repoFullName)})`);\n }\n\n const parsed = parseSource(skill.githubUrl);\n if (parsed.type !== \"github\" || !parsed.owner || !parsed.repo) {\n const message = \"Could not resolve GitHub source\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.INVALID_FORMAT, message, ErrorCategories.VALIDATION);\n }\n console.error(pc.red(message));\n return { success: false };\n }\n\n try {\n const subPathCandidates = buildSkillSubPathCandidates(skill.path, parsed.path);\n let cloneError: unknown;\n let cloned = false;\n let localPath: string | undefined;\n let cleanup: (() => Promise<void>) | undefined;\n\n for (const subPath of subPathCandidates) {\n try {\n const result = await cloneRepo(parsed.owner, parsed.repo, parsed.ref, subPath);\n if (subPath && !existsSync(result.localPath)) {\n await result.cleanup();\n continue;\n }\n localPath = result.localPath;\n cleanup = result.cleanup;\n cloned = true;\n break;\n } catch (error) {\n cloneError = error;\n }\n }\n\n if (!cloned) {\n throw cloneError ?? new Error(\"Unable to resolve skill path from marketplace metadata\");\n }\n\n return {\n success: true,\n localPath: localPath!,\n cleanup: cleanup!,\n skillName: skill.name,\n sourceValue: skill.githubUrl,\n sourceType: parsed.type,\n };\n } catch (error) {\n const message = `Failed to fetch source repository: ${formatNetworkError(error)}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.NETWORK_ERROR, message, ErrorCategories.TRANSIENT);\n }\n console.error(pc.red(message));\n return { success: false };\n }\n}\n","/**\n * GitHub fetcher for skill/MCP sources\n *\n * Clones repos or fetches specific paths via simple-git.\n */\n\nimport { simpleGit } from \"simple-git\";\nimport { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { fetchWithTimeout } from \"../network/fetch.js\";\n\n/**\n * Result of fetching a Git repository to a local temporary directory.\n *\n * @public\n */\nexport interface GitFetchResult {\n /** Absolute path to the fetched content on disk. */\n localPath: string;\n /** Cleanup function that removes the temporary directory. */\n cleanup: () => Promise<void>;\n}\n\n/**\n * Clone a GitHub repo to a temp directory.\n *\n * @remarks\n * Performs a shallow clone (`--depth 1`) to minimize download size. If a\n * `subPath` is provided, the returned `localPath` points to that subdirectory\n * within the cloned repository.\n *\n * @param owner - GitHub repository owner (user or organization)\n * @param repo - GitHub repository name\n * @param ref - Branch or tag to clone (defaults to the repo's default branch)\n * @param subPath - Subdirectory within the repo to target\n * @returns Object with local path and cleanup function\n *\n * @example\n * ```typescript\n * const { localPath, cleanup } = await cloneRepo(\"anthropics\", \"courses\", \"main\", \"skills\");\n * try {\n * console.log(`Cloned to: ${localPath}`);\n * } finally {\n * await cleanup();\n * }\n * ```\n *\n * @public\n */\nexport async function cloneRepo(\n owner: string,\n repo: string,\n ref?: string,\n subPath?: string,\n): Promise<GitFetchResult> {\n const tmpDir = await mkdtemp(join(tmpdir(), \"caamp-\"));\n const repoUrl = `https://github.com/${owner}/${repo}.git`;\n\n const git = simpleGit();\n\n const cloneOptions = [\"--depth\", \"1\"];\n if (ref) {\n cloneOptions.push(\"--branch\", ref);\n }\n\n await git.clone(repoUrl, tmpDir, cloneOptions);\n\n const localPath = subPath ? join(tmpDir, subPath) : tmpDir;\n\n return {\n localPath,\n cleanup: async () => {\n try {\n await rm(tmpDir, { recursive: true });\n } catch {\n // Ignore cleanup errors\n }\n },\n };\n}\n\n/**\n * Fetch a specific file from GitHub using the raw API.\n *\n * @remarks\n * Uses `raw.githubusercontent.com` to fetch file content without cloning\n * the entire repository. Returns `null` on any fetch error.\n *\n * @param owner - GitHub repository owner\n * @param repo - GitHub repository name\n * @param path - File path within the repository\n * @param ref - Branch or tag to fetch from (defaults to `\"main\"`)\n * @returns File content as a string, or `null` if the file cannot be fetched\n *\n * @example\n * ```typescript\n * const content = await fetchRawFile(\"owner\", \"repo\", \"skills/my-skill/SKILL.md\");\n * if (content) {\n * console.log(content);\n * }\n * ```\n *\n * @public\n */\nexport async function fetchRawFile(\n owner: string,\n repo: string,\n path: string,\n ref = \"main\",\n): Promise<string | null> {\n const url = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${path}`;\n\n try {\n const response = await fetchWithTimeout(url);\n if (!response.ok) return null;\n return await response.text();\n } catch {\n return null;\n }\n}\n\n/**\n * Check if a GitHub repo exists.\n *\n * @remarks\n * Sends a HEAD request to the GitHub API to verify repository existence\n * without downloading content.\n *\n * @param owner - GitHub repository owner\n * @param repo - GitHub repository name\n * @returns `true` if the repository exists and is accessible\n *\n * @example\n * ```typescript\n * const exists = await repoExists(\"anthropics\", \"courses\");\n * console.log(exists ? \"Repo found\" : \"Repo not found\");\n * ```\n *\n * @public\n */\nexport async function repoExists(owner: string, repo: string): Promise<boolean> {\n try {\n const response = await fetchWithTimeout(`https://api.github.com/repos/${owner}/${repo}`, {\n method: \"HEAD\",\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n","/**\n * GitLab fetcher for skill/MCP sources\n */\n\nimport { simpleGit } from \"simple-git\";\nimport { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { GitFetchResult } from \"./github.js\";\nimport { fetchWithTimeout } from \"../network/fetch.js\";\n\n/**\n * Clone a GitLab repo to a temp directory.\n *\n * @remarks\n * Performs a shallow clone (`--depth 1`) from `gitlab.com`. If a `subPath`\n * is provided, the returned `localPath` points to that subdirectory within\n * the cloned repository.\n *\n * @param owner - GitLab repository owner (user or group)\n * @param repo - GitLab repository name\n * @param ref - Branch or tag to clone (defaults to the repo's default branch)\n * @param subPath - Subdirectory within the repo to target\n * @returns Object with local path and cleanup function\n *\n * @example\n * ```typescript\n * const { localPath, cleanup } = await cloneGitLabRepo(\"mygroup\", \"skills-repo\");\n * try {\n * console.log(`Cloned to: ${localPath}`);\n * } finally {\n * await cleanup();\n * }\n * ```\n *\n * @public\n */\nexport async function cloneGitLabRepo(\n owner: string,\n repo: string,\n ref?: string,\n subPath?: string,\n): Promise<GitFetchResult> {\n const tmpDir = await mkdtemp(join(tmpdir(), \"caamp-gl-\"));\n const repoUrl = `https://gitlab.com/${owner}/${repo}.git`;\n\n const git = simpleGit();\n\n const cloneOptions = [\"--depth\", \"1\"];\n if (ref) {\n cloneOptions.push(\"--branch\", ref);\n }\n\n await git.clone(repoUrl, tmpDir, cloneOptions);\n\n const localPath = subPath ? join(tmpDir, subPath) : tmpDir;\n\n return {\n localPath,\n cleanup: async () => {\n try {\n await rm(tmpDir, { recursive: true });\n } catch {\n // Ignore cleanup errors\n }\n },\n };\n}\n\n/**\n * Fetch a specific file from GitLab using the raw API.\n *\n * @remarks\n * Uses the GitLab raw file endpoint to fetch content without cloning.\n * The file path is URL-encoded for GitLab's API format. Returns `null`\n * on any fetch error.\n *\n * @param owner - GitLab repository owner (user or group)\n * @param repo - GitLab repository name\n * @param path - File path within the repository\n * @param ref - Branch or tag to fetch from (defaults to `\"main\"`)\n * @returns File content as a string, or `null` if the file cannot be fetched\n *\n * @example\n * ```typescript\n * const content = await fetchGitLabRawFile(\"mygroup\", \"skills\", \"my-skill/SKILL.md\");\n * if (content) {\n * console.log(content);\n * }\n * ```\n *\n * @public\n */\nexport async function fetchGitLabRawFile(\n owner: string,\n repo: string,\n path: string,\n ref = \"main\",\n): Promise<string | null> {\n const encodedPath = encodeURIComponent(path);\n const url = `https://gitlab.com/${owner}/${repo}/-/raw/${ref}/${encodedPath}`;\n\n try {\n const response = await fetchWithTimeout(url);\n if (!response.ok) return null;\n return await response.text();\n } catch {\n return null;\n }\n}\n","/**\n * skills remove command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { listCanonicalSkills, removeSkill } from \"../../core/skills/installer.js\";\nimport { removeSkillFromLock } from \"../../core/skills/lock.js\";\n\n/**\n * Registers the `skills remove` subcommand for removing installed skills.\n *\n * @remarks\n * Removes the canonical skill directory and all provider symlinks, then cleans up the lock file entry.\n * Supports interactive selection when no skill name is provided.\n *\n * @param parent - The parent `skills` Command to attach the remove subcommand to\n *\n * @example\n * ```bash\n * caamp skills remove my-skill\n * caamp skills remove --yes\n * ```\n *\n * @public\n */\nexport function registerSkillsRemove(parent: Command): void {\n parent\n .command(\"remove\")\n .description(\"Remove installed skill(s)\")\n .argument(\"[name]\", \"Skill name to remove\")\n .option(\"-g, --global\", \"Remove from global scope\")\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string | undefined, opts: { global?: boolean; yes?: boolean; json?: boolean; human?: boolean }) => {\n const operation = \"skills.remove\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const providers = getInstalledProviders();\n\n if (name) {\n const result = await removeSkill(name, providers, opts.global ?? false);\n\n const removed = result.removed;\n const count = {\n removed: removed.length,\n total: providers.length,\n };\n\n if (format === \"json\") {\n if (removed.length > 0) {\n await removeSkillFromLock(name);\n }\n\n const errors = result.errors.length > 0\n ? result.errors.map((err) => ({ message: err }))\n : undefined;\n\n outputSuccess(operation, mvi, {\n removed,\n providers: providers.map((p) => p.id),\n count,\n ...(errors && { errors }),\n });\n return;\n }\n\n // Human-readable output\n if (removed.length > 0) {\n console.log(pc.green(`✓ Removed ${pc.bold(name)} from: ${removed.join(\", \")}`));\n await removeSkillFromLock(name);\n } else {\n console.log(pc.yellow(`Skill ${name} not found in any provider.`));\n }\n\n if (result.errors.length > 0) {\n for (const err of result.errors) {\n console.log(pc.red(` ${err}`));\n }\n }\n } else {\n // Interactive mode - list and select\n const skills = await listCanonicalSkills();\n if (skills.length === 0) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n removed: [],\n providers: [],\n count: { removed: 0, total: 0 },\n });\n } else {\n console.log(pc.dim(\"No skills installed.\"));\n }\n return;\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n removed: [],\n providers: [],\n count: { removed: 0, total: 0 },\n available: skills,\n });\n return;\n }\n\n // Human-readable output\n console.log(pc.bold(\"Installed skills:\"));\n for (const s of skills) {\n console.log(` ${s}`);\n }\n console.log(pc.dim(\"\\nUse: caamp skills remove <name>\"));\n }\n });\n}\n","/**\n * skills list command - LAFS-compliant with JSON-first output\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { LAFSErrorCategory } from \"@cleocode/lafs\";\nimport { resolveOutputFormat } from \"@cleocode/lafs\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { resolveProviderSkillsDir } from \"../../core/paths/standard.js\";\nimport { getInstalledProviders } from \"../../core/registry/detection.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport { discoverSkillsMulti } from \"../../core/skills/discovery.js\";\n\ninterface SkillsListOptions {\n global?: boolean;\n agent?: string;\n json?: boolean;\n human?: boolean;\n}\n\ninterface LAFSErrorShape {\n code: string;\n message: string;\n category: LAFSErrorCategory;\n retryable: boolean;\n retryAfterMs: number | null;\n details: Record<string, unknown>;\n}\n\n/**\n * Registers the `skills list` subcommand for listing installed skills.\n *\n * @remarks\n * Discovers skills installed across provider skill directories and outputs a summary\n * grouped by provider. Supports filtering by agent and scope.\n *\n * @param parent - The parent `skills` Command to attach the list subcommand to\n *\n * @example\n * ```bash\n * caamp skills list --human\n * caamp skills list --agent claude-code --global\n * ```\n *\n * @public\n */\nexport function registerSkillsList(parent: Command): void {\n parent\n .command(\"list\")\n .description(\"List installed skills\")\n .option(\"-g, --global\", \"List global skills\")\n .option(\"-a, --agent <name>\", \"List skills for specific agent\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: SkillsListOptions) => {\n const operation = \"skills.list\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n process.exit(1);\n }\n\n let dirs: string[] = [];\n\n if (opts.agent) {\n const provider = getProvider(opts.agent);\n if (!provider) {\n const message = `Provider not found: ${opts.agent}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_PROVIDER_NOT_FOUND\", message, \"NOT_FOUND\", {\n agent: opts.agent,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n dirs = opts.global\n ? [resolveProviderSkillsDir(provider, \"global\")]\n : [resolveProviderSkillsDir(provider, \"project\")];\n } else if (opts.global) {\n const providers = getInstalledProviders();\n dirs = providers.map((p) => resolveProviderSkillsDir(p, \"global\")).filter(Boolean);\n } else {\n const providers = getInstalledProviders();\n dirs = providers\n .map((p) => resolveProviderSkillsDir(p, \"project\"))\n .filter(Boolean);\n }\n\n const skills = await discoverSkillsMulti(dirs);\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n skills,\n count: skills.length,\n scope: opts.global ? \"global\" : opts.agent ? `agent:${opts.agent}` : \"project\",\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n // Human-readable output\n if (skills.length === 0) {\n console.log(pc.dim(\"No skills found.\"));\n return;\n }\n\n console.log(pc.bold(`\\n${skills.length} skill(s) found:\\n`));\n\n skills.forEach((skill, index) => {\n const num = (index + 1).toString().padStart(2);\n console.log(` ${pc.cyan(num)}. ${pc.bold(skill.name.padEnd(30))} ${pc.dim(skill.metadata?.description ?? \"\")}`);\n });\n\n console.log(pc.dim(`\\nInstall with: caamp skills install <name>`));\n console.log(pc.dim(`Remove with: caamp skills remove <name>`));\n });\n}\n\nfunction buildEnvelope<T>(\n operation: string,\n mvi: import(\"../../core/lafs.js\").MVILevel,\n result: T | null,\n error: LAFSErrorShape | null,\n) {\n return {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\" as const,\n _meta: {\n specVersion: \"1.0.0\",\n schemaVersion: \"1.0.0\",\n timestamp: new Date().toISOString(),\n operation,\n requestId: randomUUID(),\n transport: \"cli\" as const,\n strict: true,\n mvi,\n contextVersion: 0,\n },\n success: error === null,\n result,\n error,\n page: null,\n };\n}\n\nfunction emitJsonError(\n operation: string,\n mvi: import(\"../../core/lafs.js\").MVILevel,\n code: string,\n message: string,\n category: LAFSErrorCategory,\n details: Record<string, unknown> = {},\n): void {\n const envelope = buildEnvelope(operation, mvi, null, {\n code,\n message,\n category,\n retryable: false,\n retryAfterMs: null,\n details,\n });\n console.error(JSON.stringify(envelope, null, 2));\n}\n","/**\n * skills find command - marketplace search + recommendation mode\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n type LAFSErrorCategory,\n resolveOutputFormat,\n} from \"@cleocode/lafs\";\nimport type { MVILevel } from \"../../core/lafs.js\";\nimport { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { MarketplaceClient } from \"../../core/marketplace/client.js\";\nimport type { MarketplaceResult } from \"../../core/marketplace/types.js\";\nimport { formatNetworkError } from \"../../core/network/fetch.js\";\nimport {\n type RankedSkillRecommendation,\n RECOMMENDATION_ERROR_CODES,\n tokenizeCriteriaValue,\n} from \"../../core/skills/recommendation.js\";\nimport {\n formatSkillRecommendations,\n recommendSkills as recommendSkillsByQuery,\n} from \"../../core/skills/recommendation-api.js\";\n\ninterface SkillsFindOptions {\n json?: boolean;\n human?: boolean;\n limit: string;\n recommend?: boolean;\n top: string;\n details?: boolean;\n mustHave: string[];\n prefer: string[];\n exclude: string[];\n select?: string;\n}\n\nimport type { LAFSErrorShape } from \"../../core/lafs.js\";\n\nclass SkillsFindValidationError extends Error {\n code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.code = code;\n this.name = \"SkillsFindValidationError\";\n }\n}\n\ninterface RecommendationOption {\n rank: number;\n scopedName: string;\n description: string;\n score: number;\n why: string;\n source: string;\n evidence?: {\n reasons: RankedSkillRecommendation[\"reasons\"];\n breakdown?: RankedSkillRecommendation[\"breakdown\"];\n };\n}\n\n/**\n * Registers the `skills find` subcommand for searching marketplaces and recommending skills.\n *\n * @remarks\n * Supports free-text marketplace search and constraint-based skill recommendation mode with\n * must-have, prefer, and exclude criteria. Results can be output in JSON or human-readable format.\n *\n * @param parent - The parent `skills` Command to attach the find subcommand to\n *\n * @example\n * ```bash\n * caamp skills find \"testing framework\"\n * caamp skills find --recommend --must-have typescript --prefer vitest\n * ```\n *\n * @public\n */\nexport function registerSkillsFind(parent: Command): void {\n parent\n .command(\"find\")\n .description(\"Search marketplace for skills\")\n .argument(\"[query]\", \"Search query\")\n .option(\"--recommend\", \"Recommend skills from constraints\")\n .option(\"--top <n>\", \"Number of recommendation candidates\", \"3\")\n .option(\"--must-have <term>\", \"Required criteria term\", (value, previous: string[]) => [...previous, value], [])\n .option(\"--prefer <term>\", \"Preferred criteria term\", (value, previous: string[]) => [...previous, value], [])\n .option(\"--exclude <term>\", \"Excluded criteria term\", (value, previous: string[]) => [...previous, value], [])\n .option(\"--details\", \"Include expanded machine output\")\n .option(\"--human\", \"Force human-readable output\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--select <indexes>\", \"Pre-select recommendation ranks (comma-separated)\")\n .option(\"-l, --limit <n>\", \"Max results\", \"20\")\n .action(async (query: string | undefined, opts: SkillsFindOptions) => {\n const operation = opts.recommend ? \"skills.find.recommend\" : \"skills.find.search\";\n const details = Boolean(opts.details);\n const mvi: MVILevel = details ? \"full\" : \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (opts.json) {\n emitJsonError(operation, mvi, \"E_FORMAT_CONFLICT\", message, \"VALIDATION\");\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n if (opts.recommend) {\n try {\n const top = parseTop(opts.top);\n const mustHave = parseConstraintList(opts.mustHave);\n const prefer = parseConstraintList(opts.prefer);\n const exclude = parseConstraintList(opts.exclude);\n validateCriteriaConflicts(mustHave, prefer, exclude);\n const selectedRanks = parseSelectList(opts.select);\n const seedQuery = buildSeedQuery(query, mustHave, prefer, exclude);\n\n const recommendation = await recommendSkillsByQuery(\n seedQuery,\n {\n mustHave,\n prefer,\n exclude,\n },\n {\n top,\n includeDetails: details,\n },\n );\n const options = normalizeRecommendationOptions(recommendation.ranking, details);\n validateSelectedRanks(selectedRanks, options.length);\n const selected = selectedRanks.length > 0\n ? options.filter((option) => selectedRanks.includes(option.rank))\n : [];\n\n if (format === \"json\") {\n const result = formatSkillRecommendations(recommendation, { mode: \"json\", details }) as Record<string, unknown>;\n const resultOptions = Array.isArray(result.options)\n ? result.options as Array<Record<string, unknown>>\n : [];\n const selectedObjects = resultOptions.filter((option) =>\n selectedRanks.includes(Number(option.rank ?? 0))\n );\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n ...result,\n selected: selectedObjects,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n const human = formatSkillRecommendations(recommendation, { mode: \"human\", details }) as string;\n console.log(human);\n if (selected.length > 0) {\n console.log(`Selected: ${selected.map((option) => option.scopedName).join(\", \")}`);\n }\n return;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const errorCode =\n error instanceof SkillsFindValidationError\n ? error.code\n : (error as { code?: string }).code ?? RECOMMENDATION_ERROR_CODES.SOURCE_UNAVAILABLE;\n const category: LAFSErrorCategory =\n errorCode === RECOMMENDATION_ERROR_CODES.CRITERIA_CONFLICT\n ? \"CONFLICT\"\n : errorCode === RECOMMENDATION_ERROR_CODES.NO_MATCHES\n ? \"NOT_FOUND\"\n : errorCode === RECOMMENDATION_ERROR_CODES.QUERY_INVALID\n ? \"VALIDATION\"\n : \"INTERNAL\";\n if (format === \"json\") {\n emitJsonError(operation, mvi, errorCode, message, category, {\n query: query ?? null,\n });\n } else {\n console.error(pc.red(`Recommendation failed: ${message}`));\n }\n process.exit(1);\n }\n }\n\n if (!query) {\n console.log(pc.dim(\"Usage: caamp skills find <query>\"));\n return;\n }\n\n const limit = parseInt(opts.limit, 10);\n const client = new MarketplaceClient();\n\n if (format === \"human\") {\n console.log(pc.dim(`Searching marketplaces for \"${query}\"...\\n`));\n }\n\n let results: MarketplaceResult[];\n try {\n results = await client.search(query, limit);\n } catch (error) {\n const message = formatNetworkError(error);\n if (format === \"json\") {\n emitJsonError(operation, mvi, \"E_SEARCH_FAILED\", message, \"TRANSIENT\", {\n query,\n limit,\n });\n } else {\n console.error(pc.red(`Marketplace search failed: ${message}`));\n }\n process.exit(1);\n }\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n query,\n results,\n count: results.length,\n limit,\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n return;\n }\n\n if (results.length === 0) {\n console.log(pc.yellow(\"No results found.\"));\n return;\n }\n\n console.log(pc.dim(`Found ${results.length} result(s) for \"${query}\":\\n`));\n\n results.forEach((skill, index) => {\n const num = (index + 1).toString().padStart(2);\n const stars = skill.stars > 0 ? pc.yellow(`★ ${formatStars(skill.stars)}`) : \"\";\n console.log(` ${pc.cyan(num)}. ${pc.bold(skill.scopedName)} ${stars}`);\n console.log(` ${pc.dim(skill.description?.slice(0, 80) ?? \"\")}`);\n console.log(` ${pc.dim(`from ${skill.source}`)}`);\n console.log();\n });\n\n console.log(pc.dim(\"Install with: caamp skills install <name>\"));\n console.log(pc.dim(\"Or select by number: caamp skills install <n>\"));\n });\n}\n\nfunction formatStars(n: number): string {\n if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;\n return String(n);\n}\n\nfunction parseConstraintList(values: string[]): string[] {\n const normalized = values.flatMap((value) => tokenizeCriteriaValue(value));\n return Array.from(new Set(normalized));\n}\n\nfunction parseTop(value: string): number {\n const parsed = Number.parseInt(value, 10);\n if (!Number.isInteger(parsed) || parsed < 1 || parsed > 20) {\n throw new SkillsFindValidationError(RECOMMENDATION_ERROR_CODES.QUERY_INVALID, \"--top must be an integer between 1 and 20\");\n }\n return parsed;\n}\n\nfunction parseSelectList(value: string | undefined): number[] {\n if (!value) return [];\n const parsed = value\n .split(\",\")\n .map((entry) => Number.parseInt(entry.trim(), 10))\n .filter((entry) => Number.isInteger(entry) && entry > 0);\n return Array.from(new Set(parsed));\n}\n\nfunction buildSeedQuery(query: string | undefined, mustHave: string[], prefer: string[], exclude: string[]): string {\n if (query && query.trim().length > 0) {\n return query;\n }\n\n const seedTerms = [...mustHave, ...prefer, ...exclude].filter((term) => term.length > 0);\n if (seedTerms.length > 0) {\n return seedTerms.join(\" \");\n }\n\n throw new SkillsFindValidationError(\n RECOMMENDATION_ERROR_CODES.QUERY_INVALID,\n \"Recommendation mode requires a query or at least one criteria flag.\",\n );\n}\n\nfunction normalizeRecommendationOptions(ranking: RankedSkillRecommendation[], details: boolean): RecommendationOption[] {\n return ranking.map((entry, index) => {\n const whyCodes = entry.reasons.map((reason) => reason.code);\n return {\n rank: index + 1,\n scopedName: entry.skill.scopedName,\n description: entry.skill.description,\n score: entry.score,\n why: whyCodes.length > 0 ? whyCodes.join(\", \") : \"score-based match\",\n source: entry.skill.source,\n ...(details\n ? {\n evidence: {\n reasons: entry.reasons,\n breakdown: entry.breakdown,\n },\n }\n : {}),\n };\n });\n}\n\nfunction validateCriteriaConflicts(mustHave: string[], prefer: string[], exclude: string[]): void {\n const overlap = mustHave.filter((term) => exclude.includes(term));\n if (overlap.length > 0) {\n throw new SkillsFindValidationError(\n RECOMMENDATION_ERROR_CODES.CRITERIA_CONFLICT,\n \"A criteria term cannot be both required and excluded.\",\n );\n }\n\n const preferOverlap = prefer.filter((term) => exclude.includes(term));\n if (preferOverlap.length > 0) {\n throw new SkillsFindValidationError(\n RECOMMENDATION_ERROR_CODES.CRITERIA_CONFLICT,\n \"A criteria term cannot be both preferred and excluded.\",\n );\n }\n}\n\nfunction validateSelectedRanks(selectedRanks: number[], total: number): void {\n for (const rank of selectedRanks) {\n if (rank < 1 || rank > total) {\n throw new SkillsFindValidationError(\n RECOMMENDATION_ERROR_CODES.QUERY_INVALID,\n `--select rank ${rank} is out of range (1-${total}).`,\n );\n }\n }\n}\n\nfunction buildEnvelope<T>(operation: string, mvi: MVILevel, result: T | null, error: LAFSErrorShape | null) {\n return {\n $schema: \"https://lafs.dev/schemas/v1/envelope.schema.json\" as const,\n _meta: {\n specVersion: \"1.0.0\",\n schemaVersion: \"1.0.0\",\n timestamp: new Date().toISOString(),\n operation,\n requestId: randomUUID(),\n transport: \"cli\" as const,\n strict: true,\n mvi,\n contextVersion: 0,\n },\n success: error === null,\n result,\n error,\n page: null,\n };\n}\n\nfunction emitJsonError(\n operation: string,\n mvi: MVILevel,\n code: string,\n message: string,\n category: LAFSErrorCategory,\n details: Record<string, unknown> = {},\n): void {\n const envelope = buildEnvelope(operation, mvi, null, {\n code,\n message,\n category,\n retryable: false,\n retryAfterMs: null,\n details,\n });\n console.error(JSON.stringify(envelope, null, 2));\n}\n","/**\n * skills check command - check for updates - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { checkSkillUpdate, getTrackedSkills } from \"../../core/skills/lock.js\";\n\n/**\n * Registers the `skills check` subcommand for checking available skill updates.\n *\n * @remarks\n * Compares tracked skill versions against their remote sources and reports which skills\n * have updates available.\n *\n * @param parent - The parent `skills` Command to attach the check subcommand to\n *\n * @example\n * ```bash\n * caamp skills check --human\n * caamp skills check --json\n * ```\n *\n * @public\n */\nexport function registerSkillsCheck(parent: Command): void {\n parent\n .command(\"check\")\n .description(\"Check for available skill updates\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { json?: boolean; human?: boolean }) => {\n const operation = \"skills.check\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const tracked = await getTrackedSkills();\n const entries = Object.entries(tracked);\n\n if (entries.length === 0) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n skills: [],\n outdated: 0,\n total: 0,\n });\n } else {\n console.log(pc.dim(\"No tracked skills.\"));\n }\n return;\n }\n\n if (format === \"human\") {\n console.log(pc.dim(`Checking ${entries.length} skill(s) for updates...\\n`));\n }\n\n const skillResults = [];\n let updatesAvailable = 0;\n\n for (const [name, entry] of entries) {\n const update = await checkSkillUpdate(name);\n const hasUpdate = update.hasUpdate ?? false;\n\n if (hasUpdate) {\n updatesAvailable++;\n }\n\n skillResults.push({\n name,\n currentVersion: update.currentVersion ?? entry.version ?? \"unknown\",\n latestVersion: update.latestVersion ?? \"unknown\",\n hasUpdate,\n source: entry.source,\n agents: entry.agents,\n });\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n skills: skillResults.map((s) => ({\n name: s.name,\n currentVersion: s.currentVersion,\n latestVersion: s.latestVersion,\n hasUpdate: s.hasUpdate,\n })),\n outdated: updatesAvailable,\n total: entries.length,\n });\n return;\n }\n\n // Human-readable output\n for (const r of skillResults) {\n let statusLabel: string;\n if (r.hasUpdate) {\n statusLabel = pc.yellow(\"update available\");\n } else if (r.currentVersion !== \"unknown\") {\n statusLabel = pc.green(\"up to date\");\n } else {\n statusLabel = pc.dim(\"unknown\");\n }\n\n console.log(` ${pc.bold(r.name.padEnd(30))} ${statusLabel}`);\n\n if (r.currentVersion !== \"unknown\" || r.latestVersion !== \"unknown\") {\n const current = r.currentVersion !== \"unknown\" ? r.currentVersion.slice(0, 12) : \"?\";\n const latest = r.latestVersion !== \"unknown\" ? r.latestVersion : \"?\";\n if (r.hasUpdate) {\n console.log(` ${pc.dim(\"current:\")} ${current} ${pc.dim(\"->\")} ${pc.cyan(latest)}`);\n } else {\n console.log(` ${pc.dim(\"version:\")} ${current}`);\n }\n }\n\n console.log(` ${pc.dim(`source: ${r.source}`)}`);\n console.log(` ${pc.dim(`agents: ${r.agents.join(\", \")}`)}`);\n console.log();\n }\n\n if (updatesAvailable > 0) {\n console.log(pc.yellow(`${updatesAvailable} update(s) available.`));\n console.log(pc.dim(\"Run `caamp skills update` to update all.\"));\n } else {\n console.log(pc.green(\"All skills are up to date.\"));\n }\n });\n}\n","/**\n * skills update command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { getProvider } from \"../../core/registry/providers.js\";\nimport { installSkill } from \"../../core/skills/installer.js\";\nimport { checkSkillUpdate, getTrackedSkills, recordSkillInstall } from \"../../core/skills/lock.js\";\nimport { cloneRepo } from \"../../core/sources/github.js\";\nimport { cloneGitLabRepo } from \"../../core/sources/gitlab.js\";\nimport { parseSource } from \"../../core/sources/parser.js\";\nimport type { Provider } from \"../../types.js\";\n\n/**\n * Registers the `skills update` subcommand for updating all outdated skills.\n *\n * @remarks\n * Checks each tracked skill for available updates and re-installs those with newer versions.\n * Updates the lock file with new version information after successful re-installation.\n *\n * @param parent - The parent `skills` Command to attach the update subcommand to\n *\n * @example\n * ```bash\n * caamp skills update --yes\n * caamp skills update --json\n * ```\n *\n * @public\n */\nexport function registerSkillsUpdate(parent: Command): void {\n parent\n .command(\"update\")\n .description(\"Update all outdated skills\")\n .option(\"-y, --yes\", \"Skip confirmation\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (opts: { yes?: boolean; json?: boolean; human?: boolean }) => {\n const operation = \"skills.update\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const tracked = await getTrackedSkills();\n const entries = Object.entries(tracked);\n\n if (entries.length === 0) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n updated: [],\n failed: [],\n skipped: [],\n count: { updated: 0, failed: 0, skipped: 0 },\n });\n } else {\n console.log(pc.dim(\"No tracked skills to update.\"));\n }\n return;\n }\n\n if (format === \"human\") {\n console.log(pc.dim(`Checking ${entries.length} skill(s) for updates...`));\n }\n\n // Check all skills for updates\n const outdated: Array<{\n name: string;\n currentVersion?: string;\n latestVersion?: string;\n }> = [];\n\n for (const [name] of entries) {\n const result = await checkSkillUpdate(name);\n if (result.hasUpdate) {\n outdated.push({\n name,\n currentVersion: result.currentVersion,\n latestVersion: result.latestVersion,\n });\n }\n }\n\n if (outdated.length === 0) {\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n updated: [],\n failed: [],\n skipped: [],\n count: { updated: 0, failed: 0, skipped: 0 },\n });\n } else {\n console.log(pc.green(\"\\nAll skills are up to date.\"));\n }\n return;\n }\n\n if (format === \"human\") {\n console.log(pc.yellow(`\\n${outdated.length} skill(s) have updates available:\\n`));\n\n for (const skill of outdated) {\n const current = skill.currentVersion?.slice(0, 12) ?? \"?\";\n const latest = skill.latestVersion ?? \"?\";\n console.log(` ${pc.bold(skill.name)} ${pc.dim(current)} ${pc.dim(\"->\")} ${pc.cyan(latest)}`);\n }\n }\n\n // Confirm unless --yes\n if (!opts.yes && format === \"human\") {\n const readline = await import(\"node:readline\");\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const answer = await new Promise<string>((resolve) => {\n rl.question(pc.dim(\"\\nProceed with update? [y/N] \"), resolve);\n });\n rl.close();\n\n if (answer.toLowerCase() !== \"y\" && answer.toLowerCase() !== \"yes\") {\n console.log(pc.dim(\"Update cancelled.\"));\n return;\n }\n }\n\n if (format === \"human\") {\n console.log();\n }\n\n // Track results for JSON output\n const updated: string[] = [];\n const failed: Array<{ name: string; error: string }> = [];\n const skipped: string[] = [];\n\n // Update each outdated skill\n for (const skill of outdated) {\n const entry = tracked[skill.name];\n if (!entry) continue;\n\n if (format === \"human\") {\n console.log(pc.dim(`Updating ${pc.bold(skill.name)}...`));\n }\n\n try {\n const parsed = parseSource(entry.source);\n let localPath: string;\n let cleanup: (() => Promise<void>) | undefined;\n\n if (parsed.type === \"github\" && parsed.owner && parsed.repo) {\n const result = await cloneRepo(parsed.owner, parsed.repo, parsed.ref, parsed.path);\n localPath = result.localPath;\n cleanup = result.cleanup;\n } else if (parsed.type === \"gitlab\" && parsed.owner && parsed.repo) {\n const result = await cloneGitLabRepo(parsed.owner, parsed.repo, parsed.ref, parsed.path);\n localPath = result.localPath;\n cleanup = result.cleanup;\n } else {\n if (format === \"human\") {\n console.log(pc.yellow(` Skipped ${skill.name}: source type \"${parsed.type}\" does not support auto-update`));\n }\n skipped.push(skill.name);\n continue;\n }\n\n try {\n // Resolve providers from the lock entry's agent list\n const providers = entry.agents\n .map((a) => getProvider(a))\n .filter((p): p is Provider => p !== undefined);\n\n if (providers.length === 0) {\n if (format === \"human\") {\n console.log(pc.yellow(` Skipped ${skill.name}: no valid providers found`));\n }\n skipped.push(skill.name);\n continue;\n }\n\n const installResult = await installSkill(\n localPath,\n skill.name,\n providers,\n entry.isGlobal,\n entry.projectDir,\n );\n\n if (installResult.success) {\n // Record the updated version in the lock file\n await recordSkillInstall(\n skill.name,\n entry.scopedName,\n entry.source,\n entry.sourceType,\n installResult.linkedAgents,\n installResult.canonicalPath,\n entry.isGlobal,\n entry.projectDir,\n skill.latestVersion,\n );\n\n if (format === \"human\") {\n console.log(pc.green(` Updated ${pc.bold(skill.name)}`));\n }\n updated.push(skill.name);\n } else {\n if (format === \"human\") {\n console.log(pc.red(` Failed to update ${skill.name}: no agents linked`));\n }\n failed.push({ name: skill.name, error: \"no agents linked\" });\n }\n\n if (installResult.errors.length > 0 && format === \"human\") {\n for (const err of installResult.errors) {\n console.log(pc.yellow(` ${err}`));\n }\n }\n } finally {\n if (cleanup) await cleanup();\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (format === \"human\") {\n console.log(pc.red(` Failed to update ${skill.name}: ${msg}`));\n }\n failed.push({ name: skill.name, error: msg });\n }\n }\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, {\n updated,\n failed,\n skipped,\n count: {\n updated: updated.length,\n failed: failed.length,\n skipped: skipped.length,\n },\n });\n return;\n }\n\n // Human-readable output\n console.log();\n if (updated.length > 0) {\n console.log(pc.green(`Updated ${updated.length} skill(s).`));\n }\n if (failed.length > 0) {\n console.log(pc.red(`Failed to update ${failed.length} skill(s).`));\n }\n });\n}\n","/**\n * skills init command - scaffold a new skill - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync } from \"node:fs\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\n\n/**\n * Registers the `skills init` subcommand for scaffolding new SKILL.md templates.\n *\n * @remarks\n * Creates a SKILL.md file with the standard template structure in the specified directory.\n * Optionally takes a skill name to pre-fill the template heading.\n *\n * @param parent - The parent `skills` Command to attach the init subcommand to\n *\n * @example\n * ```bash\n * caamp skills init my-skill\n * caamp skills init --dir ./skills/new-skill\n * ```\n *\n * @public\n */\nexport function registerSkillsInit(parent: Command): void {\n parent\n .command(\"init\")\n .description(\"Create a new SKILL.md template\")\n .argument(\"[name]\", \"Skill name\")\n .option(\"-d, --dir <path>\", \"Output directory\", \".\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (name: string | undefined, opts: { dir: string; json?: boolean; human?: boolean }) => {\n const operation = \"skills.init\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n const skillName = name ?? \"my-skill\";\n const skillDir = join(opts.dir, skillName);\n\n if (existsSync(skillDir)) {\n const message = `Directory already exists: ${skillDir}`;\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.INVALID_CONSTRAINT, message, ErrorCategories.CONFLICT, {\n path: skillDir,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n await mkdir(skillDir, { recursive: true });\n\n const template = `---\nname: ${skillName}\ndescription: Describe what this skill does and when to use it\nlicense: MIT\nmetadata:\n author: your-name\n version: \"1.0\"\n---\n\n# ${skillName}\n\n## When to use this skill\n\nDescribe the conditions under which an AI agent should activate this skill.\n\n## Instructions\n\nProvide detailed instructions for the AI agent here.\n\n## Examples\n\nShow example inputs and expected outputs.\n`;\n\n await writeFile(join(skillDir, \"SKILL.md\"), template, \"utf-8\");\n\n const result = {\n name: skillName,\n directory: skillDir,\n template: \"SKILL.md\",\n created: true,\n };\n\n if (format === \"json\") {\n outputSuccess(operation, mvi, result);\n return;\n }\n\n // Human-readable output\n console.log(pc.green(`✓ Created skill template: ${skillDir}/SKILL.md`));\n console.log(pc.dim(\"\\nNext steps:\"));\n console.log(pc.dim(\" 1. Edit SKILL.md with your instructions\"));\n console.log(pc.dim(` 2. Validate: caamp skills validate ${join(skillDir, \"SKILL.md\")}`));\n console.log(pc.dim(` 3. Install: caamp skills install ${skillDir}`));\n });\n}\n","/**\n * skills audit command - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync, statSync } from \"node:fs\";\nimport type { LAFSErrorCategory } from \"@cleocode/lafs\";\nimport { resolveOutputFormat } from \"@cleocode/lafs\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n type LAFSErrorShape,\n outputSuccess,\n resolveFormat,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { scanDirectory, scanFile, toSarif } from \"../../core/skills/audit/scanner.js\";\nimport type { AuditResult } from \"../../types.js\";\n\ninterface SkillsAuditOptions {\n sarif?: boolean;\n json?: boolean;\n human?: boolean;\n}\n\ninterface AuditFileResult {\n path: string;\n score: number;\n findings: Array<{\n level: \"critical\" | \"high\" | \"medium\" | \"low\";\n code: string;\n message: string;\n line?: number;\n }>;\n}\n\ninterface AuditSummary {\n scanned: number;\n findings: number;\n files: AuditFileResult[];\n}\n\n/**\n * Registers the `skills audit` subcommand for security scanning skill files.\n *\n * @remarks\n * Scans SKILL.md files against 46+ security rules and outputs findings in LAFS JSON envelope,\n * human-readable, or raw SARIF format. Supports scanning individual files or entire directories.\n *\n * @param parent - The parent `skills` Command to attach the audit subcommand to\n *\n * @example\n * ```bash\n * caamp skills audit ./my-skill/SKILL.md\n * caamp skills audit ./skills-dir --sarif\n * ```\n *\n * @public\n */\nexport function registerSkillsAudit(parent: Command): void {\n parent\n .command(\"audit\")\n .description(\"Security scan skill files (46+ rules, SARIF output)\")\n .argument(\"[path]\", \"Path to SKILL.md or directory\", \".\")\n .option(\"--sarif\", \"Output in SARIF format (raw SARIF, not LAFS envelope)\")\n .option(\"--json\", \"Output as JSON (LAFS envelope)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (path: string, opts: SkillsAuditOptions) => {\n const operation = \"skills.audit\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n // Check if path exists\n if (!existsSync(path)) {\n const message = `Path not found: ${path}`;\n \n // Check if --sarif was explicitly requested\n if (opts.sarif) {\n // For SARIF mode on error, output minimal SARIF with error\n console.error(JSON.stringify({\n $schema: \"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json\",\n version: \"2.1.0\",\n runs: [{\n tool: { driver: { name: \"caamp-skills-audit\" } },\n invocations: [{\n executionSuccessful: false,\n exitCode: 1,\n exitCodeDescription: message,\n }],\n results: [],\n }],\n }, null, 2));\n } else {\n // LAFS envelope error\n emitJsonError(operation, mvi, ErrorCodes.FILE_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n path,\n });\n }\n process.exit(1);\n }\n\n // Resolve output format (SARIF is a special case - outputs raw SARIF, not LAFS envelope)\n let format: \"json\" | \"human\" | \"sarif\";\n try {\n if (opts.sarif) {\n // SARIF is handled separately - it outputs raw SARIF format\n format = \"sarif\";\n } else {\n format = resolveFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n });\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n // Perform the scan\n const stat = statSync(path);\n let results: AuditResult[];\n\n try {\n if (stat.isFile()) {\n results = [await scanFile(path)];\n } else {\n results = await scanDirectory(path);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n \n if (format === \"sarif\") {\n console.error(JSON.stringify({\n $schema: \"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json\",\n version: \"2.1.0\",\n runs: [{\n tool: { driver: { name: \"caamp-skills-audit\" } },\n invocations: [{\n executionSuccessful: false,\n exitCode: 1,\n exitCodeDescription: message,\n }],\n results: [],\n }],\n }, null, 2));\n } else {\n emitJsonError(operation, mvi, ErrorCodes.AUDIT_FAILED, message, ErrorCategories.INTERNAL, {\n path,\n });\n }\n process.exit(1);\n }\n\n // Handle no results case\n if (results.length === 0) {\n if (format === \"sarif\") {\n console.log(JSON.stringify(toSarif([]), null, 2));\n return;\n }\n\n if (format === \"json\") {\n const summary: AuditSummary = {\n scanned: 0,\n findings: 0,\n files: [],\n };\n outputSuccess(operation, mvi, summary);\n return;\n }\n\n // Human-readable\n console.log(pc.dim(\"No SKILL.md files found to scan.\"));\n return;\n }\n\n // Calculate summary\n const summary: AuditSummary = {\n scanned: results.length,\n findings: results.reduce((acc, r) => acc + r.findings.length, 0),\n files: results.map((r) => ({\n path: r.file,\n score: r.score,\n findings: r.findings.map((f) => ({\n level: f.rule.severity as \"critical\" | \"high\" | \"medium\" | \"low\",\n code: f.rule.id,\n message: `${f.rule.name}: ${f.rule.description}`,\n line: f.line,\n })),\n })),\n };\n\n // Check if all passed\n const allPassed = results.every((r) => r.passed);\n\n // SARIF output (raw SARIF format, not LAFS envelope)\n if (format === \"sarif\") {\n console.log(JSON.stringify(toSarif(results), null, 2));\n if (!allPassed) {\n process.exit(1);\n }\n return;\n }\n\n // LAFS JSON output\n if (format === \"json\") {\n outputSuccess(operation, mvi, summary);\n if (!allPassed) {\n process.exit(1);\n }\n return;\n }\n\n // Human-readable output\n let totalFindings = 0;\n\n for (const result of results) {\n const icon = result.passed ? pc.green(\"✓\") : pc.red(\"✗\");\n console.log(`\\n${icon} ${pc.bold(result.file)} (score: ${result.score}/100)`);\n\n if (result.findings.length === 0) {\n console.log(pc.dim(\" No issues found.\"));\n continue;\n }\n\n totalFindings += result.findings.length;\n\n for (const f of result.findings) {\n const sev = f.rule.severity === \"critical\" ? pc.red(f.rule.severity)\n : f.rule.severity === \"high\" ? pc.red(f.rule.severity)\n : f.rule.severity === \"medium\" ? pc.yellow(f.rule.severity)\n : pc.dim(f.rule.severity);\n\n console.log(` ${sev.padEnd(20)} ${f.rule.id} ${f.rule.name}`);\n console.log(` ${pc.dim(`L${f.line}: ${f.context.slice(0, 80)}`)}`);\n }\n }\n\n console.log(pc.bold(`\\n${results.length} file(s) scanned, ${totalFindings} finding(s)`));\n\n if (!allPassed) {\n process.exit(1);\n }\n });\n}\n","/**\n * skills validate command - LAFS-compliant with JSON-first output\n */\n\nimport type { LAFSErrorCategory } from \"@cleocode/lafs\";\nimport { resolveOutputFormat } from \"@cleocode/lafs\";\nimport type { Command } from \"commander\";\nimport pc from \"picocolors\";\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n} from \"../../core/lafs.js\";\nimport { isHuman } from \"../../core/logger.js\";\nimport { validateSkill } from \"../../core/skills/validator.js\";\n\ninterface LAFSErrorShape {\n code: string;\n message: string;\n category: LAFSErrorCategory;\n retryable: boolean;\n retryAfterMs: number | null;\n details: Record<string, unknown>;\n}\n\n/**\n * Registers the `skills validate` subcommand for validating SKILL.md file format.\n *\n * @remarks\n * Parses a SKILL.md file and checks it against the required schema, reporting any missing\n * sections, invalid metadata, or structural issues.\n *\n * @param parent - The parent `skills` Command to attach the validate subcommand to\n *\n * @example\n * ```bash\n * caamp skills validate ./my-skill/SKILL.md\n * caamp skills validate --json\n * ```\n *\n * @public\n */\nexport function registerSkillsValidate(parent: Command): void {\n parent\n .command(\"validate\")\n .description(\"Validate SKILL.md format\")\n .argument(\"[path]\", \"Path to SKILL.md\", \"SKILL.md\")\n .option(\"--json\", \"Output as JSON (default)\")\n .option(\"--human\", \"Output in human-readable format\")\n .action(async (path: string, opts: { json?: boolean; human?: boolean }) => {\n const operation = \"skills.validate\";\n const mvi: import(\"../../core/lafs.js\").MVILevel = \"standard\";\n\n let format: \"json\" | \"human\";\n try {\n format = resolveOutputFormat({\n jsonFlag: opts.json ?? false,\n humanFlag: (opts.human ?? false) || isHuman(),\n projectDefault: \"json\",\n }).format;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emitJsonError(operation, mvi, ErrorCodes.FORMAT_CONFLICT, message, ErrorCategories.VALIDATION);\n process.exit(1);\n }\n\n let result;\n try {\n result = await validateSkill(path);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (format === \"json\") {\n emitJsonError(operation, mvi, ErrorCodes.FILE_NOT_FOUND, message, ErrorCategories.NOT_FOUND, {\n path,\n });\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\n\n if (format === \"json\") {\n const envelope = buildEnvelope(\n operation,\n mvi,\n {\n valid: result.valid,\n file: path,\n issues: result.issues.map((issue) => ({\n level: issue.level === \"error\" ? \"error\" : \"warn\",\n field: issue.field,\n message: issue.message,\n })),\n },\n null,\n );\n console.log(JSON.stringify(envelope, null, 2));\n } else {\n // Human-readable output\n if (result.valid) {\n console.log(pc.green(`✓ ${path} is valid`));\n } else {\n console.log(pc.red(`✗ ${path} has validation errors`));\n }\n\n for (const issue of result.issues) {\n const icon = issue.level === \"error\" ? pc.red(\"✗\") : pc.yellow(\"!\");\n console.log(` ${icon} [${issue.field}] ${issue.message}`);\n }\n }\n\n if (!result.valid) {\n process.exit(1);\n }\n });\n}\n","/**\n * Skills management command group for installing, removing, listing, finding, checking, updating,\n * initializing, auditing, and validating AI agent skills.\n *\n * @packageDocumentation\n */\n\nimport type { Command } from \"commander\";\nimport { registerSkillsInstall } from \"./install.js\";\nimport { registerSkillsRemove } from \"./remove.js\";\nimport { registerSkillsList } from \"./list.js\";\nimport { registerSkillsFind } from \"./find.js\";\nimport { registerSkillsCheck } from \"./check.js\";\nimport { registerSkillsUpdate } from \"./update.js\";\nimport { registerSkillsInit } from \"./init.js\";\nimport { registerSkillsAudit } from \"./audit.js\";\nimport { registerSkillsValidate } from \"./validate.js\";\n\n/**\n * Registers the `skills` command group with all skill management subcommands.\n *\n * @remarks\n * Orchestrates registration of install, remove, list, find, check, update, init, audit, and\n * validate subcommands under the unified `skills` parent command.\n *\n * @param program - The root Commander program to attach the skills command group to\n *\n * @example\n * ```bash\n * caamp skills install owner/repo\n * caamp skills list --human\n * caamp skills find \"testing\"\n * ```\n *\n * @public\n */\nexport function registerSkillsCommands(program: Command): void {\n const skills = program\n .command(\"skills\")\n .description(\"Manage AI agent skills\");\n\n registerSkillsInstall(skills);\n registerSkillsRemove(skills);\n registerSkillsList(skills);\n registerSkillsFind(skills);\n registerSkillsCheck(skills);\n registerSkillsUpdate(skills);\n registerSkillsInit(skills);\n registerSkillsAudit(skills);\n registerSkillsValidate(skills);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,eAAe;;;ACFxB,SAAS,gBAAgB;;;ACAzB,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,OAKK;AAyBA,IAAM,mBAAN,cAA+B,MAAM;AAAA;AAAA,EAE1C;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAEA,YACE,MACA,SACA,YACA,cAAc,MACd,SACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW,mBAAmB,IAAI;AACvC,SAAK,cAAc;AACnB,SAAK,aAAa;AAClB,SAAK,eAAe;AACpB,SAAK,UAAU;AAAA,EACjB;AACF;AAEA,SAAS,mBAAmB,MAAiC;AAC3D,MAAI,KAAK,SAAS,YAAY,EAAG,QAAO;AACxC,MAAI,KAAK,SAAS,WAAW,EAAG,QAAO;AACvC,MAAI,KAAK,SAAS,UAAU,EAAG,QAAO;AACtC,MAAI,KAAK,SAAS,MAAM,EAAG,QAAO;AAClC,MAAI,KAAK,SAAS,YAAY,EAAG,QAAO;AACxC,MAAI,KAAK,SAAS,YAAY,EAAG,QAAO;AACxC,MAAI,KAAK,SAAS,WAAW,EAAG,QAAO;AACvC,MAAI,KAAK,SAAS,UAAU,EAAG,QAAO;AACtC,SAAO;AACT;AAEA,SAAS,SAAS,WAA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M,WAAW,KAAK;AAAA,EAChC;AACF;AAEA,QAAQ,GAAG,qBAAqB,CAAC,UAAU;AACzC,cAAY,OAAO,mBAAmB;AACtC,UAAQ,KAAK,CAAC;AAChB,CAAC;AAED,QAAQ,GAAG,sBAAsB,CAAC,WAAW;AAC3C,cAAY,QAAQ,oBAAoB;AACxC,UAAQ,KAAK,CAAC;AAChB,CAAC;AAED,eAAe,OAAsB;AACnC,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,cAAY,OAAO,KAAK;AACxB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["program","randomUUID","randomUUID","emitError","program","existsSync","join","pc","existsSync","join","pc","program","pc","pc","pc","pc","pc","pc","program","pc","pc","program","existsSync","pc","existsSync","pc","pc","pc","pc","pc","pc","pc","program","randomUUID","resolveOutputFormat","pc","program","resolveOutputFormat","emitJsonError","buildEnvelope","pc","canonical","hooks","randomUUID","existsSync","pc","join","join","simpleGit","mkdtemp","rm","tmpdir","join","mkdtemp","join","tmpdir","simpleGit","rm","emitError","pc","existsSync","pc","pc","randomUUID","resolveOutputFormat","pc","resolveOutputFormat","emitJsonError","pc","buildEnvelope","randomUUID","randomUUID","resolveOutputFormat","pc","resolveOutputFormat","emitJsonError","pc","buildEnvelope","randomUUID","pc","pc","pc","pc","existsSync","join","pc","join","existsSync","pc","existsSync","pc","existsSync","summary","pc","resolveOutputFormat","pc","resolveOutputFormat","pc","program"]}
|