@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/self/install-manager.ts","../src/self/pre-v2.ts","../src/self/uninstall-tool.ts","../src/store/tool-operations.ts","../src/self/update-tool.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { realpathSync } from \"node:fs\";\nimport { readPackageMeta } from \"../utils\";\n\n/**\n * Install-manager detection matrix (W18 R11 P3; PRD 39 R-SELF-1..3).\n *\n * The tool self-management commands (`make-docs update` / `make-docs\n * uninstall`) must decide whether the running binary is a persistent global\n * install — and if so, which install manager owns it — or a transient\n * remote-execution invocation (npx / pnpm dlx / bunx), where no persistent\n * binary exists on the machine.\n *\n * D9 implementer freedom — the documented detection matrix:\n *\n * The realpath of the running script (`process.argv[1]`, falling back to\n * `process.execPath`) is normalized to POSIX separators and matched against\n * two data-driven marker sets, in this order:\n *\n * 1. Remote-execution (transient runner cache) markers — matched first, so a\n * runner cache that happens to live under a manager directory (for\n * example pnpm's dlx store under `~/Library/pnpm/store/`) is classified\n * as remote, never persistent:\n * - `/_npx/` — npm exec / npx cache (`~/.npm/_npx/<hash>/…`)\n * - `/pnpm/store/` — pnpm content-addressable store (dlx runs here)\n * - `/.pnpm-store/` — alternate pnpm store location\n * - `/dlx-<id>/` — pnpm dlx temporary install directories\n * - `/.bun/install/cache/` — bun package cache (bunx executes from here)\n * - `/bunx-<id>/` — bunx temporary directories\n *\n * 2. Persistent global-install markers, one entry per known manager:\n * - npm — `/lib/node_modules/` (covers `$(npm root -g)`-style\n * prefixes, including Homebrew-provided node at\n * `/opt/homebrew/lib/node_modules/…`, where npm still owns\n * the install)\n * - pnpm — `/pnpm/global/`, `/.local/share/pnpm/`, `/Library/pnpm/`\n * - bun — `/.bun/install/global/`\n * - homebrew — `/Cellar/make-docs/` (a make-docs formula install; a\n * Homebrew *node* install that used `npm install -g` matches\n * the npm marker instead, which is the correct owner)\n *\n * A persistent marker only counts when the matched path also references the\n * make-docs package (substring `make-docs`), so a node binary living under\n * `/Cellar/node/…` never claims ownership. Exactly one matching manager →\n * `persistent`. More than one, or a path matching no known pattern (for\n * example a repo checkout during development) → `ambiguous`: the commands\n * never guess and instead print the exact command(s) and the affected store\n * path (R-SELF-3). A remote marker → `remote`: there is no persistent\n * binary on the machine.\n *\n * Command execution is behind the injectable {@link ExecCommand} seam so\n * tests never run a real package manager.\n */\n\n/** npm package name of the CLI itself (used in manager commands). */\nexport const SELF_PACKAGE_NAME: string = (() => {\n try {\n return readPackageMeta().name;\n } catch {\n return \"@brucewaynedecoy/make-docs\";\n }\n})();\n\nexport type InstallManagerId = \"npm\" | \"pnpm\" | \"bun\" | \"homebrew\";\n\nexport interface ManagerCommand {\n command: string;\n args: string[];\n}\n\nexport interface InstallManagerSpec {\n id: InstallManagerId;\n label: string;\n /** Path markers identifying this manager's persistent global root. */\n markers: readonly RegExp[];\n uninstallCommand: ManagerCommand;\n updateCommand: ManagerCommand;\n}\n\nexport const INSTALL_MANAGER_MATRIX: readonly InstallManagerSpec[] = [\n {\n id: \"npm\",\n label: \"npm (global install)\",\n markers: [/\\/lib\\/node_modules\\//],\n uninstallCommand: { command: \"npm\", args: [\"uninstall\", \"-g\", SELF_PACKAGE_NAME] },\n updateCommand: {\n command: \"npm\",\n args: [\"install\", \"-g\", `${SELF_PACKAGE_NAME}@latest`],\n },\n },\n {\n id: \"pnpm\",\n label: \"pnpm (global install)\",\n markers: [/\\/pnpm\\/global\\//, /\\/\\.local\\/share\\/pnpm\\//, /\\/Library\\/pnpm\\//],\n uninstallCommand: { command: \"pnpm\", args: [\"remove\", \"-g\", SELF_PACKAGE_NAME] },\n updateCommand: {\n command: \"pnpm\",\n args: [\"add\", \"-g\", `${SELF_PACKAGE_NAME}@latest`],\n },\n },\n {\n id: \"bun\",\n label: \"bun (global install)\",\n markers: [/\\/\\.bun\\/install\\/global\\//],\n uninstallCommand: { command: \"bun\", args: [\"remove\", \"-g\", SELF_PACKAGE_NAME] },\n updateCommand: {\n command: \"bun\",\n args: [\"add\", \"-g\", `${SELF_PACKAGE_NAME}@latest`],\n },\n },\n {\n id: \"homebrew\",\n label: \"Homebrew\",\n markers: [/\\/Cellar\\/make-docs\\//],\n uninstallCommand: { command: \"brew\", args: [\"uninstall\", \"make-docs\"] },\n updateCommand: { command: \"brew\", args: [\"upgrade\", \"make-docs\"] },\n },\n];\n\n/** Transient runner caches: matching paths mean remote execution. */\nexport const REMOTE_EXECUTION_MARKERS: readonly RegExp[] = [\n /\\/_npx\\//,\n /\\/pnpm\\/store\\//,\n /\\/\\.pnpm-store\\//,\n /\\/dlx-[^/]+\\//,\n /\\/\\.bun\\/install\\/cache\\//,\n /\\/bunx-[^/]+\\//,\n];\n\nexport type InstallDetection =\n | {\n kind: \"persistent\";\n manager: InstallManagerSpec;\n binaryPath: string;\n }\n | {\n kind: \"remote\";\n binaryPath: string | null;\n evidence: string;\n }\n | {\n kind: \"ambiguous\";\n binaryPath: string | null;\n candidates: InstallManagerSpec[];\n reason: string;\n };\n\nexport interface DetectInstallSourceOptions {\n /** Script path of the running CLI; defaults to `process.argv[1]`. */\n argv1?: string;\n /** Node (or standalone) binary path; defaults to `process.execPath`. */\n execPath?: string;\n /** Realpath resolver seam; defaults to `fs.realpathSync`. */\n realpath?: (candidate: string) => string;\n}\n\nexport function detectInstallSource(\n options: DetectInstallSourceOptions = {},\n): InstallDetection {\n const realpath = options.realpath ?? defaultRealpath;\n const rawCandidates = [\n options.argv1 ?? process.argv[1],\n options.execPath ?? process.execPath,\n ].filter((candidate): candidate is string => Boolean(candidate));\n const resolvedPaths = [\n ...new Set(rawCandidates.map((candidate) => toPosixPath(realpath(candidate)))),\n ];\n const primaryPath = resolvedPaths[0] ?? null;\n\n if (resolvedPaths.length === 0) {\n return {\n kind: \"ambiguous\",\n binaryPath: null,\n candidates: [],\n reason: \"No script or binary path is available to inspect.\",\n };\n }\n\n for (const resolvedPath of resolvedPaths) {\n const remoteMarker = REMOTE_EXECUTION_MARKERS.find((marker) =>\n marker.test(resolvedPath),\n );\n if (remoteMarker) {\n return {\n kind: \"remote\",\n binaryPath: resolvedPath,\n evidence: `${resolvedPath} matches the transient runner cache pattern ${remoteMarker}.`,\n };\n }\n }\n\n const owners = new Map<InstallManagerId, { spec: InstallManagerSpec; path: string }>();\n for (const resolvedPath of resolvedPaths) {\n if (!resolvedPath.includes(\"make-docs\")) {\n continue;\n }\n for (const spec of INSTALL_MANAGER_MATRIX) {\n if (spec.markers.some((marker) => marker.test(resolvedPath))) {\n owners.set(spec.id, { spec, path: resolvedPath });\n }\n }\n }\n\n const matches = [...owners.values()];\n if (matches.length === 1) {\n return {\n kind: \"persistent\",\n manager: matches[0].spec,\n binaryPath: matches[0].path,\n };\n }\n\n if (matches.length > 1) {\n return {\n kind: \"ambiguous\",\n binaryPath: primaryPath,\n candidates: matches.map((match) => match.spec),\n reason: `The path matches more than one install manager (${matches\n .map((match) => match.spec.id)\n .join(\", \")}).`,\n };\n }\n\n return {\n kind: \"ambiguous\",\n binaryPath: primaryPath,\n candidates: [],\n reason: `${primaryPath} matches no known install-manager global root or runner cache.`,\n };\n}\n\nexport function formatManagerCommand(command: ManagerCommand): string {\n return [command.command, ...command.args].join(\" \");\n}\n\n/**\n * Injectable command-execution seam. The default implementation runs the\n * manager command in the foreground with inherited stdio; tests inject a\n * fake so no real package manager ever runs.\n */\nexport type ExecCommand = (\n command: string,\n args: string[],\n) => Promise<{ exitCode: number | null }>;\n\nexport const defaultExecCommand: ExecCommand = async (command, args) => {\n const result = spawnSync(command, args, { stdio: \"inherit\" });\n return { exitCode: result.status };\n};\n\nfunction defaultRealpath(candidate: string): string {\n try {\n return realpathSync(candidate);\n } catch {\n return candidate;\n }\n}\n\nfunction toPosixPath(candidate: string): string {\n return candidate.split(\"\\\\\").join(\"/\");\n}\n","import { isCancel, note, select } from \"@clack/prompts\";\nimport type { CompatibilityClassification } from \"../compatibility\";\n\n/**\n * Pre-v2 detection and the R-MIG-2 warning-and-choice flow (W18 R11 P3).\n *\n * `update`, `setup`, and `setup reconfigure` detect a pre-v2 configuration by\n * fingerprint and, when found, warn about what the hard cutover can break,\n * then offer backing up and installing the latest version (recommended) or\n * cancelling. There are no aliases, so this flow is the only migration path\n * (R-MIG-1, R-MIG-2).\n */\n\n/**\n * D9 implementer freedom — the documented pre-v2 fingerprint set.\n *\n * Detection is a pure function over the compatibility classifier's evidence\n * ({@link CompatibilityClassification}); there is no parallel filesystem\n * scan. An install is pre-v2 when any of these fingerprints is present:\n *\n * - `manifest-schema-version-1` — the project manifest at\n * `.make-docs/manifest.json` parses and carries `schemaVersion: 1`\n * (`evidence.manifestTrust.schemaVersion === 1`).\n * - `state-clean-v1` — the classifier resolved the install to the\n * `clean-v1` source state (a pristine v1-era install).\n * - `state-modified-v1` — the classifier resolved the install to the\n * `modified-v1` source state (a v1-era install with local edits).\n *\n * Deliberately *not* fingerprints: `missing-manifest-recognizable`,\n * `malformed-manifest`, `partial-install`, and `unknown-shape`. Those states\n * carry no trustworthy version evidence, and guessing \"pre-v2\" from them\n * would route non-make-docs or broken directories into an upgrade warning\n * they do not own; the classifier's own dispositions govern those cases.\n */\nexport interface PreV2Detection {\n preV2: boolean;\n fingerprints: string[];\n}\n\nexport function detectPreV2Install(input: {\n targetDir: string;\n classification: CompatibilityClassification;\n}): PreV2Detection {\n const { classification } = input;\n const fingerprints: string[] = [];\n\n if (classification.evidence.manifestTrust.schemaVersion === 1) {\n fingerprints.push(\"manifest-schema-version-1\");\n }\n if (classification.state === \"clean-v1\") {\n fingerprints.push(\"state-clean-v1\");\n }\n if (classification.state === \"modified-v1\") {\n fingerprints.push(\"state-modified-v1\");\n }\n\n return { preV2: fingerprints.length > 0, fingerprints };\n}\n\nexport type PreV2Choice = \"backup-and-install\" | \"cancel\";\n\n/**\n * R-MIG-2 warning copy (D9 implementer freedom): itemizes the v2 changes\n * that can break a pre-v2 install on upgrade.\n */\nexport const PRE_V2_BREAKING_CHANGES: readonly string[] = [\n \"Command spellings are replaced by the five-command tree (setup, run, mcp, update, uninstall); removed spellings have no aliases.\",\n \"Project uninstall is renamed: use `make-docs setup remove` (top-level `uninstall` now removes the tool's machine footprint).\",\n \"Run-state and work-execution evidence relocate to the global store at ~/.make-docs/, keyed by a minted project identifier.\",\n \"MCP tool names are renamed to registry-derived identifiers.\",\n \"The project manifest schema is upgraded and a project identifier is minted.\",\n];\n\nexport interface SelfCommandOutput {\n write(text: string): void;\n}\n\nexport const defaultSelfCommandOutput: SelfCommandOutput = {\n write(text) {\n process.stdout.write(`${text}\\n`);\n },\n};\n\n/**\n * Presents the R-MIG-2 warning and the backup-or-cancel choice for a\n * detected pre-v2 install. Non-interactive invocations refuse to proceed:\n * they print why and return \"cancel\" — a pre-v2 install is never silently\n * upgraded.\n */\nexport async function promptPreV2Choice(input: {\n detection: PreV2Detection;\n interactive: boolean;\n command: string;\n output?: SelfCommandOutput;\n}): Promise<PreV2Choice> {\n if (!input.detection.preV2) {\n return \"backup-and-install\";\n }\n\n const output = input.output ?? defaultSelfCommandOutput;\n const warningLines = [\n `A pre-v2 make-docs install was detected (fingerprints: ${input.detection.fingerprints.join(\", \")}).`,\n \"Upgrading is a hard cutover; these changes can break the existing install:\",\n ...PRE_V2_BREAKING_CHANGES.map((change) => `- ${change}`),\n ];\n\n if (!input.interactive) {\n for (const line of warningLines) {\n output.write(line);\n }\n output.write(\n `\\`make-docs ${input.command}\\` will not silently upgrade a pre-v2 install. ` +\n \"Re-run in an interactive terminal to choose between backing up and installing the latest version (recommended) and cancelling, \" +\n \"or create an explicit backup first with `make-docs setup backup`.\",\n );\n return \"cancel\";\n }\n\n note(warningLines.join(\"\\n\"), `make-docs ${input.command}: pre-v2 install detected`);\n\n const choice = await select<PreV2Choice>({\n message: \"How should make-docs proceed?\",\n withGuide: true,\n initialValue: \"backup-and-install\",\n options: [\n {\n value: \"backup-and-install\",\n label: \"Back up and install the latest version (recommended)\",\n },\n {\n value: \"cancel\",\n label: \"Cancel\",\n },\n ],\n });\n\n if (isCancel(choice)) {\n return \"cancel\";\n }\n\n return choice;\n}\n","import { existsSync, readdirSync, rmdirSync } from \"node:fs\";\nimport { stdin, stdout } from \"node:process\";\nimport { confirm, isCancel } from \"@clack/prompts\";\nimport {\n removeGlobalStore,\n resolveStoreRoot,\n type RemoveGlobalStoreResult,\n} from \"../store\";\nimport {\n defaultExecCommand,\n detectInstallSource,\n formatManagerCommand,\n INSTALL_MANAGER_MATRIX,\n type ExecCommand,\n type InstallDetection,\n type InstallManagerId,\n} from \"./install-manager\";\nimport { defaultSelfCommandOutput, type SelfCommandOutput } from \"./pre-v2\";\n\nimport { prepareToolOperationStore, runRecordedToolOperation, withStoreRemovalLock } from \"../store/tool-operations\";\n\n/** Remove the installed binary. Preserve the global Store unless separately selected. */\nexport interface ToolUninstallOptions {\n /** Counts as confirmation; required for non-TTY runs. */\n yes: boolean;\n /** Separate explicit selection; --yes alone never removes the Store. */\n removeStore?: boolean;\n storeRoot?: string;\n homeDir?: string;\n env?: NodeJS.ProcessEnv;\n execPath?: string;\n argv1?: string;\n /** Injectable seams (tests). */\n exec?: ExecCommand;\n realpath?: (candidate: string) => string;\n output?: SelfCommandOutput;\n}\n\nexport type ToolUninstallBinaryOutcome =\n | { kind: \"removed\"; manager: InstallManagerId; command: string; exitCode: number | null }\n | { kind: \"failed\"; manager: InstallManagerId; command: string; exitCode: number | null }\n | { kind: \"not-installed\"; evidence: string }\n | { kind: \"manual\"; candidates: InstallManagerId[]; commands: string[] };\n\nexport interface ToolUninstallResult {\n operationId: string | null;\n status:\n | \"completed\"\n | \"cancelled\"\n | \"refused-non-interactive\"\n | \"manual-binary-removal-required\";\n storeRoot: string;\n detection: InstallDetection;\n storeRemoval: RemoveGlobalStoreResult | null;\n binary: ToolUninstallBinaryOutcome | null;\n /** Human-readable report lines, also written to the output seam. */\n lines: string[];\n}\n\nexport async function runToolUninstallCommand(\n options: ToolUninstallOptions,\n): Promise<ToolUninstallResult> {\n const output = options.output ?? defaultSelfCommandOutput;\n const exec = options.exec ?? defaultExecCommand;\n const storeRoot = resolveStoreRoot({\n storeRoot: options.storeRoot,\n env: options.env,\n homeDir: options.homeDir,\n });\n const detection = detectInstallSource({\n argv1: options.argv1,\n execPath: options.execPath,\n realpath: options.realpath,\n });\n\n const lines: string[] = [];\n const emit = (line: string) => {\n lines.push(line);\n output.write(line);\n };\n\n emit(\"make-docs uninstall removes the installed binary:\");\n emit(\n `- global Store: ${storeRoot} (${options.removeStore ? \"explicit removal selected; all stored history and recovery records will be deleted\" : \"preserved\"})`,\n );\n emit(`- installed binary: ${describeBinaryFootprint(detection)}`);\n emit(\n \"Repository content is never touched; to remove make-docs from a project, use `make-docs setup remove`.\",\n );\n\n const result: ToolUninstallResult = {\n operationId: null,\n status: \"completed\",\n storeRoot,\n detection,\n storeRemoval: null,\n binary: null,\n lines,\n };\n\n if (!options.yes) {\n if (!stdin.isTTY || !stdout.isTTY) {\n result.status = \"refused-non-interactive\";\n emit(\n \"Uninstall confirmation requires a TTY. Re-run with `make-docs uninstall --yes` to confirm removal of the footprint listed above. Nothing was removed.\",\n );\n return result;\n }\n\n const proceed = await confirm({\n message: options.removeStore ? \"Remove the binary and permanently delete the global Store records listed above?\" : \"Remove the make-docs binary and preserve the global Store?\",\n initialValue: false,\n active: \"Yes\",\n inactive: \"No\",\n withGuide: true,\n });\n if (isCancel(proceed) || !proceed) {\n result.status = \"cancelled\";\n emit(\"Uninstall cancelled. Nothing was removed.\");\n return result;\n }\n }\n\n const targetDir = process.cwd();\n prepareToolOperationStore(targetDir, storeRoot);\n emit(`The global Store is preserved at ${storeRoot}.`);\n const removeSelectedStore = () => {\n if (!options.removeStore) return;\n const removal = withStoreRemovalLock(targetDir, storeRoot, () =>\n removeGlobalStore({storeRoot, env:options.env, homeDir:options.homeDir}));\n removal.retainedEntries = removal.retainedEntries.filter(entry => entry !== \"removal.lock\");\n removal.warnings = removal.warnings.filter(warning => !warning.includes(\"removal.lock\"));\n if (removal.status !== \"refused\" && existsSync(storeRoot) && readdirSync(storeRoot).length === 0) {\n rmdirSync(storeRoot);\n removal.status = \"removed\";\n }\n result.storeRemoval = removal;\n emit(describeStoreRemoval(removal));\n for (const warning of removal.warnings) emit(`Warning: ${warning}`);\n };\n\n if (detection.kind === \"persistent\") {\n const command = formatManagerCommand(detection.manager.uninstallCommand);\n const recorded = await runRecordedToolOperation(targetDir, storeRoot, \"tool.uninstall\", {\n manager:detection.manager.id, command, binaryPath:detection.binaryPath,\n }, () => exec(detection.manager.uninstallCommand.command, detection.manager.uninstallCommand.args));\n result.operationId = recorded.operationId;\n const { exitCode } = recorded.result;\n emit(`Tool operation recorded in the Store: ${recorded.operationId}`);\n if (exitCode === 0) {\n result.binary = {\n kind: \"removed\",\n manager: detection.manager.id,\n command,\n exitCode,\n };\n emit(`Removed the installed binary via ${detection.manager.id}: ${command}`);\n removeSelectedStore();\n } else {\n result.binary = {\n kind: \"failed\",\n manager: detection.manager.id,\n command,\n exitCode,\n };\n result.status = \"manual-binary-removal-required\";\n emit(\n `The ${detection.manager.id} uninstall command failed (exit code ${exitCode ?? \"unknown\"}). Run it manually: ${command}`,\n );\n }\n return result;\n }\n\n if (detection.kind === \"remote\") {\n result.binary = { kind: \"not-installed\", evidence: detection.evidence };\n removeSelectedStore();\n emit(\n \"No persistent make-docs binary is installed: this invocation uses a package runner. The Store remains available unless explicit removal was selected.\",\n );\n return result;\n }\n\n // Ambiguous ownership: never guess and execute (R-SELF-3). Print the\n // exact command(s) and the affected store path instead.\n const candidates =\n detection.candidates.length > 0 ? detection.candidates : [...INSTALL_MANAGER_MATRIX];\n const commands = candidates.map((candidate) =>\n formatManagerCommand(candidate.uninstallCommand),\n );\n result.binary = {\n kind: \"manual\",\n candidates: candidates.map((candidate) => candidate.id),\n commands,\n };\n result.status = \"manual-binary-removal-required\";\n emit(\n `Could not determine which install manager owns the make-docs binary (${detection.reason})`,\n );\n emit(\n \"make-docs will not guess and run a destructive global change. If you installed the binary yourself, run the matching command:\",\n );\n for (const command of commands) {\n emit(` ${command}`);\n }\n emit(`Affected store path: ${storeRoot}`);\n return result;\n}\n\nfunction describeBinaryFootprint(detection: InstallDetection): string {\n if (detection.kind === \"persistent\") {\n return `${detection.binaryPath} (managed by ${detection.manager.id}; will run \\`${formatManagerCommand(detection.manager.uninstallCommand)}\\`)`;\n }\n if (detection.kind === \"remote\") {\n return \"none detected (remote execution via a package runner; nothing persistent to remove)\";\n }\n return \"ownership is ambiguous; the exact command(s) will be printed instead of executed\";\n}\n\nfunction describeStoreRemoval(removal: RemoveGlobalStoreResult): string {\n switch (removal.status) {\n case \"removed\":\n return `Removed the global store at ${removal.storeRoot} (${removal.removedFiles.length} file(s)).`;\n case \"not-found\":\n return `No global store exists at ${removal.storeRoot}; nothing to remove.`;\n case \"refused\":\n return `Refused to remove ${removal.storeRoot}; see the warning below.`;\n default:\n return `The global store at ${removal.storeRoot} was partially removed; retained entries: ${removal.retainedEntries.join(\", \") || \"(none)\"}.`;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport { existsSync, lstatSync, unlinkSync, readFileSync, type Stats } from \"node:fs\";\nimport { GLOBAL_ASSET_LOCK_FILE } from \"./global-asset-lock\";\nimport { STORE_LEASE_RECOVERY_FILE } from \"./lease-recovery\";\nimport { getStoreDatabasePath, classifyStoreCheckpoint9State } from \"../store\";\nimport { acquireStoreAccess, makeStoreIssue, openStoreSqliteConnection, STORE_OWNER_WAIT_MS, StoreUnavailableError, tryCreateExclusiveStoreLease, waitForStoreAccessToDrain } from \"./database\";\nimport { validateInstallationStoreRoot, withInstallationDatabase } from \"./installation-state\";\nimport { platform } from \"../platform\";\n\nexport interface ToolOperationMetadata {\n manager: string;\n command: string;\n binaryPath: string;\n}\n\n/** Prepare required machine state without minting a project or checkout identity. */\nexport function prepareToolOperationStore(targetDir: string, storeRoot: string): void {\n withInstallationDatabase(targetDir, db => {\n db.prepare(\"SELECT operation_id FROM tool_operations LIMIT 1\").get();\n }, { storeRoot });\n}\n\n/** Never retry a package manager implicitly. A crash leaves a durable pending operation. */\nexport async function runRecordedToolOperation<T extends { exitCode: number | null }>(\n targetDir: string,\n storeRoot: string,\n operation: \"tool.update\" | \"tool.uninstall\",\n metadata: ToolOperationMetadata,\n delegate: () => Promise<T>,\n): Promise<{ operationId: string; result: T }> {\n const operationId = randomUUID();\n withInstallationDatabase(targetDir, db => {\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n const pending = db.prepare(\"SELECT operation_id, pid, hostname FROM tool_operations WHERE status='pending' LIMIT 1\").get() as {operation_id:string;pid:number;hostname:string}|undefined;\n if (pending) throw new Error(`Tool operation ${pending.operation_id} is pending (${pending.hostname}, process ${pending.pid}). Inspect the package manager result before another tool change. No command was run.`);\n // A checkout reserves its SQL lock before taking its long-lived access\n // lease. Check both reservations in this same transaction so a tool\n // command cannot enter that handoff gap or bypass unfinished recovery.\n const installation = db.prepare(\"SELECT operation_id FROM installation_operations WHERE status='pending' LIMIT 1\").get() as {operation_id:string}|undefined;\n const writer = db.prepare(\"SELECT root_path FROM installation_locks LIMIT 1\").get() as {root_path:string}|undefined;\n if (installation || writer) throw new Error(\"An installation operation or checkout writer is pending. Resolve that work before a tool change. No command was run.\");\n db.prepare(\"INSERT INTO tool_operations (operation_id,operation,status,pid,hostname,metadata_json,started_at,finished_at) VALUES (?,?,'pending',?,?,?,?,NULL)\")\n .run(operationId, operation, process.pid, platform.hostname, JSON.stringify(metadata), new Date().toISOString());\n db.exec(\"COMMIT\");\n } catch(error) { db.exec(\"ROLLBACK\"); throw error; }\n }, {storeRoot});\n // Close the removal handshake before external mutation. A remover that\n // starts later must see this pending row; an earlier remover blocks here.\n withInstallationDatabase(targetDir, db => {\n const saved = db.prepare(\"SELECT status, operation, pid, hostname FROM tool_operations WHERE operation_id=?\").get(operationId) as {status:string;operation:string;pid:number;hostname:string}|undefined;\n if (!saved || saved.status !== \"pending\" || saved.operation !== operation || saved.pid !== process.pid || saved.hostname !== platform.hostname) {\n throw new Error(`Tool intent read-back failed for ${operationId}; no package manager command was run.`);\n }\n }, {storeRoot,readOnly:true});\n if (existsSync(path.join(storeRoot,\"removal.lock\"))) throw new Error(`Store removal is active; tool operation ${operationId} remains pending and no package manager command was run.`);\n let result: T;\n try { result = await delegate(); }\n catch(error) {\n // A manager error is recorded, but never inferred to mean that it made no changes.\n withInstallationDatabase(targetDir, db => {\n db.prepare(\"UPDATE tool_operations SET status='failed', metadata_json=?, finished_at=? WHERE operation_id=? AND status='pending'\")\n .run(JSON.stringify({...metadata, outcome:\"delegate-threw\", changeOutcome:\"unknown\"}),new Date().toISOString(),operationId);\n },{storeRoot});\n throw error;\n }\n // If this write fails, the pending row remains. Do not claim success or run again.\n withInstallationDatabase(targetDir, db => {\n db.prepare(\"UPDATE tool_operations SET status=?, metadata_json=?, finished_at=? WHERE operation_id=? AND status='pending'\")\n .run(result.exitCode===0 ? \"completed\" : \"failed\",JSON.stringify({...metadata, exitCode:result.exitCode}),new Date().toISOString(),operationId);\n },{storeRoot});\n return {operationId,result};\n}\n\nfunction acquireRemovalLease(storeRoot: string, lockPath: string, token: string): Stats {\n const started = Date.now();\n const deadline = started + STORE_OWNER_WAIT_MS;\n let attempts = 0;\n while (true) {\n try {\n const result = tryCreateExclusiveStoreLease(lockPath, { token, pid: process.pid, hostname: platform.hostname, startedAt: new Date().toISOString() });\n if (result.created) return result.stat;\n throw Object.assign(new Error(\"The Store removal lock exists.\"), { code: \"EEXIST\" });\n } catch (error) {\n if (error instanceof StoreUnavailableError) throw error;\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", lockPath, \"create Store removal lock\", error, { attempts: attempts + 1, waitedMs: Date.now() - started }));\n }\n if (Date.now() >= deadline) {\n throw new StoreUnavailableError({ code: \"contention-timeout\", path: lockPath, operation: \"wait for Store removal\", retryable: true, attempts: attempts + 1, waitedMs: Date.now() - started, cause: \"The Store removal owner is still active.\" });\n }\n const release = acquireStoreAccess(storeRoot, false, Math.max(0, deadline - Date.now()));\n release();\n attempts++;\n }\n }\n}\n\n/** Hold the removal marker across checks and deletion. All corrected writers honor it. */\nexport function withStoreRemovalLock<T>(targetDir: string, storeRoot: string, remove: () => T): T {\n prepareToolOperationStore(targetDir, storeRoot);\n const lockPath = path.join(storeRoot, \"removal.lock\");\n const token = randomUUID();\n const lockStat = acquireRemovalLease(storeRoot, lockPath, token);\n const lockGuard = platform.captureFileGuard(lockStat, \"file\");\n try {\n const assertNoStoreAccess = () => {\n if ([\"installation-bootstrap.lock\", GLOBAL_ASSET_LOCK_FILE, STORE_LEASE_RECOVERY_FILE].some(name => lstatSync(path.join(storeRoot,name), { throwIfNoEntry: false }))) {\n throw new Error(\"A Store schema or global asset writer is active; the Store was preserved.\");\n }\n };\n assertNoStoreAccess();\n waitForStoreAccessToDrain(storeRoot);\n const db = openStoreSqliteConnection(getStoreDatabasePath(storeRoot), {readOnly:true}, \"inspect before removal\");\n try {\n const tool = db.prepare(\"SELECT operation_id FROM tool_operations WHERE status='pending' LIMIT 1\").get();\n const project = db.prepare(\"SELECT operation_id FROM installation_operations WHERE status='pending' LIMIT 1\").get();\n const writer = db.prepare(\"SELECT root_path FROM installation_locks LIMIT 1\").get();\n if (tool || project || writer) throw new Error(\"Store removal is blocked by a pending operation or active writer. Resolve that work first; the Store was preserved.\");\n } finally { db.close(); }\n assertNoStoreAccess();\n waitForStoreAccessToDrain(storeRoot);\n return remove();\n } finally {\n const current = lstatSync(lockPath, { throwIfNoEntry: false });\n if (current?.isFile() && platform.matchesFileGuard(current, lockGuard)) {\n try {\n const record = JSON.parse(readFileSync(lockPath, \"utf8\")) as { token?: unknown };\n if (record.token === token) unlinkSync(lockPath);\n } catch {\n // Preserve a replaced or unreadable removal lock for review.\n }\n }\n }\n}\n\nexport interface PendingToolOperation {\n id: string;\n operation: string;\n startedAt: string;\n status: \"pending\";\n nextAction: string;\n}\n/** Machine operations are shown separately; they never imply checkout ownership. */\nexport function listPendingToolOperations(projectRoot: string, storeRoot: string): PendingToolOperation[] {\n const store = validateInstallationStoreRoot(projectRoot, storeRoot);\n if (!existsSync(getStoreDatabasePath(store))) return [];\n if (classifyStoreCheckpoint9State(store).state === \"supported-legacy\") return [];\n return withInstallationDatabase(projectRoot, db => {\n const rows = db.prepare(\"SELECT operation_id,operation,started_at FROM tool_operations WHERE status='pending' ORDER BY started_at,operation_id LIMIT 10\").all() as {operation_id:string;operation:string;started_at:string}[];\n return rows.map(row => ({\n id: row.operation_id,\n operation: row.operation,\n startedAt: row.started_at,\n status: \"pending\" as const,\n nextAction: \"Inspect the installed CLI version and the package manager outcome. Review that evidence before reconciling this operation. Do not replay the package manager command automatically.\",\n }));\n }, {storeRoot:store,readOnly:true});\n}\n","import path from \"node:path\";\nimport { stdin, stdout } from \"node:process\";\nimport {\n classifyCompatibilityState,\n type CompatibilityClassification,\n} from \"../compatibility\";\nimport {\n bootstrapGlobalStore,\n resolveStoreRoot,\n type StoreBootstrapReport,\n} from \"../store\";\nimport { readPackageMeta } from \"../utils\";\nimport {\n defaultExecCommand,\n detectInstallSource,\n formatManagerCommand,\n INSTALL_MANAGER_MATRIX,\n type ExecCommand,\n type InstallDetection,\n} from \"./install-manager\";\nimport {\n defaultSelfCommandOutput,\n detectPreV2Install,\n promptPreV2Choice,\n type PreV2Choice,\n type PreV2Detection,\n type SelfCommandOutput,\n} from \"./pre-v2\";\n\nimport { prepareToolOperationStore, runRecordedToolOperation } from \"../store/tool-operations\";\n\n/**\n * Top-level `make-docs update` — detect-and-delegate tool update (W18 R11\n * P3; PRD 39 R-SELF-2, R-SELF-3, R-MIG-2).\n *\n * When a persistent global install is unambiguously detected, the command\n * delegates to that manager's update command (for example\n * `npm install -g @brucewaynedecoy/make-docs@latest`). When detection is\n * ambiguous it prints the exact command(s) and the affected store path\n * instead of executing (R-SELF-3). For remote execution there is nothing\n * persistent to update, because the runner fetches the requested version.\n * In all of these cases the pending global-store schema migration is applied\n * via {@link bootstrapGlobalStore} (PRD 38 R-DB-2) and its status is\n * included in the report — the bootstrap is additive machine-level state and\n * never touches repository content, so it also runs when a pre-v2 install\n * causes the command to cancel.\n *\n * Before delegating, the command runs pre-v2 detection against `targetDir`\n * (default: the current working directory) and surfaces the R-MIG-2\n * warning-and-choice flow when a pre-v2 install is present; choosing\n * \"backup-and-install\" creates a project backup before delegation, and\n * cancelling leaves the project install untouched.\n */\n\nexport interface ToolUpdateOptions {\n /** Accepted for CLI parity; the pre-v2 choice always requires a TTY. */\n yes: boolean;\n targetDir?: string;\n storeRoot?: string;\n env?: NodeJS.ProcessEnv;\n execPath?: string;\n argv1?: string;\n homeDir?: string;\n /** Injectable seams (tests). */\n exec?: ExecCommand;\n realpath?: (candidate: string) => string;\n output?: SelfCommandOutput;\n classify?: (input: {\n targetDir: string;\n homeDir?: string;\n }) => Promise<CompatibilityClassification>;\n runBackup?: (targetDir: string) => Promise<void>;\n}\n\nexport interface ToolUpdateResult {\n operationId: string | null;\n status:\n | \"delegated\"\n | \"delegate-failed\"\n | \"manual-update-required\"\n | \"nothing-persistent\"\n | \"cancelled-pre-v2\";\n storeRoot: string;\n /** Global-store bootstrap/migration report (PRD 38 R-DB-2). */\n bootstrap: StoreBootstrapReport;\n detection: InstallDetection;\n preV2: PreV2Detection;\n preV2Choice: PreV2Choice | null;\n executedCommand: string | null;\n printedCommands: string[];\n /** Human-readable report lines, also written to the output seam. */\n lines: string[];\n}\n\nexport async function runToolUpdateCommand(\n options: ToolUpdateOptions,\n): Promise<ToolUpdateResult> {\n const output = options.output ?? defaultSelfCommandOutput;\n const exec = options.exec ?? defaultExecCommand;\n const classify = options.classify ?? classifyCompatibilityState;\n const storeRoot = resolveStoreRoot({\n storeRoot: options.storeRoot,\n env: options.env,\n homeDir: options.homeDir,\n });\n const targetDir = path.resolve(options.targetDir ?? process.cwd());\n\n const lines: string[] = [];\n const emit = (line: string) => {\n lines.push(line);\n output.write(line);\n };\n\n // Global-store schema migration applies in all cases (PRD 38 R-DB-2).\n prepareToolOperationStore(targetDir, storeRoot);\n const bootstrap = bootstrapGlobalStore({\n storeRoot,\n env: options.env,\n homeDir: options.homeDir,\n packageMeta: safeReadPackageMeta(),\n });\n emit(\n `Global store at ${bootstrap.storeRoot}: database ${bootstrap.databaseStatus}` +\n (bootstrap.schemaVersion === null\n ? \"\"\n : ` (schema version ${bootstrap.schemaVersion})`),\n );\n for (const warning of bootstrap.warnings) {\n emit(`Warning: ${warning}`);\n }\n\n const detection = detectInstallSource({\n argv1: options.argv1,\n execPath: options.execPath,\n realpath: options.realpath,\n });\n\n const result: ToolUpdateResult = {\n operationId: null,\n status: \"nothing-persistent\",\n storeRoot,\n bootstrap,\n detection,\n preV2: { preV2: false, fingerprints: [] },\n preV2Choice: null,\n executedCommand: null,\n printedCommands: [],\n lines,\n };\n\n // Pre-v2 detection against the target directory (R-MIG-2), surfaced\n // before any delegation.\n const classification = await classify({ targetDir, homeDir: options.homeDir });\n result.preV2 = detectPreV2Install({ targetDir, classification });\n if (result.preV2.preV2) {\n result.preV2Choice = await promptPreV2Choice({\n detection: result.preV2,\n interactive: Boolean(stdin.isTTY && stdout.isTTY),\n command: \"update\",\n output,\n });\n if (result.preV2Choice === \"cancel\") {\n result.status = \"cancelled-pre-v2\";\n emit(\n `Update cancelled: the pre-v2 install at ${targetDir} was left untouched. The global-store migration above is additive and does not affect the project.`,\n );\n return result;\n }\n\n emit(`Backing up the pre-v2 install at ${targetDir} before updating.`);\n const runBackup = options.runBackup ?? defaultRunBackup;\n await runBackup(targetDir);\n }\n\n if (detection.kind === \"persistent\") {\n const command = formatManagerCommand(detection.manager.updateCommand);\n emit(`Delegating to ${detection.manager.id}: ${command}`);\n const recorded = await runRecordedToolOperation(targetDir, storeRoot, \"tool.update\", {\n manager: detection.manager.id, command, binaryPath: detection.binaryPath,\n }, () => exec(detection.manager.updateCommand.command, detection.manager.updateCommand.args));\n result.operationId = recorded.operationId;\n const { exitCode } = recorded.result;\n emit(`Tool operation recorded in the Store: ${recorded.operationId}`);\n result.executedCommand = command;\n if (exitCode === 0) {\n result.status = \"delegated\";\n emit(`Update delegated to ${detection.manager.id} completed.`);\n } else {\n result.status = \"delegate-failed\";\n emit(\n `The ${detection.manager.id} update command failed (exit code ${exitCode ?? \"unknown\"}). Run it manually: ${command}`,\n );\n }\n return result;\n }\n\n if (detection.kind === \"remote\") {\n result.status = \"nothing-persistent\";\n emit(\n \"Nothing persistent to update: this invocation runs via a package runner (remote execution), and the runner fetches the requested version on each run.\",\n );\n return result;\n }\n\n // Ambiguous ownership: print the exact command(s) and the affected store\n // path instead of executing (R-SELF-3).\n const candidates =\n detection.candidates.length > 0 ? detection.candidates : [...INSTALL_MANAGER_MATRIX];\n result.printedCommands = candidates.map((candidate) =>\n formatManagerCommand(candidate.updateCommand),\n );\n result.status = \"manual-update-required\";\n emit(\n `Could not determine which install manager owns the make-docs binary (${detection.reason})`,\n );\n emit(\n \"make-docs will not guess and run a global change. If you installed the binary yourself, run the matching command:\",\n );\n for (const command of result.printedCommands) {\n emit(` ${command}`);\n }\n emit(`Affected store path: ${storeRoot}`);\n return result;\n}\n\nasync function defaultRunBackup(targetDir: string): Promise<void> {\n const { runBackupCommand } = await import(\"../backup\");\n await runBackupCommand({ targetDir, permissions: \"allow-all\" });\n}\n\nfunction safeReadPackageMeta(): { name: string; version: string } | undefined {\n try {\n return readPackageMeta();\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,oBAAoB;AAsDtB,IAAM,qBAA6B,MAAM;AAC9C,MAAI;AACF,WAAO,gBAAgB,EAAE;AAAA,EAC3B,QAAQ;AACN,WAAO;AAAA,EACT;AACF,GAAG;AAkBI,IAAM,yBAAwD;AAAA,EACnE;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,SAAS,CAAC,uBAAuB;AAAA,IACjC,kBAAkB,EAAE,SAAS,OAAO,MAAM,CAAC,aAAa,MAAM,iBAAiB,EAAE;AAAA,IACjF,eAAe;AAAA,MACb,SAAS;AAAA,MACT,MAAM,CAAC,WAAW,MAAM,GAAG,iBAAiB,SAAS;AAAA,IACvD;AAAA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;AAAA,EACT;AAEA,MAAI,UAAU,SAAS,UAAU;AAC/B,WAAO,SAAS;AAChB;AAAA,MACE;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAIA,QAAM,aACJ,UAAU,WAAW,SAAS,IAAI,UAAU,aAAa,CAAC,GAAG,sBAAsB;AACrF,SAAO,kBAAkB,WAAW;AAAA,IAAI,CAAC,cACvC,qBAAqB,UAAU,aAAa;AAAA,EAC9C;AACA,SAAO,SAAS;AAChB;AAAA,IACE,wEAAwE,UAAU,MAAM;AAAA,EAC1F;AACA;AAAA,IACE;AAAA,EACF;AACA,aAAW,WAAW,OAAO,iBAAiB;AAC5C,SAAK,KAAK,OAAO,EAAE;AAAA,EACrB;AACA,OAAK,wBAAwB,SAAS,EAAE;AACxC,SAAO;AACT;AAEA,eAAe,iBAAiB,WAAkC;AAChE,QAAM,EAAE,iBAAiB,IAAI,MAAM,OAAO,sBAAW;AACrD,QAAM,iBAAiB,EAAE,WAAW,aAAa,YAAY,CAAC;AAChE;AAEA,SAAS,sBAAqE;AAC5E,MAAI;AACF,WAAO,gBAAgB;AAAA,EACzB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["existsSync","existsSync","path","stdin","stdout","path","stdin","stdout"]}
@@ -0,0 +1,512 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ classifyCompatibilityState
4
+ } from "./chunk-BENO4IH5.js";
5
+ import {
6
+ ResourceOperationError,
7
+ createExecutionContext,
8
+ external_exports,
9
+ getOperation,
10
+ invokeOperation,
11
+ listOperationAccessFacts,
12
+ listOperations,
13
+ serializeOperationError
14
+ } from "./chunk-LVQSJF63.js";
15
+ import "./chunk-G5EF63GG.js";
16
+ import "./chunk-3BAJQXGH.js";
17
+ import {
18
+ findReviewableManagedFileConflicts,
19
+ getConfigRenderingLabels,
20
+ loadMakeDocsConfigOrThrow,
21
+ planInstall
22
+ } from "./chunk-64CTKJO7.js";
23
+ import "./chunk-HJYIQTMD.js";
24
+ import {
25
+ HARNESS_CALLER_IDENTITY_ENV
26
+ } from "./chunk-LRVV7UDD.js";
27
+ import {
28
+ cloneSelections,
29
+ defaultSelections,
30
+ loadManifest,
31
+ readPackageMeta
32
+ } from "./chunk-MXBHCHSM.js";
33
+ import "./chunk-D4HDZEJT.js";
34
+
35
+ // src/mcp/server.ts
36
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
37
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
38
+ import {
39
+ ListResourcesRequestSchema,
40
+ ReadResourceRequestSchema
41
+ } from "@modelcontextprotocol/sdk/types.js";
42
+
43
+ // src/mcp/resources.ts
44
+ import path from "path";
45
+ import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
46
+ function throwNativeResourceError(error) {
47
+ if (error instanceof ResourceOperationError) {
48
+ throw new McpError(ErrorCode.InvalidParams, error.message, {
49
+ makeDocs: {
50
+ code: error.code,
51
+ recovery: error.recovery,
52
+ ...error.uri ? { uri: error.uri } : {},
53
+ ...error.path ? { path: error.path } : {}
54
+ }
55
+ });
56
+ }
57
+ throw error;
58
+ }
59
+ async function listNativeMcpResources(targetRoot = process.cwd()) {
60
+ const invocation = await invokeOperation(
61
+ "resource.list",
62
+ { targetRoot: path.resolve(targetRoot) },
63
+ createExecutionContext({
64
+ surface: "mcp",
65
+ route: "mcp",
66
+ callerIdentityRaw: process.env[HARNESS_CALLER_IDENTITY_ENV],
67
+ cwd: targetRoot
68
+ })
69
+ ).catch(throwNativeResourceError);
70
+ const value = invocation.value;
71
+ return {
72
+ resources: value.resources.map((entry) => {
73
+ if (!entry.result.ok) {
74
+ return {
75
+ uri: entry.uri,
76
+ name: entry.uri,
77
+ description: "Unavailable Make Docs system resource.",
78
+ _meta: { makeDocs: { error: entry.result.error } }
79
+ };
80
+ }
81
+ return {
82
+ uri: entry.uri,
83
+ name: entry.uri,
84
+ description: "Make Docs system resource.",
85
+ mimeType: String(entry.result.value.mediaType),
86
+ size: Number(entry.result.value.byteLength),
87
+ _meta: { makeDocs: entry.result.value }
88
+ };
89
+ })
90
+ };
91
+ }
92
+ async function readNativeMcpResource(uri, targetRoot = process.cwd()) {
93
+ const invocation = await invokeOperation(
94
+ "resource.read",
95
+ { uri, targetRoot: path.resolve(targetRoot) },
96
+ createExecutionContext({
97
+ surface: "mcp",
98
+ route: "mcp",
99
+ callerIdentityRaw: process.env[HARNESS_CALLER_IDENTITY_ENV],
100
+ cwd: targetRoot
101
+ })
102
+ ).catch(throwNativeResourceError);
103
+ const value = invocation.value;
104
+ const { content, ...metadata } = value.resource;
105
+ return {
106
+ contents: [
107
+ {
108
+ uri: value.resource.identity.uri,
109
+ mimeType: value.resource.mediaType,
110
+ blob: content.data,
111
+ _meta: { makeDocs: metadata }
112
+ }
113
+ ]
114
+ };
115
+ }
116
+
117
+ // src/mcp/tools.ts
118
+ import path4 from "path";
119
+
120
+ // src/operations/closeout/index.ts
121
+ import {
122
+ existsSync,
123
+ mkdirSync,
124
+ readdirSync,
125
+ statSync,
126
+ writeFileSync
127
+ } from "fs";
128
+ import path2 from "path";
129
+ import { spawnSync } from "child_process";
130
+
131
+ // src/operations/lifecycle/index.ts
132
+ import { existsSync as existsSync2, readdirSync as readdirSync2, rmdirSync, rmSync } from "fs";
133
+ import path3 from "path";
134
+
135
+ // src/operations/index.ts
136
+ function listOperationDomains() {
137
+ const domains = /* @__PURE__ */ new Map();
138
+ for (const operation of listOperations()) {
139
+ let domain = domains.get(operation.domain);
140
+ if (!domain) {
141
+ domain = { name: operation.domain, commands: [] };
142
+ domains.set(operation.domain, domain);
143
+ }
144
+ domain.commands.push({
145
+ id: operation.id,
146
+ summary: operation.summary,
147
+ mutates: operation.mutates === "write",
148
+ status: operation.status
149
+ });
150
+ }
151
+ return [...domains.values()];
152
+ }
153
+
154
+ // src/mcp/tools.ts
155
+ var targetDirSchema = external_exports.string().optional().describe("Project root to inspect. Defaults to the current working directory.");
156
+ var systemAssetMaterializationModeSchema = external_exports.enum([
157
+ "full-snapshot",
158
+ "provider-backed",
159
+ "hybrid-pinned-cache"
160
+ ]);
161
+ var HAND_DEFINED_MCP_TOOLS = [
162
+ {
163
+ name: "make_docs_operation_domains",
164
+ title: "List Make Docs Operation Domains",
165
+ description: "List deterministic operation domains shared by CLI and MCP tools.",
166
+ inputSchema: {}
167
+ },
168
+ {
169
+ name: "make_docs_installed_state",
170
+ title: "Inspect Make Docs Installed State",
171
+ description: "Inspect manifest, config, compatibility, and package state for a make-docs project.",
172
+ inputSchema: { targetDir: targetDirSchema }
173
+ },
174
+ {
175
+ name: "make_docs_manifest_read",
176
+ title: "Read Make Docs Manifest",
177
+ description: "Read .make-docs/manifest.json without mutating the project.",
178
+ inputSchema: { targetDir: targetDirSchema }
179
+ },
180
+ {
181
+ name: "make_docs_config_read",
182
+ title: "Read Make Docs Config",
183
+ description: "Read .make-docs/config.yaml with default overlay diagnostics.",
184
+ inputSchema: { targetDir: targetDirSchema }
185
+ },
186
+ {
187
+ name: "make_docs_compatibility_classify",
188
+ title: "Classify Make Docs Compatibility State",
189
+ description: "Run the same compatibility classifier used by the CLI.",
190
+ inputSchema: { targetDir: targetDirSchema }
191
+ },
192
+ {
193
+ name: "make_docs_install_plan",
194
+ title: "Plan Make Docs Install Or Sync",
195
+ description: "Create a dry-run install/sync plan using CLI planner semantics and without file writes.",
196
+ inputSchema: {
197
+ targetDir: targetDirSchema,
198
+ selections: external_exports.unknown().optional().describe("Optional InstallSelections override."),
199
+ systemAssetMaterializationMode: systemAssetMaterializationModeSchema.optional()
200
+ }
201
+ }
202
+ ];
203
+ function deriveMcpToolName(operationId) {
204
+ return `make_docs_${operationId.replace(/[.-]/g, "_")}`;
205
+ }
206
+ var allowWriteSchema = external_exports.boolean().optional().describe(
207
+ "Set true to permit this mutating operation to write. Enforced uniformly by the operation core."
208
+ );
209
+ var dryRunSchema = external_exports.boolean().optional().describe("Set true to plan rather than write; rides the execution context, not the input.");
210
+ var approvalsSchema = external_exports.array(external_exports.string()).optional().describe(
211
+ "Named approval tokens granted to the operation (e.g. reviewed-overwrite); rides the execution context, not the input."
212
+ );
213
+ function operationInputShape(schema) {
214
+ if (schema instanceof external_exports.ZodObject) {
215
+ return { ...schema.shape };
216
+ }
217
+ return {};
218
+ }
219
+ function deriveToolInputSchema(definition) {
220
+ return {
221
+ ...operationInputShape(definition.inputSchema),
222
+ ...definition.mutates === "write" ? { allowWrite: allowWriteSchema } : {},
223
+ dryRun: dryRunSchema,
224
+ approvals: approvalsSchema
225
+ };
226
+ }
227
+ function deriveToolDescription(definition) {
228
+ const parts = [
229
+ definition.summary,
230
+ `Access: Store ${definition.access.store}; project ${definition.access.project}; host configuration ${definition.access.hostConfig}.`
231
+ ];
232
+ if (definition.status === "pending") {
233
+ parts.push(
234
+ `Pending: reserved registry identifier whose semantics land with ${definition.pendingLineage}; invocation is refused until then.`
235
+ );
236
+ }
237
+ if (definition.mutates === "write") {
238
+ parts.push("Mutating operation: requires allowWrite=true, enforced by the operation core.");
239
+ }
240
+ return parts.join(" ");
241
+ }
242
+ var DERIVED_MCP_OPERATION_TOOLS = listOperations().map(
243
+ (operation) => {
244
+ const definition = getOperation(operation.id);
245
+ const accessFact = listOperationAccessFacts().find((fact) => fact.operation === operation.id);
246
+ return {
247
+ name: deriveMcpToolName(operation.id),
248
+ operation: operation.id,
249
+ title: `Make Docs Operation ${operation.id}`,
250
+ description: deriveToolDescription(definition),
251
+ inputSchema: deriveToolInputSchema(definition),
252
+ access: { ...accessFact.access },
253
+ mcpReady: accessFact.mcpReady
254
+ };
255
+ }
256
+ );
257
+ var DERIVED_TOOLS_BY_NAME = new Map(
258
+ DERIVED_MCP_OPERATION_TOOLS.map((tool) => [tool.name, tool])
259
+ );
260
+ var MAKE_DOCS_MCP_TOOLS = [
261
+ ...HAND_DEFINED_MCP_TOOLS,
262
+ ...DERIVED_MCP_OPERATION_TOOLS
263
+ ];
264
+ function listMakeDocsMcpTools(targetRoot = process.cwd()) {
265
+ void targetRoot;
266
+ return MAKE_DOCS_MCP_TOOLS.map((tool) => {
267
+ if (!tool.operation || !tool.access) return tool;
268
+ return { ...tool, access: { ...tool.access } };
269
+ });
270
+ }
271
+ async function callMakeDocsMcpTool(name, args = {}) {
272
+ switch (name) {
273
+ case "make_docs_operation_domains":
274
+ return mcpPayload(name, listOperationDomains());
275
+ case "make_docs_installed_state":
276
+ return mcpPayload(name, await readInstalledState(resolveTargetDir(args)));
277
+ case "make_docs_manifest_read":
278
+ return mcpPayload(name, readManifest(resolveTargetDir(args)));
279
+ case "make_docs_config_read":
280
+ return mcpPayload(name, readConfig(resolveTargetDir(args)));
281
+ case "make_docs_compatibility_classify":
282
+ return mcpPayload(
283
+ name,
284
+ await classifyCompatibilityState({ targetDir: resolveTargetDir(args) })
285
+ );
286
+ case "make_docs_install_plan":
287
+ return mcpPayload(name, await buildInstallPlan(resolveTargetDir(args), args));
288
+ }
289
+ const derived = DERIVED_TOOLS_BY_NAME.get(name);
290
+ if (derived === void 0) {
291
+ throw new Error(`Unknown make-docs MCP tool: ${name}`);
292
+ }
293
+ const targetRoot = resolveOperationTargetDir(args);
294
+ const effective = listMakeDocsMcpTools(targetRoot).find((tool) => tool.name === name);
295
+ return mcpPayload(name, await invokeDerivedOperationTool(derived.operation, args), {
296
+ operation: derived.operation,
297
+ access: { ...derived.access },
298
+ mcpReady: effective?.mcpReady === true
299
+ });
300
+ }
301
+ async function invokeDerivedOperationTool(id, args) {
302
+ const { allowWrite, dryRun, approvals, ...input } = args;
303
+ const invocation = await invokeOperation(
304
+ id,
305
+ input,
306
+ createExecutionContext({
307
+ surface: "mcp",
308
+ route: "mcp",
309
+ callerIdentityRaw: process.env[HARNESS_CALLER_IDENTITY_ENV],
310
+ writesAllowed: allowWrite === true,
311
+ dryRun: dryRun === true,
312
+ approvals: Array.isArray(approvals) ? approvals.map(String) : []
313
+ })
314
+ );
315
+ return invocation.value;
316
+ }
317
+ async function readInstalledState(targetDir) {
318
+ return {
319
+ targetDir,
320
+ package: readPackageMeta(),
321
+ manifest: readManifest(targetDir),
322
+ config: readConfig(targetDir),
323
+ compatibility: await classifyCompatibilityState({ targetDir }),
324
+ operationDomains: listOperationDomains()
325
+ };
326
+ }
327
+ function readManifest(targetDir) {
328
+ const manifest = loadManifest(targetDir);
329
+ return {
330
+ targetDir,
331
+ present: manifest !== null,
332
+ manifest
333
+ };
334
+ }
335
+ function readConfig(targetDir) {
336
+ const loaded = loadMakeDocsConfigOrThrow(targetDir);
337
+ return {
338
+ targetDir,
339
+ present: loaded.present,
340
+ valid: loaded.valid,
341
+ configPath: loaded.configPath,
342
+ diagnostics: loaded.diagnostics,
343
+ config: loaded.config,
344
+ renderingLabels: getConfigRenderingLabels(loaded.config)
345
+ };
346
+ }
347
+ async function buildInstallPlan(targetDir, args) {
348
+ const existingManifest = loadManifest(targetDir);
349
+ const selections = resolveSelections(existingManifest?.selections, args.selections);
350
+ const plan = await planInstall({
351
+ targetDir,
352
+ selections,
353
+ existingManifest,
354
+ packageMeta: readPackageMeta(),
355
+ systemAssetMaterializationMode: systemAssetMaterializationModeSchema.optional().parse(
356
+ args.systemAssetMaterializationMode
357
+ )
358
+ });
359
+ const conflicts = findReviewableManagedFileConflicts(plan);
360
+ return summarizeInstallPlan(plan, conflicts);
361
+ }
362
+ function summarizeInstallPlan(plan, conflicts) {
363
+ const counts = {
364
+ create: 0,
365
+ generate: 0,
366
+ noop: 0,
367
+ removeManaged: 0,
368
+ skipConflict: 0,
369
+ update: 0,
370
+ updateConflict: 0
371
+ };
372
+ for (const action of plan.actions) {
373
+ switch (action.type) {
374
+ case "create":
375
+ counts.create += 1;
376
+ break;
377
+ case "generate":
378
+ counts.generate += 1;
379
+ break;
380
+ case "noop":
381
+ counts.noop += 1;
382
+ break;
383
+ case "remove-managed":
384
+ counts.removeManaged += 1;
385
+ break;
386
+ case "skip-conflict":
387
+ counts.skipConflict += 1;
388
+ break;
389
+ case "update":
390
+ case "strip-managed-block":
391
+ counts.update += 1;
392
+ break;
393
+ case "update-conflict":
394
+ counts.updateConflict += 1;
395
+ break;
396
+ }
397
+ }
398
+ return {
399
+ packageName: plan.packageName,
400
+ packageVersion: plan.packageVersion,
401
+ profile: plan.profile,
402
+ systemAssetMaterialization: plan.systemAssetMaterialization,
403
+ actionCounts: counts,
404
+ actions: plan.actions.map(summarizeAction),
405
+ reviewableManagedFileConflicts: conflicts,
406
+ writesFiles: false
407
+ };
408
+ }
409
+ function summarizeAction(action) {
410
+ const { content: _content, ...summary } = action;
411
+ return summary;
412
+ }
413
+ function resolveSelections(manifestSelections, override) {
414
+ if (override !== void 0) {
415
+ return override;
416
+ }
417
+ if (manifestSelections) {
418
+ return cloneSelections(manifestSelections);
419
+ }
420
+ return defaultSelections();
421
+ }
422
+ function mcpPayload(tool, result, details = {}) {
423
+ return {
424
+ tool,
425
+ source: "mcp",
426
+ ...details,
427
+ result
428
+ };
429
+ }
430
+ function resolveOperationTargetDir(args) {
431
+ return path4.resolve(
432
+ optionalString(args, "targetRoot") ?? optionalString(args, "targetDir") ?? process.cwd()
433
+ );
434
+ }
435
+ function resolveTargetDir(args) {
436
+ return path4.resolve(optionalString(args, "targetDir") ?? process.cwd());
437
+ }
438
+ function optionalString(args, key) {
439
+ const value = args[key];
440
+ return typeof value === "string" && value.length > 0 ? value : void 0;
441
+ }
442
+
443
+ // src/mcp/server.ts
444
+ function createMakeDocsMcpServer() {
445
+ const packageMeta = readPackageMeta();
446
+ const server = new McpServer({
447
+ name: packageMeta.name,
448
+ version: packageMeta.version
449
+ });
450
+ for (const tool of listMakeDocsMcpTools().filter((candidate) => candidate.mcpReady !== false)) {
451
+ server.registerTool(
452
+ tool.name,
453
+ {
454
+ title: tool.title,
455
+ description: tool.description,
456
+ inputSchema: tool.inputSchema
457
+ },
458
+ async (args) => {
459
+ try {
460
+ return formatMcpToolResult(await callMakeDocsMcpTool(tool.name, args));
461
+ } catch (error) {
462
+ return formatMcpToolError(error);
463
+ }
464
+ }
465
+ );
466
+ }
467
+ server.server.registerCapabilities({ resources: {} });
468
+ server.server.setRequestHandler(
469
+ ListResourcesRequestSchema,
470
+ async () => listNativeMcpResources()
471
+ );
472
+ server.server.setRequestHandler(
473
+ ReadResourceRequestSchema,
474
+ async (request) => readNativeMcpResource(request.params.uri)
475
+ );
476
+ return server;
477
+ }
478
+ async function runMcpServer() {
479
+ const server = createMakeDocsMcpServer();
480
+ const transport = new StdioServerTransport();
481
+ await server.connect(transport);
482
+ }
483
+ function formatMcpToolResult(value) {
484
+ const structuredContent = value !== null && typeof value === "object" && !Array.isArray(value) ? value : { value };
485
+ return {
486
+ content: [
487
+ {
488
+ type: "text",
489
+ text: JSON.stringify(structuredContent, null, 2)
490
+ }
491
+ ],
492
+ structuredContent
493
+ };
494
+ }
495
+ function formatMcpToolError(error) {
496
+ const structuredContent = serializeOperationError(error);
497
+ return {
498
+ isError: true,
499
+ content: [
500
+ {
501
+ type: "text",
502
+ text: JSON.stringify(structuredContent, null, 2)
503
+ }
504
+ ],
505
+ structuredContent
506
+ };
507
+ }
508
+ export {
509
+ createMakeDocsMcpServer,
510
+ runMcpServer
511
+ };
512
+ //# sourceMappingURL=server-O2ZELIMX.js.map