@brucewaynedecoy/make-docs 1.0.0-rc.1 → 2.0.2

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.
Files changed (187) hide show
  1. package/LICENSE +21 -201
  2. package/README.md +36 -27
  3. package/dist/backup-73HQNKMC.js +20 -0
  4. package/dist/backup-73HQNKMC.js.map +1 -0
  5. package/dist/chunk-3BAJQXGH.js +1575 -0
  6. package/dist/chunk-3BAJQXGH.js.map +1 -0
  7. package/dist/chunk-64CTKJO7.js +4136 -0
  8. package/dist/chunk-64CTKJO7.js.map +1 -0
  9. package/dist/chunk-BENO4IH5.js +875 -0
  10. package/dist/chunk-BENO4IH5.js.map +1 -0
  11. package/dist/chunk-D4HDZEJT.js +37 -0
  12. package/dist/chunk-D4HDZEJT.js.map +1 -0
  13. package/dist/chunk-G5EF63GG.js +1291 -0
  14. package/dist/chunk-G5EF63GG.js.map +1 -0
  15. package/dist/chunk-GNP6HRVP.js +523 -0
  16. package/dist/chunk-GNP6HRVP.js.map +1 -0
  17. package/dist/chunk-HJYIQTMD.js +204 -0
  18. package/dist/chunk-HJYIQTMD.js.map +1 -0
  19. package/dist/chunk-LQ5NSWCJ.js +39 -0
  20. package/dist/chunk-LQ5NSWCJ.js.map +1 -0
  21. package/dist/chunk-LRVV7UDD.js +2340 -0
  22. package/dist/chunk-LRVV7UDD.js.map +1 -0
  23. package/dist/chunk-LVQSJF63.js +24674 -0
  24. package/dist/chunk-LVQSJF63.js.map +1 -0
  25. package/dist/chunk-MXBHCHSM.js +13995 -0
  26. package/dist/chunk-MXBHCHSM.js.map +1 -0
  27. package/dist/chunk-Z5K4FHYP.js +922 -0
  28. package/dist/chunk-Z5K4FHYP.js.map +1 -0
  29. package/dist/index.js +3798 -250
  30. package/dist/index.js.map +1 -1
  31. package/dist/self-YYXOLDKU.js +653 -0
  32. package/dist/self-YYXOLDKU.js.map +1 -0
  33. package/dist/server-O2ZELIMX.js +512 -0
  34. package/dist/server-O2ZELIMX.js.map +1 -0
  35. package/dist/setup-system-HZROFNMP.js +544 -0
  36. package/dist/setup-system-HZROFNMP.js.map +1 -0
  37. package/dist/{skills-command-3ESCZ75U.js → skills-command-MGGHY7HU.js} +190 -32
  38. package/dist/skills-command-MGGHY7HU.js.map +1 -0
  39. package/dist/uninstall-3UXXXNFO.js +223 -0
  40. package/dist/uninstall-3UXXXNFO.js.map +1 -0
  41. package/dist/virtual_make-docs-first-party-skills-ZII74YOB.js +11 -0
  42. package/dist/virtual_make-docs-first-party-skills-ZII74YOB.js.map +1 -0
  43. package/package.json +9 -6
  44. package/skill-registry.json +328 -125
  45. package/skill-registry.schema.json +221 -45
  46. package/template/.make-docs/AGENTS.md +18 -0
  47. package/template/.make-docs/CLAUDE.md +18 -0
  48. package/template/.make-docs/archive/AGENTS.md +11 -0
  49. package/template/.make-docs/archive/CLAUDE.md +11 -0
  50. package/template/.make-docs/system/AGENTS.md +12 -0
  51. package/template/.make-docs/system/CLAUDE.md +12 -0
  52. package/template/.make-docs/system/contracts/AGENTS.md +13 -0
  53. package/template/.make-docs/system/contracts/CLAUDE.md +13 -0
  54. package/template/{docs/assets/references → .make-docs/system/contracts}/commit-message-convention.md +4 -4
  55. package/template/.make-docs/system/contracts/coverage-pass-contract.md +198 -0
  56. package/template/.make-docs/system/contracts/deferred-obligation-contract.md +128 -0
  57. package/template/{docs/assets/references → .make-docs/system/contracts}/design-contract.md +7 -2
  58. package/template/{docs/assets/references → .make-docs/system/contracts}/guide-contract.md +21 -19
  59. package/template/{docs/assets/references → .make-docs/system/contracts}/history-record-contract.md +17 -11
  60. package/template/.make-docs/system/contracts/human-experience-contract.md +134 -0
  61. package/template/.make-docs/system/contracts/naive-uat-contract.md +231 -0
  62. package/template/.make-docs/system/contracts/output-contract.md +277 -0
  63. package/template/.make-docs/system/contracts/performance-evidence-governance.md +257 -0
  64. package/template/.make-docs/system/contracts/system-resource-contract.md +93 -0
  65. package/template/.make-docs/system/prompts/AGENTS.md +12 -0
  66. package/template/.make-docs/system/prompts/CLAUDE.md +12 -0
  67. package/template/.make-docs/system/prompts/coverage-pass-maintainer-guide.prompt.md +20 -0
  68. package/template/.make-docs/system/prompts/coverage-pass-prd-reconciliation.prompt.md +18 -0
  69. package/template/.make-docs/system/prompts/coverage-pass-testing-uat.prompt.md +46 -0
  70. package/template/.make-docs/system/prompts/coverage-pass-user-guide.prompt.md +20 -0
  71. package/template/.make-docs/system/prompts/designs-to-plan-change.prompt.md +18 -0
  72. package/template/.make-docs/system/prompts/designs-to-plan.prompt.md +14 -0
  73. package/template/.make-docs/system/prompts/docs-path-hygiene-cleanup.prompt.md +29 -0
  74. package/template/.make-docs/system/prompts/naive-uat-facilitator.prompt.md +28 -0
  75. package/template/.make-docs/system/prompts/naive-uat-tester.prompt.md +20 -0
  76. package/template/.make-docs/system/prompts/performance-coverage.prompt.md +63 -0
  77. package/template/.make-docs/system/prompts/plan-to-prd-change.prompt.md +12 -0
  78. package/template/.make-docs/system/prompts/plan-to-prd-green-field.prompt.md +10 -0
  79. package/template/.make-docs/system/prompts/prd-change-to-work.prompt.md +14 -0
  80. package/template/.make-docs/system/prompts/prd-to-work-full-prd.prompt.md +10 -0
  81. package/template/.make-docs/system/prompts/prd-to-work-prd-feature.prompt.md +10 -0
  82. package/template/.make-docs/system/prompts/request-to-design.prompt.md +20 -0
  83. package/template/.make-docs/system/prompts/session-to-history-record.prompt.md +23 -0
  84. package/template/{docs/assets → .make-docs/system}/prompts/work-to-commit-message.prompt.md +2 -2
  85. package/template/.make-docs/system/prompts/work-to-guides.prompt.md +22 -0
  86. package/template/.make-docs/system/references/AGENTS.md +14 -0
  87. package/template/.make-docs/system/references/CLAUDE.md +14 -0
  88. package/template/{docs/assets → .make-docs/system}/references/design-workflow.md +15 -2
  89. package/template/.make-docs/system/references/execution-workflow.md +189 -0
  90. package/template/.make-docs/system/references/human-experience.md +138 -0
  91. package/template/.make-docs/system/references/lifecycle.md +153 -0
  92. package/template/.make-docs/system/references/naive-uat-validation.md +65 -0
  93. package/template/.make-docs/system/references/naive-uat-workflow.md +64 -0
  94. package/template/.make-docs/system/references/path-and-link-hygiene.md +101 -0
  95. package/template/.make-docs/system/references/performance-evidence.md +114 -0
  96. package/template/.make-docs/system/references/planning-workflow.md +209 -0
  97. package/template/.make-docs/system/references/prd-change-management.md +165 -0
  98. package/template/{docs/assets → .make-docs/system}/references/wave-model.md +10 -8
  99. package/template/.make-docs/system/templates/AGENTS.md +12 -0
  100. package/template/.make-docs/system/templates/CLAUDE.md +12 -0
  101. package/template/.make-docs/system/templates/design.md +79 -0
  102. package/template/{docs/assets/templates/guide-developer.md → .make-docs/system/templates/guide-maintainer.md} +7 -3
  103. package/template/{docs/assets → .make-docs/system}/templates/guide-user.md +6 -2
  104. package/template/{docs/assets → .make-docs/system}/templates/history-record.md +6 -3
  105. package/template/.make-docs/system/templates/naive-uat-scenario.md +91 -0
  106. package/template/.make-docs/system/templates/performance-evidence-profile.md +252 -0
  107. package/template/.make-docs/system/templates/plan-overview.md +76 -0
  108. package/template/.make-docs/system/templates/plan-prd-change.md +155 -0
  109. package/template/{docs/assets → .make-docs/system}/templates/plan-prd-decompose.md +10 -0
  110. package/template/{docs/assets → .make-docs/system}/templates/plan-prd.md +28 -2
  111. package/template/{docs/assets → .make-docs/system}/templates/prd-architecture.md +13 -0
  112. package/template/.make-docs/system/templates/prd-glossary.md +28 -0
  113. package/template/.make-docs/system/templates/prd-index.md +70 -0
  114. package/template/{docs/assets → .make-docs/system}/templates/prd-overview.md +13 -0
  115. package/template/.make-docs/system/templates/prd-reference.md +30 -0
  116. package/template/{docs/assets → .make-docs/system}/templates/prd-risk-register.md +16 -1
  117. package/template/{docs/assets → .make-docs/system}/templates/prd-subsystem.md +15 -0
  118. package/template/.make-docs/system/templates/work-index.md +58 -0
  119. package/template/.make-docs/system/templates/work-phase.md +107 -0
  120. package/template/.make-docs/system-resources.catalog.json +91 -0
  121. package/template/.make-docs/system-resources.schema.json +204 -0
  122. package/template/AGENTS.md +8 -1
  123. package/template/CLAUDE.md +8 -1
  124. package/template/docs/AGENTS.codex-only.md +22 -0
  125. package/template/docs/AGENTS.md +21 -13
  126. package/template/docs/CLAUDE.claude-only.md +22 -0
  127. package/template/docs/CLAUDE.md +21 -13
  128. package/template/docs/assets/AGENTS.md +11 -7
  129. package/template/docs/assets/CLAUDE.md +11 -7
  130. package/template/docs/designs/AGENTS.md +8 -3
  131. package/template/docs/designs/CLAUDE.md +8 -3
  132. package/template/docs/plans/AGENTS.md +10 -3
  133. package/template/docs/plans/CLAUDE.md +10 -3
  134. package/template/docs/prd/AGENTS.md +14 -4
  135. package/template/docs/prd/CLAUDE.md +14 -4
  136. package/template/docs/work/AGENTS.md +10 -3
  137. package/template/docs/work/CLAUDE.md +10 -3
  138. package/dist/chunk-HP3HBG7F.js +0 -626
  139. package/dist/chunk-HP3HBG7F.js.map +0 -1
  140. package/dist/chunk-QRFH4J6H.js +0 -1194
  141. package/dist/chunk-QRFH4J6H.js.map +0 -1
  142. package/dist/chunk-WM3OXYTW.js +0 -2630
  143. package/dist/chunk-WM3OXYTW.js.map +0 -1
  144. package/dist/skills-command-3ESCZ75U.js.map +0 -1
  145. package/dist/uninstall-GQE4SJF2.js +0 -150
  146. package/dist/uninstall-GQE4SJF2.js.map +0 -1
  147. package/template/.make-docs/scripts/check_path_hygiene.py +0 -435
  148. package/template/docs/assets/archive/AGENTS.md +0 -20
  149. package/template/docs/assets/archive/CLAUDE.md +0 -20
  150. package/template/docs/assets/history/AGENTS.md +0 -12
  151. package/template/docs/assets/history/CLAUDE.md +0 -12
  152. package/template/docs/assets/prompts/AGENTS.md +0 -8
  153. package/template/docs/assets/prompts/CLAUDE.md +0 -8
  154. package/template/docs/assets/prompts/designs-to-plan-change.prompt.md +0 -14
  155. package/template/docs/assets/prompts/designs-to-plan.prompt.md +0 -10
  156. package/template/docs/assets/prompts/docs-path-hygiene-cleanup.prompt.md +0 -27
  157. package/template/docs/assets/prompts/plan-to-prd-change.prompt.md +0 -8
  158. package/template/docs/assets/prompts/plan-to-prd-green-field.prompt.md +0 -6
  159. package/template/docs/assets/prompts/prd-change-to-work.prompt.md +0 -10
  160. package/template/docs/assets/prompts/prd-to-work-full-prd.prompt.md +0 -6
  161. package/template/docs/assets/prompts/prd-to-work-prd-feature.prompt.md +0 -6
  162. package/template/docs/assets/prompts/request-to-design.prompt.md +0 -16
  163. package/template/docs/assets/prompts/session-to-history-record.prompt.md +0 -19
  164. package/template/docs/assets/prompts/work-to-guides.prompt.md +0 -18
  165. package/template/docs/assets/references/AGENTS.md +0 -9
  166. package/template/docs/assets/references/CLAUDE.md +0 -9
  167. package/template/docs/assets/references/execution-workflow.md +0 -157
  168. package/template/docs/assets/references/output-contract.md +0 -221
  169. package/template/docs/assets/references/path-and-link-hygiene.md +0 -49
  170. package/template/docs/assets/references/planning-workflow.md +0 -160
  171. package/template/docs/assets/references/prd-change-management.md +0 -129
  172. package/template/docs/assets/templates/AGENTS.md +0 -8
  173. package/template/docs/assets/templates/CLAUDE.md +0 -8
  174. package/template/docs/assets/templates/design.md +0 -30
  175. package/template/docs/assets/templates/plan-overview.md +0 -32
  176. package/template/docs/assets/templates/plan-prd-change.md +0 -99
  177. package/template/docs/assets/templates/prd-change-addition.md +0 -45
  178. package/template/docs/assets/templates/prd-change-revision.md +0 -45
  179. package/template/docs/assets/templates/prd-glossary.md +0 -15
  180. package/template/docs/assets/templates/prd-index.md +0 -45
  181. package/template/docs/assets/templates/prd-reference.md +0 -17
  182. package/template/docs/assets/templates/work-index.md +0 -21
  183. package/template/docs/assets/templates/work-phase.md +0 -34
  184. package/template/docs/guides/AGENTS.md +0 -15
  185. package/template/docs/guides/CLAUDE.md +0 -15
  186. /package/template/{docs/assets → .make-docs/system}/prompts/update-readme-green-field.prompt.md +0 -0
  187. /package/template/{docs/assets → .make-docs/system}/references/harness-capability-matrix.md +0 -0
@@ -0,0 +1 @@
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,2BAA2B;AAAA,MAC1D,KAAK;AAAA,IACP,CAAC;AAAA,EACH,EAAE,MAAM,wBAAwB;AAChC,QAAM,QAAQ,WAAW;AACzB,SAAO;AAAA,IACL,WAAW,MAAM,UAAU,IAAI,CAAC,UAAU;AACxC,UAAI,CAAC,MAAM,OAAO,IAAI;AACpB,eAAO;AAAA,UACL,KAAK,MAA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