@brucewaynedecoy/make-docs 2.0.3 → 2.0.5
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 +1 -1
- package/dist/{backup-GCM64IPN.js → backup-2OT4A6LR.js} +5 -5
- package/dist/chunk-3EXHM5L2.js +1225 -0
- package/dist/chunk-3EXHM5L2.js.map +1 -0
- package/dist/{chunk-2HNJCJJE.js → chunk-46MGH32G.js} +6 -4
- package/dist/chunk-46MGH32G.js.map +1 -0
- package/dist/{chunk-O2UZ35PV.js → chunk-CCYP5NU2.js} +20 -20
- package/dist/{chunk-O2UZ35PV.js.map → chunk-CCYP5NU2.js.map} +1 -1
- package/dist/{chunk-C2IBRVUA.js → chunk-CLSOY7NV.js} +153 -6
- package/dist/chunk-CLSOY7NV.js.map +1 -0
- package/dist/{chunk-GPVKIBFC.js → chunk-CMNKQM7L.js} +3 -3
- package/dist/{chunk-U25GFKNZ.js → chunk-HXWD2EUD.js} +20 -15
- package/dist/chunk-HXWD2EUD.js.map +1 -0
- package/dist/{chunk-DNDM7DUQ.js → chunk-I4FADOUK.js} +3 -3
- package/dist/{chunk-DNDM7DUQ.js.map → chunk-I4FADOUK.js.map} +1 -1
- package/dist/{chunk-DFQJENNL.js → chunk-ISSMVKIA.js} +224 -20
- package/dist/chunk-ISSMVKIA.js.map +1 -0
- package/dist/{chunk-IHMZ2OCS.js → chunk-UNR4CYVX.js} +116 -37
- package/dist/chunk-UNR4CYVX.js.map +1 -0
- package/dist/{chunk-57GN6ALR.js → chunk-VMKG3H4B.js} +2 -2
- package/dist/{chunk-4LLSMDWJ.js → chunk-XDSWX4Y4.js} +9085 -2912
- package/dist/chunk-XDSWX4Y4.js.map +1 -0
- package/dist/index.js +308 -176
- package/dist/index.js.map +1 -1
- package/dist/registry-PC5GKAKM.js +50 -0
- package/dist/registry-PC5GKAKM.js.map +1 -0
- package/dist/{self-UHPM4A2U.js → self-WYVXO23B.js} +18 -18
- package/dist/{self-UHPM4A2U.js.map → self-WYVXO23B.js.map} +1 -1
- package/dist/server-BQOG6FTA.js +1113 -0
- package/dist/server-BQOG6FTA.js.map +1 -0
- package/dist/{setup-system-JUHGDZJW.js → setup-system-KN7FTTLT.js} +267 -44
- package/dist/setup-system-KN7FTTLT.js.map +1 -0
- package/dist/{skills-command-W3SE3OFP.js → skills-command-KEW7MOEW.js} +39 -29
- package/dist/skills-command-KEW7MOEW.js.map +1 -0
- package/dist/{uninstall-BGMJ6KCI.js → uninstall-45XF4CHD.js} +10 -10
- package/dist/virtual_make-docs-first-party-skills-ECJESFL2.js +11 -0
- package/dist/virtual_make-docs-first-party-skills-ECJESFL2.js.map +1 -0
- package/package.json +8 -8
- package/skill-registry.json +24 -8
- package/skill-registry.schema.json +2 -1
- package/template/.make-docs/system/contracts/output-contract.md +3 -1
- package/template/.make-docs/system/contracts/system-resource-contract.md +16 -0
- package/template/.make-docs/system/references/prd-change-management.md +14 -2
- package/template/.make-docs/system-resources.catalog.json +415 -0
- package/template/.make-docs/system-resources.schema.json +25 -0
- package/dist/chunk-2HNJCJJE.js.map +0 -1
- package/dist/chunk-4LLSMDWJ.js.map +0 -1
- package/dist/chunk-C2IBRVUA.js.map +0 -1
- package/dist/chunk-DFQJENNL.js.map +0 -1
- package/dist/chunk-IHMZ2OCS.js.map +0 -1
- package/dist/chunk-U25GFKNZ.js.map +0 -1
- package/dist/chunk-Z5K4FHYP.js +0 -922
- package/dist/chunk-Z5K4FHYP.js.map +0 -1
- package/dist/server-N7XAAV3X.js +0 -512
- package/dist/server-N7XAAV3X.js.map +0 -1
- package/dist/setup-system-JUHGDZJW.js.map +0 -1
- package/dist/skills-command-W3SE3OFP.js.map +0 -1
- package/dist/virtual_make-docs-first-party-skills-VXSUUHTL.js +0 -11
- package/dist/virtual_make-docs-first-party-skills-VXSUUHTL.js.map +0 -1
- /package/dist/{backup-GCM64IPN.js.map → backup-2OT4A6LR.js.map} +0 -0
- /package/dist/{chunk-GPVKIBFC.js.map → chunk-CMNKQM7L.js.map} +0 -0
- /package/dist/{chunk-57GN6ALR.js.map → chunk-VMKG3H4B.js.map} +0 -0
- /package/dist/{uninstall-BGMJ6KCI.js.map → uninstall-45XF4CHD.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/server.ts","../src/mcp/resources.ts","../src/mcp/tools.ts","../src/operations/closeout/index.ts","../src/operations/lifecycle/index.ts","../src/operations/index.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { serializeOperationError } from \"../operations/context\";\nimport { readPackageMeta } from \"../utils\";\nimport { listNativeMcpResources, readNativeMcpResource } from \"./resources\";\nimport { callMakeDocsMcpTool, listMakeDocsMcpTools } from \"./tools\";\n\nexport function createMakeDocsMcpServer(): McpServer {\n const packageMeta = readPackageMeta();\n const server = new McpServer({\n name: packageMeta.name,\n version: packageMeta.version,\n });\n\n for (const tool of listMakeDocsMcpTools().filter((candidate) => candidate.mcpReady !== false)) {\n server.registerTool(\n tool.name,\n {\n title: tool.title,\n description: tool.description,\n inputSchema: tool.inputSchema,\n },\n async (args) => {\n try {\n return formatMcpToolResult(await callMakeDocsMcpTool(tool.name, args));\n } catch (error) {\n return formatMcpToolError(error);\n }\n },\n );\n }\n\n server.server.registerCapabilities({ resources: {} });\n server.server.setRequestHandler(ListResourcesRequestSchema, async () =>\n listNativeMcpResources(),\n );\n server.server.setRequestHandler(ReadResourceRequestSchema, async (request) =>\n readNativeMcpResource(request.params.uri),\n );\n\n return server;\n}\n\nexport async function runMcpServer(): Promise<void> {\n const server = createMakeDocsMcpServer();\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\nfunction formatMcpToolResult(value: unknown) {\n const structuredContent =\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : { value };\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(structuredContent, null, 2),\n },\n ],\n structuredContent,\n };\n}\n\nfunction formatMcpToolError(error: unknown) {\n const structuredContent = serializeOperationError(error);\n return {\n isError: true,\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(structuredContent, null, 2),\n },\n ],\n structuredContent,\n };\n}\n","import path from \"node:path\";\nimport { ErrorCode, McpError } from \"@modelcontextprotocol/sdk/types.js\";\nimport { HARNESS_CALLER_IDENTITY_ENV } from \"../harness-access/contract\";\nimport { createExecutionContext } from \"../operations/context\";\nimport { invokeOperation } from \"../operations/registry\";\nimport { ResourceOperationError } from \"../operations/resource\";\n\ninterface ResourceListValue {\n targetRoot: string;\n resources: Array<{\n uri: string;\n result:\n | { ok: true; value: Record<string, unknown> }\n | { ok: false; error: Record<string, unknown> };\n }>;\n}\n\ninterface ResourceReadValue {\n targetRoot: string;\n resource: Record<string, unknown> & {\n identity: { uri: string; path: string };\n mediaType: string;\n byteLength: number;\n content: { encoding: \"base64\"; data: string };\n };\n}\n\nfunction throwNativeResourceError(error: unknown): never {\n if (error instanceof ResourceOperationError) {\n throw new McpError(ErrorCode.InvalidParams, error.message, {\n makeDocs: {\n code: error.code,\n recovery: error.recovery,\n ...(error.uri ? { uri: error.uri } : {}),\n ...(error.path ? { path: error.path } : {}),\n },\n });\n }\n throw error;\n}\n\n/** Native resources/list adapter over the same resource.list handler as CLI and tools. */\nexport async function listNativeMcpResources(targetRoot = process.cwd()) {\n const invocation = await invokeOperation(\n \"resource.list\",\n { targetRoot: path.resolve(targetRoot) },\n createExecutionContext({\n surface: \"mcp\",\n route: \"mcp\",\n callerIdentityRaw: process.env[HARNESS_CALLER_IDENTITY_ENV],\n cwd: targetRoot,\n }),\n ).catch(throwNativeResourceError);\n const value = invocation.value as unknown as ResourceListValue;\n return {\n resources: value.resources.map((entry) => {\n if (!entry.result.ok) {\n return {\n uri: entry.uri,\n name: entry.uri,\n description: \"Unavailable Make Docs system resource.\",\n _meta: { makeDocs: { error: entry.result.error } },\n };\n }\n return {\n uri: entry.uri,\n name: entry.uri,\n description: \"Make Docs system resource.\",\n mimeType: String(entry.result.value.mediaType),\n size: Number(entry.result.value.byteLength),\n _meta: { makeDocs: entry.result.value },\n };\n }),\n };\n}\n\n/** Native resources/read adapter over the same resource.read handler as CLI and tools. */\nexport async function readNativeMcpResource(uri: string, targetRoot = process.cwd()) {\n const invocation = await invokeOperation(\n \"resource.read\",\n { uri, targetRoot: path.resolve(targetRoot) },\n createExecutionContext({\n surface: \"mcp\",\n route: \"mcp\",\n callerIdentityRaw: process.env[HARNESS_CALLER_IDENTITY_ENV],\n cwd: targetRoot,\n }),\n ).catch(throwNativeResourceError);\n const value = invocation.value as unknown as ResourceReadValue;\n const { content, ...metadata } = value.resource;\n return {\n contents: [\n {\n uri: value.resource.identity.uri,\n mimeType: value.resource.mediaType,\n blob: content.data,\n _meta: { makeDocs: metadata },\n },\n ],\n };\n}\n","import path from \"node:path\";\nimport { z } from \"zod\";\nimport { classifyCompatibilityState } from \"../compatibility\";\nimport { getConfigRenderingLabels, loadMakeDocsConfigOrThrow } from \"../config\";\nimport { findReviewableManagedFileConflicts, planInstall } from \"../install\";\nimport { loadManifest } from \"../manifest\";\nimport { HARNESS_CALLER_IDENTITY_ENV } from \"../harness-access/contract\";\nimport { createExecutionContext } from \"../operations/context\";\nimport { listOperationDomains } from \"../operations/index\";\nimport {\n getOperation,\n invokeOperation,\n listOperationAccessFacts,\n listOperations,\n type OperationDefinition,\n} from \"../operations/registry\";\nimport type { OperationAccess } from \"../operations/access\";\nimport { cloneSelections, defaultSelections } from \"../profile\";\nimport type {\n InstallPlan,\n InstallSelections,\n PlannedAction,\n} from \"../types\";\nimport { readPackageMeta } from \"../utils\";\n\ntype HandDefinedMcpToolName =\n | \"make_docs_operation_domains\"\n | \"make_docs_installed_state\"\n | \"make_docs_manifest_read\"\n | \"make_docs_config_read\"\n | \"make_docs_compatibility_classify\"\n | \"make_docs_install_plan\";\n\ntype McpToolInput = Record<string, unknown>;\n\nexport interface MakeDocsMcpToolDescriptor {\n name: string;\n title: string;\n description: string;\n inputSchema: Record<string, z.ZodType>;\n /** Present for tools projected from the operation registry. */\n operation?: string;\n access?: OperationAccess;\n mcpReady?: boolean;\n}\n\ninterface DerivedMcpToolDescriptor extends MakeDocsMcpToolDescriptor {\n /** The registry identifier this tool is derived from. */\n operation: string;\n}\n\nconst targetDirSchema = z\n .string()\n .optional()\n .describe(\"Project root to inspect. Defaults to the current working directory.\");\n\nconst systemAssetMaterializationModeSchema = z.enum([\n \"full-snapshot\",\n \"provider-backed\",\n \"hybrid-pinned-cache\",\n]);\n\n/**\n * The six hand-defined non-operation tools: read-first inspection and\n * planning surfaces that are not registry operations. Everything else on\n * the MCP tool list is DERIVED from the operation registry below (R-REG-2).\n */\nconst HAND_DEFINED_MCP_TOOLS: (MakeDocsMcpToolDescriptor & { name: HandDefinedMcpToolName })[] = [\n {\n name: \"make_docs_operation_domains\",\n title: \"List Make Docs Operation Domains\",\n description: \"List deterministic operation domains shared by CLI and MCP tools.\",\n inputSchema: {},\n },\n {\n name: \"make_docs_installed_state\",\n title: \"Inspect Make Docs Installed State\",\n description:\n \"Inspect manifest, config, compatibility, and package state for a make-docs project.\",\n inputSchema: { targetDir: targetDirSchema },\n },\n {\n name: \"make_docs_manifest_read\",\n title: \"Read Make Docs Manifest\",\n description: \"Read .make-docs/manifest.json without mutating the project.\",\n inputSchema: { targetDir: targetDirSchema },\n },\n {\n name: \"make_docs_config_read\",\n title: \"Read Make Docs Config\",\n description: \"Read .make-docs/config.yaml with default overlay diagnostics.\",\n inputSchema: { targetDir: targetDirSchema },\n },\n {\n name: \"make_docs_compatibility_classify\",\n title: \"Classify Make Docs Compatibility State\",\n description: \"Run the same compatibility classifier used by the CLI.\",\n inputSchema: { targetDir: targetDirSchema },\n },\n {\n name: \"make_docs_install_plan\",\n title: \"Plan Make Docs Install Or Sync\",\n description:\n \"Create a dry-run install/sync plan using CLI planner semantics and without file writes.\",\n inputSchema: {\n targetDir: targetDirSchema,\n selections: z.unknown().optional().describe(\"Optional InstallSelections override.\"),\n systemAssetMaterializationMode:\n systemAssetMaterializationModeSchema.optional(),\n },\n },\n];\n\n/**\n * MCP tool-name derivation rule (R-MIG-3): `make_docs_` + the registry\n * identifier with its `.` and `-` separators mapped to `_`\n * (`resource.list` -> `make_docs_resource_list`,\n * `package.surface-resolve` -> `make_docs_package_surface_resolve`).\n */\nexport function deriveMcpToolName(operationId: string): string {\n return `make_docs_${operationId.replace(/[.-]/g, \"_\")}`;\n}\n\n/**\n * Context-only tool arguments. They ride the execution context, never the\n * operation input; the generic dispatch strips them before delegating.\n */\nconst allowWriteSchema = z\n .boolean()\n .optional()\n .describe(\n \"Set true to permit this mutating operation to write. Enforced uniformly by the operation core.\",\n );\nconst dryRunSchema = z\n .boolean()\n .optional()\n .describe(\"Set true to plan rather than write; rides the execution context, not the input.\");\nconst approvalsSchema = z\n .array(z.string())\n .optional()\n .describe(\n \"Named approval tokens granted to the operation (e.g. reviewed-overwrite); rides the execution context, not the input.\",\n );\n\n/**\n * Registry input contracts are `z.object` / `z.looseObject`, which expose\n * `.shape`. Documented fallback: a non-object input schema derives no named\n * tool arguments — the generic dispatch still passes all non-context args\n * through as the operation input, and the core's own schema validation\n * remains authoritative.\n */\nfunction operationInputShape(schema: OperationDefinition[\"inputSchema\"]): Record<string, z.ZodType> {\n if (schema instanceof z.ZodObject) {\n return { ...(schema.shape as Record<string, z.ZodType>) };\n }\n return {};\n}\n\nfunction deriveToolInputSchema(definition: OperationDefinition): Record<string, z.ZodType> {\n return {\n ...operationInputShape(definition.inputSchema),\n ...(definition.mutates === \"write\" ? { allowWrite: allowWriteSchema } : {}),\n dryRun: dryRunSchema,\n approvals: approvalsSchema,\n };\n}\n\nfunction deriveToolDescription(definition: OperationDefinition): string {\n const parts = [\n definition.summary,\n `Access: Store ${definition.access.store}; project ${definition.access.project}; host configuration ${definition.access.hostConfig}.`,\n ];\n if (definition.status === \"pending\") {\n parts.push(\n `Pending: reserved registry identifier whose semantics land with ${definition.pendingLineage}; invocation is refused until then.`,\n );\n }\n if (definition.mutates === \"write\") {\n parts.push(\"Mutating operation: requires allowWrite=true, enforced by the operation core.\");\n }\n return parts.join(\" \");\n}\n\n/**\n * The derived operation tool list (R-REG-2, R-MIG-3): every registry\n * identifier — active and pending — gets exactly one MCP tool, with name,\n * title, description, and input schema derived from its registry\n * definition. No operation tool is hand-maintained here.\n */\nconst DERIVED_MCP_OPERATION_TOOLS: DerivedMcpToolDescriptor[] = listOperations().map(\n (operation) => {\n const definition = getOperation(operation.id);\n const accessFact = listOperationAccessFacts().find((fact) => fact.operation === operation.id)!;\n return {\n name: deriveMcpToolName(operation.id),\n operation: operation.id,\n title: `Make Docs Operation ${operation.id}`,\n description: deriveToolDescription(definition),\n inputSchema: deriveToolInputSchema(definition),\n access: { ...accessFact.access },\n mcpReady: accessFact.mcpReady,\n };\n },\n);\n\nconst DERIVED_TOOLS_BY_NAME = new Map<string, DerivedMcpToolDescriptor>(\n DERIVED_MCP_OPERATION_TOOLS.map((tool) => [tool.name, tool]),\n);\n\nexport const MAKE_DOCS_MCP_TOOLS: MakeDocsMcpToolDescriptor[] = [\n ...HAND_DEFINED_MCP_TOOLS,\n ...DERIVED_MCP_OPERATION_TOOLS,\n];\n\n/**\n * List the stable MCP surface. Access policy runs at invocation time so a\n * caller can receive the typed not-configured, unavailable, unsafe, or denied\n * result instead of an incorrect tool-not-found result.\n */\nexport function listMakeDocsMcpTools(\n targetRoot = process.cwd(),\n): MakeDocsMcpToolDescriptor[] {\n void targetRoot;\n return MAKE_DOCS_MCP_TOOLS.map((tool) => {\n if (!tool.operation || !tool.access) return tool;\n return { ...tool, access: { ...tool.access } };\n });\n}\n\n/**\n * Conformance seam (R-TEST-1): the derived tool-name/operation pairs, for\n * tests pinning derived-tool/registry parity in both directions.\n */\nexport function listDerivedMcpOperationTools(): { name: string; operation: string }[] {\n return DERIVED_MCP_OPERATION_TOOLS.map(({ name, operation }) => ({ name, operation }));\n}\n\n/** Structured MCP exposure facts from the same operation access authority. */\nexport function listDerivedMcpOperationAccessFacts(): Array<{\n name: string;\n operation: string;\n access: OperationAccess;\n mcpReady: boolean;\n}> {\n return DERIVED_MCP_OPERATION_TOOLS.map(({ name, operation, access, mcpReady }) => ({\n name,\n operation,\n access: { ...access! },\n mcpReady: mcpReady === true,\n }));\n}\n\n/**\n * Parity check against the LIVE registry (R-TEST-1): every registry\n * identifier must have exactly one derived MCP tool and every derived tool\n * must map to a registry identifier with the derived spelling. Returns the\n * mismatches so tests can assert both the green path and the failure mode\n * with a stubbed/filtered tool list.\n */\nexport function verifyDerivedMcpToolParity(\n tools: { name: string; operation: string }[] = listDerivedMcpOperationTools(),\n): {\n missingOperations: string[];\n unknownOperations: string[];\n misderivedNames: string[];\n duplicateNames: string[];\n} {\n const registryIds = new Set(listOperations().map((operation) => operation.id));\n const byOperation = new Map<string, number>();\n const nameCounts = new Map<string, number>();\n const unknownOperations: string[] = [];\n const misderivedNames: string[] = [];\n for (const tool of tools) {\n byOperation.set(tool.operation, (byOperation.get(tool.operation) ?? 0) + 1);\n nameCounts.set(tool.name, (nameCounts.get(tool.name) ?? 0) + 1);\n if (!registryIds.has(tool.operation)) {\n unknownOperations.push(tool.operation);\n }\n if (tool.name !== deriveMcpToolName(tool.operation)) {\n misderivedNames.push(tool.name);\n }\n }\n const missingOperations = [...registryIds].filter((id) => (byOperation.get(id) ?? 0) !== 1);\n const duplicateNames = [...nameCounts.entries()]\n .filter(([, count]) => count > 1)\n .map(([name]) => name);\n return { missingOperations, unknownOperations, misderivedNames, duplicateNames };\n}\n\nexport async function callMakeDocsMcpTool(\n name: string,\n args: McpToolInput = {},\n): Promise<Record<string, unknown>> {\n switch (name) {\n case \"make_docs_operation_domains\":\n return mcpPayload(name, listOperationDomains());\n case \"make_docs_installed_state\":\n return mcpPayload(name, await readInstalledState(resolveTargetDir(args)));\n case \"make_docs_manifest_read\":\n return mcpPayload(name, readManifest(resolveTargetDir(args)));\n case \"make_docs_config_read\":\n return mcpPayload(name, readConfig(resolveTargetDir(args)));\n case \"make_docs_compatibility_classify\":\n return mcpPayload(\n name,\n await classifyCompatibilityState({ targetDir: resolveTargetDir(args) }),\n );\n case \"make_docs_install_plan\":\n return mcpPayload(name, await buildInstallPlan(resolveTargetDir(args), args));\n }\n const derived = DERIVED_TOOLS_BY_NAME.get(name);\n if (derived === undefined) {\n throw new Error(`Unknown make-docs MCP tool: ${name}`);\n }\n const targetRoot = resolveOperationTargetDir(args);\n const effective = listMakeDocsMcpTools(targetRoot).find((tool) => tool.name === name);\n return mcpPayload(name, await invokeDerivedOperationTool(derived.operation, args), {\n operation: derived.operation,\n access: { ...derived.access! },\n mcpReady: effective?.mcpReady === true,\n });\n}\n\n/**\n * The single generic dispatch path for every derived operation tool\n * (R-CORE-1): strip the context-only fields (`allowWrite`, `dryRun`,\n * `approvals`) into the execution context, pass every remaining argument\n * through as the operation input, and delegate. Input validation, write\n * gating, named approvals, and pending-lineage refusal are all enforced\n * uniformly by the operation core; this adapter carries no per-tool checks.\n */\nasync function invokeDerivedOperationTool(id: string, args: McpToolInput): Promise<unknown> {\n const { allowWrite, dryRun, approvals, ...input } = args;\n const invocation = await invokeOperation(\n id,\n input,\n createExecutionContext({\n surface: \"mcp\",\n route: \"mcp\",\n callerIdentityRaw: process.env[HARNESS_CALLER_IDENTITY_ENV],\n writesAllowed: allowWrite === true,\n dryRun: dryRun === true,\n approvals: Array.isArray(approvals) ? approvals.map(String) : [],\n }),\n );\n return invocation.value;\n}\n\nasync function readInstalledState(targetDir: string): Promise<Record<string, unknown>> {\n return {\n targetDir,\n package: readPackageMeta(),\n manifest: readManifest(targetDir),\n config: readConfig(targetDir),\n compatibility: await classifyCompatibilityState({ targetDir }),\n operationDomains: listOperationDomains(),\n };\n}\n\nfunction readManifest(targetDir: string): Record<string, unknown> {\n const manifest = loadManifest(targetDir);\n return {\n targetDir,\n present: manifest !== null,\n manifest,\n };\n}\n\nfunction readConfig(targetDir: string): Record<string, unknown> {\n const loaded = loadMakeDocsConfigOrThrow(targetDir);\n return {\n targetDir,\n present: loaded.present,\n valid: loaded.valid,\n configPath: loaded.configPath,\n diagnostics: loaded.diagnostics,\n config: loaded.config,\n renderingLabels: getConfigRenderingLabels(loaded.config),\n };\n}\n\nasync function buildInstallPlan(\n targetDir: string,\n args: McpToolInput,\n): Promise<Record<string, unknown>> {\n const existingManifest = loadManifest(targetDir);\n const selections = resolveSelections(existingManifest?.selections, args.selections);\n const plan = await planInstall({\n targetDir,\n selections,\n existingManifest,\n packageMeta: readPackageMeta(),\n systemAssetMaterializationMode:\n systemAssetMaterializationModeSchema.optional().parse(\n args.systemAssetMaterializationMode,\n ),\n });\n const conflicts = findReviewableManagedFileConflicts(plan);\n\n return summarizeInstallPlan(plan, conflicts);\n}\n\nfunction summarizeInstallPlan(\n plan: InstallPlan,\n conflicts: ReturnType<typeof findReviewableManagedFileConflicts>,\n): Record<string, unknown> {\n const counts = {\n create: 0,\n generate: 0,\n noop: 0,\n removeManaged: 0,\n skipConflict: 0,\n update: 0,\n updateConflict: 0,\n };\n\n for (const action of plan.actions) {\n switch (action.type) {\n case \"create\":\n counts.create += 1;\n break;\n case \"generate\":\n counts.generate += 1;\n break;\n case \"noop\":\n counts.noop += 1;\n break;\n case \"remove-managed\":\n counts.removeManaged += 1;\n break;\n case \"skip-conflict\":\n counts.skipConflict += 1;\n break;\n case \"update\":\n case \"strip-managed-block\":\n counts.update += 1;\n break;\n case \"update-conflict\":\n counts.updateConflict += 1;\n break;\n }\n }\n\n return {\n packageName: plan.packageName,\n packageVersion: plan.packageVersion,\n profile: plan.profile,\n systemAssetMaterialization: plan.systemAssetMaterialization,\n actionCounts: counts,\n actions: plan.actions.map(summarizeAction),\n reviewableManagedFileConflicts: conflicts,\n writesFiles: false,\n };\n}\n\nfunction summarizeAction(action: PlannedAction): Record<string, unknown> {\n const { content: _content, ...summary } = action;\n return summary;\n}\n\nfunction resolveSelections(\n manifestSelections: InstallSelections | undefined,\n override: unknown,\n): InstallSelections {\n if (override !== undefined) {\n return override as InstallSelections;\n }\n if (manifestSelections) {\n return cloneSelections(manifestSelections);\n }\n return defaultSelections();\n}\n\nfunction mcpPayload(\n tool: string,\n result: unknown,\n details: Record<string, unknown> = {},\n): Record<string, unknown> {\n return {\n tool,\n source: \"mcp\",\n ...details,\n result,\n };\n}\n\nfunction resolveOperationTargetDir(args: McpToolInput): string {\n return path.resolve(\n optionalString(args, \"targetRoot\") ?? optionalString(args, \"targetDir\") ?? process.cwd(),\n );\n}\n\nfunction resolveTargetDir(args: McpToolInput): string {\n return path.resolve(optionalString(args, \"targetDir\") ?? process.cwd());\n}\n\nfunction optionalString(args: McpToolInput, key: string): string | undefined {\n const value = args[key];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n","import {\n existsSync,\n mkdirSync,\n readdirSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport path from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\nimport {\n normalizePath,\n readJsonFile,\n readText,\n safeRunGit,\n valueAsRecord,\n} from \"../shared\";\nimport { loadMakeDocsConfig } from \"../../config\";\nimport { isPersonaScopedDocumentPath, validateGeneratedDocumentMetadata } from \"../../document-metadata\";\nimport type {\n JsonValue,\n OperationResult,\n} from \"../types\";\n\nconst COORDINATE_RE = /w(\\d+)-r(\\d+)/i;\nconst TASK_ID_RE = /\\bt([1-9]\\d*)\\b/i;\nconst RISK_HEADING_RE = /^###\\s+([DQR])-(\\d{3})\\b/gm;\nconst SLUG_RE = /[^a-z0-9]+/g;\n\nexport function buildCloseoutProbe(options: {\n repoRoot: string;\n scope: \"auto\" | \"staged\" | \"unstaged\" | \"full\";\n /** Repo-relative design paths selected by new/substantial authoring context. */\n humanExperienceRequiredPaths?: string[];\n}): Record<string, JsonValue> {\n const repoRoot = path.resolve(options.repoRoot);\n const filesByPath = changedFilesForCloseout(repoRoot, options.scope);\n const files = [...filesByPath.keys()].sort().map((filePath) => filesByPath.get(filePath)!);\n let selectedScope: string = options.scope;\n if (options.scope === \"auto\") {\n selectedScope = files.some((file) => file.staged) ? \"staged\" : \"full\";\n }\n\n const { config } = loadMakeDocsConfig(repoRoot);\n const metadataValidation = validateChangedDocumentMetadata(repoRoot, files, config, options.humanExperienceRequiredPaths);\n\n return {\n repoRoot,\n scope: selectedScope,\n statusShort: safeRunGit(repoRoot, [\"status\", \"--short\"]).split(/\\r?\\n/).filter(Boolean),\n files: files as unknown as JsonValue,\n contracts: discoverContracts(repoRoot, config) as unknown as JsonValue,\n coordinates: extractCoordinates(files.map((file) => file.path)) as unknown as JsonValue,\n historyCandidates: discoverHistoryCandidates(\n repoRoot,\n extractCoordinates(files.map((file) => file.path)),\n ),\n riskRegister: nextRiskIds(repoRoot) as unknown as JsonValue,\n metadataValidation: metadataValidation as unknown as JsonValue,\n validationHints: validationHints(files, repoRoot),\n };\n}\n\nexport function runCloseoutValidate(options: {\n repoRoot: string;\n probeJson: string;\n run: boolean;\n}): Record<string, JsonValue> {\n const probe = readJsonFile(options.probeJson);\n const commands = commandsFromProbe(probe);\n const output: Record<string, JsonValue> = {\n repoRoot: options.repoRoot,\n commands,\n ran: options.run,\n };\n if (options.run) {\n output.results = commands.map((command) => runShellCommand(options.repoRoot, command)) as unknown as JsonValue;\n }\n return output;\n}\n\nexport function runCloseoutHistory(options: {\n repoRoot: string;\n mode: \"commit\" | \"phase\";\n probeJson?: string;\n phaseJson?: string;\n title?: string;\n date: string;\n outputDir: string;\n write: boolean;\n}): Record<string, JsonValue> {\n const probe = options.probeJson ? readJsonFile(options.probeJson) : {};\n const phase = options.phaseJson ? readJsonFile(options.phaseJson) : {};\n const title = options.title ?? defaultHistoryTitle(options.mode, probe, phase);\n const contents = renderHistory(options.mode, title, options.date, probe, phase);\n const outputPath = path.join(\n options.repoRoot,\n options.outputDir,\n historyFilename(options.mode, options.date, title, probe, phase),\n );\n const result: Record<string, JsonValue> = {\n path: outputPath,\n wrote: false,\n contents,\n };\n if (options.write) {\n mkdirSync(path.dirname(outputPath), { recursive: true });\n if (existsSync(outputPath)) {\n result.contents = readText(outputPath);\n } else {\n writeFileSync(outputPath, contents, \"utf8\");\n result.wrote = true;\n }\n }\n return result;\n}\n\nexport function probeCloseout(input: {\n repoRoot: string;\n scope: \"auto\" | \"staged\" | \"unstaged\" | \"full\";\n humanExperienceRequiredPaths?: string[];\n}): OperationResult<Record<string, JsonValue>> {\n return {\n value: buildCloseoutProbe(input),\n provenance: {\n domain: \"closeout\",\n operation: \"closeout-probe\",\n source: \"shared\",\n target: input.repoRoot,\n },\n };\n}\n\ninterface CloseoutFile {\n path: string;\n gitStatus: string;\n staged: boolean;\n unstaged: boolean;\n category?: string;\n}\n\nfunction changedFilesForCloseout(\n repoRoot: string,\n scope: \"auto\" | \"staged\" | \"unstaged\" | \"full\",\n): Map<string, CloseoutFile> {\n const status = parseStatusShort(safeRunGit(repoRoot, [\"status\", \"--short\", \"--untracked-files=all\"]));\n const staged = parseNameStatus(safeRunGit(repoRoot, [\"diff\", \"--cached\", \"--name-status\"]), true);\n const unstaged = parseNameStatus(safeRunGit(repoRoot, [\"diff\", \"--name-status\"]), false);\n for (const entry of status) {\n if (entry.index === \"?\" && entry.workingTree === \"?\") {\n unstaged.set(entry.path, {\n path: entry.path,\n gitStatus: \"??\",\n staged: false,\n unstaged: true,\n });\n }\n }\n let selectedScope: typeof scope = scope;\n if (scope === \"auto\") {\n selectedScope = staged.size > 0 ? \"staged\" : \"full\";\n }\n const merged = new Map<string, CloseoutFile>();\n if (selectedScope === \"staged\" || selectedScope === \"full\") {\n for (const [filePath, file] of staged) {\n merged.set(filePath, { ...file });\n }\n }\n if (selectedScope === \"unstaged\" || selectedScope === \"full\") {\n for (const [filePath, file] of unstaged) {\n const existing = merged.get(filePath);\n if (existing) {\n existing.unstaged = true;\n existing.gitStatus = `${existing.gitStatus}+${file.gitStatus}`;\n } else {\n merged.set(filePath, { ...file });\n }\n }\n }\n for (const file of merged.values()) {\n file.category = classifyPath(file.path);\n }\n return merged;\n}\n\nfunction parseNameStatus(output: string, staged: boolean): Map<string, CloseoutFile> {\n const files = new Map<string, CloseoutFile>();\n for (const line of output.split(/\\r?\\n/)) {\n if (!line.trim()) {\n continue;\n }\n const parts = line.split(\"\\t\");\n const status = parts[0] ?? \"\";\n const filePath = parts[parts.length - 1] ?? \"\";\n files.set(filePath, {\n path: filePath,\n gitStatus: status,\n staged,\n unstaged: !staged,\n });\n }\n return files;\n}\n\nfunction parseStatusShort(output: string): Array<{ path: string; index: string; workingTree: string }> {\n const entries: Array<{ path: string; index: string; workingTree: string }> = [];\n for (const line of output.split(/\\r?\\n/)) {\n if (!line) {\n continue;\n }\n if (line.startsWith(\"?? \")) {\n entries.push({ path: line.slice(3), index: \"?\", workingTree: \"?\" });\n continue;\n }\n if (line.length >= 4) {\n entries.push({ path: line.slice(3), index: line[0] ?? \"\", workingTree: line[1] ?? \"\" });\n }\n }\n return entries;\n}\n\nfunction classifyPath(filePath: string): string {\n if (/\\.(test|spec)\\.ts$/.test(filePath) || filePath.endsWith(\"_test.py\") || filePath.endsWith(\"test_validate_output.py\")) {\n return \"tests\";\n }\n if (filePath.startsWith(\"packages/cli/src/\") || filePath.startsWith(\"packages/cli/bin/\")) {\n return \"code\";\n }\n if (filePath.startsWith(\"packages/cli/tests/\")) {\n return \"tests\";\n }\n if (filePath.startsWith(\"packages/skills/\") || filePath.startsWith(\".agents/skills/\") || filePath.startsWith(\".claude/skills/\")) {\n return \"skill\";\n }\n if (filePath.startsWith(\"docs/\") || filePath.startsWith(\".make-docs/archive/\") || filePath.startsWith(\"packages/docs/template/docs/\")) {\n return \"docs\";\n }\n if (/\\.(json|ya?ml|toml)$/.test(filePath)) {\n return \"config\";\n }\n if (/\\.(ts|tsx|js|py|rs|sh)$/.test(filePath)) {\n return \"code\";\n }\n return \"other\";\n}\n\nfunction discoverContracts(repoRoot: string, config: ReturnType<typeof loadMakeDocsConfig>[\"config\"]): Record<string, JsonValue> {\n const candidates: Record<string, string[]> = {\n rootAgentInstructions: [\"AGENTS.md\", \"CLAUDE.md\"],\n historyDir: [\".make-docs/archive/history\"],\n riskRegister: [\"docs/prd/03-open-questions-and-risk-register.md\"],\n commitConvention: [\n \".make-docs/system/contracts/commit-message-convention.md\",\n ],\n templateCommitConvention: [\n \"packages/docs/template/.make-docs/system/contracts/commit-message-convention.md\",\n ],\n guideContract: [\".make-docs/system/contracts/guide-contract.md\"],\n maintainerGuides: config.personas.filter((persona) => persona.primitive === \"maintainer\").map((persona) => `docs/assets/${persona.slug}`),\n userGuides: config.personas.filter((persona) => persona.primitive === \"user\").map((persona) => `docs/assets/${persona.slug}`),\n };\n return Object.fromEntries(\n Object.entries(candidates).map(([name, paths]) => {\n const existing = paths.filter((candidate) => existsSync(path.join(repoRoot, candidate)));\n return [name, { exists: existing.length > 0, paths: existing }];\n }),\n ) as Record<string, JsonValue>;\n}\n\nfunction extractCoordinates(paths: string[]): Array<Record<string, JsonValue>> {\n const seen = new Set<string>();\n const coordinates: Array<Record<string, JsonValue>> = [];\n for (const filePath of paths) {\n const wr = COORDINATE_RE.exec(filePath);\n const phase = filePath.startsWith(\"docs/work/\") ? /^([0-9]{2}|[1-9]\\d)-/.exec(path.basename(filePath)) : null;\n const task = TASK_ID_RE.exec(filePath);\n const coordinate = {\n w: wr ? Number(wr[1]) : null,\n r: wr ? Number(wr[2]) : null,\n p: phase ? Number(phase[1]) : null,\n t: task ? Number(task[1]) : null,\n source: filePath,\n };\n if (Object.values(coordinate).some((value) => value !== null && value !== filePath)) {\n const key = JSON.stringify(coordinate);\n if (!seen.has(key)) {\n seen.add(key);\n coordinates.push(coordinate as unknown as Record<string, JsonValue>);\n }\n }\n }\n return coordinates;\n}\n\nfunction discoverHistoryCandidates(\n repoRoot: string,\n coordinates: Array<Record<string, JsonValue>>,\n): string[] {\n const historyDir = path.join(repoRoot, \".make-docs\", \"archive\", \"history\");\n if (!existsSync(historyDir) || !statSync(historyDir).isDirectory()) {\n return [];\n }\n const terms = new Set<string>();\n for (const coordinate of coordinates) {\n if (typeof coordinate.w === \"number\" && typeof coordinate.r === \"number\") {\n terms.add(`w${coordinate.w}-r${coordinate.r}`);\n terms.add(`W${coordinate.w} R${coordinate.r}`);\n }\n }\n const candidates: string[] = [];\n for (const entry of readdirSync(historyDir).sort()) {\n if (!entry.endsWith(\".md\")) {\n continue;\n }\n const filePath = path.join(historyDir, entry);\n const rel = normalizePath(path.relative(repoRoot, filePath));\n const text = safeRead(filePath).toLowerCase();\n if (terms.size === 0 || [...terms].some((term) => `${rel}\\n${text}`.toLowerCase().includes(term.toLowerCase()))) {\n candidates.push(rel);\n }\n }\n return candidates.slice(0, 20);\n}\n\nfunction nextRiskIds(repoRoot: string): Record<string, JsonValue> {\n const riskPath = path.join(repoRoot, \"docs\", \"prd\", \"03-open-questions-and-risk-register.md\");\n if (!existsSync(riskPath)) {\n return { exists: false, path: null, next: {} };\n }\n const highest: Record<string, number> = { D: 0, Q: 0, R: 0 };\n const text = readText(riskPath);\n for (const match of text.matchAll(RISK_HEADING_RE)) {\n const prefix = match[1] ?? \"\";\n highest[prefix] = Math.max(highest[prefix] ?? 0, Number(match[2]));\n }\n return {\n exists: true,\n path: \"docs/prd/03-open-questions-and-risk-register.md\",\n next: {\n D: `D-${String(highest.D + 1).padStart(3, \"0\")}`,\n Q: `Q-${String(highest.Q + 1).padStart(3, \"0\")}`,\n R: `R-${String(highest.R + 1).padStart(3, \"0\")}`,\n },\n };\n}\n\nfunction validateChangedDocumentMetadata(\n repoRoot: string,\n files: CloseoutFile[],\n config: ReturnType<typeof loadMakeDocsConfig>[\"config\"],\n humanExperienceRequiredPaths: string[] = [],\n): Array<Record<string, JsonValue>> {\n const findings: Array<Record<string, JsonValue>> = [];\n const required = new Set(humanExperienceRequiredPaths.map(normalizePath));\n for (const file of files) {\n const isDesign = /^docs\\/designs\\/[^/]+\\.md$/u.test(normalizePath(file.path))\n && ![\"AGENTS.md\", \"CLAUDE.md\", \"README.md\"].includes(path.basename(file.path));\n if (!isPersonaScopedDocumentPath(file.path) && !isDesign) {\n continue;\n }\n const absolutePath = path.join(repoRoot, file.path);\n if (!existsSync(absolutePath) || !statSync(absolutePath).isFile()) {\n continue;\n }\n const markdown = readText(absolutePath);\n const fileFindings = validateGeneratedDocumentMetadata(markdown, {\n config,\n sourcePath: file.path,\n humanExperienceMode: isDesign && required.has(normalizePath(file.path)) ? \"required\" : \"if-present\",\n });\n if (fileFindings.length === 0) {\n continue;\n }\n findings.push({\n path: file.path,\n findings: fileFindings.map((finding) => ({\n code: finding.code,\n field: finding.field,\n message: finding.message,\n })) as unknown as JsonValue,\n });\n }\n return findings;\n}\n\nfunction validationHints(files: CloseoutFile[], repoRoot: string): string[] {\n const paths = files.map((file) => file.path);\n const categories = new Set(files.map((file) => file.category));\n const commands: string[] = [];\n if (paths.some((filePath) => filePath.startsWith(\"packages/skills/decompose-codebase/scripts/\"))) {\n commands.push(\"python3 -B packages/skills/decompose-codebase/scripts/test_validate_output.py\");\n }\n if (paths.some((filePath) => filePath.startsWith(\"packages/skills/closeout-commit/scripts/\"))) {\n commands.push(\"python3 -B packages/skills/closeout-commit/scripts/test_closeout_helpers.py\");\n }\n if (paths.some((filePath) => filePath.startsWith(\"packages/skills/closeout-phase/scripts/\"))) {\n commands.push(\"python3 -B packages/skills/closeout-phase/scripts/test_closeout_helpers.py\");\n }\n if ((categories.has(\"code\") || categories.has(\"tests\") || categories.has(\"skill\") || categories.has(\"config\")) && isMakeDocsNodeWorkspace(repoRoot, paths)) {\n commands.push(\"npm test -w packages/cli -- consistency install skill-catalog skill-registry\");\n }\n if (paths.some((filePath) => filePath.startsWith(\"packages/cli/src/\") || filePath.startsWith(\"packages/cli/tests/\"))) {\n commands.push(\"npm run build -w packages/cli\");\n }\n if (paths.some((filePath) => filePath.startsWith(\"docs/\") || filePath.startsWith(\".make-docs/archive/\") || filePath.startsWith(\"packages/docs/template/docs/\"))) {\n commands.push(\"scripts/check-instruction-routers.sh\");\n }\n commands.push(\"git diff --check\");\n return [...new Set(commands)];\n}\n\nfunction isMakeDocsNodeWorkspace(repoRoot: string, paths: string[]): boolean {\n const packageJson = path.join(repoRoot, \"package.json\");\n if (!existsSync(packageJson)) {\n return paths.some((filePath) => filePath.startsWith(\"packages/cli/\") || filePath.startsWith(\"packages/skills/\"));\n }\n const text = safeRead(packageJson);\n return text.includes(\"make-docs\") || paths.some((filePath) =>\n filePath.startsWith(\"packages/cli/\") ||\n filePath.startsWith(\"packages/skills/\") ||\n filePath === \"package.json\" ||\n filePath === \"package-lock.json\",\n );\n}\n\nfunction commandsFromProbe(probe: Record<string, JsonValue>): string[] {\n const hints = Array.isArray(probe.validationHints) ? probe.validationHints : [];\n const commands: string[] = [];\n for (const hint of hints) {\n if (typeof hint === \"string\" && !commands.includes(hint)) {\n commands.push(hint);\n }\n }\n if (!commands.includes(\"git diff --check\")) {\n commands.push(\"git diff --check\");\n }\n return commands;\n}\n\nfunction runShellCommand(repoRoot: string, command: string): Record<string, JsonValue> {\n const result = spawnSync(command, {\n cwd: repoRoot,\n shell: true,\n encoding: \"utf8\",\n });\n return {\n command,\n returncode: result.status ?? 1,\n stdout: (result.stdout ?? \"\").slice(-4000),\n stderr: (result.stderr ?? \"\").slice(-4000),\n };\n}\n\nfunction defaultHistoryTitle(\n mode: \"commit\" | \"phase\",\n probe: Record<string, JsonValue>,\n phase: Record<string, JsonValue>,\n): string {\n if (typeof phase.title === \"string\" && phase.title.length > 0) {\n return `${phase.title} Closeout`;\n }\n const files = Array.isArray(probe.files) ? probe.files : [];\n const first = files[0] as { path?: string } | undefined;\n if (first?.path) {\n return `${path.basename(first.path, path.extname(first.path)).replace(/-/g, \" \")} Closeout`;\n }\n return mode === \"phase\" ? \"Phase Closeout\" : \"Closeout\";\n}\n\nfunction historyFilename(\n mode: \"commit\" | \"phase\",\n date: string,\n title: string,\n probe: Record<string, JsonValue>,\n phase: Record<string, JsonValue>,\n): string {\n const titleSlug = slugify(title);\n if (mode === \"phase\") {\n const coord = coordinateSlug(probe, phase);\n if (coord) {\n return `${date}-${coord}-${titleSlug}.md`;\n }\n }\n return `${date}-${titleSlug}.md`;\n}\n\nfunction renderHistory(\n mode: \"commit\" | \"phase\",\n title: string,\n date: string,\n probe: Record<string, JsonValue>,\n phase: Record<string, JsonValue>,\n): string {\n const coordinate = coordinateLabel(probe, phase);\n const files = Array.isArray(probe.files) ? probe.files : [];\n const validations = commandsFromProbe(probe);\n const fileLines = files.length > 0\n ? files.map((file) => `- \\`${String((file as { path?: string }).path ?? \"\")}\\``)\n : [\"- No changed files were reported by the probe.\"];\n const phaseTasks = Array.isArray(phase.tasks) ? phase.tasks : [];\n const taskLines = phaseTasks.length > 0\n ? phaseTasks.map((task) => {\n const typedTask = task as { id?: string; checked?: boolean; text?: string };\n return `- \\`${typedTask.id ?? \"task\"}\\` ${typedTask.checked ? \"checked\" : \"unchecked\"}: ${typedTask.text ?? \"\"}`;\n })\n : [\"- No phase task data was available from the probe.\"];\n\n const sections = [\n \"---\",\n `date: ${date}`,\n `coordinate: ${coordinate}`,\n `closeout: ${mode}`,\n \"---\",\n \"\",\n `# ${title}`,\n \"\",\n \"## Purpose\",\n \"\",\n \"Document the closeout decisions for the current change set before drafting the commit message.\",\n \"\",\n \"## Changes\",\n \"\",\n ...fileLines,\n \"\",\n ];\n if (mode === \"phase\") {\n sections.push(\"## Task Status\", \"\", ...taskLines, \"\");\n }\n sections.push(\n \"## Gap Decisions\",\n \"\",\n \"No novel gaps were found.\",\n \"\",\n \"## Guide Decisions\",\n \"\",\n \"### Project\",\n \"\",\n \"Review shared project guidance and record the coverage verdict before finalizing.\",\n \"\",\n \"### Maintainer\",\n \"\",\n \"Record the coverage verdict (create/update-existing/link-only/none), effective Persona slug and rationale.\",\n \"\",\n \"### User\",\n \"\",\n \"Record the coverage verdict (create/update-existing/link-only/none), effective Persona slug and rationale.\",\n \"\",\n \"## Validation\",\n \"\",\n ...validations.map((command) => `- \\`${command}\\``),\n \"\",\n \"## Commit Message Source\",\n \"\",\n \"Use the repository commit-message convention and this history entry as the source for the draft.\",\n \"\",\n \"## Links\",\n \"\",\n \"- Add relevant PRD, plan, work, guide, or archive links before finalizing closeout.\",\n \"\",\n );\n return sections.join(\"\\n\");\n}\n\nfunction coordinateLabel(\n probe: Record<string, JsonValue>,\n phase: Record<string, JsonValue>,\n): string {\n const phaseCoordinate = valueAsRecord(phase.coordinate);\n if (typeof phaseCoordinate.w === \"number\" && typeof phaseCoordinate.r === \"number\") {\n return [\n `W${phaseCoordinate.w}`,\n `R${phaseCoordinate.r}`,\n typeof phaseCoordinate.p === \"number\" ? `P${phaseCoordinate.p}` : null,\n ].filter(Boolean).join(\" \");\n }\n const coordinates = Array.isArray(probe.coordinates) ? probe.coordinates : [];\n for (const rawCoordinate of coordinates) {\n const coordinate = valueAsRecord(rawCoordinate);\n if (typeof coordinate.w === \"number\" && typeof coordinate.r === \"number\") {\n return [\n `W${coordinate.w}`,\n `R${coordinate.r}`,\n typeof coordinate.p === \"number\" ? `P${coordinate.p}` : null,\n ].filter(Boolean).join(\" \");\n }\n }\n return \"Uncoordinated\";\n}\n\nfunction coordinateSlug(\n probe: Record<string, JsonValue>,\n phase: Record<string, JsonValue>,\n): string | null {\n const phaseCoordinate = valueAsRecord(phase.coordinate);\n if (typeof phaseCoordinate.w === \"number\" && typeof phaseCoordinate.r === \"number\") {\n return [\n `w${phaseCoordinate.w}`,\n `r${phaseCoordinate.r}`,\n typeof phaseCoordinate.p === \"number\" ? `p${phaseCoordinate.p}` : null,\n ].filter(Boolean).join(\"-\");\n }\n const coordinates = Array.isArray(probe.coordinates) ? probe.coordinates : [];\n for (const rawCoordinate of coordinates) {\n const coordinate = valueAsRecord(rawCoordinate);\n if (typeof coordinate.w === \"number\" && typeof coordinate.r === \"number\") {\n return [\n `w${coordinate.w}`,\n `r${coordinate.r}`,\n typeof coordinate.p === \"number\" ? `p${coordinate.p}` : null,\n ].filter(Boolean).join(\"-\");\n }\n }\n return null;\n}\n\nfunction slugify(value: string): string {\n return value.toLowerCase().replace(SLUG_RE, \"-\").replace(/^-+|-+$/g, \"\") || \"closeout\";\n}\n\nfunction safeRead(filePath: string): string {\n try {\n return readText(filePath);\n } catch {\n return \"\";\n }\n}\n","import { loadMakeDocsConfigOrThrow } from \"../../config\";\nimport { validateInstallationStoreRoot } from \"../../store/installation-state\";\nimport { existsSync, readdirSync, rmdirSync, rmSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n StoreSchemaNewerError,\n StoreUnavailableError,\n readWorkItemEvidence,\n recordWorkEvidence,\n resolveProjectIdentity,\n resolveStoreRoot,\n withStoreDatabase,\n type StoreDatabase,\n type WorkItemIdentity,\n} from \"../../store\";\nimport {\n loadJsonFile,\n normalizePath,\n repoRelativePath,\n runGit,\n utcNow,\n valueAsRecord,\n} from \"../shared\";\nimport { OperationError, type JsonValue } from \"../types\";\nimport type { OperationResult } from \"../types\";\nimport {\n parseWorkPhase,\n resolveWaveTarget,\n statePathFor,\n type WaveResolution,\n} from \"../work\";\n\nconst LOCKFILE_MANIFESTS: Record<string, string[]> = {\n \"Cargo.lock\": [\"Cargo.toml\"],\n \"package-lock.json\": [\"package.json\"],\n \"pnpm-lock.yaml\": [\"package.json\", \"pnpm-workspace.yaml\"],\n \"yarn.lock\": [\"package.json\"],\n \"bun.lockb\": [\"package.json\"],\n};\n\n/**\n * Work-execution evidence kinds recorded by the checkpoint operation\n * (W18 R10 P3, Stage 2). These are the genuine-state fields of the retired\n * per-repo checkpoint JSON per the keep/remove disposition in\n * `docs/assets/project/migrated-operations-inventory.md`: recorded\n * decisions and sign-offs that cannot be re-derived from the repository or\n * git. Everything else the old checkpoint file carried (wave/phase\n * resolution scaffolding, phase completion status, timestamps) is\n * re-derivable and is deliberately NOT an evidence kind. The full field\n * mapping is recorded in `packages/cli/src/store/README.md`.\n */\nexport const WORK_EVIDENCE_KINDS = [\n \"validation\",\n \"review\",\n \"closeout\",\n \"commit\",\n \"push\",\n \"notes\",\n \"commit-policy\",\n] as const;\n\nexport type WorkEvidenceKind = (typeof WORK_EVIDENCE_KINDS)[number];\n\n/** The legacy checkpoint sub-records ported one-to-one as evidence kinds. */\nconst LEGACY_RECORD_KINDS = [\n \"validation\",\n \"review\",\n \"closeout\",\n \"commit\",\n \"push\",\n] as const;\n\n/**\n * Records lifecycle evidence for a phase in the global store (R-BND-2,\n * R-PS-3). This operation consumes the canonical work-item identity produced\n * by the retained work-item identity resolver (`resolveWaveTarget`) — repo\n * root, wave slug, repo-relative phase path — and records evidence against\n * it; the store never re-derives the identity.\n *\n * Work-lifecycle state is no longer written under `.make-docs/runs/` or any\n * other repository path. When a legacy `.make-docs/runs/<wave-slug>/state.json`\n * exists, its genuine-state fields are migrated into evidence rows first and\n * the file is then removed (see {@link migrateLegacyCheckpointFile}).\n */\nexport function buildCheckpoint(options: {\n target: string;\n phase?: string;\n mode?: \"wave\" | \"phase\";\n commitPolicy?: string;\n status?: string;\n validationStatus?: string;\n validationCommands?: string[];\n reviewStatus?: string;\n reviewRequired?: boolean;\n closeoutStatus?: string;\n commitStatus?: string;\n commitSha?: string;\n pushStatus?: string;\n note?: string;\n /** Explicit store root override (tests/sandboxes); defaults to the resolved global store. */\n storeRoot?: string;\n}): Record<string, JsonValue> {\n const resolution = resolveWaveTarget(options.target);\n const repoRoot = resolution.repoRoot;\n const activePhasePath = options.phase ?? resolution.phasePath;\n if (!activePhasePath) {\n throw new OperationError(\"No phase path resolved for checkpoint.\");\n }\n const phaseRelative = repoRelativePath(activePhasePath, repoRoot);\n if (!phaseRelative) {\n throw new OperationError(\"Could not resolve a repo-relative phase path for checkpoint.\");\n }\n const projectId = requireProjectIdentity(repoRoot);\n const identity: WorkItemIdentity = {\n repoRoot,\n waveSlug: resolution.waveSlug,\n phasePath: phaseRelative,\n };\n\n const droppedFields: string[] = [];\n if (options.status) {\n droppedFields.push(\n \"status (re-derivable from the phase document's task checkboxes; not recorded as evidence)\",\n );\n }\n if (options.mode) {\n droppedFields.push(\"mode (resolution metadata, re-derivable; not recorded as evidence)\");\n }\n\n return withCheckpointStore(validateInstallationStoreRoot(resolution.repoRoot, resolveStoreRoot(options.storeRoot ? {storeRoot:options.storeRoot}:{})), (db) => {\n const legacyMigration = migrateLegacyCheckpointFile(db, resolution, projectId);\n\n const existingByKind = evidenceByKind(db, projectId, identity);\n const mergePatch = (kind: WorkEvidenceKind, patch: Record<string, JsonValue>) => {\n const payload = { ...valueAsRecord(existingByKind[kind]), ...patch };\n recordWorkEvidence(db, { projectId, identity, evidenceKind: kind, payload });\n };\n\n if (\n options.validationStatus ||\n (options.validationCommands && options.validationCommands.length > 0)\n ) {\n const patch: Record<string, JsonValue> = {};\n if (options.validationStatus) {\n patch.status = options.validationStatus;\n }\n if (options.validationCommands && options.validationCommands.length > 0) {\n patch.commands = options.validationCommands;\n }\n mergePatch(\"validation\", patch);\n }\n if (options.reviewStatus || options.reviewRequired !== undefined) {\n const patch: Record<string, JsonValue> = {};\n if (options.reviewStatus) {\n patch.status = options.reviewStatus;\n }\n if (options.reviewRequired !== undefined) {\n patch.required = options.reviewRequired;\n }\n mergePatch(\"review\", patch);\n }\n if (options.closeoutStatus) {\n mergePatch(\"closeout\", { status: options.closeoutStatus });\n }\n if (options.commitStatus || options.commitSha) {\n const patch: Record<string, JsonValue> = {};\n if (options.commitStatus) {\n patch.status = options.commitStatus;\n }\n if (options.commitSha) {\n patch.sha = options.commitSha;\n }\n mergePatch(\"commit\", patch);\n }\n if (options.pushStatus) {\n mergePatch(\"push\", { status: options.pushStatus });\n }\n if (options.commitPolicy) {\n mergePatch(\"commit-policy\", { policy: options.commitPolicy });\n }\n if (options.note) {\n const notes = Array.isArray(existingByKind.notes)\n ? [...(existingByKind.notes as JsonValue[])]\n : [];\n notes.push({ at: utcNow(), text: options.note });\n recordWorkEvidence(db, { projectId, identity, evidenceKind: \"notes\", payload: notes });\n }\n\n return {\n projectId,\n waveSlug: resolution.waveSlug,\n phasePath: phaseRelative,\n evidenceSource: \"global-store\",\n evidence: evidenceByKind(db, projectId, identity) as unknown as JsonValue,\n droppedFields,\n legacyMigration: legacyMigration as unknown as JsonValue,\n };\n });\n}\n\nexport function buildScopeReport(target: string, explicitChanged?: string[]): Record<string, JsonValue> {\n const resolution = resolveWaveTarget(target);\n if (!resolution.phasePath) {\n throw new OperationError(\"No phase path resolved for scope guard.\");\n }\n const repoRoot = resolution.repoRoot;\n const phase = parseWorkPhase(resolution.phasePath);\n const phaseRelative = normalizePath(path.relative(repoRoot, resolution.phasePath));\n const allowed = phase.declaredPaths;\n const audienceSlugs = new Set(loadMakeDocsConfigOrThrow(repoRoot).config.personas.map((persona) => persona.slug));\n const files = explicitChanged && explicitChanged.length > 0 ? explicitChanged : changedFilesForWork(repoRoot);\n const outOfScope: string[] = [];\n const allowedDerived: Array<{ path: string; reason: string }> = [];\n\n for (const file of files) {\n if (isAllowedScopePath(file, allowed, resolution.waveSlug, phaseRelative, audienceSlugs)) {\n continue;\n }\n const reason = managedStateReason(file, resolution.waveSlug) ?? derivedReason(file, files);\n if (reason) {\n allowedDerived.push({ path: file, reason });\n continue;\n }\n outOfScope.push(file);\n }\n\n return {\n phasePath: resolution.phasePath,\n declaredPaths: allowed,\n changedFiles: files,\n allowedDerived: allowedDerived as unknown as JsonValue,\n outOfScope,\n status: outOfScope.length === 0 ? \"passed\" : \"warning\",\n };\n}\n\n/**\n * Read-only gate over recorded evidence. Evidence is read from the global\n * store; a still-unmigrated legacy checkpoint file is consulted read-only for\n * evidence kinds the store does not hold yet, and is never written. Store or\n * identity trouble degrades to \"no recorded evidence\" plus a warning — a\n * missing store never blocks reading the repository (R-DB-4).\n */\nexport function buildPhaseGateReport(\n target: string,\n commitPolicy?: string,\n options: { storeRoot?: string } = {},\n): Record<string, JsonValue> {\n const resolution = resolveWaveTarget(target);\n if (!resolution.phasePath) {\n throw new OperationError(\"No phase path resolved for phase gate.\");\n }\n const phase = parseWorkPhase(resolution.phasePath);\n const view = readPhaseEvidenceView(resolution, resolution.phasePath, options.storeRoot);\n const policyEvidence = valueAsRecord(view.evidence[\"commit-policy\"]);\n const policy =\n commitPolicy ??\n (typeof policyEvidence.policy === \"string\" ? policyEvidence.policy : \"commit-required\");\n const blockers: string[] = [];\n\n if (phase.uncheckedTasks.length > 0) {\n blockers.push(`${phase.uncheckedTasks.length} unchecked task(s) remain in the phase doc`);\n }\n const validation = valueAsRecord(view.evidence.validation);\n if (validation.status !== \"passed\") {\n blockers.push(\"validation has not been recorded as passed\");\n }\n const files = changedFilesForWork(resolution.repoRoot);\n const review = valueAsRecord(view.evidence.review);\n const reviewRequired = Boolean(review.required) || hasCodeChanges(files);\n if (reviewRequired && review.status !== \"passed\" && review.status !== \"waived\") {\n blockers.push(\"code review is required and has not passed or been waived\");\n }\n const closeout = valueAsRecord(view.evidence.closeout);\n if (closeout.status !== \"passed\") {\n blockers.push(\"closeout-phase has not been recorded as passed\");\n }\n const commit = valueAsRecord(view.evidence.commit);\n if (policy === \"commit-required\" && !(commit.status === \"passed\" && typeof commit.sha === \"string\" && commit.sha.length > 0)) {\n blockers.push(\"phase commit is required but no committed SHA is recorded\");\n }\n if (policy === \"commit-and-push\") {\n if (!(commit.status === \"passed\" && typeof commit.sha === \"string\" && commit.sha.length > 0)) {\n blockers.push(\"phase commit is required but no committed SHA is recorded\");\n }\n const push = valueAsRecord(view.evidence.push);\n if (push.status !== \"passed\") {\n blockers.push(\"phase push is required but is not recorded as passed\");\n }\n }\n\n return {\n phasePath: resolution.phasePath,\n commitPolicy: policy,\n status: blockers.length === 0 ? \"passed\" : \"blocked\",\n blockers,\n evidenceSource: \"global-store\",\n evidence: view.evidence as unknown as JsonValue,\n projectIdentity: view.projectIdentity as unknown as JsonValue,\n legacyCheckpoint: view.legacyCheckpoint as unknown as JsonValue,\n warnings: view.warnings,\n };\n}\n\nexport function checkpointPhase(input: Parameters<typeof buildCheckpoint>[0]): OperationResult<Record<string, JsonValue>> {\n return {\n value: buildCheckpoint(input),\n provenance: {\n domain: \"lifecycle\",\n operation: \"checkpoint\",\n source: \"shared\",\n target: input.target,\n },\n };\n}\n\nexport function guardPhaseScope(input: {\n target: string;\n changed?: string[];\n}): OperationResult<Record<string, JsonValue>> {\n return {\n value: buildScopeReport(input.target, input.changed),\n provenance: {\n domain: \"lifecycle\",\n operation: \"scope-guard\",\n source: \"shared\",\n target: input.target,\n },\n };\n}\n\nexport function gatePhase(input: {\n target: string;\n commitPolicy?: string;\n}): OperationResult<Record<string, JsonValue>> {\n return {\n value: buildPhaseGateReport(input.target, input.commitPolicy),\n provenance: {\n domain: \"lifecycle\",\n operation: \"phase-gate\",\n source: \"shared\",\n target: input.target,\n },\n };\n}\n\nexport interface LegacyCheckpointMigration {\n /** Repo-relative path of the legacy checkpoint file. */\n legacyPath: string;\n /** True when a legacy file existed and was migrated. */\n migrated: boolean;\n /** Repo-relative phase paths whose evidence was ported. */\n migratedPhases: string[];\n /** True when the legacy file (and any emptied runs directories) was removed. */\n removed: boolean;\n}\n\n/**\n * One-way migration of a legacy `.make-docs/runs/<wave-slug>/state.json`\n * checkpoint file into work-execution evidence rows (R-PS-2).\n *\n * Field disposition (per `migrated-operations-inventory.md`; full mapping in\n * the store README):\n * - Ported (genuine state): the per-phase `validation`, `review`, `closeout`,\n * `commit`, and `push` records, per-phase `notes`, and the wave-level\n * `commitPolicy` (recorded per phase as `commit-policy`).\n * - Dropped (re-derivable): `schemaVersion`, `createdAt`/`updatedAt`,\n * `waveSlug`, `waveDir`, `target`, `coordinate`, `mode`, `nextPhasePath`,\n * `activePhasePath`, per-phase `phasePath` (it becomes the row key), and\n * per-phase `status` (re-derivable from the phase document's checkboxes).\n *\n * Evidence already present in the store is never overwritten by legacy data —\n * once relocated, the store is canonical. After a successful migration the\n * legacy file is removed (and emptied `runs/` directories pruned), because\n * relocated-canonical state must have no in-repo copy (R-MIR-2). This\n * migration runs only inside the mutating checkpoint operation; read-only\n * operations consult a not-yet-migrated file read-only and never delete it.\n */\nexport function migrateLegacyCheckpointFile(\n db: StoreDatabase,\n resolution: WaveResolution,\n projectId: string,\n): LegacyCheckpointMigration {\n const legacyAbsolute = statePathFor(resolution);\n const legacyPath = repoRelativePath(legacyAbsolute, resolution.repoRoot) ?? legacyAbsolute;\n if (!existsSync(legacyAbsolute)) {\n return { legacyPath, migrated: false, migratedPhases: [], removed: false };\n }\n\n let state: Record<string, JsonValue>;\n try {\n state = valueAsRecord(loadJsonFile(legacyAbsolute));\n } catch (error) {\n throw new OperationError(\n `Legacy checkpoint file ${legacyPath} is not valid JSON and cannot be migrated ` +\n `(${error instanceof Error ? error.message : String(error)}). Fix or remove it, then retry.`,\n );\n }\n\n const waveDirRelative =\n typeof state.waveDir === \"string\" && state.waveDir.length > 0\n ? state.waveDir\n : `docs/work/${resolution.waveSlug}`;\n const wavePolicy = typeof state.commitPolicy === \"string\" ? state.commitPolicy : null;\n const phases = valueAsRecord(state.phases);\n const migratedPhases: string[] = [];\n\n for (const [key, rawEntry] of Object.entries(phases)) {\n const entry = valueAsRecord(rawEntry);\n const phasePath =\n typeof entry.phasePath === \"string\" && entry.phasePath.length > 0\n ? entry.phasePath\n : key === \"wave\"\n ? waveDirRelative\n : `${waveDirRelative.replace(/\\/+$/g, \"\")}/${key}`;\n const identity: WorkItemIdentity = {\n repoRoot: resolution.repoRoot,\n waveSlug: resolution.waveSlug,\n phasePath,\n };\n const existing = evidenceByKind(db, projectId, identity);\n let ported = false;\n\n for (const kind of LEGACY_RECORD_KINDS) {\n if (existing[kind] !== undefined) {\n continue;\n }\n const record = valueAsRecord(entry[kind]);\n if (Object.keys(record).length === 0) {\n continue;\n }\n recordWorkEvidence(db, { projectId, identity, evidenceKind: kind, payload: record });\n ported = true;\n }\n if (existing.notes === undefined && Array.isArray(entry.notes) && entry.notes.length > 0) {\n recordWorkEvidence(db, { projectId, identity, evidenceKind: \"notes\", payload: entry.notes });\n ported = true;\n }\n if (existing[\"commit-policy\"] === undefined && wavePolicy) {\n recordWorkEvidence(db, {\n projectId,\n identity,\n evidenceKind: \"commit-policy\",\n payload: { policy: wavePolicy },\n });\n ported = true;\n }\n if (ported) {\n migratedPhases.push(phasePath);\n }\n }\n\n rmSync(legacyAbsolute, { force: true });\n pruneEmptyDirectory(path.dirname(legacyAbsolute));\n pruneEmptyDirectory(path.dirname(path.dirname(legacyAbsolute)));\n\n return { legacyPath, migrated: true, migratedPhases, removed: true };\n}\n\ninterface PhaseEvidenceView {\n evidence: Record<string, JsonValue>;\n projectIdentity: { status: string; projectId: string | null };\n legacyCheckpoint: { path: string; present: boolean };\n warnings: string[];\n}\n\n/**\n * Read-only evidence view for a phase: global-store rows first, then a\n * not-yet-migrated legacy checkpoint file for kinds the store lacks. Never\n * writes the store, the legacy file, or any repository path.\n */\nfunction readPhaseEvidenceView(\n resolution: WaveResolution,\n phasePath: string,\n storeRoot?: string,\n): PhaseEvidenceView {\n const repoRoot = resolution.repoRoot;\n const phaseRelative = repoRelativePath(phasePath, repoRoot) ?? phasePath;\n const warnings: string[] = [];\n const evidence: Record<string, JsonValue> = {};\n const identityResolution = resolveProjectIdentity(repoRoot);\n const projectIdentity = {\n status: identityResolution.status,\n projectId: identityResolution.status === \"resolved\" ? identityResolution.projectId : null,\n };\n\n if (identityResolution.status === \"resolved\") {\n try {\n const rows = withStoreDatabase(\n resolveStoreRoot(storeRoot ? { storeRoot } : {}),\n (db) =>\n readWorkItemEvidence(db, {\n projectId: identityResolution.projectId,\n identity: { waveSlug: resolution.waveSlug, phasePath: phaseRelative },\n }),\n );\n for (const row of rows) {\n evidence[row.evidenceKind] = row.payload;\n }\n } catch (error) {\n warnings.push(\n `Recorded evidence could not be read from the global store (${error instanceof Error ? error.message : String(error)}); ` +\n \"treating the phase as having no recorded evidence.\",\n );\n }\n } else {\n warnings.push(\n `Recorded evidence unavailable: ${describeIdentityGap(identityResolution.status)}`,\n );\n }\n\n const legacyAbsolute = statePathFor(resolution);\n const legacyPresent = existsSync(legacyAbsolute);\n if (legacyPresent) {\n try {\n const state = valueAsRecord(loadJsonFile(legacyAbsolute));\n const entry = valueAsRecord(valueAsRecord(state.phases)[phaseKey(phasePath)]);\n for (const kind of LEGACY_RECORD_KINDS) {\n if (evidence[kind] !== undefined) {\n continue;\n }\n const record = valueAsRecord(entry[kind]);\n if (Object.keys(record).length > 0) {\n evidence[kind] = record;\n }\n }\n if (evidence.notes === undefined && Array.isArray(entry.notes) && entry.notes.length > 0) {\n evidence.notes = entry.notes;\n }\n if (evidence[\"commit-policy\"] === undefined && typeof state.commitPolicy === \"string\") {\n evidence[\"commit-policy\"] = { policy: state.commitPolicy };\n }\n warnings.push(\n \"A legacy checkpoint file is present and was consulted read-only; the next checkpoint migrates it to the global store and removes it.\",\n );\n } catch {\n warnings.push(\n \"A legacy checkpoint file is present but unreadable; it was ignored.\",\n );\n }\n }\n\n return {\n evidence,\n projectIdentity,\n legacyCheckpoint: {\n path: repoRelativePath(legacyAbsolute, repoRoot) ?? legacyAbsolute,\n present: legacyPresent,\n },\n warnings,\n };\n}\n\nfunction evidenceByKind(\n db: StoreDatabase,\n projectId: string,\n identity: WorkItemIdentity,\n): Record<string, JsonValue> {\n const byKind: Record<string, JsonValue> = {};\n const rows = readWorkItemEvidence(db, {\n projectId,\n identity: { waveSlug: identity.waveSlug, phasePath: identity.phasePath },\n });\n for (const row of rows) {\n byKind[row.evidenceKind] = row.payload;\n }\n return byKind;\n}\n\nfunction requireProjectIdentity(repoRoot: string): string {\n const resolution = resolveProjectIdentity(repoRoot);\n if (resolution.status === \"resolved\") {\n return resolution.projectId;\n }\n throw new OperationError(\n `Cannot record lifecycle evidence: ${describeIdentityGap(resolution.status)} ` +\n \"Evidence is keyed by the manifest-minted project identifier and stored in the global store, never under a repository path.\",\n );\n}\n\nfunction describeIdentityGap(status: string): string {\n switch (status) {\n case \"unminted\":\n return \"this project's manifest predates the stable project identifier; run `make-docs` once to mint it.\";\n case \"no-manifest\":\n return \"this repository has no .make-docs/manifest.json; run `make-docs` to set up Make Docs first.\";\n default:\n return \"this project's .make-docs/manifest.json is unreadable; repair it and rerun `make-docs`.\";\n }\n}\n\nfunction withCheckpointStore<T>(\n storeRoot: string | undefined,\n fn: (db: StoreDatabase) => T,\n): T {\n try {\n return withStoreDatabase(resolveStoreRoot(storeRoot ? { storeRoot } : {}), fn);\n } catch (error) {\n if (error instanceof OperationError) {\n throw error;\n }\n if (error instanceof StoreUnavailableError || error instanceof StoreSchemaNewerError) {\n throw new OperationError(error.message);\n }\n throw new OperationError(\n `Could not record lifecycle evidence in the global store: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nfunction pruneEmptyDirectory(directory: string): void {\n try {\n if (existsSync(directory) && readdirSync(directory).length === 0) {\n rmdirSync(directory);\n }\n } catch {\n // Pruning is best-effort tidiness; a surviving empty directory is harmless.\n }\n}\n\nfunction phaseKey(value: string | null | undefined): string {\n if (!value) {\n return \"wave\";\n }\n return path.basename(value);\n}\n\nfunction isAllowedScopePath(\n filePath: string,\n allowed: string[],\n waveSlug: string,\n phasePath: string,\n audienceSlugs: Set<string>,\n): boolean {\n const normalized = filePath.replace(/^\\/+|\\/+$/g, \"\");\n if (normalized === phasePath || normalized.startsWith(`docs/work/${waveSlug}/`)) {\n return true;\n }\n const audience = /^docs\\/assets\\/([^/]+)\\//.exec(normalized)?.[1];\n if (normalized.startsWith(\".make-docs/archive/history/\") || (audience && audienceSlugs.has(audience))) {\n return true;\n }\n for (const item of allowed) {\n let clean = item.replace(/^\\/+|\\/+$/g, \"\");\n if (clean.startsWith(\"./\")) {\n clean = clean.slice(2);\n }\n if (!clean) {\n continue;\n }\n if (normalized === clean || normalized.startsWith(`${clean.replace(/\\/+$/g, \"\")}/`)) {\n return true;\n }\n }\n return false;\n}\n\nfunction changedFilesForWork(repoRoot: string): string[] {\n const output = runGit(repoRoot, [\"status\", \"--porcelain\"]);\n return [...new Set(output.split(/\\r?\\n/).filter(Boolean).map((line) => {\n const raw = line.slice(3);\n return raw.includes(\" -> \") ? raw.split(\" -> \", 2)[1]! : raw;\n }))].sort();\n}\n\nfunction derivedReason(filePath: string, files: string[]): string | null {\n const manifests = LOCKFILE_MANIFESTS[path.basename(filePath)];\n if (!manifests) {\n return null;\n }\n const normalizedFiles = new Set(files.map((file) => file.replace(/^\\/+|\\/+$/g, \"\")));\n const parent = normalizePath(path.dirname(filePath));\n for (const manifest of manifests) {\n const candidate = parent === \".\" ? manifest : `${parent}/${manifest}`;\n if (normalizedFiles.has(candidate)) {\n return `${path.basename(filePath)} is derived from changed dependency manifest ${candidate}`;\n }\n }\n return null;\n}\n\nfunction managedStateReason(filePath: string, waveSlug: string): string | null {\n const normalized = filePath.replace(/^\\/+|\\/+$/g, \"\");\n const expectedPrefix = `.make-docs/runs/${waveSlug}/`;\n if (normalized.startsWith(expectedPrefix) && normalized.endsWith(\"/state.json\")) {\n return \"legacy work-on-wave checkpoint state (migrated to the global store)\";\n }\n return null;\n}\n\nfunction hasCodeChanges(files: string[]): boolean {\n const codeSuffixes = new Set([\n \".ts\",\n \".tsx\",\n \".js\",\n \".mjs\",\n \".cjs\",\n \".py\",\n \".rs\",\n \".go\",\n \".java\",\n \".rb\",\n \".sh\",\n \".swift\",\n \".kt\",\n \".cs\",\n \".php\",\n ]);\n return files.some((file) => codeSuffixes.has(path.extname(file)));\n}\n","import { listOperations } from \"./registry\";\nimport type { OperationDomainDescriptor } from \"./types\";\n\nexport type {\n JsonValue,\n OperationCommandDescriptor,\n OperationDomainDescriptor,\n OperationDomainName,\n OperationProvenance,\n OperationRenderMode,\n OperationResult,\n} from \"./types\";\nexport { OperationError } from \"./types\";\nexport { probeCloseout } from \"./closeout\";\nexport { checkpointPhase, gatePhase, guardPhaseScope } from \"./lifecycle\";\nexport {\n isActionPrefixedPrdFilename,\n PRD_AUTHORITY_DIAGNOSTIC_CODES,\n validatePrdAuthority,\n} from \"./prd\";\nexport type {\n PrdAuthorityDiagnostic,\n PrdAuthorityDiagnosticCode,\n PrdAuthorityValidationReport,\n} from \"./prd\";\nexport {\n planWorkPhase,\n readWaveStatus,\n readWorkPhaseState,\n resolveWorkWave,\n} from \"./work\";\n\n/**\n * Domain listing derived from the operation registry (R-REG-2, R-RUN-2):\n * groups `listOperations()` identifiers by their domain segment so surfaces\n * such as `make_docs_operation_domains` advertise exactly the registry —\n * pruned legacy operations never appear here.\n */\nexport function listOperationDomains(): OperationDomainDescriptor[] {\n const domains = new Map<string, OperationDomainDescriptor>();\n for (const operation of listOperations()) {\n let domain = domains.get(operation.domain);\n if (!domain) {\n domain = { name: operation.domain, commands: [] };\n domains.set(operation.domain, domain);\n }\n domain.commands.push({\n id: operation.id,\n summary: operation.summary,\n mutates: operation.mutates === \"write\",\n status: operation.status,\n });\n }\n return [...domains.values()];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,OACK;;;ACLP,OAAO,UAAU;AACjB,SAAS,WAAW,gBAAgB;AA0BpC,SAAS,yBAAyB,OAAuB;AACvD,MAAI,iBAAiB,wBAAwB;AAC3C,UAAM,IAAI,SAAS,UAAU,eAAe,MAAM,SAAS;AAAA,MACzD,UAAU;AAAA,QACR,MAAM,MAAM;AAAA,QACZ,UAAU,MAAM;AAAA,QAChB,GAAI,MAAM,MAAM,EAAE,KAAK,MAAM,IAAI,IAAI,CAAC;AAAA,QACtC,GAAI,MAAM,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI,CAAC;AAAA,MAC3C;AAAA,IACF,CAAC;AAAA,EACH;AACA,QAAM;AACR;AAGA,eAAsB,uBAAuB,aAAa,QAAQ,IAAI,GAAG;AACvE,QAAM,aAAa,MAAM;AAAA,IACvB;AAAA,IACA,EAAE,YAAY,KAAK,QAAQ,UAAU,EAAE;AAAA,IACvC,uBAAuB;AAAA,MACrB,SAAS;AAAA,MACT,OAAO;AAAA,MACP,mBAAmB,QAAQ,IAAI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AAA,IACT,SAAS;AAAA,MACP;AAAA,QACE,MAAM;AAAA,QACN,MAAM,KAAK,UAAU,mBAAmB,MAAM,CAAC;AAAA,MACjD;AAAA,IACF;AAAA,IACA;AAAA,EACF;AACF;","names":["path","path","existsSync","readdirSync","path","path"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/setup-system.ts"],"sourcesContent":["import { confirm, isCancel, select } from \"@clack/prompts\";\nimport path from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport { ExecutableVerificationError, FIRST_PARTY_HARNESS_ADAPTERS, listBoundedHarnessCommandRules, requireFirstPartyHarnessAdapter, resolveHarnessMethodSupport, verifyMakeDocsExecutable, type HarnessAccessReceipt, type HarnessCommandRule, type HarnessCommandRuleAuthority, type HarnessMethodDefinition, type HarnessMethodSelection, type VerifiedExecutableIdentity } from \"./harness-access/index.js\";\nimport { resolveEffectiveHarnessIntegration, type ProjectHarnessIntegrationRecord } from \"./config\";\nimport { listHarnessCommandRules, listOperationAccessFacts, validateRegistryHarnessCommandRules } from \"./operations/registry\";\nimport { getStoreDatabasePath, resolveStoreRoot } from \"./store/paths\";\nimport { loadGlobalConfig, writeGlobalConfig, type GlobalConfig } from \"./store/global-config\";\nimport { readCurrentHarnessIntegrationReceipt, recordHarnessIntegrationReceipt } from \"./store/harness-integration-receipts\";\nimport { completeHarnessSystemOperation, prepareHarnessSystemOperation, readPendingHarnessSystemOperation, type PendingHarnessSystemOperation } from \"./store/harness-system-operations\";\nimport { readInstallationStatus } from \"./store/installation-state\";\nimport type { SetupHarnessState } from \"./setup-state\";\nimport type { Harness } from \"./types\";\nimport { platform } from \"./platform\";\n\nexport const SYSTEM_COMMAND_RULE_AUTHORITY: HarnessCommandRuleAuthority = Object.freeze({\n list: listHarnessCommandRules,\n validate: validateRegistryHarnessCommandRules,\n});\n\nexport type SystemSetupStatus = \"configured\" | \"skipped-none\" | \"blocked\" | \"partial\" | \"failed\" | \"recovery\" | \"unchanged\";\nexport interface SystemSetupResult { schemaVersion: 2; status: SystemSetupStatus; scope: \"machine\"; selections: Record<Harness, HarnessMethodSelection>; configured: Harness[]; skipped: Harness[]; blocked: Array<{ harness: Harness; reason: string; nextAction: string }>; attemptedWork: string[]; mutationState: \"none\" | \"planned\" | \"partial\" | \"verified\"; failedCondition: string | null; nextAction: string | null; recoveryAction: string | null; }\nexport type SystemHarnessState = \"current\" | \"drifted\" | \"blocked\" | \"unsupported\" | \"incomplete\" | \"pending\";\nexport interface SystemHarnessOperationEffect { operation: string; store: \"none\" | \"read\" | \"write\"; project: \"none\" | \"read\" | \"write\"; hostConfig: \"none\" | \"read\" | \"write\"; }\nexport interface SystemHarnessPlan { harness: Harness; method: string; status: SystemHarnessState; operations: string[]; operationEffects: SystemHarnessOperationEffect[]; allowedStoreOperations: HarnessMethodDefinition[\"allowedStoreOperations\"]; ownedEntries: string[]; machineFiles: string[]; changed: boolean; detail: string; apply(): Promise<void>; verify(): Promise<boolean>; pendingOperation?(): boolean; }\nexport interface RunSystemSetupOptions { dryRun: boolean; yes: boolean; harnesses: Record<Harness, boolean>; methods?: Partial<Record<Harness, HarnessMethodSelection>>; promptForMethods?: boolean; projectHarnessIntegrations?: readonly ProjectHarnessIntegrationRecord[]; targetRoot?: string; storeRoot?: string; machineRoot?: string; executable?: VerifiedExecutableIdentity; appliedVersion?: string; persistIntent?: boolean; onReview?: (review: string) => void; afterNativeApplyForTests?: () => void | Promise<void>; }\n\ninterface SystemIntentChange {\n harness: Harness;\n before: HarnessMethodSelection;\n after: HarnessMethodSelection;\n}\n\nexport interface SystemIntentProjection {\n config: GlobalConfig;\n changes: SystemIntentChange[];\n}\n\nexport interface PreparedSystemSetup {\n options: RunSystemSetupOptions;\n machineRoot: string;\n targetRoot: string;\n storeRoot: string;\n selections: Record<Harness, HarnessMethodSelection>;\n plans: SystemHarnessPlan[];\n intent: SystemIntentProjection;\n review: string;\n changed: boolean;\n}\n\ninterface ExecutableVerificationAttempt {\n executable?: VerifiedExecutableIdentity;\n error?: Error;\n}\n\nexport async function runSystemSetupCommand(options: RunSystemSetupOptions): Promise<SystemSetupResult> {\n const resumed = await resumePendingSystemSetupCommand(options);\n if (resumed) return resumed;\n const prepared = await prepareSystemSetupCommand(options);\n options.onReview?.(prepared.review);\n const blockedPlans = prepared.plans.filter(plan => plan.status === \"blocked\" || plan.status === \"unsupported\");\n const runnablePlans = prepared.plans.filter(plan => plan.status !== \"blocked\" && plan.status !== \"unsupported\");\n if (blockedPlans.length && runnablePlans.length === 0) {\n const blocked = blockedPlans.map(plan => ({ harness: plan.harness, reason: plan.detail, nextAction: plan.detail }));\n return makeResult(\"blocked\", prepared.selections, [], blocked, blocked[0]?.nextAction ?? null);\n }\n if (options.dryRun) {\n const blocked = blockedPlans.map(plan => ({ harness: plan.harness, reason: plan.detail, nextAction: plan.detail }));\n return makeResult(\n blocked.length || prepared.changed ? \"partial\" : prepared.plans.length ? \"unchanged\" : \"skipped-none\",\n prepared.selections,\n [],\n blocked,\n prepared.changed ? \"Run `make-docs setup system --yes` to apply the reviewed machine changes.\" : blocked[0]?.nextAction ?? null,\n );\n }\n if (prepared.changed && !options.yes) {\n const approved = await confirm({ message: \"Apply the reviewed changes to this computer?\", initialValue: false, active: \"Yes\", inactive: \"No\", withGuide: true });\n if (isCancel(approved) || !approved) return makeResult(\"blocked\", prepared.selections, [], [], \"Run `make-docs setup system` and approve the reviewed machine changes.\");\n }\n return applyPreparedSystemSetup(prepared);\n}\n\nexport async function resumePendingSystemSetupCommand(\n options: RunSystemSetupOptions,\n): Promise<SystemSetupResult | null> {\n return resumePendingSystemSetup(\n options,\n options.machineRoot ?? platform.userHome(),\n options.targetRoot ?? process.cwd(),\n options.storeRoot ?? resolveStoreRoot(),\n );\n}\n\nexport async function prepareSystemSetupCommand(options: RunSystemSetupOptions): Promise<PreparedSystemSetup> {\n const machineRoot = options.machineRoot ?? platform.userHome();\n const targetRoot = options.targetRoot ?? process.cwd();\n const storeRoot = options.storeRoot ?? resolveStoreRoot();\n const executableAttempt: ExecutableVerificationAttempt = options.executable\n ? { executable: options.executable }\n : tryVerifyCurrentExecutable();\n const selections = await selectMethods(options, machineRoot, storeRoot, executableAttempt);\n validateProjectHarnessIntegrations(options.projectHarnessIntegrations, selections, options.harnesses);\n const plans = buildAdapterPlans(options, selections, machineRoot, targetRoot, storeRoot, executableAttempt);\n const intent = buildIntentProjection(storeRoot, selections, options.harnesses, options.persistIntent !== false);\n const detection = inspectSystemHarnesses(machineRoot).filter(state => options.harnesses[state.harness]);\n const review = [\n ...detection.map(state => `${label(state.harness)} detection: ${state.state}${state.detail ? ` (${state.detail})` : \"\"}${state.nextAction ? ` Next: ${state.nextAction}` : \"\"}`),\n \"Detection is a hint. It does not prove support or limit your choice.\",\n \"\",\n ...renderMethodSupport(machineRoot, options.harnesses, executableAttempt),\n \"Generic MCP client: available; Make Docs prints a standard configuration and does not edit client-owned files. Next: rerun setup with `--generic-mcp-client <label>`.\",\n \"\",\n renderSystemPlans(plans),\n \"\",\n renderIntentChanges(storeRoot, intent.changes),\n ].join(\"\\n\");\n return {\n options,\n machineRoot,\n targetRoot,\n storeRoot,\n selections,\n plans,\n intent,\n review,\n changed: plans.some(plan => plan.changed) || intent.changes.length > 0,\n };\n}\n\n/** Run only the method screens. Full project setup uses this between harness selection and shared Skills. */\nexport async function promptForSystemSetupMethods(\n options: RunSystemSetupOptions,\n): Promise<Record<Harness, HarnessMethodSelection>> {\n const machineRoot = options.machineRoot ?? platform.userHome();\n const storeRoot = options.storeRoot ?? resolveStoreRoot();\n return selectMethods(\n { ...options, promptForMethods: true, yes: false, dryRun: false },\n machineRoot,\n storeRoot,\n options.executable ? { executable: options.executable } : tryVerifyCurrentExecutable(),\n );\n}\n\nexport async function applyPreparedSystemSetup(prepared: PreparedSystemSetup): Promise<SystemSetupResult> {\n const { options, plans, selections, targetRoot, storeRoot } = prepared;\n const blockedPlans = plans.filter(plan => plan.status === \"blocked\" || plan.status === \"unsupported\");\n const blocked: SystemSetupResult[\"blocked\"] = blockedPlans.map(plan => ({\n harness: plan.harness,\n reason: plan.detail,\n nextAction: plan.detail,\n }));\n const runnable = plans.filter(plan => plan.status !== \"blocked\" && plan.status !== \"unsupported\");\n const changed = runnable.filter(plan => plan.changed);\n const configured: Harness[] = [];\n let recoveryAction: string | null = null;\n for (const plan of runnable) {\n if (!plan.changed) {\n if (options.persistIntent !== false) {\n persistReviewedHarnessIntent(storeRoot, prepared.intent.config, plan.harness);\n }\n configured.push(plan.harness);\n continue;\n }\n try {\n await plan.apply();\n if (!(await plan.verify())) {\n const recovery = recoveryActionForPlanFailure(\n plan,\n \"The applied native entry did not verify.\",\n targetRoot,\n storeRoot,\n );\n blocked.push({ harness: plan.harness, reason: \"The applied native entry did not verify.\", nextAction: recovery });\n recoveryAction ??= recovery;\n if (plan.pendingOperation?.()) break;\n continue;\n }\n if (options.persistIntent !== false) {\n persistReviewedHarnessIntent(storeRoot, prepared.intent.config, plan.harness);\n }\n configured.push(plan.harness);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n const recovery = recoveryActionForPlanFailure(\n plan,\n reason,\n targetRoot,\n storeRoot,\n );\n blocked.push({ harness: plan.harness, reason, nextAction: recovery });\n recoveryAction ??= recovery;\n if (plan.pendingOperation?.()) break;\n }\n }\n if (options.persistIntent !== false) {\n persistReviewedDisabledIntents(storeRoot, prepared.intent.config, selections, options.harnesses);\n }\n if (blocked.length > 0) {\n const status: SystemSetupStatus = recoveryAction\n ? configured.length > 0 ? \"partial\" : \"recovery\"\n : configured.length > 0 ? \"partial\" : \"blocked\";\n return makeResult(status, selections, configured, blocked, recoveryAction ?? blocked[0]?.nextAction ?? null);\n }\n if (!changed.length) {\n if (prepared.intent.changes.length > 0) {\n if ((Object.keys(options.harnesses) as Harness[]).some(harness => options.harnesses[harness] && selections[harness] !== \"none\")) {\n return makeResult(\"configured\", selections, [], [], null);\n }\n return makeResult(\"skipped-none\", selections, [], [], null);\n }\n if (plans.length) {\n return makeResult(\"unchanged\", selections, plans.map(plan => plan.harness), [], null);\n }\n return makeResult(\"skipped-none\", selections, [], [], null);\n }\n return makeResult(\"configured\", selections, configured, [], null);\n}\n\nfunction persistReviewedHarnessIntent(\n storeRoot: string,\n projected: GlobalConfig,\n harness: Harness,\n): void {\n const intent = projected.settings.harnesses[harness];\n if (!intent) return;\n const current = loadGlobalConfig(storeRoot).config;\n current.settings.harnesses[harness] = { ...intent, accessCeiling: { ...intent.accessCeiling } };\n writeGlobalConfig(storeRoot, current);\n}\n\nfunction persistReviewedDisabledIntents(\n storeRoot: string,\n projected: GlobalConfig,\n selections: Record<Harness, HarnessMethodSelection>,\n included: Record<Harness, boolean>,\n): void {\n for (const harness of Object.keys(selections) as Harness[]) {\n if (included[harness] && selections[harness] === \"none\") {\n persistReviewedHarnessIntent(storeRoot, projected, harness);\n }\n }\n}\n\nfunction recoveryActionForPlanFailure(\n plan: SystemHarnessPlan,\n reason: string,\n targetRoot: string,\n storeRoot: string,\n): string {\n if (reason.includes(\"Run make-docs setup to review and apply the compatibility bridge\")) {\n return \"Run `make-docs setup` to review and apply the Store compatibility bridge. Full setup will retry the approved machine work after that prerequisite verifies.\";\n }\n if (reason.includes(\"Store operation is already pending\")) {\n try {\n const currentProject = readInstallationStatus(targetRoot, storeRoot);\n const pendingProject = \"pendingOperation\" in currentProject\n ? currentProject.pendingOperation\n : null;\n if (currentProject.status === \"recovery-required\" && pendingProject) {\n return \"Run `make-docs setup` again. Setup will review the unfinished work for this project before it builds a new computer plan.\";\n }\n if (\n currentProject.status === \"recovery-required\" &&\n \"toolOperations\" in currentProject &&\n currentProject.toolOperations.length > 0\n ) {\n return \"A machine-wide Store operation is still pending. Finish or recover that recorded tool operation, then run `make-docs setup` again to build a current computer plan.\";\n }\n if (currentProject.status === \"writer-active\") {\n return \"This project has an active writer. Wait for it to finish, then run `make-docs setup` again to build a current computer plan.\";\n }\n return \"This project has no pending operation to recover. Wait for the reported Store writer to finish, then run `make-docs setup` again. Setup will build a new computer plan from current Store state.\";\n } catch {\n return \"Run `make-docs setup` again. Setup will read the current project state before it builds a new computer plan.\";\n }\n }\n if (plan.pendingOperation?.()) {\n return `Run \\`make-docs setup system\\` to resume the recorded ${label(plan.harness)} machine change.`;\n }\n return `Correct the reported ${label(plan.harness)} prerequisite, then run \\`make-docs setup system\\` to review a new machine plan.`;\n}\n\nasync function selectMethods(\n options: RunSystemSetupOptions,\n root: string,\n storeRoot: string,\n executableAttempt: ExecutableVerificationAttempt,\n): Promise<Record<Harness, HarnessMethodSelection>> {\n const chosen: Record<Harness, HarnessMethodSelection> = { codex: \"none\", \"claude-code\": \"none\" };\n const existing = loadGlobalConfig(storeRoot).config.settings.harnesses;\n for (const adapter of FIRST_PARTY_HARNESS_ADAPTERS) {\n const saved = existing[adapter.harnessId];\n const savedMethod = saved?.selected && adapter.methods.some(method => method.id === saved.maximumMethod)\n ? saved.maximumMethod as HarnessMethodSelection\n : \"none\";\n chosen[adapter.harnessId] = savedMethod;\n if (!options.harnesses[adapter.harnessId]) continue;\n const supplied = options.methods?.[adapter.harnessId];\n if (supplied) { chosen[adapter.harnessId] = supplied; continue; }\n if (!options.promptForMethods || options.yes || options.dryRun) {\n throw new Error(\n `${adapter.displayName} is included but has no explicit method. Pass the matching method flag, including \\`none\\` to disable it.`,\n );\n }\n const answer = await select<HarnessMethodSelection>({ message: `${adapter.displayName} connection method`, options: [\n { value: \"none\", label: \"None\", hint: \"No native file changes. Resource reads still need no Store access.\" },\n ...adapter.methods.map(method => { const support = resolveHarnessMethodSupport(adapter, method.id); const available = support.selectable && executableAttempt.executable !== undefined; const prerequisite = executableAttempt.error ? formatExecutableVerificationFailure(executableAttempt.error) : null; return { value: method.id, label: `${method.id} (${available ? \"available\" : \"unavailable\"})`, hint: `${path.resolve(root, method.nativeFile(\"machine\"))}. ${prerequisite ?? `${support.reason} Next: ${support.nextAction}`}` }; }),\n ], initialValue: savedMethod });\n if (isCancel(answer) || typeof answer !== \"string\") continue;\n const method = answer as HarnessMethodSelection;\n if (method === \"none\") { chosen[adapter.harnessId] = \"none\"; continue; }\n chosen[adapter.harnessId] = method;\n }\n return chosen;\n}\n\nfunction buildAdapterPlans(options: RunSystemSetupOptions, selections: Record<Harness, HarnessMethodSelection>, root: string, targetRoot: string, storeRoot: string, executableAttempt: ExecutableVerificationAttempt): SystemHarnessPlan[] {\n const rules = listBoundedHarnessCommandRules(SYSTEM_COMMAND_RULE_AUTHORITY);\n const plans: SystemHarnessPlan[] = [];\n for (const adapter of FIRST_PARTY_HARNESS_ADAPTERS) {\n const method = selections[adapter.harnessId];\n if (!options.harnesses[adapter.harnessId] || method === \"none\") continue;\n const support = resolveHarnessMethodSupport(adapter, method);\n const definition = adapter.methods.find(item => item.id === method)!;\n const nativeFile = path.resolve(root, definition.nativeFile(\"machine\"));\n const reviewFacts = methodReviewFacts(definition, rules);\n const currentReceipt: HarnessAccessReceipt | null = existsSync(getStoreDatabasePath(storeRoot))\n ? readCurrentHarnessIntegrationReceipt(targetRoot, storeRoot, \"machine\", adapter.harnessId, method)\n : null;\n if (!support.selectable) { plans.push(blockedPlan(adapter.harnessId, method, `${support.reason} Next: ${support.nextAction}`, nativeFile, reviewFacts)); continue; }\n if (!executableAttempt.executable) {\n plans.push(blockedPlan(adapter.harnessId, method, formatExecutableVerificationFailure(executableAttempt.error), nativeFile, reviewFacts));\n continue;\n }\n const executable = executableAttempt.executable;\n const commandRules = definition.requiresCommandRules ? rules : undefined;\n const adapterPlan = adapter.plan({ method, scope: \"machine\", root, executable, ...(commandRules ? { commandRules, commandRuleAuthority: SYSTEM_COMMAND_RULE_AUTHORITY } : {}), ...(currentReceipt ? { receipt: currentReceipt } : {}) });\n let receipt: HarnessAccessReceipt | undefined;\n let pending: PendingHarnessSystemOperation | undefined;\n plans.push({ harness: adapter.harnessId, method, status: adapterPlan.state === \"current\" ? \"current\" : adapterPlan.state === \"missing\" ? \"incomplete\" : adapterPlan.state, ...reviewFacts, machineFiles: adapterPlan.changes.map(change => change.path), changed: adapterPlan.changes.some(change => change.action !== \"none\"), detail: adapterPlan.nextAction,\n async apply() { pending = prepareHarnessSystemOperation({ targetRoot, storeRoot, adapterId: adapter.id, harnessId: adapter.harnessId, plan: adapterPlan, appliedVersion: options.appliedVersion ?? executable.packageVersion, verifiedAt: new Date().toISOString() }); receipt = adapter.apply({ plan: adapterPlan, approved: true, operationId: pending.operationId, appliedVersion: pending.appliedVersion, verifiedAt: pending.verifiedAt }).receipt; await options.afterNativeApplyForTests?.(); },\n async verify() { const exactReceipt = receipt ?? currentReceipt; const verification = adapter.verify({ method, scope: \"machine\", root, executable, ...(commandRules ? { commandRules, commandRuleAuthority: SYSTEM_COMMAND_RULE_AUTHORITY } : {}), ...(exactReceipt ? { receipt: exactReceipt } : {}) }); if (verification.state !== \"current\" || !exactReceipt) return false; if (receipt) recordHarnessIntegrationReceipt(targetRoot, storeRoot, receipt); if (pending) completeHarnessSystemOperation(targetRoot, storeRoot, pending, exactReceipt); return true; },\n pendingOperation() { return pending !== undefined; },\n });\n }\n return plans;\n}\n\nasync function resumePendingSystemSetup(\n options: RunSystemSetupOptions,\n machineRoot: string,\n targetRoot: string,\n storeRoot: string,\n): Promise<SystemSetupResult | null> {\n const pending = readPendingHarnessSystemOperation(targetRoot, storeRoot);\n if (!pending) return null;\n const selections: Record<Harness, HarnessMethodSelection> = { codex: \"none\", \"claude-code\": \"none\" };\n selections[pending.harnessId] = pending.connectionMethod;\n const recoveryAction = `Run \\`make-docs setup system --target ${JSON.stringify(targetRoot)}\\` again to resume machine setup ${pending.operationId}.`;\n if (options.dryRun) {\n return makeResult(\"recovery\", selections, [], [{ harness: pending.harnessId, reason: `Machine setup ${pending.operationId} is pending.`, nextAction: recoveryAction }], recoveryAction);\n }\n try {\n const adapter = requireFirstPartyHarnessAdapter(pending.harnessId);\n if (adapter.id !== pending.adapterId) throw new Error(\"The pending adapter identity does not match this build.\");\n if (!platform.samePath(pending.plan.root, machineRoot)) {\n throw new Error(`The pending machine root ${pending.plan.root} does not match ${machineRoot}.`);\n }\n const executable = verifyMakeDocsExecutable({\n executablePath: pending.plan.executable.path,\n expectedSha256: pending.plan.executable.sha256,\n });\n if (JSON.stringify(executable) !== JSON.stringify(pending.plan.executable)) {\n throw new Error(\"The pending executable identity does not match this installed Make Docs binary.\");\n }\n const definition = adapter.methods.find(method => method.id === pending.connectionMethod);\n if (!definition) throw new Error(`The pending ${pending.connectionMethod} method is not implemented by this adapter.`);\n const commandRules = definition.requiresCommandRules\n ? listBoundedHarnessCommandRules(SYSTEM_COMMAND_RULE_AUTHORITY)\n : undefined;\n const applied = adapter.apply({\n plan: pending.plan,\n approved: true,\n operationId: pending.operationId,\n appliedVersion: pending.appliedVersion,\n verifiedAt: pending.verifiedAt,\n });\n const verification = adapter.verify({\n method: pending.connectionMethod,\n scope: \"machine\",\n root: machineRoot,\n executable,\n ...(commandRules ? { commandRules, commandRuleAuthority: SYSTEM_COMMAND_RULE_AUTHORITY } : {}),\n receipt: applied.receipt,\n });\n if (verification.state !== \"current\") {\n throw new Error(`Pending machine setup did not verify: ${verification.reason ?? verification.state}`);\n }\n recordHarnessIntegrationReceipt(targetRoot, storeRoot, applied.receipt);\n completeHarnessSystemOperation(targetRoot, storeRoot, pending, applied.receipt);\n if (options.persistIntent !== false) {\n persistRecoveredHarnessIntent(storeRoot, pending);\n }\n return makeResult(\"configured\", selections, [pending.harnessId], [], null);\n } catch (error) {\n return makeResult(\"recovery\", selections, [], [{ harness: pending.harnessId, reason: error instanceof Error ? error.message : String(error), nextAction: recoveryAction }], recoveryAction);\n }\n}\n\nfunction persistRecoveredHarnessIntent(\n storeRoot: string,\n pending: PendingHarnessSystemOperation,\n): void {\n const current = loadGlobalConfig(storeRoot).config;\n current.settings.harnesses[pending.harnessId] = {\n selected: true,\n maximumMethod: pending.connectionMethod,\n accessCeiling: deriveHarnessAccessCeiling(pending.connectionMethod),\n };\n writeGlobalConfig(storeRoot, current);\n}\n\nfunction buildIntentProjection(\n storeRoot: string,\n selections: Record<Harness, HarnessMethodSelection>,\n included: Record<Harness, boolean>,\n enabled: boolean,\n): SystemIntentProjection {\n const loaded = loadGlobalConfig(storeRoot);\n const changes: SystemIntentChange[] = [];\n if (!enabled) return { config: loaded.config, changes };\n for (const harness of Object.keys(selections) as Harness[]) {\n if (!included[harness]) continue;\n const method = selections[harness];\n const previous = loaded.config.settings.harnesses[harness];\n const sameMethod = previous?.selected === (method !== \"none\") &&\n previous.maximumMethod === (method === \"none\" ? null : method);\n const intent = {\n selected: method !== \"none\",\n maximumMethod: method === \"none\" ? null : method,\n accessCeiling: sameMethod && previous\n ? previous.accessCeiling\n : deriveHarnessAccessCeiling(method),\n };\n resolveEffectiveHarnessIntegration(undefined, intent, harness);\n const next = { ...(previous ?? {}), ...intent };\n if (JSON.stringify(previous ?? null) !== JSON.stringify(next)) {\n changes.push({\n harness,\n before: previous?.selected && previous.maximumMethod\n ? previous.maximumMethod as HarnessMethodSelection\n : \"none\",\n after: method,\n });\n }\n loaded.config.settings.harnesses[harness] = next;\n }\n return { config: loaded.config, changes };\n}\n\nfunction renderIntentChanges(storeRoot: string, changes: readonly SystemIntentChange[]): string {\n const configPath = path.join(storeRoot, \"config.json\");\n if (changes.length === 0) {\n return `Global intent file: ${configPath}\\n- Effect: no global harness intent change.`;\n }\n return [\n `Global intent file: ${configPath}`,\n ...changes.map(change => `- ${label(change.harness)} intent: ${change.before} -> ${change.after}`),\n \"- Effect: saves the reviewed machine access ceiling only after its native harness state verifies.\",\n ].join(\"\\n\");\n}\n\nfunction validateProjectHarnessIntegrations(records: readonly ProjectHarnessIntegrationRecord[] | undefined, selections: Record<Harness, HarnessMethodSelection>, included: Record<Harness, boolean>): void {\n for (const harness of Object.keys(selections) as Harness[]) {\n if (!included[harness]) continue;\n const method = selections[harness];\n resolveEffectiveHarnessIntegration(\n records?.find(record => record.harness === harness),\n {\n selected: method !== \"none\",\n maximumMethod: method === \"none\" ? null : method,\n accessCeiling: deriveHarnessAccessCeiling(method),\n },\n harness,\n );\n }\n}\nfunction methodReviewFacts(\n method: HarnessMethodDefinition,\n rules: readonly HarnessCommandRule[],\n): Pick<SystemHarnessPlan, \"operations\" | \"operationEffects\" | \"allowedStoreOperations\" | \"ownedEntries\"> {\n const ruleOperations = new Set(rules.flatMap(rule => [...rule.operationIds]));\n const admitted = listOperationAccessFacts().filter(fact =>\n method.allowedStoreOperations === \"active-operation-registry\"\n ? fact.mcpReady\n : fact.status === \"active\" && ruleOperations.has(fact.operation),\n );\n return {\n operations: admitted.map(fact => fact.operation),\n operationEffects: admitted.map(fact => ({ operation: fact.operation, ...fact.access })),\n allowedStoreOperations: method.allowedStoreOperations,\n ownedEntries: [...method.ownedEntries],\n };\n}\n\nexport function deriveHarnessAccessCeiling(method: HarnessMethodSelection): { store: \"none\" | \"read\" | \"write\"; project: \"none\" | \"read\" | \"write\"; hostConfig: \"none\" } {\n if (method === \"none\") return { store: \"none\", project: \"none\", hostConfig: \"none\" };\n const facts = listOperationAccessFacts().filter(fact => fact.status === \"active\" && (method === \"mcp\" || fact.commandRuleCandidate));\n const maximum = (values: Array<\"none\" | \"read\" | \"write\">): \"none\" | \"read\" | \"write\" =>\n values.includes(\"write\") ? \"write\" : values.includes(\"read\") ? \"read\" : \"none\";\n return {\n store: maximum(facts.map(fact => fact.access.store)),\n project: maximum(facts.map(fact => fact.access.project)),\n hostConfig: \"none\",\n };\n}\nfunction verifyCurrentExecutable(): VerifiedExecutableIdentity {\n const executablePath = path.resolve(process.argv[1] ?? \"\");\n return verifyMakeDocsExecutable({ executablePath });\n}\nfunction tryVerifyCurrentExecutable(): ExecutableVerificationAttempt {\n try {\n return { executable: verifyCurrentExecutable() };\n } catch (error) {\n return { error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\nfunction formatExecutableVerificationFailure(error?: Error): string {\n if (error instanceof ExecutableVerificationError) {\n return [\n `${error.code}: ${error.message}`,\n `Launch path: ${error.launchPath}.`,\n `Resolved path: ${error.resolvedPath ?? \"unresolved\"}.`,\n `Failed rule: ${error.failedRule}.`,\n `Next: ${error.nextAction}`,\n ].join(\" \");\n }\n return `package-identity-unproved: ${error?.message ?? \"The active packaged Make Docs executable could not be verified.\"} Next: Run setup from the installed package command and review the exact failure.`;\n}\nfunction blockedPlan(harness: Harness, method: string, detail: string, file: string, reviewFacts: Pick<SystemHarnessPlan, \"operations\" | \"operationEffects\" | \"allowedStoreOperations\" | \"ownedEntries\">): SystemHarnessPlan { return { harness, method, status: \"blocked\", ...reviewFacts, machineFiles: [file], changed: false, detail, async apply() {}, async verify() { return false; } }; }\nfunction makeResult(status: SystemSetupStatus, selections: Record<Harness, HarnessMethodSelection>, configured: Harness[], blocked: SystemSetupResult[\"blocked\"], recoveryAction: string | null): SystemSetupResult { const mutationState: SystemSetupResult[\"mutationState\"] = status === \"configured\" ? \"verified\" : status === \"partial\" || status === \"recovery\" ? \"partial\" : \"none\"; return { schemaVersion: 2, status, scope: \"machine\", selections, configured, skipped: (Object.keys(selections) as Harness[]).filter(h => selections[h] === \"none\"), blocked, attemptedWork: [...configured.map(harness => `verified ${harness}`), ...blocked.map(item => `checked ${item.harness}`)], mutationState, failedCondition: blocked[0]?.reason ?? null, nextAction: recoveryAction ?? blocked[0]?.nextAction ?? null, recoveryAction }; }\nfunction label(harness: Harness): string { return harness === \"claude-code\" ? \"Claude Code\" : \"Codex\"; }\n\nexport function renderSystemPlans(plans: SystemHarnessPlan[]): string {\n if (!plans.length) return [\"No native harness method is selected.\", \"Choosing none makes no native file changes.\", \"Resource reads need no Store access.\"].join(\"\\n\");\n return plans.flatMap(plan => {\n const ceiling = deriveHarnessAccessCeiling(plan.method as HarnessMethodSelection);\n return [\n `${label(plan.harness)} — ${plan.method}`,\n `- State: ${plan.status}`,\n `- Native files: ${plan.machineFiles.join(\", \") || \"none\"}`,\n `- Owned native entries: ${plan.ownedEntries.join(\", \") || \"none\"}`,\n `- Admitted operation IDs: ${plan.operations.join(\", \") || \"none\"}`,\n `- Store effects: ${plan.operationEffects.map(effect => `${effect.operation} (Store ${effect.store})`).join(\", \") || \"none\"}`,\n `- Access ceiling: Store ${ceiling.store}; project ${ceiling.project}; host config ${ceiling.hostConfig}`,\n `- Effect: ${plan.detail}`,\n \"- None effect: no native file changes; Store-backed agent operations stay unavailable; resource reads still need no Store access.\",\n ];\n }).join(\"\\n\");\n}\nexport function inspectSystemHarnesses(root = platform.userHome()): SetupHarnessState[] { return FIRST_PARTY_HARNESS_ADAPTERS.map(adapter => { const detection = adapter.detect({ scope: \"machine\", root }); return { harness: adapter.harnessId, state: detection.state, detail: detection.reason ?? (detection.evidence.length ? detection.evidence.join(\", \") : \"No native entry found\"), ...(detection.state === \"blocked\" ? { nextAction: `Resolve access to the ${adapter.displayName} native files, then run \\`make-docs setup system\\` again.` } : {}) }; }); }\nfunction renderMethodSupport(root: string, selected: Record<Harness, boolean>, executableAttempt: ExecutableVerificationAttempt): string[] { return FIRST_PARTY_HARNESS_ADAPTERS.filter(adapter => selected[adapter.harnessId]).flatMap(adapter => adapter.methods.map(method => { const support = resolveHarnessMethodSupport(adapter, method.id); const state = support.selectable && executableAttempt.executable ? support.state : \"blocked\"; const detail = support.selectable && executableAttempt.error ? formatExecutableVerificationFailure(executableAttempt.error) : `${support.reason} Next: ${support.nextAction}`; return `${adapter.displayName} ${method.id}: ${state}; ${detail}; native file ${path.resolve(root, method.nativeFile(\"machine\"))}; owned native entries ${method.ownedEntries.join(\", \")}.`; })); }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,kBAAkB;AAapB,IAAM,gCAA6D,OAAO,OAAO;AAAA,EACtF,MAAM;AAAA,EACN,UAAU;AACZ,CAAC;AAqCD,eAAsB,sBAAsB,SAA4D;AACtG,QAAM,UAAU,MAAM,gCAAgC,OAAO;AAC7D,MAAI,QAAS,QAAO;AACpB,QAAM,WAAW,MAAM,0BAA0B,OAAO;AACxD,UAAQ,WAAW,SAAS,MAAM;AAClC,QAAM,eAAe,SAA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A,EAAG,CAAC;AAAG;AACtiB,SAAS,oBAAoB,MAAc,UAAoC,mBAA4D;AAAE,SAAO,6BAA6B,OAAO,aAAW,SAAS,QAAQ,SAAS,CAAC,EAAE,QAAQ,aAAW,QAAQ,QAAQ,IAAI,YAAU;AAAE,UAAM,UAAU,4BAA4B,SAAS,OAAO,EAAE;AAAG,UAAM,QAAQ,QAAQ,cAAc,kBAAkB,aAAa,QAAQ,QAAQ;AAAW,UAAM,SAAS,QAAQ,cAAc,kBAAkB,QAAQ,oCAAoC,kBAAkB,KAAK,IAAI,GAAG,QAAQ,MAAM,UAAU,QAAQ,UAAU;AAAI,WAAO,GAAG,QAAQ,WAAW,IAAI,OAAO,EAAE,KAAK,KAAK,KAAK,MAAM,iBAAiB,KAAK,QAAQ,MAAM,OAAO,WAAW,SAAS,CAAC,CAAC,0BAA0B,OAAO,aAAa,KAAK,IAAI,CAAC;AAAA,EAAK,CAAC,CAAC;AAAG;","names":["method"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/skills-command.ts","../src/skills-ui.ts"],"sourcesContent":["import { stdin as input, stdout as output, stderr as reviewOutput } from \"node:process\";\nimport { confirm, isCancel, note } from \"@clack/prompts\";\nimport {\n applySkillsOnlyInstallPlan,\n planSkillsOnlyInstall,\n} from \"./install\";\nimport { loadMakeDocsConfigOrThrow, type MakeDocsConfig } from \"./config\";\nimport { loadManifest } from \"./manifest\";\nimport { applySkillAdoptionReview, buildSkillAdoptionReview, presentSkillAdoptionReview } from \"./skills-adoption\";\nimport { cloneSelections, defaultSelections } from \"./profile\";\nimport {\n applySkillRegistrySelectionMetadata,\n getRecommendedSkillChoices,\n} from \"./skill-catalog\";\nimport {\n loadEffectiveSkillRegistry,\n type EffectiveSkillRegistry,\n type SkillRegistry,\n} from \"./skill-registry\";\nimport {\n applySkillsUiStateToSelections,\n countSkillActions,\n createClackSkillsUiRenderer,\n renderSkillsPlanSummary,\n runSkillsUiWithRenderer,\n stateFromSkillsSelections,\n type SkillsUiState,\n} from \"./skills-ui\";\nimport type { InstallManifest, InstallPlan, InstallSelections } from \"./types\";\nimport { PACKAGE_ROOT, readPackageMeta } from \"./utils\";\nimport { resolveUnifiedSetupState } from \"./setup-state\";\n\nexport type SkillsCommandOptions = {\n targetDir: string;\n dryRun: boolean;\n yes: boolean;\n remove: boolean;\n noCodex: boolean;\n noClaudeCode: boolean;\n skillScope?: InstallSelections[\"skillScope\"];\n selectedSkills?: string[];\n skillsManifest?: string;\n adoptExisting?: string[];\n review?: string;\n};\n\nexport async function runSkillsCommand(options: SkillsCommandOptions): Promise<void> {\n if (options.review && !options.adoptExisting) throw new Error(\"--review requires --adopt-existing.\");\n if (options.adoptExisting && options.remove) throw new Error(\"--adopt-existing cannot be used with --remove.\");\n const loadedConfig = loadMakeDocsConfigOrThrow(options.targetDir);\n const makeDocsConfig = loadedConfig.config;\n const existingManifest = loadManifest(options.targetDir);\n const effectiveSkillRegistry = loadEffectiveSkillRegistry({\n packageRoot: PACKAGE_ROOT,\n manifestReference: options.skillsManifest,\n });\n const initialSelections = applySkillRegistrySelectionMetadata(\n resolveUnifiedSetupState({\n entry: \"skills\",\n projectState: existingManifest ? \"current\" : \"fresh\",\n selections: resolveSkillsSelections(options, existingManifest),\n }).selections,\n effectiveSkillRegistry,\n );\n const packageMeta = readPackageMeta();\n validateSelectedSkills(initialSelections, effectiveSkillRegistry.registry);\n if (options.adoptExisting) {\n const review = await buildSkillAdoptionReview({targetDir:options.targetDir,selections:initialSelections,adoptExisting:options.adoptExisting,effectiveRegistry:effectiveSkillRegistry});\n const presented = presentSkillAdoptionReview(review);\n reviewOutput.write(renderAdoptionSummary(presented));\n if (options.dryRun) { output.write(`${JSON.stringify(presented,null,2)}\\n`); return; }\n if (presented.status === \"blocked\") throw new Error(review.blockers.join(\"\\n\"));\n let digest = options.review;\n if (!digest && presented.status !== \"unchanged\") {\n if (options.yes || !input.isTTY || !output.isTTY) throw new Error(\"Adoption requires --review <digest> from a complete dry run. --yes does not approve adoption.\");\n output.write(`${JSON.stringify(presented,null,2)}\\n`);\n const accepted = await confirm({message:\"Apply this exact Skill adoption review?\"});\n if (isCancel(accepted) || !accepted) { output.write(\"Skill adoption cancelled.\\n\"); return; }\n digest = review.digest;\n }\n const result = applySkillAdoptionReview(review,digest ?? review.digest);\n output.write(`${JSON.stringify({...result,review:presented},null,2)}\\n`);\n return;\n }\n const interactiveState = await resolveInteractiveSkillsState({\n options,\n existingManifest,\n initialSelections,\n packageMeta,\n config: makeDocsConfig,\n effectiveSkillRegistry,\n skillChoices: getRecommendedSkillChoices(effectiveSkillRegistry.registry),\n });\n\n if (interactiveState === null) {\n output.write(\"Skills command cancelled.\\n\");\n return;\n }\n\n const state =\n interactiveState ??\n stateFromSkillsSelections({\n action: options.remove ? \"remove\" : \"sync\",\n targetDir: options.targetDir,\n selections: initialSelections,\n });\n const selections = applySkillRegistrySelectionMetadata(\n applySkillsUiStateToSelections(state, initialSelections),\n effectiveSkillRegistry,\n );\n const plan = await planSkillsOnlyInstall({\n targetDir: options.targetDir,\n selections,\n existingManifest,\n remove: state.action === \"remove\",\n packageMeta,\n skillRegistry: effectiveSkillRegistry.registry,\n });\n const hasPlannedChanges = plan.actions.some((action) => action.type !== \"noop\");\n\n printSkillsPlan({\n dryRun: options.dryRun,\n plan,\n state,\n config: makeDocsConfig,\n });\n\n if (options.dryRun) {\n output.write(\"\\nDry run complete.\\n\");\n return;\n }\n\n if (!hasPlannedChanges) {\n output.write(\"No make-docs skill changes are needed.\\n\");\n return;\n }\n\n if (!options.yes && (!input.isTTY || !output.isTTY)) {\n throw new Error(\"Interactive prompts require a TTY. Use --yes for non-interactive runs.\");\n }\n\n const applied = applySkillsOnlyInstallPlan({\n targetDir: options.targetDir,\n plan,\n existingManifest,\n });\n\n writeSkillsCompletion({\n existingManifest,\n state,\n plan,\n });\n\n if (applied.conflictFiles.length > 0) {\n output.write(\"Conflicts were staged for manual review:\\n\");\n for (const conflictFile of applied.conflictFiles) {\n output.write(`- ${conflictFile}\\n`);\n }\n }\n}\n\nfunction renderAdoptionSummary(review: ReturnType<typeof presentSkillAdoptionReview>): string {\n const effects = {register: 0, update: 0, remove: 0, retain: 0};\n for (const row of review.ownership) effects[row.effect]++;\n const files = review.ownership.filter(row => row.after && !row.after.skillExposure).length;\n const exposures = review.ownership.filter(row => row.after?.skillExposure).length;\n const registrations = review.ownership.filter(row => row.effect === 'register' && row.after && !row.after.skillExposure);\n const registeredFiles = registrations.length;\n const registeredSkills = new Set(registrations.flatMap(row => review.selectedSkills.filter(name => row.path.includes(`/skills/${name}/`)))).size;\n const skills = new Set(review.selectedSkills).size;\n const toolLabels: Record<string, string> = { codex: 'Codex', 'claude-code': 'Claude Code' };\n const skillRoots = [...new Set(review.ownership.flatMap(row => {\n if (!row.after) return [];\n const normalized = row.path.replace(/\\\\/g, '/');\n const segment = normalized.lastIndexOf('/skills/');\n return segment < 0 ? [] : [normalized.slice(0, segment + '/skills'.length)];\n }))].sort();\n const lines = [\n `Skill adoption review: ${review.status}.`,\n `Target: ${review.targetRoot}`,\n `Scope: ${review.scope}.`,\n `Selected tools: ${review.selectedTools.map(tool => toolLabels[tool] ?? tool).join(', ') || 'none'}.`,\n `Skill roots: ${skillRoots.join(', ') || 'none'}.`,\n ];\n if (review.status === 'blocked') {\n lines.push('Adoption is blocked. No changes have been made.', ...review.blockers.map(message => `- ${message}`));\n } else if (review.status === 'unchanged') {\n lines.push(`Make Docs already manages ${files} files and ${exposures} native exposures across ${skills} Skills.`, 'No file or ownership changes are needed.');\n } else {\n if (!review.changes.length) {\n lines.push('No file contents will change.');\n if (registeredFiles) lines.push(`If approved, Make Docs will manage ${registeredFiles} existing files across ${registeredSkills} ${registeredSkills === 1 ? 'Skill' : 'Skills'}.`);\n else lines.push('Ownership records will change only if you approve.');\n }\n lines.push(`Planned path changes: ${new Set(review.changes.map(change => change.path)).size}. Backup files: ${review.backups.length}.`);\n lines.push('No adoption changes have been applied.');\n }\n lines.push(`Ownership entries: ${effects.register} to register, ${effects.update} to update, ${effects.remove} to remove, ${effects.retain} to retain.`);\n lines.push(...review.recoveryLimits, review.nextAction);\n return lines.join('\\n') + '\\n';\n}\n\nasync function resolveInteractiveSkillsState(options: {\n options: SkillsCommandOptions;\n existingManifest: InstallManifest | null;\n initialSelections: InstallSelections;\n packageMeta: ReturnType<typeof readPackageMeta>;\n config: MakeDocsConfig;\n effectiveSkillRegistry: EffectiveSkillRegistry;\n skillChoices: ReturnType<typeof getRecommendedSkillChoices>;\n}): Promise<SkillsUiState | null | undefined> {\n const {\n options: commandOptions,\n existingManifest,\n initialSelections,\n packageMeta,\n config,\n effectiveSkillRegistry,\n skillChoices,\n } = options;\n\n if (commandOptions.yes || !input.isTTY || !output.isTTY) {\n return undefined;\n }\n\n const initialState = stateFromSkillsSelections({\n action: commandOptions.remove ? \"remove\" : \"sync\",\n targetDir: commandOptions.targetDir,\n selections: initialSelections,\n });\n\n return runSkillsUiWithRenderer(createClackSkillsUiRenderer(), {\n initialState,\n introTitle: \"Manage make-docs skills\",\n config,\n skillChoices,\n async buildReviewState(state) {\n const selections = applySkillRegistrySelectionMetadata(\n applySkillsUiStateToSelections(state, initialSelections),\n effectiveSkillRegistry,\n );\n const plan = await planSkillsOnlyInstall({\n targetDir: commandOptions.targetDir,\n selections,\n existingManifest,\n remove: state.action === \"remove\",\n packageMeta,\n skillRegistry: effectiveSkillRegistry.registry,\n });\n\n return {\n state,\n summary: renderSkillsPlanSummary({\n state,\n actions: plan.actions,\n dryRun: commandOptions.dryRun,\n config,\n }),\n actions:\n state.action === \"sync\"\n ? [\"apply\", \"edit-action\", \"edit-platforms\", \"edit-scope\", \"edit-skills\", \"cancel\"]\n : [\"apply\", \"edit-action\", \"cancel\"],\n };\n },\n });\n}\n\nfunction resolveSkillsSelections(\n options: SkillsCommandOptions,\n existingManifest: InstallManifest | null,\n): InstallSelections {\n const baseSelections = existingManifest ? existingManifest.selections : defaultSelections();\n const selections = cloneSelections(baseSelections);\n selections.harnesses = {...(baseSelections.skillHarnesses ?? baseSelections.harnesses)};\n\n selections.skills = true;\n if (options.noCodex) {\n selections.harnesses.codex = false;\n }\n if (options.noClaudeCode) {\n selections.harnesses[\"claude-code\"] = false;\n }\n if (options.skillScope) {\n selections.skillScope = options.skillScope;\n }\n if (options.selectedSkills !== undefined) {\n selections.selectedSkills = [...options.selectedSkills];\n }\n selections.skillHarnesses = {...selections.harnesses};\n\n return selections;\n}\n\nfunction validateSelectedSkills(\n selections: InstallSelections,\n registry: SkillRegistry,\n): void {\n const registrySkills = new Set(registry.skills.map((skill) => skill.name));\n for (const skillName of selections.selectedSkills) {\n if (!registrySkills.has(skillName)) {\n const validList = Array.from(registrySkills).sort().join(\", \");\n throw new Error(\n `Unknown selected skill \\`${skillName}\\`. Valid skills: ${validList || \"(none)\"}.`,\n );\n }\n }\n}\n\nfunction printSkillsPlan(options: {\n dryRun: boolean;\n plan: InstallPlan;\n state: SkillsUiState;\n config: MakeDocsConfig;\n}): void {\n const title =\n options.state.action === \"remove\" ? \"make-docs setup skills removal plan\" : \"make-docs setup skills plan\";\n note(\n renderSkillsPlanSummary({\n state: options.state,\n actions: options.plan.actions,\n dryRun: options.dryRun,\n config: options.config,\n }),\n title,\n );\n}\n\nfunction writeSkillsCompletion(options: {\n existingManifest: InstallManifest | null;\n state: SkillsUiState;\n plan: InstallPlan;\n}): void {\n if (options.state.action === \"remove\") {\n output.write(\"Removed managed skills. Ownership is recorded in the global Make Docs Store.\\n\");\n return;\n }\n\n const counts = countSkillActions(options.plan.actions);\n const changedCount =\n counts.create +\n counts.generate +\n counts.update +\n counts[\"update-conflict\"] +\n counts[\"strip-managed-block\"] +\n counts[\"remove-managed\"];\n const verb = options.existingManifest ? \"Updated\" : \"Installed\";\n output.write(`${verb} skills (${changedCount} changed). Ownership is recorded in the global Make Docs Store.\\n`);\n}\n","import {\n intro,\n isCancel,\n multiselect,\n note,\n select,\n} from \"@clack/prompts\";\nimport { formatAgenticSkillFileRole } from \"./agentic-skill-roles\";\nimport { getRecommendedSkillChoices } from \"./skill-catalog\";\nimport type { WizardSkillChoice } from \"./skill-catalog\";\nimport {\n createDefaultMakeDocsConfig,\n getConfigRenderingLabels,\n type MakeDocsConfig,\n} from \"./config\";\nimport {\n HARNESSES,\n type Harness,\n type InstallSelections,\n type PlannedAction,\n} from \"./types\";\nimport { formatInlineList } from \"./utils\";\n\nexport type SkillsUiAction = \"sync\" | \"remove\";\nexport type SkillsUiStep = \"action\" | \"platforms\" | \"scope\" | \"skills\" | \"review\";\ntype RenderedSkillActionKind = \"generate\" | \"update\" | \"skip\" | \"remove\";\nexport type SkillsReviewAction =\n | \"apply\"\n | \"edit-action\"\n | \"edit-platforms\"\n | \"edit-scope\"\n | \"edit-skills\"\n | \"cancel\";\n\nconst RENDERED_SKILL_ACTION_KIND_ORDER: Record<RenderedSkillActionKind, number> = {\n generate: 0,\n update: 1,\n skip: 2,\n remove: 3,\n};\n\nexport interface SkillsUiState {\n action: SkillsUiAction;\n targetDir: string;\n harnesses: Harness[];\n skillScope: InstallSelections[\"skillScope\"];\n selectedSkills: string[];\n}\n\nexport interface SkillsActionStepState {\n state: SkillsUiState;\n options: Array<{ value: SkillsUiAction; label: string; hint: string }>;\n}\n\nexport interface SkillsPlatformStepState {\n state: SkillsUiState;\n options: Array<{ value: Harness; label: string; hint: string }>;\n selectedHarnesses: Harness[];\n}\n\nexport interface SkillsScopeStepState {\n state: SkillsUiState;\n options: Array<{\n value: InstallSelections[\"skillScope\"];\n label: string;\n hint: string;\n }>;\n}\n\nexport interface SkillsSelectionStepState {\n state: SkillsUiState;\n skills: WizardSkillChoice[];\n selectedSkills: string[];\n}\n\nexport interface SkillsReviewStepState {\n state: SkillsUiState;\n summary: string;\n actions: SkillsReviewAction[];\n}\n\nexport interface SkillsUiRenderer {\n beginSession?(title: string): void | Promise<void>;\n chooseAction(state: SkillsActionStepState): Promise<SkillsUiAction | null>;\n chooseHarnesses(state: SkillsPlatformStepState): Promise<Harness[] | null>;\n chooseScope(\n state: SkillsScopeStepState,\n ): Promise<InstallSelections[\"skillScope\"] | null>;\n chooseSelectedSkills(\n state: SkillsSelectionStepState,\n ): Promise<string[] | null>;\n review(state: SkillsReviewStepState): Promise<SkillsReviewAction>;\n}\n\nexport interface RunSkillsUiOptions {\n initialState: SkillsUiState;\n introTitle: string;\n startStep?: SkillsUiStep;\n config?: MakeDocsConfig;\n skillChoices?: WizardSkillChoice[];\n buildReviewState?: (\n state: SkillsUiState,\n ) => Promise<SkillsReviewStepState> | SkillsReviewStepState;\n}\n\nconst HARNESS_METADATA: Record<Harness, { label: string; hint: string }> = {\n \"claude-code\": {\n label: \"Claude Code\",\n hint: \"CLAUDE.md + .claude/\",\n },\n codex: {\n label: \"Codex\",\n hint: \"AGENTS.md + .agents/\",\n },\n};\n\nexport async function runSkillsUiWithRenderer(\n renderer: SkillsUiRenderer,\n options: RunSkillsUiOptions,\n): Promise<SkillsUiState | null> {\n let state = cloneSkillsUiState(options.initialState);\n let step = options.startStep ?? \"action\";\n\n await renderer.beginSession?.(options.introTitle);\n\n while (true) {\n if (step === \"action\") {\n const action = await renderer.chooseAction(buildActionStepState(state));\n if (!action) {\n return null;\n }\n\n state = { ...state, action };\n step = action === \"sync\" ? \"platforms\" : \"review\";\n continue;\n }\n\n if (step === \"platforms\") {\n const harnesses = await renderer.chooseHarnesses(\n buildPlatformStepState(state),\n );\n if (!harnesses) {\n return null;\n }\n if (harnesses.length === 0) {\n continue;\n }\n\n state = { ...state, harnesses };\n step = \"scope\";\n continue;\n }\n\n if (step === \"scope\") {\n const skillScope = await renderer.chooseScope(buildScopeStepState(state));\n if (!skillScope) {\n return null;\n }\n\n state = { ...state, skillScope };\n step = \"skills\";\n continue;\n }\n\n if (step === \"skills\") {\n const selectedSkills = await renderer.chooseSelectedSkills(\n buildSkillsSelectionStepState(state, options.skillChoices),\n );\n if (!selectedSkills) {\n return null;\n }\n\n state = { ...state, selectedSkills };\n step = \"review\";\n continue;\n }\n\n const reviewState = await buildReviewState(state, options);\n const reviewAction = await renderer.review(reviewState);\n\n if (reviewAction === \"apply\") {\n return cloneSkillsUiState(state);\n }\n if (reviewAction === \"edit-action\") {\n step = \"action\";\n continue;\n }\n if (reviewAction === \"edit-platforms\" && state.action === \"sync\") {\n step = \"platforms\";\n continue;\n }\n if (reviewAction === \"edit-scope\" && state.action === \"sync\") {\n step = \"scope\";\n continue;\n }\n if (reviewAction === \"edit-skills\" && state.action === \"sync\") {\n step = \"skills\";\n continue;\n }\n\n return null;\n }\n}\n\nexport function createClackSkillsUiRenderer(): SkillsUiRenderer {\n return {\n beginSession(title) {\n intro(title);\n },\n async chooseAction(state) {\n const action = await select<SkillsUiAction>({\n message: \"What would you like to do with make-docs skills?\",\n withGuide: true,\n initialValue: state.state.action,\n options: state.options,\n });\n\n return isCancel(action) ? null : action;\n },\n async chooseHarnesses(state) {\n const harnesses = await multiselect<Harness>({\n message: \"Which agent platforms should receive skills?\",\n withGuide: true,\n required: true,\n initialValues: state.selectedHarnesses,\n options: state.options,\n });\n\n return isCancel(harnesses) ? null : harnesses;\n },\n async chooseScope(state) {\n const scope = await select<InstallSelections[\"skillScope\"]>({\n message: \"Where should skills be installed?\",\n withGuide: true,\n initialValue: state.state.skillScope,\n options: state.options,\n });\n\n return isCancel(scope) ? null : scope;\n },\n async chooseSelectedSkills(state) {\n if (state.skills.length === 0) {\n return [];\n }\n\n const selectedSkills = await multiselect<string>({\n message: \"Which skills should be installed?\",\n withGuide: true,\n required: false,\n initialValues: state.selectedSkills,\n options: state.skills.map((skill) => ({\n value: skill.name,\n label: `${formatSkillPurposeLabels(skill)} / ${skill.name}`,\n hint: formatSkillChoiceHint(skill),\n })),\n });\n\n return isCancel(selectedSkills) ? null : selectedSkills;\n },\n async review(state) {\n note(state.summary, \"Review skills changes\");\n\n const action = await select<SkillsReviewAction>({\n message: \"What would you like to do next?\",\n withGuide: true,\n options: state.actions.map((value) => reviewActionOption(value)),\n });\n\n return isCancel(action) ? \"cancel\" : action;\n },\n };\n}\n\nexport function stateFromSkillsSelections(options: {\n action: SkillsUiAction;\n targetDir: string;\n selections: InstallSelections;\n}): SkillsUiState {\n return {\n action: options.action,\n targetDir: options.targetDir,\n harnesses: getSelectedHarnesses({...options.selections,harnesses:options.selections.skillHarnesses ?? options.selections.harnesses}),\n skillScope: options.selections.skillScope,\n selectedSkills: [...options.selections.selectedSkills],\n };\n}\n\nexport function applySkillsUiStateToSelections(\n state: SkillsUiState,\n baseSelections: InstallSelections,\n): InstallSelections {\n const selections = structuredClone(baseSelections);\n selections.skills = true;\n if (state.action === \"remove\") {\n return selections;\n }\n\n selections.harnesses = Object.fromEntries(\n HARNESSES.map((harness) => [harness, state.harnesses.includes(harness)]),\n ) as Record<Harness, boolean>;\n selections.skillHarnesses = {...selections.harnesses};\n selections.skillScope = state.skillScope;\n selections.selectedSkills = [...state.selectedSkills];\n return selections;\n}\n\nexport function renderSkillsPlanSummary(options: {\n state: SkillsUiState;\n actions: PlannedAction[];\n dryRun: boolean;\n config?: MakeDocsConfig;\n}): string {\n const counts = countSkillActions(options.actions);\n const labels = getConfigRenderingLabels(\n options.config ?? createDefaultMakeDocsConfig(),\n );\n const lines = [\n `Target: ${options.state.targetDir}`,\n `Action: ${options.state.action === \"remove\" ? \"remove managed skills\" : \"sync skills\"}`,\n `Mode: ${options.dryRun ? \"dry run\" : \"apply\"}`,\n `Document kind labels: ${labels.documentKinds}`,\n `Coordinate labels: ${labels.coordinates}`,\n `Persona labels: ${labels.personas}`,\n ];\n\n if (options.state.action === \"sync\") {\n lines.push(\n `Platforms: ${formatHarnesses(options.state.harnesses)}`,\n `Scope: ${options.state.skillScope}`,\n `Selected skills: ${formatSelectedSkills(options.state.selectedSkills)}`,\n );\n } else {\n lines.push(\"Removal scope: all manifest-tracked skill files\");\n }\n\n lines.push(\n `Managed skill files evaluated: ${options.actions.length}`,\n `Already current: ${counts.noop}`,\n `Generate: ${counts.create + counts.generate}`,\n `Update: ${counts.update + counts[\"update-conflict\"] + counts[\"strip-managed-block\"]}`,\n `Skip: ${counts.skip + counts[\"skip-conflict\"]}`,\n `Remove: ${counts[\"remove-managed\"]}`,\n \"\",\n \"Planned skill file operations:\",\n );\n\n const plannedOperations = getRenderedSkillActions(options.actions);\n if (plannedOperations.length === 0) {\n lines.push(\"- none\");\n } else {\n for (const action of plannedOperations) {\n lines.push(`- ${formatSkillActionLine(action)}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function countSkillActions(\n actions: PlannedAction[],\n): Record<PlannedAction[\"type\"], number> {\n return {\n create: actions.filter((action) => action.type === \"create\").length,\n generate: actions.filter((action) => action.type === \"generate\").length,\n noop: actions.filter((action) => action.type === \"noop\").length,\n \"remove-managed\": actions.filter((action) => action.type === \"remove-managed\").length,\n skip: actions.filter((action) => action.type === \"skip\").length,\n \"skip-conflict\": actions.filter((action) => action.type === \"skip-conflict\").length,\n \"strip-managed-block\": actions.filter((action) => action.type === \"strip-managed-block\").length,\n update: actions.filter((action) => action.type === \"update\").length,\n \"update-conflict\": actions.filter((action) => action.type === \"update-conflict\").length,\n };\n}\n\nfunction buildActionStepState(state: SkillsUiState): SkillsActionStepState {\n return {\n state: cloneSkillsUiState(state),\n options: [\n {\n value: \"sync\",\n label: \"Sync or update skills\",\n hint: \"Install missing skills and refresh managed skill files\",\n },\n {\n value: \"remove\",\n label: \"Remove managed skills\",\n hint: \"Remove skill files tracked by the make-docs manifest\",\n },\n ],\n };\n}\n\nfunction buildPlatformStepState(state: SkillsUiState): SkillsPlatformStepState {\n return {\n state: cloneSkillsUiState(state),\n options: HARNESSES.map((harness) => ({\n value: harness,\n label: HARNESS_METADATA[harness].label,\n hint: HARNESS_METADATA[harness].hint,\n })),\n selectedHarnesses: [...state.harnesses],\n };\n}\n\nfunction buildScopeStepState(state: SkillsUiState): SkillsScopeStepState {\n return {\n state: cloneSkillsUiState(state),\n options: [\n {\n value: \"project\",\n label: \"Project\",\n hint: \"Install skills into this project.\",\n },\n {\n value: \"global\",\n label: \"Global\",\n hint: \"Install skills into your home directory for reuse across projects.\",\n },\n ],\n };\n}\n\nfunction buildSkillsSelectionStepState(\n state: SkillsUiState,\n skillChoices: WizardSkillChoice[] = getRecommendedSkillChoices(),\n): SkillsSelectionStepState {\n const skillNames = new Set(skillChoices.map((skill) => skill.name));\n\n return {\n state: cloneSkillsUiState(state),\n skills: skillChoices,\n selectedSkills: state.selectedSkills.filter((skillName) =>\n skillNames.has(skillName),\n ),\n };\n}\n\nasync function buildReviewState(\n state: SkillsUiState,\n options: RunSkillsUiOptions,\n): Promise<SkillsReviewStepState> {\n if (options.buildReviewState) {\n return options.buildReviewState(cloneSkillsUiState(state));\n }\n\n return {\n state: cloneSkillsUiState(state),\n summary: renderSkillsPlanSummary({\n state,\n actions: [],\n dryRun: false,\n config: options.config,\n }),\n actions: reviewActionsForState(state),\n };\n}\n\nfunction reviewActionsForState(state: SkillsUiState): SkillsReviewAction[] {\n return state.action === \"sync\"\n ? [\"apply\", \"edit-action\", \"edit-platforms\", \"edit-scope\", \"edit-skills\", \"cancel\"]\n : [\"apply\", \"edit-action\", \"cancel\"];\n}\n\nfunction reviewActionOption(\n value: SkillsReviewAction,\n): { value: SkillsReviewAction; label: string; hint: string } {\n const options: Record<SkillsReviewAction, { label: string; hint: string }> = {\n apply: {\n label: \"Apply\",\n hint: \"Use this skills configuration\",\n },\n \"edit-action\": {\n label: \"Edit action\",\n hint: \"Switch between sync and removal\",\n },\n \"edit-platforms\": {\n label: \"Edit platforms\",\n hint: \"Adjust Claude Code and Codex targets\",\n },\n \"edit-scope\": {\n label: \"Edit scope\",\n hint: \"Adjust project or global installation\",\n },\n \"edit-skills\": {\n label: \"Edit selected skills\",\n hint: \"Adjust selected skills\",\n },\n cancel: {\n label: \"Cancel\",\n hint: \"Exit without applying changes\",\n },\n };\n\n return { value, ...options[value] };\n}\n\nfunction getSelectedHarnesses(selections: Pick<InstallSelections, \"harnesses\">): Harness[] {\n return HARNESSES.filter((harness) => selections.harnesses[harness]);\n}\n\nfunction formatHarnesses(harnesses: Harness[]): string {\n const labels = harnesses.map((harness) => HARNESS_METADATA[harness].label);\n return labels.length > 0 ? formatInlineList(labels) : \"none\";\n}\n\nfunction formatSelectedSkills(selectedSkills: string[]): string {\n return selectedSkills.length > 0 ? formatInlineList(selectedSkills) : \"none\";\n}\n\nfunction formatSkillPurposeLabels(skill: WizardSkillChoice): string {\n return skill.purposes.length > 0\n ? skill.purposes.map((purpose) => purpose.label).join(\", \")\n : \"Uncategorized\";\n}\n\nfunction formatSkillChoiceHint(skill: WizardSkillChoice): string {\n return [\n skill.description,\n `Source: ${skill.sourcePolicyKind}`,\n `Harnesses: ${formatInlineList(skill.supportedHarnesses)}`,\n `Provenance: ${skill.provenanceLabel}`,\n ].join(\" | \");\n}\n\nfunction formatSkillActionLine(action: PlannedAction): string {\n const kind = getRenderedSkillActionKind(action);\n if (!kind) {\n throw new Error(`Cannot render no-op action for ${action.relativePath}.`);\n }\n\n const agenticRole = formatAgenticSkillFileRole(action.agenticRole);\n return `${kind}: ${agenticRole ? `${agenticRole}: ` : \"\"}${action.relativePath}`;\n}\n\nfunction getRenderedSkillActions(actions: PlannedAction[]): PlannedAction[] {\n return actions\n .filter((action) => getRenderedSkillActionKind(action) !== null)\n .sort(compareRenderedSkillActions);\n}\n\nfunction compareRenderedSkillActions(left: PlannedAction, right: PlannedAction): number {\n const leftKind = getRenderedSkillActionKind(left);\n const rightKind = getRenderedSkillActionKind(right);\n\n if (leftKind && rightKind && leftKind !== rightKind) {\n return (\n RENDERED_SKILL_ACTION_KIND_ORDER[leftKind] -\n RENDERED_SKILL_ACTION_KIND_ORDER[rightKind]\n );\n }\n\n return comparePosixTreePath(left.relativePath, right.relativePath);\n}\n\nfunction getRenderedSkillActionKind(\n action: PlannedAction,\n): RenderedSkillActionKind | null {\n switch (action.type) {\n case \"create\":\n case \"generate\":\n return \"generate\";\n case \"update\":\n case \"update-conflict\":\n case \"strip-managed-block\":\n return \"update\";\n case \"skip\":\n case \"skip-conflict\":\n return \"skip\";\n case \"remove-managed\":\n return \"remove\";\n case \"noop\":\n return null;\n }\n}\n\nfunction comparePosixTreePath(left: string, right: string): number {\n if (left === right) {\n return 0;\n }\n\n return left < right ? -1 : 1;\n}\n\nfunction cloneSkillsUiState(state: SkillsUiState): SkillsUiState {\n return {\n ...state,\n harnesses: [...state.harnesses],\n selectedSkills: [...state.selectedSkills],\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,OAAO,UAAU,QAAQ,UAAU,oBAAoB;;;ACkCzE,IAAM,mCAA4E;AAAA,EAChF,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,QAAQ;AACV;AAkEA,IAAM,mBAAqE;AAAA,EACzE,eAAe;AAAA,IACb,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAAA,EACA,OAAO;AAAA,IACL,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AACF;AAEA,eAAsB,wBACpB,UACA,SAC+B;AAC/B,MAAI,QAAQ,mBAAmB,QAAQ,YAAY;AACnD,MAAI,OAAO,QAAQ,aAAa;AAEhC,QAAM,SAAS,eAAe,QAAQ,UAAU;AAEhD,SAAO,MAAM;AACX,QAAI,SAAS,UAAU;AACrB,YAAM,SAAS,MAAM,SAAS,aAAa,qBAAqB,KAAK,CAAC;AACtE,UAAI,CAAC,QAAQ;AACX,eAAO;AAAA,MACT;AAEA,cAAQ,EAAE,GAAG,OAAO,OAAO;AAC3B,aAAO,WAAW,SAAS,cAAc;AACzC;AAAA,IACF;AAEA,QAAI,SAAS,aAAa;AACxB,YAAM,YAAY,MAAM,SAAS;AAAA,QAC/B,uBAAuB,KAAK;AAAA,MAC9B;AACA,UAAI,CAAC,WAAW;AACd,eAAO;AAAA,MACT;AACA,UAAI,UAAU,WAAW,GAAG;AAC1B;AAAA,MACF;AAEA,cAAQ,EAAE,GAAG,OAAO,UAAU;AAC9B,aAAO;AACP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