github-router 0.3.378 → 0.3.380
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -0
- package/dist/ado-tools-CsfbnY8x.js +1 -0
- package/dist/{aic-ledger-CeSXqTEE.js → aic-ledger-6GKI28nY.js} +3 -3
- package/dist/{aic-ledger-CeSXqTEE.js.map → aic-ledger-6GKI28nY.js.map} +1 -1
- package/dist/{aic-statusline-settings-BKveu679.js → aic-statusline-settings-wLL1l_Z6.js} +2 -2
- package/dist/{aic-statusline-settings-BKveu679.js.map → aic-statusline-settings-wLL1l_Z6.js.map} +1 -1
- package/dist/atomic-file-Dif1kLKM.js +198 -0
- package/dist/atomic-file-Dif1kLKM.js.map +1 -0
- package/dist/{attribution-settings-BR5Umj2L.js → attribution-settings-BJ1fjX7V.js} +10 -10
- package/dist/{attribution-settings-BR5Umj2L.js.map → attribution-settings-BJ1fjX7V.js.map} +1 -1
- package/dist/{auth-BZHpTtfF.js → auth-5TKcQbbH.js} +3 -3
- package/dist/{auth-BZHpTtfF.js.map → auth-5TKcQbbH.js.map} +1 -1
- package/dist/bin.js +1479 -0
- package/dist/bin.js.map +1 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-BlIWDuV2.js → check-usage-DM39fdel.js} +4 -4
- package/dist/{check-usage-BlIWDuV2.js.map → check-usage-DM39fdel.js.map} +1 -1
- package/dist/{claude--4O3wHRq.js → claude-BWwkOMi3.js} +26 -25
- package/dist/{claude--4O3wHRq.js.map → claude-BWwkOMi3.js.map} +1 -1
- package/dist/{claude-md-injection-Biq_Xhve.js → claude-md-injection-DNMDcw1W.js} +15 -24
- package/dist/claude-md-injection-DNMDcw1W.js.map +1 -0
- package/dist/{codex-DHRMLpSo.js → codex-C6ix3BaY.js} +8 -7
- package/dist/{codex-DHRMLpSo.js.map → codex-C6ix3BaY.js.map} +1 -1
- package/dist/{copilot-discount-UXC6NQbN.js → copilot-discount-DM98PuAF.js} +2 -2
- package/dist/{copilot-discount-UXC6NQbN.js.map → copilot-discount-DM98PuAF.js.map} +1 -1
- package/dist/{debug-1HUHCWFl.js → debug-Df0Kuzi3.js} +2 -2
- package/dist/{debug-1HUHCWFl.js.map → debug-Df0Kuzi3.js.map} +1 -1
- package/dist/diagnostics-cXjCT_JQ.js +12 -0
- package/dist/diagnostics-cXjCT_JQ.js.map +1 -0
- package/dist/engine-B6la_uIW.js +1 -0
- package/dist/{gate-discovery-DjH9YXoN.js → gate-discovery-2ILpM2fi.js} +5 -5
- package/dist/{gate-discovery-DjH9YXoN.js.map → gate-discovery-2ILpM2fi.js.map} +1 -1
- package/dist/{get-copilot-usage-CKg42gSH.js → get-copilot-usage-BZ6t2hFZ.js} +2 -2
- package/dist/{get-copilot-usage-CKg42gSH.js.map → get-copilot-usage-BZ6t2hFZ.js.map} +1 -1
- package/dist/hooks.mjs +13 -0
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-sKwchRJz.js → index-cmd-DsK6VFs8.js} +4 -4
- package/dist/{index-cmd-sKwchRJz.js.map → index-cmd-DsK6VFs8.js.map} +1 -1
- package/dist/{internal-aic-status-B_hEeM37.js → internal-aic-status-CUZ7-trf.js} +3 -3
- package/dist/{internal-aic-status-B_hEeM37.js.map → internal-aic-status-CUZ7-trf.js.map} +1 -1
- package/dist/{internal-artifact-open-DbHjipxU.js → internal-artifact-open-DRBg1PpV.js} +2 -2
- package/dist/{internal-artifact-open-DbHjipxU.js.map → internal-artifact-open-DRBg1PpV.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-DMzqs-r8.js → internal-fast-dispatch-guard-D6-Ees_6.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js → internal-fast-dispatch-guard-ZeS9u0A3.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-PDdlkPU3.js.map → internal-fast-dispatch-guard-ZeS9u0A3.js.map} +1 -1
- package/dist/{internal-first-mate-guard-BxPDUsV3.js → internal-first-mate-guard-BijeVpi9.js} +1 -1
- package/dist/{internal-first-mate-guard-4Yro9xNM.js → internal-first-mate-guard-DsEEsLKJ.js} +3 -3
- package/dist/{internal-first-mate-guard-4Yro9xNM.js.map → internal-first-mate-guard-DsEEsLKJ.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-0teaxIc1.js → internal-max-dispatch-guard-4RLca1i5.js} +2 -2
- package/dist/{internal-max-dispatch-guard-0teaxIc1.js.map → internal-max-dispatch-guard-4RLca1i5.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-5LSaHN_y.js → internal-max-dispatch-guard-DeEfWqfP.js} +1 -1
- package/dist/{internal-plan-review-BfHLeszV.js → internal-plan-review-bzqGNdtw.js} +3 -3
- package/dist/{internal-plan-review-BfHLeszV.js.map → internal-plan-review-bzqGNdtw.js.map} +1 -1
- package/dist/{internal-prompt-submit-BixNLmM3.js → internal-prompt-submit-BZ2-CExM.js} +4 -4
- package/dist/{internal-prompt-submit-BixNLmM3.js.map → internal-prompt-submit-BZ2-CExM.js.map} +1 -1
- package/dist/{internal-prompt-submit-Ou8xtRXj.js → internal-prompt-submit-ZBhH-SQ1.js} +2 -2
- package/dist/{internal-rebrief-BBGM0PMv.js → internal-rebrief-BIWbN7Sr.js} +4 -4
- package/dist/{internal-rebrief-BBGM0PMv.js.map → internal-rebrief-BIWbN7Sr.js.map} +1 -1
- package/dist/{internal-session-bind-pN1V11Mn.js → internal-session-bind-BL6hFRLO.js} +2 -2
- package/dist/{internal-session-bind-pN1V11Mn.js.map → internal-session-bind-BL6hFRLO.js.map} +1 -1
- package/dist/{internal-stop-hook-DO9Iiaes.js → internal-stop-hook-cDF1MuJZ.js} +5 -5
- package/dist/{internal-stop-hook-DO9Iiaes.js.map → internal-stop-hook-cDF1MuJZ.js.map} +1 -1
- package/dist/{internal-stop-review-BWp-4XWW.js → internal-stop-review-y8zjpK_3.js} +2 -2
- package/dist/{internal-stop-review-BWp-4XWW.js.map → internal-stop-review-y8zjpK_3.js.map} +1 -1
- package/dist/{internal-worker-guard-C9OZPgzu.js → internal-worker-guard-DdyYBZR0.js} +2 -2
- package/dist/{internal-worker-guard-C9OZPgzu.js.map → internal-worker-guard-DdyYBZR0.js.map} +1 -1
- package/dist/{internal-workspace-header-B4TXFBLU.js → internal-workspace-header-BMKbO8yX.js} +2 -2
- package/dist/{internal-workspace-header-B4TXFBLU.js.map → internal-workspace-header-BMKbO8yX.js.map} +1 -1
- package/dist/lib/tree-sitter-pool/worker.js +268 -21
- package/dist/lifecycle-BOjgq9_l.js +1 -0
- package/dist/{lifecycle-vjHAFCaY.js → lifecycle-BlC_kzNt.js} +2 -2
- package/dist/{lifecycle-vjHAFCaY.js.map → lifecycle-BlC_kzNt.js.map} +1 -1
- package/dist/{lifecycle-Dh9y8OF1.js → lifecycle-COZhARmE.js} +2 -2
- package/dist/{lifecycle-Dh9y8OF1.js.map → lifecycle-COZhARmE.js.map} +1 -1
- package/dist/lifecycle-NQvr4flt.js +1 -0
- package/dist/main.js +39 -24
- package/dist/main.js.map +1 -1
- package/dist/{mcp-workspace-header-C5-dOWNa.js → mcp-workspace-header-Bpa4BId8.js} +2 -2
- package/dist/{mcp-workspace-header-C5-dOWNa.js.map → mcp-workspace-header-Bpa4BId8.js.map} +1 -1
- package/dist/{models-B6nH1sS6.js → models-BDV-YLf2.js} +3 -3
- package/dist/{models-B6nH1sS6.js.map → models-BDV-YLf2.js.map} +1 -1
- package/dist/npm-env-H60tX76c.js +130 -0
- package/dist/npm-env-H60tX76c.js.map +1 -0
- package/dist/optional-DGAeyguL.js +586 -0
- package/dist/optional-DGAeyguL.js.map +1 -0
- package/dist/{orchestration-B93jxrWI.js → orchestration-Bto5Nc1Y.js} +2 -2
- package/dist/{orchestration-B93jxrWI.js.map → orchestration-Bto5Nc1Y.js.map} +1 -1
- package/dist/origin-BXtpcKP9.js +382 -0
- package/dist/origin-BXtpcKP9.js.map +1 -0
- package/dist/origin-DbFUCiGp.js +1 -0
- package/dist/paths-CquOjytP.js +1 -0
- package/dist/paths-DK_b2ihK.js +176 -0
- package/dist/paths-DK_b2ihK.js.map +1 -0
- package/dist/{paths-CVEO8jEH.js → paths-DeFmYJhO.js} +16 -3
- package/dist/paths-DeFmYJhO.js.map +1 -0
- package/dist/{peer-mcp-personas-OWsSm6To.js → peer-mcp-personas-Dny0r5Am.js} +14 -14
- package/dist/{peer-mcp-personas-OWsSm6To.js.map → peer-mcp-personas-Dny0r5Am.js.map} +1 -1
- package/dist/{pi-B0EFY6l7.js → pi-YhoA26wi.js} +718 -119
- package/dist/pi-YhoA26wi.js.map +1 -0
- package/dist/pi-foreign-artifacts-CNt6wQ1P.js +660 -0
- package/dist/pi-foreign-artifacts-CNt6wQ1P.js.map +1 -0
- package/dist/pi-memory-bridge-BxmCIIbk.js +618 -0
- package/dist/pi-memory-bridge-BxmCIIbk.js.map +1 -0
- package/dist/pi-memory-bridge-D5A0h_Kf.js +1 -0
- package/dist/pi-version-check-BeBB0Ny9.js +551 -0
- package/dist/pi-version-check-BeBB0Ny9.js.map +1 -0
- package/dist/pi-version-check-D5RvdLsG.js +1 -0
- package/dist/{plan-review-hook-MhjK92wq.js → plan-review-hook-D_yyjOgO.js} +3 -3
- package/dist/{plan-review-hook-MhjK92wq.js.map → plan-review-hook-D_yyjOgO.js.map} +1 -1
- package/dist/{provision-DPL8aGe2.js → provision-BWtuDq_v.js} +30 -36
- package/dist/provision-BWtuDq_v.js.map +1 -0
- package/dist/rerank-cross-encoder-BhjImuwG.js +192 -0
- package/dist/rerank-cross-encoder-BhjImuwG.js.map +1 -0
- package/dist/{self-invocation-DMUnXVGT.js → self-invocation-Dnq4iVD6.js} +4 -31
- package/dist/{self-invocation-DMUnXVGT.js.map → self-invocation-Dnq4iVD6.js.map} +1 -1
- package/dist/{serve-C13q-9w0.js → serve-DrHAX2Bh.js} +15 -14
- package/dist/{serve-C13q-9w0.js.map → serve-DrHAX2Bh.js.map} +1 -1
- package/dist/{server-setup-CptI7SUT.js → server-setup-DLwejgVA.js} +12 -638
- package/dist/server-setup-DLwejgVA.js.map +1 -0
- package/dist/{service-backend-Cdgz6WPx.js → service-backend-BdhWVRSz.js} +17 -62
- package/dist/service-backend-BdhWVRSz.js.map +1 -0
- package/dist/{start-DioCGjM8.js → start-DvV3Lbwy.js} +5 -4
- package/dist/{start-DioCGjM8.js.map → start-DvV3Lbwy.js.map} +1 -1
- package/dist/{static-context-pack-CtnBwHSd.js → static-context-pack-BKFelEbM.js} +3 -3
- package/dist/{static-context-pack-CtnBwHSd.js.map → static-context-pack-BKFelEbM.js.map} +1 -1
- package/dist/{stop-gate-hook-CBVLD8iB.js → stop-gate-hook-DBOj0TqL.js} +3 -3
- package/dist/{stop-gate-hook-CBVLD8iB.js.map → stop-gate-hook-DBOj0TqL.js.map} +1 -1
- package/dist/{stop-gate-policy-BehNiNix.js → stop-gate-policy-Bp2wGh_W.js} +2 -2
- package/dist/{stop-gate-policy-BehNiNix.js.map → stop-gate-policy-Bp2wGh_W.js.map} +1 -1
- package/dist/{token-CPzYxU4Y.js → token-CKPOBdO0.js} +23 -88
- package/dist/{token-CPzYxU4Y.js.map → token-CKPOBdO0.js.map} +1 -1
- package/dist/{token-DHEkiO4g.js → token-Ygd7D32L.js} +3 -3
- package/dist/{token-DHEkiO4g.js.map → token-Ygd7D32L.js.map} +1 -1
- package/dist/update-CB21YRKz.js +1 -0
- package/dist/update-T1L7yFon.js +1548 -0
- package/dist/update-T1L7yFon.js.map +1 -0
- package/dist/update-fEgWTrIx.js +214 -0
- package/dist/update-fEgWTrIx.js.map +1 -0
- package/dist/update-lock-BeS_WmC8.js +1 -0
- package/dist/update-lock-BmXx6QaR.js +171 -0
- package/dist/update-lock-BmXx6QaR.js.map +1 -0
- package/dist/volatile-root-DQNNvQ7Z.js +50 -0
- package/dist/volatile-root-DQNNvQ7Z.js.map +1 -0
- package/dist/{worker-dispatch-C7RtNOXv.js → worker-dispatch-DBWKTMda.js} +2 -2
- package/dist/{worker-dispatch-C7RtNOXv.js.map → worker-dispatch-DBWKTMda.js.map} +1 -1
- package/dist/{workiq-CQauEAMc.js → workiq-D5b7xlbr.js} +2 -2
- package/dist/{workiq-CQauEAMc.js.map → workiq-D5b7xlbr.js.map} +1 -1
- package/dist/{workiq-tools-DL6rC4bP.js → workiq-tools-DdiQ2DOW.js} +1 -1
- package/package.json +16 -4
- package/dist/ado-tools-CRkyU51J.js +0 -1
- package/dist/claude-md-injection-Biq_Xhve.js.map +0 -1
- package/dist/engine-V46un8Xl.js +0 -1
- package/dist/lifecycle-BENRuuX6.js +0 -1
- package/dist/lifecycle-Dli9vGI2.js +0 -1
- package/dist/paths-Be9_ujQ3.js +0 -1
- package/dist/paths-CVEO8jEH.js.map +0 -1
- package/dist/pi-B0EFY6l7.js.map +0 -1
- package/dist/pi-memory-bridge-Dvj1T3e3.js +0 -403
- package/dist/pi-memory-bridge-Dvj1T3e3.js.map +0 -1
- package/dist/provision-DPL8aGe2.js.map +0 -1
- package/dist/rerank-cross-encoder-B87lZgvc.js +0 -110
- package/dist/rerank-cross-encoder-B87lZgvc.js.map +0 -1
- package/dist/server-setup-CptI7SUT.js.map +0 -1
- package/dist/service-backend-Cdgz6WPx.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"update-T1L7yFon.js","names":["fs","fs","fs","fs"],"sources":["../src/lib/managed-install/pointer.ts","../src/lib/managed-install/install.ts","../src/lib/managed-install/launcher.ts","../src/lib/managed-install/shim.ts","../src/lib/managed-install/update.ts"],"sourcesContent":["/**\n * The managed-install pointer: `m/<kind>/current.json`.\n *\n * This is the ONE mutable thing in the layout, and every design constraint here\n * comes from a measured failure:\n *\n * - **It is a file, not a directory or a junction.** On Windows,\n * `MoveFileExW(MOVEFILE_REPLACE_EXISTING)` cannot replace a directory or a\n * reparse point, so swapping a live `current/` directory works on first\n * install and fails `EPERM` on every update — and the `rmdir` + `rename`\n * fallback is non-atomic across exactly the window the ~13 per-turn\n * `internal-*` hooks fire. A file-over-file rename is supported everywhere.\n * - **A bad pointer must never be fatal.** A launch that cannot resolve its\n * payload must fall back to \"no managed install\" and run from whatever tree it\n * already has. So every parse failure, unknown schema version, missing field,\n * and missing entry resolves to `null`, and the caller treats that as absent.\n * - **Readers retry through a racing rename**, so the pointer is read via\n * `readFileWithRetry` rather than raw `readFile`: a reader can legitimately see\n * `ENOENT`/`EBUSY` for a microsecond after a writer's rename.\n *\n * ### What the pointer must NOT say\n *\n * The published bin is the bootstrap (`dist/bin.js`), so anything that resolves\n * \"the bin target from package.json\" would write a pointer to the bootstrap and\n * exec itself in a loop. `entry` is therefore the **app entry**, checked against\n * the installed tree, and `resolvePointer` refuses a pointer whose entry is the\n * bootstrap.\n *\n * ### `runtimeHint` is a hint\n *\n * Recording an absolute `node` path as authoritative is the \"`claude` vanished\n * after a node upgrade\" bug: nvm/fnm/volta/brew all delete the previous\n * interpreter, and a shim written once would then fail forever. The pointer\n * records what ran the install for diagnostics and fallback, and the launcher\n * resolves the runtime at run time.\n */\n\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport { readFileWithRetry, writeFileAtomic } from \"../atomic-file\"\nimport { reportManagedDiagnostic } from \"./diagnostics\"\nimport {\n type ManagedKind,\n entryRelativeFor,\n installedMarkerPath,\n pointerPath,\n versionDir,\n} from \"./paths\"\n\nexport const POINTER_SCHEMA_VERSION = 1\n\n/** The bootstrap entry, never a valid payload entry. */\nexport const BOOTSTRAP_ENTRY = \"dist/bin.js\"\n\nexport interface ManagedPointer {\n schemaVersion: number\n kind: ManagedKind\n version: string\n /** Path INSIDE the version dir, e.g. `node_modules/github-router/dist/main.js`. */\n entry: string\n /** Absolute path of the payload entry, derived; never trusted from disk alone. */\n entryPath: string\n /** The runtime that performed the install. Diagnostics + last-resort fallback. */\n runtimeHint?: string\n registry?: string\n installedAt?: string\n}\n\n/** On-disk shape. Kept separate so validation is explicit about optionality. */\ninterface PointerFile {\n schemaVersion?: unknown\n kind?: unknown\n version?: unknown\n entry?: unknown\n runtimeHint?: unknown\n registry?: unknown\n installedAt?: unknown\n}\n\nexport interface WritePointerParams {\n kind: ManagedKind\n version: string\n /** Relative entry. Defaults to the kind's known entry. */\n entry?: string\n runtimeHint?: string\n registry?: string\n installedAt?: string\n}\n\n/**\n * Reject an entry that would point at the bootstrap or escape the version dir.\n *\n * This is not paranoia about our own writer: the pointer is a plain file in a\n * user-writable directory, and the launcher `import()`s whatever it names. A\n * relative entry that climbs out (`../../..`) or is absolute would turn a\n * corrupt pointer into arbitrary code execution on the next launch.\n */\nexport function isSafeEntry(entry: string): boolean {\n if (entry.length === 0) return false\n if (path.isAbsolute(entry) || entry.startsWith(\"/\") || /^[A-Za-z]:/.test(entry)) return false\n // Reject both separators regardless of platform: a pointer written on POSIX\n // can be read by a Windows install (roaming profile) and vice versa.\n const normalized = entry.replace(/\\\\/g, \"/\")\n if (normalized.split(\"/\").some((segment) => segment === \"..\")) return false\n if (normalized === BOOTSTRAP_ENTRY || normalized.endsWith(`/${BOOTSTRAP_ENTRY}`)) return false\n return true\n}\n\nfunction kindOf(value: unknown): ManagedKind | null {\n return value === \"self\" || value === \"pi\" ? value : null\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined\n}\n\n/**\n * Parse + validate a pointer body. Returns `null` for anything unusable, which\n * every caller must treat identically to \"no managed install\".\n */\nexport function parsePointer(raw: string, kind: ManagedKind): ManagedPointer | null {\n let parsed: PointerFile\n try {\n parsed = JSON.parse(raw) as PointerFile\n } catch {\n return null\n }\n if (typeof parsed !== \"object\" || parsed === null) return null\n if (parsed.schemaVersion !== POINTER_SCHEMA_VERSION) return null\n if (kindOf(parsed.kind) !== kind) return null\n const version = nonEmptyString(parsed.version)\n if (!version) return null\n // A version string reaches a path join; refuse separators outright rather\n // than reasoning about whether a crafted name can escape the root.\n if (version.includes(\"/\") || version.includes(\"\\\\\") || version === \".\" || version === \"..\") {\n return null\n }\n const entry = nonEmptyString(parsed.entry) ?? entryRelativeFor(kind)\n if (!isSafeEntry(entry)) return null\n\n return {\n schemaVersion: POINTER_SCHEMA_VERSION,\n kind,\n version,\n entry,\n entryPath: path.join(versionDir(kind, version), entry),\n runtimeHint: nonEmptyString(parsed.runtimeHint),\n registry: nonEmptyString(parsed.registry),\n installedAt: nonEmptyString(parsed.installedAt),\n }\n}\n\n/**\n * Why a pointer read produced no pointer.\n *\n * `absent` and `unreadable` MUST be distinguishable, and the distinction is not\n * academic: GC treats \"no pointer\" as \"nothing is live, so an old version dir may\n * be deleted\". A transient `EPERM`/`EBUSY` (a virus scanner holding the file, a\n * torn read on a network home) reported as `absent` would let GC delete the very\n * tree the pointer names — unrecoverable without reinstalling, and it happens\n * precisely on the machines that are already unhappy.\n *\n * - `ok` — a complete pointer.\n * - `absent` — no pointer file, or one whose body is unusable.\n * - `unreadable` — the read failed for a reason other than ENOENT.\n */\nexport type PointerReadStatus = \"ok\" | \"absent\" | \"unreadable\"\n\nexport interface PointerReadResult {\n status: PointerReadStatus\n pointer: ManagedPointer | null\n}\n\n/**\n * Read the pointer with the reason it was not usable.\n *\n * This is the primitive; `readPointer` is the ergonomic form for callers whose\n * only decision is \"run the payload or not\". GC must use this one.\n */\nexport async function readPointerDetailed(\n kind: ManagedKind,\n opts: { verifyEntry?: boolean } = {},\n): Promise<PointerReadResult> {\n const file = pointerPath(kind)\n let raw: string\n try {\n // `retryMissing: false`: a missing pointer is the normal first-run state, so\n // waiting out the retry window would tax every launch that has no managed\n // install yet (measured 760 ms before this flag existed).\n raw = await readFileWithRetry(file, { retryMissing: false })\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { status: \"absent\", pointer: null }\n }\n onReadError(kind, err)\n return { status: \"unreadable\", pointer: null }\n }\n const pointer = parsePointer(raw, kind)\n if (!pointer) {\n onInvalid(kind, file)\n return { status: \"absent\", pointer: null }\n }\n if (opts.verifyEntry === false) return { status: \"ok\", pointer }\n\n try {\n const stat = await fs.stat(pointer.entryPath)\n if (!stat.isFile()) {\n onMissingEntry(kind, pointer)\n return { status: \"absent\", pointer: null }\n }\n } catch {\n onMissingEntry(kind, pointer)\n return { status: \"absent\", pointer: null }\n }\n return { status: \"ok\", pointer }\n}\n\n/**\n * Read the pointer, or `null`.\n *\n * A missing file is the normal first-run answer. Any other read error is a\n * debug-level event, never a throw: a launch must not die because the pointer\n * is unreadable, and the caller's fallback (run from the current tree) is always\n * correct. The entry is stat'd by default, so a pointer to a GC'd or\n * half-published payload is also reported as absent.\n *\n * Callers that DESTROY something based on this answer must use\n * `readPointerDetailed` instead — see `PointerReadStatus`.\n */\nexport async function readPointer(\n kind: ManagedKind,\n opts: { verifyEntry?: boolean } = {},\n): Promise<ManagedPointer | null> {\n return (await readPointerDetailed(kind, opts)).pointer\n}\n\n/**\n * Write the pointer atomically.\n *\n * Temp + fsync + rename, with a bounded retry through a transient Windows lock\n * (`atomic-file`).\n *\n * `atomic-file`'s exhausted-rename fallback re-reads the destination and accepts\n * a byte-for-byte match as success. For a pointer that is not the \"did I win?\"\n * question being swept under the rug: the body carries `version` + `installedAt`,\n * so identical bytes mean the other writer published the SAME version at the\n * same instant, and reporting success is correct. Two writers naming DIFFERENT\n * versions can never byte-match, so the caller still learns who won.\n */\nexport async function writePointer(params: WritePointerParams): Promise<ManagedPointer> {\n const entry = params.entry ?? entryRelativeFor(params.kind)\n if (!isSafeEntry(entry)) {\n throw new Error(`refusing to write an unsafe managed entry: ${entry}`)\n }\n const body = {\n schemaVersion: POINTER_SCHEMA_VERSION,\n kind: params.kind,\n version: params.version,\n entry,\n ...(params.runtimeHint ? { runtimeHint: params.runtimeHint } : {}),\n ...(params.registry ? { registry: params.registry } : {}),\n installedAt: params.installedAt ?? new Date().toISOString(),\n }\n const file = pointerPath(params.kind)\n await fs.mkdir(path.dirname(file), { recursive: true })\n await writeFileAtomic(file, `${JSON.stringify(body, null, 2)}\\n`, { mode: 0o644 })\n return {\n schemaVersion: POINTER_SCHEMA_VERSION,\n kind: params.kind,\n version: params.version,\n entry,\n entryPath: path.join(versionDir(params.kind, params.version), entry),\n runtimeHint: params.runtimeHint,\n registry: params.registry,\n installedAt: body.installedAt,\n }\n}\n\n/** Remove the pointer (used by `update --force` and by tests). */\nexport async function removePointer(kind: ManagedKind): Promise<void> {\n await fs.rm(pointerPath(kind), { force: true })\n}\n\n// ---------------------------------------------------------------------------\n// Reporting\n//\n// The pointer is read by the bootstrap (`dist/bin.js`) and by the launcher path,\n// both of which must stay importable without `consola` — two bundles would mean\n// two instances and two configurations. Messages go through the sink instead;\n// see `diagnostics.ts`.\n// ---------------------------------------------------------------------------\n\nfunction onReadError(kind: ManagedKind, err: unknown): void {\n reportManagedDiagnostic(\n \"debug\",\n `managed[${kind}]: could not read current.json (${\n err instanceof Error ? err.message : String(err)\n }); treating as no managed install`,\n )\n}\n\nfunction onInvalid(kind: ManagedKind, file: string): void {\n reportManagedDiagnostic(\n \"warn\",\n `managed[${kind}]: ${file} is not a valid pointer (schema/kind/entry); ignoring it. \\`github-router update\\` will rewrite it.`,\n )\n}\n\nfunction onMissingEntry(kind: ManagedKind, pointer: ManagedPointer): void {\n reportManagedDiagnostic(\n \"debug\",\n `managed[${kind}]: pointer names ${pointer.version} but ${pointer.entryPath} is missing; treating as no managed install`,\n )\n}\n\n// ---------------------------------------------------------------------------\n// Installed-marker bookkeeping\n// ---------------------------------------------------------------------------\n\nexport interface InstalledMarker {\n version: string\n /** `{ \"pkg@version\": { resolved, integrity } }` for provenance. */\n packages?: Record<string, { resolved?: string; integrity?: string }>\n installedAt?: string\n runtime?: string\n registry?: string\n}\n\n/**\n * Write `<version>/.installed.json`.\n *\n * Publishing is rename-then-pointer, so this marker is the only thing that says\n * \"this directory is a COMPLETE payload\". `install.ts` writes it after the\n * rename, inside the version dir; `update` reads it to decide adopt-vs-install.\n */\nexport async function writeInstalledMarker(\n kind: ManagedKind,\n marker: InstalledMarker,\n): Promise<void> {\n const file = installedMarkerPath(kind, marker.version)\n await writeFileAtomic(file, `${JSON.stringify(marker, null, 2)}\\n`, { mode: 0o644 })\n}\n\nexport async function readInstalledMarker(\n kind: ManagedKind,\n version: string,\n): Promise<InstalledMarker | null> {\n try {\n // A missing marker is a normal state (not installed yet), so do not wait\n // out the retry window for it.\n const raw = await readFileWithRetry(installedMarkerPath(kind, version), {\n retryMissing: false,\n })\n const parsed = JSON.parse(raw) as InstalledMarker\n if (typeof parsed !== \"object\" || parsed === null) return null\n if (parsed.version !== version) return null\n return parsed\n } catch {\n return null\n }\n}\n","/**\n * The managed installer: put one exact package version into\n * `<APP_DIR>/m/<kind>/<version>/` and point `current.json` at it.\n *\n * The whole design is driven by three measured facts:\n *\n * 1. **`npx github-router@latest` re-extracts ~586 MB per published version**\n * (16 releases in 31 days; `~/.npm/_npx` was 2.5 GB across 25 directories).\n * Re-extraction, not re-download, is the 3 s cost — the tarball is cached.\n * 2. **A live npm tree must never be mutated in place.** On Windows\n * `npm install` over files a process holds open fails `EPERM`/`EBUSY`; this\n * is why the `-g` path uses a detached post-exit waiter. So publishing is\n * `rename()` of a fully-built sibling directory, which is atomic and touches\n * nothing the running process has open.\n * 3. **npm exits 0 on several env-driven no-ops** (`dry_run`, `global`,\n * `workspaces`, `omit`). See `npm-env.ts` for the table. Verifying the\n * entry file is therefore mandatory, not defensive.\n *\n * The staging directory lives INSIDE `<kind>/` on purpose: `rename` must be\n * same-directory (no `EXDEV`, and people symlink node_modules-heavy dirs onto\n * other volumes), and a `.`-prefixed name is what GC uses to tell a leftover\n * attempt from a version.\n */\n\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport { writeFileAtomic } from \"../atomic-file\"\nimport { resolveExecutable, runCommandCapture } from \"../exec\"\nimport { withInstallLockResult } from \"../update-lock\"\nimport { buildNpmEnv, managedInstallDisabled } from \"./npm-env\"\nimport { reportManagedDiagnostic } from \"./diagnostics\"\nimport {\n type ManagedKind,\n STAGING_RE,\n TRASH_RE,\n entryRelativeFor,\n isVersionName,\n managedRoot,\n npmPackageFor,\n stagingDir,\n trashDir,\n versionDir,\n} from \"./paths\"\nimport {\n type InstalledMarker,\n readInstalledMarker,\n readPointer,\n readPointerDetailed,\n removePointer,\n writePointer,\n} from \"./pointer\"\nimport {\n KEEP_VERSIONS,\n TRANSIENT_TTL_MS,\n VERSION_FLOOR_MS,\n mayAttemptNow,\n nextAttemptAtFor,\n patchInstallState,\n readInstallState,\n} from \"./state\"\n\n/** Ceiling for one install. A cold 66 MB install is ~10 s; a slow mirror is minutes. */\nconst INSTALL_TIMEOUT_MS = 10 * 60_000\n\nexport type InstallOutcomeKind =\n | \"installed\"\n | \"adopted\"\n | \"disabled\"\n | \"locked\"\n | \"no-npm\"\n | \"backoff\"\n | \"failed\"\n\nexport interface InstallOutcome {\n kind: InstallOutcomeKind\n /** The version now live, when one is. */\n version: string | null\n /** Absolute path of the payload entry, when one is. */\n entryPath?: string\n /** Human-readable detail for the CLI. */\n detail?: string\n error?: unknown\n}\n\nexport interface EnsureInstallOpts {\n kind: ManagedKind\n /** Exact version to install. Required — never a range, never `latest`. */\n version: string\n /** Ignore the backoff window (explicit `github-router update --force`). */\n force?: boolean\n /** Point at this version even if the pointer already names another. */\n activate?: boolean\n /**\n * Registry override for this install (`npm_config_registry`).\n *\n * Injected rather than derived: Pi needs `resolvePiRegistry()` (a corporate\n * mirror can lag below `PI_MIN_VERSION`), but importing `pi-version-check`\n * here would drag consola and the whole Pi graph into the installer — and\n * this module is called from the bootstrap's background path.\n */\n registry?: string\n signal?: AbortSignal\n}\n\n/**\n * Make `version` available and (optionally) live for `kind`.\n *\n * Idempotent and safe to run concurrently across processes: the second caller\n * loses the lock, or loses the `rename` race and adopts the winner's payload.\n */\nexport async function ensureManagedInstall(opts: EnsureInstallOpts): Promise<InstallOutcome> {\n const { kind, version } = opts\n if (managedInstallDisabled()) {\n return { kind: \"disabled\", version: null, detail: \"GH_ROUTER_NO_MANAGED_INSTALL is set\" }\n }\n if (!/^\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) {\n return { kind: \"failed\", version: null, detail: `invalid version \"${version}\"` }\n }\n\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) {\n return {\n kind: \"no-npm\",\n version: null,\n detail:\n \"npm is not on PATH, so the managed install is unavailable; this launch runs from the current tree.\",\n }\n }\n\n const state = await readInstallState(kind)\n // `mayAttemptNow`, not `installAllowedNow`: a bare reservation (written\n // optimistically by every attempt, so two launches cannot both run npm) is not\n // a failure and must not suppress this one. See `state.ts`.\n if (!opts.force && !mayAttemptNow(state)) {\n return {\n kind: \"backoff\",\n version: null,\n // First line only: `lastError` embeds npm's stderr, which is 20 lines long\n // and ends mid-filename. The full text stays in `install-state.json` for a\n // support thread; the CLI gets the sentence.\n detail: `last attempt failed (${firstLine(state.lastError) ?? \"unknown error\"}); next try after ${state.nextAttemptAt}`,\n }\n }\n\n // Optimistic: reserve the attempt before running so a concurrent launch backs\n // off instead of starting a second npm process over the same prefix.\n const reservation = nextAttemptAtFor((state.consecutiveFailures ?? 0) + 1)\n await patchInstallState(kind, {\n lastAttemptAt: new Date().toISOString(),\n nextAttemptAt: reservation,\n })\n\n const lock = await withInstallLockResult(`managed-${kind}.lock`, async () => {\n // Re-check inside the lock: the winner may have just published it.\n const existing = await probeVersion(kind, version)\n if (existing) {\n await activate(kind, version, opts.activate !== false)\n return\n }\n await installInto(kind, version, npmPath, opts.registry, opts.signal)\n await activate(kind, version, opts.activate !== false)\n })\n\n if (lock.outcome === \"failed\") {\n const lastError = errorText(lock.error)\n // Re-read rather than reusing the snapshot taken before an install that may\n // have run for minutes: another process (or `npmProbes`) writes this file.\n const fresh = await readInstallState(kind)\n // A concurrent process may have SUCCEEDED while this one was failing (its\n // lock was released, ours then failed for its own reason). Recording a\n // failure now would install a backoff on top of a healthy payload and make\n // the next launch report \"last attempt failed\" about a machine that is up to\n // date. `lastSuccessAt` moving is exactly that signal.\n if (fresh.lastSuccessAt !== state.lastSuccessAt) {\n return { kind: \"failed\", version: null, detail: lastError, error: lock.error }\n }\n const failures = (fresh.consecutiveFailures ?? 0) + 1\n await patchInstallState(kind, {\n lastAttemptAt: new Date().toISOString(),\n consecutiveFailures: failures,\n nextAttemptAt: nextAttemptAtFor(failures),\n lastError,\n })\n return { kind: \"failed\", version: null, detail: lastError, error: lock.error }\n }\n\n if (lock.outcome === \"skipped\") {\n // NOT a failure, so the reservation written above must not harden into a\n // backoff window. It was written to keep two launches from both running npm;\n // leaving it in place would make the very next launch skip an install that\n // nothing tried yet — and if the winner finished first, the loser's\n // reservation would land AFTER the winner cleared it, suppressing refreshes\n // for an hour on a machine that is already up to date.\n //\n // Guarded rather than unconditional: the lock holder may have FAILED in the\n // meantime and written its own (genuine) window, which restoring ours would\n // erase. Only the reservation this call wrote is ours to remove.\n const now = await readInstallState(kind)\n if (now.nextAttemptAt === reservation) {\n await patchInstallState(kind, { nextAttemptAt: state.nextAttemptAt })\n }\n return {\n kind: \"locked\",\n version: null,\n detail: \"another github-router process is installing; retry shortly\",\n }\n }\n\n const live = await readPointer(kind, { verifyEntry: false })\n // `adopted` vs `installed` is user-visible (``update`` prints it), so it must be\n // judged against what is on disk now, not against the snapshot taken before an\n // install that may have taken minutes.\n const fresh = await readInstallState(kind)\n const alreadySucceeded = fresh.lastSuccessAt !== undefined && live?.version === version\n const stateWritten = await patchInstallState(kind, {\n lastAttemptAt: new Date().toISOString(),\n lastSuccessAt: new Date().toISOString(),\n consecutiveFailures: 0,\n // Explicit `undefined` = delete, which is what clears the ladder.\n nextAttemptAt: undefined,\n lastError: undefined,\n })\n return {\n kind: alreadySucceeded ? \"adopted\" : \"installed\",\n version,\n entryPath: live?.version === version ? live.entryPath : versionEntry(kind, version),\n // A failed write is NOT a failed install — the payload is live and this\n // process knows it — but the next launch reads the stale ladder from disk and\n // would report \"last attempt failed\" for up to 24 h on a healthy machine. Say\n // so once, here, instead of leaving it to be discovered as a mystery.\n ...(stateWritten\n ? {}\n : {\n detail:\n \"installed, but install-state.json could not be written; the next launch may think the previous attempt failed\",\n }),\n }\n}\n\n/**\n * Publish `version` as the live payload.\n *\n * Reads the pointer back rather than trusting its own write: if a concurrent\n * `update` published a different version first, the pointer is the winner and\n * this call must not claim otherwise.\n */\nasync function activate(kind: ManagedKind, version: string, activateIt: boolean): Promise<void> {\n const marker = await readInstalledMarker(kind, version)\n if (!activateIt) return\n await writePointer({\n kind,\n version,\n entry: entryRelativeFor(kind),\n runtimeHint: process.execPath,\n registry: marker?.registry,\n installedAt: new Date().toISOString(),\n })\n}\n\n/** The payload entry inside a published version dir. */\nexport function versionEntry(kind: ManagedKind, version: string): string {\n return path.join(versionDir(kind, version), entryRelativeFor(kind))\n}\n\n/**\n * Is `version` already a complete payload?\n *\n * Both conditions are required. The marker alone is not enough (a killed\n * `npm install` leaves whatever it got so far, and the marker is written by us\n * only after verification), and the entry alone is not enough (a half-installed\n * tree can contain the entry file while its dependencies are missing).\n */\nasync function probeVersion(\n kind: ManagedKind,\n version: string,\n): Promise<{ version: string; entryPath: string } | null> {\n const entryPath = versionEntry(kind, version)\n const marker = await readInstalledMarker(kind, version)\n if (!marker) return null\n try {\n const stat = await fs.stat(entryPath)\n if (!stat.isFile()) return null\n } catch {\n return null\n }\n return { version, entryPath }\n}\n\n/**\n * Do the install and publish it.\n *\n * Everything happens in a fresh `.staging-<pid>-<rand>` sibling:\n *\n * 1. private `package.json` with an EXACT dependency (a range would make\n * `adopt` and `npm view` disagree about what is live),\n * 2. `npm install` with `cwd` = staging and a scrubbed env,\n * 3. verify the entry, harvest provenance from `package-lock.json`, write the\n * marker INSIDE staging,\n * 4. `rename(staging → <version>)`, then verify again through the final path.\n *\n * The marker lands before the rename so a crash can never leave a\n * complete-looking version dir without one — and a crash before the rename\n * leaves only a `.staging-*` dir, which GC sweeps.\n */\nasync function installInto(\n kind: ManagedKind,\n version: string,\n npmPath: string,\n registry?: string,\n signal?: AbortSignal,\n): Promise<void> {\n const root = managedRoot(kind)\n await fs.mkdir(root, { recursive: true, mode: 0o700 })\n\n const pkgName = npmPackageFor(kind)\n const staging = stagingDir(kind)\n // NOT `recursive: true`: the name already carries pid + random, so an EEXIST\n // here means a name collision (pid reuse after a crashed attempt left\n // `.staging-<pid>-<rand>` behind — unlikely, but the consequence is severe).\n // npm installing into an inherited tree would find an entry file it did not\n // fetch, `assertFile` would pass, a fresh `.installed.json` would be minted,\n // and an incomplete payload would publish — the \"npm exited 0 and installed\n // nothing\" laundering `npm-env.ts` exists to prevent. Failing loudly and\n // letting the caller retry with a new name is the only safe answer.\n await fs.mkdir(staging, { mode: 0o700 })\n\n try {\n const pkgJson = {\n name: `gh-router-managed-${kind}`,\n private: true,\n version: \"0.0.0\",\n // Exact, not a range: the publish step is rename-only, so anything the\n // resolver decides here becomes the live payload without a second look.\n dependencies: { [pkgName]: version },\n }\n await writeFileAtomic(path.join(staging, \"package.json\"), `${JSON.stringify(pkgJson, null, 2)}\\n`, {\n mode: 0o644,\n })\n\n // Registry is passed BOTH as env (so a transitive `npm` child spawned by a\n // lifecycle script would also see it — there are none, `--ignore-scripts`,\n // but belt and braces) and as an explicit flag below, because a flag beats\n // every config source npm has. For Pi this is not optional: a lagging mirror\n // can sit below `PI_MIN_VERSION`, and the floor is enforced against what\n // actually got installed.\n const overrides: NodeJS.ProcessEnv = {}\n if (registry) overrides.npm_config_registry = registry\n\n const scrub = buildNpmEnv(process.env, overrides)\n reportManagedDiagnostic(\n \"debug\",\n `managed[${kind}]: npm env kept=${scrub.kept.length} dropped=${scrub.dropped.join(\",\") || \"none\"}`,\n )\n\n reportManagedDiagnostic(\"info\", `Installing ${pkgName}@${version} (one-time per version)…`)\n const { code, stderr } = await runCommandCapture(\n [\n npmPath,\n \"install\",\n // Defence in depth against the env keys scrubbed above: a flag beats\n // both env and .npmrc, so the destination and completeness cannot be\n // redirected by anything the user exported.\n \"--no-global\",\n \"--no-dry-run\",\n \"--include=optional\",\n \"--ignore-scripts\",\n \"--no-audit\",\n \"--no-fund\",\n \"--loglevel=error\",\n ...(registry ? [`--registry=${registry}`] : []),\n ],\n {\n // cloudcli.ts inherits the caller's cwd, so npm reads that directory's\n // `.npmrc` — a repo-local `registry` line would silently redirect this\n // install. From the staging dir only `$HOME/.npmrc` and the global\n // file apply.\n cwd: staging,\n env: scrub.env,\n timeoutMs: INSTALL_TIMEOUT_MS,\n signal,\n },\n )\n if (code !== 0) {\n throw new Error(\n `npm install ${pkgName}@${version} failed (exit ${code}). This usually means no network, a corporate proxy, or a registry that does not carry the version.\\n${stderr.slice(0, 600)}`,\n )\n }\n\n // Exit 0 does not imply \"installed\" (see the npm-env.ts table).\n const stagedEntry = path.join(staging, entryRelativeFor(kind))\n await assertFile(stagedEntry, `${pkgName}@${version} installed but its entry is missing`)\n // And the entry existing does not imply the RIGHT version: an inherited\n // staging tree, a mirror serving a different tarball under the requested\n // version, or `omit=optional` leaving a stale tree all produce a complete-\n // looking directory. The marker written below is the only thing that certifies\n // \"this dir is complete\", and `probeVersion` adopts any dir that has one\n // forever — so check the version the tree actually contains, and fail before\n // the marker exists.\n await assertInstalledVersion(path.join(staging, \"node_modules\", pkgName), pkgName, version)\n\n const marker: InstalledMarker = {\n version,\n installedAt: new Date().toISOString(),\n runtime: process.execPath,\n packages: await harvestProvenance(staging),\n }\n const resolvedRegistry = firstRegistry(marker) ?? registry\n if (resolvedRegistry) marker.registry = resolvedRegistry\n\n // Written INTO STAGING before the rename, so a version dir can never\n // appear without it. (`writeInstalledMarker` targets the final path, which\n // does not exist yet — hence the explicit staging path here.)\n await writeFileAtomic(stagingMarkerPath(staging), `${JSON.stringify(marker, null, 2)}\\n`, {\n mode: 0o644,\n })\n\n const target = versionDir(kind, version)\n const published = await publishTo(staging, target, kind)\n if (published === \"raced\") {\n // Another installer won. Adopt its tree if it is complete; otherwise it\n // was mid-publish and we must not leave a broken version live.\n if (!(await probeVersion(kind, version))) {\n throw new Error(`another process published ${pkgName}@${version} incompletely; retry`)\n }\n }\n await assertFile(versionEntry(kind, version), `${pkgName}@${version} published without its entry`)\n } finally {\n // No-op on success (the rename moved it away).\n await fs.rm(staging, { recursive: true, force: true }).catch(() => {})\n }\n}\n\ntype PublishResult = \"published\" | \"raced\"\n\n/**\n * `rename(staging → target)`, moving a corrupt existing tree aside first.\n *\n * Rename onto an existing non-empty directory is `ENOTEMPTY` on POSIX and\n * `EPERM`/`EEXIST` on Windows — the exact `npm error code ENOTEMPTY` failure\n * Claude Code's updater hit. Renaming the loser aside to a fresh name always\n * works, so the published path is never a partially-overwritten tree.\n */\nasync function publishTo(\n staging: string,\n target: string,\n kind: ManagedKind,\n): Promise<PublishResult> {\n try {\n await fs.rename(staging, target)\n return \"published\"\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code !== \"ENOTEMPTY\" && code !== \"EEXIST\" && code !== \"EPERM\" && code !== \"EACCES\") {\n throw err\n }\n }\n\n // Something is already at `target`. If it is a complete payload, another\n // process just won the race — adopt it. If not, move it aside and retry once.\n //\n // `kind` is threaded through instead of re-derived from the path: a `null`\n // derivation used to fall back to `trashDir(\"self\")`, i.e. a Pi payload would\n // be moved into the SELF root, where the next `self` GC would delete it.\n if (await probeVersion(kind, path.basename(target))) return \"raced\"\n\n const aside = trashDir(kind)\n let movedAside = false\n try {\n await fs.rename(target, aside)\n movedAside = true\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n // Vanished between the failed rename and now: nothing to move aside, and\n // nothing to restore either.\n if (code !== \"ENOENT\") throw err\n }\n try {\n await fs.rename(staging, target)\n return \"published\"\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === \"ENOTEMPTY\" || code === \"EEXIST\" || code === \"EPERM\" || code === \"EACCES\") {\n // Lost a second race — treat as adopt, verified by the caller.\n return \"raced\"\n }\n // The publish failed for an unrelated reason (permissions, disk) AFTER the\n // old tree was moved aside. Put it back: the pointer may still name it, and\n // a pointer with no payload is a launch that falls back to the npx tree —\n // a silent downgrade caused by a failed update. GC would otherwise delete\n // the moved-aside copy an hour later, making the loss permanent.\n let restored = false\n if (movedAside) {\n restored = await fs.rename(aside, target).then(\n () => true,\n () => false,\n )\n }\n // The restore failed too. Nothing can run from `target`, and leaving the\n // pointer in place makes `update --check` report a version that is not on\n // disk (every other reader already treats it as absent). Drop it only when it\n // names the tree that is now gone — it may name a DIFFERENT version, which is\n // still perfectly good.\n if (!restored) {\n const live = await readPointer(kind, { verifyEntry: false })\n if (live && live.version === path.basename(target)) {\n await removePointer(kind).catch(() => {})\n }\n }\n throw err\n }\n}\n\n/**\n * Assert `dir`'s `package.json` declares `version`.\n *\n * Deliberately a THROW, not a warning: the caller writes the marker (which\n * certifies completeness forever) immediately after this, so \"close enough\" here\n * means a wrong or incomplete payload becomes the live one.\n */\nasync function assertInstalledVersion(dir: string, pkgName: string, version: string): Promise<void> {\n const manifestPath = path.join(dir, \"package.json\")\n let declared: unknown\n try {\n declared = (JSON.parse(await fs.readFile(manifestPath, \"utf8\")) as { version?: unknown }).version\n } catch {\n throw new Error(`${pkgName}@${version} installed but ${manifestPath} is missing or unreadable`)\n }\n if (declared !== version) {\n throw new Error(\n `${pkgName}@${version} installed but its package.json declares ${JSON.stringify(declared)}; refusing to publish it`,\n )\n }\n}\n\n/** The `.installed.json` path inside a staging dir (same name the final dir uses). */\nfunction stagingMarkerPath(staging: string): string {\n return path.join(staging, \".installed.json\")\n}\n\n/** `{ \"<pkg>@<version>\": { resolved, integrity } }` from the prefix lockfile. */\nasync function harvestProvenance(\n prefix: string,\n): Promise<Record<string, { resolved?: string; integrity?: string }>> {\n const out: Record<string, { resolved?: string; integrity?: string }> = {}\n try {\n const raw = await fs.readFile(path.join(prefix, \"package-lock.json\"), \"utf8\")\n const parsed = JSON.parse(raw) as {\n packages?: Record<\n string,\n { version?: string; resolved?: string; integrity?: string; link?: boolean }\n >\n }\n for (const [key, entry] of Object.entries(parsed.packages ?? {})) {\n if (!key.startsWith(\"node_modules/\") || entry.link) continue\n const name = key.slice(\"node_modules/\".length)\n // Only top-level provenance: the transitive tree is reproducible from\n // the registry once the root tarball's integrity is pinned.\n if (name.includes(\"node_modules/\")) continue\n if (!entry.version) continue\n out[`${name}@${entry.version}`] = {\n ...(entry.resolved ? { resolved: entry.resolved } : {}),\n ...(entry.integrity ? { integrity: entry.integrity } : {}),\n }\n }\n } catch {\n // No lockfile (npm can be told not to write one). Provenance is\n // best-effort diagnostics, never a gate.\n }\n return out\n}\n\n/**\n * The registry a payload actually came from, derived from a tarball URL.\n *\n * NOT `new URL(resolved).origin`: a corporate mirror keeps its path\n * (`https://nexus.example/repository/npm-group/github-router/-/github-router-1.2.3.tgz`),\n * and truncating to the origin writes `https://nexus.example/` into `current.json`\n * and `install-state.json` as \"the registry this install used\". Anyone — a support\n * thread, a future reader, `update --check` — who then fetches from it gets a 404.\n *\n * The npm registry layout makes the answer exact: everything before the\n * `<pkg>/-/<pkg>-<version>.tgz` segment is the registry. When that shape is not\n * recognisable, prefer no answer over a wrong one.\n */\nfunction registryFromResolved(resolved: string): string | undefined {\n try {\n const url = new URL(resolved)\n const marker = url.pathname.lastIndexOf(\"/-/\")\n if (marker <= 0) return undefined\n const basePath = url.pathname.slice(0, marker + 1)\n return `${url.origin}${basePath}`\n } catch {\n // A non-URL `resolved` (file:, git:) has no registry.\n return undefined\n }\n}\n\nfunction firstRegistry(marker: InstalledMarker): string | undefined {\n for (const entry of Object.values(marker.packages ?? {})) {\n if (!entry.resolved) continue\n const registry = registryFromResolved(entry.resolved)\n if (registry) return registry\n }\n return undefined\n}\n\nasync function assertFile(file: string, message: string): Promise<void> {\n try {\n const stat = await fs.stat(file)\n if (stat.isFile()) return\n } catch {\n // fall through\n }\n throw new Error(message)\n}\n\nfunction errorText(err: unknown): string {\n if (err instanceof Error) return err.message.slice(0, 800)\n return String(err).slice(0, 800)\n}\n\n/** First non-empty line of a multi-line diagnostic, or null. */\nfunction firstLine(text: string | undefined): string | null {\n if (!text) return null\n const line = text.split(/\\r?\\n/).find((part) => part.trim().length > 0)\n return line ? line.trim() : null\n}\n\n// ---------------------------------------------------------------------------\n// Garbage collection\n// ---------------------------------------------------------------------------\n\nexport interface GcReport {\n removedStaging: Array<string>\n removedTrash: Array<string>\n /** Atomic-write temp files (`current.json.<pid>.<rand>.tmp`). */\n removedTransient: Array<string>\n removedVersions: Array<string>\n /** Kept, with the reason — this is what makes a support thread answerable. */\n kept: Array<{ name: string; reason: string }>\n}\n\n/**\n * Sweep leftover attempts and old payloads.\n *\n * Non-blocking and best-effort by contract: every removal error is swallowed\n * (`EBUSY` on Windows is normal while a virus scanner holds a file) and retried\n * on the next boot. The rules:\n *\n * - `.staging-*` / `.trash-*` older than an hour: delete.\n * - a `<version>` dir: delete only if it is NOT the pointer's, NOT one of the\n * two newest, AND older than the 7-day floor.\n *\n * The floor exists because a live session's hooks name its payload dir\n * (`--package-root`), so a version can be in use long after the pointer moved\n * on. Bounding that at a week is the deliberate trade recorded in the plan.\n */\nexport async function gcManaged(kind: ManagedKind, now = Date.now()): Promise<GcReport> {\n const report: GcReport = {\n removedStaging: [],\n removedTrash: [],\n removedTransient: [],\n removedVersions: [],\n kept: [],\n }\n const root = managedRoot(kind)\n let names: Array<string>\n try {\n names = await fs.readdir(root)\n } catch {\n return report\n }\n\n // Abort the WHOLE sweep when the pointer cannot be read for a reason other\n // than \"there is none\". Without this a transient `EPERM`/`EBUSY` (a virus\n // scanner holding current.json, a torn read on a network home) reads as\n // \"nothing is live\", and the version it names — possibly neither of the two\n // newest nor inside the 7-day floor — gets deleted. That is unrecoverable\n // without a reinstall, on exactly the machine that is already in trouble.\n // Sweeping is an optimisation; skipping it costs disk, deleting a live tree\n // costs a working install.\n const pointerRead = await readPointerDetailed(kind, { verifyEntry: false })\n if (pointerRead.status === \"unreadable\") {\n return report\n }\n const live = pointerRead.pointer\n // Two different time quantities, kept apart on purpose: `modifiedAt` is an\n // absolute timestamp (used only to order \"newest first\") and `age` is a\n // duration (used only against the floor). An earlier version of this code\n // stored the timestamp and compared it to `VERSION_FLOOR_MS`, which made the\n // 7-day floor unfalsifiable — every real timestamp is larger than 7 days in\n // milliseconds, so the floor never protected anything.\n const versions: Array<{ name: string; modifiedAt: number; age: number }> = []\n\n for (const name of names) {\n const full = path.join(root, name)\n // Transient names are matched against the SAME shapes `paths.ts` defines for\n // staging/trash, not a bare prefix: a `.staging-notes` file a user dropped in\n // is not ours to delete, and the two modules must not disagree about what a\n // leftover looks like.\n if (STAGING_RE.test(name)) {\n const age = await ageMs(full, now)\n if (age !== null && age > TRANSIENT_TTL_MS) {\n if (await removeDir(full)) report.removedStaging.push(name)\n }\n continue\n }\n if (TRASH_RE.test(name)) {\n const age = await ageMs(full, now)\n if (age !== null && age > TRANSIENT_TTL_MS) {\n if (await removeDir(full)) report.removedTrash.push(name)\n }\n continue\n }\n // A killed `writeFileAtomic` leaves `<file>.<pid>.<rand>.tmp` beside the\n // file it was replacing — same TTL rule as the other transient names, so a\n // `.tmp` from a crashed pointer write does not sit here forever.\n if (name.endsWith(\".tmp\")) {\n const age = await ageMs(full, now)\n if (age !== null && age > TRANSIENT_TTL_MS) {\n if (await removeFile(full)) report.removedTransient.push(name)\n }\n continue\n }\n if (!isVersionName(name)) continue\n const age = (await ageMs(full, now)) ?? 0\n versions.push({ name, modifiedAt: now - age, age })\n }\n\n // Newest first (highest timestamp, then highest version as a tiebreak so a\n // same-second install of two versions is still deterministic).\n versions.sort((a, b) =>\n a.modifiedAt === b.modifiedAt\n ? compareVersions(b.name, a.name)\n : b.modifiedAt - a.modifiedAt,\n )\n const protectedNames = new Set<string>()\n if (live) protectedNames.add(live.version)\n for (const entry of versions.slice(0, KEEP_VERSIONS)) protectedNames.add(entry.name)\n\n for (const entry of versions) {\n if (protectedNames.has(entry.name)) {\n report.kept.push({ name: entry.name, reason: \"newest-or-live\" })\n continue\n }\n if (entry.age < VERSION_FLOOR_MS) {\n report.kept.push({ name: entry.name, reason: \"within-7-day-floor\" })\n continue\n }\n const full = path.join(root, entry.name)\n if (await removeDir(full)) report.removedVersions.push(entry.name)\n else report.kept.push({ name: entry.name, reason: \"removal-failed\" })\n }\n\n return report\n}\n\nasync function ageMs(full: string, now: number): Promise<number | null> {\n try {\n const stat = await fs.stat(full)\n return now - stat.mtimeMs\n } catch {\n return null\n }\n}\n\nasync function removeFile(full: string): Promise<boolean> {\n try {\n await fs.rm(full, { force: true })\n return true\n } catch (err) {\n reportManagedDiagnostic(\"debug\", `managed: could not remove ${full}: ${String(err)}`)\n return false\n }\n}\n\nasync function removeDir(full: string): Promise<boolean> {\n try {\n await fs.rm(full, { recursive: true, force: true })\n return true\n } catch (err) {\n reportManagedDiagnostic(\"debug\", `managed: could not remove ${full}: ${String(err)}`)\n return false\n }\n}\n\nfunction compareVersions(a: string, b: string): number {\n const pa = a.split(/[.+-]/).map((n) => Number.parseInt(n, 10))\n const pb = b.split(/[.+-]/).map((n) => Number.parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = Number.isNaN(pa[i]) ? 0 : (pa[i] ?? 0)\n const bv = Number.isNaN(pb[i]) ? 0 : (pb[i] ?? 0)\n if (av !== bv) return av - bv\n }\n return 0\n}\n\n/** Absolute path of a published version's entry, without touching the pointer. */\nexport function managedEntryPath(kind: ManagedKind, version: string): string {\n return versionEntry(kind, version)\n}\n\n","/**\n * The stable launcher: `<APP_DIR>/m/<kind>/launcher.mjs`.\n *\n * This file is the entire point of the managed layout. Shims (and anything else\n * that wants a version-independent path) exec THIS, and it figures out which\n * concrete payload is live by reading `current.json` and re-execing it. It is\n * written once and never swapped, so a shim baked onto PATH years ago keeps\n * working across every future version — which is exactly the property\n * `claude`'s native installer has and `npx` does not.\n *\n * It is generated as SOURCE TEXT rather than built as a bundle entry, and that\n * is deliberate:\n *\n * - it must survive when the package tree it came from is deleted (that is the\n * `bunx`/`npx` case this feature exists for), so it cannot carry a single\n * non-`node:` import;\n * - it is ~150 lines of self-contained logic, so a build entry would add a\n * fourth bundle, a sidecar digest, and a publish step for no benefit;\n * - `tests/isolated/managed-launcher.test.ts` runs the real emitted file under\n * the real `node`, on every platform CI has, which pins behaviour harder than\n * a typecheck would.\n *\n * What it must never do: resolve the version itself, install anything, or touch\n * the network. Every failure has to be a message plus a non-zero exit, because\n * the caller is a shell or a hook with no way to recover.\n */\n\nimport fs from \"node:fs/promises\"\n\nimport consola from \"consola\"\n\nimport { writeFileAtomic } from \"../atomic-file\"\nimport { type ManagedKind, launcherPath, managedRoot } from \"./paths\"\n\n/**\n * Marker line every generated file carries.\n *\n * `shim.ts` uses the same idea for its guards: a file is only ever overwritten\n * if it contains this marker, so a user's own script that happens to sit at the\n * same path is never clobbered. Keep the two constants in sync — `LAUNCHER_BODY`\n * includes it as a comment, and `hasManagedMarker()` is the reader.\n */\nexport const MANAGED_MARKER = \"github-router-managed-file\"\n\nexport function hasManagedMarker(content: string): boolean {\n return content.includes(MANAGED_MARKER)\n}\n\n/**\n * The launcher program.\n *\n * Constraints on the body (all enforced by tests):\n * - no top-level import other than `node:` builtins;\n * - no reference to `github-router` package code;\n * - must run on Node 20 and on bun.\n */\nconst LAUNCHER_BODY = String.raw`\n// ${MANAGED_MARKER} — generated by \\`github-router update\\`. Do not edit.\n// Resolves <dir>/current.json and re-execs the payload it names.\nimport { spawn } from \"node:child_process\"\nimport { readFileSync, existsSync, statSync, writeSync } from \"node:fs\"\nimport { dirname, join, isAbsolute } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nconst here = dirname(fileURLToPath(import.meta.url))\n// Test seams, gated behind an explicit opt-in. Ungated they are a footgun with a\n// security edge: a stale GH_ROUTER_MANAGED_ENTRY in a user's environment would\n// execute an ARBITRARY file on every launch (it bypasses the traversal/absolute\n// checks below, which is the whole point of an override), and a stale\n// GH_ROUTER_MANAGED_DRY_RUN would make every hook exit 0 having printed JSON\n// instead of doing its work — a success that means nothing.\nconst TEST_SEAMS = process.env.GH_ROUTER_MANAGED_TEST === \"1\"\nconst ENTRY_OVERRIDE = TEST_SEAMS ? process.env.GH_ROUTER_MANAGED_ENTRY : undefined\nconst DRY_RUN = TEST_SEAMS && process.env.GH_ROUTER_MANAGED_DRY_RUN === \"1\"\n\nfunction fail(message, code) {\n // writeSync, not process.stderr.write: on a PIPE stderr is asynchronous, and\n // process.exit tears the loop down before the bytes reach the reader — so a\n // hook or a CI step saw a bare exit 78 with no explanation, which is precisely\n // the case this message exists for.\n try {\n writeSync(2, \"github-router: \" + message + \"\\n\")\n } catch {\n // Best effort: still exit with the code.\n }\n process.exit(typeof code === \"number\" ? code : 1)\n}\n\nfunction readPointer() {\n const file = join(here, \"current.json\")\n let raw\n try {\n raw = readFileSync(file, \"utf8\")\n } catch (err) {\n if (err && err.code === \"ENOENT\") {\n fail(\n \"no managed install is active (\" + file + \" is missing).\\n\" +\n \" Run: github-router update\\n\" +\n \" Or reinstall: npm install -g github-router\",\n 78\n )\n }\n fail(\"could not read \" + file + \": \" + (err && err.message ? err.message : String(err)))\n }\n let parsed\n try {\n parsed = JSON.parse(raw)\n } catch {\n fail(file + \" is not valid JSON. Run: github-router update\")\n }\n if (!parsed || typeof parsed !== \"object\") fail(file + \" is not a pointer object. Run: github-router update\")\n if (parsed.schemaVersion !== 1) {\n fail(\n \"unsupported pointer schema \" + String(parsed.schemaVersion) + \". This launcher is too old for the installed layout; reinstall github-router.\",\n 78\n )\n }\n if (typeof parsed.version !== \"string\" || typeof parsed.entry !== \"string\") {\n fail(file + \" is missing its version/entry fields. Run: github-router update\")\n }\n // A version string becomes a path segment: never let it climb out.\n if (parsed.version.indexOf(\"/\") >= 0 || parsed.version.indexOf(\"\\\\\") >= 0 || parsed.version.indexOf(\"..\") >= 0) {\n fail(file + \" names an invalid version. Run: github-router update\")\n }\n // The entry becomes an argv the runtime executes. Absolute paths and\n // traversal are refused for the same reason the writer refuses them.\n if (isAbsolute(parsed.entry) || parsed.entry.split(/[\\\\/]/).indexOf(\"..\") >= 0) {\n fail(file + \" names an unsafe entry. Run: github-router update\")\n }\n return parsed\n}\n\n/**\n * Pick the runtime for the payload.\n *\n * Order: whatever is already running this launcher, then the pointer's\n * \\`runtimeHint\\`, then \\`node\\` on PATH.\n *\n * \\`process.execPath\\` comes first because it is the only candidate whose version\n * we can check for free: spawning \\`node --version\\` on every launch is a real\n * cost, and this file runs on every CLI invocation a session makes. That check\n * matters when a \\`bunx\\` user's bun reports a node-compat major below the\n * payload's floor — rare, but it is the difference between a clear engine error\n * and a mystery crash.\n *\n * \\`runtimeHint\\` is only a FALLBACK, never authoritative: nvm/fnm/volta/brew\n * delete the previous interpreter on every upgrade, so trusting a recorded\n * absolute path is exactly how a launcher \"stops working after a node upgrade\".\n */\nfunction isFile(candidate) {\n try {\n return typeof candidate === \"string\" && candidate.length > 0 && statSync(candidate).isFile()\n } catch {\n return false\n }\n}\n\nfunction runningNodeMajor() {\n const running = process.versions && process.versions.node\n if (!running) return null\n const major = Number(String(running).split(\".\")[0])\n return Number.isNaN(major) ? null : major\n}\n\n/** \\`engines.node\\` major from the PAYLOAD's package.json, or null. */\nfunction enginesNodeMajor(entryPath) {\n let dir = dirname(entryPath)\n for (let i = 0; i < 6; i++) {\n const candidate = join(dir, \"package.json\")\n if (existsSync(candidate)) {\n try {\n const pkg = JSON.parse(readFileSync(candidate, \"utf8\"))\n if (pkg && typeof pkg.name === \"string\") {\n const range = pkg.engines && pkg.engines.node\n if (typeof range !== \"string\") return null\n const match = range.match(/(\\d+)/)\n return match ? Number(match[1]) : null\n }\n } catch {\n // Keep walking.\n }\n }\n const parent = dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n return null\n}\n\nfunction chooseRuntime(pointer, entryPath) {\n const minMajor = enginesNodeMajor(entryPath)\n const mine = runningNodeMajor()\n // Unknown floor or unknown running version: do not filter, keep the runtime\n // the user chose. A wrong guess here is worse than an engine mismatch.\n const mineOk = minMajor === null || mine === null || mine >= minMajor\n if (mineOk && isFile(process.execPath)) return process.execPath\n\n if (isFile(pointer.runtimeHint)) return pointer.runtimeHint\n\n const pathEnv = process.env.PATH || \"\"\n const sep = process.platform === \"win32\" ? \";\" : \":\"\n const names = process.platform === \"win32\" ? [\"node.exe\", \"node\"] : [\"node\"]\n for (const dir of pathEnv.split(sep)) {\n if (!dir) continue\n for (const name of names) {\n const candidate = join(dir, name)\n if (isFile(candidate)) return candidate\n }\n }\n // Nothing better: let the spawn fail with its own message.\n return process.execPath\n}\n\nconst pointer = readPointer()\nconst versionDir = join(here, pointer.version)\nconst entryPath = ENTRY_OVERRIDE || join(versionDir, pointer.entry)\n\nif (!existsSync(entryPath)) {\n fail(\n \"the live payload is missing: \" + entryPath + \"\\n\" +\n \" The install is incomplete. Run: github-router update\",\n 78\n )\n}\n\nif (DRY_RUN) {\n // Test/diagnostic hook: report what WOULD run, without running it. Used by\n // the managed-install e2e test to prove a launch landed on the managed tree\n // without parsing debug logs.\n process.stdout.write(JSON.stringify({ version: pointer.version, entryPath }) + \"\\n\")\n process.exit(0)\n}\n\nconst runtime = chooseRuntime(pointer, entryPath)\n\nconst SIGNALS = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"]\nconst SIGNAL_NUMBERS = { SIGHUP: 1, SIGINT: 2, SIGTERM: 15 }\n// Registered BEFORE the spawn: a signal that arrives between \\`spawn\\` returning\n// and the handler being installed kills this launcher with the default\n// disposition and leaves the payload running with nobody forwarding to it.\nlet child = null\nfor (const signal of SIGNALS) {\n try {\n process.on(signal, () => {\n try {\n if (child) child.kill(signal)\n } catch {\n // already gone\n }\n })\n } catch {\n // Platform without this signal.\n }\n}\n\ntry {\n child = spawn(runtime, [entryPath, ...process.argv.slice(2)], {\n stdio: \"inherit\",\n windowsHide: true,\n env: process.env,\n })\n} catch (err) {\n fail(\"could not start \" + runtime + \": \" + (err && err.message ? err.message : String(err)))\n}\n\nchild.on(\"error\", (err) => {\n fail(\"could not start \" + runtime + \": \" + (err && err.message ? err.message : String(err)))\n})\n\nchild.on(\"exit\", (code, signal) => {\n if (signal) {\n // Mirror the child's fate so a supervisor (systemd, a CI runner, a hook\n // wrapper) sees a signal death rather than a generic exit 1.\n //\n // The forwarding handlers above MUST go first: Node does not re-raise a\n // signal that has a listener, so leaving them installed makes the re-raise a\n // no-op that falls through to exit 0 — an interrupted launch reports success.\n // 128+n is also set, for a signal that cannot be re-raised at all.\n for (const name of SIGNALS) process.removeAllListeners(name)\n process.exitCode = 128 + (SIGNAL_NUMBERS[signal] || 0)\n try {\n process.kill(process.pid, signal)\n } catch {\n process.exit(process.exitCode)\n }\n return\n }\n process.exit(typeof code === \"number\" ? code : 1)\n})\n`.trimStart()\n\n/** The exact bytes written to `launcher.mjs` for `kind`. */\nexport function launcherSource(): string {\n return LAUNCHER_BODY.endsWith(\"\\n\") ? LAUNCHER_BODY : `${LAUNCHER_BODY}\\n`\n}\n\nexport interface EnsureLauncherResult {\n path: string\n written: boolean\n}\n\n/**\n * Write the launcher if it is absent or stale.\n *\n * Content-checked, not existence-checked: a future release can improve the\n * launcher (a new signal, a new runtime rule) and have it take effect on the\n * next run of any version, without a migration step. It is safe to rewrite\n * because nothing holds this file open — the shims exec it and the process\n * exits when the payload does — and `writeFileAtomic` means a concurrent launch\n * sees either the old bytes or the new bytes, never a truncation.\n */\nexport async function ensureLauncher(kind: ManagedKind): Promise<EnsureLauncherResult> {\n const file = launcherPath(kind)\n const desired = launcherSource()\n try {\n const current = await fs.readFile(file, \"utf8\")\n if (current === desired) return { path: file, written: false }\n } catch {\n // Absent or unreadable: write it below.\n }\n await fs.mkdir(managedRoot(kind), { recursive: true })\n try {\n await writeFileAtomic(file, desired, { mode: 0o755 })\n } catch (err) {\n // A virus scanner or an EDR holding `launcher.mjs` turns the rename into\n // EPERM. The PAYLOAD is already live and the pointer names it, so failing the\n // whole update here would report a broken install for a cosmetic miss; the\n // next `update` retries. Same policy as `writeShim`.\n consola.warn(`Could not write the managed launcher ${file}:`, err)\n return { path: file, written: false }\n }\n return { path: file, written: true }\n}\n","/**\n * PATH shims for the managed install.\n *\n * The launcher (`<APP_DIR>/m/<kind>/launcher.mjs`) is the stable thing; a shim is\n * just the name a shell can type. Two rules make these safe to write:\n *\n * 1. **Marker-required.** A file is only overwritten if it carries\n * `MANAGED_MARKER`. Anything else is left alone with a warning, because the\n * alternative is deleting a user's own `github-router` script — the\n * `lstat`-then-refuse discipline already used for `.github-router-managed`\n * (`src/lib/paths.ts:786-812`).\n * 2. **Never in `PATHS.TOOLBELT_BIN_DIR`.** `pruneUnexpected`\n * (`src/lib/toolbelt/provision.ts:96-110`) deletes anything not in its\n * manifest, so a shim placed there is deleted on the next launch — a bug that\n * only shows up on the second run.\n *\n * The directory is `<APP_DIR>/cli-bin` (`paths.ts` → `cliBinDir`), NOT\n * `~/.local/bin`: the app dir is the one location the router already owns and\n * GC already understands, and writing into `~/.local/bin` would mean guessing\n * whether that directory belongs to us. The consequence is that the directory is\n * usually NOT on PATH, so `update` prints one copy-pasteable line (`pathHint`)\n * instead of editing a shell rc file we cannot verify.\n *\n * The shims intentionally do NOT hardcode a runtime. They exec the launcher with\n * whatever `node`/`bun` the shell resolves, so a future nvm switch keeps working\n * and there is no baked interpreter path to go stale.\n */\n\nimport { realpathSync } from \"node:fs\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport { writeFileAtomic } from \"../atomic-file\"\nimport { MANAGED_MARKER, hasManagedMarker } from \"./launcher\"\nimport { type ManagedKind, cliBinDir, launcherPath, shimPath } from \"./paths\"\n\n/** The command names we own. `github-router` for self, `pi` only when managed. */\nexport function shimBases(kind: ManagedKind): Array<string> {\n return kind === \"self\" ? [\"github-router\"] : [\"pi\"]\n}\n\nexport type ShimWriteOutcome = \"written\" | \"updated\" | \"unchanged\" | \"refused\"\n\nexport interface ShimResult {\n path: string\n outcome: ShimWriteOutcome\n}\n\n/**\n * POSIX shim body.\n *\n * `exec` (not a subshell) so the payload inherits the caller's stdio, exit\n * status, and signal disposition — a hook that runs\n * `github-router internal-…` must see the child's exit code directly.\n *\n * The runtime is chosen by trying the launcher's own candidates rather than\n * hardcoding: `command -v node` then `command -v bun`. If neither exists the\n * message names the missing dependency instead of failing with \"not found\".\n */\nfunction posixShim(launcher: string): string {\n return `#!/bin/sh\n# ${MANAGED_MARKER} — generated by \\`github-router update\\`. Do not edit.\n# Re-run \\`github-router update\\` to refresh; deleting this file is safe.\nset -e\nLAUNCHER=\"${launcher}\"\nif [ ! -f \"$LAUNCHER\" ]; then\n echo \"github-router: the managed launcher is missing ($LAUNCHER).\" >&2\n echo \" Reinstall: npm install -g github-router\" >&2\n exit 78\nfi\nfor RUNTIME in node bun; do\n if command -v \"$RUNTIME\" >/dev/null 2>&1; then\n exec \"$RUNTIME\" \"$LAUNCHER\" \"$@\"\n fi\ndone\necho \"github-router: neither node nor bun is on PATH.\" >&2\necho \" Install Node.js 20+ (https://nodejs.org) and try again.\" >&2\nexit 127\n`\n}\n\n/**\n * Windows `.cmd` shim.\n *\n * `%~dp0` is deliberately NOT used: the shim lives in `<APP_DIR>\\\\cli-bin` while\n * the launcher lives in `<APP_DIR>\\\\m\\\\<kind>`, so the absolute path is baked in\n * (and rewritten by `github-router update` if the app dir ever moves).\n *\n * `where` (not `which`) is the Windows lookup, and `>nul 2>nul` keeps a missing\n * candidate from printing. `%*` forwards the original argv verbatim, which is\n * what `buildExecInvocation`'s quoting expects downstream.\n */\nfunction cmdShim(launcher: string): string {\n return `@echo off\\r\nrem ${MANAGED_MARKER} - generated by github-router update. Do not edit.\\r\nsetlocal\\r\nset \"LAUNCHER=${launcher}\"\\r\nif not exist \"%LAUNCHER%\" (\\r\n echo github-router: the managed launcher is missing ^(\"%LAUNCHER%^). 1>&2\\r\n echo Reinstall: npm install -g github-router 1>&2\\r\n exit /b 78\\r\n)\\r\nrem %ERRORLEVEL% inside a ( ) block is expanded when the BLOCK is parsed, so a\\r\nrem 'where node && ( node .. & exit /b %ERRORLEVEL% )' would report where's status\\r\nrem instead of the launcher's, so every Windows hook would look successful. The\\r\nrem goto-based flow instead of blocks: each %ERRORLEVEL% below is on its own line,\\r\nrem expanded at execution, after the child has exited. Delayed expansion is not an\\r\nrem option here — it would mangle '!' in forwarded arguments.\\r\nwhere node >nul 2>nul\\r\nif not errorlevel 1 goto :gh_shim_node\\r\nwhere bun >nul 2>nul\\r\nif not errorlevel 1 goto :gh_shim_bun\\r\necho github-router: neither node nor bun is on PATH. 1>&2\\r\necho Install Node.js 20+ ^(https://nodejs.org^) and try again. 1>&2\\r\nexit /b 127\\r\n:gh_shim_node\\r\nnode \"%LAUNCHER%\" %*\\r\nexit /b %ERRORLEVEL%\\r\n:gh_shim_bun\\r\nbun \"%LAUNCHER%\" %*\\r\nexit /b %ERRORLEVEL%\\r\n`\n}\n\n/**\n * PowerShell shim.\n *\n * Present because a `.cmd` is invisible to a bare `github-router` in PowerShell\n * only in theory (PATHEXT covers it) but fails in practice under constrained\n * execution policies that block `.cmd`. `$LASTEXITCODE` is propagated explicitly\n * — PowerShell would otherwise return 0 for a failed native command, turning a\n * hook failure into a success.\n */\nfunction ps1Shim(launcher: string): string {\n return `# ${MANAGED_MARKER} - generated by github-router update. Do not edit.\n$ErrorActionPreference = \"Stop\"\n$Launcher = '${launcher.replace(/'/g, \"''\")}'\nif (-not (Test-Path -LiteralPath $Launcher)) {\n [Console]::Error.WriteLine(\"github-router: the managed launcher is missing ($Launcher).\")\n [Console]::Error.WriteLine(\" Reinstall: npm install -g github-router\")\n exit 78\n}\nforeach ($Runtime in @(\"node\", \"bun\")) {\n $cmd = Get-Command $Runtime -ErrorAction SilentlyContinue\n if ($cmd) {\n & $cmd.Source $Launcher @args\n exit $LASTEXITCODE\n }\n}\n[Console]::Error.WriteLine(\"github-router: neither node nor bun is on PATH.\")\n[Console]::Error.WriteLine(\" Install Node.js 20+ (https://nodejs.org) and try again.\")\nexit 127\n`\n}\n\nexport interface ShimBody {\n path: string\n content: string\n /** POSIX shims need the executable bit; `.cmd`/`.ps1` must not have it set oddly. */\n mode: number\n}\n\n/** The exact files `ensureShims` should own for `kind` on this platform. */\nexport function shimBodies(\n kind: ManagedKind,\n launcher = launcherPath(kind),\n platform: NodeJS.Platform = process.platform,\n): Array<ShimBody> {\n const out: Array<ShimBody> = []\n for (const base of shimBases(kind)) {\n if (platform === \"win32\") {\n out.push({ path: shimPath(base, platform), content: cmdShim(launcher), mode: 0o644 })\n out.push({\n path: shimPath(base, platform).replace(/\\.cmd$/, \".ps1\"),\n content: ps1Shim(launcher),\n mode: 0o644,\n })\n } else {\n out.push({ path: shimPath(base, platform), content: posixShim(launcher), mode: 0o755 })\n }\n }\n return out\n}\n\n/**\n * Write (or refresh) the shims.\n *\n * Refusal is per-file and non-fatal: one file we do not own must not stop the\n * other from being written, and it must not fail an update — the payload is\n * already live by the time this runs.\n */\nexport async function ensureShims(\n kind: ManagedKind,\n launcher = launcherPath(kind),\n platform: NodeJS.Platform = process.platform,\n): Promise<Array<ShimResult>> {\n const results: Array<ShimResult> = []\n for (const body of shimBodies(kind, launcher, platform)) {\n results.push(await writeShim(body))\n }\n return results\n}\n\nasync function writeShim(body: ShimBody): Promise<ShimResult> {\n const existing = await readIfExists(body.path)\n if (existing !== null && !hasManagedMarker(existing)) {\n consola.warn(\n `Refusing to overwrite ${body.path}: it exists and was not written by github-router. Move it aside if you want the managed shim there.`,\n )\n return { path: body.path, outcome: \"refused\" }\n }\n if (existing === body.content) {\n // Content equality is not \"nothing to do\": a shim that lost its executable\n // bit (unzip, a copy, a restore from a backup, an inconsistent umask) is\n // `permission denied` forever while this branch keeps saying \"unchanged\".\n // Cheap to check, and the only repair opportunity we get.\n //\n // Keyed on the HOST (`process.platform`), not on `body`'s flavour: the mode\n // bits belong to the filesystem, not to the shim body. On Windows\n // `fs.stat().mode` is derived from the read-only attribute, so a 0o755 request\n // can never be satisfied there and this branch reported `updated` on every\n // call, forever — a caller that trusts the outcome sees an install that never\n // settles. Windows shims are `.cmd`/`.ps1` and need no executable bit.\n const mode = await fs.stat(body.path).then(\n (st) => st.mode & 0o777,\n () => null,\n )\n if (process.platform !== \"win32\" && (mode === null || (mode & body.mode) !== body.mode)) {\n await fs.chmod(body.path, body.mode).catch(() => {})\n return { path: body.path, outcome: \"updated\" }\n }\n return { path: body.path, outcome: \"unchanged\" }\n }\n\n await fs.mkdir(path.dirname(body.path), { recursive: true, mode: 0o755 })\n try {\n await writeFileAtomic(body.path, body.content, { mode: body.mode })\n } catch (err) {\n // A read-only cli-bin (or a managed container home) is not a reason to\n // fail an update; the launcher is already live and can be invoked directly.\n consola.warn(`Could not write shim ${body.path}:`, err)\n return { path: body.path, outcome: \"refused\" }\n }\n // `writeFileAtomic` sets the mode on the temp file, but a rename can drop it on\n // some Windows/network filesystems; set it again best-effort.\n await fs.chmod(body.path, body.mode).catch(() => {})\n return { path: body.path, outcome: existing === null ? \"written\" : \"updated\" }\n}\n\nasync function readIfExists(file: string): Promise<string | null> {\n try {\n // lstat first: a symlink at the shim path must be refused, not followed.\n const stat = await fs.lstat(file)\n if (!stat.isFile()) return \"\"\n return await fs.readFile(file, \"utf8\")\n } catch {\n return null\n }\n}\n\n/** Absolute path of the directory the shims live in. */\nexport function shimDir(): string {\n return cliBinDir()\n}\n\n/**\n * Whether `dir` is already on `PATH`.\n *\n * Compares resolved forms: `/var/…` vs `/private/var/…` on macOS and a\n * case-insensitive Windows path would both otherwise report \"not on PATH\" for a\n * directory that is.\n */\nexport function isOnPath(\n dir: string,\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n): boolean {\n const raw = env.PATH ?? env.Path ?? env.path ?? \"\"\n const sep = platform === \"win32\" ? \";\" : \":\"\n const target = canonicalPath(dir, platform)\n return raw.split(sep).some((entry) => entry.length > 0 && canonicalPath(entry, platform) === target)\n}\n\nfunction canonicalPath(value: string, platform: NodeJS.Platform): string {\n const trimmed = value.replace(/[/\\\\]+$/, \"\")\n if (platform === \"win32\") return trimmed.toLowerCase()\n // Resolve symlinks so `/var/...` and `/private/var/...` compare equal — macOS\n // reports one and accepts the other, so a PATH entry that IS this directory\n // would otherwise read as \"not on PATH\" and print a pointless PATH edit.\n // Only existing paths are resolved (`realpathSync` throws for the rest, and a\n // PATH entry that does not exist cannot be this directory anyway).\n try {\n return realpathSync(trimmed)\n } catch {\n return trimmed\n }\n}\n\n/**\n * One actionable line when the shim directory is not on PATH, else `null`.\n *\n * Returned rather than logged for the same reason as\n * `hookLauncherDegradedWarning`: `claude`/`codex` redirect `consola` to the error\n * log, so a warning logged deep inside update is invisible exactly where it\n * matters. The CLI prints it next to the readiness line.\n */\nexport function pathHint(\n dir = shimDir(),\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n): string | null {\n if (isOnPath(dir, env, platform)) return null\n if (platform === \"win32\") {\n // NOT `setx PATH \"%PATH%;<dir>\"`. That is the suggestion everyone writes and\n // it is actively destructive: `%PATH%` at that moment is the MACHINE path\n // followed by the USER path, so pasting it folds the machine entries into the\n // user path permanently, and `setx` truncates at 1024 characters — which\n // silently drops the tail of a developer's PATH. Print the value and let the\n // user add it through the UI, which edits only the user scope.\n return (\n `Add ${dir} to PATH to run \\`github-router\\` from any shell.\\n`\n + ` Windows: Settings > System > About > Advanced system settings > Environment Variables,\\n`\n + ` edit \"User variables\" PATH and add: ${dir}`\n )\n }\n return `Add ${dir} to PATH to run \\`github-router\\` from any shell:\\n export PATH=\"${dir}:$PATH\"`\n}\n\n/**\n * Whether `candidate` is our own shim (vs a user's real install).\n *\n * Pi precedence needs this: a `pi` on PATH that is *our* shim must not be\n * treated as the user's own Pi, or the managed install would shadow itself.\n * Detected by the marker line, never by basename — a user's `~/bin/pi` is\n * theirs.\n */\nexport async function isOurShim(candidate: string): Promise<boolean> {\n const content = await readIfExists(candidate)\n return content !== null && hasManagedMarker(content)\n}\n\n","/**\n * \"What version should be live, and how do I get there?\"\n *\n * The installer (`install.ts`) knows how to put an exact version on disk; this\n * module knows which exact version to ask for and how often to ask. Three\n * decisions here were forced by measurement, not taste:\n *\n * 1. **The installed version is authoritative, never the requested one.** A\n * corporate mirror, `min-release-age`, or a `latest` tag pointing at an older\n * release all make `npm view` disagree with what the tarball actually is. If\n * the update loop trusted its own request, it would queue the same install\n * forever: request `1.2.4`, get `1.2.3`, pointer still says `1.2.3`, next hour\n * request `1.2.4` again. So after an install we re-read the pointer and adopt\n * whatever landed.\n * 2. **A version already on disk is adopted without npm.** That covers\n * `update --version <v>` for a version that is present, a lost/restored\n * pointer, and the second of two racing installers. `rename` onto a non-empty\n * directory is `ENOTEMPTY`, so this is also what keeps the common case from\n * ever reaching a rename at all.\n * 3. **Background work is throttled and detached.** A launch must never wait on\n * npm, and a short-lived command (`--version`) must not be held open by an\n * install either. So the background path is a DETACHED child running\n * `update --self --quiet`, unref'd, with its own throttle in\n * `install-state.json`.\n */\n\nimport consola from \"consola\"\n\nimport { spawn } from \"node:child_process\"\n\nimport { resolveExecutable, runCommandCapture } from \"../exec\"\nimport { type InstallOutcome, ensureManagedInstall, gcManaged } from \"./install\"\nimport { describeOrigin, classifyOrigin } from \"./origin\"\nimport { type ManagedKind, launcherPath, npmPackageFor } from \"./paths\"\nimport { managedInstallDisabled } from \"./npm-env\"\nimport { readInstalledMarker, readPointer } from \"./pointer\"\nimport { ensureLauncher } from \"./launcher\"\nimport { mayAttemptNow, patchInstallState, readInstallState } from \"./state\"\nimport { ensureShims, pathHint } from \"./shim\"\n\n/** 5 s is enough for `npm view` and short enough not to notice. */\nconst NPM_VIEW_TIMEOUT_MS = 8000\n\nexport interface UpdateCheck {\n kind: ManagedKind\n installedVersion: string | null\n latestVersion: string | null\n /** Exact version that would be installed/adopted. */\n targetVersion: string | null\n upToDate: boolean\n registry: string | null\n entryPath: string | null\n}\n\n/**\n * Registry for a kind.\n *\n * Pi has its own resolution rule (`resolvePiRegistry()`), and it is not a detail\n * we can inherit here: a lagging corporate mirror below `PI_MIN_VERSION` makes\n * the floor unreachable, which was a real install loop. `self` uses the user's\n * configured registry, which is what they expect for the router itself.\n */\nexport async function registryFor(kind: ManagedKind): Promise<string | null> {\n if (kind === \"pi\") {\n // Imported lazily: `pi-version-check` pulls `consola` and the Pi graph, and\n // this module is reachable from the bootstrap.\n const { resolvePiRegistry } = await import(\"../pi-version-check\")\n return resolvePiRegistry()\n }\n return null\n}\n\n/** `npm view <pkg> version`, or `null` when npm is absent/offline. */\nexport async function fetchLatestVersion(kind: ManagedKind): Promise<string | null> {\n const npmPath = resolveExecutable(\"npm\")\n if (!npmPath) return null\n const registry = await registryFor(kind)\n const args = [npmPath, \"view\", npmPackageFor(kind), \"version\", \"--silent\"]\n if (registry) args.push(`--registry=${registry}`)\n try {\n const { stdout, code } = await runCommandCapture(args, { timeoutMs: NPM_VIEW_TIMEOUT_MS })\n if (code !== 0) return null\n const value = stdout.trim().split(/\\r?\\n/).pop()?.trim() ?? \"\"\n return /^\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(value) ? value : null\n } catch {\n return null\n }\n}\n\n/** Compare two semver-shaped strings on the leading `X.Y.Z`. */\nexport function isNewerVersion(installed: string | null, latest: string | null): boolean {\n if (!installed || !latest) return false\n const a = installed.split(/[.+-]/).map((n) => Number.parseInt(n, 10))\n const b = latest.split(/[.+-]/).map((n) => Number.parseInt(n, 10))\n for (let i = 0; i < 3; i++) {\n const av = Number.isNaN(a[i]) ? 0 : (a[i] ?? 0)\n const bv = Number.isNaN(b[i]) ? 0 : (b[i] ?? 0)\n if (av < bv) return true\n if (av > bv) return false\n }\n return false\n}\n\n/** What is live right now for `kind`, if anything. */\nexport async function currentManagedVersion(kind: ManagedKind): Promise<string | null> {\n const pointer = await readPointer(kind, { verifyEntry: false })\n return pointer?.version ?? null\n}\n\n/**\n * Compute the desired state without changing anything.\n *\n * `--check` uses this, and so does the background path (to decide whether to\n * spawn at all): a launch that only needs to know \"am I current\" must not write\n * the pointer, install a launcher, or touch npm's tree.\n */\nexport async function checkForUpdate(\n kind: ManagedKind,\n opts: { version?: string; force?: boolean } = {},\n): Promise<UpdateCheck> {\n const pointer = await readPointer(kind, { verifyEntry: false })\n const installedVersion = pointer?.version ?? null\n const latestVersion = opts.version ?? (await fetchLatestVersion(kind))\n const targetVersion = opts.version ?? latestVersion\n // Only when there IS an installed version: passing `\"\"` reads the kind-root\n // `.installed.json`, which is not a thing, and only a version-mismatch guard\n // made that harmless.\n const marker = installedVersion ? await readInstalledMarker(kind, installedVersion) : null\n return {\n kind,\n installedVersion,\n latestVersion,\n targetVersion,\n upToDate:\n targetVersion !== null && installedVersion !== null\n && targetVersion === installedVersion && (await readPointer(kind)) !== null,\n registry: marker?.registry ?? (await registryFor(kind)),\n entryPath: pointer?.entryPath ?? null,\n }\n}\n\nexport interface UpdateOptions {\n kind: ManagedKind\n /** Exact version to install. Defaults to npm's `latest`. */\n version?: string\n /** Ignore the backoff window and reinstall even if the version matches. */\n force?: boolean\n /** Report only; never install, never write. */\n check?: boolean\n signal?: AbortSignal\n}\n\nexport interface UpdateReport {\n check: UpdateCheck\n /** What actually happened. Absent for `--check`. */\n outcome?: InstallOutcome\n launcher?: { path: string; written: boolean }\n shims?: Array<{ path: string; outcome: string }>\n /** One-line PATH instruction when the shim dir is not on PATH. */\n pathHint?: string | null\n gc?: {\n removedVersions: Array<string>\n removedStaging: Array<string>\n removedTransient: Array<string>\n }\n}\n\n/**\n * Bring `kind` up to date: install (or adopt) the target version, publish the\n * pointer, then make the stable surface point at it.\n *\n * Order matters and is deliberate: the payload and pointer land FIRST, and the\n * launcher/shims are refreshed after. A launcher written before a failed install\n * would still be correct (it reads the pointer), but a shim written before the\n * pointer exists would advertise a managed install that is not there.\n */\nexport async function runManagedUpdate(opts: UpdateOptions): Promise<UpdateReport> {\n const registry = await registryFor(opts.kind)\n const check = await checkForUpdate(opts.kind, { version: opts.version, force: opts.force })\n if (opts.check) return { check }\n\n const target = check.targetVersion\n if (!target) {\n return {\n check,\n outcome: {\n kind: \"failed\",\n version: null,\n detail:\n \"could not determine a version to install (npm view failed). Check your connection/registry, or pass --version.\",\n },\n }\n }\n\n const outcome = await ensureManagedInstall({\n kind: opts.kind,\n version: target,\n force: opts.force,\n registry: registry ?? undefined,\n signal: opts.signal,\n })\n\n // GC runs on FAILURE TOO, not just after a successful install. A failed\n // install is precisely what leaves `.staging-*` behind, and the backoff ladder\n // (1 h → 6 h → 24 h) means a machine that keeps failing may never reach a\n // successful install to sweep it. `gcManaged` protects the pointer's version,\n // the two newest, and anything younger than 7 days, so it cannot race an\n // install that is actually in progress — and it is skipped outright when the\n // install lock is held, because the lock holder will sweep after itself.\n const gc = await gcUnderLock(opts.kind)\n\n if (outcome.kind !== \"installed\" && outcome.kind !== \"adopted\") {\n return { check, outcome, gc }\n }\n\n const launcher = await ensureLauncher(opts.kind)\n const shims = await ensureShims(opts.kind, launcherPath(opts.kind))\n return {\n check: { ...check, installedVersion: outcome.version ?? check.installedVersion, upToDate: true },\n outcome,\n launcher,\n shims,\n pathHint: pathHint(),\n gc,\n }\n}\n\n/**\n * Sweep a kind's directory, but only while holding the install lock.\n *\n * Two reasons for the lock, not one: it guarantees we never delete a\n * `.staging-*` that a live install is writing into (those are inside the 1 h TTL\n * anyway, but a slow corporate install can exceed that), and it guarantees we\n * never delete a version dir in the window between `rename` publishing it and\n * the pointer being written. Both are `skipped` conditions rather than errors —\n * the lock holder sweeps after itself.\n */\nasync function gcUnderLock(kind: ManagedKind): Promise<NonNullable<UpdateReport[\"gc\"]>> {\n const empty: NonNullable<UpdateReport[\"gc\"]> = {\n removedVersions: [],\n removedStaging: [],\n removedTransient: [],\n }\n let captured = empty\n try {\n const { withInstallLockResult } = await import(\"../update-lock\")\n const result = await withInstallLockResult(`managed-${kind}.lock`, async () => {\n const report = await gcManaged(kind)\n captured = {\n removedVersions: report.removedVersions,\n removedStaging: report.removedStaging,\n removedTransient: report.removedTransient,\n }\n })\n return result.outcome === \"ran\" ? captured : empty\n } catch {\n return empty\n }\n}\n\n/**\n * The background entry point for the bootstrap: \"install self if it is not\n * installed, and refresh it when a launch notices a newer one\".\n *\n * Returns a short description of what it decided, which the bootstrap logs at\n * debug level. Never throws and never blocks: the actual install is a DETACHED\n * child, so even `github-router --version` exits immediately.\n */\nexport async function scheduleBackgroundSelfInstall(\n opts: { quiet?: boolean } = {},\n): Promise<string> {\n // Checked before the origin probe, let alone the `npm view`: with the managed\n // layer switched off there is nothing to schedule, and an 8 s `npm view` plus a\n // detached child that immediately reports \"disabled\" is a silly price for\n // discovering that.\n if (managedInstallDisabled()) return \"managed install is disabled (GH_ROUTER_NO_MANAGED_INSTALL)\"\n\n const origin = await classifyOrigin()\n // Only disposable origins engage. `npm i -g` and a source checkout own their\n // trees (user decision 4) and a managed copy would be a second thing to update.\n if (origin.origin !== \"npx\" && origin.origin !== \"bunx\") {\n return `origin is ${describeOrigin(origin.origin)}; managed install not engaged`\n }\n\n const state = await readInstallState(\"self\")\n if (!mayAttemptNow(state)) {\n return `backing off until ${state.nextAttemptAt} after: ${state.lastError ?? \"previous failure\"}`\n }\n\n const pointer = await readPointer(\"self\")\n const installed = pointer?.version ?? null\n const latest = await fetchLatestVersion(\"self\")\n if (latest && installed === latest) return `already at ${installed}`\n\n // Reserve the attempt before spawning so concurrent launches (and a second\n // npx invocation a minute later) do not each start an npm process. A PATCH,\n // not `{...state, ...}`: the snapshot above was read before an `npm view` that\n // can take seconds, and spreading it would resurrect fields another process\n // cleared in the meantime (`npmProbe`, in particular — losing it costs a\n // 250 ms subprocess on every later launch).\n await patchInstallState(\"self\", {\n lastAttemptAt: new Date().toISOString(),\n lastOrigin: origin.origin,\n })\n\n const entry = process.argv[1]\n if (typeof entry !== \"string\" || entry.length === 0) return \"no argv[1]; cannot spawn the updater\"\n\n spawnDetachedUpdater(entry, [\n \"update\",\n \"--self\",\n // Never pull the optional payloads from a background child: they are up to\n // 547 MB and nobody is watching.\n \"--no-optional\",\n ...(opts.quiet === false ? [] : [\"--quiet\"]),\n ])\n return latest ? `queued install of ${latest}` : \"no published version visible; launch will run from the current tree\"\n}\n\n/**\n * The Pi twin of `scheduleBackgroundSelfInstall`.\n *\n * Tighter on purpose: this only ever refreshes a payload that is already live\n * (an install with nothing on disk is the launcher's foreground job, where a\n * failure can be reported to the user), and it never writes a pointer — the\n * detached `update --pi` child does that under the install lock.\n */\nexport async function scheduleBackgroundPiInstall(): Promise<string> {\n if (managedInstallDisabled()) return \"managed install is disabled (GH_ROUTER_NO_MANAGED_INSTALL)\"\n const pointer = await readPointer(\"pi\", { verifyEntry: false })\n if (!pointer) return \"no managed Pi yet\"\n\n const state = await readInstallState(\"pi\")\n if (!mayAttemptNow(state)) {\n return `backing off until ${state.nextAttemptAt} after: ${state.lastError ?? \"previous failure\"}`\n }\n\n const latest = await fetchLatestVersion(\"pi\")\n if (latest && pointer.version === latest) return `already at ${pointer.version}`\n\n await patchInstallState(\"pi\", { lastAttemptAt: new Date().toISOString() })\n const entry = process.argv[1]\n if (typeof entry !== \"string\" || entry.length === 0) return \"no argv[1]; cannot spawn the updater\"\n spawnDetachedUpdater(entry, [\"update\", \"--pi\", \"--quiet\", \"--no-optional\"])\n return latest ? `queued install of ${latest}` : \"no published Pi version visible\"\n}\n\n/**\n * Spawn a detached `node <entry> <args…>` that outlives this process.\n *\n * Detached and unref'd on purpose. The alternative — doing the install in-process\n * — holds the event loop open, so `github-router --version` would sit there for a\n * minute waiting on npm. A detached child keeps the promise \"launch is never\n * delayed by an update\", and if it is killed mid-install the staging dir is\n * swept by GC an hour later.\n *\n * `stdio: \"ignore\"` because the parent's stdio may be a Claude Code hook pipe;\n * writing the child's chatter there would corrupt a hook payload.\n */\nexport function spawnDetachedUpdater(entry: string, args: Array<string>): boolean {\n try {\n const child = spawn(process.execPath, [entry, ...args], {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n env: { ...process.env, GH_ROUTER_MANAGED_BACKGROUND: \"1\" },\n })\n child.on(\"error\", () => {})\n child.unref()\n return true\n } catch (err) {\n consola.debug(\"Could not spawn the background managed install:\", err)\n return false\n }\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkGA,SAAgB,YAAY,OAAwB;CAClD,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,IAAI,KAAK,WAAW,KAAK,KAAK,MAAM,WAAW,GAAG,KAAK,aA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AW;AAClD;;;;;;;;;AAUA,eAAsB,8BAA+C;CACnE,IAAI,uBAAuB,GAAG,OAAO;CACrC,MAAM,UAAU,MAAM,YAAY,MAAM,EAAE,aAAa,MAAM,CAAC;CAC9D,IAAI,CAAC,SAAS,OAAO;CAErB,MAAM,QAAQ,MAAM,iBAAiB,IAAI;CACzC,IAAI,CAAC,cAAc,KAAK,GACtB,OAAO,qBAAqB,MAAM,cAAc,UAAU,MAAM,aAAa;CAG/E,MAAM,SAAS,MAAM,mBAAmB,IAAI;CAC5C,IAAI,UAAU,QAAQ,YAAY,QAAQ,OAAO,cAAc,QAAQ;CAEvE,MAAM,kBAAkB,MAAM,EAAE,gCAAe,IAAI,KAAK,EAAA,CAAE,YAAY,EAAE,CAAC;CACzE,MAAM,QAAQ,QAAQ,KAAK;CAC3B,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG,OAAO;CAC5D,qBAAqB,OAAO;EAAC;EAAU;EAAQ;EAAW;CAAe,CAAC;CAC1E,OAAO,SAAS,qBAAqB,WAAW;AAClD;;;;;;;;;;;;;AAcA,SAAgB,qBAAqB,OAAe,MAA8B;CAChF,IAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,UAAU,CAAC,OAAO,GAAG,IAAI,GAAG;GACtD,UAAU;GACV,OAAO;GACP,aAAa;GACb,KAAK;IAAE,GAAG,QAAQ;IAAK,8BAA8B;GAAI;EAC3D,CAAC;EACD,MAAM,GAAG,eAAe,CAAC,CAAC;EAC1B,MAAM,MAAM;EACZ,OAAO;CACT,SAAS,KAAK;EACZ,QAAQ,MAAM,mDAAmD,GAAG;EACpE,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { n as PI_MIN_VERSION } from "./pi-version-check-BeBB0Ny9.js";
|
|
2
|
+
import { a as runManagedUpdate, d as readPointer, n as currentManagedVersion, t as checkForUpdate } from "./update-T1L7yFon.js";
|
|
3
|
+
import { a as optionalInstallDisabled, i as isOptionalPackage, n as ensureOptionalPackage, t as OPTIONAL_PACKAGES } from "./optional-DGAeyguL.js";
|
|
4
|
+
import { n as managedInstallDisabled } from "./npm-env-H60tX76c.js";
|
|
5
|
+
import { defineCommand } from "citty";
|
|
6
|
+
import consola from "consola";
|
|
7
|
+
// src/update.ts
|
|
8
|
+
/**
|
|
9
|
+
* `github-router update` — bring the managed install up to date, on demand.
|
|
10
|
+
*
|
|
11
|
+
* The user-facing half of `lib/managed-install/update.ts`. Deliberately keeps
|
|
12
|
+
* citty's surface tiny and does the reporting itself, because the interesting
|
|
13
|
+
* outcomes are not exit-code-shaped: "another process is installing", "the
|
|
14
|
+
* registry did not answer", "installed, but `~/.local/bin` is not on PATH" are
|
|
15
|
+
* all successes-with-a-note, and burying them behind a non-zero exit would make
|
|
16
|
+
* `update` unusable in a script or a shell profile.
|
|
17
|
+
*
|
|
18
|
+
* `--quiet` exists for the detached background child (`scheduleBackgroundSelfInstall`),
|
|
19
|
+
* whose stdio is `ignore` anyway but whose ARGV is visible in `ps`, and for anyone
|
|
20
|
+
* wiring this into a cron job.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Which kinds to act on.
|
|
24
|
+
*
|
|
25
|
+
* Bare `update` maintains both, which is the useful default for the user's stated
|
|
26
|
+
* goal ("my install should just stay current"). `--self`/`--pi` narrow it, and an
|
|
27
|
+
* explicit `--version` implies `--self` so `update --version 1.2.3` never
|
|
28
|
+
* accidentally re-pins Pi.
|
|
29
|
+
*/
|
|
30
|
+
function resolveKinds(opts) {
|
|
31
|
+
if (opts.self && opts.pi) return ["self", "pi"];
|
|
32
|
+
if (opts.self) return ["self"];
|
|
33
|
+
if (opts.pi) return ["pi"];
|
|
34
|
+
if (opts.version) return ["self"];
|
|
35
|
+
return ["self", "pi"];
|
|
36
|
+
}
|
|
37
|
+
function printCheck(kind, report) {
|
|
38
|
+
const label = kind === "pi" ? "Pi" : "github-router";
|
|
39
|
+
const installed = report.installedVersion ?? "not installed";
|
|
40
|
+
if (!report.targetVersion) {
|
|
41
|
+
consola.warn(`${label}: ${installed}; could not determine the latest version (npm view failed)`);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (report.upToDate) {
|
|
45
|
+
consola.info(`${label}: ${installed} (up to date)`);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
consola.info(`${label}: ${installed} → ${report.targetVersion}`);
|
|
49
|
+
}
|
|
50
|
+
/** First non-empty line of a multi-line diagnostic. */
|
|
51
|
+
function firstLine(text) {
|
|
52
|
+
if (!text) return null;
|
|
53
|
+
const line = text.split(/\r?\n/).find((part) => part.trim().length > 0);
|
|
54
|
+
return line ? line.trim() : null;
|
|
55
|
+
}
|
|
56
|
+
function printOutcome(kind, report) {
|
|
57
|
+
const label = kind === "pi" ? "Pi" : "github-router";
|
|
58
|
+
const outcome = report.outcome;
|
|
59
|
+
if (!outcome) return;
|
|
60
|
+
switch (outcome.kind) {
|
|
61
|
+
case "installed":
|
|
62
|
+
case "adopted":
|
|
63
|
+
consola.success(`${label} ${outcome.version} ${outcome.kind === "adopted" ? "adopted" : "installed"} at ${outcome.entryPath ?? ""}`);
|
|
64
|
+
if (report.launcher) consola.info(report.launcher.written ? `Launcher installed: ${report.launcher.path}` : `Launcher up to date: ${report.launcher.path}`);
|
|
65
|
+
for (const shim of report.shims ?? []) if (shim.outcome === "refused") consola.warn(`Left ${shim.path} alone (not written by github-router).`);
|
|
66
|
+
if (report.pathHint) consola.info(report.pathHint);
|
|
67
|
+
if (report.gc && report.gc.removedVersions.length > 0) consola.debug(`${label}: removed old versions ${report.gc.removedVersions.join(", ")}`);
|
|
68
|
+
return;
|
|
69
|
+
case "disabled":
|
|
70
|
+
consola.info(`${label}: managed install is disabled (${outcome.detail ?? "GH_ROUTER_NO_MANAGED_INSTALL"}).`);
|
|
71
|
+
return;
|
|
72
|
+
case "locked":
|
|
73
|
+
consola.warn(`${label}: ${outcome.detail ?? "another install is in progress"}`);
|
|
74
|
+
return;
|
|
75
|
+
case "no-npm":
|
|
76
|
+
consola.warn(`${label}: ${outcome.detail ?? "npm not found on PATH"}`);
|
|
77
|
+
return;
|
|
78
|
+
case "backoff":
|
|
79
|
+
consola.warn(`${label}: ${firstLine(outcome.detail) ?? "backing off after a failed attempt"}`);
|
|
80
|
+
return;
|
|
81
|
+
case "failed":
|
|
82
|
+
consola.error(`${label}: ${firstLine(outcome.detail) ?? "install failed"}`);
|
|
83
|
+
if (outcome.detail && outcome.detail.includes("\n")) consola.debug(outcome.detail);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async function runUpdate(opts) {
|
|
88
|
+
let kinds = opts.optionalOnly ? [] : resolveKinds(opts);
|
|
89
|
+
let failures = 0;
|
|
90
|
+
if (kinds.length > 0 && managedInstallDisabled()) {
|
|
91
|
+
if (!opts.quiet) consola.info("managed install is disabled (GH_ROUTER_NO_MANAGED_INSTALL), so there is nothing to install or check for github-router/Pi.");
|
|
92
|
+
kinds = [];
|
|
93
|
+
}
|
|
94
|
+
for (const kind of kinds) {
|
|
95
|
+
if (opts.check) {
|
|
96
|
+
const report = await checkForUpdate(kind, {
|
|
97
|
+
version: opts.version,
|
|
98
|
+
force: opts.force
|
|
99
|
+
});
|
|
100
|
+
if (!opts.quiet) printCheck(kind, report);
|
|
101
|
+
if (report.targetVersion === null) failures += 1;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const report = await runManagedUpdate({
|
|
105
|
+
kind,
|
|
106
|
+
version: opts.version,
|
|
107
|
+
force: opts.force,
|
|
108
|
+
check: false
|
|
109
|
+
});
|
|
110
|
+
if (!opts.quiet) printOutcome(kind, report);
|
|
111
|
+
if (report.outcome?.kind === "failed") failures += 1;
|
|
112
|
+
}
|
|
113
|
+
if (opts.check && opts.optionalOnly) {
|
|
114
|
+
if (!opts.quiet) consola.warn("--check does not inspect the optional payloads (they are installed on demand), so --check --optional-only has nothing to report.");
|
|
115
|
+
return failures === 0 ? 0 : 1;
|
|
116
|
+
}
|
|
117
|
+
if (opts.optional !== false && !opts.check && !optionalInstallDisabled()) {
|
|
118
|
+
const wanted = opts.optionalPkg === void 0 ? OPTIONAL_PACKAGES : [opts.optionalPkg];
|
|
119
|
+
const results = [];
|
|
120
|
+
for (const pkg of wanted) {
|
|
121
|
+
const result = await ensureOptionalPackage(pkg, { force: opts.force });
|
|
122
|
+
results.push({
|
|
123
|
+
pkg,
|
|
124
|
+
...result
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
for (const result of results) if (result.dir) {
|
|
128
|
+
if (!opts.quiet) consola.success(`${result.pkg} ready at ${result.dir}`);
|
|
129
|
+
} else if (!opts.quiet) consola.warn(`${result.pkg} unavailable: ${result.detail ?? "unknown error"}`);
|
|
130
|
+
}
|
|
131
|
+
return failures === 0 ? 0 : 1;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* A bare `update` may also be the FIRST thing a user runs after `npm i -g`, in
|
|
135
|
+
* which case there is nothing managed yet and the honest answer is "here is where
|
|
136
|
+
* it would go". `checkForUpdate` already reports that as "not installed → latest",
|
|
137
|
+
* so nothing extra is needed; the pointer read below is only for the debug line.
|
|
138
|
+
*/
|
|
139
|
+
const update = defineCommand({
|
|
140
|
+
meta: {
|
|
141
|
+
name: "update",
|
|
142
|
+
description: `Install or refresh the managed github-router/Pi payload (Pi floor ${PI_MIN_VERSION})`
|
|
143
|
+
},
|
|
144
|
+
args: {
|
|
145
|
+
self: {
|
|
146
|
+
type: "boolean",
|
|
147
|
+
default: false,
|
|
148
|
+
description: "Update github-router only"
|
|
149
|
+
},
|
|
150
|
+
pi: {
|
|
151
|
+
type: "boolean",
|
|
152
|
+
default: false,
|
|
153
|
+
description: "Update the managed Pi only"
|
|
154
|
+
},
|
|
155
|
+
check: {
|
|
156
|
+
type: "boolean",
|
|
157
|
+
default: false,
|
|
158
|
+
description: "Report what would change; install nothing"
|
|
159
|
+
},
|
|
160
|
+
version: {
|
|
161
|
+
type: "string",
|
|
162
|
+
description: "Install an exact version instead of npm's latest"
|
|
163
|
+
},
|
|
164
|
+
force: {
|
|
165
|
+
type: "boolean",
|
|
166
|
+
default: false,
|
|
167
|
+
description: "Ignore the failure backoff and reinstall even if the version matches"
|
|
168
|
+
},
|
|
169
|
+
quiet: {
|
|
170
|
+
type: "boolean",
|
|
171
|
+
default: false,
|
|
172
|
+
description: "Only report problems (used by the background self-install)"
|
|
173
|
+
},
|
|
174
|
+
"optional-only": {
|
|
175
|
+
type: "boolean",
|
|
176
|
+
default: false,
|
|
177
|
+
description: "Install the heavy optional payloads and nothing else (internal: what a rerank or structural search spawns on demand)"
|
|
178
|
+
},
|
|
179
|
+
"optional-pkg": {
|
|
180
|
+
type: "string",
|
|
181
|
+
description: `Install only this optional payload (${OPTIONAL_PACKAGES.join(", ")}). Internal: used by --optional-only spawns so a grammar miss does not download the ONNX runtime.`
|
|
182
|
+
},
|
|
183
|
+
optional: {
|
|
184
|
+
type: "boolean",
|
|
185
|
+
default: true,
|
|
186
|
+
description: "Also install the heavy optional payloads (transformers/ONNX for reranking, tree-sitter grammars) into the shared optional dir. --no-optional skips them; reranking then falls back to BM25F and structural ranking to the regex heuristic."
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
async run({ args }) {
|
|
190
|
+
const rawOptionalPkg = args["optional-pkg"];
|
|
191
|
+
if (rawOptionalPkg !== void 0 && !(typeof rawOptionalPkg === "string" && isOptionalPackage(rawOptionalPkg))) {
|
|
192
|
+
consola.error(`--optional-pkg must be one of: ${OPTIONAL_PACKAGES.join(", ")} (got ${JSON.stringify(rawOptionalPkg)}).`);
|
|
193
|
+
process.exitCode = 2;
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const pointer = await readPointer("self", { verifyEntry: false });
|
|
197
|
+
consola.debug(`managed: live self version ${pointer?.version ?? "none"} (live pointer ${await currentManagedVersion("self") ?? "none"})`);
|
|
198
|
+
const code = await runUpdate({
|
|
199
|
+
self: args.self,
|
|
200
|
+
pi: args.pi,
|
|
201
|
+
check: args.check,
|
|
202
|
+
version: typeof args.version === "string" ? args.version : void 0,
|
|
203
|
+
force: args.force,
|
|
204
|
+
quiet: args.quiet,
|
|
205
|
+
optional: args.optional,
|
|
206
|
+
optionalOnly: args["optional-only"],
|
|
207
|
+
...typeof rawOptionalPkg === "string" && isOptionalPackage(rawOptionalPkg) ? { optionalPkg: rawOptionalPkg } : {}
|
|
208
|
+
});
|
|
209
|
+
process.exitCode = code;
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
export { update };
|
|
213
|
+
|
|
214
|
+
//# sourceMappingURL=update-fEgWTrIx.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"update-fEgWTrIx.js","names":[],"sources":["../src/update.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * `github-router update` — bring the managed install up to date, on demand.\n *\n * The user-facing half of `lib/managed-install/update.ts`. Deliberately keeps\n * citty's surface tiny and does the reporting itself, because the interesting\n * outcomes are not exit-code-shaped: \"another process is installing\", \"the\n * registry did not answer\", \"installed, but `~/.local/bin` is not on PATH\" are\n * all successes-with-a-note, and burying them behind a non-zero exit would make\n * `update` unusable in a script or a shell profile.\n *\n * `--quiet` exists for the detached background child (`scheduleBackgroundSelfInstall`),\n * whose stdio is `ignore` anyway but whose ARGV is visible in `ps`, and for anyone\n * wiring this into a cron job.\n */\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { PI_MIN_VERSION } from \"./lib/pi-version-check\"\nimport { readPointer } from \"./lib/managed-install/pointer\"\nimport {\n OPTIONAL_PACKAGES,\n type OptionalPackage,\n ensureOptionalPackage,\n isOptionalPackage,\n optionalInstallDisabled,\n} from \"./lib/managed-install/optional\"\nimport { managedInstallDisabled } from \"./lib/managed-install/npm-env\"\nimport {\n checkForUpdate,\n currentManagedVersion,\n runManagedUpdate,\n type UpdateReport,\n} from \"./lib/managed-install/update\"\nimport type { ManagedKind } from \"./lib/managed-install/paths\"\n\nexport interface RunUpdateOptions {\n self: boolean\n pi: boolean\n check: boolean\n version?: string\n force: boolean\n quiet: boolean\n /** Also install the heavy optional payloads (default on, `--no-optional`). */\n optional?: boolean\n /**\n * Install the optional payloads and nothing else.\n *\n * This is what the on-demand path spawns (`scheduleOptionalInstall`): a rerank\n * or a structural search that found no payload wants THAT payload, not a\n * self-update, and definitely not a managed Pi appearing on a developer's\n * source checkout as a side effect of a search.\n */\n optionalOnly?: boolean\n /**\n * Install only this optional payload (`--optional-pkg <name>`).\n *\n * What `scheduleOptionalInstall` passes: a structural-search miss wants the\n * grammar set, and must not start a 547 MB ONNX download as a side effect.\n */\n optionalPkg?: OptionalPackage\n}\n\n/**\n * Which kinds to act on.\n *\n * Bare `update` maintains both, which is the useful default for the user's stated\n * goal (\"my install should just stay current\"). `--self`/`--pi` narrow it, and an\n * explicit `--version` implies `--self` so `update --version 1.2.3` never\n * accidentally re-pins Pi.\n */\nexport function resolveKinds(opts: Pick<RunUpdateOptions, \"self\" | \"pi\" | \"version\">): Array<ManagedKind> {\n if (opts.self && opts.pi) return [\"self\", \"pi\"]\n if (opts.self) return [\"self\"]\n if (opts.pi) return [\"pi\"]\n if (opts.version) return [\"self\"]\n return [\"self\", \"pi\"]\n}\n\nfunction printCheck(kind: ManagedKind, report: UpdateReport[\"check\"]): void {\n const label = kind === \"pi\" ? \"Pi\" : \"github-router\"\n const installed = report.installedVersion ?? \"not installed\"\n if (!report.targetVersion) {\n // `npm view` failed. Saying \"0.3.379 → unknown\" presents a network failure as\n // \"maybe there is a newer one\", which in a cron job is indistinguishable from\n // a real pending update. Say the thing that is actually true, and exit\n // non-zero (the caller counts a null target as a failure).\n consola.warn(`${label}: ${installed}; could not determine the latest version (npm view failed)`)\n return\n }\n if (report.upToDate) {\n consola.info(`${label}: ${installed} (up to date)`)\n return\n }\n consola.info(`${label}: ${installed} → ${report.targetVersion}`)\n}\n\n/** First non-empty line of a multi-line diagnostic. */\nfunction firstLine(text: string | undefined): string | null {\n if (!text) return null\n const line = text.split(/\\r?\\n/).find((part) => part.trim().length > 0)\n return line ? line.trim() : null\n}\n\nfunction printOutcome(kind: ManagedKind, report: UpdateReport): void {\n const label = kind === \"pi\" ? \"Pi\" : \"github-router\"\n const outcome = report.outcome\n if (!outcome) return\n switch (outcome.kind) {\n case \"installed\":\n case \"adopted\":\n consola.success(\n `${label} ${outcome.version} ${outcome.kind === \"adopted\" ? \"adopted\" : \"installed\"} at ${outcome.entryPath ?? \"\"}`,\n )\n if (report.launcher) {\n consola.info(\n report.launcher.written\n ? `Launcher installed: ${report.launcher.path}`\n : `Launcher up to date: ${report.launcher.path}`,\n )\n }\n for (const shim of report.shims ?? []) {\n if (shim.outcome === \"refused\") {\n consola.warn(`Left ${shim.path} alone (not written by github-router).`)\n }\n }\n if (report.pathHint) {\n // Printed as info, not warn: nothing is broken, the command just is not\n // reachable by name yet. One copy-pasteable line, no rc editing.\n consola.info(report.pathHint)\n }\n if (report.gc && report.gc.removedVersions.length > 0) {\n consola.debug(`${label}: removed old versions ${report.gc.removedVersions.join(\", \")}`)\n }\n return\n case \"disabled\":\n consola.info(`${label}: managed install is disabled (${outcome.detail ?? \"GH_ROUTER_NO_MANAGED_INSTALL\"}).`)\n return\n case \"locked\":\n consola.warn(`${label}: ${outcome.detail ?? \"another install is in progress\"}`)\n return\n case \"no-npm\":\n consola.warn(`${label}: ${outcome.detail ?? \"npm not found on PATH\"}`)\n return\n case \"backoff\":\n consola.warn(`${label}: ${firstLine(outcome.detail) ?? \"backing off after a failed attempt\"}`)\n return\n case \"failed\":\n // The detail embeds npm's stderr. Print its first line as the message and\n // the rest at debug, so a broken registry is one readable sentence on the\n // console instead of a wall of npm internals ending mid-filename — while\n // still being available under --verbose.\n consola.error(`${label}: ${firstLine(outcome.detail) ?? \"install failed\"}`)\n if (outcome.detail && outcome.detail.includes(\"\\n\")) consola.debug(outcome.detail)\n return\n }\n}\n\nexport async function runUpdate(opts: RunUpdateOptions): Promise<number> {\n let kinds = opts.optionalOnly ? [] : resolveKinds(opts)\n let failures = 0\n\n if (kinds.length > 0 && managedInstallDisabled()) {\n // `--check` would otherwise print \"not installed → 0.3.379\" on a machine\n // where the managed layer is switched OFF, which reads as an update that is\n // about to happen and never will.\n if (!opts.quiet) {\n consola.info(\n \"managed install is disabled (GH_ROUTER_NO_MANAGED_INSTALL), so there is nothing to install or check for github-router/Pi.\",\n )\n }\n // NOT `return 0`: the optional payloads have their own, unrelated off switch\n // (`GH_ROUTER_NO_OPTIONAL_INSTALL`). Returning here would make a bare\n // `github-router update` on a machine with the managed layer disabled skip\n // reranking/grammar payloads that the user never opted out of — the two\n // switches are documented as independent, so they must behave that way.\n kinds = []\n }\n\n for (const kind of kinds) {\n if (opts.check) {\n const report = await checkForUpdate(kind, { version: opts.version, force: opts.force })\n if (!opts.quiet) printCheck(kind, report)\n // \"Could not find out\" is a FAILURE for anything that parses the exit code\n // (a cron job, a CI step, a wrapper script). Printing a warning and exiting\n // 0 makes a broken registry indistinguishable from \"you are up to date\".\n if (report.targetVersion === null) failures += 1\n continue\n }\n const report = await runManagedUpdate({\n kind,\n version: opts.version,\n force: opts.force,\n check: false,\n })\n if (!opts.quiet) printOutcome(kind, report)\n if (report.outcome?.kind === \"failed\") failures += 1\n }\n\n if (opts.check && opts.optionalOnly) {\n // Both halves of this combination are silently empty: `--optional-only` makes\n // `kinds` empty, and `--check` skips the optional block. Left alone the\n // command prints nothing and exits 0, which reads as \"everything is fine\".\n if (!opts.quiet) {\n consola.warn(\n \"--check does not inspect the optional payloads (they are installed on demand), so --check --optional-only has nothing to report.\",\n )\n }\n return failures === 0 ? 0 : 1\n }\n\n if (opts.optional !== false && !opts.check && !optionalInstallDisabled()) {\n // Optional payloads are the difference between a 66 MB and a 586 MB install,\n // so they are NOT installed with the package. `update` is where a user asks\n // for the whole thing, and where a failure is visible instead of silently\n // degrading search quality. A failure here is a WARNING, never a non-zero\n // exit: reranking and structural search both have documented fallbacks.\n const wanted: ReadonlyArray<OptionalPackage> =\n opts.optionalPkg === undefined ? OPTIONAL_PACKAGES : [opts.optionalPkg]\n const results = []\n for (const pkg of wanted) {\n const result = await ensureOptionalPackage(pkg, { force: opts.force })\n results.push({ pkg, ...result })\n }\n for (const result of results) {\n if (result.dir) {\n if (!opts.quiet) consola.success(`${result.pkg} ready at ${result.dir}`)\n } else if (!opts.quiet) {\n consola.warn(`${result.pkg} unavailable: ${result.detail ?? \"unknown error\"}`)\n }\n }\n }\n\n return failures === 0 ? 0 : 1\n}\n\n/**\n * A bare `update` may also be the FIRST thing a user runs after `npm i -g`, in\n * which case there is nothing managed yet and the honest answer is \"here is where\n * it would go\". `checkForUpdate` already reports that as \"not installed → latest\",\n * so nothing extra is needed; the pointer read below is only for the debug line.\n */\nexport const update = defineCommand({\n meta: {\n name: \"update\",\n description: `Install or refresh the managed github-router/Pi payload (Pi floor ${PI_MIN_VERSION})`,\n },\n args: {\n self: {\n type: \"boolean\",\n default: false,\n description: \"Update github-router only\",\n },\n pi: {\n type: \"boolean\",\n default: false,\n description: \"Update the managed Pi only\",\n },\n check: {\n type: \"boolean\",\n default: false,\n description: \"Report what would change; install nothing\",\n },\n version: {\n type: \"string\",\n description: \"Install an exact version instead of npm's latest\",\n },\n force: {\n type: \"boolean\",\n default: false,\n description: \"Ignore the failure backoff and reinstall even if the version matches\",\n },\n quiet: {\n type: \"boolean\",\n default: false,\n description: \"Only report problems (used by the background self-install)\",\n },\n \"optional-only\": {\n type: \"boolean\",\n default: false,\n description:\n \"Install the heavy optional payloads and nothing else (internal: what a rerank or structural search spawns on demand)\",\n },\n \"optional-pkg\": {\n type: \"string\",\n description: `Install only this optional payload (${OPTIONAL_PACKAGES.join(\", \")}). Internal: used by --optional-only spawns so a grammar miss does not download the ONNX runtime.`,\n },\n optional: {\n type: \"boolean\",\n default: true,\n description:\n \"Also install the heavy optional payloads (transformers/ONNX for reranking, tree-sitter grammars) into the shared optional dir. --no-optional skips them; reranking then falls back to BM25F and structural ranking to the regex heuristic.\",\n },\n },\n async run({ args }) {\n // Validate BEFORE any work. An unknown name must not degrade to \"install\n // everything\": for this pair that means a 547 MB ONNX download triggered by\n // a typo, and it must not degrade to \"install nothing\" either, which would\n // look like success.\n const rawOptionalPkg = args[\"optional-pkg\"]\n if (\n rawOptionalPkg !== undefined\n && !(typeof rawOptionalPkg === \"string\" && isOptionalPackage(rawOptionalPkg))\n ) {\n consola.error(\n `--optional-pkg must be one of: ${OPTIONAL_PACKAGES.join(\", \")} (got ${JSON.stringify(rawOptionalPkg)}).`,\n )\n process.exitCode = 2\n return\n }\n\n const pointer = await readPointer(\"self\", { verifyEntry: false })\n consola.debug(\n `managed: live self version ${pointer?.version ?? \"none\"} (live pointer ${await currentManagedVersion(\"self\") ?? \"none\"})`,\n )\n const code = await runUpdate({\n self: args.self,\n pi: args.pi,\n check: args.check,\n version: typeof args.version === \"string\" ? args.version : undefined,\n force: args.force,\n quiet: args.quiet,\n optional: args.optional,\n optionalOnly: args[\"optional-only\"],\n ...(typeof rawOptionalPkg === \"string\" && isOptionalPackage(rawOptionalPkg)\n ? { optionalPkg: rawOptionalPkg }\n : {}),\n })\n process.exitCode = code\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,SAAgB,aAAa,MAA6E;CACxG,IAAI,KAAK,QAAQ,KAAK,IAAI,OAAO,CAAC,QAAQ,IAAI;CAC9C,IAAI,KAAK,MAAM,OAAO,CAAC,MAAM;CAC7B,IAAI,KAAK,IAAI,OAAO,CAAC,IAAI;CACzB,IAAI,KAAK,SAAS,OAAO,CAAC,MAAM;CAChC,OAAO,CAAC,QAAQ,IAAI;AACtB;AAEA,SAAS,WAAW,MAAmB,QAAqC;CAC1E,MAAM,QAAQ,SAAS,OAAO,OAAO;CACrC,MAAM,YAAY,OAAO,oBAAoB;CAC7C,IAAI,CAAC,OAAO,eAAe;EAKzB,QAAQ,KAAK,GAAG,MAAM,IAAI,UAAU,2DAA2D;EAC/F;CACF;CACA,IAAI,OAA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