@cleocode/caamp 2026.4.6 → 2026.4.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -8
- package/dist/{chunk-43GULI6J.js → chunk-JC77OAHA.js} +1766 -400
- package/dist/chunk-JC77OAHA.js.map +1 -0
- package/dist/cli.js +1420 -71
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +1860 -293
- package/dist/index.js +29 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/dist/chunk-43GULI6J.js.map +0 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/commands/advanced/common.ts","../src/commands/advanced/lafs.ts","../src/commands/advanced/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);\n registerSkillsAudit(skills);\n registerSkillsValidate(skills);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,eAAe;;;ACFxB,SAAS,gBAAgB;;;ACAzB,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,OAKK;AAyBA,IAAM,mBAAN,cAA+B,MAAM;AAAA;AAAA,EAE1C;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAEA,YACE,MACA,SACA,YACA,cAAc,MACd,SACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW,mBAAmB,IAAI;AACvC,SAAK,cAAc;AACnB,SAAK,aAAa;AAClB,SAAK,eAAe;AACpB,SAAK,UAAU;AAAA,EACjB;AACF;AAEA,SAAS,mBAAmB,MAAiC;AAC3D,MAAI,KAAK,SAAS,YAAY,EAAG,QAAO;AACxC,MAAI,KAAK,SAAS,WAAW,EAAG,QAAO;AACvC,MAAI,KAAK,SA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,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/mcp/common.ts","../src/commands/mcp/detect.ts","../src/commands/mcp/install.ts","../src/commands/mcp/list.ts","../src/commands/mcp/remove.ts","../src/commands/mcp/index.ts","../src/commands/pi/cant.ts","../src/core/sources/github.ts","../src/core/sources/gitlab.ts","../src/commands/pi/common.ts","../src/commands/pi/extensions.ts","../src/commands/pi/models.ts","../src/commands/pi/prompts.ts","../src/commands/pi/sessions.ts","../src/commands/pi/themes.ts","../src/commands/pi/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/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 { registerMcpCommands } from './commands/mcp/index.js';\nimport { registerPiCommands } from './commands/pi/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);\nregisterMcpCommands(program);\nregisterPiCommands(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 * Shared helpers for the `caamp mcp <verb>` command group.\n *\n * @remarks\n * Every `caamp mcp` verb has to:\n *\n * 1. Look up a provider in the registry and validate it declares an\n * `capabilities.mcp` block — bare instruction-only providers (Pi)\n * cannot be targets for MCP server installs.\n * 2. Resolve a `--scope project|global` option into the {@link McpScope}\n * type used by the underlying `core/mcp/*` library.\n * 3. Resolve a project directory for the `project` scope, honouring an\n * explicit `--project-dir` flag and falling back to `process.cwd()`.\n * 4. Throw {@link LAFSCommandError} for any caller-side validation\n * failure so the LAFS envelope carries a registered error code.\n *\n * This module centralises those steps so each verb file stays focused\n * on its own argument shaping and output construction.\n *\n * @packageDocumentation\n */\n\nimport type { McpScope } from '../../core/mcp/index.js';\nimport { getProvider } from '../../core/registry/providers.js';\nimport type { Provider } from '../../types.js';\nimport { LAFSCommandError } from '../advanced/lafs.js';\n\n/**\n * Canonical LAFS error codes used by the `caamp mcp` command group.\n *\n * @remarks\n * The `advanced/lafs.ts` emit path normalises any unregistered error\n * code to `E_INTERNAL_UNEXPECTED` — so every code thrown by the mcp\n * commands MUST come from the canonical LAFS error registry. The four\n * codes covered here are also the same set used by the `caamp pi`\n * command group, kept consistent so downstream tooling can rely on a\n * single error vocabulary across both groups.\n *\n * - `VALIDATION` — caller-supplied input failed validation\n * - `NOT_FOUND` — referenced resource (provider, file) does not exist\n * - `CONFLICT` — target server entry already exists without `--force`\n * - `TRANSIENT` — upstream operation failed and retry is viable\n *\n * @public\n */\nexport const MCP_ERROR_CODES = {\n /** Caller-supplied input failed validation (shape, type, enum). */\n VALIDATION: 'E_VALIDATION_SCHEMA',\n /** Referenced resource does not exist on disk or in the registry. */\n NOT_FOUND: 'E_NOT_FOUND_RESOURCE',\n /** Server entry already exists and overwrite was not requested. */\n CONFLICT: 'E_CONFLICT_VERSION',\n /** Upstream operation failed; retry is viable. */\n TRANSIENT: 'E_TRANSIENT_UPSTREAM',\n} as const;\n\n/**\n * Standard option shape accepted by every `caamp mcp <verb>` command.\n *\n * @public\n */\nexport interface McpCommandBaseOptions {\n /** `--scope project|global` (default: project). */\n scope?: string;\n /** `--project-dir <path>` — override cwd for the `project` scope. */\n projectDir?: string;\n}\n\n/**\n * Look up an MCP-capable provider in the registry by id, throwing a\n * typed {@link LAFSCommandError} when the id is unknown or the\n * provider does not declare an MCP capability.\n *\n * @remarks\n * The \"no MCP capability\" check is treated as a NOT_FOUND error\n * rather than a VALIDATION error because it semantically means \"this\n * provider does not have an MCP config file to target\", not \"you\n * passed a malformed flag value\". The error message includes a\n * recovery hint pointing the caller at `caamp providers list` so\n * they can discover the right id.\n *\n * @param providerId - Raw provider id supplied via `--provider <id>`.\n * @returns The resolved {@link Provider} entry.\n * @throws `LAFSCommandError` when the provider is unknown or has no\n * MCP capability.\n *\n * @public\n */\nexport function requireMcpProvider(providerId: string): Provider {\n const provider = getProvider(providerId);\n if (provider === undefined) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.NOT_FOUND,\n `Unknown provider id: ${providerId}`,\n 'Run `caamp providers list` to see registered provider ids.',\n false,\n );\n }\n if (provider.capabilities.mcp === null) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.NOT_FOUND,\n `Provider ${providerId} does not declare an MCP capability.`,\n 'This provider does not consume MCP servers via a config file. Pick a different provider, or check `caamp providers list` for MCP-capable providers.',\n false,\n );\n }\n return provider;\n}\n\n/**\n * Parse and validate a `--scope` option value into a typed\n * {@link McpScope}.\n *\n * @remarks\n * Accepts `project`, `global`, or `undefined` — in which case the\n * `defaultScope` is returned. Any other value throws a typed\n * {@link LAFSCommandError} so the error envelope carries a meaningful\n * code rather than an opaque Commander error.\n *\n * @param raw - The raw option value from Commander (may be undefined).\n * @param defaultScope - Scope to use when `raw` is undefined.\n * @returns A resolved {@link McpScope}.\n * @throws `LAFSCommandError` when `raw` is set to an invalid value.\n *\n * @public\n */\nexport function parseScope(raw: string | undefined, defaultScope: McpScope): McpScope {\n if (raw === undefined) return defaultScope;\n if (raw === 'project' || raw === 'global') return raw;\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n `Invalid --scope value: ${raw}`,\n \"Use one of: 'project', 'global'.\",\n false,\n );\n}\n\n/**\n * Resolve the project directory used for the `project` scope.\n *\n * @remarks\n * Mirrors the `caamp pi` resolver: returns the explicit\n * `--project-dir` value when set, falls back to `process.cwd()`\n * otherwise, and returns `undefined` for the `global` scope so the\n * underlying core helpers can decline the project-dir argument\n * cleanly.\n *\n * @param scope - Resolved scope.\n * @param explicit - The raw `--project-dir` option value.\n * @returns Absolute project dir for `project`, else `undefined`.\n *\n * @public\n */\nexport function resolveProjectDir(\n scope: McpScope,\n explicit: string | undefined,\n): string | undefined {\n if (scope !== 'project') return undefined;\n if (explicit !== undefined && explicit.length > 0) return explicit;\n return process.cwd();\n}\n\n/**\n * Parse a single `--env KEY=VALUE` option value into a `[key, value]`\n * pair, throwing a typed validation error when the shape is wrong.\n *\n * @remarks\n * The MCP install verb takes a repeatable `--env KEY=VALUE` flag and\n * accumulates the parsed pairs into the `env` field of the\n * {@link McpServerConfig} payload. Splitting and validating happens\n * here so the verb's action body can stay declarative.\n *\n * @param raw - Single `KEY=VALUE` token from Commander.\n * @returns Tuple of `[key, value]`.\n * @throws `LAFSCommandError` when the token is malformed.\n *\n * @public\n */\nexport function parseEnvAssignment(raw: string): [string, string] {\n const idx = raw.indexOf('=');\n if (idx <= 0) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n `Invalid --env value: ${raw}`,\n 'Use KEY=VALUE format, e.g. --env GITHUB_TOKEN=ghp_...',\n false,\n );\n }\n const key = raw.slice(0, idx);\n const value = raw.slice(idx + 1);\n if (key.length === 0) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n `Invalid --env value: ${raw}`,\n 'KEY must be non-empty.',\n false,\n );\n }\n return [key, value];\n}\n","/**\n * `caamp mcp detect` command.\n *\n * @remarks\n * Auto-detects which providers on the current machine already have an\n * MCP config file on disk and reports the per-provider server count\n * and last-modified timestamp. Useful for onboarding (\"which tools on\n * my machine already have MCP configured?\") and for cross-checking\n * before running `caamp mcp install`.\n *\n * Iterates every MCP-capable provider in the registry, NOT just\n * \"installed\" providers — a config file may exist for a provider\n * whose binary is not on PATH (e.g. a stale config from a previous\n * install). The result envelope marks each entry with `exists` and\n * `serverCount` so callers can filter as needed.\n *\n * @packageDocumentation\n */\n\nimport type { Command } from 'commander';\nimport { detectMcpInstallations } from '../../core/mcp/index.js';\nimport { runLafsCommand } from '../advanced/lafs.js';\nimport { type McpCommandBaseOptions, parseScope, resolveProjectDir } from './common.js';\n\n/**\n * Options accepted by `caamp mcp detect`.\n *\n * @public\n */\nexport interface McpDetectOptions extends McpCommandBaseOptions {\n /** Show only providers that actually have a config file on disk. */\n onlyExisting?: boolean;\n}\n\n/**\n * Registers the `caamp mcp detect` subcommand.\n *\n * @param parent - Parent `mcp` Command to attach the subcommand to.\n *\n * @example\n * ```bash\n * caamp mcp detect\n * caamp mcp detect --scope global\n * caamp mcp detect --only-existing\n * ```\n *\n * @public\n */\nexport function registerMcpDetectCommand(parent: Command): void {\n parent\n .command('detect')\n .description('Detect which providers currently have MCP config files on disk')\n .option('--scope <scope>', 'Scope: project|global (default: project)')\n .option('--project-dir <path>', 'Project directory for the project scope (default: cwd)')\n .option('--only-existing', 'Only include providers whose config file exists on disk')\n .action(async (opts: McpDetectOptions) =>\n runLafsCommand('mcp.detect', 'standard', async () => {\n const scope = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(scope, opts.projectDir);\n\n const all = await detectMcpInstallations(scope, projectDir);\n const filtered = opts.onlyExisting === true ? all.filter((e) => e.exists) : all;\n const existingCount = filtered.filter((e) => e.exists).length;\n const totalServers = filtered.reduce((sum, e) => sum + (e.serverCount ?? 0), 0);\n\n return {\n scope,\n providersProbed: all.length,\n existingCount,\n totalServers,\n entries: filtered,\n };\n }),\n );\n}\n","/**\n * `caamp mcp install` command.\n *\n * @remarks\n * Installs an MCP server entry into a provider's config file. Two\n * input shapes are supported:\n *\n * 1. Inline command + args after a `--` sentinel:\n *\n * ```bash\n * caamp mcp install github --provider claude-desktop -- \\\n * npx -y @modelcontextprotocol/server-github\n * ```\n *\n * 2. JSON file containing a {@link McpServerConfig}:\n *\n * ```bash\n * caamp mcp install github --provider claude-desktop \\\n * --from ./github-mcp.json\n * ```\n *\n * `--env KEY=VALUE` is repeatable and contributes to the `env` field of\n * the resulting payload (overriding values from `--from` when both are\n * supplied). `--force` overwrites an existing entry; without it the\n * call returns a typed `E_CONFLICT_VERSION` envelope.\n *\n * The verb does NOT speak the MCP protocol — it just writes a JSON/\n * YAML/TOML record to the right location using the format-agnostic\n * substrate from `core/formats`.\n *\n * @packageDocumentation\n */\n\nimport { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport type { Command } from 'commander';\nimport { installMcpServer } from '../../core/mcp/index.js';\nimport type { McpServerConfig } from '../../types.js';\nimport { LAFSCommandError, runLafsCommand } from '../advanced/lafs.js';\nimport {\n MCP_ERROR_CODES,\n type McpCommandBaseOptions,\n parseEnvAssignment,\n parseScope,\n requireMcpProvider,\n resolveProjectDir,\n} from './common.js';\n\n/**\n * Options accepted by `caamp mcp install`.\n *\n * @public\n */\nexport interface McpInstallOptions extends McpCommandBaseOptions {\n /** Provider id to install into (required). */\n provider?: string;\n /** Optional path to a JSON file containing an `McpServerConfig`. */\n from?: string;\n /** Repeatable `KEY=VALUE` env assignments. */\n env?: string[];\n /** Overwrite an existing entry instead of failing. */\n force?: boolean;\n}\n\n/**\n * Validate that an arbitrary parsed JSON object is a usable\n * {@link McpServerConfig}.\n *\n * @remarks\n * Permissive validation: we accept any object with at least one of\n * `command`, `url`, or `type` because the MCP server config schema\n * across providers is loose (some require `command`, some accept\n * `url`-only remotes). The full transport-specific validation is the\n * downstream tool's responsibility — CAAMP just preserves the shape\n * the user supplied.\n *\n * @internal\n */\nfunction coerceServerConfig(value: unknown, source: string): McpServerConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n `${source} did not contain a JSON object.`,\n 'Pass an object with at least `command` or `url` (and optional `args`, `env`).',\n false,\n );\n }\n const obj = value as Record<string, unknown>;\n const hasCommand = typeof obj['command'] === 'string';\n const hasUrl = typeof obj['url'] === 'string';\n const hasType = typeof obj['type'] === 'string';\n if (!hasCommand && !hasUrl && !hasType) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n `${source} must contain at least one of: command, url, type.`,\n 'Provide either a stdio `command` (with optional `args`/`env`) or a remote `url`/`type`.',\n false,\n );\n }\n // Cast to the canonical shape — fields are optional in the type so any\n // subset of (command, args, env, url, type, headers) round-trips\n // through writeConfig untouched.\n return obj as McpServerConfig;\n}\n\n/**\n * Build the canonical {@link McpServerConfig} from the verb's input\n * sources, in this priority order:\n *\n * 1. Inline `command [args...]` after `--` (highest precedence for\n * transport shape).\n * 2. JSON loaded from `--from <file>` (used as a base).\n * 3. `--env KEY=VALUE` (merged on top of any env from the JSON file).\n *\n * @internal\n */\nasync function buildConfigFromOptions(\n inlineArgs: string[],\n opts: McpInstallOptions,\n): Promise<McpServerConfig> {\n let base: McpServerConfig | null = null;\n\n if (opts.from !== undefined && opts.from.length > 0) {\n if (!existsSync(opts.from)) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.NOT_FOUND,\n `--from file does not exist: ${opts.from}`,\n 'Check the path and try again.',\n false,\n );\n }\n let parsed: unknown;\n try {\n const content = await readFile(opts.from, 'utf8');\n parsed = JSON.parse(content);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n `Failed to read --from JSON: ${message}`,\n 'Ensure the file is valid JSON containing an MCP server config object.',\n false,\n );\n }\n base = coerceServerConfig(parsed, `--from ${opts.from}`);\n }\n\n if (inlineArgs.length > 0) {\n const command = inlineArgs[0];\n if (command === undefined || command.length === 0) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n 'Inline command was empty.',\n 'Pass `--` followed by a command, e.g. `-- npx -y @mcp/server-github`.',\n false,\n );\n }\n const args = inlineArgs.slice(1);\n base = {\n ...(base ?? {}),\n command,\n ...(args.length > 0 ? { args } : {}),\n };\n }\n\n if (base === null) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n 'Either an inline `-- <command> [args...]` or `--from <file>` is required.',\n 'Pass an MCP server definition via inline command or a JSON file.',\n false,\n );\n }\n\n if (opts.env !== undefined && opts.env.length > 0) {\n const env: Record<string, string> = { ...(base.env ?? {}) };\n for (const entry of opts.env) {\n const [k, v] = parseEnvAssignment(entry);\n env[k] = v;\n }\n base = { ...base, env };\n }\n\n return base;\n}\n\n/**\n * Registers the `caamp mcp install` subcommand.\n *\n * @param parent - Parent `mcp` Command to attach the subcommand to.\n *\n * @example\n * ```bash\n * # Inline form\n * caamp mcp install github --provider claude-desktop -- \\\n * npx -y @modelcontextprotocol/server-github\n *\n * # From file\n * caamp mcp install github --provider cursor --from ./github.json\n *\n * # With env vars\n * caamp mcp install github --provider claude-code \\\n * --env GITHUB_TOKEN=ghp_xxx -- \\\n * npx -y @modelcontextprotocol/server-github\n * ```\n *\n * @public\n */\nexport function registerMcpInstallCommand(parent: Command): void {\n parent\n .command('install <serverName> [args...]')\n .description('Install an MCP server entry into a provider config file')\n .option('--provider <id>', 'Provider id to install into (required)')\n .option('--from <file>', 'Path to a JSON file containing an MCP server config')\n .option(\n '--env <kv>',\n 'Repeatable env var KEY=VALUE',\n (value: string, prev: string[] = []) => [...prev, value],\n [] as string[],\n )\n .option('--scope <scope>', 'Scope: project|global (default: project)')\n .option('--force', 'Overwrite an existing server entry')\n .option('--project-dir <path>', 'Project directory for the project scope (default: cwd)')\n .action(async (serverName: string, inlineArgs: string[], opts: McpInstallOptions) =>\n runLafsCommand('mcp.install', 'standard', async () => {\n if (opts.provider === undefined || opts.provider.length === 0) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n '--provider <id> is required',\n 'Pass a provider id, e.g. --provider claude-desktop.',\n false,\n );\n }\n if (serverName.length === 0) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n 'Server name is required',\n 'Pass a non-empty server name as the first positional argument.',\n false,\n );\n }\n const provider = requireMcpProvider(opts.provider);\n const scope = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(scope, opts.projectDir);\n const config = await buildConfigFromOptions(inlineArgs, opts);\n\n const result = await installMcpServer(provider, serverName, config, {\n scope,\n force: opts.force ?? false,\n projectDir,\n });\n\n if (!result.installed && result.conflicted) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.CONFLICT,\n `Server ${serverName} already exists in ${result.sourcePath}`,\n 'Re-run with --force to overwrite the existing entry.',\n false,\n { sourcePath: result.sourcePath, providerId: result.providerId },\n );\n }\n\n return {\n installed: true,\n conflicted: result.conflicted,\n provider: provider.id,\n serverName,\n scope,\n sourcePath: result.sourcePath,\n config,\n };\n }),\n );\n}\n","/**\n * `caamp mcp list` command.\n *\n * @remarks\n * Two execution modes:\n *\n * - `--provider <id>` — list MCP servers for a single provider's\n * config file.\n * - (no flag) — fan out across every MCP-capable provider in\n * the registry.\n *\n * Both modes accept `--scope project|global` and `--project-dir <path>`.\n * Output is a LAFS envelope containing a `count`, an optional\n * `provider` summary (single-mode only), and an `entries` array.\n *\n * Missing config files are NOT errors — a provider with no MCP\n * servers installed simply contributes an empty section to the\n * result. The only error path is an unknown `--provider` id (or one\n * that does not declare an MCP capability), which is surfaced via\n * {@link requireMcpProvider} as a typed `E_NOT_FOUND_RESOURCE`.\n *\n * @packageDocumentation\n */\n\nimport type { Command } from 'commander';\nimport { listAllMcpServers, listMcpServers } from '../../core/mcp/index.js';\nimport type { McpServerEntry } from '../../types.js';\nimport { runLafsCommand } from '../advanced/lafs.js';\nimport {\n type McpCommandBaseOptions,\n parseScope,\n requireMcpProvider,\n resolveProjectDir,\n} from './common.js';\n\n/**\n * Options accepted by `caamp mcp list`.\n *\n * @public\n */\nexport interface McpListOptions extends McpCommandBaseOptions {\n /** Restrict the listing to a single provider id. */\n provider?: string;\n}\n\n/**\n * Registers the `caamp mcp list` subcommand.\n *\n * @param parent - Parent `mcp` Command to attach the subcommand to.\n *\n * @example\n * ```bash\n * caamp mcp list\n * caamp mcp list --provider claude-code\n * caamp mcp list --provider cursor --scope global\n * ```\n *\n * @public\n */\nexport function registerMcpListCommand(parent: Command): void {\n parent\n .command('list')\n .description('List MCP servers configured for one or every MCP-capable provider')\n .option('--provider <id>', 'Restrict to a single provider id')\n .option('--scope <scope>', 'Scope: project|global (default: project)')\n .option('--project-dir <path>', 'Project directory for the project scope (default: cwd)')\n .action(async (opts: McpListOptions) =>\n runLafsCommand('mcp.list', 'standard', async () => {\n const scope = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(scope, opts.projectDir);\n\n if (opts.provider !== undefined && opts.provider.length > 0) {\n const provider = requireMcpProvider(opts.provider);\n const entries = await listMcpServers(provider, scope, projectDir);\n return {\n scope,\n provider: {\n id: provider.id,\n toolName: provider.toolName,\n },\n count: entries.length,\n entries,\n };\n }\n\n const map = await listAllMcpServers(scope, projectDir);\n const flat: McpServerEntry[] = [];\n const byProvider: Record<string, number> = {};\n for (const [providerId, entries] of map.entries()) {\n byProvider[providerId] = entries.length;\n flat.push(...entries);\n }\n return {\n scope,\n providers: byProvider,\n count: flat.length,\n entries: flat,\n };\n }),\n );\n}\n","/**\n * `caamp mcp remove` command.\n *\n * @remarks\n * Two execution modes:\n *\n * - `--provider <id>` — remove a single server entry from a single\n * provider's config file (the common case).\n * - `--all-providers` — remove a server entry by name from every\n * MCP-capable provider in the registry that currently has it.\n *\n * Both modes are idempotent: when the entry is not present, the call\n * returns `removed: false` rather than throwing. The result envelope\n * always carries enough detail to render a precise human-readable\n * report.\n *\n * @packageDocumentation\n */\n\nimport type { Command } from 'commander';\nimport { removeMcpServer, removeMcpServerFromAll } from '../../core/mcp/index.js';\nimport { LAFSCommandError, runLafsCommand } from '../advanced/lafs.js';\nimport {\n MCP_ERROR_CODES,\n type McpCommandBaseOptions,\n parseScope,\n requireMcpProvider,\n resolveProjectDir,\n} from './common.js';\n\n/**\n * Options accepted by `caamp mcp remove`.\n *\n * @public\n */\nexport interface McpRemoveOptions extends McpCommandBaseOptions {\n /** Provider id to remove from (mutually exclusive with --all-providers). */\n provider?: string;\n /** Remove from every MCP-capable provider in the registry. */\n allProviders?: boolean;\n}\n\n/**\n * Registers the `caamp mcp remove` subcommand.\n *\n * @param parent - Parent `mcp` Command to attach the subcommand to.\n *\n * @example\n * ```bash\n * caamp mcp remove github --provider claude-desktop\n * caamp mcp remove github --provider cursor --scope global\n * caamp mcp remove github --all-providers\n * ```\n *\n * @public\n */\nexport function registerMcpRemoveCommand(parent: Command): void {\n parent\n .command('remove <serverName>')\n .description('Remove an MCP server entry from a provider config file')\n .option('--provider <id>', 'Provider id to remove from')\n .option('--all-providers', 'Remove from every MCP-capable provider in the registry')\n .option('--scope <scope>', 'Scope: project|global (default: project)')\n .option('--project-dir <path>', 'Project directory for the project scope (default: cwd)')\n .action(async (serverName: string, opts: McpRemoveOptions) =>\n runLafsCommand('mcp.remove', 'standard', async () => {\n if (serverName.length === 0) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n 'Server name is required',\n 'Pass a non-empty server name as the positional argument.',\n false,\n );\n }\n const usingAll = opts.allProviders === true;\n const usingProvider = opts.provider !== undefined && opts.provider.length > 0;\n if (usingAll === usingProvider) {\n throw new LAFSCommandError(\n MCP_ERROR_CODES.VALIDATION,\n 'Pass exactly one of --provider <id> or --all-providers',\n 'Use --provider for a single target, or --all-providers to remove everywhere.',\n false,\n );\n }\n\n const scope = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(scope, opts.projectDir);\n\n if (usingAll) {\n const results = await removeMcpServerFromAll(serverName, { scope, projectDir });\n const removedCount = results.filter((r) => r.removed).length;\n return {\n mode: 'all-providers',\n serverName,\n scope,\n removedCount,\n providersProbed: results.length,\n results,\n };\n }\n\n // usingProvider\n const provider = requireMcpProvider(opts.provider as string);\n const result = await removeMcpServer(provider, serverName, { scope, projectDir });\n return {\n mode: 'single-provider',\n serverName,\n scope,\n provider: provider.id,\n removed: result.removed,\n reason: result.reason,\n sourcePath: result.sourcePath,\n };\n }),\n );\n}\n","/**\n * `caamp mcp` command group — MCP server config management across\n * providers.\n *\n * @remarks\n * Per ADR-035, CAAMP exposes a small set of verbs for editing MCP\n * server entries inside the per-agent config files of every provider\n * that declares an `capabilities.mcp` block in `providers/registry.json`.\n *\n * This module is the single entry point for wiring every sub-verb\n * into the root `caamp` program. Each sub-verb owns its own\n * registration in the corresponding `commands/mcp/<verb>.ts` file and\n * exposes a `register*Command(parent)` function with the same shape as\n * the Wave-1 `caamp pi` verbs.\n *\n * The verbs do NOT speak the MCP protocol themselves — they just\n * read/write JSON/JSONC/YAML/TOML records via the format-agnostic\n * substrate from `core/formats`. Treat MCP server configs as plain\n * data records: `{ command, args?, env?, url?, type?, headers? }`.\n *\n * @packageDocumentation\n */\n\nimport type { Command } from 'commander';\nimport { registerMcpDetectCommand } from './detect.js';\nimport { registerMcpInstallCommand } from './install.js';\nimport { registerMcpListCommand } from './list.js';\nimport { registerMcpRemoveCommand } from './remove.js';\n\n/**\n * Register the `mcp` command group and all sub-verbs on the root\n * program.\n *\n * @remarks\n * Attaches `list`, `install`, `remove`, and `detect` under a single\n * parent `mcp` command. Verb ordering follows the natural workflow:\n * detect what is installed, list what is configured, install or\n * remove individual servers.\n *\n * @param program - The root Commander program to attach the `mcp`\n * group to.\n *\n * @example\n * ```bash\n * caamp mcp detect\n * caamp mcp list --provider claude-code\n * caamp mcp install github --provider claude-desktop -- npx -y @modelcontextprotocol/server-github\n * caamp mcp remove github --provider claude-desktop\n * ```\n *\n * @public\n */\nexport function registerMcpCommands(program: Command): void {\n const mcp = program.command('mcp').description('MCP server config management across providers');\n\n registerMcpDetectCommand(mcp);\n registerMcpListCommand(mcp);\n registerMcpInstallCommand(mcp);\n registerMcpRemoveCommand(mcp);\n}\n","/**\n * `caamp pi cant` command group.\n *\n * @remarks\n * Four verbs implementing ADR-035 §D5 (CANT single engine) for the Pi\n * harness:\n *\n * - `list` — walk every tier (project → user → global) and emit an\n * array of {@link CantProfileEntry} objects with shadow flags and\n * per-profile section counts.\n * - `install <source>` — copy a source `.cant` file (local path, GitHub\n * URL/shorthand, or remote HTTPS URL) into the target tier after\n * running it through cant-core's 42-rule validator.\n * - `remove <name>` — delete a named CANT profile from the target tier.\n * - `validate <path>` — pure validation helper that runs the 42-rule\n * engine against an arbitrary `.cant` file without installing it.\n *\n * Every verb follows the established LAFS envelope pattern via\n * {@link runLafsCommand}. Pi-absent detection happens inside\n * {@link requirePiHarness}, so each verb body only handles the happy\n * path plus verb-specific argument validation.\n *\n * The installed `.cant` files are consumed at runtime by the canonical\n * `cant-bridge.ts` Pi extension via `/cant:load <file>`; this command\n * group is the management plane for those files.\n *\n * @packageDocumentation\n */\n\nimport { existsSync } from 'node:fs';\nimport { writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport type { Command } from 'commander';\nimport type { PiHarness } from '../../core/harness/pi.js';\nimport type { HarnessTier } from '../../core/harness/scope.js';\nimport type { CantProfileCounts, HarnessInstallOptions } from '../../core/harness/types.js';\nimport { fetchWithTimeout } from '../../core/network/fetch.js';\nimport { cloneRepo } from '../../core/sources/github.js';\nimport { cloneGitLabRepo } from '../../core/sources/gitlab.js';\nimport { parseSource } from '../../core/sources/parser.js';\nimport { LAFSCommandError, runLafsCommand } from '../advanced/lafs.js';\nimport {\n PI_ERROR_CODES,\n type PiCommandBaseOptions,\n parseScope,\n requirePiHarness,\n resolveProjectDir,\n} from './common.js';\n\n/**\n * Options accepted by `caamp pi cant list`.\n *\n * @public\n */\nexport interface PiCantListOptions extends PiCommandBaseOptions {\n /** Project directory used for the `project` tier. */\n projectDir?: string;\n}\n\n/**\n * Options accepted by `caamp pi cant install`.\n *\n * @public\n */\nexport interface PiCantInstallOptions extends PiCommandBaseOptions {\n /** Profile name override. Defaults to the inferred source name. */\n name?: string;\n}\n\n/**\n * Options accepted by `caamp pi cant remove`.\n *\n * @public\n */\nexport type PiCantRemoveOptions = PiCommandBaseOptions;\n\n/**\n * Resolved CANT source descriptor returned by {@link resolveCantSource}.\n *\n * @internal\n */\ninterface ResolvedCantSource {\n /** Absolute path to a local copy of the `.cant` file. */\n localPath: string;\n /** Best-effort cleanup callback (deletes tmp files / cloned repos). */\n cleanup: () => Promise<void>;\n /** Inferred profile name (basename without `.cant`). */\n inferredName: string;\n}\n\n/**\n * Normalize a raw source argument into an absolute local `.cant` file\n * path.\n *\n * @remarks\n * Handles four source kinds:\n *\n * - Local file path (`./profile.cant`, absolute, `~/profile.cant`)\n * - Remote HTTPS URL to a raw `.cant` file (`https://...profile.cant`)\n * - GitHub shorthand/URL pointing at a `.cant` file inside a repo\n * (clones the repo shallowly, resolves the file, returns its path)\n * - GitLab URL pointing at a `.cant` file inside a repo\n *\n * Returns a `{ localPath, cleanup }` pair where `cleanup` is a best-\n * effort async function the caller MUST run when it is done with\n * `localPath` (typically inside a `try { ... } finally { ... }` block).\n *\n * Mirrors the resolution flow in `extensions.ts`'s\n * `resolveExtensionSource` so both verbs accept the same source kinds.\n *\n * Throws {@link LAFSCommandError} for unsupported source shapes or\n * network failures.\n *\n * @internal\n */\nasync function resolveCantSource(source: string): Promise<ResolvedCantSource> {\n // Local file path first — cheapest check.\n if (\n source.startsWith('/') ||\n source.startsWith('./') ||\n source.startsWith('../') ||\n source.startsWith('~')\n ) {\n const expanded = source.startsWith('~/')\n ? join(process.env['HOME'] ?? '', source.slice(2))\n : source;\n if (!existsSync(expanded)) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `Source file does not exist: ${expanded}`,\n 'Check the path and try again.',\n false,\n );\n }\n return {\n localPath: expanded,\n cleanup: async () => {\n // Local files are not owned by us — never delete.\n },\n inferredName: inferNameFromPath(expanded),\n };\n }\n\n // Remote HTTPS fetch.\n if (/^https?:\\/\\//.test(source)) {\n const parsed = parseSource(source);\n if (parsed.type === 'github' && parsed.owner !== undefined && parsed.repo !== undefined) {\n const cloneResult = await cloneRepo(parsed.owner, parsed.repo, parsed.ref);\n const filePath =\n parsed.path !== undefined\n ? join(cloneResult.localPath, parsed.path)\n : cloneResult.localPath;\n if (!existsSync(filePath)) {\n await cloneResult.cleanup();\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `Source path not found inside cloned repo: ${parsed.path ?? '(root)'}`,\n 'Check the repository URL and path.',\n false,\n );\n }\n return {\n localPath: filePath,\n cleanup: cloneResult.cleanup,\n inferredName: inferNameFromPath(filePath),\n };\n }\n if (parsed.type === 'gitlab' && parsed.owner !== undefined && parsed.repo !== undefined) {\n const cloneResult = await cloneGitLabRepo(parsed.owner, parsed.repo, parsed.ref);\n const filePath =\n parsed.path !== undefined\n ? join(cloneResult.localPath, parsed.path)\n : cloneResult.localPath;\n if (!existsSync(filePath)) {\n await cloneResult.cleanup();\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `Source path not found inside cloned repo: ${parsed.path ?? '(root)'}`,\n 'Check the repository URL and path.',\n false,\n );\n }\n return {\n localPath: filePath,\n cleanup: cloneResult.cleanup,\n inferredName: inferNameFromPath(filePath),\n };\n }\n // Raw HTTP(S) URL — download to a tmp file.\n const resp = await fetchWithTimeout(source);\n if (!resp.ok) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.TRANSIENT,\n `Failed to download source from ${source}: HTTP ${resp.status}`,\n 'Check the URL and network connectivity.',\n true,\n );\n }\n const body = await resp.text();\n const baseName = inferNameFromUrl(source);\n const tmp = join(tmpdir(), `caamp-pi-cant-${process.pid}-${Date.now()}-${baseName}.cant`);\n await writeFile(tmp, body, 'utf8');\n return {\n localPath: tmp,\n cleanup: async () => {\n try {\n await (await import('node:fs/promises')).rm(tmp, { force: true });\n } catch {\n // ignore — best-effort cleanup\n }\n },\n inferredName: baseName,\n };\n }\n\n // GitHub shorthand: owner/repo[/path.cant]\n const parsed = parseSource(source);\n if (parsed.type === 'github' && parsed.owner !== undefined && parsed.repo !== undefined) {\n const cloneResult = await cloneRepo(parsed.owner, parsed.repo, parsed.ref);\n const filePath =\n parsed.path !== undefined ? join(cloneResult.localPath, parsed.path) : cloneResult.localPath;\n if (!existsSync(filePath)) {\n await cloneResult.cleanup();\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `Source path not found inside cloned repo: ${parsed.path ?? '(root)'}`,\n 'Check the repository shorthand and path.',\n false,\n );\n }\n return {\n localPath: filePath,\n cleanup: cloneResult.cleanup,\n inferredName: inferNameFromPath(filePath),\n };\n }\n\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n `Unsupported source: ${source}`,\n 'Use a local file path, HTTPS URL, or GitHub shorthand (owner/repo/path.cant).',\n false,\n );\n}\n\n/**\n * Infer a stable profile name from a file path by stripping the\n * directory portion and the `.cant` suffix.\n *\n * @internal\n */\nfunction inferNameFromPath(filePath: string): string {\n const base = filePath.split(/[/\\\\]/).pop() ?? filePath;\n return base.replace(/\\.cant$/, '');\n}\n\n/**\n * Infer a stable profile name from an HTTPS URL by using the final\n * path segment (without querystring or extension).\n *\n * @internal\n */\nfunction inferNameFromUrl(url: string): string {\n try {\n const u = new URL(url);\n const seg = u.pathname.split('/').filter(Boolean).pop() ?? 'profile';\n return seg.replace(/\\.cant$/, '');\n } catch {\n return 'profile';\n }\n}\n\n/**\n * Wrap {@link PiHarness.installCantProfile} so any thrown harness error\n * is rethrown as a typed {@link LAFSCommandError}.\n *\n * @remarks\n * Centralises the try/catch wrapper so the install verb body stays\n * linear and the result type stays narrow (avoiding `let` declarations\n * with deferred assignment).\n *\n * @internal\n */\nasync function invokeInstallCantProfile(\n harness: PiHarness,\n sourcePath: string,\n name: string,\n tier: HarnessTier,\n projectDir: string | undefined,\n installOpts: HarnessInstallOptions,\n): Promise<{ targetPath: string; tier: HarnessTier; counts: CantProfileCounts }> {\n try {\n return await harness.installCantProfile(sourcePath, name, tier, projectDir, installOpts);\n } catch (err) {\n rethrowAsLafs(err);\n }\n}\n\n/**\n * Translate a PiHarness error message into a LAFS-typed error so the\n * envelope carries the right code.\n *\n * @remarks\n * The harness layer throws plain `Error` instances with descriptive\n * messages (e.g. `installCantProfile: target already exists at ...`).\n * Each verb in this file uses this helper to map those messages onto\n * one of the four canonical Pi error codes so callers see consistent\n * envelopes regardless of the failure mode.\n *\n * @internal\n */\nfunction rethrowAsLafs(err: unknown): never {\n const message = err instanceof Error ? err.message : String(err);\n if (/already exists/i.test(message)) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.CONFLICT,\n message,\n 'Pass --force to overwrite the existing profile.',\n false,\n );\n }\n if (/does not exist|not found/i.test(message)) {\n throw new LAFSCommandError(PI_ERROR_CODES.NOT_FOUND, message, 'Check the path.', false);\n }\n if (/failed cant-core validation|expected a CANT source file|not a regular file/i.test(message)) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n message,\n 'Run `caamp pi cant validate <path>` to inspect the diagnostics.',\n false,\n );\n }\n throw new LAFSCommandError(\n 'E_INTERNAL_UNEXPECTED',\n message,\n 'Inspect the message for the underlying cant-core failure mode.',\n false,\n );\n}\n\n/**\n * Registers the `caamp pi cant` command group.\n *\n * @remarks\n * Attaches `list`, `install <source>`, `remove <name>`, and\n * `validate <path>` subcommands under the parent `pi` group. All\n * output is LAFS-compliant via {@link runLafsCommand}; all errors\n * surface as typed {@link LAFSCommandError}s so the envelope carries a\n * code.\n *\n * @param parent - The parent `pi` Command to attach the cant group to.\n *\n * @example\n * ```bash\n * caamp pi cant list\n * caamp pi cant install ./my-profile.cant --scope user\n * caamp pi cant install owner/repo/path/profile.cant --scope global\n * caamp pi cant remove my-profile --scope user\n * caamp pi cant validate ./my-profile.cant\n * ```\n *\n * @public\n */\nexport function registerPiCantCommands(parent: Command): void {\n const cant = parent.command('cant').description('Manage Pi CANT profiles across tiers');\n\n cant\n .command('list')\n .description('List Pi CANT profiles across project, user, and global tiers')\n .option('--scope <tier>', 'Filter to a single tier: project|user|global')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (opts: PiCantListOptions) =>\n runLafsCommand('pi.cant.list', 'standard', async () => {\n const harness = requirePiHarness();\n const projectDir = opts.projectDir ?? process.cwd();\n const allEntries = await harness.listCantProfiles(projectDir);\n const filterTier = opts.scope === undefined ? null : parseScope(opts.scope, 'project');\n const entries =\n filterTier === null ? allEntries : allEntries.filter((e) => e.tier === filterTier);\n const sorted = [...entries].sort((a, b) => a.name.localeCompare(b.name));\n return {\n count: sorted.length,\n entries: sorted,\n };\n }),\n );\n\n cant\n .command('install <source>')\n .description('Install a Pi CANT profile from a local path, HTTPS URL, or GitHub shorthand')\n .option('--scope <tier>', 'Install tier: project|user|global (default: project)')\n .option('--name <name>', 'Override the inferred profile name')\n .option('--force', 'Overwrite an existing profile at the target tier')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (source: string, opts: PiCantInstallOptions) =>\n runLafsCommand('pi.cant.install', 'standard', async () => {\n const harness = requirePiHarness();\n const tier = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(tier, opts.projectDir);\n\n const resolved = await resolveCantSource(source);\n try {\n const name = opts.name ?? resolved.inferredName;\n const installOpts: HarnessInstallOptions = { force: opts.force ?? false };\n const result = await invokeInstallCantProfile(\n harness,\n resolved.localPath,\n name,\n tier,\n projectDir,\n installOpts,\n );\n return {\n installed: {\n name,\n tier: result.tier,\n targetPath: result.targetPath,\n counts: result.counts,\n source,\n },\n };\n } finally {\n await resolved.cleanup();\n }\n }),\n );\n\n cant\n .command('remove <name>')\n .description('Remove a Pi CANT profile from the given tier')\n .option('--scope <tier>', 'Target tier: project|user|global (default: project)')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (name: string, opts: PiCantRemoveOptions) =>\n runLafsCommand('pi.cant.remove', 'standard', async () => {\n const harness = requirePiHarness();\n const tier = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(tier, opts.projectDir);\n const removed = await harness.removeCantProfile(name, tier, projectDir);\n return {\n name,\n tier,\n removed,\n };\n }),\n );\n\n cant\n .command('validate <path>')\n .description('Validate a .cant file via cant-core without installing it')\n .action(async (path: string) =>\n runLafsCommand('pi.cant.validate', 'standard', async () => {\n const harness = requirePiHarness();\n if (!existsSync(path)) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `Source file does not exist: ${path}`,\n 'Check the path and try again.',\n false,\n );\n }\n const result = await harness.validateCantProfile(path);\n if (!result.valid) {\n // Surface the validation failure as a typed error so the\n // envelope carries an exit code 1; the diagnostics ride along\n // in the error details for tooling to consume.\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n `cant-core validation failed with ${result.errors.length} diagnostic(s)`,\n 'See the `errors` field for ruleId/line/col/message details.',\n false,\n { valid: false, counts: result.counts, errors: result.errors },\n );\n }\n return {\n valid: true,\n counts: result.counts,\n errors: result.errors,\n };\n }),\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 * Shared helpers for the `caamp pi <verb>` command group.\n *\n * @remarks\n * Every `caamp pi` verb has to:\n *\n * 1. Check that Pi is installed and abort with a stable error envelope\n * when it is not (per ADR-035 cross-cutting concerns §\"Pi-absent\n * fallback\").\n * 2. Resolve a three-tier scope flag from the Commander option object\n * into a typed {@link HarnessTier}.\n * 3. Construct a {@link PiHarness} bound to the resolved provider so\n * every verb talks to the same concrete implementation.\n *\n * This module centralises those steps so each verb file stays focused\n * on its own argument parsing and output shaping.\n *\n * @packageDocumentation\n */\n\nimport { getHarnessFor } from '../../core/harness/index.js';\nimport { PiHarness } from '../../core/harness/pi.js';\nimport type { HarnessTier } from '../../core/harness/scope.js';\nimport { getInstalledProviders } from '../../core/registry/detection.js';\nimport { getProvider } from '../../core/registry/providers.js';\nimport { LAFSCommandError } from '../advanced/lafs.js';\n\n/**\n * Canonical LAFS error codes used by the `caamp pi` command group.\n *\n * @remarks\n * The `advanced/lafs.ts` emit path normalises any unregistered error\n * code to `E_INTERNAL_UNEXPECTED` — so every code the Pi commands\n * throw MUST come from the canonical LAFS error registry. These\n * constants map the semantic verbs we care about onto the registered\n * codes:\n *\n * - `VALIDATION` — caller-supplied input failed validation\n * - `NOT_FOUND` — referenced resource does not exist\n * - `CONFLICT` — target already exists (overwrite without `--force`)\n * - `TRANSIENT` — network/upstream call failed, retry is viable\n *\n * The three codes covered here (`E_VALIDATION_SCHEMA`,\n * `E_NOT_FOUND_RESOURCE`, `E_CONFLICT_VERSION`, `E_TRANSIENT_UPSTREAM`)\n * are registered in `packages/lafs/schemas/v1/error-registry.json` and\n * round-trip through `runLafsCommand`'s envelope builder without being\n * rewritten to `E_INTERNAL_UNEXPECTED`.\n *\n * @public\n */\nexport const PI_ERROR_CODES = {\n /** Caller-supplied input failed validation (shape, type, enum). */\n VALIDATION: 'E_VALIDATION_SCHEMA',\n /** Referenced resource does not exist on disk or in the registry. */\n NOT_FOUND: 'E_NOT_FOUND_RESOURCE',\n /** Write target already exists and overwrite was not requested. */\n CONFLICT: 'E_CONFLICT_VERSION',\n /** Network/upstream call failed; retry is viable. */\n TRANSIENT: 'E_TRANSIENT_UPSTREAM',\n} as const;\n\n/**\n * Standard option shape accepted by every `caamp pi <verb>` command.\n *\n * @public\n */\nexport interface PiCommandBaseOptions {\n /** `--scope project|user|global`. */\n scope?: string;\n /** `--force` — overwrite existing targets on install verbs. */\n force?: boolean;\n /** `--project-dir <path>` — override cwd for the `project` tier. */\n projectDir?: string;\n}\n\n/**\n * Resolve and validate Pi's installation, returning a ready-to-use\n * {@link PiHarness}.\n *\n * @remarks\n * Throws a {@link LAFSCommandError} with code `E_NOT_FOUND` when Pi is\n * not installed — which `runLafsCommand` converts to an exit code 1\n * error envelope. The ADR calls for exit code 4 semantically, but the\n * CAAMP LAFS layer only exposes exit code 1 for errors; the category\n * `NOT_FOUND` and the explicit code `E_PI_NOT_INSTALLED` carry the\n * semantic distinction instead.\n *\n * @returns A PiHarness bound to the resolved Pi provider entry.\n * @throws `LAFSCommandError` when Pi is not installed.\n *\n * @public\n */\nexport function requirePiHarness(): PiHarness {\n const provider = getProvider('pi');\n if (provider === undefined) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n 'Pi provider is not registered in the CAAMP registry.',\n 'This is a configuration bug — open an issue with `caamp providers list`.',\n false,\n );\n }\n\n const installed = getInstalledProviders();\n const piInstalled = installed.some((p) => p.id === 'pi');\n if (!piInstalled) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n 'Pi is not installed. Run: caamp providers install pi',\n 'Install Pi via its official installer, then retry this command.',\n true,\n );\n }\n\n const harness = getHarnessFor(provider);\n if (!(harness instanceof PiHarness)) {\n throw new LAFSCommandError(\n 'E_INTERNAL_UNEXPECTED',\n 'Pi provider is registered but no PiHarness implementation was returned.',\n 'This is a programming error — the harness dispatcher should always return a PiHarness for Pi.',\n false,\n );\n }\n return harness;\n}\n\n/**\n * Parse and validate a `--scope` option value into a typed tier.\n *\n * @remarks\n * Accepts `project`, `user`, `global`, or `undefined` — in which case\n * the `defaultTier` is returned. Unknown values throw a typed\n * {@link LAFSCommandError} so the error envelope carries a meaningful\n * error code.\n *\n * @param raw - The raw option value from Commander (may be undefined).\n * @param defaultTier - Tier to use when `raw` is undefined.\n * @returns A resolved {@link HarnessTier}.\n * @throws `LAFSCommandError` when `raw` is set to an invalid value.\n *\n * @public\n */\nexport function parseScope(raw: string | undefined, defaultTier: HarnessTier): HarnessTier {\n if (raw === undefined) return defaultTier;\n if (raw === 'project' || raw === 'user' || raw === 'global') return raw;\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n `Invalid --scope value: ${raw}`,\n \"Use one of: 'project', 'user', 'global'.\",\n false,\n );\n}\n\n/**\n * Resolve the project directory to use for the `project` tier,\n * honouring an explicit `--project-dir` flag and falling back to cwd.\n *\n * @remarks\n * Kept in a helper so every verb resolves the same way. Returning\n * `undefined` for non-project tiers allows downstream list/install\n * calls to decline the project-dir argument cleanly.\n *\n * @param tier - Resolved tier the verb is targeting.\n * @param explicit - The raw `--project-dir` option value.\n * @returns Absolute project dir when `tier === 'project'`, else `undefined`.\n *\n * @public\n */\nexport function resolveProjectDir(\n tier: HarnessTier,\n explicit: string | undefined,\n): string | undefined {\n if (tier !== 'project') return undefined;\n if (explicit !== undefined && explicit.length > 0) return explicit;\n return process.cwd();\n}\n","/**\n * `caamp pi extensions` command group.\n *\n * @remarks\n * Three verbs implementing ADR-035 §D1 for Pi extensions:\n *\n * - `list` — walk every tier (project → user → global) and emit an\n * array of {@link ExtensionEntry} objects with shadow flags.\n * - `install <source>` — copy a source `.ts` file (local path, GitHub\n * URL/shorthand, or remote HTTPS URL) into the target tier.\n * - `remove <name>` — delete a named extension from the target tier.\n *\n * Every verb follows the established LAFS envelope pattern via\n * {@link runLafsCommand}. Pi-absent detection happens inside\n * {@link requirePiHarness}, so each verb body only handles the happy\n * path plus verb-specific argument validation.\n *\n * @packageDocumentation\n */\n\nimport { existsSync } from 'node:fs';\nimport { writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport type { Command } from 'commander';\nimport type { HarnessInstallOptions } from '../../core/harness/types.js';\nimport { fetchWithTimeout } from '../../core/network/fetch.js';\nimport { cloneRepo } from '../../core/sources/github.js';\nimport { cloneGitLabRepo } from '../../core/sources/gitlab.js';\nimport { parseSource } from '../../core/sources/parser.js';\nimport { LAFSCommandError, runLafsCommand } from '../advanced/lafs.js';\nimport {\n PI_ERROR_CODES,\n type PiCommandBaseOptions,\n parseScope,\n requirePiHarness,\n resolveProjectDir,\n} from './common.js';\n\n/**\n * Options accepted by `caamp pi extensions list`.\n *\n * @public\n */\nexport interface PiExtensionsListOptions extends PiCommandBaseOptions {\n /** Project directory used for the `project` tier. */\n projectDir?: string;\n}\n\n/**\n * Options accepted by `caamp pi extensions install`.\n *\n * @public\n */\nexport interface PiExtensionsInstallOptions extends PiCommandBaseOptions {\n /** Extension name override. Defaults to the inferred source name. */\n name?: string;\n}\n\n/**\n * Options accepted by `caamp pi extensions remove`.\n *\n * @public\n */\nexport type PiExtensionsRemoveOptions = PiCommandBaseOptions;\n\n/**\n * Normalize a raw source argument into an absolute local `.ts` file path.\n *\n * @remarks\n * Handles four source kinds:\n *\n * - Local file path (`./ext.ts`, absolute, `~/ext.ts`)\n * - Remote HTTPS URL to a raw `.ts` file (`https://...ext.ts`)\n * - GitHub shorthand/URL pointing at a `.ts` file inside a repo\n * (clones the repo shallowly, resolves the file, returns its path)\n * - GitLab URL pointing at a `.ts` file inside a repo\n *\n * Returns a `{ localPath, cleanup }` pair where `cleanup` is a best-\n * effort async function the caller MUST run when it is done with\n * `localPath` (typically inside a `try { ... } finally { ... }` block).\n *\n * Throws {@link LAFSCommandError} for unsupported source shapes or\n * network failures.\n *\n * @internal\n */\nasync function resolveExtensionSource(\n source: string,\n): Promise<{ localPath: string; cleanup: () => Promise<void>; inferredName: string }> {\n // Local file path first — cheapest check.\n if (\n source.startsWith('/') ||\n source.startsWith('./') ||\n source.startsWith('../') ||\n source.startsWith('~')\n ) {\n const expanded = source.startsWith('~/')\n ? join(process.env['HOME'] ?? '', source.slice(2))\n : source;\n if (!existsSync(expanded)) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `Source file does not exist: ${expanded}`,\n 'Check the path and try again.',\n false,\n );\n }\n const inferredName = inferNameFromPath(expanded);\n return {\n localPath: expanded,\n cleanup: async () => {\n // Local files are not owned by us — never delete.\n },\n inferredName,\n };\n }\n\n // Remote HTTPS fetch.\n if (/^https?:\\/\\//.test(source)) {\n const parsed = parseSource(source);\n if (parsed.type === 'github' && parsed.owner !== undefined && parsed.repo !== undefined) {\n const cloneResult = await cloneRepo(parsed.owner, parsed.repo, parsed.ref);\n const filePath =\n parsed.path !== undefined\n ? join(cloneResult.localPath, parsed.path)\n : cloneResult.localPath;\n if (!existsSync(filePath)) {\n await cloneResult.cleanup();\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `Source path not found inside cloned repo: ${parsed.path ?? '(root)'}`,\n 'Check the repository URL and path.',\n false,\n );\n }\n return {\n localPath: filePath,\n cleanup: cloneResult.cleanup,\n inferredName: inferNameFromPath(filePath),\n };\n }\n if (parsed.type === 'gitlab' && parsed.owner !== undefined && parsed.repo !== undefined) {\n const cloneResult = await cloneGitLabRepo(parsed.owner, parsed.repo, parsed.ref);\n const filePath =\n parsed.path !== undefined\n ? join(cloneResult.localPath, parsed.path)\n : cloneResult.localPath;\n if (!existsSync(filePath)) {\n await cloneResult.cleanup();\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `Source path not found inside cloned repo: ${parsed.path ?? '(root)'}`,\n 'Check the repository URL and path.',\n false,\n );\n }\n return {\n localPath: filePath,\n cleanup: cloneResult.cleanup,\n inferredName: inferNameFromPath(filePath),\n };\n }\n // Raw HTTP(S) URL — download to a tmp file.\n const resp = await fetchWithTimeout(source);\n if (!resp.ok) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.TRANSIENT,\n `Failed to download source from ${source}: HTTP ${resp.status}`,\n 'Check the URL and network connectivity.',\n true,\n );\n }\n const body = await resp.text();\n const baseName = inferNameFromUrl(source);\n const tmp = join(tmpdir(), `caamp-pi-ext-${process.pid}-${Date.now()}-${baseName}.ts`);\n await writeFile(tmp, body, 'utf8');\n return {\n localPath: tmp,\n cleanup: async () => {\n try {\n await (await import('node:fs/promises')).rm(tmp, { force: true });\n } catch {\n // ignore\n }\n },\n inferredName: baseName,\n };\n }\n\n // GitHub shorthand: owner/repo[/path.ts]\n const parsed = parseSource(source);\n if (parsed.type === 'github' && parsed.owner !== undefined && parsed.repo !== undefined) {\n const cloneResult = await cloneRepo(parsed.owner, parsed.repo, parsed.ref);\n const filePath =\n parsed.path !== undefined ? join(cloneResult.localPath, parsed.path) : cloneResult.localPath;\n if (!existsSync(filePath)) {\n await cloneResult.cleanup();\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `Source path not found inside cloned repo: ${parsed.path ?? '(root)'}`,\n 'Check the repository shorthand and path.',\n false,\n );\n }\n return {\n localPath: filePath,\n cleanup: cloneResult.cleanup,\n inferredName: inferNameFromPath(filePath),\n };\n }\n\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n `Unsupported source: ${source}`,\n 'Use a local file path, HTTPS URL, or GitHub shorthand (owner/repo/path.ts).',\n false,\n );\n}\n\n/**\n * Infer a stable extension name from a file path by stripping the\n * directory portion and the `.ts` suffix.\n *\n * @internal\n */\nfunction inferNameFromPath(filePath: string): string {\n const base = filePath.split(/[/\\\\]/).pop() ?? filePath;\n return base.replace(/\\.(ts|tsx|mts)$/, '');\n}\n\n/**\n * Infer a stable extension name from an HTTPS URL by using the final\n * path segment (without querystring or extension).\n *\n * @internal\n */\nfunction inferNameFromUrl(url: string): string {\n try {\n const u = new URL(url);\n const seg = u.pathname.split('/').filter(Boolean).pop() ?? 'extension';\n return seg.replace(/\\.(ts|tsx|mts)$/, '');\n } catch {\n return 'extension';\n }\n}\n\n/**\n * Registers the `caamp pi extensions` command group.\n *\n * @remarks\n * Attaches `list`, `install <source>`, and `remove <name>` subcommands\n * under the parent `pi` group. All output is LAFS-compliant via\n * {@link runLafsCommand}; all errors surface as typed\n * {@link LAFSCommandError}s so the envelope carries a code.\n *\n * @param parent - The parent `pi` Command to attach the extensions group to.\n *\n * @example\n * ```bash\n * caamp pi extensions list\n * caamp pi extensions install ./my-ext.ts --scope user\n * caamp pi extensions install owner/repo/path/ext.ts --scope global\n * caamp pi extensions remove my-ext --scope user\n * ```\n *\n * @public\n */\nexport function registerPiExtensionsCommands(parent: Command): void {\n const ext = parent.command('extensions').description('Manage Pi extensions across tiers');\n\n ext\n .command('list')\n .description('List Pi extensions across project, user, and global tiers')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (opts: PiExtensionsListOptions) =>\n runLafsCommand('pi.extensions.list', 'standard', async () => {\n const harness = requirePiHarness();\n const projectDir = opts.projectDir ?? process.cwd();\n const entries = await harness.listExtensions(projectDir);\n return {\n count: entries.length,\n extensions: entries,\n };\n }),\n );\n\n ext\n .command('install <source>')\n .description('Install a Pi extension from a local path, HTTPS URL, or GitHub shorthand')\n .option('--scope <tier>', 'Install tier: project|user|global (default: project)')\n .option('--name <name>', 'Override the inferred extension name')\n .option('--force', 'Overwrite an existing extension at the target tier')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (source: string, opts: PiExtensionsInstallOptions) =>\n runLafsCommand('pi.extensions.install', 'standard', async () => {\n const harness = requirePiHarness();\n const tier = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(tier, opts.projectDir);\n\n const resolved = await resolveExtensionSource(source);\n try {\n const name = opts.name ?? resolved.inferredName;\n const installOpts: HarnessInstallOptions = { force: opts.force ?? false };\n const result = await harness.installExtension(\n resolved.localPath,\n name,\n tier,\n projectDir,\n installOpts,\n );\n return {\n installed: {\n name,\n tier: result.tier,\n targetPath: result.targetPath,\n source,\n },\n };\n } finally {\n await resolved.cleanup();\n }\n }),\n );\n\n ext\n .command('remove <name>')\n .description('Remove a Pi extension from the given tier')\n .option('--scope <tier>', 'Target tier: project|user|global (default: project)')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (name: string, opts: PiExtensionsRemoveOptions) =>\n runLafsCommand('pi.extensions.remove', 'standard', async () => {\n const harness = requirePiHarness();\n const tier = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(tier, opts.projectDir);\n const removed = await harness.removeExtension(name, tier, projectDir);\n return {\n name,\n tier,\n removed,\n };\n }),\n );\n}\n","/**\n * `caamp pi models` command group.\n *\n * @remarks\n * Six verbs implementing ADR-035 §D3 for Pi's dual-file models\n * configuration. `models.json` is authoritative for definitions,\n * `settings.json:enabledModels` is authoritative for selection, and\n * `settings.json:defaultModel` + `defaultProvider` are authoritative\n * for defaults.\n *\n * | Verb | Mutates | Reads |\n * | --------- | ------------------------------------------ | ------------------- |\n * | `list` | — | both files |\n * | `add` | `models.json` | — |\n * | `remove` | `models.json` | — |\n * | `enable` | `settings.json:enabledModels` | `models.json` |\n * | `disable` | `settings.json:enabledModels` | — |\n * | `default` | `settings.json:defaultModel + provider` | `models.json` |\n *\n * @packageDocumentation\n */\n\nimport type { Command } from 'commander';\nimport type {\n HarnessScope,\n PiModelDefinition,\n PiModelProvider,\n PiModelsConfig,\n} from '../../core/harness/types.js';\nimport { LAFSCommandError, runLafsCommand } from '../advanced/lafs.js';\nimport { PI_ERROR_CODES, type PiCommandBaseOptions, requirePiHarness } from './common.js';\n\n/**\n * Options accepted by every `caamp pi models` verb.\n *\n * @public\n */\nexport interface PiModelsCommandOptions extends PiCommandBaseOptions {\n /** `--global` targets the Pi global state root instead of the project. */\n global?: boolean;\n}\n\n/**\n * Options accepted by `caamp pi models add`.\n *\n * @public\n */\nexport interface PiModelsAddOptions extends PiModelsCommandOptions {\n /** Human-readable model name. */\n displayName?: string;\n /** Override the provider base URL. */\n baseUrl?: string;\n /** Reasoning-capable flag. */\n reasoning?: boolean;\n /** Context window size in tokens. */\n contextWindow?: string;\n /** Maximum output tokens. */\n maxTokens?: string;\n}\n\n/**\n * Parse a `provider:model-id` specifier into its parts.\n *\n * @remarks\n * Throws a typed {@link LAFSCommandError} when the specifier does not\n * match `<provider>:<model-id>` so the error envelope carries a\n * meaningful code and recovery hint.\n *\n * @internal\n */\nfunction parseModelSpec(spec: string): { provider: string; id: string } {\n const idx = spec.indexOf(':');\n if (idx <= 0 || idx === spec.length - 1) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n `Invalid model specifier: ${spec}`,\n \"Use 'provider:model-id', e.g. 'anthropic:claude-sonnet-4-20250514'.\",\n false,\n );\n }\n return { provider: spec.slice(0, idx), id: spec.slice(idx + 1) };\n}\n\n/**\n * Resolve a scope from the `--global` flag into a {@link HarnessScope}.\n *\n * @remarks\n * Mirrors the legacy two-tier scope used by PiHarness' settings and\n * models I/O methods. Defaults to global scope, matching Pi's own\n * behaviour where `models.json` lives at the user-tier root unless a\n * project override is explicitly requested.\n *\n * @internal\n */\nfunction resolveModelsScope(opts: PiModelsCommandOptions): HarnessScope {\n if (opts.global === true) return { kind: 'global' };\n if (opts.projectDir !== undefined && opts.projectDir.length > 0) {\n return { kind: 'project', projectDir: opts.projectDir };\n }\n return { kind: 'global' };\n}\n\n/**\n * Parse a numeric CLI option value.\n *\n * @remarks\n * Throws {@link LAFSCommandError} when the string is not a positive\n * finite integer. Used by `--context-window` and `--max-tokens`.\n *\n * @internal\n */\nfunction parsePositiveInt(raw: string | undefined, name: string): number | undefined {\n if (raw === undefined) return undefined;\n const parsed = Number.parseInt(raw, 10);\n if (!Number.isFinite(parsed) || parsed <= 0 || String(parsed) !== raw.trim()) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n `Invalid value for --${name}: ${raw}`,\n `--${name} must be a positive integer.`,\n false,\n );\n }\n return parsed;\n}\n\n/**\n * Registers the `caamp pi models` command group.\n *\n * @param parent - The parent `pi` Command to attach the models group to.\n *\n * @example\n * ```bash\n * caamp pi models list\n * caamp pi models add custom-provider:my-model --display-name \"My Model\"\n * caamp pi models enable anthropic:claude-opus-4-20250514\n * caamp pi models default anthropic:claude-sonnet-4-20250514\n * ```\n *\n * @public\n */\nexport function registerPiModelsCommands(parent: Command): void {\n const models = parent.command('models').description(\"Manage Pi's dual-file models configuration\");\n\n models\n .command('list')\n .description('List every model known to Pi (union of models.json and enabledModels)')\n .option('--global', 'Read from the Pi global state root (default)')\n .option('--project-dir <path>', 'Read from a project-scoped Pi config')\n .action(async (opts: PiModelsCommandOptions) =>\n runLafsCommand('pi.models.list', 'standard', async () => {\n const harness = requirePiHarness();\n const scope = resolveModelsScope(opts);\n const entries = await harness.listModels(scope);\n const active = entries.filter((e) => e.enabled);\n const def = entries.find((e) => e.isDefault) ?? null;\n return {\n scope: scope.kind,\n count: entries.length,\n activeCount: active.length,\n default: def,\n models: entries,\n };\n }),\n );\n\n models\n .command('add <spec>')\n .description('Add a custom model definition to models.json (e.g. provider:model-id)')\n .option('--global', 'Write to the Pi global state root (default)')\n .option('--project-dir <path>', 'Write to a project-scoped Pi config')\n .option('--display-name <name>', 'Human-readable model name')\n .option('--base-url <url>', 'Override the provider base URL')\n .option('--reasoning', 'Mark the model as reasoning-capable')\n .option('--context-window <tokens>', 'Context window size in tokens')\n .option('--max-tokens <tokens>', 'Maximum output tokens')\n .action(async (spec: string, opts: PiModelsAddOptions) =>\n runLafsCommand('pi.models.add', 'standard', async () => {\n const harness = requirePiHarness();\n const scope = resolveModelsScope(opts);\n const { provider, id } = parseModelSpec(spec);\n const contextWindow = parsePositiveInt(opts.contextWindow, 'context-window');\n const maxTokens = parsePositiveInt(opts.maxTokens, 'max-tokens');\n\n const config = await harness.readModelsConfig(scope);\n const providerBlock: PiModelProvider = config.providers[provider] ?? {};\n if (opts.baseUrl !== undefined) providerBlock.baseUrl = opts.baseUrl;\n\n const nextModels: PiModelDefinition[] = providerBlock.models\n ? [...providerBlock.models]\n : [];\n const existingIdx = nextModels.findIndex((m) => m.id === id);\n const definition: PiModelDefinition = {\n id,\n name: opts.displayName ?? id,\n };\n if (opts.reasoning === true) definition.reasoning = true;\n if (contextWindow !== undefined) definition.contextWindow = contextWindow;\n if (maxTokens !== undefined) definition.maxTokens = maxTokens;\n\n if (existingIdx >= 0) {\n nextModels[existingIdx] = definition;\n } else {\n nextModels.push(definition);\n }\n providerBlock.models = nextModels;\n\n const nextConfig: PiModelsConfig = {\n providers: { ...config.providers, [provider]: providerBlock },\n };\n await harness.writeModelsConfig(nextConfig, scope);\n\n return {\n added: { provider, id, name: definition.name },\n replaced: existingIdx >= 0,\n scope: scope.kind,\n };\n }),\n );\n\n models\n .command('remove <spec>')\n .description('Remove a custom model definition from models.json')\n .option('--global', 'Write to the Pi global state root (default)')\n .option('--project-dir <path>', 'Write to a project-scoped Pi config')\n .action(async (spec: string, opts: PiModelsCommandOptions) =>\n runLafsCommand('pi.models.remove', 'standard', async () => {\n const harness = requirePiHarness();\n const scope = resolveModelsScope(opts);\n const { provider, id } = parseModelSpec(spec);\n\n const config = await harness.readModelsConfig(scope);\n const providerBlock = config.providers[provider];\n if (providerBlock === undefined || providerBlock.models === undefined) {\n return { removed: false, provider, id, reason: 'provider-not-found' };\n }\n const before = providerBlock.models.length;\n const filtered = providerBlock.models.filter((m) => m.id !== id);\n if (filtered.length === before) {\n return { removed: false, provider, id, reason: 'model-not-found' };\n }\n const nextProviderBlock: PiModelProvider = { ...providerBlock, models: filtered };\n if (filtered.length === 0) {\n delete nextProviderBlock.models;\n }\n const nextConfig: PiModelsConfig = {\n providers: { ...config.providers, [provider]: nextProviderBlock },\n };\n await harness.writeModelsConfig(nextConfig, scope);\n return { removed: true, provider, id, scope: scope.kind };\n }),\n );\n\n models\n .command('enable <spec>')\n .description('Enable a model by appending it to settings.json:enabledModels')\n .option('--global', 'Write to the Pi global state root (default)')\n .option('--project-dir <path>', 'Write to a project-scoped Pi config')\n .action(async (spec: string, opts: PiModelsCommandOptions) =>\n runLafsCommand('pi.models.enable', 'standard', async () => {\n const harness = requirePiHarness();\n const scope = resolveModelsScope(opts);\n const { provider, id } = parseModelSpec(spec);\n\n // Validate against models.json when the spec is a concrete id.\n if (!id.includes('*')) {\n const config = await harness.readModelsConfig(scope);\n const providerBlock = config.providers[provider];\n const defined = providerBlock?.models?.some((m) => m.id === id) ?? false;\n if (!defined) {\n // Soft validation: a missing definition means the id must\n // resolve against Pi's built-in registry. We allow the\n // enable but surface an advisory flag.\n }\n }\n\n const current = await harness.readSettings(scope);\n const currentObj =\n typeof current === 'object' && current !== null && !Array.isArray(current)\n ? (current as Record<string, unknown>)\n : {};\n const enabledRaw = currentObj['enabledModels'];\n const enabled = Array.isArray(enabledRaw)\n ? enabledRaw.filter((v): v is string => typeof v === 'string')\n : [];\n const already = enabled.includes(spec);\n if (already) {\n return { enabled: false, reason: 'already-enabled', spec, scope: scope.kind };\n }\n enabled.push(spec);\n await harness.writeSettings({ enabledModels: enabled }, scope);\n return { enabled: true, spec, provider, id, scope: scope.kind };\n }),\n );\n\n models\n .command('disable <spec>')\n .description('Disable a model by removing it from settings.json:enabledModels')\n .option('--global', 'Write to the Pi global state root (default)')\n .option('--project-dir <path>', 'Write to a project-scoped Pi config')\n .action(async (spec: string, opts: PiModelsCommandOptions) =>\n runLafsCommand('pi.models.disable', 'standard', async () => {\n const harness = requirePiHarness();\n const scope = resolveModelsScope(opts);\n const current = await harness.readSettings(scope);\n const currentObj =\n typeof current === 'object' && current !== null && !Array.isArray(current)\n ? (current as Record<string, unknown>)\n : {};\n const enabledRaw = currentObj['enabledModels'];\n const enabled = Array.isArray(enabledRaw)\n ? enabledRaw.filter((v): v is string => typeof v === 'string')\n : [];\n const filtered = enabled.filter((e) => e !== spec);\n if (filtered.length === enabled.length) {\n return { disabled: false, reason: 'not-enabled', spec, scope: scope.kind };\n }\n await harness.writeSettings({ enabledModels: filtered }, scope);\n return { disabled: true, spec, scope: scope.kind };\n }),\n );\n\n models\n .command('default <spec>')\n .description('Set settings.json:defaultProvider and defaultModel')\n .option('--global', 'Write to the Pi global state root (default)')\n .option('--project-dir <path>', 'Write to a project-scoped Pi config')\n .action(async (spec: string, opts: PiModelsCommandOptions) =>\n runLafsCommand('pi.models.default', 'standard', async () => {\n const harness = requirePiHarness();\n const scope = resolveModelsScope(opts);\n const { provider, id } = parseModelSpec(spec);\n\n // Validate against models.json; do not hard-fail on missing\n // definition so callers can target Pi's built-in registry, but\n // carry the advisory in the envelope.\n const config = await harness.readModelsConfig(scope);\n const providerBlock = config.providers[provider];\n const defined = providerBlock?.models?.some((m) => m.id === id) ?? false;\n\n await harness.writeSettings({ defaultProvider: provider, defaultModel: id }, scope);\n return {\n set: true,\n provider,\n id,\n knownInModelsJson: defined,\n scope: scope.kind,\n };\n }),\n );\n}\n","/**\n * `caamp pi prompts` command group.\n *\n * @remarks\n * Three verbs implementing ADR-035 §D1 + spec hook T266 for Pi prompts.\n *\n * - `install <sourceDir>` — copy a prompt directory (containing\n * `prompt.md` + optional metadata) into the target tier. Errors on\n * existing target unless `--force`.\n * - `list` — walk every tier and emit an array of {@link PromptEntry}.\n * MUST read only directory listings — never prompt bodies — for\n * token efficiency.\n * - `remove <name>` — delete a prompt directory from the target tier.\n *\n * @packageDocumentation\n */\n\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport type { Command } from 'commander';\nimport type { HarnessInstallOptions } from '../../core/harness/types.js';\nimport { LAFSCommandError, runLafsCommand } from '../advanced/lafs.js';\nimport {\n PI_ERROR_CODES,\n type PiCommandBaseOptions,\n parseScope,\n requirePiHarness,\n resolveProjectDir,\n} from './common.js';\n\n/**\n * Options accepted by `caamp pi prompts install`.\n *\n * @public\n */\nexport interface PiPromptsInstallOptions extends PiCommandBaseOptions {\n /** Override the inferred prompt directory name. */\n name?: string;\n}\n\n/**\n * Options accepted by `caamp pi prompts list`.\n *\n * @public\n */\nexport type PiPromptsListOptions = PiCommandBaseOptions;\n\n/**\n * Options accepted by `caamp pi prompts remove`.\n *\n * @public\n */\nexport type PiPromptsRemoveOptions = PiCommandBaseOptions;\n\n/**\n * Infer a prompt name from a source directory path by taking the\n * trailing path segment.\n *\n * @internal\n */\nfunction inferPromptName(sourceDir: string): string {\n const normalized = resolve(sourceDir).replace(/[\\\\/]+$/, '');\n const base = normalized.split(/[\\\\/]/).pop();\n if (base === undefined || base.length === 0) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n `Could not infer a prompt name from source: ${sourceDir}`,\n 'Pass --name <name> to override the inferred name.',\n false,\n );\n }\n return base;\n}\n\n/**\n * Registers the `caamp pi prompts` command group.\n *\n * @param parent - The parent `pi` Command to attach the prompts group to.\n *\n * @example\n * ```bash\n * caamp pi prompts install ./prompts/my-prompt --scope user\n * caamp pi prompts list\n * caamp pi prompts remove my-prompt --scope user\n * ```\n *\n * @public\n */\nexport function registerPiPromptsCommands(parent: Command): void {\n const prompts = parent.command('prompts').description('Manage Pi prompts across tiers');\n\n prompts\n .command('install <source>')\n .description('Install a Pi prompt directory (contains prompt.md + optional metadata)')\n .option('--scope <tier>', 'Install tier: project|user|global (default: project)')\n .option('--name <name>', 'Override the inferred prompt name')\n .option('--force', 'Overwrite an existing prompt at the target tier')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (source: string, opts: PiPromptsInstallOptions) =>\n runLafsCommand('pi.prompts.install', 'standard', async () => {\n const harness = requirePiHarness();\n const tier = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(tier, opts.projectDir);\n\n const absSource = resolve(source);\n if (!existsSync(absSource)) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `Source directory does not exist: ${absSource}`,\n 'Check the path and try again.',\n false,\n );\n }\n if (!existsSync(join(absSource, 'prompt.md'))) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n `Source directory is missing prompt.md: ${absSource}`,\n 'Add a prompt.md to the source directory and retry.',\n false,\n );\n }\n\n const name = opts.name ?? inferPromptName(absSource);\n const installOpts: HarnessInstallOptions = { force: opts.force ?? false };\n const result = await harness.installPrompt(absSource, name, tier, projectDir, installOpts);\n return {\n installed: {\n name,\n tier: result.tier,\n targetPath: result.targetPath,\n source: absSource,\n },\n };\n }),\n );\n\n prompts\n .command('list')\n .description('List Pi prompts across project, user, and global tiers')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (opts: PiPromptsListOptions) =>\n runLafsCommand('pi.prompts.list', 'standard', async () => {\n const harness = requirePiHarness();\n const projectDir = opts.projectDir ?? process.cwd();\n const entries = await harness.listPrompts(projectDir);\n return {\n count: entries.length,\n prompts: entries,\n };\n }),\n );\n\n prompts\n .command('remove <name>')\n .description('Remove a Pi prompt from the given tier')\n .option('--scope <tier>', 'Target tier: project|user|global (default: project)')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (name: string, opts: PiPromptsRemoveOptions) =>\n runLafsCommand('pi.prompts.remove', 'standard', async () => {\n const harness = requirePiHarness();\n const tier = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(tier, opts.projectDir);\n const removed = await harness.removePrompt(name, tier, projectDir);\n return { name, tier, removed };\n }),\n );\n}\n","/**\n * `caamp pi sessions` command group.\n *\n * @remarks\n * Four verbs implementing ADR-035 §D2 for Pi sessions:\n *\n * - `list` — read only line 1 of every `*.jsonl` under the user-tier\n * sessions directory (and the `subagents/` subdir); NEVER load full\n * session bodies.\n * - `show <id>` — load the full session file and return its raw JSONL\n * entries alongside the header summary.\n * - `export <id> --jsonl|--md` — stream the session file line-by-line\n * into the output sink. Markdown export filters to message-type\n * entries.\n * - `resume <id>` — thin shell-out to `pi --session <id>`; we never\n * reimplement Pi-owned lifecycle semantics.\n *\n * @packageDocumentation\n */\n\nimport { spawn } from 'node:child_process';\nimport { createReadStream, createWriteStream, existsSync } from 'node:fs';\nimport { createInterface } from 'node:readline/promises';\nimport type { Command } from 'commander';\nimport { LAFSCommandError, runLafsCommand } from '../advanced/lafs.js';\nimport { PI_ERROR_CODES, requirePiHarness } from './common.js';\n\n/**\n * Options accepted by `caamp pi sessions list`.\n *\n * @public\n */\nexport interface PiSessionsListOptions {\n /** Include sessions under the `subagents/` subdirectory (default: true). */\n includeSubagents?: boolean;\n}\n\n/**\n * Options accepted by `caamp pi sessions export`.\n *\n * @public\n */\nexport interface PiSessionsExportOptions {\n /** Emit raw JSONL. Mutually exclusive with `md`. */\n jsonl?: boolean;\n /** Emit Markdown (filtered to message/custom_message entries). */\n md?: boolean;\n /** Write to this file path instead of stdout. */\n output?: string;\n}\n\n/**\n * Stream a session file line-by-line through a transform into a write\n * target (stdout or a file).\n *\n * @remarks\n * Uses a Node `readline` interface on top of a read stream so we never\n * pull the full file into memory. The transform decides whether each\n * line contributes to the output and returns the string to emit (or\n * `null` to skip). A trailing newline is written after every emitted\n * line so downstream tools see a well-formed file.\n *\n * @internal\n */\nasync function streamSession(\n filePath: string,\n outputPath: string | undefined,\n transform: (line: string) => string | null,\n): Promise<number> {\n const writeToFile = outputPath !== undefined && outputPath.length > 0;\n const out = writeToFile ? createWriteStream(outputPath) : process.stdout;\n const reader = createInterface({\n input: createReadStream(filePath, { encoding: 'utf8' }),\n crlfDelay: Infinity,\n });\n let emitted = 0;\n try {\n for await (const line of reader) {\n const result = transform(line);\n if (result === null) continue;\n out.write(`${result}\\n`);\n emitted += 1;\n }\n } finally {\n reader.close();\n if (writeToFile && 'end' in out) {\n await new Promise<void>((resolve) => {\n (out as NodeJS.WritableStream).end(resolve);\n });\n }\n }\n return emitted;\n}\n\n/**\n * Produce a Markdown representation of a single JSONL session entry.\n *\n * @remarks\n * Returns `null` for entry kinds that carry no user-visible content so\n * the export transform can drop them cleanly. Supported kinds match\n * ADR-035 §D2's \"Markdown export filters to message/custom_message\n * entry types only\" rule, plus the line-1 session header which is\n * converted into a level-1 heading.\n *\n * @internal\n */\nfunction sessionEntryToMarkdown(line: string): string | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return null;\n }\n if (typeof parsed !== 'object' || parsed === null) return null;\n const obj = parsed as Record<string, unknown>;\n const type = typeof obj['type'] === 'string' ? obj['type'] : null;\n\n if (type === 'session') {\n const id = typeof obj['id'] === 'string' ? obj['id'] : '(no id)';\n const ts = typeof obj['timestamp'] === 'string' ? obj['timestamp'] : '';\n return `# Session ${id}${ts.length > 0 ? ` · ${ts}` : ''}\\n`;\n }\n\n if (type === 'message') {\n const role = typeof obj['role'] === 'string' ? obj['role'] : 'assistant';\n const content = extractMessageContent(obj['content']);\n if (content === null) return null;\n const label = role.charAt(0).toUpperCase() + role.slice(1);\n return `## ${label}\\n\\n${content}\\n`;\n }\n\n if (type === 'custom_message') {\n const label = typeof obj['label'] === 'string' ? obj['label'] : 'Custom';\n const text = typeof obj['text'] === 'string' ? obj['text'] : '';\n return `### ${label}\\n\\n${text}\\n`;\n }\n\n return null;\n}\n\n/**\n * Extract a text body from a Pi message `content` field.\n *\n * @remarks\n * Pi's message schema allows either a bare string or an array of\n * content blocks where each block is `{ type: \"text\", text: \"...\" }`\n * or similar. We handle both shapes and concatenate text blocks with a\n * blank line separator. Non-text blocks are silently dropped because\n * the Markdown export is a lossy text preview, not a fidelity-\n * preserving format.\n *\n * @internal\n */\nfunction extractMessageContent(content: unknown): string | null {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return null;\n const parts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n parts.push(block);\n continue;\n }\n if (typeof block !== 'object' || block === null) continue;\n const b = block as Record<string, unknown>;\n if (b['type'] === 'text' && typeof b['text'] === 'string') {\n parts.push(b['text']);\n }\n }\n if (parts.length === 0) return null;\n return parts.join('\\n\\n');\n}\n\n/**\n * Registers the `caamp pi sessions` command group.\n *\n * @param parent - The parent `pi` Command to attach the sessions group to.\n *\n * @example\n * ```bash\n * caamp pi sessions list\n * caamp pi sessions show sess-abc123\n * caamp pi sessions export sess-abc123 --md --output session.md\n * caamp pi sessions resume sess-abc123\n * ```\n *\n * @public\n */\nexport function registerPiSessionsCommands(parent: Command): void {\n const sessions = parent.command('sessions').description('Inspect and resume Pi sessions');\n\n sessions\n .command('list')\n .description('List Pi sessions (reads only line 1 of each JSONL file)')\n .option('--no-subagents', 'Skip sessions under subagents/')\n .action(async (opts: PiSessionsListOptions) =>\n runLafsCommand('pi.sessions.list', 'standard', async () => {\n const harness = requirePiHarness();\n const summaries = await harness.listSessions({\n includeSubagents: opts.includeSubagents !== false,\n });\n return {\n count: summaries.length,\n sessions: summaries,\n };\n }),\n );\n\n sessions\n .command('show <id>')\n .description('Show the full body of a Pi session by id')\n .action(async (id: string) =>\n runLafsCommand('pi.sessions.show', 'full', async () => {\n const harness = requirePiHarness();\n const doc = await harness.showSession(id);\n return {\n summary: doc.summary,\n entryCount: doc.entries.length,\n entries: doc.entries,\n };\n }),\n );\n\n sessions\n .command('export <id>')\n .description('Export a Pi session to JSONL or Markdown')\n .option('--jsonl', 'Emit the raw JSONL body (default)')\n .option('--md', 'Emit a Markdown transcription (messages only)')\n .option('--output <path>', 'Write to this file instead of stdout')\n .action(async (id: string, opts: PiSessionsExportOptions) =>\n runLafsCommand('pi.sessions.export', 'standard', async () => {\n if (opts.jsonl === true && opts.md === true) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n 'Cannot pass both --jsonl and --md',\n 'Pick one of --jsonl or --md.',\n false,\n );\n }\n const harness = requirePiHarness();\n // Resolve the file path via the harness listing so we never\n // need to know the user-tier layout inline.\n const summaries = await harness.listSessions({ includeSubagents: true });\n const match = summaries.find((s) => s.id === id);\n if (match === undefined) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `No session found with id ${id}`,\n 'Run `caamp pi sessions list` to see known ids.',\n false,\n );\n }\n const format: 'jsonl' | 'md' = opts.md === true ? 'md' : 'jsonl';\n const emitted =\n format === 'md'\n ? await streamSession(match.filePath, opts.output, sessionEntryToMarkdown)\n : await streamSession(match.filePath, opts.output, (line) =>\n line.length === 0 ? null : line,\n );\n return {\n id,\n format,\n filePath: match.filePath,\n output: opts.output ?? 'stdout',\n entriesEmitted: emitted,\n };\n }),\n );\n\n sessions\n .command('resume <id>')\n .description('Resume a Pi session by shelling out to `pi --session <id>`')\n .action(async (id: string) =>\n runLafsCommand('pi.sessions.resume', 'standard', async () => {\n const harness = requirePiHarness();\n // Sanity-check the session exists before shelling out so we\n // return a typed error envelope rather than an opaque Pi exit\n // code when the id is wrong.\n const summaries = await harness.listSessions({ includeSubagents: true });\n const match = summaries.find((s) => s.id === id);\n if (match === undefined) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `No session found with id ${id}`,\n 'Run `caamp pi sessions list` to see known ids.',\n false,\n );\n }\n const piBinary = harness.provider.detection.binary ?? 'pi';\n // Verify the binary is actually callable before spawning.\n if (!existsSync(piBinary) && piBinary === 'pi') {\n // `pi` might live on PATH; we trust that case and just spawn.\n }\n const child = spawn(piBinary, ['--session', id], {\n stdio: 'inherit',\n detached: false,\n });\n const exitCode: number = await new Promise((resolve) => {\n child.on('exit', (code) => resolve(code ?? 0));\n });\n if (exitCode !== 0) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.TRANSIENT,\n `pi --session ${id} exited with code ${exitCode}`,\n 'Check the Pi binary output for details.',\n true,\n );\n }\n return {\n id,\n filePath: match.filePath,\n exitCode,\n };\n }),\n );\n}\n","/**\n * `caamp pi themes` command group.\n *\n * @remarks\n * Three verbs implementing ADR-035 §D1 + spec hook T267 for Pi themes.\n *\n * - `install <sourceFile>` — copy a theme file (`.ts`, `.tsx`, `.mts`,\n * or `.json`) into the target tier. Errors on existing target unless\n * `--force`.\n * - `list` — walk every tier and emit an array of {@link ThemeEntry}\n * with shadow flags and the file extension preserved so callers see\n * whether each theme is TypeScript or JSON.\n * - `remove <name>` — delete a theme file from the target tier,\n * handling both `.ts`/`.json` extensions.\n *\n * @packageDocumentation\n */\n\nimport { existsSync, statSync } from 'node:fs';\nimport { extname, resolve } from 'node:path';\nimport type { Command } from 'commander';\nimport type { HarnessInstallOptions } from '../../core/harness/types.js';\nimport { LAFSCommandError, runLafsCommand } from '../advanced/lafs.js';\nimport {\n PI_ERROR_CODES,\n type PiCommandBaseOptions,\n parseScope,\n requirePiHarness,\n resolveProjectDir,\n} from './common.js';\n\n/**\n * Options accepted by `caamp pi themes install`.\n *\n * @public\n */\nexport interface PiThemesInstallOptions extends PiCommandBaseOptions {\n /** Override the inferred theme name. */\n name?: string;\n}\n\n/**\n * Options accepted by `caamp pi themes list`.\n *\n * @public\n */\nexport type PiThemesListOptions = PiCommandBaseOptions;\n\n/**\n * Options accepted by `caamp pi themes remove`.\n *\n * @public\n */\nexport type PiThemesRemoveOptions = PiCommandBaseOptions;\n\n/**\n * Infer a theme name from a source file path by taking the basename\n * and stripping the recognised theme file extension.\n *\n * @internal\n */\nfunction inferThemeName(sourceFile: string): string {\n const base = resolve(sourceFile).split(/[\\\\/]/).pop();\n if (base === undefined || base.length === 0) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n `Could not infer a theme name from source: ${sourceFile}`,\n 'Pass --name <name> to override the inferred name.',\n false,\n );\n }\n const ext = extname(base);\n if (ext === '') return base;\n return base.slice(0, -ext.length);\n}\n\n/**\n * Registers the `caamp pi themes` command group.\n *\n * @param parent - The parent `pi` Command to attach the themes group to.\n *\n * @example\n * ```bash\n * caamp pi themes install ./themes/my-theme.json --scope user\n * caamp pi themes list\n * caamp pi themes remove my-theme --scope user\n * ```\n *\n * @public\n */\nexport function registerPiThemesCommands(parent: Command): void {\n const themes = parent.command('themes').description('Manage Pi themes across tiers');\n\n themes\n .command('install <source>')\n .description('Install a Pi theme file (.ts/.tsx/.mts/.json)')\n .option('--scope <tier>', 'Install tier: project|user|global (default: project)')\n .option('--name <name>', 'Override the inferred theme name')\n .option('--force', 'Overwrite an existing theme at the target tier')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (source: string, opts: PiThemesInstallOptions) =>\n runLafsCommand('pi.themes.install', 'standard', async () => {\n const harness = requirePiHarness();\n const tier = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(tier, opts.projectDir);\n\n const absSource = resolve(source);\n if (!existsSync(absSource)) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.NOT_FOUND,\n `Source theme does not exist: ${absSource}`,\n 'Check the path and try again.',\n false,\n );\n }\n const stats = statSync(absSource);\n if (!stats.isFile()) {\n throw new LAFSCommandError(\n PI_ERROR_CODES.VALIDATION,\n `Source theme is not a regular file: ${absSource}`,\n 'Themes must be a single .ts/.tsx/.mts/.json file.',\n false,\n );\n }\n\n const name = opts.name ?? inferThemeName(absSource);\n const installOpts: HarnessInstallOptions = { force: opts.force ?? false };\n const result = await harness.installTheme(absSource, name, tier, projectDir, installOpts);\n return {\n installed: {\n name,\n tier: result.tier,\n targetPath: result.targetPath,\n source: absSource,\n },\n };\n }),\n );\n\n themes\n .command('list')\n .description('List Pi themes across project, user, and global tiers')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (opts: PiThemesListOptions) =>\n runLafsCommand('pi.themes.list', 'standard', async () => {\n const harness = requirePiHarness();\n const projectDir = opts.projectDir ?? process.cwd();\n const entries = await harness.listThemes(projectDir);\n return {\n count: entries.length,\n themes: entries,\n };\n }),\n );\n\n themes\n .command('remove <name>')\n .description('Remove a Pi theme from the given tier')\n .option('--scope <tier>', 'Target tier: project|user|global (default: project)')\n .option('--project-dir <path>', 'Project directory for the project tier (default: cwd)')\n .action(async (name: string, opts: PiThemesRemoveOptions) =>\n runLafsCommand('pi.themes.remove', 'standard', async () => {\n const harness = requirePiHarness();\n const tier = parseScope(opts.scope, 'project');\n const projectDir = resolveProjectDir(tier, opts.projectDir);\n const removed = await harness.removeTheme(name, tier, projectDir);\n return { name, tier, removed };\n }),\n );\n}\n","/**\n * `caamp pi` command group — Pi-specific verbs for the Pi coding agent\n * harness.\n *\n * @remarks\n * Per ADR-035, CAAMP exposes Wave-1 Pi operations (extensions, sessions,\n * models, prompts, themes) as first-class verbs that wrap\n * {@link PiHarness} methods in LAFS-compliant envelopes. This module is\n * the single entry point for wiring every sub-verb into the root\n * `caamp` program.\n *\n * @packageDocumentation\n */\n\nimport type { Command } from 'commander';\nimport { registerPiCantCommands } from './cant.js';\nimport { registerPiExtensionsCommands } from './extensions.js';\nimport { registerPiModelsCommands } from './models.js';\nimport { registerPiPromptsCommands } from './prompts.js';\nimport { registerPiSessionsCommands } from './sessions.js';\nimport { registerPiThemesCommands } from './themes.js';\n\n/**\n * Register the `pi` command group and all Wave-1 sub-verbs on the root\n * program.\n *\n * @remarks\n * Attaches `extensions`, `sessions`, `models`, `prompts`, and `themes`\n * under a single parent `pi` command. Each sub-group owns its own\n * verb registration in the corresponding `commands/pi/<noun>.ts` file.\n *\n * Ordering matches the logical documentation order from ADR-035 rather\n * than alphabetic, so `caamp pi --help` reads as the natural workflow:\n * install an extension, inspect a session, configure a model, install\n * a prompt, install a theme.\n *\n * @param program - The root Commander program to attach the `pi` group to.\n *\n * @example\n * ```bash\n * caamp pi extensions list\n * caamp pi sessions list\n * caamp pi models list\n * caamp pi prompts list\n * caamp pi themes list\n * caamp pi cant list\n * ```\n *\n * @public\n */\nexport function registerPiCommands(program: Command): void {\n const pi = program\n .command('pi')\n .description('Pi harness operations (extensions, sessions, models, prompts, themes, cant)');\n\n registerPiExtensionsCommands(pi);\n registerPiSessionsCommands(pi);\n registerPiModelsCommands(pi);\n registerPiPromptsCommands(pi);\n registerPiThemesCommands(pi);\n registerPiCantCommands(pi);\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 * 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);\n registerSkillsAudit(skills);\n registerSkillsValidate(skills);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,eAAe;;;ACFxB,SAAS,gBAAgB;;;ACAzB,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,OAKK;AAyBA,IAAM,mBAAN,cAA+B,MAAM;AAAA;AAAA,EAE1C;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAEA,YACE,MACA,SACA,YACA,cAAc,MACd,SACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW,mBAAmB,IAA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,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","existsSync","readFile","existsSync","readFile","program","existsSync","tmpdir","join","join","join","mkdtemp","rm","tmpdir","join","simpleGit","mkdtemp","join","tmpdir","simpleGit","rm","parseScope","resolveProjectDir","join","existsSync","parsed","tmpdir","parseScope","resolveProjectDir","existsSync","writeFile","tmpdir","join","join","existsSync","inferNameFromPath","parsed","inferNameFromUrl","tmpdir","writeFile","parseScope","resolveProjectDir","existsSync","join","parseScope","resolveProjectDir","existsSync","join","existsSync","resolve","existsSync","existsSync","resolve","resolve","parseScope","resolveProjectDir","existsSync","program","randomUUID","resolveOutputFormat","pc","program","resolveOutputFormat","emitJsonError","buildEnvelope","pc","canonical","hooks","spawn","randomUUID","existsSync","statSync","pc","existsSync","statSync","summary","pc","pc","pc","randomUUID","resolveOutputFormat","pc","resolveOutputFormat","emitJsonError","pc","buildEnvelope","randomUUID","existsSync","writeFile","join","pc","join","existsSync","pc","writeFile","existsSync","pc","emitError","pc","existsSync","randomUUID","resolveOutputFormat","pc","resolveOutputFormat","emitJsonError","pc","buildEnvelope","randomUUID","pc","pc","pc","pc","resolve","resolveOutputFormat","pc","resolveOutputFormat","pc","program"]}
|