@brucewaynedecoy/make-docs 2.0.3 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +1 -1
  2. package/dist/{backup-GCM64IPN.js → backup-2OT4A6LR.js} +5 -5
  3. package/dist/chunk-3EXHM5L2.js +1225 -0
  4. package/dist/chunk-3EXHM5L2.js.map +1 -0
  5. package/dist/{chunk-2HNJCJJE.js → chunk-46MGH32G.js} +6 -4
  6. package/dist/chunk-46MGH32G.js.map +1 -0
  7. package/dist/{chunk-O2UZ35PV.js → chunk-CCYP5NU2.js} +20 -20
  8. package/dist/{chunk-O2UZ35PV.js.map → chunk-CCYP5NU2.js.map} +1 -1
  9. package/dist/{chunk-C2IBRVUA.js → chunk-CLSOY7NV.js} +153 -6
  10. package/dist/chunk-CLSOY7NV.js.map +1 -0
  11. package/dist/{chunk-GPVKIBFC.js → chunk-CMNKQM7L.js} +3 -3
  12. package/dist/{chunk-U25GFKNZ.js → chunk-HXWD2EUD.js} +20 -15
  13. package/dist/chunk-HXWD2EUD.js.map +1 -0
  14. package/dist/{chunk-DNDM7DUQ.js → chunk-I4FADOUK.js} +3 -3
  15. package/dist/{chunk-DNDM7DUQ.js.map → chunk-I4FADOUK.js.map} +1 -1
  16. package/dist/{chunk-DFQJENNL.js → chunk-ISSMVKIA.js} +224 -20
  17. package/dist/chunk-ISSMVKIA.js.map +1 -0
  18. package/dist/{chunk-IHMZ2OCS.js → chunk-UNR4CYVX.js} +116 -37
  19. package/dist/chunk-UNR4CYVX.js.map +1 -0
  20. package/dist/{chunk-57GN6ALR.js → chunk-VMKG3H4B.js} +2 -2
  21. package/dist/{chunk-4LLSMDWJ.js → chunk-XDSWX4Y4.js} +9085 -2912
  22. package/dist/chunk-XDSWX4Y4.js.map +1 -0
  23. package/dist/index.js +308 -176
  24. package/dist/index.js.map +1 -1
  25. package/dist/registry-PC5GKAKM.js +50 -0
  26. package/dist/registry-PC5GKAKM.js.map +1 -0
  27. package/dist/{self-UHPM4A2U.js → self-WYVXO23B.js} +18 -18
  28. package/dist/{self-UHPM4A2U.js.map → self-WYVXO23B.js.map} +1 -1
  29. package/dist/server-BQOG6FTA.js +1113 -0
  30. package/dist/server-BQOG6FTA.js.map +1 -0
  31. package/dist/{setup-system-JUHGDZJW.js → setup-system-KN7FTTLT.js} +267 -44
  32. package/dist/setup-system-KN7FTTLT.js.map +1 -0
  33. package/dist/{skills-command-W3SE3OFP.js → skills-command-KEW7MOEW.js} +39 -29
  34. package/dist/skills-command-KEW7MOEW.js.map +1 -0
  35. package/dist/{uninstall-BGMJ6KCI.js → uninstall-45XF4CHD.js} +10 -10
  36. package/dist/virtual_make-docs-first-party-skills-ECJESFL2.js +11 -0
  37. package/dist/virtual_make-docs-first-party-skills-ECJESFL2.js.map +1 -0
  38. package/package.json +8 -8
  39. package/skill-registry.json +24 -8
  40. package/skill-registry.schema.json +2 -1
  41. package/template/.make-docs/system/contracts/output-contract.md +3 -1
  42. package/template/.make-docs/system/contracts/system-resource-contract.md +16 -0
  43. package/template/.make-docs/system/references/prd-change-management.md +14 -2
  44. package/template/.make-docs/system-resources.catalog.json +415 -0
  45. package/template/.make-docs/system-resources.schema.json +25 -0
  46. package/dist/chunk-2HNJCJJE.js.map +0 -1
  47. package/dist/chunk-4LLSMDWJ.js.map +0 -1
  48. package/dist/chunk-C2IBRVUA.js.map +0 -1
  49. package/dist/chunk-DFQJENNL.js.map +0 -1
  50. package/dist/chunk-IHMZ2OCS.js.map +0 -1
  51. package/dist/chunk-U25GFKNZ.js.map +0 -1
  52. package/dist/chunk-Z5K4FHYP.js +0 -922
  53. package/dist/chunk-Z5K4FHYP.js.map +0 -1
  54. package/dist/server-N7XAAV3X.js +0 -512
  55. package/dist/server-N7XAAV3X.js.map +0 -1
  56. package/dist/setup-system-JUHGDZJW.js.map +0 -1
  57. package/dist/skills-command-W3SE3OFP.js.map +0 -1
  58. package/dist/virtual_make-docs-first-party-skills-VXSUUHTL.js +0 -11
  59. package/dist/virtual_make-docs-first-party-skills-VXSUUHTL.js.map +0 -1
  60. /package/dist/{backup-GCM64IPN.js.map → backup-2OT4A6LR.js.map} +0 -0
  61. /package/dist/{chunk-GPVKIBFC.js.map → chunk-CMNKQM7L.js.map} +0 -0
  62. /package/dist/{chunk-57GN6ALR.js.map → chunk-VMKG3H4B.js.map} +0 -0
  63. /package/dist/{uninstall-BGMJ6KCI.js.map → uninstall-45XF4CHD.js.map} +0 -0
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ADMITTED_OPERATION_IDS,
4
+ OPERATION_ID_PATTERN,
5
+ assertOperationMcpMetadata,
6
+ assertOperationStoreAdmission,
7
+ getOperation,
8
+ hasOperation,
9
+ invokeOperation,
10
+ isOperationMcpReady,
11
+ listAdmittedOperations,
12
+ listCommandRuleCandidates,
13
+ listEffectiveHarnessCommandRules,
14
+ listHarnessCommandRules,
15
+ listOperationAccessFacts,
16
+ listOperations,
17
+ operationCliCommand,
18
+ operationCliPath,
19
+ operationCliProjection,
20
+ operationDomain,
21
+ validateRegistryHarnessCommandRules
22
+ } from "./chunk-XDSWX4Y4.js";
23
+ import "./chunk-CLSOY7NV.js";
24
+ import "./chunk-VMKG3H4B.js";
25
+ import "./chunk-UNR4CYVX.js";
26
+ import "./chunk-ISSMVKIA.js";
27
+ import "./chunk-HXWD2EUD.js";
28
+ import "./chunk-D4HDZEJT.js";
29
+ export {
30
+ ADMITTED_OPERATION_IDS,
31
+ OPERATION_ID_PATTERN,
32
+ assertOperationMcpMetadata,
33
+ assertOperationStoreAdmission,
34
+ getOperation,
35
+ hasOperation,
36
+ invokeOperation,
37
+ isOperationMcpReady,
38
+ listAdmittedOperations,
39
+ listCommandRuleCandidates,
40
+ listEffectiveHarnessCommandRules,
41
+ listHarnessCommandRules,
42
+ listOperationAccessFacts,
43
+ listOperations,
44
+ operationCliCommand,
45
+ operationCliPath,
46
+ operationCliProjection,
47
+ operationDomain,
48
+ validateRegistryHarnessCommandRules
49
+ };
50
+ //# sourceMappingURL=registry-PC5GKAKM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  classifyCompatibilityState
4
- } from "./chunk-GPVKIBFC.js";
5
- import "./chunk-2HNJCJJE.js";
4
+ } from "./chunk-CMNKQM7L.js";
5
+ import "./chunk-46MGH32G.js";
6
+ import {
7
+ confirm,
8
+ isCancel,
9
+ note,
10
+ select
11
+ } from "./chunk-3EXHM5L2.js";
6
12
  import {
7
13
  bootstrapGlobalStore,
8
14
  removeGlobalStore
9
- } from "./chunk-IHMZ2OCS.js";
10
- import {
11
- Ct,
12
- Jt,
13
- Rt,
14
- Vt
15
- } from "./chunk-Z5K4FHYP.js";
16
- import "./chunk-DFQJENNL.js";
15
+ } from "./chunk-UNR4CYVX.js";
16
+ import "./chunk-ISSMVKIA.js";
17
17
  import {
18
18
  GLOBAL_ASSET_LOCK_FILE,
19
19
  STORE_LEASE_RECOVERY_FILE,
@@ -29,7 +29,7 @@ import {
29
29
  tryCreateExclusiveStoreLease,
30
30
  waitForStoreAccessToDrain,
31
31
  withInstallationDatabase
32
- } from "./chunk-U25GFKNZ.js";
32
+ } from "./chunk-HXWD2EUD.js";
33
33
  import "./chunk-D4HDZEJT.js";
34
34
 
35
35
  // src/self/install-manager.ts
@@ -218,8 +218,8 @@ async function promptPreV2Choice(input) {
218
218
  );
219
219
  return "cancel";
220
220
  }
221
- Vt(warningLines.join("\n"), `make-docs ${input.command}: pre-v2 install detected`);
222
- const choice = await Jt({
221
+ note(warningLines.join("\n"), `make-docs ${input.command}: pre-v2 install detected`);
222
+ const choice = await select({
223
223
  message: "How should make-docs proceed?",
224
224
  withGuide: true,
225
225
  initialValue: "backup-and-install",
@@ -234,7 +234,7 @@ async function promptPreV2Choice(input) {
234
234
  }
235
235
  ]
236
236
  });
237
- if (Ct(choice)) {
237
+ if (isCancel(choice)) {
238
238
  return "cancel";
239
239
  }
240
240
  return choice;
@@ -396,14 +396,14 @@ async function runToolUninstallCommand(options) {
396
396
  );
397
397
  return result;
398
398
  }
399
- const proceed = await Rt({
399
+ const proceed = await confirm({
400
400
  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?",
401
401
  initialValue: false,
402
402
  active: "Yes",
403
403
  inactive: "No",
404
404
  withGuide: true
405
405
  });
406
- if (Ct(proceed) || !proceed) {
406
+ if (isCancel(proceed) || !proceed) {
407
407
  result.status = "cancelled";
408
408
  emit("Uninstall cancelled. Nothing was removed.");
409
409
  return result;
@@ -626,7 +626,7 @@ async function runToolUpdateCommand(options) {
626
626
  return result;
627
627
  }
628
628
  async function defaultRunBackup(targetDir) {
629
- const { runBackupCommand } = await import("./backup-GCM64IPN.js");
629
+ const { runBackupCommand } = await import("./backup-2OT4A6LR.js");
630
630
  await runBackupCommand({ targetDir, permissions: "allow-all" });
631
631
  }
632
632
  function safeReadPackageMeta() {
@@ -650,4 +650,4 @@ export {
650
650
  runToolUninstallCommand,
651
651
  runToolUpdateCommand
652
652
  };
653
- //# sourceMappingURL=self-UHPM4A2U.js.map
653
+ //# sourceMappingURL=self-WYVXO23B.js.map
@@ -1 +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,EACF;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,SAAS,CAAC,oBAAoB,4BAA4B,mBAAmB;AAAA,IAC7E,kBAAkB,EAAE,SAAS,QAAQ,MAAM,CAAC,UAAU,MAAM,iBAAiB,EAAE;AAAA,IAC/E,eAAe;AAAA,MACb,SAAS;AAAA,MACT,MAAM,CAAC,OAAO,MAAM,GAAG,iBAAiB,SAAS;AAAA,IACnD;AAAA,EACF;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,SAAS,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A,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"]}
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":";;;;;;;;;;;;;;;;;;;;;;;;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