github-router 0.3.379 → 0.3.381

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 (165) hide show
  1. package/README.md +62 -0
  2. package/dist/ado-tools-CsfbnY8x.js +1 -0
  3. package/dist/{aic-ledger-CeSXqTEE.js → aic-ledger-6GKI28nY.js} +3 -3
  4. package/dist/{aic-ledger-CeSXqTEE.js.map → aic-ledger-6GKI28nY.js.map} +1 -1
  5. package/dist/{aic-statusline-settings-BKveu679.js → aic-statusline-settings-wLL1l_Z6.js} +2 -2
  6. package/dist/{aic-statusline-settings-BKveu679.js.map → aic-statusline-settings-wLL1l_Z6.js.map} +1 -1
  7. package/dist/atomic-file-Dif1kLKM.js +198 -0
  8. package/dist/atomic-file-Dif1kLKM.js.map +1 -0
  9. package/dist/{attribution-settings-BWYL2b8N.js → attribution-settings-BEwSkdhK.js} +10 -10
  10. package/dist/{attribution-settings-BWYL2b8N.js.map → attribution-settings-BEwSkdhK.js.map} +1 -1
  11. package/dist/{auth-BZHpTtfF.js → auth-5TKcQbbH.js} +3 -3
  12. package/dist/{auth-BZHpTtfF.js.map → auth-5TKcQbbH.js.map} +1 -1
  13. package/dist/bin.js +1479 -0
  14. package/dist/bin.js.map +1 -0
  15. package/dist/browser-ext/manifest.json +1 -1
  16. package/dist/{check-usage-BlIWDuV2.js → check-usage-DM39fdel.js} +4 -4
  17. package/dist/{check-usage-BlIWDuV2.js.map → check-usage-DM39fdel.js.map} +1 -1
  18. package/dist/{claude-CSuIdaLV.js → claude-CkrhHkPQ.js} +26 -25
  19. package/dist/{claude-CSuIdaLV.js.map → claude-CkrhHkPQ.js.map} +1 -1
  20. package/dist/{claude-md-injection-Biq_Xhve.js → claude-md-injection-DNMDcw1W.js} +15 -24
  21. package/dist/claude-md-injection-DNMDcw1W.js.map +1 -0
  22. package/dist/{codex-BG0pfud9.js → codex-50GzveCD.js} +8 -7
  23. package/dist/{codex-BG0pfud9.js.map → codex-50GzveCD.js.map} +1 -1
  24. package/dist/{copilot-discount-UXC6NQbN.js → copilot-discount-DM98PuAF.js} +2 -2
  25. package/dist/{copilot-discount-UXC6NQbN.js.map → copilot-discount-DM98PuAF.js.map} +1 -1
  26. package/dist/{debug-1HUHCWFl.js → debug-Df0Kuzi3.js} +2 -2
  27. package/dist/{debug-1HUHCWFl.js.map → debug-Df0Kuzi3.js.map} +1 -1
  28. package/dist/diagnostics-cXjCT_JQ.js +12 -0
  29. package/dist/diagnostics-cXjCT_JQ.js.map +1 -0
  30. package/dist/engine-B6la_uIW.js +1 -0
  31. package/dist/{gate-discovery-DjH9YXoN.js → gate-discovery-2ILpM2fi.js} +5 -5
  32. package/dist/{gate-discovery-DjH9YXoN.js.map → gate-discovery-2ILpM2fi.js.map} +1 -1
  33. package/dist/{get-copilot-usage-CKg42gSH.js → get-copilot-usage-BZ6t2hFZ.js} +2 -2
  34. package/dist/{get-copilot-usage-CKg42gSH.js.map → get-copilot-usage-BZ6t2hFZ.js.map} +1 -1
  35. package/dist/hooks.mjs +13 -0
  36. package/dist/hooks.sha256 +1 -1
  37. package/dist/{index-cmd-sKwchRJz.js → index-cmd-DsK6VFs8.js} +4 -4
  38. package/dist/{index-cmd-sKwchRJz.js.map → index-cmd-DsK6VFs8.js.map} +1 -1
  39. package/dist/{internal-aic-status-B_hEeM37.js → internal-aic-status-CUZ7-trf.js} +3 -3
  40. package/dist/{internal-aic-status-B_hEeM37.js.map → internal-aic-status-CUZ7-trf.js.map} +1 -1
  41. package/dist/{internal-artifact-open-DbHjipxU.js → internal-artifact-open-DRBg1PpV.js} +2 -2
  42. package/dist/{internal-artifact-open-DbHjipxU.js.map → internal-artifact-open-DRBg1PpV.js.map} +1 -1
  43. package/dist/{internal-fast-dispatch-guard-DMzqs-r8.js → internal-fast-dispatch-guard-D6-Ees_6.js} +1 -1
  44. package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js → internal-fast-dispatch-guard-ZeS9u0A3.js} +2 -2
  45. package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js.map → internal-fast-dispatch-guard-ZeS9u0A3.js.map} +1 -1
  46. package/dist/{internal-first-mate-guard-BxPDUsV3.js → internal-first-mate-guard-BijeVpi9.js} +1 -1
  47. package/dist/{internal-first-mate-guard-4Yro9xNM.js → internal-first-mate-guard-DsEEsLKJ.js} +3 -3
  48. package/dist/{internal-first-mate-guard-4Yro9xNM.js.map → internal-first-mate-guard-DsEEsLKJ.js.map} +1 -1
  49. package/dist/{internal-max-dispatch-guard-0teaxIc1.js → internal-max-dispatch-guard-4RLca1i5.js} +2 -2
  50. package/dist/{internal-max-dispatch-guard-0teaxIc1.js.map → internal-max-dispatch-guard-4RLca1i5.js.map} +1 -1
  51. package/dist/{internal-max-dispatch-guard-5LSaHN_y.js → internal-max-dispatch-guard-DeEfWqfP.js} +1 -1
  52. package/dist/{internal-plan-review-BfHLeszV.js → internal-plan-review-bzqGNdtw.js} +3 -3
  53. package/dist/{internal-plan-review-BfHLeszV.js.map → internal-plan-review-bzqGNdtw.js.map} +1 -1
  54. package/dist/{internal-prompt-submit-BixNLmM3.js → internal-prompt-submit-BZ2-CExM.js} +4 -4
  55. package/dist/{internal-prompt-submit-BixNLmM3.js.map → internal-prompt-submit-BZ2-CExM.js.map} +1 -1
  56. package/dist/{internal-prompt-submit-Ou8xtRXj.js → internal-prompt-submit-ZBhH-SQ1.js} +2 -2
  57. package/dist/{internal-rebrief-BBGM0PMv.js → internal-rebrief-BIWbN7Sr.js} +4 -4
  58. package/dist/{internal-rebrief-BBGM0PMv.js.map → internal-rebrief-BIWbN7Sr.js.map} +1 -1
  59. package/dist/{internal-session-bind-pN1V11Mn.js → internal-session-bind-BL6hFRLO.js} +2 -2
  60. package/dist/{internal-session-bind-pN1V11Mn.js.map → internal-session-bind-BL6hFRLO.js.map} +1 -1
  61. package/dist/{internal-stop-hook-DO9Iiaes.js → internal-stop-hook-cDF1MuJZ.js} +5 -5
  62. package/dist/{internal-stop-hook-DO9Iiaes.js.map → internal-stop-hook-cDF1MuJZ.js.map} +1 -1
  63. package/dist/{internal-stop-review-BWp-4XWW.js → internal-stop-review-y8zjpK_3.js} +2 -2
  64. package/dist/{internal-stop-review-BWp-4XWW.js.map → internal-stop-review-y8zjpK_3.js.map} +1 -1
  65. package/dist/{internal-worker-guard-C9OZPgzu.js → internal-worker-guard-DdyYBZR0.js} +2 -2
  66. package/dist/{internal-worker-guard-C9OZPgzu.js.map → internal-worker-guard-DdyYBZR0.js.map} +1 -1
  67. package/dist/{internal-workspace-header-B4TXFBLU.js → internal-workspace-header-BMKbO8yX.js} +2 -2
  68. package/dist/{internal-workspace-header-B4TXFBLU.js.map → internal-workspace-header-BMKbO8yX.js.map} +1 -1
  69. package/dist/lib/tree-sitter-pool/worker.js +268 -21
  70. package/dist/lifecycle-BOjgq9_l.js +1 -0
  71. package/dist/{lifecycle-vjHAFCaY.js → lifecycle-BlC_kzNt.js} +2 -2
  72. package/dist/{lifecycle-vjHAFCaY.js.map → lifecycle-BlC_kzNt.js.map} +1 -1
  73. package/dist/{lifecycle-Dh9y8OF1.js → lifecycle-COZhARmE.js} +2 -2
  74. package/dist/{lifecycle-Dh9y8OF1.js.map → lifecycle-COZhARmE.js.map} +1 -1
  75. package/dist/lifecycle-NQvr4flt.js +1 -0
  76. package/dist/main.js +39 -24
  77. package/dist/main.js.map +1 -1
  78. package/dist/{mcp-workspace-header-C5-dOWNa.js → mcp-workspace-header-Bpa4BId8.js} +2 -2
  79. package/dist/{mcp-workspace-header-C5-dOWNa.js.map → mcp-workspace-header-Bpa4BId8.js.map} +1 -1
  80. package/dist/{models-B6nH1sS6.js → models-BDV-YLf2.js} +3 -3
  81. package/dist/{models-B6nH1sS6.js.map → models-BDV-YLf2.js.map} +1 -1
  82. package/dist/npm-env-H60tX76c.js +130 -0
  83. package/dist/npm-env-H60tX76c.js.map +1 -0
  84. package/dist/optional-DGAeyguL.js +586 -0
  85. package/dist/optional-DGAeyguL.js.map +1 -0
  86. package/dist/{orchestration-B93jxrWI.js → orchestration-Bto5Nc1Y.js} +2 -2
  87. package/dist/{orchestration-B93jxrWI.js.map → orchestration-Bto5Nc1Y.js.map} +1 -1
  88. package/dist/origin-BXtpcKP9.js +382 -0
  89. package/dist/origin-BXtpcKP9.js.map +1 -0
  90. package/dist/origin-DbFUCiGp.js +1 -0
  91. package/dist/paths-CquOjytP.js +1 -0
  92. package/dist/paths-DK_b2ihK.js +176 -0
  93. package/dist/paths-DK_b2ihK.js.map +1 -0
  94. package/dist/{paths-CVEO8jEH.js → paths-DeFmYJhO.js} +16 -3
  95. package/dist/paths-DeFmYJhO.js.map +1 -0
  96. package/dist/{peer-mcp-personas-OWsSm6To.js → peer-mcp-personas-Dny0r5Am.js} +14 -14
  97. package/dist/{peer-mcp-personas-OWsSm6To.js.map → peer-mcp-personas-Dny0r5Am.js.map} +1 -1
  98. package/dist/{pi-DmeBxzIo.js → pi-DVud9eQn.js} +386 -243
  99. package/dist/pi-DVud9eQn.js.map +1 -0
  100. package/dist/{pi-foreign-artifacts-DZ4tioyO.js → pi-foreign-artifacts-CNt6wQ1P.js} +2 -2
  101. package/dist/{pi-foreign-artifacts-DZ4tioyO.js.map → pi-foreign-artifacts-CNt6wQ1P.js.map} +1 -1
  102. package/dist/pi-memory-bridge-BxmCIIbk.js +618 -0
  103. package/dist/pi-memory-bridge-BxmCIIbk.js.map +1 -0
  104. package/dist/pi-memory-bridge-D5A0h_Kf.js +1 -0
  105. package/dist/pi-version-check-BeBB0Ny9.js +551 -0
  106. package/dist/pi-version-check-BeBB0Ny9.js.map +1 -0
  107. package/dist/pi-version-check-D5RvdLsG.js +1 -0
  108. package/dist/{plan-review-hook-MhjK92wq.js → plan-review-hook-D_yyjOgO.js} +3 -3
  109. package/dist/{plan-review-hook-MhjK92wq.js.map → plan-review-hook-D_yyjOgO.js.map} +1 -1
  110. package/dist/{provision-DPL8aGe2.js → provision-BWtuDq_v.js} +30 -36
  111. package/dist/provision-BWtuDq_v.js.map +1 -0
  112. package/dist/rerank-cross-encoder-BhjImuwG.js +192 -0
  113. package/dist/rerank-cross-encoder-BhjImuwG.js.map +1 -0
  114. package/dist/{self-invocation-DMUnXVGT.js → self-invocation-Dnq4iVD6.js} +4 -31
  115. package/dist/{self-invocation-DMUnXVGT.js.map → self-invocation-Dnq4iVD6.js.map} +1 -1
  116. package/dist/{serve-zbQKfx1E.js → serve-B8Igr9Q0.js} +15 -14
  117. package/dist/{serve-zbQKfx1E.js.map → serve-B8Igr9Q0.js.map} +1 -1
  118. package/dist/{server-setup-ClZdV33Q.js → server-setup-byIhjgOb.js} +708 -640
  119. package/dist/server-setup-byIhjgOb.js.map +1 -0
  120. package/dist/{service-backend-Cdgz6WPx.js → service-backend-BdhWVRSz.js} +17 -62
  121. package/dist/service-backend-BdhWVRSz.js.map +1 -0
  122. package/dist/{start-mnedD5cH.js → start-7CiQIl0r.js} +5 -4
  123. package/dist/{start-mnedD5cH.js.map → start-7CiQIl0r.js.map} +1 -1
  124. package/dist/{static-context-pack-CtnBwHSd.js → static-context-pack-BKFelEbM.js} +3 -3
  125. package/dist/{static-context-pack-CtnBwHSd.js.map → static-context-pack-BKFelEbM.js.map} +1 -1
  126. package/dist/{stop-gate-hook-CBVLD8iB.js → stop-gate-hook-DBOj0TqL.js} +3 -3
  127. package/dist/{stop-gate-hook-CBVLD8iB.js.map → stop-gate-hook-DBOj0TqL.js.map} +1 -1
  128. package/dist/{stop-gate-policy-BehNiNix.js → stop-gate-policy-Bp2wGh_W.js} +2 -2
  129. package/dist/{stop-gate-policy-BehNiNix.js.map → stop-gate-policy-Bp2wGh_W.js.map} +1 -1
  130. package/dist/{token-CPzYxU4Y.js → token-CKPOBdO0.js} +23 -88
  131. package/dist/{token-CPzYxU4Y.js.map → token-CKPOBdO0.js.map} +1 -1
  132. package/dist/{token-DHEkiO4g.js → token-Ygd7D32L.js} +3 -3
  133. package/dist/{token-DHEkiO4g.js.map → token-Ygd7D32L.js.map} +1 -1
  134. package/dist/update-CB21YRKz.js +1 -0
  135. package/dist/update-T1L7yFon.js +1548 -0
  136. package/dist/update-T1L7yFon.js.map +1 -0
  137. package/dist/update-fEgWTrIx.js +214 -0
  138. package/dist/update-fEgWTrIx.js.map +1 -0
  139. package/dist/update-lock-BeS_WmC8.js +1 -0
  140. package/dist/update-lock-BmXx6QaR.js +171 -0
  141. package/dist/update-lock-BmXx6QaR.js.map +1 -0
  142. package/dist/volatile-root-DQNNvQ7Z.js +50 -0
  143. package/dist/volatile-root-DQNNvQ7Z.js.map +1 -0
  144. package/dist/{worker-dispatch-C7RtNOXv.js → worker-dispatch-DBWKTMda.js} +2 -2
  145. package/dist/{worker-dispatch-C7RtNOXv.js.map → worker-dispatch-DBWKTMda.js.map} +1 -1
  146. package/dist/{workiq-CQauEAMc.js → workiq-D5b7xlbr.js} +2 -2
  147. package/dist/{workiq-CQauEAMc.js.map → workiq-D5b7xlbr.js.map} +1 -1
  148. package/dist/{workiq-tools-DL6rC4bP.js → workiq-tools-DdiQ2DOW.js} +1 -1
  149. package/package.json +16 -4
  150. package/dist/ado-tools-CRkyU51J.js +0 -1
  151. package/dist/claude-md-injection-Biq_Xhve.js.map +0 -1
  152. package/dist/engine-V46un8Xl.js +0 -1
  153. package/dist/lifecycle-BENRuuX6.js +0 -1
  154. package/dist/lifecycle-Dli9vGI2.js +0 -1
  155. package/dist/paths-Be9_ujQ3.js +0 -1
  156. package/dist/paths-CVEO8jEH.js.map +0 -1
  157. package/dist/pi-DmeBxzIo.js.map +0 -1
  158. package/dist/pi-memory-bridge-Bp9AnYw9.js +0 -1
  159. package/dist/pi-memory-bridge-CICIdDVP.js +0 -413
  160. package/dist/pi-memory-bridge-CICIdDVP.js.map +0 -1
  161. package/dist/provision-DPL8aGe2.js.map +0 -1
  162. package/dist/rerank-cross-encoder-B87lZgvc.js +0 -110
  163. package/dist/rerank-cross-encoder-B87lZgvc.js.map +0 -1
  164. package/dist/server-setup-ClZdV33Q.js.map +0 -1
  165. package/dist/service-backend-Cdgz6WPx.js.map +0 -1
package/dist/bin.js ADDED
@@ -0,0 +1,1479 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import path from "node:path";
4
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
5
+ import os from "node:os";
6
+ import process$1 from "node:process";
7
+ import fs from "node:fs/promises";
8
+ import { randomBytes } from "node:crypto";
9
+ // src/lib/exec.ts
10
+ /**
11
+ * Windows-safe, injection-safe command execution helpers.
12
+ *
13
+ * Why this module exists: on Windows, npm-installed CLIs (`claude`,
14
+ * `npm`, `codex`) are `.cmd`/`.bat` shims. Node's `execFile`/`spawn`
15
+ * with `shell:false` cannot launch them (CreateProcess only resolves
16
+ * `.exe`), so callers must invoke `cmd.exe` explicitly. Using
17
+ * `shell:true` delegates quoting back to the runtime and breaks absolute shim
18
+ * paths containing spaces, so this module builds one verified `/s /c`
19
+ * envelope and asks CreateProcess to pass it verbatim. That opens two hazards
20
+ * this module closes:
21
+ *
22
+ * 1. **Metacharacter injection** (`& | < > ^ ( ) ! %`). A naive
23
+ * "quote only tokens with spaces" scheme lets `pkg@latest&calc`
24
+ * run `calc` as a second command. `buildExecInvocation` applies
25
+ * real cmd.exe quoting (argv-quote + caret-escape) and fails
26
+ * closed on `%` (which cannot be reliably escaped on the cmd
27
+ * command line).
28
+ *
29
+ * 2. **CWD shadowing.** `cmd.exe` resolves a bare `npm` from the
30
+ * current directory before PATH, so an untrusted repo can plant
31
+ * `npm.cmd`. `resolveExecutable` resolves to an absolute path
32
+ * against PATH only (honoring PATHEXT), never the cwd, so callers
33
+ * spawn the real binary by absolute path.
34
+ *
35
+ * All runners are best-effort and timeout-bounded; callers wrap in
36
+ * try/catch and never let an update/probe failure block launch.
37
+ */
38
+ /** Read the PATH value from an env object, case-insensitively. */
39
+ function pathValueOf(env) {
40
+ for (const key of Object.keys(env)) if (key.toLowerCase() === "path") return env[key] ?? "";
41
+ return "";
42
+ }
43
+ /**
44
+ * Resolve an executable name to an absolute path against PATH, honoring
45
+ * `PATHEXT` on Windows and **excluding the current working directory**.
46
+ *
47
+ * Returns `null` when unresolved — callers treat that as "tool absent"
48
+ * and skip (best-effort). Spawning the returned absolute path means
49
+ * `cmd.exe`'s implicit cwd-first lookup never applies, closing the
50
+ * planted-`npm.cmd` vector.
51
+ */
52
+ function resolveExecutable(name, opts = {}) {
53
+ const platform = opts.platform ?? process$1.platform;
54
+ const env = opts.env ?? process$1.env;
55
+ const cwdRaw = opts.cwd ?? (typeof process$1.cwd === "function" ? process$1.cwd() : void 0);
56
+ const resolvedCwd = cwdRaw ? path.resolve(cwdRaw) : null;
57
+ const dirs = pathValueOf(env).split(path.delimiter).filter((d) => d.length > 0 && d !== ".");
58
+ const isWin = platform === "win32";
59
+ if (!isWin && name.includes("/")) return existsSync(name) ? path.resolve(name) : null;
60
+ if (isWin && (name.includes("\\") || name.includes("/"))) return existsSync(name) ? path.resolve(name) : null;
61
+ const exts = isWin && path.extname(name) === "" ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").map((e) => e.trim()).filter(Boolean) : [""];
62
+ for (const dir of dirs) {
63
+ if (resolvedCwd && path.resolve(dir) === resolvedCwd) continue;
64
+ for (const ext of exts) {
65
+ const candidate = path.join(dir, name + ext);
66
+ if (existsSync(candidate)) return candidate;
67
+ }
68
+ }
69
+ return null;
70
+ }
71
+ /**
72
+ * Quote one argument for a `cmd.exe /c "<line>"` command line so the
73
+ * target program receives it verbatim and no `cmd.exe` metacharacter
74
+ * retains shell meaning.
75
+ *
76
+ * Two phases (the canonical Windows approach — Colascione / Rust std):
77
+ * 1. **argv quoting** so `CommandLineToArgvW` in the target parses
78
+ * the token as one argument (double-quote, backslash-escape).
79
+ * 2. **caret-escaping** every `cmd.exe` metacharacter — including the
80
+ * quotes from phase 1 — so `cmd.exe` is never in quote-mode, strips
81
+ * the carets, and hands the argv-quoted string to the program.
82
+ *
83
+ * `%` is special: it cannot be reliably escaped on the `cmd.exe`
84
+ * *command line* (caret does not stop `%VAR%` expansion there). Rather
85
+ * than mis-escape, we **throw** — our callers never pass `%`, so this
86
+ * fails closed on the one unescapable injection vector.
87
+ */
88
+ function quoteWinArg(arg) {
89
+ if (arg.includes("%")) throw new Error("buildExecInvocation: argument contains '%', which cannot be safely escaped on the Windows command line; refusing to build the command.");
90
+ let quoted;
91
+ if (arg.length > 0 && !/[ \t\n\v"&|<>()^!]/.test(arg)) quoted = arg;
92
+ else {
93
+ let s = "\"";
94
+ let backslashes = 0;
95
+ for (const ch of arg) if (ch === "\\") backslashes++;
96
+ else if (ch === "\"") {
97
+ s += "\\".repeat(backslashes * 2 + 1) + "\"";
98
+ backslashes = 0;
99
+ } else {
100
+ s += "\\".repeat(backslashes) + ch;
101
+ backslashes = 0;
102
+ }
103
+ s += "\\".repeat(backslashes * 2) + "\"";
104
+ quoted = s;
105
+ }
106
+ return quoted.replace(/[()!^"<>&|]/g, "^$&");
107
+ }
108
+ function assertSafeBatchToken(value, kind) {
109
+ if ([...value].some((char) => char.charCodeAt(0) < 32) || value.includes("\"") || value.includes("%")) throw new Error(`buildExecInvocation: ${kind} contains a character that cannot be safely passed through cmd.exe; refusing to build the command.`);
110
+ }
111
+ function quoteBatchArg(arg) {
112
+ assertSafeBatchToken(arg, "argument");
113
+ return `"${arg.replaceAll("^", "^^").replace(/[&|<>]/g, "^$&")}"`;
114
+ }
115
+ function windowsCmdExe() {
116
+ const systemRoot = process$1.env.SystemRoot ?? process$1.env.SYSTEMROOT;
117
+ return systemRoot ? path.win32.join(systemRoot, "System32", "cmd.exe") : process$1.env.ComSpec ?? "cmd.exe";
118
+ }
119
+ /**
120
+ * Build the platform-correct `spawn` invocation for a command given as
121
+ * an argv array. Pure / unit-testable (no spawn).
122
+ *
123
+ * - win32 native executables (`.exe`/`.com`) → direct spawn with split
124
+ * argv. This avoids cmd.exe quoting and correctly handles absolute paths
125
+ * containing spaces (for example `C:\\Program Files\\Git\\...\\git.exe`).
126
+ * - win32 batch shims (`.cmd`/`.bat`) → explicit cmd.exe with `shell:false`
127
+ * and one verbatim `/s /c` envelope. Every token is quoted, so shell
128
+ * metacharacters are data; `%`, quotes, and controls fail closed.
129
+ * - unresolved win32 bare commands retain the legacy quoted `shell:true`
130
+ * path. Normal callers resolve first, so this is only a compatibility
131
+ * fallback.
132
+ * - posix → `(cmd[0], cmd.slice(1))` with `shell:false` — no shell,
133
+ * no injection surface.
134
+ */
135
+ function buildExecInvocation(cmd, platform = process$1.platform) {
136
+ if (cmd.length === 0) throw new Error("buildExecInvocation: empty command");
137
+ if (platform === "win32") {
138
+ const ext = path.extname(cmd[0]).toLowerCase();
139
+ if (ext === ".exe" || ext === ".com") return {
140
+ command: cmd[0],
141
+ args: cmd.slice(1),
142
+ shell: false
143
+ };
144
+ if (ext === ".cmd" || ext === ".bat") {
145
+ if (!path.win32.isAbsolute(cmd[0])) throw new Error("buildExecInvocation: Windows batch executable must be an absolute path");
146
+ assertSafeBatchToken(cmd[0], "executable");
147
+ const line = `""${cmd[0]}"${cmd.slice(1).map((arg) => ` ${quoteBatchArg(arg)}`).join("")}"`;
148
+ return {
149
+ command: windowsCmdExe(),
150
+ args: [
151
+ "/d",
152
+ "/s",
153
+ "/v:OFF",
154
+ "/c",
155
+ line
156
+ ],
157
+ shell: false,
158
+ windowsVerbatimArguments: true
159
+ };
160
+ }
161
+ return {
162
+ command: cmd.map(quoteWinArg).join(" "),
163
+ args: [],
164
+ shell: true
165
+ };
166
+ }
167
+ return {
168
+ command: cmd[0],
169
+ args: cmd.slice(1),
170
+ shell: false
171
+ };
172
+ }
173
+ /** Same ceiling shape for stderr, which only ever feeds diagnostics. */
174
+ const CAPTURE_STDERR_CAP = 65536;
175
+ function runInternal(cmd, stdoutMode, opts) {
176
+ const { command, args, shell, windowsVerbatimArguments } = buildExecInvocation(cmd);
177
+ return new Promise((resolve, reject) => {
178
+ let child;
179
+ try {
180
+ child = spawn(command, args, {
181
+ cwd: opts.cwd,
182
+ env: opts.env ?? process$1.env,
183
+ shell,
184
+ windowsVerbatimArguments,
185
+ windowsHide: true,
186
+ stdio: [
187
+ "ignore",
188
+ stdoutMode,
189
+ stdoutMode === "inherit" ? "inherit" : "pipe"
190
+ ]
191
+ });
192
+ } catch (err) {
193
+ reject(err instanceof Error ? err : new Error(String(err)));
194
+ return;
195
+ }
196
+ const stdoutDecoder = new TextDecoder();
197
+ const stderrDecoder = new TextDecoder();
198
+ let stdout = "";
199
+ let stderr = "";
200
+ let stdoutBytes = 0;
201
+ let stderrBytes = 0;
202
+ let truncated = false;
203
+ let stderrTruncated = false;
204
+ let timedOut = false;
205
+ let settled = false;
206
+ const maxStdoutBytes = opts.maxStdoutBytes ?? 16777216;
207
+ const timer = opts.timeoutMs ? setTimeout(() => {
208
+ timedOut = true;
209
+ killTree(child.pid);
210
+ }, opts.timeoutMs) : void 0;
211
+ timer?.unref?.();
212
+ const onAbort = () => killTree(child.pid);
213
+ if (opts.signal?.aborted) onAbort();
214
+ else opts.signal?.addEventListener("abort", onAbort, { once: true });
215
+ child.stdout?.on("data", (c) => {
216
+ if (truncated) return;
217
+ const room = maxStdoutBytes - stdoutBytes;
218
+ if (c.length > room) {
219
+ if (room > 0) {
220
+ stdout += stdoutDecoder.decode(c.subarray(0, room), { stream: true });
221
+ stdoutBytes += room;
222
+ }
223
+ truncated = true;
224
+ return;
225
+ }
226
+ stdout += stdoutDecoder.decode(c, { stream: true });
227
+ stdoutBytes += c.length;
228
+ });
229
+ child.stderr?.on("data", (c) => {
230
+ if (stderrBytes >= CAPTURE_STDERR_CAP) {
231
+ stderrTruncated = true;
232
+ return;
233
+ }
234
+ const room = CAPTURE_STDERR_CAP - stderrBytes;
235
+ const slice = c.length > room ? c.subarray(0, room) : c;
236
+ if (slice.length < c.length) stderrTruncated = true;
237
+ stderr += stderrDecoder.decode(slice, { stream: true });
238
+ stderrBytes += slice.length;
239
+ });
240
+ child.stdout?.on("error", () => {});
241
+ child.stderr?.on("error", () => {});
242
+ const finish = (code) => {
243
+ if (settled) return;
244
+ settled = true;
245
+ if (timer) clearTimeout(timer);
246
+ opts.signal?.removeEventListener("abort", onAbort);
247
+ if (!truncated) stdout += stdoutDecoder.decode();
248
+ if (!stderrTruncated) stderr += stderrDecoder.decode();
249
+ resolve({
250
+ stdout,
251
+ stderr,
252
+ code,
253
+ timedOut,
254
+ truncated,
255
+ stderrTruncated
256
+ });
257
+ };
258
+ child.on("error", (err) => {
259
+ if (settled) return;
260
+ settled = true;
261
+ if (timer) clearTimeout(timer);
262
+ opts.signal?.removeEventListener("abort", onAbort);
263
+ reject(err);
264
+ });
265
+ child.on("close", (code) => finish(code));
266
+ });
267
+ }
268
+ /**
269
+ * Spawn `taskkill` best-effort, without any chance of taking the proxy down.
270
+ *
271
+ * Two things a bare `try { spawn("taskkill", ...) } catch {}` gets wrong, both
272
+ * of which this helper is the single place that fixes:
273
+ *
274
+ * 1. **The catch cannot catch.** `spawn` reports ENOENT / EPERM / EACCES by
275
+ * emitting `'error'` ASYNCHRONOUSLY, so the surrounding `try` (which only
276
+ * guards the synchronous throw) never sees it. An EventEmitter `'error'`
277
+ * with no listener THROWS — which lands in the `uncaughtException` handler
278
+ * in `~/main` and calls `process.exit(1)`. A best-effort child kill on a
279
+ * timeout path could therefore kill the whole proxy. The listener must be
280
+ * attached synchronously at the spawn site, which is why this is a helper
281
+ * and not a convention.
282
+ * 2. **The bare name is hijackable.** `CreateProcess`'s search order can
283
+ * include the cwd, so `"taskkill"` may resolve to a planted binary;
284
+ * `taskkillExe()` pins `System32\taskkill.exe`.
285
+ */
286
+ function spawnTaskkillBestEffort(pid) {
287
+ try {
288
+ spawn(taskkillExe(), [
289
+ "/T",
290
+ "/F",
291
+ "/PID",
292
+ String(pid)
293
+ ], {
294
+ stdio: "ignore",
295
+ windowsHide: true
296
+ }).on("error", () => {
297
+ fallbackKill(pid);
298
+ });
299
+ return true;
300
+ } catch {
301
+ fallbackKill(pid);
302
+ return false;
303
+ }
304
+ }
305
+ /**
306
+ * Last-resort single-process kill when `taskkill` itself cannot run.
307
+ *
308
+ * Not a tree kill — grandchildren survive — but it is the difference between
309
+ * "the timed-out child dies and its `close` event settles the caller" and "the
310
+ * caller waits forever". `runInternal` resolves ONLY from `close`, so a timeout
311
+ * whose kill never lands leaves that promise pending for the life of the
312
+ * process, which is a worse failure than the crash `spawnTaskkillBestEffort`
313
+ * was written to prevent. Best-effort by construction: ESRCH means the child
314
+ * was already gone, which is the success case.
315
+ */
316
+ function fallbackKill(pid) {
317
+ try {
318
+ process$1.kill(pid);
319
+ } catch {}
320
+ }
321
+ /** Kill a process tree best-effort (taskkill /T on Windows). */
322
+ function killTree(pid) {
323
+ if (!pid) return;
324
+ try {
325
+ if (process$1.platform === "win32") spawnTaskkillBestEffort(pid);
326
+ else process$1.kill(pid, "SIGTERM");
327
+ } catch {}
328
+ }
329
+ /** Run a command and capture stdout/stderr. Rejects on spawn error. */
330
+ function runCommandCapture(cmd, opts = {}) {
331
+ return runInternal(cmd, "pipe", opts);
332
+ }
333
+ /**
334
+ * Absolute path to Windows `taskkill.exe`. Bare `"taskkill"` would let
335
+ * `CreateProcess`'s search order (which can include the cwd) run a planted
336
+ * `taskkill.exe`; pinning the System32 path closes that hijack.
337
+ */
338
+ function taskkillExe() {
339
+ const root = process$1.env.SystemRoot || process$1.env.windir || "C:\\Windows";
340
+ return path.join(root, "System32", "taskkill.exe");
341
+ }
342
+ // src/lib/volatile-root.ts
343
+ /**
344
+ * "Could the OS delete this path while we are not looking?"
345
+ *
346
+ * One predicate, two consumers with the same question and different stakes:
347
+ *
348
+ * - `hook-launcher/self-invocation.ts` asks it about a PERSISTED hook command, so
349
+ * the answer drives a user-facing warning;
350
+ * - `managed-install/origin.ts` asks it about the running code, so the answer
351
+ * drives "is this tree disposable enough to replace with the managed install".
352
+ *
353
+ * It lives alone here because `origin.ts` is imported by the bootstrap bundle
354
+ * (`dist/bin.js`), which must not pull `consola`, `PATHS`, or the hook-launcher
355
+ * provisioning graph just to compare two path prefixes. Hence: `node:` builtins
356
+ * only, no logging, no app state.
357
+ *
358
+ * Why it cannot be a bare prefix test: `os.tmpdir()` reports `/var/folders/…` on
359
+ * macOS while a process sees `/private/var/folders/…`, so a single-form compare
360
+ * silently never matches. Both sides are therefore compared in resolved AND
361
+ * unresolved form, and `realpath` failure (a path that does not exist, which is
362
+ * the normal case for a hook command that has not run yet) must not change the
363
+ * answer.
364
+ */
365
+ function realpathIfPossible(file) {
366
+ try {
367
+ return realpathSync(file);
368
+ } catch {
369
+ return file;
370
+ }
371
+ }
372
+ /**
373
+ * Whether `target` sits under a directory the OS is entitled to clean out from
374
+ * under a running session: the per-user temp dir on every platform, which is
375
+ * where `bunx` (unlike `npx`, which uses a cache under `$HOME`) installs.
376
+ */
377
+ function isUnderVolatileRoot(target) {
378
+ try {
379
+ const prefixes = /* @__PURE__ */ new Set();
380
+ for (const root of [os.tmpdir(), realpathIfPossible(os.tmpdir())]) prefixes.add(root.endsWith(path.sep) ? root : root + path.sep);
381
+ return [target, realpathIfPossible(target)].some((candidate) => [...prefixes].some((prefix) => candidate.startsWith(prefix)));
382
+ } catch {
383
+ return false;
384
+ }
385
+ }
386
+ // src/lib/atomic-file.ts
387
+ /**
388
+ * Atomic file replacement, shared by every durable pointer this codebase keeps
389
+ * on disk (credentials, settings, the managed-install pointer).
390
+ *
391
+ * Why a module: the same three-step dance — write a pretend temp beside the
392
+ * destination, `rename` over it, retry through a transient Windows lock — had
393
+ * been re-implemented four times (`token.ts`, `cloudagent-hook-settings.ts`,
394
+ * `claude-md-injection.ts`, `first-mate/durable-store.ts`) with slightly
395
+ * different retry lists. The managed installer adds a fifth and, unlike the
396
+ * others, runs it unattended in the middle of an update where a `EPERM` is the
397
+ * difference between "updated" and "silently did nothing". So it lives here and
398
+ * the four existing callers keep their behaviour by delegating.
399
+ *
400
+ * The invariants every writer here guarantees:
401
+ *
402
+ * - **no partial destination.** A reader sees either the old bytes or the new
403
+ * bytes. `writeFile` at the destination truncates first, so a crash, a full
404
+ * disk, or a kill leaves a truncated file — for `current.json` that means a
405
+ * launch that cannot resolve its own payload.
406
+ * - **durability.** The file is `fsync`ed before the rename and the parent
407
+ * directory after it, so a power loss cannot leave the rename in the journal
408
+ * with the content still in page cache. (`fsync` on a directory is a no-op
409
+ * on Windows, which is fine: `MoveFileExW` already journals the metadata.)
410
+ * - **no symlink following.** Temp names come from `randomBytes` and are
411
+ * created with `flag: "wx"`, so an attacker who pre-places a symlink at a
412
+ * predictable temp name gets `EEXIST` instead of a write through their link.
413
+ * - **no copy fallback.** A failed rename throws. `copyFile` follows the
414
+ * destination, which reintroduces exactly the symlink/hardlink escape the
415
+ * `wx` flag exists to prevent.
416
+ */
417
+ /**
418
+ * Backoff for a transient Windows rename failure.
419
+ *
420
+ * On Windows `fs.rename` over an existing destination transiently fails with
421
+ * `EPERM` / `EBUSY` / `EACCES` when anything else holds the destination open
422
+ * for a moment — antivirus, the search indexer, a backup agent, an editor.
423
+ * Nothing is wrong and the handle closes microseconds later, but without a
424
+ * retry a scan landing on the wrong millisecond costs the user a launch.
425
+ *
426
+ * `server-setup`'s `claude` settings write, the credential write and the
427
+ * CLAUDE.md injection all use this same list; keeping one copy means a future
428
+ * Windows behaviour change is diagnosed once, not four times.
429
+ */
430
+ const RENAME_RETRY_DELAYS_MS = [
431
+ 50,
432
+ 200,
433
+ 500
434
+ ];
435
+ /**
436
+ * Error codes worth retrying on read. A reader racing a rename can observe
437
+ * `ENOENT` (the destination name is briefly unlinked on some filesystems,
438
+ * notably when a network client replays the operation) and can observe the
439
+ * Windows lock codes while the writer's handle is still open.
440
+ */
441
+ const TRANSIENT_READ_CODES = /* @__PURE__ */ new Set([
442
+ "EPERM",
443
+ "EBUSY",
444
+ "EACCES",
445
+ "ENOENT"
446
+ ]);
447
+ function errorCode(err) {
448
+ const code = err?.code;
449
+ return typeof code === "string" ? code : void 0;
450
+ }
451
+ const sleep = (ms) => new Promise((resolve) => {
452
+ setTimeout(resolve, ms);
453
+ });
454
+ /**
455
+ * `rename(from, to)` with bounded retry through a transient Windows lock.
456
+ *
457
+ * Returns `true` when the rename landed (or the destination already held
458
+ * `acceptedContent`). Returns `false` — never throws — when retries are
459
+ * exhausted and the destination does not match; the caller decides whether that
460
+ * is fatal (`writeFileAtomic` treats it as fatal).
461
+ *
462
+ * `from` is NOT cleaned up on failure: a caller holding a temp path may want to
463
+ * inspect it, and every caller here either retries or unlinks in its own
464
+ * `finally`. The one exception is `writeFileAtomic`, which owns its temp.
465
+ */
466
+ async function renameWithRetry(from, to, opts = {}) {
467
+ const delays = opts.delaysMs ?? RENAME_RETRY_DELAYS_MS;
468
+ let lastErr;
469
+ for (let attempt = 0; attempt <= delays.length; attempt++) try {
470
+ await fs.rename(from, to);
471
+ return true;
472
+ } catch (err) {
473
+ lastErr = err;
474
+ if (attempt < delays.length) await sleep(delays[attempt]);
475
+ }
476
+ if (opts.acceptedContent !== void 0) try {
477
+ if (await fs.readFile(to, "utf8") === opts.acceptedContent) return true;
478
+ } catch {}
479
+ opts.onExhausted?.(lastErr);
480
+ return false;
481
+ }
482
+ /** `fsync` a directory, ignoring platforms/filesystems that refuse. */
483
+ async function fsyncDir(dir) {
484
+ let handle;
485
+ try {
486
+ handle = await fs.open(dir, "r");
487
+ await handle.sync();
488
+ } catch {} finally {
489
+ await handle?.close().catch(() => {});
490
+ }
491
+ }
492
+ /** `fsync` an open file handle, ignoring failures on exotic filesystems. */
493
+ async function fsyncFile(handle) {
494
+ try {
495
+ await handle.sync();
496
+ } catch {}
497
+ }
498
+ /**
499
+ * Replace `filePath` with `data` atomically: temp + fsync + rename + fsync(dir).
500
+ *
501
+ * Throws on failure, having removed its temp file. Never leaves a partially
502
+ * written destination and never writes through a pre-placed symlink.
503
+ *
504
+ * The temp file is created in the SAME directory as the destination — a
505
+ * cross-directory temp would make the rename a cross-device copy (`EXDEV`) on
506
+ * any setup with a separate mount for the parent, and would stop being atomic.
507
+ */
508
+ async function writeFileAtomic(filePath, data, opts = {}) {
509
+ const tmp = `${filePath}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
510
+ let handle;
511
+ try {
512
+ await fs.writeFile(tmp, data, {
513
+ mode: opts.mode ?? 384,
514
+ flag: "wx"
515
+ });
516
+ handle = await fs.open(tmp, "r");
517
+ await fsyncFile(handle);
518
+ const closedHandle = handle;
519
+ handle = void 0;
520
+ await closedHandle.close();
521
+ if (!await renameWithRetry(tmp, filePath, {
522
+ acceptedContent: opts.acceptedContent ?? (typeof data === "string" ? data : void 0),
523
+ delaysMs: opts.delaysMs
524
+ })) throw new Error(`atomic write failed: could not rename ${tmp} over ${filePath} after ${(opts.delaysMs ?? RENAME_RETRY_DELAYS_MS).length + 1} attempts`);
525
+ await fsyncDir(
526
+ /** same directory as the destination */
527
+ dirnameOf(filePath)
528
+ );
529
+ return;
530
+ } catch (err) {
531
+ await handle?.close().catch(() => {});
532
+ await fs.unlink(tmp).catch(() => {});
533
+ throw err;
534
+ }
535
+ }
536
+ /**
537
+ * `path.dirname` without importing `node:path` at module scope.
538
+ *
539
+ * The launcher this module's output is inlined into runs before any bundler
540
+ * chunk is available, and a stray `node:path` import is one more thing the
541
+ * inlining recipe has to keep external. A local split is exact for the paths
542
+ * here (always absolute) and cannot drift from `dirname` for them.
543
+ */
544
+ function dirnameOf(p) {
545
+ const idx = Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\"));
546
+ if (idx <= 0) return ".";
547
+ return p.slice(0, idx);
548
+ }
549
+ /**
550
+ * Read a file, retrying briefly through a racing rename.
551
+ *
552
+ * A reader that lands between the writer's `rename` and the OS finishing the
553
+ * directory update can see `ENOENT`; a Windows reader can see `EBUSY` while the
554
+ * writer's handle is still closing. Both clear within the retry window. A
555
+ * persistent failure still propagates: callers must not treat "could not read"
556
+ * as "absent" when their decision depends on it.
557
+ *
558
+ * `retryMissing` defaults to `true` because the readers that existed first (the
559
+ * credential files) race a writer that replaces them constantly. Set it to
560
+ * `false` for a file whose absence is a *normal state* — the managed pointer on
561
+ * first run — where retrying would put 750 ms of latency in front of every
562
+ * launch for no benefit. (Measured: the first version of `readPointer` cost
563
+ * 760 ms per call on a machine with no managed install.)
564
+ */
565
+ async function readFileWithRetry(filePath, opts = {}) {
566
+ const delays = opts.delaysMs ?? RENAME_RETRY_DELAYS_MS;
567
+ const retryMissing = opts.retryMissing ?? true;
568
+ let lastErr;
569
+ for (let attempt = 0; attempt <= delays.length; attempt++) try {
570
+ return await fs.readFile(filePath, "utf8");
571
+ } catch (err) {
572
+ lastErr = err;
573
+ const code = errorCode(err);
574
+ if (!(code !== void 0 && TRANSIENT_READ_CODES.has(code) && (retryMissing || code !== "ENOENT"))) throw err;
575
+ if (attempt < delays.length) await sleep(delays[attempt]);
576
+ }
577
+ throw lastErr;
578
+ }
579
+ // src/lib/managed-install/paths.ts
580
+ /**
581
+ * Filesystem layout for the managed install.
582
+ *
583
+ * `npx github-router@latest` re-extracts a ~586 MB tree for every published
584
+ * version (measured: 16 releases in 31 days), so the router wants the Claude
585
+ * Code shape instead: install once into a per-user prefix, keep versioned
586
+ * payloads side by side, and let a pointer decide which one runs. This module is
587
+ * only the NAMES — no I/O — so it can be imported by the standalone launcher,
588
+ * the CLI, and tests without pulling in npm or the app graph.
589
+ *
590
+ * ```
591
+ * <APP_DIR>/m/<kind>/
592
+ * current.json the only mutable pointer (atomic file rename)
593
+ * launcher.mjs stable path, written once, never swapped
594
+ * install-state.json lastAttemptAt / failures / cache
595
+ * <version>/package.json generated { private: true, dependencies: … }
596
+ * <version>/node_modules/… immutable payload
597
+ * <version>/.installed.json {version, resolved, integrity, installedAt, runtime}
598
+ * .staging-<pid>-<rand>/ npm --prefix target, renamed away on publish
599
+ * .trash-<rand>/ rename-aside target for a corrupt version
600
+ * <APP_DIR>/optional/<pkg>@<version>/ shared heavy payload (§8 of the plan)
601
+ * <APP_DIR>/cli-bin/github-router… shims
602
+ * ```
603
+ *
604
+ * Two naming decisions are load-bearing and must not drift:
605
+ *
606
+ * 1. **`<version>` is the version dir name directly under `<kind>`**, not under a
607
+ * `versions/` level. Windows `MAX_PATH` applies per file, and an installed
608
+ * npm tree already carries ~139 characters of relative path; the
609
+ * `versions/<v>` form pushes a Pi payload past 260 for an 18-character
610
+ * username (measured 264 vs 249). See the plan's §7 table.
611
+ * 2. **Every transient name starts with `.`**. That single rule is the GC
612
+ * contract: anything `readdir` returns that starts with `.` is never a
613
+ * version, so a killed install can never be mistaken for one.
614
+ */
615
+ /**
616
+ * The app-data root. Mirrors `PATHS.APP_DIR` (`src/lib/paths.ts:9`) but is
617
+ * resolved independently: the launcher runs before the app graph loads (and
618
+ * must not import `consola` or `cloudagent-hook-settings`), and tests need to
619
+ * relocate it without touching the real `~/.local/share`.
620
+ */
621
+ function appDir() {
622
+ const override = process.env.GH_ROUTER_APP_DIR?.trim();
623
+ if (override && path.isAbsolute(override)) return override;
624
+ return path.join(os.homedir(), ".local", "share", "github-router");
625
+ }
626
+ function managedRoot(kind) {
627
+ return path.join(appDir(), "m", kind);
628
+ }
629
+ function pointerPath(kind) {
630
+ return path.join(managedRoot(kind), "current.json");
631
+ }
632
+ function installStatePath(kind) {
633
+ return path.join(managedRoot(kind), "install-state.json");
634
+ }
635
+ /** A concrete installed payload. `dirName` is what `readdir` reports. */
636
+ function versionDir(kind, version) {
637
+ return path.join(managedRoot(kind), version);
638
+ }
639
+ /**
640
+ * Relative entry path for a kind, once its package is installed.
641
+ *
642
+ * `self` names the APP entry (`dist/main.js`), never the published bin
643
+ * (`dist/bin.js`). That is not cosmetic: the bin IS the bootstrap, so a pointer
644
+ * derived from the bin map would re-exec the bootstrap, which reads the same
645
+ * pointer, forever. `pointer.isSafeEntry` refuses it as a second line of defence.
646
+ */
647
+ const ENTRY_RELATIVE = {
648
+ self: "node_modules/github-router/dist/main.js",
649
+ pi: "node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js"
650
+ };
651
+ /**
652
+ * Test seams for the two constants above.
653
+ *
654
+ * The installer's interesting behaviour (staging, publish-by-rename, provenance,
655
+ * GC) is identical for a 6 KB package with no install scripts and for the real
656
+ * 66 MB payload, so the end-to-end test installs a tiny one. Without these the
657
+ * test would either need the network and a minute per case, or would have to
658
+ * re-implement the layout — which is exactly the duplicated-logic trap that
659
+ * makes a test pass while production breaks.
660
+ *
661
+ * Not part of the public surface: nothing in `src/` calls them.
662
+ */
663
+ let entryOverride = {};
664
+ function entryRelativeFor(kind) {
665
+ return entryOverride[kind] ?? ENTRY_RELATIVE[kind];
666
+ }
667
+ // src/lib/managed-install/state.ts
668
+ /**
669
+ * `install-state.json`: the managed installer's memory across launches.
670
+ *
671
+ * Three separate concerns share one small file because they are written at the
672
+ * same moments and a second file would be a second thing to keep consistent:
673
+ *
674
+ * - **backoff** (`lastAttemptAt`, `consecutiveFailures`, `nextAttemptAt`,
675
+ * `lastError`), so a failing registry is retried on a ladder instead of on
676
+ * every launch;
677
+ * - **the cached npm cache path**, because `NPM_CONFIG_CACHE` is routinely moved
678
+ * and probing it costs a subprocess on every CLI invocation.
679
+ *
680
+ * There is deliberately no `registry` field. It used to be written here, was
681
+ * never read (`update --check` takes provenance from the version dir's
682
+ * `.installed.json`, which is per-install rather than per-machine), and never
683
+ * cleared — so it reported one old install's registry forever. A field nobody
684
+ * reads is a lie waiting to be trusted; `InstallState` ignores unknown keys, so
685
+ * dropping it cannot break an existing file.
686
+ *
687
+ * Lives here rather than in `install.ts` because `origin.ts` needs it and must not
688
+ * import the installer: the installer pulls `consola`, and `origin.ts` is on the
689
+ * bootstrap's path. Nothing here logs.
690
+ */
691
+ async function readInstallState(kind) {
692
+ try {
693
+ const raw = await readFileWithRetry(installStatePath(kind), { retryMissing: false });
694
+ const parsed = JSON.parse(raw);
695
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
696
+ } catch {
697
+ return {};
698
+ }
699
+ }
700
+ /**
701
+ * Write state. Returns `false` on failure instead of throwing — this file is an
702
+ * optimisation, never a gate — but never silently: a failed write is reported,
703
+ * because the CALLER's next launch is what pays for it. The expensive case is the
704
+ * success patch: if that one fails, the ladder from a previous failure is still
705
+ * on disk, and every launch for the next 1–24 h reports "last attempt failed"
706
+ * on a machine that is perfectly up to date.
707
+ */
708
+ async function writeInstallState(kind, state) {
709
+ try {
710
+ await fs.mkdir(managedRoot(kind), { recursive: true });
711
+ await writeFileAtomic(installStatePath(kind), `${JSON.stringify(state, null, 2)}\n`, { mode: 420 });
712
+ return true;
713
+ } catch (err) {
714
+ `${kind}${installStatePath(kind)}${err instanceof Error ? err.message : String(err)}`;
715
+ return false;
716
+ }
717
+ }
718
+ /**
719
+ * Read-modify-write a patch onto the CURRENT on-disk state.
720
+ *
721
+ * Not `writeInstallState({...staleSnapshot, ...patch})`: the callers that hold a
722
+ * snapshot across an install (which can take minutes) would otherwise clobber
723
+ * fields another process — or a `npmProbes()` probe earlier in this one — wrote
724
+ * in the meantime. The observable version of that bug is subtle and expensive: the
725
+ * cache/global-root memo disappears, and every launch pays a 250 ms npm probe
726
+ * again.
727
+ *
728
+ * KNOWN LIMIT, stated because suppressing it would need a real lock on the file:
729
+ * the read and the write are not atomic together, so two processes patching
730
+ * DIFFERENT keys in the same instant can lose one of them ("last writer wins for
731
+ * the whole file"). Callers hold the install lock for anything that must not be
732
+ * lost, and every other writer writes a self-healing value: a lost `npmProbe` is
733
+ * re-derived on the next launch, a lost `lastOrigin` is cosmetic. Do not add a
734
+ * field whose loss changes a decision without also holding the lock.
735
+ */
736
+ async function patchInstallState(kind, patch) {
737
+ const next = {
738
+ ...await readInstallState(kind),
739
+ ...patch
740
+ };
741
+ for (const key of Object.keys(patch)) if (patch[key] === void 0) delete next[key];
742
+ return writeInstallState(kind, next);
743
+ }
744
+ /**
745
+ * Whether the backoff window has expired.
746
+ *
747
+ * `nextAttemptAt` is written BEFORE an attempt (optimistic), so two launches
748
+ * racing on the same failing registry do not both hammer npm.
749
+ */
750
+ function installAllowedNow(state, now = Date.now()) {
751
+ if (!state.nextAttemptAt) return true;
752
+ const next = new Date(state.nextAttemptAt).getTime();
753
+ if (Number.isNaN(next)) return true;
754
+ return now >= next;
755
+ }
756
+ /**
757
+ * Whether an attempt may start, distinguishing a RESERVATION from a BACKOFF.
758
+ *
759
+ * `nextAttemptAt` is written optimistically before every attempt so two launches
760
+ * cannot both run npm, and it is also the backoff ladder's output. Those two
761
+ * meanings must not be conflated: a reservation (`consecutiveFailures` still 0)
762
+ * is not evidence of failure, so treating it as one makes an explicit
763
+ * `github-router update` issued right after a launch that merely *scheduled* an
764
+ * install print "last attempt failed (unknown error)" and do nothing. The install
765
+ * lock — not this window — is what serialises attempts, so re-attempting a
766
+ * reservation is cheap: the loser exits immediately.
767
+ *
768
+ * A crash mid-install also leaves a bare reservation, and retrying it is the
769
+ * correct repair (the leftover `.staging-*` is swept by GC).
770
+ */
771
+ function mayAttemptNow(state, now = Date.now()) {
772
+ if ((state.consecutiveFailures ?? 0) === 0) return true;
773
+ return installAllowedNow(state, now);
774
+ }
775
+ // src/lib/managed-install/origin.ts
776
+ /**
777
+ * Where did this process start from?
778
+ *
779
+ * The bootstrap (`dist/bin.js`) has to answer one question before it does
780
+ * anything else: *is the tree I am running from a disposable copy?* If it is
781
+ * (`npx`, `bunx`), adopting the managed install is the whole point of the
782
+ * feature. If it is not (`npm i -g`, a git checkout, or already managed), the
783
+ * bootstrap must be a pure pass-through — user decision 4 is explicit that a
784
+ * global install stays its own owner and must never be duplicated.
785
+ *
786
+ * Classification is deliberately **positive** and **fail-safe**: each branch
787
+ * needs evidence (a realpath under a known root, a `.git` marker), and the
788
+ * default answer is `unknown`, which every caller treats as `source` — no adopt,
789
+ * no install, no background work. A wrong `npx` answer costs the user a 66 MB
790
+ * install they did not want; a wrong `source` answer costs nothing.
791
+ *
792
+ * Cost matters here in a way it does not elsewhere: this runs on EVERY CLI
793
+ * invocation. So every probe is bounded, cached in-process, and the two that
794
+ * spawn (`npm root -g`, `npm config get cache`) are cached across runs in
795
+ * `install-state.json` — `NPM_CONFIG_CACHE` moving is rare enough that one
796
+ * stale read is worth avoiding 300 ms on every launch.
797
+ */
798
+ /** Timeout for the two npm probes. A cold `npm root -g` can take ~300 ms. */
799
+ const PROBE_TIMEOUT_MS = 5e3;
800
+ let cached;
801
+ /** Walk up from `entry` to the `github-router` package root. */
802
+ function findPackageRoot(entry) {
803
+ if (typeof entry !== "string" || entry.length === 0) return void 0;
804
+ let cur = path.dirname(realpathIfPossible(entry));
805
+ for (let i = 0; i < 10; i++) {
806
+ try {
807
+ const pkg = JSON.parse(readFileSync(path.join(cur, "package.json"), "utf8"));
808
+ if (pkg.name === "github-router" || pkg.name === "@animeshkundu/github-router") return cur;
809
+ } catch {}
810
+ const parent = path.dirname(cur);
811
+ if (parent === cur) break;
812
+ cur = parent;
813
+ }
814
+ }
815
+ /**
816
+ * Normalized, separator-trailing form so prefix tests cannot match `/foo` in
817
+ * `/foobar`.
818
+ *
819
+ * Lowercased on Windows: NTFS is case-insensitive, so `C:\Users\X\AppData\npm`
820
+ * (what `npm root -g` reports) and `c:\users\x\appdata\npm\node_modules\…`
821
+ * (what a launcher spawned from a differently-cased PATH entry sees) are the same
822
+ * directory and must compare equal. A case-sensitive compare would classify a
823
+ * global install as `unknown` — and `unknown` means "never adopt, never install",
824
+ * so the failure is a silent absence of the feature on that machine.
825
+ */
826
+ function asPrefix(dir) {
827
+ const resolved = realpathIfPossible(dir);
828
+ const withSep = resolved.endsWith(path.sep) ? resolved : `${resolved}${path.sep}`;
829
+ return process.platform === "win32" ? withSep.toLowerCase() : withSep;
830
+ }
831
+ function normalizeForCompare(value) {
832
+ return process.platform === "win32" ? value.toLowerCase() : value;
833
+ }
834
+ function isUnder(target, root) {
835
+ if (!root) return false;
836
+ const prefix = asPrefix(root);
837
+ for (const candidate of [target, realpathIfPossible(target)]) {
838
+ if (normalizeForCompare(candidate).startsWith(prefix)) return true;
839
+ if (normalizeForCompare(realpathIfPossible(candidate)).startsWith(prefix)) return true;
840
+ }
841
+ return false;
842
+ }
843
+ /** One `npm config get <key>` probe, bounded and never throwing. */
844
+ async function npmConfigValue(args) {
845
+ const npmPath = resolveExecutable("npm");
846
+ if (!npmPath) return null;
847
+ try {
848
+ const { stdout, code } = await runCommandCapture([npmPath, ...args], { timeoutMs: PROBE_TIMEOUT_MS });
849
+ if (code !== 0) return null;
850
+ const value = stdout.trim().split(/\r?\n/).pop()?.trim();
851
+ return value && path.isAbsolute(value) ? value : null;
852
+ } catch {
853
+ return null;
854
+ }
855
+ }
856
+ /**
857
+ * Resolve (and memoise) both npm probes.
858
+ *
859
+ * Cached in-process for the life of this process and across runs in
860
+ * `install-state.json`, keyed by `process.execPath`. The key matters: under nvm
861
+ * the global root IS per-node-version, so an unkeyed cache would point the next
862
+ * launch at a tree that node version no longer owns.
863
+ *
864
+ * One probe run per cache miss, not one per query: `classifyEntry` needs both,
865
+ * and each is a ~250 ms subprocess.
866
+ */
867
+ async function npmProbes(kind = "self") {
868
+ const runtime = process.execPath;
869
+ const cached = (await readInstallState(kind)).npmProbe;
870
+ if (cached?.runtime === runtime && cached.globalRoot && cached.cacheRoot) return {
871
+ globalRoot: cached.globalRoot,
872
+ cacheRoot: cached.cacheRoot
873
+ };
874
+ const [globalRoot, cacheRoot] = await Promise.all([cached?.runtime === runtime && cached.globalRoot ? Promise.resolve(cached.globalRoot) : npmConfigValue(["root", "-g"]), cached?.runtime === runtime && cached.cacheRoot ? Promise.resolve(cached.cacheRoot) : npmConfigValue([
875
+ "config",
876
+ "get",
877
+ "cache"
878
+ ])]);
879
+ if (globalRoot || cacheRoot) await patchInstallState(kind, {
880
+ ...cacheRoot ? { npmCache: cacheRoot } : {},
881
+ npmProbe: {
882
+ runtime,
883
+ ...globalRoot ? { globalRoot } : {},
884
+ ...cacheRoot ? { cacheRoot } : {}
885
+ }
886
+ });
887
+ return {
888
+ globalRoot,
889
+ cacheRoot
890
+ };
891
+ }
892
+ /**
893
+ * Classify this process's install origin.
894
+ *
895
+ * Order is significant and cheapest-first:
896
+ *
897
+ * 1. `managed` — a realpath under our own version dir. This must come first and
898
+ * short-circuit the pointer read, or a managed payload would adopt itself.
899
+ * 2. `npm-global` — under `npm root -g`. User decision 4: never duplicated.
900
+ * 3. `npx` — under `<npm cache>/_npx`.
901
+ * 4. `source` — a `.git` beside the package root. Deliberately ahead of the
902
+ * volatility heuristic: a checkout in `/tmp` is still the developer's code.
903
+ * 5. `bunx` — under a `.bunx-*` root, or any other volatile temp root.
904
+ * 6. `unknown` — everything else, including "the package root could not be
905
+ * found". Treated exactly like `source` by every caller.
906
+ */
907
+ async function classifyOrigin() {
908
+ if (cached) return cached;
909
+ const info = await classifyEntry(process.argv[1]);
910
+ cached = info;
911
+ return info;
912
+ }
913
+ /**
914
+ * Classify an arbitrary entry path.
915
+ *
916
+ * Extracted from `classifyOrigin` so the matrix is testable without respawning
917
+ * the test runner with a doctored argv: the classification is pure with respect
918
+ * to `entry`, and the only impurity (two npm probes) is already injectable via
919
+ * the process PATH and the install-state cache.
920
+ */
921
+ async function classifyEntry(entry) {
922
+ if (typeof entry !== "string" || entry.length === 0) return {
923
+ origin: "unknown",
924
+ detail: "no argv[1]; cannot tell where this code lives"
925
+ };
926
+ const packageRoot = findPackageRoot(entry);
927
+ const probe = packageRoot ?? path.dirname(realpathIfPossible(entry));
928
+ if (isUnder(probe, managedRootOf("self")) || isUnder(probe, managedRootOf("pi"))) return {
929
+ origin: "managed",
930
+ packageRoot,
931
+ detail: `running from the managed tree (${probe})`
932
+ };
933
+ const { globalRoot, cacheRoot } = await npmProbes();
934
+ if (globalRoot && isUnder(probe, globalRoot)) return {
935
+ origin: "npm-global",
936
+ packageRoot,
937
+ detail: `running from the global install ${globalRoot}`
938
+ };
939
+ if (cacheRoot && isUnder(probe, path.join(cacheRoot, "_npx"))) return {
940
+ origin: "npx",
941
+ packageRoot,
942
+ detail: `running from the npx cache ${path.join(cacheRoot, "_npx")}`
943
+ };
944
+ if (hasGitAncestor(packageRoot ?? probe)) return {
945
+ origin: "source",
946
+ packageRoot,
947
+ detail: `running from a git checkout (${packageRoot ?? probe})`
948
+ };
949
+ if (isUnderBunCache(probe)) return {
950
+ origin: "bunx",
951
+ packageRoot,
952
+ detail: `running from the bun cache (${BUN_CACHE_HINT})`
953
+ };
954
+ if (probe.includes(`${path.sep}.bunx-`) || isUnderVolatileRoot(probe)) return {
955
+ origin: "bunx",
956
+ packageRoot,
957
+ detail: `running from a volatile bunx/temp tree (${probe})`
958
+ };
959
+ `${probe}`;
960
+ return {
961
+ origin: "unknown",
962
+ packageRoot,
963
+ detail: `unrecognised origin (${probe})`
964
+ };
965
+ }
966
+ /**
967
+ * Whether a `.git` sits at or above `dir`.
968
+ *
969
+ * "Above" matters: in a checkout the package.json IS the repo root, but a
970
+ * monorepo/workspace has the package in a subdirectory with `.git` above it, and
971
+ * a `git worktree` checkout puts `.git` in the parent with a pointer file. All
972
+ * three are the developer's own code.
973
+ *
974
+ * Bounded and non-recursive past the filesystem root; `existsSync` rather than a
975
+ * stat-only check so a `.git` FILE (worktree/submodule) counts too.
976
+ */
977
+ function hasGitAncestor(dir) {
978
+ let cur = dir;
979
+ for (let i = 0; i < 6; i++) {
980
+ if (existsSync(path.join(cur, ".git"))) return true;
981
+ const parent = path.dirname(cur);
982
+ if (parent === cur) return false;
983
+ cur = parent;
984
+ }
985
+ return false;
986
+ }
987
+ /** Where a `bunx` tree lands, for the diagnostic string. */
988
+ const BUN_CACHE_HINT = "$BUN_INSTALL/cache (or ~/.bun/install/cache)";
989
+ /**
990
+ * Whether `dir` is inside bun's shared install cache.
991
+ *
992
+ * Both the cache root and its parent are tested, because bun's layout has been
993
+ * `install/cache/<pkg>@<ver>@@@1` and, in older versions, a sibling directory.
994
+ * Case-insensitive on Windows for the same reason `asPrefix` is.
995
+ */
996
+ function isUnderBunCache(dir) {
997
+ const candidates = [process.env.BUN_INSTALL, process.env.BUN_INSTALL_CACHE_DIR].filter((value) => typeof value === "string" && value.length > 0);
998
+ const roots = /* @__PURE__ */ new Set();
999
+ for (const base of candidates) {
1000
+ roots.add(path.join(base, "cache"));
1001
+ roots.add(path.join(base, "install", "cache"));
1002
+ }
1003
+ const home = os.homedir();
1004
+ if (home) roots.add(path.join(home, ".bun", "install", "cache"));
1005
+ for (const root of roots) if (isUnder(dir, root) || isUnder(realpathIfPossible(dir), realpathIfPossible(root))) return true;
1006
+ return false;
1007
+ }
1008
+ function managedRootOf(kind) {
1009
+ return managedRoot(kind);
1010
+ }
1011
+ /**
1012
+ * Whether this origin should adopt an existing managed install.
1013
+ *
1014
+ * Kept as its own function so the policy is one line to read and one line to
1015
+ * change: only the disposable-copy origins adopt. `npm-global` and `source`
1016
+ * never do (their trees are the owner's), and `unknown` never does.
1017
+ */
1018
+ function shouldAdoptFor(origin) {
1019
+ return origin === "npx" || origin === "bunx";
1020
+ }
1021
+ /**
1022
+ * Reject an entry that would point at the bootstrap or escape the version dir.
1023
+ *
1024
+ * This is not paranoia about our own writer: the pointer is a plain file in a
1025
+ * user-writable directory, and the launcher `import()`s whatever it names. A
1026
+ * relative entry that climbs out (`../../..`) or is absolute would turn a
1027
+ * corrupt pointer into arbitrary code execution on the next launch.
1028
+ */
1029
+ function isSafeEntry(entry) {
1030
+ if (entry.length === 0) return false;
1031
+ if (path.isAbsolute(entry) || entry.startsWith("/") || /^[A-Za-z]:/.test(entry)) return false;
1032
+ const normalized = entry.replace(/\\/g, "/");
1033
+ if (normalized.split("/").some((segment) => segment === "..")) return false;
1034
+ if (normalized === "dist/bin.js" || normalized.endsWith(`/dist/bin.js`)) return false;
1035
+ return true;
1036
+ }
1037
+ function kindOf(value) {
1038
+ return value === "self" || value === "pi" ? value : null;
1039
+ }
1040
+ function nonEmptyString(value) {
1041
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1042
+ }
1043
+ /**
1044
+ * Parse + validate a pointer body. Returns `null` for anything unusable, which
1045
+ * every caller must treat identically to "no managed install".
1046
+ */
1047
+ function parsePointer(raw, kind) {
1048
+ let parsed;
1049
+ try {
1050
+ parsed = JSON.parse(raw);
1051
+ } catch {
1052
+ return null;
1053
+ }
1054
+ if (typeof parsed !== "object" || parsed === null) return null;
1055
+ if (parsed.schemaVersion !== 1) return null;
1056
+ if (kindOf(parsed.kind) !== kind) return null;
1057
+ const version = nonEmptyString(parsed.version);
1058
+ if (!version) return null;
1059
+ if (version.includes("/") || version.includes("\\") || version === "." || version === "..") return null;
1060
+ const entry = nonEmptyString(parsed.entry) ?? entryRelativeFor(kind);
1061
+ if (!isSafeEntry(entry)) return null;
1062
+ return {
1063
+ schemaVersion: 1,
1064
+ kind,
1065
+ version,
1066
+ entry,
1067
+ entryPath: path.join(versionDir(kind, version), entry),
1068
+ runtimeHint: nonEmptyString(parsed.runtimeHint),
1069
+ registry: nonEmptyString(parsed.registry),
1070
+ installedAt: nonEmptyString(parsed.installedAt)
1071
+ };
1072
+ }
1073
+ /**
1074
+ * Read the pointer with the reason it was not usable.
1075
+ *
1076
+ * This is the primitive; `readPointer` is the ergonomic form for callers whose
1077
+ * only decision is "run the payload or not". GC must use this one.
1078
+ */
1079
+ async function readPointerDetailed(kind, opts = {}) {
1080
+ const file = pointerPath(kind);
1081
+ let raw;
1082
+ try {
1083
+ raw = await readFileWithRetry(file, { retryMissing: false });
1084
+ } catch (err) {
1085
+ if (err.code === "ENOENT") return {
1086
+ status: "absent",
1087
+ pointer: null
1088
+ };
1089
+ onReadError(kind, err);
1090
+ return {
1091
+ status: "unreadable",
1092
+ pointer: null
1093
+ };
1094
+ }
1095
+ const pointer = parsePointer(raw, kind);
1096
+ if (!pointer) {
1097
+ onInvalid(kind, file);
1098
+ return {
1099
+ status: "absent",
1100
+ pointer: null
1101
+ };
1102
+ }
1103
+ if (opts.verifyEntry === false) return {
1104
+ status: "ok",
1105
+ pointer
1106
+ };
1107
+ try {
1108
+ if (!(await fs.stat(pointer.entryPath)).isFile()) {
1109
+ onMissingEntry(kind, pointer);
1110
+ return {
1111
+ status: "absent",
1112
+ pointer: null
1113
+ };
1114
+ }
1115
+ } catch {
1116
+ onMissingEntry(kind, pointer);
1117
+ return {
1118
+ status: "absent",
1119
+ pointer: null
1120
+ };
1121
+ }
1122
+ return {
1123
+ status: "ok",
1124
+ pointer
1125
+ };
1126
+ }
1127
+ /**
1128
+ * Read the pointer, or `null`.
1129
+ *
1130
+ * A missing file is the normal first-run answer. Any other read error is a
1131
+ * debug-level event, never a throw: a launch must not die because the pointer
1132
+ * is unreadable, and the caller's fallback (run from the current tree) is always
1133
+ * correct. The entry is stat'd by default, so a pointer to a GC'd or
1134
+ * half-published payload is also reported as absent.
1135
+ *
1136
+ * Callers that DESTROY something based on this answer must use
1137
+ * `readPointerDetailed` instead — see `PointerReadStatus`.
1138
+ */
1139
+ async function readPointer(kind, opts = {}) {
1140
+ return (await readPointerDetailed(kind, opts)).pointer;
1141
+ }
1142
+ function onReadError(kind, err) {
1143
+ `${kind}${err instanceof Error ? err.message : String(err)}`;
1144
+ }
1145
+ function onInvalid(kind, file) {
1146
+ `${kind}${file}`;
1147
+ }
1148
+ function onMissingEntry(kind, pointer) {
1149
+ `${kind}${pointer.version}${pointer.entryPath}`;
1150
+ }
1151
+ // src/lib/managed-install/npm-env.ts
1152
+ /**
1153
+ * Whether a managed install may run at all in this process.
1154
+ *
1155
+ * `GH_ROUTER_NO_MANAGED_INSTALL` is the user's off switch (documented in the
1156
+ * plan); `ghRouterNoManagedInstall()` is the only place that reads it so the
1157
+ * bootstrap, the CLI, and the tests cannot disagree about its spelling.
1158
+ */
1159
+ function managedInstallDisabled(env = process.env) {
1160
+ const raw = env.GH_ROUTER_NO_MANAGED_INSTALL?.trim().toLowerCase();
1161
+ return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
1162
+ }
1163
+ // src/lib/managed-install/bootstrap.ts
1164
+ /**
1165
+ * The bootstrap decision: "run me, or hand off?"
1166
+ *
1167
+ * `dist/bin.js` is the published `bin`, so it runs on EVERY invocation — including
1168
+ * the ~13 per-turn Claude Code hooks. That makes this file's job narrow and its
1169
+ * cost budget tight: decide in a few milliseconds, then get out of the way.
1170
+ *
1171
+ * The decision itself is pure (`decideBootstrap` takes its inputs, returns a
1172
+ * plan), because the alternative — asserting behaviour by spawning the real CLI
1173
+ * and parsing logs — cannot reach the interesting cases (a managed pointer whose
1174
+ * payload was reaped, a re-exec that must preserve a signal death).
1175
+ *
1176
+ * ### Why re-exec instead of adopting in-process
1177
+ *
1178
+ * `main.ts` prints the banner (`:45`) and computes the version (`:16`) at module
1179
+ * scope, so an in-process adoption could only happen *after* the npx copy had
1180
+ * already evaluated citty/consola and printed its own banner: two banners, two
1181
+ * module graphs, and duplicated singletons (`state.ts`, `mcp-inflight.ts`, the
1182
+ * keep-awake refcount, the launch registry). Rewriting `argv[1]` first is worse —
1183
+ * it mutates a global before a fallible import, leaving argv pointing into the
1184
+ * managed tree while npx code runs.
1185
+ *
1186
+ * Re-exec makes `argv[1]` correct by construction, so `packageRoot()`,
1187
+ * `currentInvocation()`, and the self-respawn sites need no changes at all. The
1188
+ * cost is one extra runtime start (~40 ms) against a solved 3 s problem.
1189
+ *
1190
+ * ### The three things that must NOT re-exec
1191
+ *
1192
+ * - **`internal-*` subcommands.** They run per turn; an extra hop each time is a
1193
+ * fifth of a second per turn, and they must run the code the session already
1194
+ * validated rather than whatever is live now.
1195
+ * - **`update`.** It is the repair tool. Bootstrapping it would make a broken
1196
+ * pointer unrepairable, and the background child re-entering this file would
1197
+ * spawn itself forever.
1198
+ * - **A missing/nonexistent payload.** Falling back to the current tree is always
1199
+ * correct; re-exec into a hole is not.
1200
+ */
1201
+ /**
1202
+ * Subcommands that must never take the hand-off path.
1203
+ *
1204
+ * `internal-*` is a prefix, not a list: a new hook subcommand added to
1205
+ * `main.ts` should inherit the rule without editing this file.
1206
+ */
1207
+ function mustRunInline(subcommand) {
1208
+ if (!subcommand) return null;
1209
+ if (subcommand.startsWith("internal-")) return "internal hook (per-turn hot path)";
1210
+ if (subcommand === "update") return "update is the repair tool";
1211
+ return null;
1212
+ }
1213
+ /**
1214
+ * Decide what `dist/bin.js` should do, given the argv it was started with.
1215
+ *
1216
+ * Returns `passthrough` for every origin that owns its own tree (`npm-global`,
1217
+ * `source`, `managed`, `unknown`): user decision 4 is that a global install is
1218
+ * never duplicated, and a dev checkout must run its own code.
1219
+ */
1220
+ async function decideBootstrap(inputs) {
1221
+ const env = inputs.env ?? process.env;
1222
+ const argv = inputs.argv;
1223
+ const terminator = argv.indexOf("--");
1224
+ const subcommand = (terminator >= 0 ? argv.slice(0, terminator) : argv).find((arg) => !arg.startsWith("-"));
1225
+ if (managedInstallDisabled(env)) return {
1226
+ action: "passthrough",
1227
+ reason: "GH_ROUTER_NO_MANAGED_INSTALL is set"
1228
+ };
1229
+ if (argv.includes("--no-managed-install")) return {
1230
+ action: "passthrough",
1231
+ reason: "--no-managed-install"
1232
+ };
1233
+ if (env.GH_ROUTER_MANAGED_BACKGROUND === "1") return {
1234
+ action: "passthrough",
1235
+ reason: "background child; bootstrap already decided"
1236
+ };
1237
+ const inline = mustRunInline(subcommand);
1238
+ if (inline) return {
1239
+ action: "passthrough",
1240
+ reason: inline
1241
+ };
1242
+ const entry = inputs.entry ?? argvEntry();
1243
+ const origin = await classifyEntry(entry);
1244
+ if (origin.origin === "managed") return {
1245
+ action: "passthrough",
1246
+ reason: "already running from the managed tree"
1247
+ };
1248
+ if (!shouldAdoptFor(origin.origin)) return {
1249
+ action: "passthrough",
1250
+ reason: `origin is ${origin.origin}; this tree owns itself`
1251
+ };
1252
+ const pointer = await readPointer("self");
1253
+ if (pointer) return {
1254
+ action: "reexec",
1255
+ entryPath: pointer.entryPath,
1256
+ version: pointer.version,
1257
+ reason: `managed ${pointer.version} is live`
1258
+ };
1259
+ if (!entry) return {
1260
+ action: "passthrough",
1261
+ reason: "no argv[1]; cannot schedule an install"
1262
+ };
1263
+ const state = await readInstallState("self");
1264
+ if (!mayAttemptNow(state)) return {
1265
+ action: "passthrough",
1266
+ reason: `managed install backing off until ${state.nextAttemptAt}`
1267
+ };
1268
+ return {
1269
+ action: "schedule",
1270
+ reason: "no managed install yet",
1271
+ updaterEntry: entry
1272
+ };
1273
+ }
1274
+ /** `process.argv[1]` when it looks usable. */
1275
+ function argvEntry() {
1276
+ const entry = process.argv[1];
1277
+ return typeof entry === "string" && entry.length > 0 && path.isAbsolute(entry) ? entry : void 0;
1278
+ }
1279
+ /**
1280
+ * Reserve a background attempt and stamp the origin.
1281
+ *
1282
+ * Written BEFORE the spawn (optimistic) so a second `npx github-router@latest`
1283
+ * a minute later sees the reservation and waits, instead of starting a competing
1284
+ * npm install over the same prefix.
1285
+ *
1286
+ * Deliberately NOT `nextAttemptAt`: a reservation must never become a backoff
1287
+ * window, or a spawn that fails outright (ENOMEM, a deleted `process.execPath`)
1288
+ * would silence the next launch for an hour without npm ever having run. The
1289
+ * cheap-and-honest split is: this file records only that an attempt was QUEUED
1290
+ * (`lastAttemptAt`, `lastOrigin`), and the child records success or failure when
1291
+ * it has something real to report. Stamp-per-spawn would move the write after the
1292
+ * spawn it is supposed to guard (a rival launch can win that window), and buys
1293
+ * nothing the model above does not already give.
1294
+ */
1295
+ async function reserveBackgroundAttempt(origin) {
1296
+ await patchInstallState("self", {
1297
+ lastAttemptAt: (/* @__PURE__ */ new Date()).toISOString(),
1298
+ lastOrigin: origin
1299
+ });
1300
+ }
1301
+ /**
1302
+ * The argv the detached background child runs. Exported so a test can pin it.
1303
+ *
1304
+ * `--no-optional` is deliberate: the optional payloads are up to 547 MB, and a
1305
+ * detached child that the user never sees must not start downloading them. They
1306
+ * are installed by an explicit `github-router update` (or on demand, from the
1307
+ * feature that needs one).
1308
+ */
1309
+ const BACKGROUND_UPDATE_ARGS = [
1310
+ "update",
1311
+ "--self",
1312
+ "--quiet",
1313
+ "--no-optional"
1314
+ ];
1315
+ // src/bin.ts
1316
+ /**
1317
+ * The published `bin` entry — `dist/bin.js`.
1318
+ *
1319
+ * Runs on every invocation, including the ~13 per-turn Claude Code hooks, so it
1320
+ * must be cheap and must never change behaviour for a tree that owns itself.
1321
+ * `lib/managed-install/bootstrap.ts` holds the whole decision (and its rationale);
1322
+ * this file only executes the plan.
1323
+ *
1324
+ * Two mechanical constraints on the code below:
1325
+ *
1326
+ * 1. **`main.js` is imported DYNAMICALLY and by a computed specifier.** A static
1327
+ * `import "./main.js"` would be folded into this bundle by tsdown, which would
1328
+ * make `dist/bin.js` the entire 40 MB app and defeat the point of a bootstrap
1329
+ * that can hand off before the app graph loads. The computed string keeps it a
1330
+ * runtime import.
1331
+ * 2. **Nothing here throws.** A bootstrap failure must degrade to "run this
1332
+ * tree", never to "the CLI is broken". Every step is wrapped, and the fallback
1333
+ * is always `import` of this tree's own entry.
1334
+ */
1335
+ /** `SIGINT`→2 etc., for the 128+n convention when a re-raise is not possible. */
1336
+ const SIGNAL_NUMBERS = {
1337
+ SIGHUP: 1,
1338
+ SIGINT: 2,
1339
+ SIGTERM: 15
1340
+ };
1341
+ /**
1342
+ * Run this tree's real entry.
1343
+ *
1344
+ * The specifier is built at RUNTIME from `import.meta.url`, and that is not
1345
+ * decoration: a literal `import("./main.js")` — or even `./${"main"}.js`, which
1346
+ * rolldown folds statically — is inlined by the bundler, which turns
1347
+ * `dist/bin.js` into a second copy of the whole app (measured: 13.4 MB and the
1348
+ * full tree-sitter/transformers graph). A `URL` is opaque to the bundler, so the
1349
+ * import stays a real runtime module load and `dist/bin.js` stays a few KB.
1350
+ */
1351
+ async function runThisTree() {
1352
+ await import(new URL("./main.js", import.meta.url).href);
1353
+ }
1354
+ /**
1355
+ * Hand off to the managed payload.
1356
+ *
1357
+ * Re-exec rather than in-process adoption: `main.ts` prints its banner and reads
1358
+ * its version at module scope, so adopting after this module has already been
1359
+ * evaluated would print two banners and evaluate two module graphs. `stdio:
1360
+ * "inherit"` keeps the caller's pipes (a hook's stdout IS its payload), and the
1361
+ * child's exit code and signal are propagated verbatim so a supervisor sees the
1362
+ * real outcome.
1363
+ */
1364
+ async function handOff(entryPath, version) {
1365
+ const SIGNALS = [
1366
+ "SIGINT",
1367
+ "SIGTERM",
1368
+ "SIGHUP"
1369
+ ];
1370
+ const dropForwarders = () => {
1371
+ for (const name of SIGNALS) process.removeAllListeners(name);
1372
+ };
1373
+ let child = null;
1374
+ for (const signal of SIGNALS) process.on(signal, () => {
1375
+ try {
1376
+ child?.kill(signal);
1377
+ } catch {}
1378
+ });
1379
+ try {
1380
+ child = spawn(process.execPath, [entryPath, ...process.argv.slice(2)], {
1381
+ stdio: "inherit",
1382
+ windowsHide: true,
1383
+ env: {
1384
+ ...process.env,
1385
+ GH_ROUTER_MANAGED_HANDOFF: version
1386
+ }
1387
+ });
1388
+ } catch (err) {
1389
+ dropForwarders();
1390
+ throw err;
1391
+ }
1392
+ await new Promise((resolve, reject) => {
1393
+ child.on("error", (err) => {
1394
+ dropForwarders();
1395
+ reject(err);
1396
+ });
1397
+ child.on("exit", (code, signal) => {
1398
+ dropForwarders();
1399
+ if (signal) {
1400
+ process.exitCode = 128 + (SIGNAL_NUMBERS[signal] ?? 0);
1401
+ try {
1402
+ process.kill(process.pid, signal);
1403
+ return;
1404
+ } catch {
1405
+ resolve();
1406
+ return;
1407
+ }
1408
+ }
1409
+ process.exitCode = typeof code === "number" ? code : 1;
1410
+ resolve();
1411
+ });
1412
+ });
1413
+ }
1414
+ /**
1415
+ * Queue the background install.
1416
+ *
1417
+ * Detached and unref'd: this launch must not be delayed by, or kept alive for, an
1418
+ * npm install. The child is `node <this entry> update --self --quiet`, which
1419
+ * reaches the same code with `GH_ROUTER_MANAGED_BACKGROUND=1` so it cannot recurse
1420
+ * into another spawn.
1421
+ */
1422
+ function scheduleBackgroundInstall(entry) {
1423
+ try {
1424
+ const child = spawn(process.execPath, [entry, ...BACKGROUND_UPDATE_ARGS], {
1425
+ detached: true,
1426
+ stdio: "ignore",
1427
+ windowsHide: true,
1428
+ env: {
1429
+ ...process.env,
1430
+ GH_ROUTER_MANAGED_BACKGROUND: "1"
1431
+ }
1432
+ });
1433
+ child.on("error", () => {});
1434
+ child.unref();
1435
+ } catch {}
1436
+ }
1437
+ async function main() {
1438
+ let plan;
1439
+ try {
1440
+ plan = await decideBootstrap({
1441
+ argv: process.argv.slice(2),
1442
+ entry: argvEntry()
1443
+ });
1444
+ } catch {
1445
+ await runThisTree();
1446
+ return;
1447
+ }
1448
+ if (plan.action === "reexec") try {
1449
+ await handOff(plan.entryPath, plan.version);
1450
+ return;
1451
+ } catch {
1452
+ await runThisTree();
1453
+ return;
1454
+ }
1455
+ if (plan.action === "schedule") {
1456
+ try {
1457
+ await reserveBackgroundAttempt((await classifyOrigin()).origin);
1458
+ } catch {}
1459
+ scheduleBackgroundInstall(plan.updaterEntry);
1460
+ }
1461
+ await runThisTree();
1462
+ }
1463
+ /**
1464
+ * Top-level guard.
1465
+ *
1466
+ * `runThisTree` is the one thing that must happen; if the bootstrap itself is
1467
+ * broken (an unreadable app dir, a corrupt state file that somehow throws), the
1468
+ * user still gets a working CLI. Deliberately `console.error` rather than
1469
+ * `consola`: the app graph has not loaded yet and pulling it in here would
1470
+ * reintroduce the double-instance hazard.
1471
+ */
1472
+ main().catch((err) => {
1473
+ const message = err instanceof Error ? err.message : String(err);
1474
+ console.error(`github-router: bootstrap fell back to this tree (${message})`);
1475
+ process.exitCode = 1;
1476
+ });
1477
+ export {};
1478
+
1479
+ //# sourceMappingURL=bin.js.map