github-router 0.3.354 → 0.3.356

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/dist/ado-tools-DokE2DbX.js +1 -0
  2. package/dist/{aic-ledger-BdvCgRmx.js → aic-ledger-BuFrsGur.js} +3 -3
  3. package/dist/{aic-ledger-BdvCgRmx.js.map → aic-ledger-BuFrsGur.js.map} +1 -1
  4. package/dist/{aic-statusline-settings-EdsV1gzY.js → aic-statusline-settings-DBS9sEGC.js} +2 -2
  5. package/dist/{aic-statusline-settings-EdsV1gzY.js.map → aic-statusline-settings-DBS9sEGC.js.map} +1 -1
  6. package/dist/{attribution-settings-8Uv97n9j.js → attribution-settings-CnmV9MSv.js} +11 -11
  7. package/dist/{attribution-settings-8Uv97n9j.js.map → attribution-settings-CnmV9MSv.js.map} +1 -1
  8. package/dist/{auth-a_1lXYZ1.js → auth-DFawaLJU.js} +4 -4
  9. package/dist/{auth-a_1lXYZ1.js.map → auth-DFawaLJU.js.map} +1 -1
  10. package/dist/{bluebird-client-ltPIiyJU.js → bluebird-client-C29-JOkG.js} +92 -4
  11. package/dist/bluebird-client-C29-JOkG.js.map +1 -0
  12. package/dist/bluebird-client-DGE3WZqh.js +1 -0
  13. package/dist/browser-ext/manifest.json +1 -1
  14. package/dist/{check-usage-Bsbc-Sn6.js → check-usage-BkVEl-Su.js} +4 -4
  15. package/dist/{check-usage-Bsbc-Sn6.js.map → check-usage-BkVEl-Su.js.map} +1 -1
  16. package/dist/{claude-C_1OM7ce.js → claude-DvR3Y7fu.js} +28 -27
  17. package/dist/claude-DvR3Y7fu.js.map +1 -0
  18. package/dist/{claude-md-injection-CDOoGNEJ.js → claude-md-injection-Cpzolxin.js} +4 -4
  19. package/dist/{claude-md-injection-CDOoGNEJ.js.map → claude-md-injection-Cpzolxin.js.map} +1 -1
  20. package/dist/{codex-5eTmciDG.js → codex-DQpSPjpQ.js} +9 -9
  21. package/dist/{codex-5eTmciDG.js.map → codex-DQpSPjpQ.js.map} +1 -1
  22. package/dist/{copilot-discount-kpOLluHm.js → copilot-discount-Bsmv_3OX.js} +2 -2
  23. package/dist/{copilot-discount-kpOLluHm.js.map → copilot-discount-Bsmv_3OX.js.map} +1 -1
  24. package/dist/{debug-BtqbflcL.js → debug-DkNTuErv.js} +2 -2
  25. package/dist/{debug-BtqbflcL.js.map → debug-DkNTuErv.js.map} +1 -1
  26. package/dist/engine-DgmsdkCe.js +1 -0
  27. package/dist/{gate-discovery-CqJVzT_D.js → gate-discovery-B2x_8hNL.js} +5 -5
  28. package/dist/{gate-discovery-CqJVzT_D.js.map → gate-discovery-B2x_8hNL.js.map} +1 -1
  29. package/dist/{get-copilot-usage-0_S8pRWJ.js → get-copilot-usage-P9chc-X2.js} +3 -3
  30. package/dist/{get-copilot-usage-0_S8pRWJ.js.map → get-copilot-usage-P9chc-X2.js.map} +1 -1
  31. package/dist/hooks.mjs +2 -0
  32. package/dist/hooks.sha256 +1 -1
  33. package/dist/{index-cmd-CJXUOH4q.js → index-cmd-BkfYr9FH.js} +4 -4
  34. package/dist/{index-cmd-CJXUOH4q.js.map → index-cmd-BkfYr9FH.js.map} +1 -1
  35. package/dist/{internal-aic-status-wYPsCG4r.js → internal-aic-status-C6L4-ncP.js} +3 -3
  36. package/dist/{internal-aic-status-wYPsCG4r.js.map → internal-aic-status-C6L4-ncP.js.map} +1 -1
  37. package/dist/{internal-artifact-open-C67gDjKo.js → internal-artifact-open-DgJ3PCtt.js} +2 -2
  38. package/dist/{internal-artifact-open-C67gDjKo.js.map → internal-artifact-open-DgJ3PCtt.js.map} +1 -1
  39. package/dist/{internal-fast-dispatch-guard-D_TCtJhQ.js → internal-fast-dispatch-guard-CgBtUsQI.js} +2 -2
  40. package/dist/{internal-fast-dispatch-guard-D_TCtJhQ.js.map → internal-fast-dispatch-guard-CgBtUsQI.js.map} +1 -1
  41. package/dist/{internal-fast-dispatch-guard-A8teEib4.js → internal-fast-dispatch-guard-CicGz6oM.js} +1 -1
  42. package/dist/{internal-first-mate-guard-BJvCsVlU.js → internal-first-mate-guard-BfWYN6Jb.js} +3 -3
  43. package/dist/{internal-first-mate-guard-BJvCsVlU.js.map → internal-first-mate-guard-BfWYN6Jb.js.map} +1 -1
  44. package/dist/{internal-first-mate-guard-D-IQGiTs.js → internal-first-mate-guard-DTXPT7JW.js} +1 -1
  45. package/dist/{internal-max-dispatch-guard-D7ByWH4v.js → internal-max-dispatch-guard-CY8l9SDw.js} +3 -3
  46. package/dist/{internal-max-dispatch-guard-D7ByWH4v.js.map → internal-max-dispatch-guard-CY8l9SDw.js.map} +1 -1
  47. package/dist/{internal-max-dispatch-guard-BM_B15EH.js → internal-max-dispatch-guard-mNl9CCir.js} +1 -1
  48. package/dist/{internal-plan-review-DIvaBBUd.js → internal-plan-review-2OHTs8Nk.js} +3 -3
  49. package/dist/{internal-plan-review-DIvaBBUd.js.map → internal-plan-review-2OHTs8Nk.js.map} +1 -1
  50. package/dist/{internal-prompt-submit-C77GnEaW.js → internal-prompt-submit-CkfUcu34.js} +4 -4
  51. package/dist/{internal-prompt-submit-C77GnEaW.js.map → internal-prompt-submit-CkfUcu34.js.map} +1 -1
  52. package/dist/{internal-prompt-submit-CDTwamkW.js → internal-prompt-submit-DZ_-2A6a.js} +2 -2
  53. package/dist/{internal-rebrief-DZygfGHp.js → internal-rebrief-EhBHAHsz.js} +4 -4
  54. package/dist/{internal-rebrief-DZygfGHp.js.map → internal-rebrief-EhBHAHsz.js.map} +1 -1
  55. package/dist/{internal-session-bind-CQLDPuTx.js → internal-session-bind-Bv50ju2n.js} +2 -2
  56. package/dist/{internal-session-bind-CQLDPuTx.js.map → internal-session-bind-Bv50ju2n.js.map} +1 -1
  57. package/dist/{internal-stop-hook-Dn_AF0BF.js → internal-stop-hook-Dm-m8RoA.js} +5 -5
  58. package/dist/{internal-stop-hook-Dn_AF0BF.js.map → internal-stop-hook-Dm-m8RoA.js.map} +1 -1
  59. package/dist/{internal-stop-review-X7zRRhyc.js → internal-stop-review-K6f8xsCh.js} +2 -2
  60. package/dist/{internal-stop-review-X7zRRhyc.js.map → internal-stop-review-K6f8xsCh.js.map} +1 -1
  61. package/dist/{internal-worker-guard-wP3UN-3D.js → internal-worker-guard-GVhTjVlR.js} +2 -2
  62. package/dist/{internal-worker-guard-wP3UN-3D.js.map → internal-worker-guard-GVhTjVlR.js.map} +1 -1
  63. package/dist/{internal-workspace-header-DiUnkUeU.js → internal-workspace-header-d2hFf9Jy.js} +2 -2
  64. package/dist/{internal-workspace-header-DiUnkUeU.js.map → internal-workspace-header-d2hFf9Jy.js.map} +1 -1
  65. package/dist/lifecycle-BU_d2QMs.js +1 -0
  66. package/dist/lifecycle-ByFyew_w.js +1 -0
  67. package/dist/{lifecycle-BJ83L0tz.js → lifecycle-C6cxM_Nk.js} +2 -2
  68. package/dist/{lifecycle-BJ83L0tz.js.map → lifecycle-C6cxM_Nk.js.map} +1 -1
  69. package/dist/{lifecycle-aApO0hZW.js → lifecycle-pl9QpvqD.js} +2 -2
  70. package/dist/{lifecycle-aApO0hZW.js.map → lifecycle-pl9QpvqD.js.map} +1 -1
  71. package/dist/main.js +23 -23
  72. package/dist/{max-profile-contract-CMvzKSsg.js → max-profile-contract-Cx5_Z1Y7.js} +2 -2
  73. package/dist/{max-profile-contract-CMvzKSsg.js.map → max-profile-contract-Cx5_Z1Y7.js.map} +1 -1
  74. package/dist/{mcp-workspace-header-DBQugQlQ.js → mcp-workspace-header-Su8uUxJg.js} +2 -2
  75. package/dist/{mcp-workspace-header-DBQugQlQ.js.map → mcp-workspace-header-Su8uUxJg.js.map} +1 -1
  76. package/dist/{models-JIvKAGn0.js → models-D8v8OTbN.js} +3 -3
  77. package/dist/{models-JIvKAGn0.js.map → models-D8v8OTbN.js.map} +1 -1
  78. package/dist/{orchestration-D-S_0GVt.js → orchestration-Bov4rZEi.js} +2 -2
  79. package/dist/{orchestration-D-S_0GVt.js.map → orchestration-Bov4rZEi.js.map} +1 -1
  80. package/dist/{paths-xTSEAWfN.js → paths-BSI_EtDT.js} +18 -18
  81. package/dist/paths-BSI_EtDT.js.map +1 -0
  82. package/dist/paths-BYxX9DfA.js +1 -0
  83. package/dist/{peer-mcp-personas-DlF1dKCs.js → peer-mcp-personas-CVxXq1Q-.js} +2859 -170
  84. package/dist/peer-mcp-personas-CVxXq1Q-.js.map +1 -0
  85. package/dist/{pi-2m2IgZlm.js → pi-D-BgxVhx.js} +22 -16
  86. package/dist/{pi-2m2IgZlm.js.map → pi-D-BgxVhx.js.map} +1 -1
  87. package/dist/{plan-review-hook-BQ29WGv7.js → plan-review-hook-CHK1wL3-.js} +3 -3
  88. package/dist/{plan-review-hook-BQ29WGv7.js.map → plan-review-hook-CHK1wL3-.js.map} +1 -1
  89. package/dist/{provision-DLGlhu3a.js → provision-DYmZgZDr.js} +6 -5
  90. package/dist/provision-DYmZgZDr.js.map +1 -0
  91. package/dist/{self-invocation-Dr5zlbpM.js → self-invocation-Dk_UHD_v.js} +2 -2
  92. package/dist/{self-invocation-Dr5zlbpM.js.map → self-invocation-Dk_UHD_v.js.map} +1 -1
  93. package/dist/{serve-8tXHVHOr.js → serve-DfxxKLFl.js} +25 -17
  94. package/dist/serve-DfxxKLFl.js.map +1 -0
  95. package/dist/{server-setup-BBSmse1J.js → server-setup-VYf8ptCH.js} +168 -33
  96. package/dist/server-setup-VYf8ptCH.js.map +1 -0
  97. package/dist/{service-backend-DV1u5x0Q.js → service-backend-DHyd9vjW.js} +3 -3
  98. package/dist/{service-backend-DV1u5x0Q.js.map → service-backend-DHyd9vjW.js.map} +1 -1
  99. package/dist/{start-B7jTBpAc.js → start-BsY1d26G.js} +4 -4
  100. package/dist/{start-B7jTBpAc.js.map → start-BsY1d26G.js.map} +1 -1
  101. package/dist/{state-CfEVoqBM.js → state-CiwCLVDZ.js} +3 -1
  102. package/dist/{state-CfEVoqBM.js.map → state-CiwCLVDZ.js.map} +1 -1
  103. package/dist/{static-context-pack-BRqt4ajJ.js → static-context-pack-dKrzbfIN.js} +3 -3
  104. package/dist/{static-context-pack-BRqt4ajJ.js.map → static-context-pack-dKrzbfIN.js.map} +1 -1
  105. package/dist/{stop-gate-hook-BYd0NruJ.js → stop-gate-hook-CC7VWkZM.js} +3 -3
  106. package/dist/{stop-gate-hook-BYd0NruJ.js.map → stop-gate-hook-CC7VWkZM.js.map} +1 -1
  107. package/dist/{stop-gate-policy-FGAfpfc-.js → stop-gate-policy-CoR8xKNQ.js} +2 -2
  108. package/dist/{stop-gate-policy-FGAfpfc-.js.map → stop-gate-policy-CoR8xKNQ.js.map} +1 -1
  109. package/dist/{token-CTf5jCmP.js → token-CA2s70qj.js} +3 -3
  110. package/dist/{token-CTf5jCmP.js.map → token-CA2s70qj.js.map} +1 -1
  111. package/dist/{worker-dispatch-BjfROaic.js → worker-dispatch-B_rriT7z.js} +2 -2
  112. package/dist/{worker-dispatch-BjfROaic.js.map → worker-dispatch-B_rriT7z.js.map} +1 -1
  113. package/docs/azure-mcp.md +38 -25
  114. package/package.json +1 -1
  115. package/dist/ado-tools-CN4i9OVl.js +0 -1
  116. package/dist/bluebird-client-ltPIiyJU.js.map +0 -1
  117. package/dist/bluebird-client-mr3M67k-.js +0 -1
  118. package/dist/claude-C_1OM7ce.js.map +0 -1
  119. package/dist/engine-CIAopp0h.js +0 -1
  120. package/dist/lifecycle-CVg2-zQ3.js +0 -1
  121. package/dist/lifecycle-Dk_BHtfz.js +0 -1
  122. package/dist/paths-C9x5U3dO.js +0 -1
  123. package/dist/paths-xTSEAWfN.js.map +0 -1
  124. package/dist/peer-mcp-personas-DlF1dKCs.js.map +0 -1
  125. package/dist/provision-DLGlhu3a.js.map +0 -1
  126. package/dist/serve-8tXHVHOr.js.map +0 -1
  127. package/dist/server-setup-BBSmse1J.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-discount-kpOLluHm.js","names":[],"sources":["../src/lib/copilot-discount.ts"],"sourcesContent":["/**\n * Approximate discounted USD for a session, from static per-model discount\n * factors applied to the AIC ledger's billed nano-AIU.\n *\n * Background: GitHub's portal lists per-token rates, but the spend dashboard\n * bills several models well below portal (gpt-5.6-sol ≈ 0.28x, the Opus /\n * Sonnet / Codex cluster ≈ 0.6x, gemini-3.7-flash ≈ 0.29x since Sep 2026),\n * while Luna bills long-context portal tiers and Grok / 3.8-flash bill\n * portal-default exactly. No uniform per-lab factor exists (verified across\n * 28d / MTD / 7d / daily windows), so each model carries its own factor.\n *\n * The factors scale NANO-AIU, not tokens × portal rates: nano is already\n * tier-correct upstream (long-context tiers, cache writes), so no tier\n * engine or portal-rate table is needed here. Displayed total is capped:\n * `min(factored, totalCredits × $0.01)` — the cap can only ever lower the\n * number (all factors ≤ 1), so a typo like 2.8-instead-of-0.28 degrades to\n * the unfactored total rather than overstating spend.\n *\n * Staleness: rates move (3.7-flash flipped 1.00x → 0.29x overnight once\n * already). Re-derive monthly from the portal + spend dashboard; drift\n * degrades to cap-bound display, never to overstatement.\n */\n\nimport type { AicSnapshot } from \"./aic-ledger\"\nimport { aicTotalCredits } from \"./aic-ledger\"\n\n/** USD value of one AI credit (GitHub's published conversion). */\nexport const USD_PER_AIC_CREDIT = 0.01\n\nexport interface DiscountFactorRow {\n /** Multiply nano-implied USD by this. */\n factor: number\n /** Why this value: which snapshot window(s) it was derived from. */\n source: string\n}\n\nfunction row(factor: number, source: string): DiscountFactorRow {\n return { factor, source }\n}\n\n/**\n * Static per-model discount factors, keyed by resolved (Copilot-side) model\n * id — the same key the ledger's `perModel` uses. Derived Sep 2026 from the\n * 28d / MTD / 7d / daily spend-dashboard windows vs portal rates.\n */\nexport const DISCOUNT_FACTORS: Readonly<Record<string, DiscountFactorRow>> =\n Object.freeze({\n \"gpt-6-sol\": row(0.28, \"carried from gpt-5.6-sol; re-derive on refresh\"),\n \"gpt-6.1-sol\": row(1.0, \"unmeasured: default no discount (do not carry 0.28 without spend data)\"),\n \"gpt-5.6-sol\": row(0.28, \"0.27-0.29 across 28d/MTD/7d/pre/9-9; write-mix refuted\"),\n \"claude-opus-5.5\": row(0.62, \"carried from opus-5; re-derive on refresh\"),\n \"claude-opus-5\": row(0.62, \"0.61-0.64 across windows; 9/7 1.02 excluded as single-day artifact\"),\n \"claude-sonnet-5\": row(0.66, \"0.62-0.71 across windows\"),\n \"gpt-5.3-codex\": row(0.60, \"0.59-0.62 across windows\"),\n \"gpt-5.4\": row(0.60, \"single snapshot 0.598\"),\n // Regime break: billed 1.00x pre-Sep, 0.29x since. Recheck FIRST at\n // every refresh — likeliest row to have moved again.\n \"gemini-3.7-flash\": row(0.29, \"September regime; pre-Sep 1.00x — volatile\"),\n // No discount: Luna's heat is long-context tiers + ~2% cache writes\n // (both already in nano); Grok / 3.8-flash bill portal-default exactly.\n \"gpt-6-luna\": row(1.0, \"carried from gpt-5.6-luna; re-derive on refresh\"),\n \"gpt-5.6-luna\": row(1.0, \"long-tier portal + writes, no discount\"),\n \"grok-4.6\": row(1.0, \"portal default, six windows\"),\n \"grok-4.7\": row(1.0, \"portal default, carried from grok-4.6\"),\n \"gemini-3.8-flash\": row(1.0, \"portal exact, six windows to the dollar\"),\n })\n\n/** Discount factor for a model id; 1.0 (no discount) when unlisted. */\nexport function discountFactorFor(modelId: string): number {\n return sanitizeFactor(DISCOUNT_FACTORS[modelId]?.factor)\n}\n\n/**\n * Clamp a factor to usable range. Non-finite or negative factors (corrupt\n * table edit, bad injection) degrade to 1.0 — unfactored but never NaN,\n * never negative on screen.\n */\nfunction sanitizeFactor(raw: unknown): number {\n return typeof raw === \"number\" && Number.isFinite(raw) && raw >= 0 ? raw : 1.0\n}\n\nexport interface DiscountedUsd {\n /** Capped total actually displayed (`~$`). */\n total: number\n /** Per-model factored USD, scaled to the capped total when the cap binds. */\n byModel: Record<string, number>\n /** True when the cap (not the factors) decided the total. */\n capped: boolean\n}\n\n/**\n * Session discounted USD from a ledger snapshot. Total function: never\n * throws (guards non-finite/negative ledger values defensively — a corrupt\n * snapshot must degrade the status line, not crash the hook).\n */\nexport function discountedUsdForSnapshot(snapshot: AicSnapshot): DiscountedUsd {\n return discountedUsdWithFactors(snapshot, DISCOUNT_FACTORS)\n}\n\n/**\n * Factor-injectable core (exported for unit tests — e.g. proving a\n * fat-finger factor can never overstate spend). `factors` falls back to\n * 1.0 per model exactly like the table lookup.\n */\nexport function discountedUsdWithFactors(\n snapshot: AicSnapshot,\n factors: Readonly<Record<string, DiscountFactorRow>>,\n): DiscountedUsd {\n const byModel: Record<string, number> = {}\n let sum = 0\n for (const [model, entry] of Object.entries(snapshot.perModel)) {\n const nano =\n typeof entry.nanoAiu === \"number\" && Number.isFinite(entry.nanoAiu)\n ? Math.max(0, entry.nanoAiu)\n : 0\n const factor = sanitizeFactor(factors[model]?.factor)\n const usd = (nano / 1_000_000_000) * USD_PER_AIC_CREDIT * factor\n byModel[model] = usd\n sum += usd\n }\n const cap = aicTotalCredits(snapshot) * USD_PER_AIC_CREDIT\n // Relative epsilon: per-model float summation can exceed the cap by a\n // final-ulp hair without any factor being wrong — only bind on a real gap.\n if (!(sum > cap * (1 + 1e-9)) || sum <= 0) {\n return { total: sum, byModel, capped: false }\n }\n // Cap binds (fat-finger factor, volatile row, unknown-model overstatement):\n // scale rows down proportionally so the table still sums to its Total.\n const scale = cap / sum\n const scaled: Record<string, number> = {}\n for (const [model, usd] of Object.entries(byModel)) {\n scaled[model] = usd * scale\n }\n return { total: cap, byModel: scaled, capped: true }\n}\n\n/** Format table dollars: always cents (`~$` added by callers that want it). */\nexport function formatTableUsd(usd: number): string {\n return usd.toFixed(2)\n}\n\ninterface CostTableRow {\n model: string\n uncached: number\n cached: number\n writes: number\n output: number\n usd: number\n}\n\n/**\n * Beautiful per-model session cost table (plain text, no ANSI — it lands on\n * stderr / logs). Columns mirror the spend dashboard: Uncached / Cached /\n * [Write] / Cache% / Output / $. The Write column appears only when the\n * session actually wrote cache. `Cache% = cache_read / (cache_read + input)`;\n * writes are excluded (they are new tokens, not hits).\n */\nexport function formatDiscountedCostTable(\n snapshot: AicSnapshot,\n discounted: DiscountedUsd,\n): string {\n const tokens = snapshot.tokensByModel ?? {}\n const models = new Set([...Object.keys(snapshot.perModel), ...Object.keys(tokens)])\n const rows: Array<CostTableRow> = []\n for (const model of models) {\n const t = tokens[model]\n rows.push({\n model,\n uncached: t?.input ?? 0,\n cached: t?.cache_read ?? 0,\n writes: t?.cache_write ?? 0,\n output: t?.output ?? 0,\n usd: discounted.byModel[model] ?? 0,\n })\n }\n if (rows.length === 0) return \"\"\n rows.sort((a, b) => b.usd - a.usd || a.model.localeCompare(b.model))\n\n const showWrites = rows.some((r) => r.writes > 0)\n const cachePct = (cached: number, uncached: number): string => {\n const denom = cached + uncached\n if (denom <= 0) return \"—\"\n return `${((cached / denom) * 100).toFixed(1)}%`\n }\n\n type Cell = { text: string; align: \"left\" | \"right\" }\n const header: Array<Cell> = [\n { text: \"Model\", align: \"left\" },\n { text: \"Uncached\", align: \"right\" },\n { text: \"Cached\", align: \"right\" },\n ]\n if (showWrites) header.push({ text: \"Write\", align: \"right\" })\n header.push(\n { text: \"Cache%\", align: \"right\" },\n { text: \"Output\", align: \"right\" },\n { text: \"$\", align: \"right\" },\n )\n\n const body: Array<Array<Cell>> = rows.map((r) => {\n const cells: Array<Cell> = [\n { text: r.model, align: \"left\" },\n { text: formatCount(r.uncached), align: \"right\" },\n { text: formatCount(r.cached), align: \"right\" },\n ]\n if (showWrites) cells.push({ text: formatCount(r.writes), align: \"right\" })\n cells.push(\n { text: cachePct(r.cached, r.uncached), align: \"right\" },\n { text: formatCount(r.output), align: \"right\" },\n { text: `~$${formatTableUsd(r.usd)}`, align: \"right\" },\n )\n return cells\n })\n\n const totalUncached = rows.reduce((n, r) => n + r.uncached, 0)\n const totalCached = rows.reduce((n, r) => n + r.cached, 0)\n const totalWrites = rows.reduce((n, r) => n + r.writes, 0)\n const totalOutput = rows.reduce((n, r) => n + r.output, 0)\n const totalCells: Array<Cell> = [\n { text: \"Total\", align: \"left\" },\n { text: formatCount(totalUncached), align: \"right\" },\n { text: formatCount(totalCached), align: \"right\" },\n ]\n if (showWrites) {\n totalCells.push({ text: formatCount(totalWrites), align: \"right\" })\n }\n totalCells.push(\n { text: cachePct(totalCached, totalUncached), align: \"right\" },\n { text: formatCount(totalOutput), align: \"right\" },\n { text: `~$${formatTableUsd(discounted.total)}`, align: \"right\" },\n )\n\n const widths = header.map((h, i) => {\n let w = h.text.length\n for (const row of [...body, totalCells]) {\n w = Math.max(w, row[i].text.length)\n }\n return w\n })\n const render = (cells: Array<Cell>): string =>\n cells\n .map((c, i) =>\n c.align === \"left\" ? c.text.padEnd(widths[i]) : c.text.padStart(widths[i]),\n )\n .join(\" \")\n const lines = [\n \"Session cost (discounted actuals, ~$):\",\n render(header),\n ...body.map(render),\n render(totalCells),\n ]\n return lines.join(\"\\n\")\n}\n\n/** Compact count for table cells: `999` → `999`, `15234` → `15.2k`. */\nfunction formatCount(n: number): string {\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`\n if (n >= 1000) return `${(n / 1000).toFixed(1)}k`\n return `${n}`\n}\n"],"mappings":";;;AA2BA,MAAa,qBAAqB;AASlC,SAAS,IAAI,QAAgB,QAAmC;CAC9D,OAAO;EAAE;EAAQ;CAAO;AAC1B;;;;;;AAOA,MAAa,mBACX,OAAO,OAAO;CACZ,aAAa,IAAI,KAAM,gDAAgD;CACvE,eAAe,IAAI,GAAK,wEAAwE;CAChG,eAAe,IAAI,KAAM,wDAAwD;CACjF,mBAAmB,IAAI,KAAM,2CAA2C;CACxE,iBAAiB,IAAI,KAAM,oEAAoE;CAC/F,mBAAmB,IAAI,KAAM,0BAA0B;CACvD,iBAAiB,IAAI,IAAM,0BAA0B;CACrD,WAAW,IAAI,IAAM,uBAAuB;CAG5C,oBAAoB,IAAI,KAAM,4CAA4C;CAG1E,cAAc,IAAI,GAAK,iDAAiD;CACxE,gBAAgB,IAAI,GAAK,wCAAwC;CACjE,YAAY,IAAI,GAAK,6BAA6B;CAClD,YAAY,IAAI,GAAK,uCA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EAAE,CAC3E,CAAC,CACA,KAAK,IAAI;CAOd,OAAO;EALL;EACA,OAAO,MAAM;EACb,GAAG,KAAK,IAAI,MAAM;EAClB,OAAO,UAAU;CAER,CAAC,CAAC,KAAK,IAAI;AACxB;;AAGA,SAAS,YAAY,GAAmB;CACtC,IAAI,KAAK,KAAW,OAAO,IAAI,IAAI,IAAA,CAAW,QAAQ,CAAC,EAAE;CACzD,IAAI,KAAK,KAAM,OAAO,IAAI,IAAI,IAAA,CAAM,QAAQ,CAAC,EAAE;CAC/C,OAAO,GAAG;AACZ"}
1
+ {"version":3,"file":"copilot-discount-Bsmv_3OX.js","names":[],"sources":["../src/lib/copilot-discount.ts"],"sourcesContent":["/**\n * Approximate discounted USD for a session, from static per-model discount\n * factors applied to the AIC ledger's billed nano-AIU.\n *\n * Background: GitHub's portal lists per-token rates, but the spend dashboard\n * bills several models well below portal (gpt-5.6-sol ≈ 0.28x, the Opus /\n * Sonnet / Codex cluster ≈ 0.6x, gemini-3.7-flash ≈ 0.29x since Sep 2026),\n * while Luna bills long-context portal tiers and Grok / 3.8-flash bill\n * portal-default exactly. No uniform per-lab factor exists (verified across\n * 28d / MTD / 7d / daily windows), so each model carries its own factor.\n *\n * The factors scale NANO-AIU, not tokens × portal rates: nano is already\n * tier-correct upstream (long-context tiers, cache writes), so no tier\n * engine or portal-rate table is needed here. Displayed total is capped:\n * `min(factored, totalCredits × $0.01)` — the cap can only ever lower the\n * number (all factors ≤ 1), so a typo like 2.8-instead-of-0.28 degrades to\n * the unfactored total rather than overstating spend.\n *\n * Staleness: rates move (3.7-flash flipped 1.00x → 0.29x overnight once\n * already). Re-derive monthly from the portal + spend dashboard; drift\n * degrades to cap-bound display, never to overstatement.\n */\n\nimport type { AicSnapshot } from \"./aic-ledger\"\nimport { aicTotalCredits } from \"./aic-ledger\"\n\n/** USD value of one AI credit (GitHub's published conversion). */\nexport const USD_PER_AIC_CREDIT = 0.01\n\nexport interface DiscountFactorRow {\n /** Multiply nano-implied USD by this. */\n factor: number\n /** Why this value: which snapshot window(s) it was derived from. */\n source: string\n}\n\nfunction row(factor: number, source: string): DiscountFactorRow {\n return { factor, source }\n}\n\n/**\n * Static per-model discount factors, keyed by resolved (Copilot-side) model\n * id — the same key the ledger's `perModel` uses. Derived Sep 2026 from the\n * 28d / MTD / 7d / daily spend-dashboard windows vs portal rates.\n */\nexport const DISCOUNT_FACTORS: Readonly<Record<string, DiscountFactorRow>> =\n Object.freeze({\n \"gpt-6-sol\": row(0.28, \"carried from gpt-5.6-sol; re-derive on refresh\"),\n \"gpt-6.1-sol\": row(1.0, \"unmeasured: default no discount (do not carry 0.28 without spend data)\"),\n \"gpt-5.6-sol\": row(0.28, \"0.27-0.29 across 28d/MTD/7d/pre/9-9; write-mix refuted\"),\n \"claude-opus-5.5\": row(0.62, \"carried from opus-5; re-derive on refresh\"),\n \"claude-opus-5\": row(0.62, \"0.61-0.64 across windows; 9/7 1.02 excluded as single-day artifact\"),\n \"claude-sonnet-5\": row(0.66, \"0.62-0.71 across windows\"),\n \"gpt-5.3-codex\": row(0.60, \"0.59-0.62 across windows\"),\n \"gpt-5.4\": row(0.60, \"single snapshot 0.598\"),\n // Regime break: billed 1.00x pre-Sep, 0.29x since. Recheck FIRST at\n // every refresh — likeliest row to have moved again.\n \"gemini-3.7-flash\": row(0.29, \"September regime; pre-Sep 1.00x — volatile\"),\n // No discount: Luna's heat is long-context tiers + ~2% cache writes\n // (both already in nano); Grok / 3.8-flash bill portal-default exactly.\n \"gpt-6-luna\": row(1.0, \"carried from gpt-5.6-luna; re-derive on refresh\"),\n \"gpt-5.6-luna\": row(1.0, \"long-tier portal + writes, no discount\"),\n \"grok-4.6\": row(1.0, \"portal default, six windows\"),\n \"grok-4.7\": row(1.0, \"portal default, carried from grok-4.6\"),\n \"gemini-3.8-flash\": row(1.0, \"portal exact, six windows to the dollar\"),\n })\n\n/** Discount factor for a model id; 1.0 (no discount) when unlisted. */\nexport function discountFactorFor(modelId: string): number {\n return sanitizeFactor(DISCOUNT_FACTORS[modelId]?.factor)\n}\n\n/**\n * Clamp a factor to usable range. Non-finite or negative factors (corrupt\n * table edit, bad injection) degrade to 1.0 — unfactored but never NaN,\n * never negative on screen.\n */\nfunction sanitizeFactor(raw: unknown): number {\n return typeof raw === \"number\" && Number.isFinite(raw) && raw >= 0 ? raw : 1.0\n}\n\nexport interface DiscountedUsd {\n /** Capped total actually displayed (`~$`). */\n total: number\n /** Per-model factored USD, scaled to the capped total when the cap binds. */\n byModel: Record<string, number>\n /** True when the cap (not the factors) decided the total. */\n capped: boolean\n}\n\n/**\n * Session discounted USD from a ledger snapshot. Total function: never\n * throws (guards non-finite/negative ledger values defensively — a corrupt\n * snapshot must degrade the status line, not crash the hook).\n */\nexport function discountedUsdForSnapshot(snapshot: AicSnapshot): DiscountedUsd {\n return discountedUsdWithFactors(snapshot, DISCOUNT_FACTORS)\n}\n\n/**\n * Factor-injectable core (exported for unit tests — e.g. proving a\n * fat-finger factor can never overstate spend). `factors` falls back to\n * 1.0 per model exactly like the table lookup.\n */\nexport function discountedUsdWithFactors(\n snapshot: AicSnapshot,\n factors: Readonly<Record<string, DiscountFactorRow>>,\n): DiscountedUsd {\n const byModel: Record<string, number> = {}\n let sum = 0\n for (const [model, entry] of Object.entries(snapshot.perModel)) {\n const nano =\n typeof entry.nanoAiu === \"number\" && Number.isFinite(entry.nanoAiu)\n ? Math.max(0, entry.nanoAiu)\n : 0\n const factor = sanitizeFactor(factors[model]?.factor)\n const usd = (nano / 1_000_000_000) * USD_PER_AIC_CREDIT * factor\n byModel[model] = usd\n sum += usd\n }\n const cap = aicTotalCredits(snapshot) * USD_PER_AIC_CREDIT\n // Relative epsilon: per-model float summation can exceed the cap by a\n // final-ulp hair without any factor being wrong — only bind on a real gap.\n if (!(sum > cap * (1 + 1e-9)) || sum <= 0) {\n return { total: sum, byModel, capped: false }\n }\n // Cap binds (fat-finger factor, volatile row, unknown-model overstatement):\n // scale rows down proportionally so the table still sums to its Total.\n const scale = cap / sum\n const scaled: Record<string, number> = {}\n for (const [model, usd] of Object.entries(byModel)) {\n scaled[model] = usd * scale\n }\n return { total: cap, byModel: scaled, capped: true }\n}\n\n/** Format table dollars: always cents (`~$` added by callers that want it). */\nexport function formatTableUsd(usd: number): string {\n return usd.toFixed(2)\n}\n\ninterface CostTableRow {\n model: string\n uncached: number\n cached: number\n writes: number\n output: number\n usd: number\n}\n\n/**\n * Beautiful per-model session cost table (plain text, no ANSI — it lands on\n * stderr / logs). Columns mirror the spend dashboard: Uncached / Cached /\n * [Write] / Cache% / Output / $. The Write column appears only when the\n * session actually wrote cache. `Cache% = cache_read / (cache_read + input)`;\n * writes are excluded (they are new tokens, not hits).\n */\nexport function formatDiscountedCostTable(\n snapshot: AicSnapshot,\n discounted: DiscountedUsd,\n): string {\n const tokens = snapshot.tokensByModel ?? {}\n const models = new Set([...Object.keys(snapshot.perModel), ...Object.keys(tokens)])\n const rows: Array<CostTableRow> = []\n for (const model of models) {\n const t = tokens[model]\n rows.push({\n model,\n uncached: t?.input ?? 0,\n cached: t?.cache_read ?? 0,\n writes: t?.cache_write ?? 0,\n output: t?.output ?? 0,\n usd: discounted.byModel[model] ?? 0,\n })\n }\n if (rows.length === 0) return \"\"\n rows.sort((a, b) => b.usd - a.usd || a.model.localeCompare(b.model))\n\n const showWrites = rows.some((r) => r.writes > 0)\n const cachePct = (cached: number, uncached: number): string => {\n const denom = cached + uncached\n if (denom <= 0) return \"—\"\n return `${((cached / denom) * 100).toFixed(1)}%`\n }\n\n type Cell = { text: string; align: \"left\" | \"right\" }\n const header: Array<Cell> = [\n { text: \"Model\", align: \"left\" },\n { text: \"Uncached\", align: \"right\" },\n { text: \"Cached\", align: \"right\" },\n ]\n if (showWrites) header.push({ text: \"Write\", align: \"right\" })\n header.push(\n { text: \"Cache%\", align: \"right\" },\n { text: \"Output\", align: \"right\" },\n { text: \"$\", align: \"right\" },\n )\n\n const body: Array<Array<Cell>> = rows.map((r) => {\n const cells: Array<Cell> = [\n { text: r.model, align: \"left\" },\n { text: formatCount(r.uncached), align: \"right\" },\n { text: formatCount(r.cached), align: \"right\" },\n ]\n if (showWrites) cells.push({ text: formatCount(r.writes), align: \"right\" })\n cells.push(\n { text: cachePct(r.cached, r.uncached), align: \"right\" },\n { text: formatCount(r.output), align: \"right\" },\n { text: `~$${formatTableUsd(r.usd)}`, align: \"right\" },\n )\n return cells\n })\n\n const totalUncached = rows.reduce((n, r) => n + r.uncached, 0)\n const totalCached = rows.reduce((n, r) => n + r.cached, 0)\n const totalWrites = rows.reduce((n, r) => n + r.writes, 0)\n const totalOutput = rows.reduce((n, r) => n + r.output, 0)\n const totalCells: Array<Cell> = [\n { text: \"Total\", align: \"left\" },\n { text: formatCount(totalUncached), align: \"right\" },\n { text: formatCount(totalCached), align: \"right\" },\n ]\n if (showWrites) {\n totalCells.push({ text: formatCount(totalWrites), align: \"right\" })\n }\n totalCells.push(\n { text: cachePct(totalCached, totalUncached), align: \"right\" },\n { text: formatCount(totalOutput), align: \"right\" },\n { text: `~$${formatTableUsd(discounted.total)}`, align: \"right\" },\n )\n\n const widths = header.map((h, i) => {\n let w = h.text.length\n for (const row of [...body, totalCells]) {\n w = Math.max(w, row[i].text.length)\n }\n return w\n })\n const render = (cells: Array<Cell>): string =>\n cells\n .map((c, i) =>\n c.align === \"left\" ? c.text.padEnd(widths[i]) : c.text.padStart(widths[i]),\n )\n .join(\" \")\n const lines = [\n \"Session cost (discounted actuals, ~$):\",\n render(header),\n ...body.map(render),\n render(totalCells),\n ]\n return lines.join(\"\\n\")\n}\n\n/** Compact count for table cells: `999` → `999`, `15234` → `15.2k`. */\nfunction formatCount(n: number): string {\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`\n if (n >= 1000) return `${(n / 1000).toFixed(1)}k`\n return `${n}`\n}\n"],"mappings":";;;AA2BA,MAAa,qBAAqB;AASlC,SAAS,IAAI,QAAgB,QAAmC;CAC9D,OAAO;EAAE;EAAQ;CAAO;AAC1B;;;;;;A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a;EAAG,OAAO;CAAQ,GAC7D;EAAE,MAAM,YAAY,WAAW;EAAG,OAAO;CAAQ,GACjD;EAAE,MAAM,KAAK,eAAe,WAAW,KAAK;EAAK,OAAO;CAAQ,CAClE;CAEA,MAAM,SAAS,OAAO,KAAK,GAAG,MAAM;EAClC,IAAI,IAAI,EAAE,KAAK;EACf,KAAK,MAAM,OAAO,CAAC,GAAG,MAAM,UAAU,GACpC,IAAI,KAAK,IAAI,GAAG,IAAI,EAAE,CAAC,KAAK,MAAM;EAEpC,OAAO;CACT,CAAC;CACD,MAAM,UAAU,UACd,MACG,KAAK,GAAG,MACP,EAAE,UAAU,SAAS,EAAE,KAAK,OAAO,OAAO,EAAE,IAAI,EAAE,KAAK,SAAS,OAAO,EAAE,CAC3E,CAAC,CACA,KAAK,IAAI;CAOd,OAAO;EALL;EACA,OAAO,MAAM;EACb,GAAG,KAAK,IAAI,MAAM;EAClB,OAAO,UAAU;CAER,CAAC,CAAC,KAAK,IAAI;AACxB;;AAGA,SAAS,YAAY,GAAmB;CACtC,IAAI,KAAK,KAAW,OAAO,IAAI,IAAI,IAAA,CAAW,QAAQ,CAAC,EAAE;CACzD,IAAI,KAAK,KAAM,OAAO,IAAI,IAAI,IAAA,CAAM,QAAQ,CAAC,EAAE;CAC/C,OAAO,GAAG;AACZ"}
@@ -1,4 +1,4 @@
1
- import { t as PATHS } from "./paths-xTSEAWfN.js";
1
+ import { t as PATHS } from "./paths-BSI_EtDT.js";
2
2
  import { defineCommand } from "citty";
3
3
  import consola from "consola";
4
4
  import fs from "node:fs/promises";
@@ -78,4 +78,4 @@ const debug = defineCommand({
78
78
  //#endregion
79
79
  export { debug };
80
80
 
81
- //# sourceMappingURL=debug-BtqbflcL.js.map
81
+ //# sourceMappingURL=debug-DkNTuErv.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"debug-BtqbflcL.js","names":[],"sources":["../src/debug.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\n\nimport { PATHS } from \"./lib/paths\"\n\ninterface DebugInfo {\n version: string\n runtime: {\n name: string\n version: string\n platform: string\n arch: string\n }\n paths: {\n APP_DIR: string\n GITHUB_TOKEN_PATH: string\n }\n tokenExists: boolean\n}\n\ninterface RunDebugOptions {\n json: boolean\n}\n\nasync function getPackageVersion(): Promise<string> {\n try {\n const packageJsonPath = new URL(\"../package.json\", import.meta.url).pathname\n // @ts-expect-error https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v59.0.1/docs/rules/prefer-json-parse-buffer.md\n // JSON.parse() can actually parse buffers\n const packageJson = JSON.parse(await fs.readFile(packageJsonPath)) as {\n version: string\n }\n return packageJson.version\n } catch {\n return \"unknown\"\n }\n}\n\nfunction getRuntimeInfo() {\n const isBun = typeof Bun !== \"undefined\"\n\n return {\n name: isBun ? \"bun\" : \"node\",\n version: isBun ? Bun.version : process.version.slice(1),\n platform: os.platform(),\n arch: os.arch(),\n }\n}\n\nasync function checkTokenExists(): Promise<boolean> {\n try {\n const stats = await fs.stat(PATHS.GITHUB_TOKEN_PATH)\n if (!stats.isFile()) return false\n\n const content = await fs.readFile(PATHS.GITHUB_TOKEN_PATH, \"utf8\")\n return content.trim().length > 0\n } catch {\n return false\n }\n}\n\nasync function getDebugInfo(): Promise<DebugInfo> {\n const [version, tokenExists] = await Promise.all([\n getPackageVersion(),\n checkTokenExists(),\n ])\n\n return {\n version,\n runtime: getRuntimeInfo(),\n paths: {\n APP_DIR: PATHS.APP_DIR,\n GITHUB_TOKEN_PATH: PATHS.GITHUB_TOKEN_PATH,\n },\n tokenExists,\n }\n}\n\nfunction printDebugInfoPlain(info: DebugInfo): void {\n consola.info(`github-router debug\n\nVersion: ${info.version}\nRuntime: ${info.runtime.name} ${info.runtime.version} (${info.runtime.platform} ${info.runtime.arch})\n\nPaths:\n- APP_DIR: ${info.paths.APP_DIR}\n- GITHUB_TOKEN_PATH: ${info.paths.GITHUB_TOKEN_PATH}\n\nToken exists: ${info.tokenExists ? \"Yes\" : \"No\"}`)\n}\n\nfunction printDebugInfoJson(info: DebugInfo): void {\n console.log(JSON.stringify(info, null, 2))\n}\n\nexport async function runDebug(options: RunDebugOptions): Promise<void> {\n const debugInfo = await getDebugInfo()\n\n if (options.json) {\n printDebugInfoJson(debugInfo)\n } else {\n printDebugInfoPlain(debugInfo)\n }\n}\n\nexport const debug = defineCommand({\n meta: {\n name: \"debug\",\n description: \"Print debug information about the application\",\n },\n args: {\n json: {\n type: \"boolean\",\n default: false,\n description: \"Output debug information as JSON\",\n },\n },\n run({ args }) {\n return runDebug({\n json: args.json,\n })\n },\n})\n"],"mappings":";;;;;;AA4BA,eAAe,oBAAqC;CAClD,IAAI;EACF,MAAM,kBAAkB,IAAI,IAAI,mBAAmB,YAAY,GAAG,CAAC,CAAC;EAMpE,OAHoB,KAAK,MAAM,MAAM,GAAG,SAAS,eAAe,CAG/C,CAAC,CAAC;CACrB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,iBAAiB;CACxB,MAAM,QAAQ,OAAO,QAAQ;CAE7B,OAAO;EACL,MAAM,QAAQ,QAAQ;EACtB,SAAS,QAAQ,IAAI,UAAU,QAAQ,QAAQ,MAAM,CAAC;EACtD,UAAU,GAAG,SAAS;EACtB,MAAM,GAAG,KAAK;CAChB;AACF;AAEA,eAAe,mBAAqC;CAClD,IAAI;EAEF,IAAI,EAAC,MADe,GAAG,KAAK,MAAM,iBAAiB,EAAA,CACxC,OAAO,GAAG,OAAO;EAG5B,QAAO,MADe,GAAG,SAAS,MAAM,mBAAmB,MAAM,EAAA,CAClD,KAAK,CAAC,CAAC,SAAS;CACjC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,eAAmC;CAChD,MAAM,CAAC,SAAS,eAAe,MAAM,QAAQ,IAAI,CAC/C,kBAAkB,GAClB,iBAAiB,CACnB,CAAC;CAED,OAAO;EACL;EACA,SAAS,eAAe;EACxB,OAAO;GACL,SAAS,MAAM;GACf,mBAAmB,MAAM;EAC3B;EACA;CACF;AACF;AAEA,SAAS,oBAAoB,MAAuB;CAClD,QAAQ,KAAK;;WAEJ,KAAK,QAAQ;WACb,KAAK,QAAQ,KAAK,GAAG,KAAK,QAAQ,QAAQ,IAAI,KAAK,QAAQ,SAAS,GAAG,KAAK,QAAQ,KAAK;;;aAGvF,KAAK,MAAM,QAAQ;uBACT,KAAK,MAAM,kBAAkB;;gBAEpC,KAAK,cAAc,QAAQ,MAAM;AACjD;AAEA,SAAS,mBAAmB,MAAuB;CACjD,QAAQ,IAAI,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAC3C;AAEA,eAAsB,SAAS,SAAyC;CACtE,MAAM,YAAY,MAAM,aAAa;CAErC,IAAI,QAAQ,MACV,mBAAmB,SAAS;MAE5B,oBAAoB,SAAS;AAEjC;AAEA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM,EACJ,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;CACf,EACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,SAAS,EACd,MAAM,KAAK,KACb,CAAC;CACH;AACF,CAAC"}
1
+ {"version":3,"file":"debug-DkNTuErv.js","names":[],"sources":["../src/debug.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\n\nimport { PATHS } from \"./lib/paths\"\n\ninterface DebugInfo {\n version: string\n runtime: {\n name: string\n version: string\n platform: string\n arch: string\n }\n paths: {\n APP_DIR: string\n GITHUB_TOKEN_PATH: string\n }\n tokenExists: boolean\n}\n\ninterface RunDebugOptions {\n json: boolean\n}\n\nasync function getPackageVersion(): Promise<string> {\n try {\n const packageJsonPath = new URL(\"../package.json\", import.meta.url).pathname\n // @ts-expect-error https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v59.0.1/docs/rules/prefer-json-parse-buffer.md\n // JSON.parse() can actually parse buffers\n const packageJson = JSON.parse(await fs.readFile(packageJsonPath)) as {\n version: string\n }\n return packageJson.version\n } catch {\n return \"unknown\"\n }\n}\n\nfunction getRuntimeInfo() {\n const isBun = typeof Bun !== \"undefined\"\n\n return {\n name: isBun ? \"bun\" : \"node\",\n version: isBun ? Bun.version : process.version.slice(1),\n platform: os.platform(),\n arch: os.arch(),\n }\n}\n\nasync function checkTokenExists(): Promise<boolean> {\n try {\n const stats = await fs.stat(PATHS.GITHUB_TOKEN_PATH)\n if (!stats.isFile()) return false\n\n const content = await fs.readFile(PATHS.GITHUB_TOKEN_PATH, \"utf8\")\n return content.trim().length > 0\n } catch {\n return false\n }\n}\n\nasync function getDebugInfo(): Promise<DebugInfo> {\n const [version, tokenExists] = await Promise.all([\n getPackageVersion(),\n checkTokenExists(),\n ])\n\n return {\n version,\n runtime: getRuntimeInfo(),\n paths: {\n APP_DIR: PATHS.APP_DIR,\n GITHUB_TOKEN_PATH: PATHS.GITHUB_TOKEN_PATH,\n },\n tokenExists,\n }\n}\n\nfunction printDebugInfoPlain(info: DebugInfo): void {\n consola.info(`github-router debug\n\nVersion: ${info.version}\nRuntime: ${info.runtime.name} ${info.runtime.version} (${info.runtime.platform} ${info.runtime.arch})\n\nPaths:\n- APP_DIR: ${info.paths.APP_DIR}\n- GITHUB_TOKEN_PATH: ${info.paths.GITHUB_TOKEN_PATH}\n\nToken exists: ${info.tokenExists ? \"Yes\" : \"No\"}`)\n}\n\nfunction printDebugInfoJson(info: DebugInfo): void {\n console.log(JSON.stringify(info, null, 2))\n}\n\nexport async function runDebug(options: RunDebugOptions): Promise<void> {\n const debugInfo = await getDebugInfo()\n\n if (options.json) {\n printDebugInfoJson(debugInfo)\n } else {\n printDebugInfoPlain(debugInfo)\n }\n}\n\nexport const debug = defineCommand({\n meta: {\n name: \"debug\",\n description: \"Print debug information about the application\",\n },\n args: {\n json: {\n type: \"boolean\",\n default: false,\n description: \"Output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AAQ,IAAI,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAC3C;AAEA,eAAsB,SAAS,SAAyC;CACtE,MAAM,YAAY,MAAM,aAAa;CAErC,IAAI,QAAQ,MACV,mBAAmB,SAAS;MAE5B,oBAAoB,SAAS;AAEjC;AAEA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM,EACJ,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;CACf,EACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,SAAS,EACd,MAAM,KAAK,KACb,CAAC;CACH;AACF,CAAC"}
@@ -0,0 +1 @@
1
+ export { C as runWorkerAgent } from "./peer-mcp-personas-CVxXq1Q-.js";
@@ -1,7 +1,7 @@
1
- import { t as PATHS } from "./paths-xTSEAWfN.js";
1
+ import { t as PATHS } from "./paths-BSI_EtDT.js";
2
2
  import { s as resolveExecutable } from "./exec-Bf8g_bIR.js";
3
- import { l as repoFingerprint, u as repoRoot } from "./stop-gate-policy-FGAfpfc-.js";
4
- import { p as resolveSealedGate } from "./stop-gate-hook-BYd0NruJ.js";
3
+ import { l as repoFingerprint, u as repoRoot } from "./stop-gate-policy-CoR8xKNQ.js";
4
+ import { p as resolveSealedGate } from "./stop-gate-hook-CC7VWkZM.js";
5
5
  import { existsSync, promises } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { createHash } from "node:crypto";
@@ -606,7 +606,7 @@ async function discoverGateCommands(cwd, opts) {
606
606
  if (files.length === 0) return null;
607
607
  let result;
608
608
  try {
609
- const { runWorkerAgent } = await import("./engine-CIAopp0h.js");
609
+ const { runWorkerAgent } = await import("./engine-DgmsdkCe.js");
610
610
  result = await runWorkerAgent({
611
611
  mode: "explore",
612
612
  workspace: root,
@@ -632,4 +632,4 @@ async function discoverGateCommands(cwd, opts) {
632
632
  //#endregion
633
633
  export { checksForDescriptor as a, writeDiscoveredGate as i, readDiscoveredGate as n, descriptorHash as o, sourcesHash as r, parseGateDescriptor as s, discoverGateCommands as t };
634
634
 
635
- //# sourceMappingURL=gate-discovery-CqJVzT_D.js.map
635
+ //# sourceMappingURL=gate-discovery-B2x_8hNL.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"gate-discovery-CqJVzT_D.js","names":["fs","nodePath","fs","nodePath"],"sources":["../src/lib/orchestration/harness-parse.ts","../src/lib/orchestration/gate-discovery.ts"],"sourcesContent":["/**\n * Deterministic, language-agnostic harness PARSER for the structural Stop-gate.\n *\n * The gate runs a repo's own checks (typecheck/lint/test/build) when the agent\n * tries to finish. Historically it only auto-enabled for Bun/TS repos via a\n * hard-coded sealed gate. This module generalizes detection by PARSING the\n * project's own authoritative config — `package.json` scripts, CI `run:` steps,\n * Make/just/task targets, and language manifests — and emitting the canonical\n * check commands it finds.\n *\n * Design properties (a cross-lab panel chose a parser over a model for these):\n * - EVIDENCE-PINNED BY CONSTRUCTION: every emitted command is either lifted\n * verbatim from a parsed source file (a package.json script, a CI `run:`\n * line, a Make target invocation) or is a fixed canonical manifest command\n * for a detected ecosystem (`cargo check`, `go vet ./...`). The parser never\n * invents a command, so it has no hallucination / prompt-injection surface.\n * - PURE + DETERMINISTIC: a function of the repo's files + the live PATH. The\n * runtime Stop hook re-derives it at each stop (no cache), so it always\n * reflects the current tree and fails open for free when a tool vanished.\n * - SHELL-SAFE: `liveExec` runs `command.trim().split(/\\s+/)` (naive argv\n * split, no shell), so every emitted command is validated to be plain\n * space-separated tokens with no shell operators and no `%` (cmd.exe quoting\n * throws on `%`). See `isSafeCommand`.\n *\n * This is consumed ONLY by the local Stop hook. The sealed-gate kernel\n * (`run_workflow`) is never fed a parsed command — `GateDescriptor.kind` is\n * `\"parsed\"`, never a sealed id, and `sealedGateIds()` is unchanged.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { existsSync, promises as fs } from \"node:fs\"\nimport nodePath from \"node:path\"\n\nimport { resolveExecutable } from \"~/lib/exec\"\n\nimport { resolveSealedGate } from \"./gate-registry\"\nimport { type CheckSpec } from \"./gate-runner\"\n\n/** Canonical check ids — stable across ecosystems so baseline isolation and the\n * selector key on the same names regardless of language. `build` is deliberately\n * NOT a check: build scripts are too variable in cost to auto-run on every stop\n * (a full bundle/SEA build is the slow-command / false-red footgun the design\n * avoids). Compile-checking is covered under `typecheck` (`go vet`, `cargo\n * check`, `tsc`). */\nexport type CheckId = \"typecheck\" | \"lint\" | \"test\"\n\n/** The fast static checks that are always-on; `test` is opt-in (it runs project\n * code and can be slow on every stop). */\nconst STATIC_IDS: ReadonlySet<CheckId> = new Set([\"typecheck\", \"lint\"])\n\n/**\n * The resolved gate source for a repo.\n * - `sealed` — the bun/TS fast-path (a sealed gate id, byte-identical to\n * the legacy behavior; the runtime hook resolves it via the\n * sealed registry).\n * - `parsed` — deterministic parser output (this module).\n * - `discovered` — the evidence-pinned model fallback (see `gate-discovery`).\n * `workdir` is the directory the checks run in (the repo/package root where the\n * evidence was found), NOT the Stop payload's cwd — so a monorepo stop from a\n * nested dir still runs the root's checks.\n */\nexport type GateDescriptor =\n | { kind: \"sealed\"; gateId: string; workdir: string }\n | { kind: \"parsed\"; checks: CheckSpec[]; ecosystem: string; workdir: string; evidence: string[] }\n | { kind: \"discovered\"; checks: CheckSpec[]; ecosystem: string; workdir: string; evidence: string[] }\n\ninterface Candidate {\n id: CheckId\n command: string\n /** The source file the command was lifted from (for evidence + messages). */\n source: string\n}\n\n/** Reject anything that is not a plain, shell-free, `%`-free argv line. This is\n * the load-bearing guard for `liveExec`'s naive whitespace split. */\nexport function isSafeCommand(command: string): boolean {\n const c = command.trim()\n if (c.length === 0 || c.length > 200) return false\n if (/[\\r\\n]/.test(c)) return false\n // Each token may contain only these chars: letters/digits and a small set of\n // path/flag punctuation. This rejects shell metacharacters (; & | < > ( ) $\n // backtick \" ' * ? ! ^ \\ %), env expansion, and quoting in one shot.\n const tokens = c.split(/\\s+/).filter(Boolean)\n if (tokens.length === 0) return false\n return tokens.every((t) => /^[A-Za-z0-9._/:@=+-]+$/.test(t))\n}\n\n/** First token of a command (the executable), for a PATH-presence probe. */\nfunction firstToken(command: string): string {\n return command.trim().split(/\\s+/)[0] ?? \"\"\n}\n\n/** True when a command would MUTATE the tree and so must never be a gate: a\n * `--fix`/`--write` flag or a `:fix`/`:write` script-name suffix (e.g.\n * `npm run lint:fix`, `eslint --fix`). Whitespace is normalized first so a\n * tab/double-space can't slip a flag past the scan. Exported + shared with the\n * discovered-command sanitizer. */\nexport function isMutatingCommand(command: string): boolean {\n const c = command.trim().replace(/\\s+/g, \" \")\n if (/(^| )(--fix|--write|-w|--watch|--serve|--interactive|-i)( |=|$)/i.test(c)) return true\n if (/(^| |:|-)(fix|write)\\b/i.test(c)) return true\n return false\n}\n\n/** True when the command is safe AND its executable resolves on PATH (a missing\n * tool → drop the check rather than guarantee a false-red). */\nfunction commandRunnable(command: string): boolean {\n if (!isSafeCommand(command)) return false\n return resolveExecutable(firstToken(command), { env: process.env }) !== null\n}\n\nasync function readJsonFile(file: string): Promise<unknown | undefined> {\n try {\n return JSON.parse(await fs.readFile(file, \"utf8\")) as unknown\n } catch {\n return undefined\n }\n}\n\nasync function readTextFile(file: string): Promise<string | undefined> {\n try {\n return await fs.readFile(file, \"utf8\")\n } catch {\n return undefined\n }\n}\n\n/** package.json `scripts` as a plain string→string map (best-effort). */\nasync function readScripts(root: string): Promise<Record<string, string>> {\n const pkg = await readJsonFile(nodePath.join(root, \"package.json\"))\n const scripts = pkg && typeof pkg === \"object\" ? (pkg as { scripts?: unknown }).scripts : undefined\n const out: Record<string, string> = {}\n if (scripts && typeof scripts === \"object\") {\n for (const [k, v] of Object.entries(scripts as Record<string, unknown>)) {\n if (typeof v === \"string\") out[k] = v\n }\n }\n return out\n}\n\n/** Pick the JS package runner from the lockfile present at the root. */\nfunction nodeRunner(root: string): \"bun\" | \"pnpm\" | \"yarn\" | \"npm\" {\n if (existsSync(nodePath.join(root, \"bun.lockb\")) || existsSync(nodePath.join(root, \"bun.lock\"))) return \"bun\"\n if (existsSync(nodePath.join(root, \"pnpm-lock.yaml\"))) return \"pnpm\"\n if (existsSync(nodePath.join(root, \"yarn.lock\"))) return \"yarn\"\n return \"npm\"\n}\n\n/** Map a package.json script NAME to a canonical id (read-only checks only — a\n * `:fix`/`:write` variant mutates the tree and is never a gate). */\nfunction scriptNameToId(name: string): CheckId | null {\n if (/:(fix|write)$/i.test(name)) return null\n if (/^(typecheck|type-check|check-types|tsc|types)$/i.test(name)) return \"typecheck\"\n if (/^(lint|lint:check|eslint)$/i.test(name)) return \"lint\"\n if (/^test$/i.test(name)) return \"test\"\n return null\n}\n\nasync function collectNodeChecks(root: string, includeTests: boolean): Promise<Candidate[]> {\n if (!existsSync(nodePath.join(root, \"package.json\"))) return []\n const runner = nodeRunner(root)\n if (resolveExecutable(runner, { env: process.env }) === null) return []\n const scripts = await readScripts(root)\n const out: Candidate[] = []\n for (const [name] of Object.entries(scripts)) {\n const id = scriptNameToId(name)\n if (!id) continue\n if (id === \"test\" && !includeTests) continue\n const command = `${runner} run ${name}`\n if (isSafeCommand(command)) out.push({ id, command, source: \"package.json\" })\n }\n return out\n}\n\n/**\n * Best-effort CI gap-filler: scan GitHub Actions / GitLab CI YAML for single-line\n * `run:` static checks (typecheck/lint/build) the project actually runs. We do\n * NOT lift `test` from CI — CI test jobs frequently need services/secrets and\n * would false-red on every stop. Multi-line / scripted `run:` blocks are skipped\n * (they can't be a single argv). Any parse failure yields nothing.\n */\nasync function collectCiChecks(root: string): Promise<Candidate[]> {\n const files: string[] = []\n const wfDir = nodePath.join(root, \".github\", \"workflows\")\n try {\n for (const name of await fs.readdir(wfDir)) {\n if (/\\.ya?ml$/i.test(name)) files.push(nodePath.join(wfDir, name))\n }\n } catch {\n /* no workflows dir */\n }\n const gitlab = nodePath.join(root, \".gitlab-ci.yml\")\n if (existsSync(gitlab)) files.push(gitlab)\n if (files.length === 0) return []\n\n let parseYaml: (s: string) => unknown\n try {\n // Lazy import so the parser module has no hard dep when CI files are absent.\n ;({ parse: parseYaml } = await import(\"yaml\"))\n } catch {\n return []\n }\n\n const out: Candidate[] = []\n const seen = new Set<CheckId>()\n const classify = (cmd: string): CheckId | null => {\n if (/\\b(typecheck|type-check|tsc|mypy|pyright)\\b/i.test(cmd)) return \"typecheck\"\n if (/\\b(lint|eslint|ruff|clippy|golangci|vet)\\b/i.test(cmd)) return \"lint\"\n return null\n }\n const consider = (run: unknown, source: string): void => {\n if (typeof run !== \"string\") return\n const cmd = run.trim()\n if (cmd.includes(\"\\n\")) return // multi-line script block — not a single argv.\n if (!isSafeCommand(cmd) || isMutatingCommand(cmd) || !commandRunnable(cmd)) return\n const id = classify(cmd)\n if (!id || seen.has(id)) return\n seen.add(id)\n out.push({ id, command: cmd, source })\n }\n // Walk the parsed YAML for any `run:` string anywhere (GH `steps[].run`, GitLab\n // `<job>.script[]`). A generic deep walk tolerates both schemas + future shapes.\n const walk = (node: unknown, source: string): void => {\n if (!node || typeof node !== \"object\") return\n if (Array.isArray(node)) {\n for (const v of node) walk(v, source)\n return\n }\n for (const [k, v] of Object.entries(node as Record<string, unknown>)) {\n if (k === \"run\" && typeof v === \"string\") consider(v, source)\n else if (k === \"script\") {\n // GitLab `script:` is a string or string[].\n if (typeof v === \"string\") consider(v, source)\n else if (Array.isArray(v)) for (const s of v) consider(s, source)\n } else walk(v, source)\n }\n }\n for (const f of files) {\n const text = await readTextFile(f)\n if (text === undefined) continue\n try {\n walk(parseYaml(text), nodePath.relative(root, f) || nodePath.basename(f))\n } catch {\n /* unparseable workflow → skip */\n }\n }\n return out\n}\n\n/** Make / just / Taskfile targets matching canonical ids → `<tool> <target>`. */\nasync function collectTaskChecks(root: string, includeTests: boolean): Promise<Candidate[]> {\n const out: Candidate[] = []\n const wantId = (target: string): CheckId | null => scriptNameToId(target)\n // Makefile / justfile: a line `target:` (Make) or `target:` (just recipe head).\n for (const [file, tool] of [\n [\"Makefile\", \"make\"],\n [\"makefile\", \"make\"],\n [\"justfile\", \"just\"],\n [\".justfile\", \"just\"],\n ] as const) {\n const text = await readTextFile(nodePath.join(root, file))\n if (text === undefined) continue\n if (resolveExecutable(tool, { env: process.env }) === null) continue\n for (const line of text.split(/\\r?\\n/)) {\n const m = /^([A-Za-z0-9._-]+)\\s*:/.exec(line)\n if (!m) continue\n const id = wantId(m[1])\n if (!id || (id === \"test\" && !includeTests)) continue\n const command = `${tool} ${m[1]}`\n if (isSafeCommand(command)) out.push({ id, command, source: file })\n }\n }\n // Taskfile.yml: top-level `tasks:` keys.\n const taskfile = [\"Taskfile.yml\", \"Taskfile.yaml\"].map((n) => nodePath.join(root, n)).find((p) => existsSync(p))\n if (taskfile && resolveExecutable(\"task\", { env: process.env }) !== null) {\n const text = await readTextFile(taskfile)\n if (text !== undefined) {\n try {\n const { parse } = await import(\"yaml\")\n const doc = parse(text) as { tasks?: Record<string, unknown> } | undefined\n for (const name of Object.keys(doc?.tasks ?? {})) {\n const id = wantId(name)\n if (!id || (id === \"test\" && !includeTests)) continue\n const command = `task ${name}`\n if (isSafeCommand(command)) out.push({ id, command, source: nodePath.basename(taskfile) })\n }\n } catch {\n /* skip */\n }\n }\n }\n return out\n}\n\nasync function collectRustChecks(root: string, includeTests: boolean): Promise<Candidate[]> {\n if (!existsSync(nodePath.join(root, \"Cargo.toml\"))) return []\n if (resolveExecutable(\"cargo\", { env: process.env }) === null) return []\n const out: Candidate[] = [{ id: \"typecheck\", command: \"cargo check\", source: \"Cargo.toml\" }]\n // clippy is a separate component; only emit it if `cargo-clippy` resolves.\n if (resolveExecutable(\"cargo-clippy\", { env: process.env }) !== null) {\n out.push({ id: \"lint\", command: \"cargo clippy\", source: \"Cargo.toml\" })\n }\n if (includeTests) out.push({ id: \"test\", command: \"cargo test\", source: \"Cargo.toml\" })\n return out\n}\n\nasync function collectGoChecks(root: string, includeTests: boolean): Promise<Candidate[]> {\n if (!existsSync(nodePath.join(root, \"go.mod\"))) return []\n if (resolveExecutable(\"go\", { env: process.env }) === null) return []\n // `go vet` compiles + reports suspect constructs — the typecheck-equivalent.\n const out: Candidate[] = [{ id: \"typecheck\", command: \"go vet ./...\", source: \"go.mod\" }]\n if (includeTests) out.push({ id: \"test\", command: \"go test ./...\", source: \"go.mod\" })\n return out\n}\n\nasync function collectPythonChecks(root: string, includeTests: boolean): Promise<Candidate[]> {\n const configFiles = [\"pyproject.toml\", \"setup.cfg\", \"pytest.ini\", \"tox.ini\", \"ruff.toml\", \"mypy.ini\"]\n const present = configFiles.filter((f) => existsSync(nodePath.join(root, f)))\n if (present.length === 0) return []\n const evidence = present[0]\n const out: Candidate[] = []\n const configText = (await readTextFile(nodePath.join(root, present[0]))) ?? \"\"\n const mentions = (tool: string): boolean => present.some((f) => f.startsWith(tool)) || configText.includes(tool)\n // Only emit a Python tool when BOTH config evidence AND the tool resolve.\n if (mentions(\"mypy\") && resolveExecutable(\"mypy\", { env: process.env }) !== null) {\n out.push({ id: \"typecheck\", command: \"mypy .\", source: evidence })\n }\n if (mentions(\"ruff\") && resolveExecutable(\"ruff\", { env: process.env }) !== null) {\n out.push({ id: \"lint\", command: \"ruff check .\", source: evidence })\n }\n if (includeTests && (mentions(\"pytest\") || existsSync(nodePath.join(root, \"pytest.ini\")))) {\n if (resolveExecutable(\"pytest\", { env: process.env }) !== null) {\n out.push({ id: \"test\", command: \"pytest -q\", source: evidence })\n }\n }\n return out\n}\n\n/** Pick the first runnable candidate per id, in source-priority order. */\nfunction pickByPriority(candidates: Candidate[]): { checks: CheckSpec[]; evidence: string[] } {\n const byId = new Map<CheckId, Candidate>()\n for (const c of candidates) {\n if (!byId.has(c.id) && commandRunnable(c.command)) byId.set(c.id, c)\n }\n const order: CheckId[] = [\"typecheck\", \"lint\", \"test\"]\n const checks: CheckSpec[] = []\n const evidence = new Set<string>()\n for (const id of order) {\n const c = byId.get(id)\n if (c) {\n checks.push({ id: c.id, command: c.command })\n evidence.add(c.source)\n }\n }\n return { checks, evidence: [...evidence] }\n}\n\n/**\n * Resolve the gate descriptor for an already-resolved repo `root`.\n * 1. bun/TS sealed fast-path — byte-identical to the legacy `detectHarnessGateId`\n * (bun on PATH + a `typecheck` script → sealed `default-ci`/`typecheck-test`).\n * 2. else the deterministic parser: collect candidates from package.json\n * scripts (primary, self-contained), Make/just/task, language manifests, and\n * a CI gap-filler for static checks; pick one per id by priority. A `parsed`\n * descriptor is returned only when at least one STATIC check survives (a\n * test-only set would either be off-by-default or risk false-reds).\n * 3. else null (the launcher prints why and the gate stays off).\n */\nexport async function parseGateDescriptor(\n root: string,\n opts: { includeTests: boolean },\n): Promise<GateDescriptor | null> {\n // (1) bun/TS sealed parity.\n if (resolveExecutable(\"bun\", { env: process.env }) !== null) {\n const scripts = await readScripts(root)\n if (typeof scripts.typecheck === \"string\") {\n const gateId = typeof scripts.lint === \"string\" ? \"default-ci\" : \"typecheck-test\"\n return { kind: \"sealed\", gateId, workdir: root }\n }\n }\n\n // (2) deterministic parser. package.json scripts first (self-contained), then\n // task runners + manifests, then a CI gap-filler for static checks.\n const groups = await Promise.all([\n collectNodeChecks(root, opts.includeTests),\n collectTaskChecks(root, opts.includeTests),\n collectRustChecks(root, opts.includeTests),\n collectGoChecks(root, opts.includeTests),\n collectPythonChecks(root, opts.includeTests),\n collectCiChecks(root),\n ])\n const candidates = groups.flat()\n if (candidates.length === 0) return null\n\n const ecosystem =\n candidates.find((c) => c.source === \"package.json\") ? \"node\"\n : candidates.find((c) => c.source === \"Cargo.toml\") ? \"rust\"\n : candidates.find((c) => c.source === \"go.mod\") ? \"go\"\n : candidates.find((c) => /^(pyproject|setup|pytest|tox|ruff|mypy)/.test(c.source)) ? \"python\"\n : candidates.find((c) => /^(Makefile|makefile|justfile|\\.justfile|Taskfile)/.test(c.source)) ? \"make\"\n : \"ci\"\n\n const { checks, evidence } = pickByPriority(candidates)\n if (checks.length === 0) return null\n // Require at least one STATIC check (typecheck/lint/build) unless the caller\n // opted into running the full test suite — a test-only set is otherwise either\n // off-by-default or a slow/false-red risk on every stop.\n const hasStatic = checks.some((c) => STATIC_IDS.has(c.id as CheckId))\n if (!hasStatic && !opts.includeTests) return null\n return { kind: \"parsed\", checks, ecosystem, workdir: root, evidence }\n}\n\n/** The checks a descriptor runs: a sealed descriptor resolves its sealed command\n * set from the registry; parsed/discovered carry their own. Fresh array. */\nexport function checksForDescriptor(d: GateDescriptor): CheckSpec[] {\n if (d.kind === \"sealed\") {\n const sealed = resolveSealedGate(d.gateId)\n return sealed ? sealed.checks.map((c) => ({ id: c.id, command: c.command })) : []\n }\n return d.checks.map((c) => ({ id: c.id, command: c.command }))\n}\n\n/** A stable key over a descriptor's effective check set, for baseline isolation.\n * Sealed descriptors key on their gate id (preserving legacy baseline keys);\n * parsed/discovered key on the canonicalized (id,command) set, so a changed\n * command set yields a fresh baseline instead of masking/inventing regressions. */\nexport function descriptorHash(d: GateDescriptor): string {\n if (d.kind === \"sealed\") return `sealed:${d.gateId}`\n const canon = [...d.checks]\n .map((c) => `${c.id}\u0000${c.command.trim().replace(/\\s+/g, \" \")}`)\n .sort()\n .join(\"\u0001\")\n return `${d.kind}:${createHash(\"sha256\").update(canon).digest(\"hex\").slice(0, 32)}`\n}\n","/**\n * Evidence-pinned model FALLBACK for the structural Stop-gate — the last resort\n * when the deterministic parser (`harness-parse`) finds no runnable checks.\n *\n * A read-only worker reads the repo's own config/docs and proposes the canonical\n * check commands. Two guards keep this safe despite being model-authored:\n * 1. SANITIZE — `sanitizeDiscoveredCheck` rejects shell metacharacters (so a\n * command can never chain/redirect/expand), destructive/stateful verbs,\n * interactive/watch shapes, and an executable that isn't on PATH. What\n * survives is a single plain argv line, safe for `liveExec`'s naive split.\n * 2. EVIDENCE-PIN — a surviving command must appear (whitespace-normalized)\n * VERBATIM in one of the collected source files. The model cannot invent a\n * command or be prompt-injected into emitting one that isn't already a real\n * command in the repo (and a real command in a user-trusted repo is the\n * same authority the existing gate already runs).\n *\n * Discovery runs ONCE at launch and the result is cached per (repoFingerprint,\n * sourcesHash) in a human-readable record. The runtime Stop hook only READS the\n * cached record (no model call at stop). This is consumed ONLY by the local Stop\n * hook; the sealed-gate kernel never sees a discovered command.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { existsSync, promises as fs } from \"node:fs\"\nimport nodePath from \"node:path\"\n\nimport { resolveExecutable } from \"~/lib/exec\"\nimport { PATHS } from \"~/lib/paths\"\n\nimport { type CheckSpec } from \"./gate-runner\"\nimport { isMutatingCommand, isSafeCommand, type CheckId } from \"./harness-parse\"\nimport { repoFingerprint, repoRoot } from \"./stop-gate-policy\"\n\n/** The allowlist of files the discovery worker is steered to read — config +\n * docs that legitimately describe how to check a project. Secret files are\n * additionally blocked at the worker IO layer (`.env*`/`*.pem`/`id_*`/…). */\nconst SIGNAL_FILES: ReadonlyArray<string> = [\n \"package.json\",\n \"Makefile\",\n \"makefile\",\n \"justfile\",\n \".justfile\",\n \"Taskfile.yml\",\n \"Taskfile.yaml\",\n \"Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"setup.cfg\",\n \"tox.ini\",\n \"pytest.ini\",\n \"CONTRIBUTING.md\",\n \"CONTRIBUTING\",\n \"README.md\",\n \"README\",\n \"DEVELOPING.md\",\n \"mix.exs\",\n \"build.gradle\",\n \"pom.xml\",\n \"composer.json\",\n]\nconst SIGNAL_DIRS: ReadonlyArray<string> = [\".github/workflows\"]\n\n/** A discovered check command after sanitization + evidence-pinning. */\nexport interface DiscoveredRecord {\n root: string\n fingerprint: string\n sourcesHash: string\n discoveredAt: string\n model: string\n ecosystem: string\n checks: CheckSpec[]\n confidence: string\n evidence: string[]\n}\n\nconst MAX_SIGNAL_BYTES = 64 * 1024\n/** Global caps so a repo with many workflow files can't inflate discovery /\n * hashing cost: at most this many files and this much total text. */\nconst MAX_SIGNAL_FILES = 40\nconst MAX_TOTAL_SIGNAL_BYTES = 512 * 1024\n\n/** Words that mark a command as destructive, stateful, or non-terminating — a\n * \"check\" must never do any of these. (Shell operators are already rejected by\n * `isSafeCommand`, so chaining can't smuggle them past this word scan.) */\nconst DENY_WORD =\n /\\b(rm|rmdir|mv|dd|mkfs|sudo|chmod|chown|publish|push|deploy|migrate|kubectl|terraform|docker|curl|wget|ssh|scp|rsync|nc|eval|npm i|npm install|yarn add|pip install|apt|brew|watch|serve|repl|dev|start)\\b/i\n\n/**\n * True when `command` is safe to auto-run as a check: a plain argv line (no\n * shell metacharacters), no destructive/stateful verb, no mutating/interactive\n * shape, and its executable resolves on PATH. The deny-word scan runs on a\n * whitespace-NORMALIZED copy so a tab / double-space can't split `npm install`\n * past the literal-space patterns.\n */\nexport function sanitizeDiscoveredCheck(command: string): boolean {\n if (!isSafeCommand(command)) return false\n const norm = normalizeWs(command)\n if (DENY_WORD.test(norm)) return false\n if (isMutatingCommand(norm)) return false // --fix/--write/--watch + :fix/:write scripts\n const first = norm.split(\" \")[0] ?? \"\"\n return resolveExecutable(first, { env: process.env }) !== null\n}\n\nfunction normalizeWs(s: string): string {\n return s.replace(/\\s+/g, \" \").trim()\n}\n\n/** Collect the text of the allowlisted signal files (capped), for evidence-pin +\n * the sources hash. Returns the concatenated text and the relative file list. */\nasync function collectSignals(root: string): Promise<{ text: string; files: string[] }> {\n const parts: string[] = []\n const files: string[] = []\n let total = 0\n const readCapped = async (abs: string, rel: string): Promise<void> => {\n if (files.length >= MAX_SIGNAL_FILES || total >= MAX_TOTAL_SIGNAL_BYTES) return\n try {\n const raw = await fs.readFile(abs, \"utf8\")\n const slice = raw.length > MAX_SIGNAL_BYTES ? raw.slice(0, MAX_SIGNAL_BYTES) : raw\n parts.push(slice)\n files.push(rel)\n total += slice.length\n } catch {\n /* unreadable → skip */\n }\n }\n for (const f of SIGNAL_FILES) {\n const abs = nodePath.join(root, f)\n if (existsSync(abs)) await readCapped(abs, f)\n }\n for (const d of SIGNAL_DIRS) {\n const dir = nodePath.join(root, d)\n try {\n for (const name of await fs.readdir(dir)) {\n if (/\\.(ya?ml)$/i.test(name)) await readCapped(nodePath.join(dir, name), nodePath.join(d, name))\n }\n } catch {\n /* no dir */\n }\n }\n return { text: parts.join(\"\\n\"), files }\n}\n\n/** A freshness hash over the signal files' contents + relative paths. A change\n * to how the project checks itself flips this → re-discovery on next launch. */\nexport async function sourcesHash(root: string): Promise<string> {\n const { text, files } = await collectSignals(root)\n return createHash(\"sha256\")\n .update(files.sort().join(\"\\n\"))\n .update(\"\\0\")\n .update(text)\n .digest(\"hex\")\n}\n\nfunction discoveredDir(): string {\n return nodePath.join(PATHS.APP_DIR, \"stop-gate\", \"discovered\")\n}\nfunction recordPathFor(root: string): string {\n return nodePath.join(discoveredDir(), createHash(\"sha256\").update(nodePath.resolve(root)).digest(\"hex\").slice(0, 32))\n}\n\n/** Read the cached discovered record for `root`, verifying it still matches the\n * live repo identity AND the live sources hash. Any mismatch / unreadable /\n * empty-checks record → null (re-discover or stay off; never run a stale set). */\nexport async function readDiscoveredGate(root: string): Promise<DiscoveredRecord | null> {\n let rec: DiscoveredRecord\n try {\n rec = JSON.parse(await fs.readFile(recordPathFor(root), \"utf8\")) as DiscoveredRecord\n } catch {\n return null\n }\n if (!rec || !Array.isArray(rec.checks) || rec.checks.length === 0) return null\n const fp = await repoFingerprint(root).catch(() => \"\")\n if (fp.length === 0 || fp !== rec.fingerprint) return null // identity drift → deny.\n const sh = await sourcesHash(root).catch(() => \"\")\n if (sh.length === 0 || sh !== rec.sourcesHash) return null // config changed → stale.\n // Re-validate id AND re-sanitize the command at read time (defense-in-depth\n // against a tampered/corrupt record).\n const checks = rec.checks.filter(\n (c) => c && typeof c.id === \"string\" && VALID_IDS.has(c.id) && typeof c.command === \"string\" && sanitizeDiscoveredCheck(c.command),\n )\n if (checks.length === 0) return null\n return { ...rec, checks }\n}\n\nexport async function writeDiscoveredGate(rec: DiscoveredRecord): Promise<void> {\n await fs.mkdir(discoveredDir(), { recursive: true })\n const tmp = `${recordPathFor(rec.root)}.${process.pid}.tmp`\n await fs.writeFile(tmp, `${JSON.stringify(rec, null, 2)}\\n`, { mode: 0o600 })\n await fs.rename(tmp, recordPathFor(rec.root))\n}\n\nconst DISCOVERY_PROMPT = (files: string[]): string =>\n `You are configuring an automated pre-finish CHECK gate for this repository. Read ONLY these `\n + `already-present config/doc files to learn how the project checks itself: ${files.join(\", \")}. `\n + `Identify the canonical FAST static check command (typecheck and/or lint) and, if obvious, the test `\n + `command. Rules: (1) return a command ONLY if it appears VERBATIM in one of those files — never invent `\n + `one; (2) commands must be non-interactive, self-terminating, read-only verification (NO install / `\n + `publish / push / deploy / migrate / format-in-place / watch / serve / dev-server / delete); (3) at most `\n + `3 commands; (4) if unsure, return an empty list. Respond with ONLY a fenced \\`\\`\\`json block of the shape `\n + `{\"ecosystem\":\"<label>\",\"checks\":[{\"id\":\"typecheck|lint|test\",\"command\":\"<single-line command>\"}],`\n + `\"confidence\":\"high|low\"} and NOTHING else.`\n\ninterface DiscoverResult {\n ecosystem: string\n checks: CheckSpec[]\n confidence: string\n evidence: string[]\n}\n\n/** Extract the first fenced/bare JSON object from the worker's text. */\nfunction extractJson(text: string): unknown {\n const fenced = /```(?:json)?\\s*([\\s\\S]*?)```/i.exec(text)\n const body = fenced ? fenced[1] : text\n const start = body.indexOf(\"{\")\n const end = body.lastIndexOf(\"}\")\n if (start < 0 || end <= start) return undefined\n try {\n return JSON.parse(body.slice(start, end + 1)) as unknown\n } catch {\n return undefined\n }\n}\n\nconst VALID_IDS: ReadonlySet<string> = new Set<CheckId>([\"typecheck\", \"lint\", \"test\"])\n\n/**\n * Sanitize + EVIDENCE-PIN the model's raw checks against the collected source\n * text. Pure (no IO) so it is unit-testable without the worker. A check survives\n * only if: its id is canonical, it isn't a `test` while tests are off, its id\n * hasn't already been taken, it passes `sanitizeDiscoveredCheck`, AND its command\n * appears (whitespace-normalized) VERBATIM in `evidenceText`. The evidence-pin is\n * the load-bearing guard: the model cannot invent a command or be prompt-injected\n * into one that isn't already a real command in the (user-trusted) repo.\n */\nexport function filterDiscoveredChecks(\n rawChecks: unknown,\n evidenceText: string,\n includeTests: boolean,\n): CheckSpec[] {\n const evidenceNorm = normalizeWs(evidenceText)\n const seen = new Set<string>()\n const checks: CheckSpec[] = []\n for (const c of Array.isArray(rawChecks) ? rawChecks : []) {\n if (!c || typeof c !== \"object\") continue\n const id = (c as { id?: unknown }).id\n const command = (c as { command?: unknown }).command\n if (typeof id !== \"string\" || !VALID_IDS.has(id)) continue\n if (typeof command !== \"string\") continue\n if (id === \"test\" && !includeTests) continue\n if (seen.has(id)) continue\n if (!sanitizeDiscoveredCheck(command)) continue\n if (!evidenceNorm.includes(normalizeWs(command))) continue\n seen.add(id)\n checks.push({ id, command: command.trim() })\n }\n return checks\n}\n\n/**\n * Run the read-only worker to discover check commands for `cwd`. Returns the\n * sanitized + evidence-pinned result, or null (worker unavailable / errored /\n * nothing survived). NEVER throws.\n */\nexport async function discoverGateCommands(\n cwd: string,\n opts: { signal?: AbortSignal; includeTests: boolean },\n): Promise<DiscoverResult | null> {\n const root = await repoRoot(cwd).catch(() => cwd)\n const { text: evidenceText, files } = await collectSignals(root)\n if (files.length === 0) return null\n\n let result: { text: string; isError?: boolean }\n try {\n // Lazy-import the heavy worker-agent engine ONLY when discovery actually\n // runs — keeping it out of the module-load graph of `claude.ts` (which\n // imports this module), so the mock.module-isolated CLI tests don't deadlock\n // pulling the Pi runtime at load time.\n const { runWorkerAgent } = await import(\"~/lib/worker-agent/engine\")\n // Discovery is advisory setup, not a verified workflow producer/checker,\n // so honoring the operator's explore default here is intentional.\n result = await runWorkerAgent({\n mode: \"explore\",\n workspace: root,\n prompt: DISCOVERY_PROMPT(files),\n signal: opts.signal,\n })\n } catch {\n return null\n }\n if (result.isError) return null\n const parsed = extractJson(result.text)\n if (!parsed || typeof parsed !== \"object\") return null\n const obj = parsed as { ecosystem?: unknown; checks?: unknown; confidence?: unknown }\n const checks = filterDiscoveredChecks(obj.checks, evidenceText, opts.includeTests)\n if (checks.length === 0) return null\n const ecosystem = typeof obj.ecosystem === \"string\" && obj.ecosystem.length > 0 ? obj.ecosystem : \"discovered\"\n const confidence = typeof obj.confidence === \"string\" ? obj.confidence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;EAAE,WAFS,OAAO,IAAI,cAAc,YAAY,IAAI,UAAU,SAAS,IAAI,IAAI,YAAY;EAE9E;EAAQ,YADT,OAAO,IAAI,eAAe,WAAW,IAAI,aAAa;EACjC,UAAU;CAAM;AAC1D"}
1
+ {"version":3,"file":"gate-discovery-B2x_8hNL.js","names":["fs","nodePath","fs","nodePath"],"sources":["../src/lib/orchestration/harness-parse.ts","../src/lib/orchestration/gate-discovery.ts"],"sourcesContent":["/**\n * Deterministic, language-agnostic harness PARSER for the structural Stop-gate.\n *\n * The gate runs a repo's own checks (typecheck/lint/test/build) when the agent\n * tries to finish. Historically it only auto-enabled for Bun/TS repos via a\n * hard-coded sealed gate. This module generalizes detection by PARSING the\n * project's own authoritative config — `package.json` scripts, CI `run:` steps,\n * Make/just/task targets, and language manifests — and emitting the canonical\n * check commands it finds.\n *\n * Design properties (a cross-lab panel chose a parser over a model for these):\n * - EVIDENCE-PINNED BY CONSTRUCTION: every emitted command is either lifted\n * verbatim from a parsed source file (a package.json script, a CI `run:`\n * line, a Make target invocation) or is a fixed canonical manifest command\n * for a detected ecosystem (`cargo check`, `go vet ./...`). The parser never\n * invents a command, so it has no hallucination / prompt-injection surface.\n * - PURE + DETERMINISTIC: a function of the repo's files + the live PATH. The\n * runtime Stop hook re-derives it at each stop (no cache), so it always\n * reflects the current tree and fails open for free when a tool vanished.\n * - SHELL-SAFE: `liveExec` runs `command.trim().split(/\\s+/)` (naive argv\n * split, no shell), so every emitted command is validated to be plain\n * space-separated tokens with no shell operators and no `%` (cmd.exe quoting\n * throws on `%`). See `isSafeCommand`.\n *\n * This is consumed ONLY by the local Stop hook. The sealed-gate kernel\n * (`run_workflow`) is never fed a parsed command — `GateDescriptor.kind` is\n * `\"parsed\"`, never a sealed id, and `sealedGateIds()` is unchanged.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { existsSync, promises as fs } from \"node:fs\"\nimport nodePath from \"node:path\"\n\nimport { resolveExecutable } from \"~/lib/exec\"\n\nimport { resolveSealedGate } from \"./gate-registry\"\nimport { type CheckSpec } from \"./gate-runner\"\n\n/** Canonical check ids — stable across ecosystems so baseline isolation and the\n * selector key on the same names regardless of language. `build` is deliberately\n * NOT a check: build scripts are too variable in cost to auto-run on every stop\n * (a full bundle/SEA build is the slow-command / false-red footgun the design\n * avoids). Compile-checking is covered under `typecheck` (`go vet`, `cargo\n * check`, `tsc`). */\nexport type CheckId = \"typecheck\" | \"lint\" | \"test\"\n\n/** The fast static checks that are always-on; `test` is opt-in (it runs project\n * code and can be slow on every stop). */\nconst STATIC_IDS: ReadonlySet<CheckId> = new Set([\"typecheck\", \"lint\"])\n\n/**\n * The resolved gate source for a repo.\n * - `sealed` — the bun/TS fast-path (a sealed gate id, byte-identical to\n * the legacy behavior; the runtime hook resolves it via the\n * sealed registry).\n * - `parsed` — deterministic parser output (this module).\n * - `discovered` — the evidence-pinned model fallback (see `gate-discovery`).\n * `workdir` is the directory the checks run in (the repo/package root where the\n * evidence was found), NOT the Stop payload's cwd — so a monorepo stop from a\n * nested dir still runs the root's checks.\n */\nexport type GateDescriptor =\n | { kind: \"sealed\"; gateId: string; workdir: string }\n | { kind: \"parsed\"; checks: CheckSpec[]; ecosystem: string; workdir: string; evidence: string[] }\n | { kind: \"discovered\"; checks: CheckSpec[]; ecosystem: string; workdir: string; evidence: string[] }\n\ninterface Candidate {\n id: CheckId\n command: string\n /** The source file the command was lifted from (for evidence + messages). */\n source: string\n}\n\n/** Reject anything that is not a plain, shell-free, `%`-free argv line. This is\n * the load-bearing guard for `liveExec`'s naive whitespace split. */\nexport function isSafeCommand(command: string): boolean {\n const c = command.trim()\n if (c.length === 0 || c.length > 200) return false\n if (/[\\r\\n]/.test(c)) return false\n // Each token may contain only these chars: letters/digits and a small set of\n // path/flag punctuation. This rejects shell metacharacters (; & | < > ( ) $\n // backtick \" ' * ? ! ^ \\ %), env expansion, and quoting in one shot.\n const tokens = c.split(/\\s+/).filter(Boolean)\n if (tokens.length === 0) return false\n return tokens.every((t) => /^[A-Za-z0-9._/:@=+-]+$/.test(t))\n}\n\n/** First token of a command (the executable), for a PATH-presence probe. */\nfunction firstToken(command: string): string {\n return command.trim().split(/\\s+/)[0] ?? \"\"\n}\n\n/** True when a command would MUTATE the tree and so must never be a gate: a\n * `--fix`/`--write` flag or a `:fix`/`:write` script-name suffix (e.g.\n * `npm run lint:fix`, `eslint --fix`). Whitespace is normalized first so a\n * tab/double-space can't slip a flag past the scan. Exported + shared with the\n * discovered-command sanitizer. */\nexport function isMutatingCommand(command: string): boolean {\n const c = command.trim().replace(/\\s+/g, \" \")\n if (/(^| )(--fix|--write|-w|--watch|--serve|--interactive|-i)( |=|$)/i.test(c)) return true\n if (/(^| |:|-)(fix|write)\\b/i.test(c)) return true\n return false\n}\n\n/** True when the command is safe AND its executable resolves on PATH (a missing\n * tool → drop the check rather than guarantee a false-red). */\nfunction commandRunnable(command: string): boolean {\n if (!isSafeCommand(command)) return false\n return resolveExecutable(firstToken(command), { env: process.env }) !== null\n}\n\nasync function readJsonFile(file: string): Promise<unknown | undefined> {\n try {\n return JSON.parse(await fs.readFile(file, \"utf8\")) as unknown\n } catch {\n return undefined\n }\n}\n\nasync function readTextFile(file: string): Promise<string | undefined> {\n try {\n return await fs.readFile(file, \"utf8\")\n } catch {\n return undefined\n }\n}\n\n/** package.json `scripts` as a plain string→string map (best-effort). */\nasync function readScripts(root: string): Promise<Record<string, string>> {\n const pkg = await readJsonFile(nodePath.join(root, \"package.json\"))\n const scripts = pkg && typeof pkg === \"object\" ? (pkg as { scripts?: unknown }).scripts : undefined\n const out: Record<string, string> = {}\n if (scripts && typeof scripts === \"object\") {\n for (const [k, v] of Object.entries(scripts as Record<string, unknown>)) {\n if (typeof v === \"string\") out[k] = v\n }\n }\n return out\n}\n\n/** Pick the JS package runner from the lockfile present at the root. */\nfunction nodeRunner(root: string): \"bun\" | \"pnpm\" | \"yarn\" | \"npm\" {\n if (existsSync(nodePath.join(root, \"bun.lockb\")) || existsSync(nodePath.join(root, \"bun.lock\"))) return \"bun\"\n if (existsSync(nodePath.join(root, \"pnpm-lock.yaml\"))) return \"pnpm\"\n if (existsSync(nodePath.join(root, \"yarn.lock\"))) return \"yarn\"\n return \"npm\"\n}\n\n/** Map a package.json script NAME to a canonical id (read-only checks only — a\n * `:fix`/`:write` variant mutates the tree and is never a gate). */\nfunction scriptNameToId(name: string): CheckId | null {\n if (/:(fix|write)$/i.test(name)) return null\n if (/^(typecheck|type-check|check-types|tsc|types)$/i.test(name)) return \"typecheck\"\n if (/^(lint|lint:check|eslint)$/i.test(name)) return \"lint\"\n if (/^test$/i.test(name)) return \"test\"\n return null\n}\n\nasync function collectNodeChecks(root: string, includeTests: boolean): Promise<Candidate[]> {\n if (!existsSync(nodePath.join(root, \"package.json\"))) return []\n const runner = nodeRunner(root)\n if (resolveExecutable(runner, { env: process.env }) === null) return []\n const scripts = await readScripts(root)\n const out: Candidate[] = []\n for (const [name] of Object.entries(scripts)) {\n const id = scriptNameToId(name)\n if (!id) continue\n if (id === \"test\" && !includeTests) continue\n const command = `${runner} run ${name}`\n if (isSafeCommand(command)) out.push({ id, command, source: \"package.json\" })\n }\n return out\n}\n\n/**\n * Best-effort CI gap-filler: scan GitHub Actions / GitLab CI YAML for single-line\n * `run:` static checks (typecheck/lint/build) the project actually runs. We do\n * NOT lift `test` from CI — CI test jobs frequently need services/secrets and\n * would false-red on every stop. Multi-line / scripted `run:` blocks are skipped\n * (they can't be a single argv). Any parse failure yields nothing.\n */\nasync function collectCiChecks(root: string): Promise<Candidate[]> {\n const files: string[] = []\n const wfDir = nodePath.join(root, \".github\", \"workflows\")\n try {\n for (const name of await fs.readdir(wfDir)) {\n if (/\\.ya?ml$/i.test(name)) files.push(nodePath.join(wfDir, name))\n }\n } catch {\n /* no workflows dir */\n }\n const gitlab = nodePath.join(root, \".gitlab-ci.yml\")\n if (existsSync(gitlab)) files.push(gitlab)\n if (files.length === 0) return []\n\n let parseYaml: (s: string) => unknown\n try {\n // Lazy import so the parser module has no hard dep when CI files are absent.\n ;({ parse: parseYaml } = await import(\"yaml\"))\n } catch {\n return []\n }\n\n const out: Candidate[] = []\n const seen = new Set<CheckId>()\n const classify = (cmd: string): CheckId | null => {\n if (/\\b(typecheck|type-check|tsc|mypy|pyright)\\b/i.test(cmd)) return \"typecheck\"\n if (/\\b(lint|eslint|ruff|clippy|golangci|vet)\\b/i.test(cmd)) return \"lint\"\n return null\n }\n const consider = (run: unknown, source: string): void => {\n if (typeof run !== \"string\") return\n const cmd = run.trim()\n if (cmd.includes(\"\\n\")) return // multi-line script block — not a single argv.\n if (!isSafeCommand(cmd) || isMutatingCommand(cmd) || !commandRunnable(cmd)) return\n const id = classify(cmd)\n if (!id || seen.has(id)) return\n seen.add(id)\n out.push({ id, command: cmd, source })\n }\n // Walk the parsed YAML for any `run:` string anywhere (GH `steps[].run`, GitLab\n // `<job>.script[]`). A generic deep walk tolerates both schemas + future shapes.\n const walk = (node: unknown, source: string): void => {\n if (!node || typeof node !== \"object\") return\n if (Array.isArray(node)) {\n for (const v of node) walk(v, source)\n return\n }\n for (const [k, v] of Object.entries(node as Record<string, unknown>)) {\n if (k === \"run\" && typeof v === \"string\") consider(v, source)\n else if (k === \"script\") {\n // GitLab `script:` is a string or string[].\n if (typeof v === \"string\") consider(v, source)\n else if (Array.isArray(v)) for (const s of v) consider(s, source)\n } else walk(v, source)\n }\n }\n for (const f of files) {\n const text = await readTextFile(f)\n if (text === undefined) continue\n try {\n walk(parseYaml(text), nodePath.relative(root, f) || nodePath.basename(f))\n } catch {\n /* unparseable workflow → skip */\n }\n }\n return out\n}\n\n/** Make / just / Taskfile targets matching canonical ids → `<tool> <target>`. */\nasync function collectTaskChecks(root: string, includeTests: boolean): Promise<Candidate[]> {\n const out: Candidate[] = []\n const wantId = (target: string): CheckId | null => scriptNameToId(target)\n // Makefile / justfile: a line `target:` (Make) or `target:` (just recipe head).\n for (const [file, tool] of [\n [\"Makefile\", \"make\"],\n [\"makefile\", \"make\"],\n [\"justfile\", \"just\"],\n [\".justfile\", \"just\"],\n ] as const) {\n const text = await readTextFile(nodePath.join(root, file))\n if (text === undefined) continue\n if (resolveExecutable(tool, { env: process.env }) === null) continue\n for (const line of text.split(/\\r?\\n/)) {\n const m = /^([A-Za-z0-9._-]+)\\s*:/.exec(line)\n if (!m) continue\n const id = wantId(m[1])\n if (!id || (id === \"test\" && !includeTests)) continue\n const command = `${tool} ${m[1]}`\n if (isSafeCommand(command)) out.push({ id, command, source: file })\n }\n }\n // Taskfile.yml: top-level `tasks:` keys.\n const taskfile = [\"Taskfile.yml\", \"Taskfile.yaml\"].map((n) => nodePath.join(root, n)).find((p) => existsSync(p))\n if (taskfile && resolveExecutable(\"task\", { env: process.env }) !== null) {\n const text = await readTextFile(taskfile)\n if (text !== undefined) {\n try {\n const { parse } = await import(\"yaml\")\n const doc = parse(text) as { tasks?: Record<string, unknown> } | undefined\n for (const name of Object.keys(doc?.tasks ?? {})) {\n const id = wantId(name)\n if (!id || (id === \"test\" && !includeTests)) continue\n const command = `task ${name}`\n if (isSafeCommand(command)) out.push({ id, command, source: nodePath.basename(taskfile) })\n }\n } catch {\n /* skip */\n }\n }\n }\n return out\n}\n\nasync function collectRustChecks(root: string, includeTests: boolean): Promise<Candidate[]> {\n if (!existsSync(nodePath.join(root, \"Cargo.toml\"))) return []\n if (resolveExecutable(\"cargo\", { env: process.env }) === null) return []\n const out: Candidate[] = [{ id: \"typecheck\", command: \"cargo check\", source: \"Cargo.toml\" }]\n // clippy is a separate component; only emit it if `cargo-clippy` resolves.\n if (resolveExecutable(\"cargo-clippy\", { env: process.env }) !== null) {\n out.push({ id: \"lint\", command: \"cargo clippy\", source: \"Cargo.toml\" })\n }\n if (includeTests) out.push({ id: \"test\", command: \"cargo test\", source: \"Cargo.toml\" })\n return out\n}\n\nasync function collectGoChecks(root: string, includeTests: boolean): Promise<Candidate[]> {\n if (!existsSync(nodePath.join(root, \"go.mod\"))) return []\n if (resolveExecutable(\"go\", { env: process.env }) === null) return []\n // `go vet` compiles + reports suspect constructs — the typecheck-equivalent.\n const out: Candidate[] = [{ id: \"typecheck\", command: \"go vet ./...\", source: \"go.mod\" }]\n if (includeTests) out.push({ id: \"test\", command: \"go test ./...\", source: \"go.mod\" })\n return out\n}\n\nasync function collectPythonChecks(root: string, includeTests: boolean): Promise<Candidate[]> {\n const configFiles = [\"pyproject.toml\", \"setup.cfg\", \"pytest.ini\", \"tox.ini\", \"ruff.toml\", \"mypy.ini\"]\n const present = configFiles.filter((f) => existsSync(nodePath.join(root, f)))\n if (present.length === 0) return []\n const evidence = present[0]\n const out: Candidate[] = []\n const configText = (await readTextFile(nodePath.join(root, present[0]))) ?? \"\"\n const mentions = (tool: string): boolean => present.some((f) => f.startsWith(tool)) || configText.includes(tool)\n // Only emit a Python tool when BOTH config evidence AND the tool resolve.\n if (mentions(\"mypy\") && resolveExecutable(\"mypy\", { env: process.env }) !== null) {\n out.push({ id: \"typecheck\", command: \"mypy .\", source: evidence })\n }\n if (mentions(\"ruff\") && resolveExecutable(\"ruff\", { env: process.env }) !== null) {\n out.push({ id: \"lint\", command: \"ruff check .\", source: evidence })\n }\n if (includeTests && (mentions(\"pytest\") || existsSync(nodePath.join(root, \"pytest.ini\")))) {\n if (resolveExecutable(\"pytest\", { env: process.env }) !== null) {\n out.push({ id: \"test\", command: \"pytest -q\", source: evidence })\n }\n }\n return out\n}\n\n/** Pick the first runnable candidate per id, in source-priority order. */\nfunction pickByPriority(candidates: Candidate[]): { checks: CheckSpec[]; evidence: string[] } {\n const byId = new Map<CheckId, Candidate>()\n for (const c of candidates) {\n if (!byId.has(c.id) && commandRunnable(c.command)) byId.set(c.id, c)\n }\n const order: CheckId[] = [\"typecheck\", \"lint\", \"test\"]\n const checks: CheckSpec[] = []\n const evidence = new Set<string>()\n for (const id of order) {\n const c = byId.get(id)\n if (c) {\n checks.push({ id: c.id, command: c.command })\n evidence.add(c.source)\n }\n }\n return { checks, evidence: [...evidence] }\n}\n\n/**\n * Resolve the gate descriptor for an already-resolved repo `root`.\n * 1. bun/TS sealed fast-path — byte-identical to the legacy `detectHarnessGateId`\n * (bun on PATH + a `typecheck` script → sealed `default-ci`/`typecheck-test`).\n * 2. else the deterministic parser: collect candidates from package.json\n * scripts (primary, self-contained), Make/just/task, language manifests, and\n * a CI gap-filler for static checks; pick one per id by priority. A `parsed`\n * descriptor is returned only when at least one STATIC check survives (a\n * test-only set would either be off-by-default or risk false-reds).\n * 3. else null (the launcher prints why and the gate stays off).\n */\nexport async function parseGateDescriptor(\n root: string,\n opts: { includeTests: boolean },\n): Promise<GateDescriptor | null> {\n // (1) bun/TS sealed parity.\n if (resolveExecutable(\"bun\", { env: process.env }) !== null) {\n const scripts = await readScripts(root)\n if (typeof scripts.typecheck === \"string\") {\n const gateId = typeof scripts.lint === \"string\" ? \"default-ci\" : \"typecheck-test\"\n return { kind: \"sealed\", gateId, workdir: root }\n }\n }\n\n // (2) deterministic parser. package.json scripts first (self-contained), then\n // task runners + manifests, then a CI gap-filler for static checks.\n const groups = await Promise.all([\n collectNodeChecks(root, opts.includeTests),\n collectTaskChecks(root, opts.includeTests),\n collectRustChecks(root, opts.includeTests),\n collectGoChecks(root, opts.includeTests),\n collectPythonChecks(root, opts.includeTests),\n collectCiChecks(root),\n ])\n const candidates = groups.flat()\n if (candidates.length === 0) return null\n\n const ecosystem =\n candidates.find((c) => c.source === \"package.json\") ? \"node\"\n : candidates.find((c) => c.source === \"Cargo.toml\") ? \"rust\"\n : candidates.find((c) => c.source === \"go.mod\") ? \"go\"\n : candidates.find((c) => /^(pyproject|setup|pytest|tox|ruff|mypy)/.test(c.source)) ? \"python\"\n : candidates.find((c) => /^(Makefile|makefile|justfile|\\.justfile|Taskfile)/.test(c.source)) ? \"make\"\n : \"ci\"\n\n const { checks, evidence } = pickByPriority(candidates)\n if (checks.length === 0) return null\n // Require at least one STATIC check (typecheck/lint/build) unless the caller\n // opted into running the full test suite — a test-only set is otherwise either\n // off-by-default or a slow/false-red risk on every stop.\n const hasStatic = checks.some((c) => STATIC_IDS.has(c.id as CheckId))\n if (!hasStatic && !opts.includeTests) return null\n return { kind: \"parsed\", checks, ecosystem, workdir: root, evidence }\n}\n\n/** The checks a descriptor runs: a sealed descriptor resolves its sealed command\n * set from the registry; parsed/discovered carry their own. Fresh array. */\nexport function checksForDescriptor(d: GateDescriptor): CheckSpec[] {\n if (d.kind === \"sealed\") {\n const sealed = resolveSealedGate(d.gateId)\n return sealed ? sealed.checks.map((c) => ({ id: c.id, command: c.command })) : []\n }\n return d.checks.map((c) => ({ id: c.id, command: c.command }))\n}\n\n/** A stable key over a descriptor's effective check set, for baseline isolation.\n * Sealed descriptors key on their gate id (preserving legacy baseline keys);\n * parsed/discovered key on the canonicalized (id,command) set, so a changed\n * command set yields a fresh baseline instead of masking/inventing regressions. */\nexport function descriptorHash(d: GateDescriptor): string {\n if (d.kind === \"sealed\") return `sealed:${d.gateId}`\n const canon = [...d.checks]\n .map((c) => `${c.id}\u0000${c.command.trim().replace(/\\s+/g, \" \")}`)\n .sort()\n .join(\"\u0001\")\n return `${d.kind}:${createHash(\"sha256\").update(canon).digest(\"hex\").slice(0, 32)}`\n}\n","/**\n * Evidence-pinned model FALLBACK for the structural Stop-gate — the last resort\n * when the deterministic parser (`harness-parse`) finds no runnable checks.\n *\n * A read-only worker reads the repo's own config/docs and proposes the canonical\n * check commands. Two guards keep this safe despite being model-authored:\n * 1. SANITIZE — `sanitizeDiscoveredCheck` rejects shell metacharacters (so a\n * command can never chain/redirect/expand), destructive/stateful verbs,\n * interactive/watch shapes, and an executable that isn't on PATH. What\n * survives is a single plain argv line, safe for `liveExec`'s naive split.\n * 2. EVIDENCE-PIN — a surviving command must appear (whitespace-normalized)\n * VERBATIM in one of the collected source files. The model cannot invent a\n * command or be prompt-injected into emitting one that isn't already a real\n * command in the repo (and a real command in a user-trusted repo is the\n * same authority the existing gate already runs).\n *\n * Discovery runs ONCE at launch and the result is cached per (repoFingerprint,\n * sourcesHash) in a human-readable record. The runtime Stop hook only READS the\n * cached record (no model call at stop). This is consumed ONLY by the local Stop\n * hook; the sealed-gate kernel never sees a discovered command.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { existsSync, promises as fs } from \"node:fs\"\nimport nodePath from \"node:path\"\n\nimport { resolveExecutable } from \"~/lib/exec\"\nimport { PATHS } from \"~/lib/paths\"\n\nimport { type CheckSpec } from \"./gate-runner\"\nimport { isMutatingCommand, isSafeCommand, type CheckId } from \"./harness-parse\"\nimport { repoFingerprint, repoRoot } from \"./stop-gate-policy\"\n\n/** The allowlist of files the discovery worker is steered to read — config +\n * docs that legitimately describe how to check a project. Secret files are\n * additionally blocked at the worker IO layer (`.env*`/`*.pem`/`id_*`/…). */\nconst SIGNAL_FILES: ReadonlyArray<string> = [\n \"package.json\",\n \"Makefile\",\n \"makefile\",\n \"justfile\",\n \".justfile\",\n \"Taskfile.yml\",\n \"Taskfile.yaml\",\n \"Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"setup.cfg\",\n \"tox.ini\",\n \"pytest.ini\",\n \"CONTRIBUTING.md\",\n \"CONTRIBUTING\",\n \"README.md\",\n \"README\",\n \"DEVELOPING.md\",\n \"mix.exs\",\n \"build.gradle\",\n \"pom.xml\",\n \"composer.json\",\n]\nconst SIGNAL_DIRS: ReadonlyArray<string> = [\".github/workflows\"]\n\n/** A discovered check command after sanitization + evidence-pinning. */\nexport interface DiscoveredRecord {\n root: string\n fingerprint: string\n sourcesHash: string\n discoveredAt: string\n model: string\n ecosystem: string\n checks: CheckSpec[]\n confidence: string\n evidence: string[]\n}\n\nconst MAX_SIGNAL_BYTES = 64 * 1024\n/** Global caps so a repo with many workflow files can't inflate discovery /\n * hashing cost: at most this many files and this much total text. */\nconst MAX_SIGNAL_FILES = 40\nconst MAX_TOTAL_SIGNAL_BYTES = 512 * 1024\n\n/** Words that mark a command as destructive, stateful, or non-terminating — a\n * \"check\" must never do any of these. (Shell operators are already rejected by\n * `isSafeCommand`, so chaining can't smuggle them past this word scan.) */\nconst DENY_WORD =\n /\\b(rm|rmdir|mv|dd|mkfs|sudo|chmod|chown|publish|push|deploy|migrate|kubectl|terraform|docker|curl|wget|ssh|scp|rsync|nc|eval|npm i|npm install|yarn add|pip install|apt|brew|watch|serve|repl|dev|start)\\b/i\n\n/**\n * True when `command` is safe to auto-run as a check: a plain argv line (no\n * shell metacharacters), no destructive/stateful verb, no mutating/interactive\n * shape, and its executable resolves on PATH. The deny-word scan runs on a\n * whitespace-NORMALIZED copy so a tab / double-space can't split `npm install`\n * past the literal-space patterns.\n */\nexport function sanitizeDiscoveredCheck(command: string): boolean {\n if (!isSafeCommand(command)) return false\n const norm = normalizeWs(command)\n if (DENY_WORD.test(norm)) return false\n if (isMutatingCommand(norm)) return false // --fix/--write/--watch + :fix/:write scripts\n const first = norm.split(\" \")[0] ?? \"\"\n return resolveExecutable(first, { env: process.env }) !== null\n}\n\nfunction normalizeWs(s: string): string {\n return s.replace(/\\s+/g, \" \").trim()\n}\n\n/** Collect the text of the allowlisted signal files (capped), for evidence-pin +\n * the sources hash. Returns the concatenated text and the relative file list. */\nasync function collectSignals(root: string): Promise<{ text: string; files: string[] }> {\n const parts: string[] = []\n const files: string[] = []\n let total = 0\n const readCapped = async (abs: string, rel: string): Promise<void> => {\n if (files.length >= MAX_SIGNAL_FILES || total >= MAX_TOTAL_SIGNAL_BYTES) return\n try {\n const raw = await fs.readFile(abs, \"utf8\")\n const slice = raw.length > MAX_SIGNAL_BYTES ? raw.slice(0, MAX_SIGNAL_BYTES) : raw\n parts.push(slice)\n files.push(rel)\n total += slice.length\n } catch {\n /* unreadable → skip */\n }\n }\n for (const f of SIGNAL_FILES) {\n const abs = nodePath.join(root, f)\n if (existsSync(abs)) await readCapped(abs, f)\n }\n for (const d of SIGNAL_DIRS) {\n const dir = nodePath.join(root, d)\n try {\n for (const name of await fs.readdir(dir)) {\n if (/\\.(ya?ml)$/i.test(name)) await readCapped(nodePath.join(dir, name), nodePath.join(d, name))\n }\n } catch {\n /* no dir */\n }\n }\n return { text: parts.join(\"\\n\"), files }\n}\n\n/** A freshness hash over the signal files' contents + relative paths. A change\n * to how the project checks itself flips this → re-discovery on next launch. */\nexport async function sourcesHash(root: string): Promise<string> {\n const { text, files } = await collectSignals(root)\n return createHash(\"sha256\")\n .update(files.sort().join(\"\\n\"))\n .update(\"\\0\")\n .update(text)\n .digest(\"hex\")\n}\n\nfunction discoveredDir(): string {\n return nodePath.join(PATHS.APP_DIR, \"stop-gate\", \"discovered\")\n}\nfunction recordPathFor(root: string): string {\n return nodePath.join(discoveredDir(), createHash(\"sha256\").update(nodePath.resolve(root)).digest(\"hex\").slice(0, 32))\n}\n\n/** Read the cached discovered record for `root`, verifying it still matches the\n * live repo identity AND the live sources hash. Any mismatch / unreadable /\n * empty-checks record → null (re-discover or stay off; never run a stale set). */\nexport async function readDiscoveredGate(root: string): Promise<DiscoveredRecord | null> {\n let rec: DiscoveredRecord\n try {\n rec = JSON.parse(await fs.readFile(recordPathFor(root), \"utf8\")) as DiscoveredRecord\n } catch {\n return null\n }\n if (!rec || !Array.isArray(rec.checks) || rec.checks.length === 0) return null\n const fp = await repoFingerprint(root).catch(() => \"\")\n if (fp.length === 0 || fp !== rec.fingerprint) return null // identity drift → deny.\n const sh = await sourcesHash(root).catch(() => \"\")\n if (sh.length === 0 || sh !== rec.sourcesHash) return null // config changed → stale.\n // Re-validate id AND re-sanitize the command at read time (defense-in-depth\n // against a tampered/corrupt record).\n const checks = rec.checks.filter(\n (c) => c && typeof c.id === \"string\" && VALID_IDS.has(c.id) && typeof c.command === \"string\" && sanitizeDiscoveredCheck(c.command),\n )\n if (checks.length === 0) return null\n return { ...rec, checks }\n}\n\nexport async function writeDiscoveredGate(rec: DiscoveredRecord): Promise<void> {\n await fs.mkdir(discoveredDir(), { recursive: true })\n const tmp = `${recordPathFor(rec.root)}.${process.pid}.tmp`\n await fs.writeFile(tmp, `${JSON.stringify(rec, null, 2)}\\n`, { mode: 0o600 })\n await fs.rename(tmp, recordPathFor(rec.root))\n}\n\nconst DISCOVERY_PROMPT = (files: string[]): string =>\n `You are configuring an automated pre-finish CHECK gate for this repository. Read ONLY these `\n + `already-present config/doc files to learn how the project checks itself: ${files.join(\", \")}. `\n + `Identify the canonical FAST static check command (typecheck and/or lint) and, if obvious, the test `\n + `command. Rules: (1) return a command ONLY if it appears VERBATIM in one of those files — never invent `\n + `one; (2) commands must be non-interactive, self-terminating, read-only verification (NO install / `\n + `publish / push / deploy / migrate / format-in-place / watch / serve / dev-server / delete); (3) at most `\n + `3 commands; (4) if unsure, return an empty list. Respond with ONLY a fenced \\`\\`\\`json block of the shape `\n + `{\"ecosystem\":\"<label>\",\"checks\":[{\"id\":\"typecheck|lint|test\",\"command\":\"<single-line command>\"}],`\n + `\"confidence\":\"high|low\"} and NOTHING else.`\n\ninterface DiscoverResult {\n ecosystem: string\n checks: CheckSpec[]\n confidence: string\n evidence: string[]\n}\n\n/** Extract the first fenced/bare JSON object from the worker's text. */\nfunction extractJson(text: string): unknown {\n const fenced = /```(?:json)?\\s*([\\s\\S]*?)```/i.exec(text)\n const body = fenced ? fenced[1] : text\n const start = body.indexOf(\"{\")\n const end = body.lastIndexOf(\"}\")\n if (start < 0 || end <= start) return undefined\n try {\n return JSON.parse(body.slice(start, end + 1)) as unknown\n } catch {\n return undefined\n }\n}\n\nconst VALID_IDS: ReadonlySet<string> = new Set<CheckId>([\"typecheck\", \"lint\", \"test\"])\n\n/**\n * Sanitize + EVIDENCE-PIN the model's raw checks against the collected source\n * text. Pure (no IO) so it is unit-testable without the worker. A check survives\n * only if: its id is canonical, it isn't a `test` while tests are off, its id\n * hasn't already been taken, it passes `sanitizeDiscoveredCheck`, AND its command\n * appears (whitespace-normalized) VERBATIM in `evidenceText`. The evidence-pin is\n * the load-bearing guard: the model cannot invent a command or be prompt-injected\n * into one that isn't already a real command in the (user-trusted) repo.\n */\nexport function filterDiscoveredChecks(\n rawChecks: unknown,\n evidenceText: string,\n includeTests: boolean,\n): CheckSpec[] {\n const evidenceNorm = normalizeWs(evidenceText)\n const seen = new Set<string>()\n const checks: CheckSpec[] = []\n for (const c of Array.isArray(rawChecks) ? rawChecks : []) {\n if (!c || typeof c !== \"object\") continue\n const id = (c as { id?: unknown }).id\n const command = (c as { command?: unknown }).command\n if (typeof id !== \"string\" || !VALID_IDS.has(id)) continue\n if (typeof command !== \"string\") continue\n if (id === \"test\" && !includeTests) continue\n if (seen.has(id)) continue\n if (!sanitizeDiscoveredCheck(command)) continue\n if (!evidenceNorm.includes(normalizeWs(command))) continue\n seen.add(id)\n checks.push({ id, command: command.trim() })\n }\n return checks\n}\n\n/**\n * Run the read-only worker to discover check commands for `cwd`. Returns the\n * sanitized + evidence-pinned result, or null (worker unavailable / errored /\n * nothing survived). NEVER throws.\n */\nexport async function discoverGateCommands(\n cwd: string,\n opts: { signal?: AbortSignal; includeTests: boolean },\n): Promise<DiscoverResult | null> {\n const root = await repoRoot(cwd).catch(() => cwd)\n const { text: evidenceText, files } = await collectSignals(root)\n if (files.length === 0) return null\n\n let result: { text: string; isError?: boolean }\n try {\n // Lazy-import the heavy worker-agent engine ONLY when discovery actually\n // runs — keeping it out of the module-load graph of `claude.ts` (which\n // imports this module), so the mock.module-isolated CLI tests don't deadlock\n // pulling the Pi runtime at load time.\n const { runWorkerAgent } = await import(\"~/lib/worker-agent/engine\")\n // Discovery is advisory setup, not a verified workflow producer/checker,\n // so honoring the operator's explore default here is intentional.\n result = await runWorkerAgent({\n mode: \"explore\",\n workspace: root,\n prompt: DISCOVERY_PROMPT(files),\n signal: opts.signal,\n })\n } catch {\n return null\n }\n if (result.isError) return null\n const parsed = extractJson(result.text)\n if (!parsed || typeof parsed !== \"object\") return null\n const obj = parsed as { ecosystem?: unknown; checks?: unknown; confidence?: unknown }\n const checks = filterDiscoveredChecks(obj.checks, evidenceText, opts.includeTests)\n if (checks.length === 0) return null\n const ecosystem = typeof obj.ecosystem === \"string\" && obj.ecosystem.length > 0 ? obj.ecosystem : \"discovered\"\n const confidence = typeof ob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AAG,OAAO;CAGhC,OAAO;EAAE,WAFS,OAAO,IAAI,cAAc,YAAY,IAAI,UAAU,SAAS,IAAI,IAAI,YAAY;EAE9E;EAAQ,YADT,OAAO,IAAI,eAAe,WAAW,IAAI,aAAa;EACjC,UAAU;CAAM;AAC1D"}
@@ -1,5 +1,5 @@
1
- import { t as state } from "./state-CfEVoqBM.js";
2
- import { T as githubHeaders, g as HTTPError, v as GITHUB_API_BASE_URL } from "./token-CTf5jCmP.js";
1
+ import { t as state } from "./state-CiwCLVDZ.js";
2
+ import { T as githubHeaders, g as HTTPError, v as GITHUB_API_BASE_URL } from "./token-CA2s70qj.js";
3
3
  import { r as fetchWithTransientRetry } from "./upstream-retry-i1k1Xai2.js";
4
4
  //#region src/services/github/get-copilot-usage.ts
5
5
  const getCopilotUsage = async () => {
@@ -10,4 +10,4 @@ const getCopilotUsage = async () => {
10
10
  //#endregion
11
11
  export { getCopilotUsage as t };
12
12
 
13
- //# sourceMappingURL=get-copilot-usage-0_S8pRWJ.js.map
13
+ //# sourceMappingURL=get-copilot-usage-P9chc-X2.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"get-copilot-usage-0_S8pRWJ.js","names":[],"sources":["../src/services/github/get-copilot-usage.ts"],"sourcesContent":["import { GITHUB_API_BASE_URL, githubHeaders } from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { state } from \"~/lib/state\"\nimport { fetchWithTransientRetry } from \"~/lib/upstream-retry\"\n\nexport const getCopilotUsage = async (): Promise<CopilotUsageResponse> => {\n // GitHub PAT GET — retry transient 429/5xx/network; a 401 (bad PAT) fails\n // fast (not retried by the helper).\n const response = await fetchWithTransientRetry(\n () =>\n fetch(`${GITHUB_API_BASE_URL}/copilot_internal/user`, {\n headers: githubHeaders(state),\n }),\n { label: \"/copilot_internal/user\" },\n )\n\n if (!response.ok) {\n throw new HTTPError(\"Failed to get Copilot usage\", response)\n }\n\n return (await response.json()) as CopilotUsageResponse\n}\n\nexport interface QuotaDetail {\n entitlement: number\n overage_count: number\n overage_permitted: boolean\n percent_remaining: number\n quota_id: string\n quota_remaining: number\n remaining: number\n unlimited: boolean\n}\n\ninterface QuotaSnapshots {\n chat: QuotaDetail\n completions: QuotaDetail\n premium_interactions: QuotaDetail\n}\n\ninterface CopilotUsageResponse {\n access_type_sku: string\n analytics_tracking_id: string\n assigned_date: string\n can_signup_for_limited: boolean\n chat_enabled: boolean\n copilot_plan: string\n organization_login_list: Array<unknown>\n organization_list: Array<unknown>\n quota_reset_date: string\n quota_snapshots: QuotaSnapshots\n}\n"],"mappings":";;;;AAKA,MAAa,kBAAkB,YAA2C;CAGxE,MAAM,WAAW,MAAM,8BAEnB,MAAM,GAAG,oBAAoB,yBAAyB,EACpD,SAAS,cAAc,KAAK,EAC9B,CAAC,GACH,EAAE,OAAO,yBAAyB,CACpC;CAEA,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,UAAU,+BAA+B,QAAQ;CAG7D,OAAQ,MAAM,SAAS,KAAK;AAC9B"}
1
+ {"version":3,"file":"get-copilot-usage-P9chc-X2.js","names":[],"sources":["../src/services/github/get-copilot-usage.ts"],"sourcesContent":["import { GITHUB_API_BASE_URL, githubHeaders } from \"~/lib/api-config\"\nimport { HTTPError } from \"~/lib/error\"\nimport { state } from \"~/lib/state\"\nimport { fetchWithTransientRetry } from \"~/lib/upstream-retry\"\n\nexport const getCopilotUsage = async (): Promise<CopilotUsageResponse> => {\n // GitHub PAT GET — retry transient 429/5xx/network; a 401 (bad PAT) fails\n // fast (not retried by the helper).\n const response = await fetchWithTransientRetry(\n () =>\n fetch(`${GITHUB_API_BASE_URL}/copilot_internal/user`, {\n headers: githubHeaders(state),\n }),\n { label: \"/copilot_internal/user\" },\n )\n\n if (!response.ok) {\n throw new HTTPError(\"Failed to get Copilot usage\", response)\n }\n\n return (await response.json()) as CopilotUsageResponse\n}\n\nexport interface QuotaDetail {\n entitlement: number\n overage_count: number\n overage_permitted: boolean\n percent_remaining: number\n quota_id: string\n quota_remaining: number\n remaining: number\n unlimited: boolean\n}\n\ninterface QuotaSnapshots {\n chat: QuotaDetail\n completions: QuotaDetail\n premium_interactions: QuotaDetail\n}\n\ninterface CopilotUsageResponse {\n access_type_sku: string\n analytics_tracking_id: string\n assigned_date: string\n can_signup_for_limited: boolean\n chat_enabled: boolean\n copilot_plan: string\n organization_login_list: Array<unknown>\n organization_list: Array<unknown>\n quota_reset_date: string\n quota_snapshots: QuotaSnapshots\n}\n"],"mappings":";;;;AAKA,MAAa,kBAAkB,YAA2C;CAGxE,MAAM,WAAW,MAAM,8BAEnB,MAAM,GAAG,oBAAoB,yBAAyB,EACpD,SAAS,cAAc,KAAK,EAC9B,CAAC,GACH,EAAE,OAAO,yBAAyB,CACpC;CAEA,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,UAAU,+BAA+B,QAAQ;CAG7D,OAAQ,MAAM,SAAS,KAAK;AAC9B"}
package/dist/hooks.mjs CHANGED
@@ -11093,6 +11093,8 @@ var init_state = __esmMin((() => {
11093
11093
  kustoEnabled: false,
11094
11094
  kustoCluster: null,
11095
11095
  kustoDatabase: null,
11096
+ cloudAgentEnabled: false,
11097
+ cloudAgentEnvironment: "prod",
11096
11098
  humanlikeForce: "auto",
11097
11099
  sessionId: randomUUID(),
11098
11100
  machineId: randomBytes(32).toString("hex"),
package/dist/hooks.sha256 CHANGED
@@ -1 +1 @@
1
- 31e51b4d93d3a9d683c1aae6cb05b20cd059160cbcbe73b6546d0292a6382f25
1
+ acd1e544b8a61e54f091bfc6e439e0a37eb0f8295fdbcdd691830663513aeb06
@@ -1,7 +1,7 @@
1
- import { A as validateWorkspace, C as provisionColbert, a as semanticBackend, b as validateIndexIntegrity, c as serviceFreshness, g as freshnessVerdict, h as completedIndexOnDisk, i as selectServerVariant, l as stopServiceServer, m as colbertProjectDir, n as populateWorkspace, p as waitForInit, s as serviceBackendProvisionable, t as ensureServerForeground, u as kickBackgroundInit, v as indexDirSignature, w as provisionNextPlaidServer, y as readColbertMeta } from "./service-backend-DV1u5x0Q.js";
2
- import { t as PATHS } from "./paths-xTSEAWfN.js";
1
+ import { A as validateWorkspace, C as provisionColbert, a as semanticBackend, b as validateIndexIntegrity, c as serviceFreshness, g as freshnessVerdict, h as completedIndexOnDisk, i as selectServerVariant, l as stopServiceServer, m as colbertProjectDir, n as populateWorkspace, p as waitForInit, s as serviceBackendProvisionable, t as ensureServerForeground, u as kickBackgroundInit, v as indexDirSignature, w as provisionNextPlaidServer, y as readColbertMeta } from "./service-backend-DHyd9vjW.js";
2
+ import { t as PATHS } from "./paths-BSI_EtDT.js";
3
3
  import { a as parseBoolEnv } from "./exec-Bf8g_bIR.js";
4
- import { r as registerColbertExitHandlers } from "./lifecycle-BJ83L0tz.js";
4
+ import { r as registerColbertExitHandlers } from "./lifecycle-C6cxM_Nk.js";
5
5
  import { defineCommand } from "citty";
6
6
  import consola from "consola";
7
7
  import * as os$1 from "node:os";
@@ -327,4 +327,4 @@ async function runColbertIndex(workspace, deadlineMs, timeoutMin) {
327
327
  //#endregion
328
328
  export { indexCmd };
329
329
 
330
- //# sourceMappingURL=index-cmd-CJXUOH4q.js.map
330
+ //# sourceMappingURL=index-cmd-BkfYr9FH.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index-cmd-CJXUOH4q.js","names":["os"],"sources":["../src/index-cmd.ts"],"sourcesContent":["/**\n * `github-router index` — build the semantic code-search index in the\n * foreground, without starting the proxy (`start`/`claude`/`codex`).\n *\n * Phase 4a: drives the CURRENT colbert backend (foreground `init` with\n * progress). Phase 5: `auto` (default) prefers the persistent service\n * backend — foreground all-core encode with CUDA when a GPU is visible —\n * with TRUE DELTA indexing (only changed files are re-embedded); falls\n * back to colbert when the service is not actionable. `--backend` forces\n * `service` or `colbert`. The explicit invocation IS the opt-in — `--search` is not\n * required — but `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` still hard-disables\n * (building an index that can never be served is pointless).\n *\n * Exit codes: 0 = fresh or successfully built; 1 = provision/build\n * failure; 2 = usage error (bad workspace, hard-disabled).\n */\n\nimport { defineCommand } from \"citty\";\nimport consola from \"consola\";\nimport * as os from \"node:os\";\nimport process from \"node:process\";\n\nimport { validateWorkspace } from \"~/lib/code-search\";\nimport {\n colbertProjectDir,\n completedIndexOnDisk,\n freshnessVerdict,\n indexDirSignature,\n readColbertMeta,\n validateIndexIntegrity,\n} from \"~/lib/colbert/index-store\";\nimport { registerColbertExitHandlers } from \"~/lib/colbert/lifecycle\";\nimport { provisionColbert, provisionNextPlaidServer } from \"~/lib/colbert/provision\";\nimport { kickBackgroundInit, waitForInit } from \"~/lib/colbert/runner\";\nimport {\n ensureServerForeground,\n populateWorkspace,\n selectServerVariant,\n semanticBackend,\n serviceBackendProvisionable,\n serviceFreshness,\n stopServiceServer,\n} from \"~/lib/colbert/service-backend\";\nimport { PATHS } from \"~/lib/paths\";\nimport { parseBoolEnv } from \"~/lib/exec\";\n\nconst POLL_MS = 10_000;\n\nfunction cpuCount(): number {\n try {\n const n = os.cpus().length;\n return Number.isSafeInteger(n) && n > 0 ? n : 4;\n } catch {\n return 4;\n }\n}\n\ninterface IndexStatus {\n workspace: string;\n verdict: string;\n indexOnDisk: boolean;\n shards?: number;\n embeddings?: number;\n integrity?: string;\n head?: string;\n dirty?: boolean;\n lastIndexedAt?: string;\n}\n\nasync function collectStatus(workspace: string): Promise<IndexStatus> {\n const { verdict, head, dirty } = await freshnessVerdict(workspace);\n const onDisk = await completedIndexOnDisk(workspace);\n const status: IndexStatus = {\n workspace,\n verdict,\n indexOnDisk: onDisk,\n };\n const projectDir = await colbertProjectDir(workspace);\n if (projectDir) {\n const integrity = validateIndexIntegrity(`${projectDir}/index`);\n if (integrity.verdict === \"coherent\") {\n status.shards = integrity.shardCount;\n status.embeddings = integrity.embeddingCount;\n } else {\n status.integrity = integrity.verdict;\n }\n }\n const meta = await readColbertMeta(workspace);\n if (meta?.lastIndexedAt) status.lastIndexedAt = meta.lastIndexedAt;\n if (head !== undefined) status.head = head.slice(0, 12);\n if (dirty !== undefined) status.dirty = dirty;\n return status;\n}\n\nfunction printStatus(s: IndexStatus): void {\n consola.info(`workspace: ${s.workspace}`);\n consola.info(`verdict: ${s.verdict}`);\n consola.info(`index: ${s.indexOnDisk ? \"present\" : \"absent\"}`);\n if (s.shards !== undefined) {\n consola.info(`shards: ${s.shards} (${s.embeddings ?? 0} embeddings)`);\n }\n if (s.integrity && s.integrity !== \"not-built\") {\n consola.info(`integrity: ${s.integrity}`);\n }\n if (s.head !== undefined)\n consola.info(`head: ${s.head}${s.dirty ? \" (dirty)\" : \"\"}`);\n if (s.lastIndexedAt) consola.info(`indexed: ${s.lastIndexedAt}`);\n}\n\ninterface IndexServiceStatus {\n workspace: string;\n backend: string;\n verdict: string;\n indexedAt?: string;\n docCount?: number;\n head?: string;\n dirty?: boolean;\n}\n\nasync function collectServiceStatus(workspace: string): Promise<IndexServiceStatus> {\n const { verdict, meta, head, dirty } = await serviceFreshness(workspace);\n const status: IndexServiceStatus = {\n workspace,\n backend: \"service\",\n verdict,\n };\n if (meta?.indexedAt) status.indexedAt = meta.indexedAt;\n if (meta?.docCount !== undefined) status.docCount = meta.docCount;\n if (head !== undefined) status.head = head.slice(0, 12);\n if (dirty !== undefined) status.dirty = dirty;\n return status;\n}\n\nfunction printServiceStatus(s: IndexServiceStatus): void {\n consola.info(`workspace: ${s.workspace}`);\n consola.info(`backend: ${s.backend}`);\n consola.info(`verdict: ${s.verdict}`);\n if (s.docCount !== undefined) consola.info(`documents: ${s.docCount}`);\n if (s.head !== undefined)\n consola.info(`head: ${s.head}${s.dirty ? \" (dirty)\" : \"\"}`);\n if (s.indexedAt) consola.info(`indexed: ${s.indexedAt}`);\n}\n\ntype IndexBackend = \"service\" | \"colgrep\";\n\nfunction resolveIndexBackend(requested: unknown): { backend: IndexBackend; explicit: boolean } | { error: string } {\n const raw = typeof requested === \"string\" && requested.length > 0 ? requested.toLowerCase() : \"auto\";\n if (raw !== \"auto\" && raw !== \"service\" && raw !== \"colgrep\") {\n return { error: `index: --backend must be auto, service, or colgrep (got ${String(requested)})` };\n }\n // Explicit opt-in (flag or env) always means service.\n if (raw === \"service\" || (raw === \"auto\" && semanticBackend() === \"service\")) {\n return { backend: \"service\", explicit: true };\n }\n if (raw === \"colgrep\") return { backend: \"colgrep\", explicit: false };\n // Auto: service when provisionable (binary on disk or promoted\n // download + model present), else the colgrep fallback.\n return serviceBackendProvisionable()\n ? { backend: \"service\", explicit: false }\n : { backend: \"colgrep\", explicit: false };\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const t = setTimeout(resolve, ms);\n t.unref?.();\n });\n}\n\nexport const indexCmd = defineCommand({\n meta: {\n name: \"index\",\n description:\n \"Build the semantic code-search index for a workspace in the foreground (no proxy needed)\",\n },\n args: {\n workspace: {\n alias: \"w\",\n type: \"string\",\n description: \"Absolute path to the repo to index (default: cwd)\",\n },\n status: {\n type: \"boolean\",\n default: false,\n description: \"Print index status and exit (no build)\",\n },\n timeout: {\n type: \"string\",\n description: \"Max minutes to wait for the build (0 = none, default 0)\",\n },\n backend: {\n type: \"string\",\n description: \"Index backend: auto (service with CUDA/CPU autodetect, colgrep fallback), service, or colgrep (default auto)\",\n },\n full: {\n type: \"boolean\",\n default: false,\n description: \"Force a full rebuild, ignoring content hashes (service backend)\",\n },\n dryRun: {\n type: \"boolean\",\n default: false,\n description: \"Classify changed files without building (service backend)\",\n },\n },\n async run({ args }) {\n const rawWorkspace =\n typeof args.workspace === \"string\" && args.workspace.length > 0\n ? args.workspace\n : process.cwd();\n const ws = validateWorkspace(rawWorkspace);\n if (!ws.ok || !ws.canonical) {\n consola.error(`index: ${ws.error ?? \"workspace validation failed\"}`);\n process.exitCode = 2;\n return;\n }\n const workspace = ws.canonical;\n\n if (parseBoolEnv(process.env.GH_ROUTER_DISABLE_SEMANTIC_SEARCH) === true) {\n consola.error(\n \"index: semantic search is hard-disabled (GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1); nothing to build\",\n );\n process.exitCode = 2;\n return;\n }\n\n const backendSelection = resolveIndexBackend(args.backend);\n if (\"error\" in backendSelection) {\n consola.error(backendSelection.error);\n process.exitCode = 2;\n return;\n }\n const { backend, explicit: backendExplicit } = backendSelection;\n\n if (args.status === true) {\n if (backend === \"service\") {\n printServiceStatus(await collectServiceStatus(workspace));\n } else {\n printStatus(await collectStatus(workspace));\n }\n return;\n }\n\n const timeoutMin = args.timeout === undefined ? 0 : Number(args.timeout);\n if (\n args.timeout !== undefined &&\n !(Number.isFinite(timeoutMin) && timeoutMin >= 0)\n ) {\n consola.error(\n \"index: --timeout must be a non-negative number of minutes\",\n );\n process.exitCode = 2;\n return;\n }\n const deadlineMs =\n timeoutMin > 0\n ? Date.now() + timeoutMin * 60_000\n : Number.POSITIVE_INFINITY;\n\n // Foreground dedicated build: use all cores unless the operator capped\n // explicitly. Background auto-indexing stays at 25% (the colbert\n // default); an explicit `index` invocation expects speed.\n if (process.env.GH_ROUTER_COLBERT_PARALLEL === undefined) {\n process.env.GH_ROUTER_COLBERT_PARALLEL = String(cpuCount());\n consola.debug(\n `index: parallelism defaulted to ${cpuCount()} sessions (override with GH_ROUTER_COLBERT_PARALLEL)`,\n );\n }\n\n registerColbertExitHandlers();\n\n consola.info(\n `Provisioning semantic-search artifacts into ${PATHS.COLBERT_INDICES_DIR}…`,\n );\n try {\n const result = await provisionColbert();\n if (result.status !== \"ready\") {\n consola.error(\n `index: provision ${result.status}${result.reason ? ` (${result.reason})` : \"\"}`,\n );\n process.exitCode = 1;\n return;\n }\n } catch (err) {\n consola.error(\"index: provision threw:\", err);\n process.exitCode = 1;\n return;\n }\n\n // Auto resolves the backend AFTER provisioning (the model dir must\n // exist before provisionability can report actionable). An\n // explicit service request that cannot provision the server binary\n // fails closed; auto silently falls back to colgrep.\n if (backend === \"service\") {\n let variant: Awaited<ReturnType<typeof selectServerVariant>> | undefined;\n try {\n variant = await selectServerVariant();\n const server = await provisionNextPlaidServer(variant);\n if (server.path) {\n consola.info(`index: service backend ready (${variant}: ${server.path})`);\n } else if (backendExplicit) {\n consola.error(\n `index: service binary unavailable (${server.reason ?? \"unknown\"}) — retry with --backend=colgrep`,\n );\n process.exitCode = 1;\n return;\n } else {\n consola.warn(\n `index: service binary unavailable (${server.reason ?? \"unknown\"}) — falling back to colgrep`,\n );\n if (args.full === true || args.dryRun === true) {\n consola.warn(\n \"index: --full/--dry-run apply to the service backend only; ignored for colgrep\",\n );\n }\n\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n return;\n }\n } catch (err) {\n if (backendExplicit) {\n consola.error(\"index: service provision threw:\", err);\n process.exitCode = 1;\n return;\n }\n consola.warn(\"index: service provision skipped:\", err);\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n return;\n }\n // Foreground service build (all-core encode; CUDA when detected).\n if (variant === undefined) {\n consola.error(\"index: no service variant resolved\");\n process.exitCode = 1;\n return;\n }\n await runServiceIndex(workspace, {\n full: args.full === true,\n dryRun: args.dryRun === true,\n deadlineMs,\n timeoutMin,\n variant,\n });\n return;\n }\n\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n },\n});\n\nasync function runServiceIndex(\n workspace: string,\n opts: {\n full: boolean;\n dryRun: boolean;\n deadlineMs: number;\n timeoutMin: number;\n variant: string;\n },\n): Promise<void> {\n const startMs = Date.now();\n const signal =\n Number.isFinite(opts.deadlineMs) && opts.deadlineMs !== Number.POSITIVE_INFINITY\n ? AbortSignal.timeout(Math.max(1, opts.deadlineMs - Date.now()))\n : undefined;\n\n if (opts.dryRun) {\n const plan = await populateWorkspace(workspace, { dryRun: true }).catch((err) => {\n consola.error(\"index: dry-run failed:\", err);\n process.exitCode = 1;\n return null;\n });\n if (!plan) return;\n consola.info(\n `dry-run: ${plan.scanned} files scanned → ${plan.updatedFiles} to index, ${plan.removedFiles} to remove, ${plan.unchanged} unchanged`,\n );\n return;\n }\n\n const first = await serviceFreshness(workspace);\n if (first.verdict === \"fresh\" && !opts.full) {\n consola.success(\"index is already fresh — nothing to build\");\n printServiceStatus(await collectServiceStatus(workspace));\n return;\n }\n\n consola.info(\n `Building service index for ${workspace} (freshness: ${first.verdict}, variant: ${opts.variant})…`,\n );\n const server = await ensureServerForeground();\n if (!server) {\n consola.error(\n \"index: service server failed to start — retry with --backend=colgrep\",\n );\n process.exitCode = 1;\n return;\n }\n let lastLogMs = 0;\n try { const result = await populateWorkspace(workspace, {\n full: opts.full,\n foreground: true,\n ...(signal ? { signal } : {}),\n onProgress: (p) => {\n const now = Date.now();\n if (p.phase !== \"done\" && now - lastLogMs < POLL_MS) return;\n lastLogMs = now;\n if (p.phase === \"done\") return;\n consola.info(\n `… ${p.phase}: ${p.scanned}/${p.total} files` +\n (p.phase === \"encode\" || p.phase === \"extract\"\n ? ` (${p.updatedFiles} changed, ${p.units} units)`\n : \"\"),\n );\n },\n });\n const elapsedS = Math.round((Date.now() - startMs) / 1000);\n if (result.status === \"unchanged\") {\n consola.success(`index ready in ${elapsedS}s (no changes)`);\n } else {\n consola.success(\n `index ready in ${elapsedS}s (delta: ${result.unchanged} unchanged, ${result.updatedFiles} updated, ${result.removedFiles} removed, ${result.units} units)`,\n );\n }\n printServiceStatus(await collectServiceStatus(workspace));\n } catch (err) {\n if (signal?.aborted || Date.now() > opts.deadlineMs) {\n consola.error(\n `index: timed out after ${opts.timeoutMin}min — retry or raise --timeout`,\n );\n } else {\n consola.error(\"index: service build failed:\", err);\n }\n process.exitCode = 1;\n } finally {\n // The persistent server holds the event loop open — stop it or this\n // foreground command never exits (and orphans a server per run).\n await stopServiceServer();\n }\n}\n\nasync function runColbertIndex(\n workspace: string,\n deadlineMs: number,\n timeoutMin: number,\n): Promise<void> {\n const first = await freshnessVerdict(workspace);\n if (first.verdict === \"fresh\") {\n consola.success(\"index is already fresh — nothing to build\");\n printStatus(await collectStatus(workspace));\n return;\n }\n if (first.verdict === \"failed\") {\n consola.warn(\n \"index: last build failed; starting one bounded rebuild attempt\",\n );\n }\n\n consola.info(\n `Building semantic index for ${workspace} (freshness: ${first.verdict})…`,\n );\n kickBackgroundInit(workspace);\n const startMs = Date.now();\n\n for (;;) {\n if (Date.now() > deadlineMs) {\n consola.error(\n `index: timed out after ${timeoutMin}min — the background build continues; retry or raise --timeout`,\n );\n process.exitCode = 1;\n return;\n }\n // Wait for this process's tracked build; resolves immediately when\n // another proxy owns it, in which case the sleep below paces polling.\n await waitForInit(workspace).catch(() => {});\n const v = await freshnessVerdict(workspace);\n const elapsedS = Math.round((Date.now() - startMs) / 1000);\n if (v.verdict === \"fresh\") {\n consola.success(`index ready in ${elapsedS}s`);\n printStatus(await collectStatus(workspace));\n return;\n }\n if (\n v.verdict === \"failed\" ||\n v.verdict === \"crashed\" ||\n v.verdict === \"corrupt\"\n ) {\n consola.error(\n `index: build ended ${v.verdict} — lexical code search still works; see the proxy error log for the failure class`,\n );\n process.exitCode = 1;\n return;\n }\n // building | stale | absent: report progress, keep waiting. colgrep\n // is silent on pipes during encode, so disk growth is the signal.\n const sig = indexDirSignature(workspace);\n const progress =\n sig.kind === \"observed\" ? ` [${sig.signature}]` : \" [starting…]\";\n consola.info(\n `… ${elapsedS}s elapsed (freshness: ${v.verdict})${progress}`,\n );\n await sleep(POLL_MS);\n // Re-kick if nothing owns the build (crash between kick and track).\n kickBackgroundInit(workspace);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,UAAU;AAEhB,SAAS,WAAmB;CAC1B,IAAI;EACF,MAAM,IAAIA,KAAG,KAAK,CAAC,CAAC;EACpB,OAAO,OAAO,cAAc,CAAC,KAAK,IAAI,IAAI,IAAI;CAChD,QAAQ;EACN,OAAO;CACT;AACF;AAcA,eAAe,cAAc,WAAyC;CACpE,MAAM,EAAE,SAAS,MAAM,UAAU,MAAM,iBAAiB,SAAS;CAEjE,MAAM,SAAsB;EAC1B;EACA;EACA,aAAa,MAJM,qBAAqB,SAAS;CAKnD;CACA,MAAM,aAAa,MAAM,kBAAkB,SAAS;CACpD,IAAI,YAAY;EACd,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F;EACA,IACE,EAAE,YAAY,YACd,EAAE,YAAY,aACd,EAAE,YAAY,WACd;GACA,QAAQ,MACN,sBAAsB,EAAE,QAAQ,kFAClC;GACA,QAAQ,WAAW;GACnB;EACF;EAGA,MAAM,MAAM,kBAAkB,SAAS;EACvC,MAAM,WACJ,IAAI,SAAS,aAAa,KAAK,IAAI,UAAU,KAAK;EACpD,QAAQ,KACN,KAAK,SAAS,wBAAwB,EAAE,QAAQ,GAAG,UACrD;EACA,MAAM,MAAM,OAAO;EAEnB,mBAAmB,SAAS;CAC9B;AACF"}
1
+ {"version":3,"file":"index-cmd-BkfYr9FH.js","names":["os"],"sources":["../src/index-cmd.ts"],"sourcesContent":["/**\n * `github-router index` — build the semantic code-search index in the\n * foreground, without starting the proxy (`start`/`claude`/`codex`).\n *\n * Phase 4a: drives the CURRENT colbert backend (foreground `init` with\n * progress). Phase 5: `auto` (default) prefers the persistent service\n * backend — foreground all-core encode with CUDA when a GPU is visible —\n * with TRUE DELTA indexing (only changed files are re-embedded); falls\n * back to colbert when the service is not actionable. `--backend` forces\n * `service` or `colbert`. The explicit invocation IS the opt-in — `--search` is not\n * required — but `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` still hard-disables\n * (building an index that can never be served is pointless).\n *\n * Exit codes: 0 = fresh or successfully built; 1 = provision/build\n * failure; 2 = usage error (bad workspace, hard-disabled).\n */\n\nimport { defineCommand } from \"citty\";\nimport consola from \"consola\";\nimport * as os from \"node:os\";\nimport process from \"node:process\";\n\nimport { validateWorkspace } from \"~/lib/code-search\";\nimport {\n colbertProjectDir,\n completedIndexOnDisk,\n freshnessVerdict,\n indexDirSignature,\n readColbertMeta,\n validateIndexIntegrity,\n} from \"~/lib/colbert/index-store\";\nimport { registerColbertExitHandlers } from \"~/lib/colbert/lifecycle\";\nimport { provisionColbert, provisionNextPlaidServer } from \"~/lib/colbert/provision\";\nimport { kickBackgroundInit, waitForInit } from \"~/lib/colbert/runner\";\nimport {\n ensureServerForeground,\n populateWorkspace,\n selectServerVariant,\n semanticBackend,\n serviceBackendProvisionable,\n serviceFreshness,\n stopServiceServer,\n} from \"~/lib/colbert/service-backend\";\nimport { PATHS } from \"~/lib/paths\";\nimport { parseBoolEnv } from \"~/lib/exec\";\n\nconst POLL_MS = 10_000;\n\nfunction cpuCount(): number {\n try {\n const n = os.cpus().length;\n return Number.isSafeInteger(n) && n > 0 ? n : 4;\n } catch {\n return 4;\n }\n}\n\ninterface IndexStatus {\n workspace: string;\n verdict: string;\n indexOnDisk: boolean;\n shards?: number;\n embeddings?: number;\n integrity?: string;\n head?: string;\n dirty?: boolean;\n lastIndexedAt?: string;\n}\n\nasync function collectStatus(workspace: string): Promise<IndexStatus> {\n const { verdict, head, dirty } = await freshnessVerdict(workspace);\n const onDisk = await completedIndexOnDisk(workspace);\n const status: IndexStatus = {\n workspace,\n verdict,\n indexOnDisk: onDisk,\n };\n const projectDir = await colbertProjectDir(workspace);\n if (projectDir) {\n const integrity = validateIndexIntegrity(`${projectDir}/index`);\n if (integrity.verdict === \"coherent\") {\n status.shards = integrity.shardCount;\n status.embeddings = integrity.embeddingCount;\n } else {\n status.integrity = integrity.verdict;\n }\n }\n const meta = await readColbertMeta(workspace);\n if (meta?.lastIndexedAt) status.lastIndexedAt = meta.lastIndexedAt;\n if (head !== undefined) status.head = head.slice(0, 12);\n if (dirty !== undefined) status.dirty = dirty;\n return status;\n}\n\nfunction printStatus(s: IndexStatus): void {\n consola.info(`workspace: ${s.workspace}`);\n consola.info(`verdict: ${s.verdict}`);\n consola.info(`index: ${s.indexOnDisk ? \"present\" : \"absent\"}`);\n if (s.shards !== undefined) {\n consola.info(`shards: ${s.shards} (${s.embeddings ?? 0} embeddings)`);\n }\n if (s.integrity && s.integrity !== \"not-built\") {\n consola.info(`integrity: ${s.integrity}`);\n }\n if (s.head !== undefined)\n consola.info(`head: ${s.head}${s.dirty ? \" (dirty)\" : \"\"}`);\n if (s.lastIndexedAt) consola.info(`indexed: ${s.lastIndexedAt}`);\n}\n\ninterface IndexServiceStatus {\n workspace: string;\n backend: string;\n verdict: string;\n indexedAt?: string;\n docCount?: number;\n head?: string;\n dirty?: boolean;\n}\n\nasync function collectServiceStatus(workspace: string): Promise<IndexServiceStatus> {\n const { verdict, meta, head, dirty } = await serviceFreshness(workspace);\n const status: IndexServiceStatus = {\n workspace,\n backend: \"service\",\n verdict,\n };\n if (meta?.indexedAt) status.indexedAt = meta.indexedAt;\n if (meta?.docCount !== undefined) status.docCount = meta.docCount;\n if (head !== undefined) status.head = head.slice(0, 12);\n if (dirty !== undefined) status.dirty = dirty;\n return status;\n}\n\nfunction printServiceStatus(s: IndexServiceStatus): void {\n consola.info(`workspace: ${s.workspace}`);\n consola.info(`backend: ${s.backend}`);\n consola.info(`verdict: ${s.verdict}`);\n if (s.docCount !== undefined) consola.info(`documents: ${s.docCount}`);\n if (s.head !== undefined)\n consola.info(`head: ${s.head}${s.dirty ? \" (dirty)\" : \"\"}`);\n if (s.indexedAt) consola.info(`indexed: ${s.indexedAt}`);\n}\n\ntype IndexBackend = \"service\" | \"colgrep\";\n\nfunction resolveIndexBackend(requested: unknown): { backend: IndexBackend; explicit: boolean } | { error: string } {\n const raw = typeof requested === \"string\" && requested.length > 0 ? requested.toLowerCase() : \"auto\";\n if (raw !== \"auto\" && raw !== \"service\" && raw !== \"colgrep\") {\n return { error: `index: --backend must be auto, service, or colgrep (got ${String(requested)})` };\n }\n // Explicit opt-in (flag or env) always means service.\n if (raw === \"service\" || (raw === \"auto\" && semanticBackend() === \"service\")) {\n return { backend: \"service\", explicit: true };\n }\n if (raw === \"colgrep\") return { backend: \"colgrep\", explicit: false };\n // Auto: service when provisionable (binary on disk or promoted\n // download + model present), else the colgrep fallback.\n return serviceBackendProvisionable()\n ? { backend: \"service\", explicit: false }\n : { backend: \"colgrep\", explicit: false };\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const t = setTimeout(resolve, ms);\n t.unref?.();\n });\n}\n\nexport const indexCmd = defineCommand({\n meta: {\n name: \"index\",\n description:\n \"Build the semantic code-search index for a workspace in the foreground (no proxy needed)\",\n },\n args: {\n workspace: {\n alias: \"w\",\n type: \"string\",\n description: \"Absolute path to the repo to index (default: cwd)\",\n },\n status: {\n type: \"boolean\",\n default: false,\n description: \"Print index status and exit (no build)\",\n },\n timeout: {\n type: \"string\",\n description: \"Max minutes to wait for the build (0 = none, default 0)\",\n },\n backend: {\n type: \"string\",\n description: \"Index backend: auto (service with CUDA/CPU autodetect, colgrep fallback), service, or colgrep (default auto)\",\n },\n full: {\n type: \"boolean\",\n default: false,\n description: \"Force a full rebuild, ignoring content hashes (service backend)\",\n },\n dryRun: {\n type: \"boolean\",\n default: false,\n description: \"Classify changed files without building (service backend)\",\n },\n },\n async run({ args }) {\n const rawWorkspace =\n typeof args.workspace === \"string\" && args.workspace.length > 0\n ? args.workspace\n : process.cwd();\n const ws = validateWorkspace(rawWorkspace);\n if (!ws.ok || !ws.canonical) {\n consola.error(`index: ${ws.error ?? \"workspace validation failed\"}`);\n process.exitCode = 2;\n return;\n }\n const workspace = ws.canonical;\n\n if (parseBoolEnv(process.env.GH_ROUTER_DISABLE_SEMANTIC_SEARCH) === true) {\n consola.error(\n \"index: semantic search is hard-disabled (GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1); nothing to build\",\n );\n process.exitCode = 2;\n return;\n }\n\n const backendSelection = resolveIndexBackend(args.backend);\n if (\"error\" in backendSelection) {\n consola.error(backendSelection.error);\n process.exitCode = 2;\n return;\n }\n const { backend, explicit: backendExplicit } = backendSelection;\n\n if (args.status === true) {\n if (backend === \"service\") {\n printServiceStatus(await collectServiceStatus(workspace));\n } else {\n printStatus(await collectStatus(workspace));\n }\n return;\n }\n\n const timeoutMin = args.timeout === undefined ? 0 : Number(args.timeout);\n if (\n args.timeout !== undefined &&\n !(Number.isFinite(timeoutMin) && timeoutMin >= 0)\n ) {\n consola.error(\n \"index: --timeout must be a non-negative number of minutes\",\n );\n process.exitCode = 2;\n return;\n }\n const deadlineMs =\n timeoutMin > 0\n ? Date.now() + timeoutMin * 60_000\n : Number.POSITIVE_INFINITY;\n\n // Foreground dedicated build: use all cores unless the operator capped\n // explicitly. Background auto-indexing stays at 25% (the colbert\n // default); an explicit `index` invocation expects speed.\n if (process.env.GH_ROUTER_COLBERT_PARALLEL === undefined) {\n process.env.GH_ROUTER_COLBERT_PARALLEL = String(cpuCount());\n consola.debug(\n `index: parallelism defaulted to ${cpuCount()} sessions (override with GH_ROUTER_COLBERT_PARALLEL)`,\n );\n }\n\n registerColbertExitHandlers();\n\n consola.info(\n `Provisioning semantic-search artifacts into ${PATHS.COLBERT_INDICES_DIR}…`,\n );\n try {\n const result = await provisionColbert();\n if (result.status !== \"ready\") {\n consola.error(\n `index: provision ${result.status}${result.reason ? ` (${result.reason})` : \"\"}`,\n );\n process.exitCode = 1;\n return;\n }\n } catch (err) {\n consola.error(\"index: provision threw:\", err);\n process.exitCode = 1;\n return;\n }\n\n // Auto resolves the backend AFTER provisioning (the model dir must\n // exist before provisionability can report actionable). An\n // explicit service request that cannot provision the server binary\n // fails closed; auto silently falls back to colgrep.\n if (backend === \"service\") {\n let variant: Awaited<ReturnType<typeof selectServerVariant>> | undefined;\n try {\n variant = await selectServerVariant();\n const server = await provisionNextPlaidServer(variant);\n if (server.path) {\n consola.info(`index: service backend ready (${variant}: ${server.path})`);\n } else if (backendExplicit) {\n consola.error(\n `index: service binary unavailable (${server.reason ?? \"unknown\"}) — retry with --backend=colgrep`,\n );\n process.exitCode = 1;\n return;\n } else {\n consola.warn(\n `index: service binary unavailable (${server.reason ?? \"unknown\"}) — falling back to colgrep`,\n );\n if (args.full === true || args.dryRun === true) {\n consola.warn(\n \"index: --full/--dry-run apply to the service backend only; ignored for colgrep\",\n );\n }\n\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n return;\n }\n } catch (err) {\n if (backendExplicit) {\n consola.error(\"index: service provision threw:\", err);\n process.exitCode = 1;\n return;\n }\n consola.warn(\"index: service provision skipped:\", err);\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n return;\n }\n // Foreground service build (all-core encode; CUDA when detected).\n if (variant === undefined) {\n consola.error(\"index: no service variant resolved\");\n process.exitCode = 1;\n return;\n }\n await runServiceIndex(workspace, {\n full: args.full === true,\n dryRun: args.dryRun === true,\n deadlineMs,\n timeoutMin,\n variant,\n });\n return;\n }\n\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n },\n});\n\nasync function runServiceIndex(\n workspace: string,\n opts: {\n full: boolean;\n dryRun: boolean;\n deadlineMs: number;\n timeoutMin: number;\n variant: string;\n },\n): Promise<void> {\n const startMs = Date.now();\n const signal =\n Number.isFinite(opts.deadlineMs) && opts.deadlineMs !== Number.POSITIVE_INFINITY\n ? AbortSignal.timeout(Math.max(1, opts.deadlineMs - Date.now()))\n : undefined;\n\n if (opts.dryRun) {\n const plan = await populateWorkspace(workspace, { dryRun: true }).catch((err) => {\n consola.error(\"index: dry-run failed:\", err);\n process.exitCode = 1;\n return null;\n });\n if (!plan) return;\n consola.info(\n `dry-run: ${plan.scanned} files scanned → ${plan.updatedFiles} to index, ${plan.removedFiles} to remove, ${plan.unchanged} unchanged`,\n );\n return;\n }\n\n const first = await serviceFreshness(workspace);\n if (first.verdict === \"fresh\" && !opts.full) {\n consola.success(\"index is already fresh — nothing to build\");\n printServiceStatus(await collectServiceStatus(workspace));\n return;\n }\n\n consola.info(\n `Building service index for ${workspace} (freshness: ${first.verdict}, variant: ${opts.variant})…`,\n );\n const server = await ensureServerForeground();\n if (!server) {\n consola.error(\n \"index: service server failed to start — retry with --backend=colgrep\",\n );\n process.exitCode = 1;\n return;\n }\n let lastLogMs = 0;\n try { const result = await populateWorkspace(workspace, {\n full: opts.full,\n foreground: true,\n ...(signal ? { signal } : {}),\n onProgress: (p) => {\n const now = Date.now();\n if (p.phase !== \"done\" && now - lastLogMs < POLL_MS) return;\n lastLogMs = now;\n if (p.phase === \"done\") return;\n consola.info(\n `… ${p.phase}: ${p.scanned}/${p.total} files` +\n (p.phase === \"encode\" || p.phase === \"extract\"\n ? ` (${p.updatedFiles} changed, ${p.units} units)`\n : \"\"),\n );\n },\n });\n const elapsedS = Math.round((Date.now() - startMs) / 1000);\n if (result.status === \"unchanged\") {\n consola.success(`index ready in ${elapsedS}s (no changes)`);\n } else {\n consola.success(\n `index ready in ${elapsedS}s (delta: ${result.unchanged} unchanged, ${result.updatedFiles} updated, ${result.removedFiles} removed, ${result.units} units)`,\n );\n }\n printServiceStatus(await collectServiceStatus(workspace));\n } catch (err) {\n if (signal?.aborted || Date.now() > opts.deadlineMs) {\n consola.error(\n `index: timed out after ${opts.timeoutMin}min — retry or raise --timeout`,\n );\n } else {\n consola.error(\"index: service build failed:\", err);\n }\n process.exitCode = 1;\n } finally {\n // The persistent server holds the event loop open — stop it or this\n // foreground command never exits (and orphans a server per run).\n await stopServiceServer();\n }\n}\n\nasync function runColbertIndex(\n workspace: string,\n deadlineMs: number,\n timeoutMin: number,\n): Promise<void> {\n const first = await freshnessVerdict(workspace);\n if (first.verdict === \"fresh\") {\n consola.success(\"index is already fresh — nothing to build\");\n printStatus(await collectStatus(workspace));\n return;\n }\n if (first.verdict === \"failed\") {\n consola.warn(\n \"index: last build failed; starting one bounded rebuild attempt\",\n );\n }\n\n consola.info(\n `Building semantic index for ${workspace} (freshness: ${first.verdict})…`,\n );\n kickBackgroundInit(workspace);\n const startMs = Date.now();\n\n for (;;) {\n if (Date.now() > deadlineMs) {\n consola.error(\n `index: timed out after ${timeoutMin}min — the background build continues; retry or raise --timeout`,\n );\n process.exitCode = 1;\n return;\n }\n // Wait for this process's tracked build; resolves immediately when\n // another proxy owns it, in which case the sleep below paces polling.\n await waitForInit(workspace).catch(() => {});\n const v = await freshnessVerdict(workspace);\n const elapsedS = Math.round((Date.now() - startMs) / 1000);\n if (v.verdict === \"fresh\") {\n consola.success(`index ready in ${elapsedS}s`);\n printStatus(await collectStatus(workspace));\n return;\n }\n if (\n v.verdict === \"failed\" ||\n v.verdict === \"crashed\" ||\n v.verdict === \"corrupt\"\n ) {\n consola.error(\n `index: build ended ${v.verdict} — lexical code search still works; see the proxy error log for the failure class`,\n );\n process.exitCode = 1;\n return;\n }\n // building | stale | absent: report progress, keep waiting. colgrep\n // is silent on pipes during encode, so disk growth is the signal.\n const sig = indexDirSignature(workspace);\n const progress =\n sig.kind === \"observed\" ? ` [${sig.signature}]` : \" [starting…]\";\n consola.info(\n `… ${elapsedS}s elapsed (freshness: ${v.verdict})${progress}`,\n );\n await sleep(POLL_MS);\n // Re-kick if nothing owns the build (crash between kick and track).\n kickBackgroundInit(workspace);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,UAAU;AAEhB,SAAS,WAAmB;CAC1B,IAAI;EACF,MAAM,IAAIA,KAAG,KAAK,CAAC,CAAC;EACpB,OAAO,OAAO,cAAc,CAAC,KAAK,IAAI,IAAI,IAAI;CAChD,QAAQ;EACN,OAAO;CACT;AACF;AAcA,eAAe,cAAc,WAAyC;CACpE,MAAM,EAAE,SAAS,MAAM,UAAU,MAAM,iBAAiB,SAAS;CAEjE,MAAM,SAAsB;EAC1B;EACA;EACA,aAAa,MAJM,qBAAqB,SAAS;CAKnD;CACA,MAAM,aAAa,MAAM,kBAAkB,SAAS;CACpD,IAAI,YAAY;EACd,MAAM,YAAY,uBAAuB,GAAG,WAAW,OAAO;EAC9D,IAAI,UAAU,YAAY,YAAY;GACpC,OAAO,SAAS,UAAU;GAC1B,OAAO,aAAa,UAAU;EAChC,OACE,OAAO,YAAY,UAAU;CAEjC;CACA,MAAM,OAAO,MAAM,gBAAgB,SAAS;CAC5C,IAAI,MAAM,eAAe,OAAO,gBAAgB,KAAK;CACrD,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,KAAK,MAAM,GAAG,EAAE;CACtD,IAAI,UAAU,KAAA,GAAW,OAAO,QAAQ;CACxC,OAAO;AACT;AAEA,SAAS,YAAY,GAAsB;CACzC,QAAQ,KAAK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./exec-Bf8g_bIR.js";
2
- import { c as readAicSnapshotFile, s as formatAicStatus } from "./aic-ledger-BdvCgRmx.js";
3
- import { t as discountedUsdForSnapshot } from "./copilot-discount-kpOLluHm.js";
2
+ import { c as readAicSnapshotFile, s as formatAicStatus } from "./aic-ledger-BuFrsGur.js";
3
+ import { t as discountedUsdForSnapshot } from "./copilot-discount-Bsmv_3OX.js";
4
4
  import { defineCommand } from "citty";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { spawnSync } from "node:child_process";
@@ -481,4 +481,4 @@ const internalAicStatus = defineCommand({
481
481
  //#endregion
482
482
  export { internalAicStatus };
483
483
 
484
- //# sourceMappingURL=internal-aic-status-wYPsCG4r.js.map
484
+ //# sourceMappingURL=internal-aic-status-C6L4-ncP.js.map