@cleocode/caamp 2026.4.4 → 2026.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-XWQ5WPHC.js → chunk-364OHA2T.js} +25 -5
- package/dist/{chunk-XWQ5WPHC.js.map → chunk-364OHA2T.js.map} +1 -1
- package/dist/{chunk-6NBM4CAF.js → chunk-43GULI6J.js} +524 -105
- package/dist/chunk-43GULI6J.js.map +1 -0
- package/dist/{chunk-FLBRAXDW.js → chunk-CU2VX67L.js} +2 -2
- package/dist/{chunk-CRU25LRL.js → chunk-KWYLZ46H.js} +60 -23
- package/dist/chunk-KWYLZ46H.js.map +1 -0
- package/dist/cli.js +161 -47
- package/dist/cli.js.map +1 -1
- package/dist/{hooks-VLIP52LY.js → hooks-M2DMKNHI.js} +3 -3
- package/dist/index.d.ts +955 -273
- package/dist/index.js +17 -5
- package/dist/index.js.map +1 -1
- package/dist/{injector-ALLOKC54.js → injector-O23XOBYB.js} +3 -3
- package/package.json +2 -2
- package/providers/hook-mappings.json +27 -3
- package/providers/registry.json +750 -455
- package/dist/chunk-6NBM4CAF.js.map +0 -1
- package/dist/chunk-CRU25LRL.js.map +0 -1
- /package/dist/{chunk-FLBRAXDW.js.map → chunk-CU2VX67L.js.map} +0 -0
- /package/dist/{hooks-VLIP52LY.js.map → hooks-M2DMKNHI.js.map} +0 -0
- /package/dist/{injector-ALLOKC54.js.map → injector-O23XOBYB.js.map} +0 -0
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/batch.ts","../src/commands/advanced/instructions.ts","../src/commands/advanced/providers.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/check.ts","../src/commands/instructions/inject.ts","../src/commands/instructions/update.ts","../src/commands/instructions/index.ts","../src/commands/providers.ts","../src/commands/skills/audit.ts","../src/commands/skills/check.ts","../src/commands/skills/find.ts","../src/commands/skills/init.ts","../src/commands/skills/install.ts","../src/core/sources/github.ts","../src/core/sources/gitlab.ts","../src/commands/skills/list.ts","../src/commands/skills/remove.ts","../src/commands/skills/update.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 { 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);\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(\n error: unknown,\n source: 'uncaughtException' | 'unhandledRejection' | 'cli',\n): 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 { SkillBatchOperation } from '../../core/advanced/orchestration.js';\nimport { getInstalledProviders } from '../../core/registry/detection.js';\nimport { getAllProviders, getProvider } from '../../core/registry/providers.js';\nimport type { Provider, ProviderPriority } from '../../types.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 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 LAFSError,\n type LAFSErrorCategory,\n type LAFSMeta,\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 batch command\n */\n\nimport type { Command } from 'commander';\nimport {\n installBatchWithRollback,\n selectProvidersByMinimumPriority,\n} from '../../core/advanced/orchestration.js';\nimport { parsePriority, 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 skills.\n *\n * @remarks\n * Installs skills from a JSON file 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 --skills-file skills.json\n * caamp advanced batch --skills-file skills.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 skills')\n .option(\n '-a, --agent <name>',\n 'Target specific provider(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\n .option('--all', 'Use all registry providers (not only detected)')\n .option('--min-tier <tier>', 'Minimum priority tier: high|medium|low', 'low')\n .requiredOption('--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(\n async (opts: {\n agent: string[];\n all?: boolean;\n minTier: string;\n skillsFile: string;\n projectDir?: string;\n details?: boolean;\n }) =>\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 skills = await readSkillOperations(opts.skillsFile);\n\n if (skills.length === 0) {\n throw new LAFSCommandError(\n 'E_ADVANCED_VALIDATION_NO_OPS',\n 'No operations provided.',\n 'Provide a --skills-file with at least one operation.',\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 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 skills with rollback safety',\n constraints: {\n minimumPriority,\n providerCount: providers.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 skillsApplied: result.skillsApplied,\n rollbackPerformed: result.rollbackPerformed,\n },\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(\n '-a, --agent <name>',\n 'Target specific provider(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\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(\n 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 }) =>\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 =\n 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","/**\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(\n '-a, --agent <name>',\n 'Target specific provider(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\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: { agent: string[]; all?: boolean; minTier: string; 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","/**\n * Advanced orchestration command group providing LAFS-compliant wrappers for batch operations,\n * provider selection, and instruction management.\n *\n * @packageDocumentation\n */\n\nimport type { Command } from 'commander';\nimport { registerAdvancedBatch } from './batch.js';\nimport { registerAdvancedInstructions } from './instructions.js';\nimport { registerAdvancedProviders } from './providers.js';\n\n/**\n * Registers the `advanced` command group with providers, batch, and instructions 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 --skills-file skills.json\n * caamp advanced instructions --content \"## Setup\" --all\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 registerAdvancedInstructions(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 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.command('config').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(\n 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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n operation,\n mvi,\n ErrorCodes.PROVIDER_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n providerId,\n },\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(\n operation,\n mvi,\n ErrorCodes.FILE_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n configPath,\n scope,\n },\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(\n operation,\n mvi,\n ErrorCodes.FILE_SYSTEM_ERROR,\n message,\n ErrorCategories.INTERNAL,\n );\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\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 { LAFSError, LAFSErrorCategory, LAFSMeta, LAFSPage, Warning } 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 ErrorCategories,\n ErrorCodes,\n emitJsonError,\n handleFormatError,\n outputSuccess,\n resolveFormat,\n} from '../core/lafs.js';\nimport { readLockFile } from '../core/lock-utils.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';\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 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/') || 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\n/**\n * Validate the CAAMP skills lock file integrity.\n *\n * @remarks\n * Checks the lock file for skill-installation drift in three dimensions:\n * orphaned entries (lock-tracked but missing from disk), untracked skills\n * (on disk but not in lock), and agent-list mismatches (lock claims a\n * provider symlink that no longer exists). Lock-file IO errors surface as\n * a `'fail'` check, which causes the doctor command to exit non-zero.\n *\n * @returns Section result with one or more lock-file health checks\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:\n mismatches.slice(0, 5).join(', ') +\n (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 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 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 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 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/') || 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","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 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(\n '-a, --agent <name>',\n 'Check specific agent(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\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(\n 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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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","/**\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 {\n generateInjectionContent,\n groupByInstructFile,\n} 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(\n '-a, --agent <name>',\n 'Target specific agent(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\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(\n 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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n operation,\n mvi,\n ErrorCodes.PROVIDER_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n );\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 =\n action === 'created'\n ? pc.green('+')\n : action === 'updated'\n ? 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","/**\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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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 { registerInstructionsCheck } from './check.js';\nimport { registerInstructionsInject } from './inject.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 * 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 {\n buildHookMatrix,\n CANONICAL_HOOK_EVENTS,\n getCommonEvents,\n getHookMappingsVersion,\n getHookSupport,\n getProviderSummary,\n translateToAll,\n} from '../core/hooks/index.js';\nimport type { CanonicalHookEvent } from '../core/hooks/types.js';\nimport { isHuman } from '../core/logger.js';\nimport { detectAllProviders, detectProjectProviders } from '../core/registry/detection.js';\nimport {\n buildSkillsMap,\n getAllProviders,\n getProvider,\n getProviderCount,\n getProvidersByPriority,\n getRegistryVersion,\n providerSupports,\n} from '../core/registry/providers.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.command('providers').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 =\n tier === 'high'\n ? pc.green('HIGH')\n : tier === 'medium'\n ? pc.yellow('MEDIUM')\n : pc.dim('LOW');\n console.log(`${tierLabel} priority:`);\n\n for (const p of tierProviders) {\n const status =\n p.status === 'active'\n ? pc.green('active')\n : p.status === 'beta'\n ? pc.yellow('beta')\n : pc.dim(p.status);\n\n console.log(\n ` ${pc.bold(p.agentFlag.padEnd(20))} ${p.toolName.padEnd(22)} ${p.vendor.padEnd(16)} [${status}]`,\n );\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 ? detectProjectProviders(process.cwd()) : 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(\n ` ${pc.green('✓')} ${pc.bold(r.provider.toolName.padEnd(22))} via ${pc.dim(methods)}${project}`,\n );\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.command('hooks').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.map((p) => getProviderSummary(p.id)).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(\n ` ${'─'.repeat(22)} ${'─'.repeat(10)} ${'─'.repeat(12)} ${'─'.repeat(12)} ${'─'.repeat(20)}`,\n );\n\n for (const s of summaries) {\n if (!s) continue;\n const system =\n s.hookSystem === 'none'\n ? pc.dim('none')\n : s.experimental\n ? pc.yellow(s.hookSystem + '*')\n : pc.green(s.hookSystem);\n const coverage =\n s.coverage > 0\n ? (s.coverage >= 75 ? pc.green : s.coverage >= 40 ? pc.yellow : pc.dim)(\n `${s.coverage}%`,\n )\n : pc.dim('0%');\n const supported =\n s.supportedCount > 0 ? `${s.supportedCount}/${s.totalCanonical}` : 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(\n pc.dim(\n `\\n ${withHooks.length} providers with hook support, ${summaries.length - withHooks.length} without`,\n ),\n );\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\n .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 })\n .join('');\n\n console.log(` ${event.padEnd(22)} ${cells}`);\n }\n\n // Common events\n const commonEvents = getCommonEvents(matrix.providers);\n console.log(\n pc.dim(`\\n Common events: ${commonEvents.length > 0 ? commonEvents.join(', ') : 'none'}`),\n );\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(\n async (\n event: string,\n opts: { to?: string; from?: string; json?: boolean; human?: boolean },\n ) => {\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(\n operation,\n mvi,\n {\n direction: 'canonical-to-native',\n providerId: opts.to,\n ...result,\n },\n null,\n );\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(\n operation,\n mvi,\n {\n direction: 'native-to-canonical',\n native: event,\n providerId: opts.from,\n canonical,\n supported: canonical !== null,\n },\n null,\n );\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 `\\n ${pc.bold(event)} (${opts.from}) → ${pc.dim('no canonical mapping (provider-only event)')}`,\n );\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(\n operation,\n mvi,\n {\n direction: 'canonical-to-all',\n canonical: event,\n translations,\n supportedCount: Object.keys(translations).length,\n totalProviders: allIds.length,\n },\n null,\n );\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\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(\n '--filter <path>',\n 'Filter to providers supporting a capability dot-path (e.g. spawn.supportsSubagents)',\n )\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 audit command - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync, statSync } 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 { 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(\n JSON.stringify(\n {\n $schema:\n 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',\n version: '2.1.0',\n runs: [\n {\n tool: { driver: { name: 'caamp-skills-audit' } },\n invocations: [\n {\n executionSuccessful: false,\n exitCode: 1,\n exitCodeDescription: message,\n },\n ],\n results: [],\n },\n ],\n },\n null,\n 2,\n ),\n );\n } else {\n // LAFS envelope error\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.FILE_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n path,\n },\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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n JSON.stringify(\n {\n $schema:\n 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',\n version: '2.1.0',\n runs: [\n {\n tool: { driver: { name: 'caamp-skills-audit' } },\n invocations: [\n {\n executionSuccessful: false,\n exitCode: 1,\n exitCodeDescription: message,\n },\n ],\n results: [],\n },\n ],\n },\n null,\n 2,\n ),\n );\n } else {\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.AUDIT_FAILED,\n message,\n ErrorCategories.INTERNAL,\n {\n path,\n },\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 =\n f.rule.severity === 'critical'\n ? pc.red(f.rule.severity)\n : f.rule.severity === 'high'\n ? pc.red(f.rule.severity)\n : f.rule.severity === 'medium'\n ? 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 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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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 find command - marketplace search + recommendation mode\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { type LAFSErrorCategory, resolveOutputFormat } from '@cleocode/lafs';\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport type { MVILevel } from '../../core/lafs.js';\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(\n '--must-have <term>',\n 'Required criteria term',\n (value, previous: string[]) => [...previous, value],\n [],\n )\n .option(\n '--prefer <term>',\n 'Preferred criteria term',\n (value, previous: string[]) => [...previous, value],\n [],\n )\n .option(\n '--exclude <term>',\n 'Excluded criteria term',\n (value, previous: string[]) => [...previous, value],\n [],\n )\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 =\n selectedRanks.length > 0\n ? options.filter((option) => selectedRanks.includes(option.rank))\n : [];\n\n if (format === 'json') {\n const result = formatSkillRecommendations(recommendation, {\n mode: 'json',\n details,\n }) 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, {\n mode: 'human',\n details,\n }) 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 ??\n 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(\n RECOMMENDATION_ERROR_CODES.QUERY_INVALID,\n '--top must be an integer between 1 and 20',\n );\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(\n query: string | undefined,\n mustHave: string[],\n prefer: string[],\n exclude: string[],\n): 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(\n ranking: RankedSkillRecommendation[],\n details: boolean,\n): 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>(\n operation: string,\n mvi: 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: 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 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(\n 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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n operation,\n mvi,\n ErrorCodes.INVALID_CONSTRAINT,\n message,\n ErrorCategories.CONFLICT,\n {\n path: skillDir,\n },\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","/**\n * skills install command - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync } from 'node:fs';\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitError,\n emitJsonError,\n type MVILevel,\n outputSuccess,\n resolveFormat,\n} from '../../core/lafs.js';\nimport { MarketplaceClient } from '../../core/marketplace/client.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(\n '-a, --agent <name>',\n 'Target specific agent(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\n .option('-g, --global', 'Install globally')\n .option('-y, --yes', 'Skip confirmation')\n .option('--all', 'Install to all detected agents')\n .option(\n '--profile <name>',\n 'Install a skill library profile (minimal, core, recommended, full)',\n )\n .option('--json', 'Output as JSON (default)')\n .option('--human', 'Output in human-readable format')\n .action(\n async (\n source: string | undefined,\n opts: {\n agent: string[];\n global?: boolean;\n yes?: boolean;\n all?: boolean;\n profile?: string;\n json?: boolean;\n human?: boolean;\n },\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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n operation,\n mvi,\n ErrorCodes.PROVIDER_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n );\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(\n opts.profile,\n providers,\n opts.global ?? false,\n format,\n operation,\n mvi,\n );\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(\n operation,\n mvi,\n ErrorCodes.INVALID_INPUT,\n message,\n ErrorCategories.VALIDATION,\n );\n }\n console.error(pc.red(message));\n console.log(\n pc.dim('Usage: caamp skills install <source> or caamp skills install --profile <name>'),\n );\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(\n operation,\n mvi,\n ErrorCodes.NETWORK_ERROR,\n message,\n ErrorCategories.TRANSIENT,\n );\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(\n parsed.owner,\n parsed.repo,\n parsed.ref,\n parsed.path,\n );\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(\n operation,\n mvi,\n ErrorCodes.NETWORK_ERROR,\n message,\n ErrorCategories.TRANSIENT,\n );\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 =\n 'No skill library registered. Register one with registerSkillLibraryFromPath() or set CAAMP_SKILL_LIBRARY env var.';\n if (format === 'json') {\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.INVALID_INPUT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n ` Found in catalog: ${pc.bold(catalogSkill.name)} v${catalogSkill.version} (${pc.dim(catalogSkill.category)})`,\n );\n }\n } else {\n const message = `Skill not found in catalog: ${parsed.inferredName}`;\n if (format === 'json') {\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.SKILL_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n availableSkills: catalog.listSkills(),\n },\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(\n operation,\n mvi,\n ErrorCodes.INVALID_FORMAT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n operation,\n mvi,\n ErrorCodes.INTERNAL_ERROR,\n message,\n ErrorCategories.INTERNAL,\n );\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n\n const result = await installSkill(localPath, skillName!, providers, opts.global ?? false);\n\n if (result.success) {\n // Record in lock file\n const isGlobal =\n 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 {\n name: skillName!,\n error: result.errors.join(', '),\n },\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}\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 =\n '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(\n operation,\n mvi,\n ErrorCodes.SKILL_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n availableProfiles: catalog.listProfiles(),\n },\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(skillDir, name, providers, isGlobal);\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 `\\n${pc.green(`${installed.length} installed`)}, ${failed.length > 0 ? pc.yellow(`${failed.length} failed`) : '0 failed'}`,\n );\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(\n ` Found: ${pc.bold(skill.name)} by ${skill.author} (${pc.dim(skill.repoFullName)})`,\n );\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 { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { simpleGit } from 'simple-git';\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 { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { simpleGit } from 'simple-git';\nimport { fetchWithTimeout } from '../network/fetch.js';\nimport type { GitFetchResult } from './github.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 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.map((p) => resolveProviderSkillsDir(p, 'project')).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(\n ` ${pc.cyan(num)}. ${pc.bold(skill.name.padEnd(30))} ${pc.dim(skill.metadata?.description ?? '')}`,\n );\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 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(\n async (\n name: string | undefined,\n opts: { global?: boolean; yes?: boolean; json?: boolean; human?: boolean },\n ) => {\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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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 =\n result.errors.length > 0 ? result.errors.map((err) => ({ message: err })) : 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","/**\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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n ` ${pc.bold(skill.name)} ${pc.dim(current)} ${pc.dim('->')} ${pc.cyan(latest)}`,\n );\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(\n parsed.owner,\n parsed.repo,\n parsed.ref,\n parsed.path,\n );\n localPath = result.localPath;\n cleanup = result.cleanup;\n } else {\n if (format === 'human') {\n console.log(\n pc.yellow(\n ` Skipped ${skill.name}: source type \"${parsed.type}\" does not support auto-update`,\n ),\n );\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 validate command - LAFS-compliant with JSON-first output\n */\n\nimport { resolveOutputFormat } from '@cleocode/lafs';\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport { buildEnvelope, ErrorCategories, ErrorCodes, emitJsonError } from '../../core/lafs.js';\nimport { isHuman } from '../../core/logger.js';\nimport { validateSkill } from '../../core/skills/validator.js';\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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\n process.exit(1);\n }\n\n let result: import('../../core/skills/validator.js').ValidationResult;\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(\n operation,\n mvi,\n ErrorCodes.FILE_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n path,\n },\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 { registerSkillsAudit } from './audit.js';\nimport { registerSkillsCheck } from './check.js';\nimport { registerSkillsFind } from './find.js';\nimport { registerSkillsInit } from './init.js';\nimport { registerSkillsInstall } from './install.js';\nimport { registerSkillsList } from './list.js';\nimport { registerSkillsRemove } from './remove.js';\nimport { registerSkillsUpdate } from './update.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.command('skills').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,IA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Q,OAAuB;AACtC,MAAI,iBAAiB,MAAO,QAAO;AACnC,SAAO,IAAI,MAAM,OAAO,KAAK,CAAC;AAChC;AAEA,SAAS,YACP,OACA,QACM;AACN,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","randomUUID","resolveOutputFormat","pc","program","resolveOutputFormat","emitJsonError","buildEnvelope","pc","canonical","hooks","randomUUID","existsSync","pc","existsSync","summary","pc","pc","pc","randomUUID","resolveOutputFormat","pc","resolveOutputFormat","emitJsonError","pc","buildEnvelope","randomUUID","existsSync","join","pc","join","existsSync","pc","existsSync","pc","join","join","mkdtemp","rm","tmpdir","join","simpleGit","mkdtemp","join","tmpdir","simpleGit","rm","emitError","pc","existsSync","randomUUID","resolveOutputFormat","pc","resolveOutputFormat","emitJsonError","pc","buildEnvelope","randomUUID","pc","pc","pc","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/batch.ts","../src/commands/advanced/instructions.ts","../src/commands/advanced/providers.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/check.ts","../src/commands/instructions/inject.ts","../src/commands/instructions/update.ts","../src/commands/instructions/index.ts","../src/commands/providers.ts","../src/commands/skills/audit.ts","../src/commands/skills/check.ts","../src/commands/skills/find.ts","../src/commands/skills/init.ts","../src/commands/skills/install.ts","../src/core/sources/github.ts","../src/core/sources/gitlab.ts","../src/commands/skills/list.ts","../src/commands/skills/remove.ts","../src/commands/skills/update.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 { 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);\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(\n error: unknown,\n source: 'uncaughtException' | 'unhandledRejection' | 'cli',\n): 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 { SkillBatchOperation } from '../../core/advanced/orchestration.js';\nimport { resolveDefaultTargetProviders } from '../../core/harness/index.js';\nimport { getAllProviders, getProvider } from '../../core/registry/providers.js';\nimport type { Provider, ProviderPriority } from '../../types.js';\nimport { LAFSCommandError } from './lafs.js';\n\nconst VALID_PRIORITIES = new Set<ProviderPriority>(['primary', '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: primary, 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 resolveDefaultTargetProviders();\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 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 LAFSError,\n type LAFSErrorCategory,\n type LAFSMeta,\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 batch command\n */\n\nimport type { Command } from 'commander';\nimport {\n installBatchWithRollback,\n selectProvidersByMinimumPriority,\n} from '../../core/advanced/orchestration.js';\nimport { parsePriority, 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 skills.\n *\n * @remarks\n * Installs skills from a JSON file 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 --skills-file skills.json\n * caamp advanced batch --skills-file skills.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 skills')\n .option(\n '-a, --agent <name>',\n 'Target specific provider(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\n .option('--all', 'Use all registry providers (not only detected)')\n .option('--min-tier <tier>', 'Minimum priority tier: high|medium|low', 'low')\n .requiredOption('--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(\n async (opts: {\n agent: string[];\n all?: boolean;\n minTier: string;\n skillsFile: string;\n projectDir?: string;\n details?: boolean;\n }) =>\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 skills = await readSkillOperations(opts.skillsFile);\n\n if (skills.length === 0) {\n throw new LAFSCommandError(\n 'E_ADVANCED_VALIDATION_NO_OPS',\n 'No operations provided.',\n 'Provide a --skills-file with at least one operation.',\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 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 skills with rollback safety',\n constraints: {\n minimumPriority,\n providerCount: providers.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 skillsApplied: result.skillsApplied,\n rollbackPerformed: result.rollbackPerformed,\n },\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(\n '-a, --agent <name>',\n 'Target specific provider(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\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(\n 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 }) =>\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 =\n 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","/**\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(\n '-a, --agent <name>',\n 'Target specific provider(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\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: { agent: string[]; all?: boolean; minTier: string; 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.capabilities.mcp?.configFormat ?? null,\n })),\n };\n }),\n );\n}\n","/**\n * Advanced orchestration command group providing LAFS-compliant wrappers for batch operations,\n * provider selection, and instruction management.\n *\n * @packageDocumentation\n */\n\nimport type { Command } from 'commander';\nimport { registerAdvancedBatch } from './batch.js';\nimport { registerAdvancedInstructions } from './instructions.js';\nimport { registerAdvancedProviders } from './providers.js';\n\n/**\n * Registers the `advanced` command group with providers, batch, and instructions 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 --skills-file skills.json\n * caamp advanced instructions --content \"## Setup\" --all\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 registerAdvancedInstructions(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 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.command('config').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(\n 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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n operation,\n mvi,\n ErrorCodes.PROVIDER_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n providerId,\n },\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 mcp = provider.capabilities.mcp;\n if (!mcp) {\n const message = `${provider.toolName} has no MCP config integration (extension-based harness)`;\n if (format === 'json') {\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.PROVIDER_NOT_FOUND,\n message,\n ErrorCategories.VALIDATION,\n { providerId },\n );\n } else {\n console.log(pc.dim(message));\n }\n process.exit(1);\n }\n const configPath = resolveProviderConfigPath(provider, scope) ?? mcp.configPathGlobal;\n\n if (!existsSync(configPath)) {\n const message = `No config file at: ${configPath}`;\n if (format === 'json') {\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.FILE_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n configPath,\n scope,\n },\n );\n } else {\n console.log(pc.dim(message));\n }\n process.exit(1);\n }\n\n try {\n const data = await readConfig(configPath, mcp.configFormat);\n\n if (format === 'json') {\n outputSuccess(operation, mvi, {\n provider: provider.id,\n config: data,\n format: mcp.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(\n operation,\n mvi,\n ErrorCodes.FILE_SYSTEM_ERROR,\n message,\n ErrorCategories.INTERNAL,\n );\n } else {\n console.error(pc.red(message));\n }\n process.exit(1);\n }\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 const mcp = provider.capabilities.mcp;\n if (!mcp) {\n console.error(\n pc.red(`${provider.toolName} has no MCP config integration (extension-based harness)`),\n );\n process.exit(1);\n }\n\n if (scope === 'global') {\n console.log(mcp.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(mcp.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 { LAFSError, LAFSErrorCategory, LAFSMeta, LAFSPage, Warning } 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 ErrorCategories,\n ErrorCodes,\n emitJsonError,\n handleFormatError,\n outputSuccess,\n resolveFormat,\n} from '../core/lafs.js';\nimport { readLockFile } from '../core/lock-utils.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';\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 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 // Core fields must exist on every provider. MCP fields only apply to\n // providers that declare `capabilities.mcp`; providers without MCP\n // integration (like Pi, which uses extensions) are valid without them.\n if (!p.id || !p.toolName) {\n malformed.push(p.id || '(unknown)');\n continue;\n }\n const mcp = p.capabilities.mcp;\n if (mcp && (!mcp.configKey || !mcp.configFormat)) {\n malformed.push(p.id);\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/') || 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\n/**\n * Validate the CAAMP skills lock file integrity.\n *\n * @remarks\n * Checks the lock file for skill-installation drift in three dimensions:\n * orphaned entries (lock-tracked but missing from disk), untracked skills\n * (on disk but not in lock), and agent-list mismatches (lock claims a\n * provider symlink that no longer exists). Lock-file IO errors surface as\n * a `'fail'` check, which causes the doctor command to exit non-zero.\n *\n * @returns Section result with one or more lock-file health checks\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:\n mismatches.slice(0, 5).join(', ') +\n (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 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 mcp = provider.capabilities.mcp;\n if (!mcp) {\n checks.push({\n label: `${provider.id}: no MCP integration (extension-based harness)`,\n status: 'pass',\n });\n continue;\n }\n const configPath = mcp.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, mcp.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 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((p) => {\n if (!p.id || !p.toolName) return true;\n const mcp = p.capabilities.mcp;\n return mcp !== null && (!mcp.configKey || !mcp.configFormat);\n }).length;\n const detectionResults = detectAllProviders();\n const installedProviders = detectionResults.filter((r) => r.installed);\n const { canonicalCount, brokenCount, staleCount } = countSkillIssues();\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 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/') || 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","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 check command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport { resolveDefaultTargetProviders } from '../../core/harness/index.js';\nimport { checkAllInjections } from '../../core/instructions/injector.js';\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from '../../core/lafs.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(\n '-a, --agent <name>',\n 'Check specific agent(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\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(\n 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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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 = resolveDefaultTargetProviders();\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","/**\n * instructions inject command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport {\n getHarnessFor,\n type HarnessScope,\n resolveDefaultTargetProviders,\n} from '../../core/harness/index.js';\nimport { injectAll } from '../../core/instructions/injector.js';\nimport {\n generateInjectionContent,\n groupByInstructFile,\n} from '../../core/instructions/templates.js';\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from '../../core/lafs.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(\n '-a, --agent <name>',\n 'Target specific agent(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\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(\n 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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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 = resolveDefaultTargetProviders();\n }\n\n if (providers.length === 0) {\n const message = 'No providers found.';\n if (format === 'json') {\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.PROVIDER_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n );\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 // Split targets into harness-backed providers and generic providers\n // so that each harness's native injection path is used when\n // available, while generic providers continue through the shared\n // marker-based injector.\n const harnessProviders: Provider[] = [];\n const genericProviders: Provider[] = [];\n for (const p of providers) {\n if (getHarnessFor(p) !== null) {\n harnessProviders.push(p);\n } else {\n genericProviders.push(p);\n }\n }\n\n const results: Map<string, 'created' | 'added' | 'consolidated' | 'updated' | 'intact'> =\n new Map();\n const harnessScope: HarnessScope =\n scope === 'global' ? { kind: 'global' } : { kind: 'project', projectDir: process.cwd() };\n for (const provider of harnessProviders) {\n const harness = getHarnessFor(provider);\n if (harness === null) continue;\n try {\n await harness.injectInstructions(content, harnessScope);\n // Harness does not report back a file-level action; record a\n // synthetic \"updated\" entry keyed by provider id so downstream\n // reporting has something to show.\n results.set(`${provider.id}:AGENTS.md`, 'updated');\n } catch (err) {\n if (format === 'human') {\n console.log(\n pc.red(` x ${provider.id}: ${err instanceof Error ? err.message : String(err)}`),\n );\n }\n }\n }\n\n if (genericProviders.length > 0) {\n const genericResults = await injectAll(genericProviders, process.cwd(), scope, content);\n for (const [file, action] of genericResults) {\n results.set(file, action);\n }\n }\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 =\n action === 'created'\n ? pc.green('+')\n : action === 'updated'\n ? 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","/**\n * instructions update command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport {\n getHarnessFor,\n type HarnessScope,\n resolveDefaultTargetProviders,\n} from '../../core/harness/index.js';\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 type { Provider } from '../../types.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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\n process.exit(1);\n }\n\n const providers = resolveDefaultTargetProviders();\n const scope = opts.global ? ('global' as const) : ('project' as const);\n const content = generateInjectionContent();\n\n // Split harness-backed providers from generic providers: harness\n // providers own their own instruction file lifecycle and are\n // unconditionally refreshed via `injectInstructions`; generic\n // providers still go through the shared marker-based injector.\n const harnessProviders: Provider[] = [];\n const genericProviders: Provider[] = [];\n for (const provider of providers) {\n if (getHarnessFor(provider) !== null) {\n harnessProviders.push(provider);\n } else {\n genericProviders.push(provider);\n }\n }\n\n // Check current state for generic providers only — the harness\n // injection path is idempotent and ownership-clean, so we always\n // refresh its block.\n const checks = await checkAllInjections(genericProviders, process.cwd(), scope, content);\n const needsUpdate = checks.filter((c) => c.status !== 'current');\n\n if (harnessProviders.length === 0 && 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' && needsUpdate.length > 0) {\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 generic providers to only those needing updates.\n const providerIds = new Set(needsUpdate.map((c) => c.provider));\n const toUpdate = genericProviders.filter((p) => providerIds.has(p.id));\n\n const results = await injectAll(toUpdate, process.cwd(), scope, content);\n\n // Refresh harness instruction blocks unconditionally.\n const harnessScope: HarnessScope =\n scope === 'global' ? { kind: 'global' } : { kind: 'project', projectDir: process.cwd() };\n const harnessFailures: Array<{ provider: string; error: string }> = [];\n for (const provider of harnessProviders) {\n const harness = getHarnessFor(provider);\n if (harness === null) continue;\n try {\n await harness.injectInstructions(content, harnessScope);\n results.set(`${provider.id}:AGENTS.md`, 'updated');\n } catch (err) {\n harnessFailures.push({\n provider: provider.id,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\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 for (const failure of harnessFailures) {\n console.log(` ${pc.red('x')} ${failure.provider}: ${failure.error}`);\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: harnessFailures,\n count: { updated: updated.length, failed: harnessFailures.length },\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 { registerInstructionsCheck } from './check.js';\nimport { registerInstructionsInject } from './inject.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 * 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 {\n buildHookMatrix,\n CANONICAL_HOOK_EVENTS,\n getCommonEvents,\n getHookMappingsVersion,\n getHookSupport,\n getProviderSummary,\n translateToAll,\n} from '../core/hooks/index.js';\nimport type { CanonicalHookEvent } from '../core/hooks/types.js';\nimport { isHuman } from '../core/logger.js';\nimport { detectAllProviders, detectProjectProviders } from '../core/registry/detection.js';\nimport {\n buildSkillsMap,\n getAllProviders,\n getProvider,\n getProviderCount,\n getProvidersByPriority,\n getRegistryVersion,\n providerSupports,\n} from '../core/registry/providers.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.command('providers').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 =\n tier === 'high'\n ? pc.green('HIGH')\n : tier === 'medium'\n ? pc.yellow('MEDIUM')\n : pc.dim('LOW');\n console.log(`${tierLabel} priority:`);\n\n for (const p of tierProviders) {\n const status =\n p.status === 'active'\n ? pc.green('active')\n : p.status === 'beta'\n ? pc.yellow('beta')\n : pc.dim(p.status);\n\n console.log(\n ` ${pc.bold(p.agentFlag.padEnd(20))} ${p.toolName.padEnd(22)} ${p.vendor.padEnd(16)} [${status}]`,\n );\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 ? detectProjectProviders(process.cwd()) : 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(\n ` ${pc.green('✓')} ${pc.bold(r.provider.toolName.padEnd(22))} via ${pc.dim(methods)}${project}`,\n );\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 const mcp = provider.capabilities.mcp;\n if (mcp) {\n console.log(` Config format: ${mcp.configFormat}`);\n console.log(` Config key: ${mcp.configKey}`);\n console.log(` Transports: ${mcp.supportedTransports.join(', ')}`);\n console.log(` Headers: ${mcp.supportsHeaders ? 'yes' : 'no'}`);\n } else {\n console.log(` MCP integration: ${pc.dim('(none — extension-based harness)')}`);\n }\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 if (mcp) {\n console.log(` Global config: ${mcp.configPathGlobal}`);\n console.log(` Project config: ${mcp.configPathProject || '(none)'}`);\n }\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.command('hooks').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.map((p) => getProviderSummary(p.id)).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(\n ` ${'─'.repeat(22)} ${'─'.repeat(10)} ${'─'.repeat(12)} ${'─'.repeat(12)} ${'─'.repeat(20)}`,\n );\n\n for (const s of summaries) {\n if (!s) continue;\n const system =\n s.hookSystem === 'none'\n ? pc.dim('none')\n : s.experimental\n ? pc.yellow(s.hookSystem + '*')\n : pc.green(s.hookSystem);\n const coverage =\n s.coverage > 0\n ? (s.coverage >= 75 ? pc.green : s.coverage >= 40 ? pc.yellow : pc.dim)(\n `${s.coverage}%`,\n )\n : pc.dim('0%');\n const supported =\n s.supportedCount > 0 ? `${s.supportedCount}/${s.totalCanonical}` : 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(\n pc.dim(\n `\\n ${withHooks.length} providers with hook support, ${summaries.length - withHooks.length} without`,\n ),\n );\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\n .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 })\n .join('');\n\n console.log(` ${event.padEnd(22)} ${cells}`);\n }\n\n // Common events\n const commonEvents = getCommonEvents(matrix.providers);\n console.log(\n pc.dim(`\\n Common events: ${commonEvents.length > 0 ? commonEvents.join(', ') : 'none'}`),\n );\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(\n async (\n event: string,\n opts: { to?: string; from?: string; json?: boolean; human?: boolean },\n ) => {\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(\n operation,\n mvi,\n {\n direction: 'canonical-to-native',\n providerId: opts.to,\n ...result,\n },\n null,\n );\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(\n operation,\n mvi,\n {\n direction: 'native-to-canonical',\n native: event,\n providerId: opts.from,\n canonical,\n supported: canonical !== null,\n },\n null,\n );\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 `\\n ${pc.bold(event)} (${opts.from}) → ${pc.dim('no canonical mapping (provider-only event)')}`,\n );\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(\n operation,\n mvi,\n {\n direction: 'canonical-to-all',\n canonical: event,\n translations,\n supportedCount: Object.keys(translations).length,\n totalProviders: allIds.length,\n },\n null,\n );\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\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(\n '--filter <path>',\n 'Filter to providers supporting a capability dot-path (e.g. spawn.supportsSubagents)',\n )\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 audit command - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync, statSync } 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 { 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(\n JSON.stringify(\n {\n $schema:\n 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',\n version: '2.1.0',\n runs: [\n {\n tool: { driver: { name: 'caamp-skills-audit' } },\n invocations: [\n {\n executionSuccessful: false,\n exitCode: 1,\n exitCodeDescription: message,\n },\n ],\n results: [],\n },\n ],\n },\n null,\n 2,\n ),\n );\n } else {\n // LAFS envelope error\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.FILE_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n path,\n },\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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n JSON.stringify(\n {\n $schema:\n 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',\n version: '2.1.0',\n runs: [\n {\n tool: { driver: { name: 'caamp-skills-audit' } },\n invocations: [\n {\n executionSuccessful: false,\n exitCode: 1,\n exitCodeDescription: message,\n },\n ],\n results: [],\n },\n ],\n },\n null,\n 2,\n ),\n );\n } else {\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.AUDIT_FAILED,\n message,\n ErrorCategories.INTERNAL,\n {\n path,\n },\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 =\n f.rule.severity === 'critical'\n ? pc.red(f.rule.severity)\n : f.rule.severity === 'high'\n ? pc.red(f.rule.severity)\n : f.rule.severity === 'medium'\n ? 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 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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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 find command - marketplace search + recommendation mode\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { type LAFSErrorCategory, resolveOutputFormat } from '@cleocode/lafs';\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport type { MVILevel } from '../../core/lafs.js';\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(\n '--must-have <term>',\n 'Required criteria term',\n (value, previous: string[]) => [...previous, value],\n [],\n )\n .option(\n '--prefer <term>',\n 'Preferred criteria term',\n (value, previous: string[]) => [...previous, value],\n [],\n )\n .option(\n '--exclude <term>',\n 'Excluded criteria term',\n (value, previous: string[]) => [...previous, value],\n [],\n )\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 =\n selectedRanks.length > 0\n ? options.filter((option) => selectedRanks.includes(option.rank))\n : [];\n\n if (format === 'json') {\n const result = formatSkillRecommendations(recommendation, {\n mode: 'json',\n details,\n }) 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, {\n mode: 'human',\n details,\n }) 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 ??\n 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(\n RECOMMENDATION_ERROR_CODES.QUERY_INVALID,\n '--top must be an integer between 1 and 20',\n );\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(\n query: string | undefined,\n mustHave: string[],\n prefer: string[],\n exclude: string[],\n): 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(\n ranking: RankedSkillRecommendation[],\n details: boolean,\n): 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>(\n operation: string,\n mvi: 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: 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 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(\n 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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n operation,\n mvi,\n ErrorCodes.INVALID_CONSTRAINT,\n message,\n ErrorCategories.CONFLICT,\n {\n path: skillDir,\n },\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","/**\n * skills install command - LAFS-compliant with JSON-first output\n */\n\nimport { existsSync } from 'node:fs';\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport {\n dispatchInstallSkillAcrossProviders,\n resolveDefaultTargetProviders,\n} from '../../core/harness/index.js';\nimport {\n buildEnvelope,\n ErrorCategories,\n ErrorCodes,\n emitError,\n emitJsonError,\n type MVILevel,\n outputSuccess,\n resolveFormat,\n} from '../../core/lafs.js';\nimport { MarketplaceClient } from '../../core/marketplace/client.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 { 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(\n '-a, --agent <name>',\n 'Target specific agent(s)',\n (v, prev: string[]) => [...prev, v],\n [],\n )\n .option('-g, --global', 'Install globally')\n .option('-y, --yes', 'Skip confirmation')\n .option('--all', 'Install to all detected agents')\n .option(\n '--profile <name>',\n 'Install a skill library profile (minimal, core, recommended, full)',\n )\n .option('--json', 'Output as JSON (default)')\n .option('--human', 'Output in human-readable format')\n .action(\n async (\n source: string | undefined,\n opts: {\n agent: string[];\n global?: boolean;\n yes?: boolean;\n all?: boolean;\n profile?: string;\n json?: boolean;\n human?: boolean;\n },\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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\n process.exit(1);\n }\n\n // Determine target providers. Default (no --agent, no --all) prefers\n // the registry's primary harness when it is installed; otherwise it\n // falls back to the legacy installed-providers list.\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 = resolveDefaultTargetProviders();\n }\n\n if (providers.length === 0) {\n const message = 'No target providers found. Use --agent or --all.';\n if (format === 'json') {\n emitError(\n operation,\n mvi,\n ErrorCodes.PROVIDER_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n );\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(\n opts.profile,\n providers,\n opts.global ?? false,\n format,\n operation,\n mvi,\n );\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(\n operation,\n mvi,\n ErrorCodes.INVALID_INPUT,\n message,\n ErrorCategories.VALIDATION,\n );\n }\n console.error(pc.red(message));\n console.log(\n pc.dim('Usage: caamp skills install <source> or caamp skills install --profile <name>'),\n );\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(\n operation,\n mvi,\n ErrorCodes.NETWORK_ERROR,\n message,\n ErrorCategories.TRANSIENT,\n );\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(\n parsed.owner,\n parsed.repo,\n parsed.ref,\n parsed.path,\n );\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(\n operation,\n mvi,\n ErrorCodes.NETWORK_ERROR,\n message,\n ErrorCategories.TRANSIENT,\n );\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 =\n 'No skill library registered. Register one with registerSkillLibraryFromPath() or set CAAMP_SKILL_LIBRARY env var.';\n if (format === 'json') {\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.INVALID_INPUT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n ` Found in catalog: ${pc.bold(catalogSkill.name)} v${catalogSkill.version} (${pc.dim(catalogSkill.category)})`,\n );\n }\n } else {\n const message = `Skill not found in catalog: ${parsed.inferredName}`;\n if (format === 'json') {\n emitJsonError(\n operation,\n mvi,\n ErrorCodes.SKILL_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n availableSkills: catalog.listSkills(),\n },\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(\n operation,\n mvi,\n ErrorCodes.INVALID_FORMAT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n operation,\n mvi,\n ErrorCodes.INTERNAL_ERROR,\n message,\n ErrorCategories.INTERNAL,\n );\n }\n console.error(pc.red(message));\n process.exit(1);\n }\n\n const result = await dispatchInstallSkillAcrossProviders(\n localPath,\n skillName!,\n providers,\n opts.global ?? false,\n );\n\n if (result.success) {\n // Record in lock file\n const isGlobal =\n 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 {\n name: skillName!,\n error: result.errors.join(', '),\n },\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}\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 =\n '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(\n operation,\n mvi,\n ErrorCodes.SKILL_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n availableProfiles: catalog.listProfiles(),\n },\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 dispatchInstallSkillAcrossProviders(skillDir, name, providers, isGlobal);\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 `\\n${pc.green(`${installed.length} installed`)}, ${failed.length > 0 ? pc.yellow(`${failed.length} failed`) : '0 failed'}`,\n );\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(\n ` Found: ${pc.bold(skill.name)} by ${skill.author} (${pc.dim(skill.repoFullName)})`,\n );\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 { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { simpleGit } from 'simple-git';\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 { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { simpleGit } from 'simple-git';\nimport { fetchWithTimeout } from '../network/fetch.js';\nimport type { GitFetchResult } from './github.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 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 { resolveDefaultTargetProviders } from '../../core/harness/index.js';\nimport { isHuman } from '../../core/logger.js';\nimport { resolveProviderSkillsDir } from '../../core/paths/standard.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 = resolveDefaultTargetProviders();\n dirs = providers.map((p) => resolveProviderSkillsDir(p, 'global')).filter(Boolean);\n } else {\n const providers = resolveDefaultTargetProviders();\n dirs = providers.map((p) => resolveProviderSkillsDir(p, 'project')).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(\n ` ${pc.cyan(num)}. ${pc.bold(skill.name.padEnd(30))} ${pc.dim(skill.metadata?.description ?? '')}`,\n );\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 remove command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport {\n dispatchRemoveSkillAcrossProviders,\n resolveDefaultTargetProviders,\n} from '../../core/harness/index.js';\nimport {\n ErrorCategories,\n ErrorCodes,\n emitJsonError,\n outputSuccess,\n resolveFormat,\n} from '../../core/lafs.js';\nimport { isHuman } from '../../core/logger.js';\nimport { listCanonicalSkills } 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(\n async (\n name: string | undefined,\n opts: { global?: boolean; yes?: boolean; json?: boolean; human?: boolean },\n ) => {\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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\n process.exit(1);\n }\n\n const providers = resolveDefaultTargetProviders();\n\n if (name) {\n const result = await dispatchRemoveSkillAcrossProviders(\n name,\n providers,\n opts.global ?? false,\n );\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 =\n result.errors.length > 0 ? result.errors.map((err) => ({ message: err })) : 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","/**\n * skills update command - LAFS-compliant with JSON-first output\n */\n\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport { dispatchInstallSkillAcrossProviders } from '../../core/harness/index.js';\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 { 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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\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(\n ` ${pc.bold(skill.name)} ${pc.dim(current)} ${pc.dim('->')} ${pc.cyan(latest)}`,\n );\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(\n parsed.owner,\n parsed.repo,\n parsed.ref,\n parsed.path,\n );\n localPath = result.localPath;\n cleanup = result.cleanup;\n } else {\n if (format === 'human') {\n console.log(\n pc.yellow(\n ` Skipped ${skill.name}: source type \"${parsed.type}\" does not support auto-update`,\n ),\n );\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 dispatchInstallSkillAcrossProviders(\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 validate command - LAFS-compliant with JSON-first output\n */\n\nimport { resolveOutputFormat } from '@cleocode/lafs';\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport { buildEnvelope, ErrorCategories, ErrorCodes, emitJsonError } from '../../core/lafs.js';\nimport { isHuman } from '../../core/logger.js';\nimport { validateSkill } from '../../core/skills/validator.js';\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(\n operation,\n mvi,\n ErrorCodes.FORMAT_CONFLICT,\n message,\n ErrorCategories.VALIDATION,\n );\n process.exit(1);\n }\n\n let result: import('../../core/skills/validator.js').ValidationResult;\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(\n operation,\n mvi,\n ErrorCodes.FILE_NOT_FOUND,\n message,\n ErrorCategories.NOT_FOUND,\n {\n path,\n },\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 { registerSkillsAudit } from './audit.js';\nimport { registerSkillsCheck } from './check.js';\nimport { registerSkillsFind } from './find.js';\nimport { registerSkillsInit } from './init.js';\nimport { registerSkillsInstall } from './install.js';\nimport { registerSkillsList } from './list.js';\nimport { registerSkillsRemove } from './remove.js';\nimport { registerSkillsUpdate } from './update.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.command('skills').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);\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C;","names":["program","randomUUID","randomUUID","emitError","program","existsSync","join","pc","existsSync","join","pc","program","pc","pc","pc","pc","pc","pc","program","randomUUID","resolveOutputFormat","pc","program","resolveOutputFormat","emitJsonError","buildEnvelope","pc","canonical","hooks","randomUUID","existsSync","pc","existsSync","summary","pc","pc","pc","randomUUID","resolveOutputFormat","pc","resolveOutputFormat","emitJsonError","pc","buildEnvelope","randomUUID","existsSync","join","pc","join","existsSync","pc","existsSync","pc","join","join","mkdtemp","rm","tmpdir","join","simpleGit","mkdtemp","join","tmpdir","simpleGit","rm","emitError","pc","existsSync","randomUUID","resolveOutputFormat","pc","resolveOutputFormat","emitJsonError","pc","buildEnvelope","randomUUID","pc","pc","pc","pc","resolveOutputFormat","pc","resolveOutputFormat","pc","program"]}
|