github-router 0.3.330 → 0.3.332

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 (128) hide show
  1. package/README.md +4 -2
  2. package/dist/{aic-ledger-CsBx1crE.js → aic-ledger-D4fmThbS.js} +2 -2
  3. package/dist/{aic-ledger-CsBx1crE.js.map → aic-ledger-D4fmThbS.js.map} +1 -1
  4. package/dist/{attribution-settings-DepziZU8.js → attribution-settings-BeO1w_DL.js} +62 -51
  5. package/dist/attribution-settings-BeO1w_DL.js.map +1 -0
  6. package/dist/{auth-xgFZGZbf.js → auth-DjKEIiqG.js} +4 -4
  7. package/dist/{auth-xgFZGZbf.js.map → auth-DjKEIiqG.js.map} +1 -1
  8. package/dist/bluebird-client-DpYl1YmJ.js +1163 -0
  9. package/dist/bluebird-client-DpYl1YmJ.js.map +1 -0
  10. package/dist/bluebird-client-bn9Yv6Cb.js +2 -0
  11. package/dist/browser-ext/manifest.json +1 -1
  12. package/dist/{check-usage-vUDk6oV7.js → check-usage-B7UrDwD8.js} +4 -4
  13. package/dist/{check-usage-vUDk6oV7.js.map → check-usage-B7UrDwD8.js.map} +1 -1
  14. package/dist/{claude-Dw4V8o8l.js → claude-BQQPdXLb.js} +37 -29
  15. package/dist/claude-BQQPdXLb.js.map +1 -0
  16. package/dist/{codex-CXOpv4WP.js → codex-fW-hbxtT.js} +12 -8
  17. package/dist/codex-fW-hbxtT.js.map +1 -0
  18. package/dist/{copilot-discount-0lG67i9O.js → copilot-discount-BcUa3f-k.js} +2 -2
  19. package/dist/{copilot-discount-0lG67i9O.js.map → copilot-discount-BcUa3f-k.js.map} +1 -1
  20. package/dist/{debug-a737qcCC.js → debug-CigFsS-h.js} +2 -2
  21. package/dist/{debug-a737qcCC.js.map → debug-CigFsS-h.js.map} +1 -1
  22. package/dist/engine-E4WJGSeg.js +2 -0
  23. package/dist/{exec-COUT4QsS.js → exec-MCU1H-KZ.js} +63 -13
  24. package/dist/exec-MCU1H-KZ.js.map +1 -0
  25. package/dist/{gate-discovery-BGqS7R2g.js → gate-discovery-DbwVeERm.js} +6 -6
  26. package/dist/{gate-discovery-BGqS7R2g.js.map → gate-discovery-DbwVeERm.js.map} +1 -1
  27. package/dist/{get-copilot-usage-VKU2IvuE.js → get-copilot-usage-CGaV01dC.js} +4 -3
  28. package/dist/{get-copilot-usage-VKU2IvuE.js.map → get-copilot-usage-CGaV01dC.js.map} +1 -1
  29. package/dist/hooks.mjs +90 -27
  30. package/dist/hooks.sha256 +1 -1
  31. package/dist/index-cmd-DXYWgKS6.js +330 -0
  32. package/dist/index-cmd-DXYWgKS6.js.map +1 -0
  33. package/dist/{internal-aic-status-Cfl5HiAN.js → internal-aic-status-Bma0r0ZS.js} +6 -5
  34. package/dist/internal-aic-status-Bma0r0ZS.js.map +1 -0
  35. package/dist/{internal-artifact-open-CX2fRP_D.js → internal-artifact-open-lta2UPnE.js} +2 -2
  36. package/dist/{internal-artifact-open-CX2fRP_D.js.map → internal-artifact-open-lta2UPnE.js.map} +1 -1
  37. package/dist/{internal-fast-dispatch-guard-Cxattkm4.js → internal-fast-dispatch-guard-DPR16qUE.js} +1 -1
  38. package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js → internal-fast-dispatch-guard-DoXO3X7P.js} +2 -2
  39. package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js.map → internal-fast-dispatch-guard-DoXO3X7P.js.map} +1 -1
  40. package/dist/{internal-first-mate-guard-D_JFcrl_.js → internal-first-mate-guard-BEwDjHfX.js} +3 -3
  41. package/dist/{internal-first-mate-guard-D_JFcrl_.js.map → internal-first-mate-guard-BEwDjHfX.js.map} +1 -1
  42. package/dist/{internal-first-mate-guard-97qsseTP.js → internal-first-mate-guard-CAefr6Ce.js} +1 -1
  43. package/dist/{internal-max-dispatch-guard-DQMyOds8.js → internal-max-dispatch-guard-6ZCEanI6.js} +1 -1
  44. package/dist/{internal-max-dispatch-guard-Cxe8h12x.js → internal-max-dispatch-guard-CtIO7pm1.js} +3 -3
  45. package/dist/{internal-max-dispatch-guard-Cxe8h12x.js.map → internal-max-dispatch-guard-CtIO7pm1.js.map} +1 -1
  46. package/dist/{internal-plan-review-O2dwnQv3.js → internal-plan-review-jIts3KYd.js} +3 -3
  47. package/dist/{internal-plan-review-O2dwnQv3.js.map → internal-plan-review-jIts3KYd.js.map} +1 -1
  48. package/dist/{internal-prompt-submit-CD0UFkT-.js → internal-prompt-submit-BfoWVyzs.js} +10 -7
  49. package/dist/internal-prompt-submit-BfoWVyzs.js.map +1 -0
  50. package/dist/{internal-session-bind-CHIOd5ys.js → internal-session-bind-IpZ5hJzR.js} +2 -2
  51. package/dist/{internal-session-bind-CHIOd5ys.js.map → internal-session-bind-IpZ5hJzR.js.map} +1 -1
  52. package/dist/{internal-stop-hook-CH9SKjZ9.js → internal-stop-hook-DO8RKfKB.js} +6 -6
  53. package/dist/{internal-stop-hook-CH9SKjZ9.js.map → internal-stop-hook-DO8RKfKB.js.map} +1 -1
  54. package/dist/{internal-stop-review-a3rpzzhd.js → internal-stop-review-BtGDVrv-.js} +2 -2
  55. package/dist/{internal-stop-review-a3rpzzhd.js.map → internal-stop-review-BtGDVrv-.js.map} +1 -1
  56. package/dist/{internal-worker-guard-BY5seBqp.js → internal-worker-guard-C0FJ4b29.js} +2 -2
  57. package/dist/{internal-worker-guard-BY5seBqp.js.map → internal-worker-guard-C0FJ4b29.js.map} +1 -1
  58. package/dist/{internal-workspace-header-CPZNphnk.js → internal-workspace-header-tvJVAXpv.js} +2 -2
  59. package/dist/{internal-workspace-header-CPZNphnk.js.map → internal-workspace-header-tvJVAXpv.js.map} +1 -1
  60. package/dist/{lifecycle-D8vQXfeC.js → lifecycle-BqWTXaeC.js} +3 -3
  61. package/dist/{lifecycle-D8vQXfeC.js.map → lifecycle-BqWTXaeC.js.map} +1 -1
  62. package/dist/lifecycle-DMRZswwc.js +2 -0
  63. package/dist/lifecycle-FT75ohVw.js +2 -0
  64. package/dist/{lifecycle-MmpJWRcl.js → lifecycle-kpLzHUgD.js} +2 -2
  65. package/dist/{lifecycle-MmpJWRcl.js.map → lifecycle-kpLzHUgD.js.map} +1 -1
  66. package/dist/main.js +21 -21
  67. package/dist/{max-profile-contract-Bl7I_EOC.js → max-profile-contract-MJJt0zm-.js} +2 -2
  68. package/dist/{max-profile-contract-Bl7I_EOC.js.map → max-profile-contract-MJJt0zm-.js.map} +1 -1
  69. package/dist/{mcp-workspace-header-DX_mD0JT.js → mcp-workspace-header-B77WqVFw.js} +2 -2
  70. package/dist/{mcp-workspace-header-DX_mD0JT.js.map → mcp-workspace-header-B77WqVFw.js.map} +1 -1
  71. package/dist/{models-BjCRO0AC.js → models-68HDOEPK.js} +3 -3
  72. package/dist/{models-BjCRO0AC.js.map → models-68HDOEPK.js.map} +1 -1
  73. package/dist/{orchestration-Dn5v8c0a.js → orchestration-Ccmfslh4.js} +3 -3
  74. package/dist/{orchestration-Dn5v8c0a.js.map → orchestration-Ccmfslh4.js.map} +1 -1
  75. package/dist/{paths-P5ajjpzU.js → paths-CpbTHKeP.js} +3 -3
  76. package/dist/{paths-P5ajjpzU.js.map → paths-CpbTHKeP.js.map} +1 -1
  77. package/dist/paths-Dfivvq21.js +2 -0
  78. package/dist/{peer-mcp-personas-CnYMTizo.js → peer-mcp-personas-CeB2Kcn2.js} +184 -76
  79. package/dist/peer-mcp-personas-CeB2Kcn2.js.map +1 -0
  80. package/dist/{plan-review-hook-CfZBvsHd.js → plan-review-hook-ciat1jgZ.js} +4 -4
  81. package/dist/{plan-review-hook-CfZBvsHd.js.map → plan-review-hook-ciat1jgZ.js.map} +1 -1
  82. package/dist/{prompt-submit-hook-CRH6m7Vz.js → prompt-submit-hook-C8q_hDOv.js} +21 -17
  83. package/dist/prompt-submit-hook-C8q_hDOv.js.map +1 -0
  84. package/dist/{provision-D5KOOw6n.js → provision-DZLsyRYh.js} +7 -6
  85. package/dist/provision-DZLsyRYh.js.map +1 -0
  86. package/dist/{self-invocation-DBWyjvGm.js → self-invocation-DIUyoRgL.js} +2 -2
  87. package/dist/{self-invocation-DBWyjvGm.js.map → self-invocation-DIUyoRgL.js.map} +1 -1
  88. package/dist/{serve-fJWhiivo.js → serve-ik_96Q2Z.js} +33 -21
  89. package/dist/serve-ik_96Q2Z.js.map +1 -0
  90. package/dist/{server-setup-DHMPOXKT.js → server-setup-CK3O_Hwf.js} +37 -13
  91. package/dist/{server-setup-DHMPOXKT.js.map → server-setup-CK3O_Hwf.js.map} +1 -1
  92. package/dist/{service-backend-DYEPoszR.js → service-backend-7SPDLUB9.js} +411 -25
  93. package/dist/service-backend-7SPDLUB9.js.map +1 -0
  94. package/dist/{start-Gs4jAwUR.js → start-DPOJJSvp.js} +4 -4
  95. package/dist/{start-Gs4jAwUR.js.map → start-DPOJJSvp.js.map} +1 -1
  96. package/dist/{state-BlMpEFAt.js → state-CVp30CBF.js} +7 -1
  97. package/dist/state-CVp30CBF.js.map +1 -0
  98. package/dist/{stop-gate-hook-BACb8dlj.js → stop-gate-hook-DZVfKoSh.js} +4 -4
  99. package/dist/{stop-gate-hook-BACb8dlj.js.map → stop-gate-hook-DZVfKoSh.js.map} +1 -1
  100. package/dist/{stop-gate-policy-D6jIeOXB.js → stop-gate-policy-Gd_cNT9-.js} +3 -3
  101. package/dist/{stop-gate-policy-D6jIeOXB.js.map → stop-gate-policy-Gd_cNT9-.js.map} +1 -1
  102. package/dist/{token-Dlb_84hW.js → token-DATA_OQK.js} +5 -383
  103. package/dist/token-DATA_OQK.js.map +1 -0
  104. package/dist/upstream-retry-i1k1Xai2.js +383 -0
  105. package/dist/upstream-retry-i1k1Xai2.js.map +1 -0
  106. package/dist/{worker-dispatch-DtjQchvM.js → worker-dispatch-lRhno09M.js} +2 -2
  107. package/dist/{worker-dispatch-DtjQchvM.js.map → worker-dispatch-lRhno09M.js.map} +1 -1
  108. package/docs/bluebird-search.md +338 -0
  109. package/package.json +3 -2
  110. package/dist/attribution-settings-DepziZU8.js.map +0 -1
  111. package/dist/claude-Dw4V8o8l.js.map +0 -1
  112. package/dist/codex-CXOpv4WP.js.map +0 -1
  113. package/dist/engine-CYba_zi7.js +0 -2
  114. package/dist/exec-COUT4QsS.js.map +0 -1
  115. package/dist/index-cmd-DUjQs9zw.js +0 -182
  116. package/dist/index-cmd-DUjQs9zw.js.map +0 -1
  117. package/dist/internal-aic-status-Cfl5HiAN.js.map +0 -1
  118. package/dist/internal-prompt-submit-CD0UFkT-.js.map +0 -1
  119. package/dist/lifecycle-B2eB8nRg.js +0 -2
  120. package/dist/lifecycle-Dz-Rq8pD.js +0 -2
  121. package/dist/paths-DVXBtLyo.js +0 -2
  122. package/dist/peer-mcp-personas-CnYMTizo.js.map +0 -1
  123. package/dist/prompt-submit-hook-CRH6m7Vz.js.map +0 -1
  124. package/dist/provision-D5KOOw6n.js.map +0 -1
  125. package/dist/serve-fJWhiivo.js.map +0 -1
  126. package/dist/service-backend-DYEPoszR.js.map +0 -1
  127. package/dist/state-BlMpEFAt.js.map +0 -1
  128. package/dist/token-Dlb_84hW.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"stop-gate-policy-D6jIeOXB.js","names":["nodePath","fs"],"sources":["../src/lib/orchestration/stop-gate-policy.ts"],"sourcesContent":["/**\n * Pure + thin-IO policy helpers for the consent-gated, top-level-only structural\n * Stop-gate. Split out of `stop-gate-hook.ts` so the security-critical decisions\n * (is this a subagent? is this repo trusted? which checks regressed?) are small,\n * named, and unit-testable.\n *\n * Verified against the official Claude Code hooks reference\n * (https://code.claude.com/docs/en/hooks), 2026-06:\n * - `Stop` fires for the MAIN agent; subagents fire `SubagentStop`, and a\n * `Stop`-registered hook is converted to `SubagentStop` in a subagent\n * context — so the hook command CAN run for a subagent. The payload carries\n * `agent_id` / `agent_type` ONLY inside a subagent/teammate context, so that\n * is the reliable top-level-vs-sub discriminator (NOT an env var, which the\n * proxy cannot set on Claude-spawned subagents).\n * - `UserPromptSubmit` fires only for human prompts to the main agent.\n * - `stop_hook_active` is NOT in the current documented payload, so the\n * per-prompt block budget — not that flag — must be the termination guard.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { promises as fs } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport nodePath from \"node:path\"\n\nimport { parseBoolEnv, resolveExecutable, runCommandCapture } from \"~/lib/exec\"\nimport { PATHS } from \"~/lib/paths\"\n\n/** Minimal shape of the hook payload fields these helpers read. */\nexport interface HookPayloadCommon {\n cwd?: unknown\n session_id?: unknown\n agent_id?: unknown\n agent_type?: unknown\n}\n\n/**\n * True when the hook is firing inside a subagent / teammate context (NOT the\n * top-level user session). Claude Code adds `agent_id` + `agent_type` to the\n * payload only there, so their presence is the discriminator. The Stop-gate and\n * the prompt-steer hook both stand down when this is true, scoping them to the\n * top-level session.\n */\nexport function isSubagentContext(payload: HookPayloadCommon | null | undefined): boolean {\n // Fail CLOSED: ANY present, non-null agent marker means \"not the top-level\n // session\" -> stand down. Main-agent payloads omit these keys entirely\n // (undefined), so this never disables the gate for the top-level session; but\n // a numeric / empty-string / null marker (malformed or future shape) still\n // scopes us OUT, which is the safe direction for the top-level-only invariant.\n const present = (v: unknown): boolean => v !== undefined && v !== null\n return present(payload?.agent_type) || present(payload?.agent_id)\n}\n\n// ─── Per-repo trust (consent once) ───────────────────────────────────────────\n// The gate executes the repo's own `bun run typecheck` / `bun test` / `bun run\n// lint` scripts, which are arbitrary shell. It must NEVER run them in a repo the\n// user has not explicitly trusted. Trust is recorded once per repo in a STABLE\n// dir (survives across launches), keyed by the resolved git repo root.\n\n/** Stable trust dir (NOT the per-launch mirror — trust must persist). */\nfunction trustDir(): string {\n return nodePath.join(PATHS.APP_DIR, \"stop-gate\", \"trust\")\n}\n\n/**\n * Per-process memo for `repoRoot` ONLY.\n *\n * `repoRoot` re-spawned `git rev-parse --show-toplevel` on every call — three\n * times per `github-router claude` launch (via `repoRoot`, `trustRepo` and\n * `stopGateEnabledForRepo`), ~35ms per spawn on Windows. The repo root of a\n * fixed cwd does not change inside a launch, so memoizing a SUCCESSFUL lookup\n * is sound.\n *\n * A FALLBACK result is never memoized. `runCommandCapture` is `.catch`ed to\n * `undefined`, so a git failure or 5s timeout RESOLVES with `cwd` rather than\n * rejecting — which a naive memo would then pin for the life of the process.\n * That matters because the fallback feeds a trust decision: `trustFileFor`\n * keys on the returned root, so a pinned `cwd` would key trust on a\n * subdirectory instead of the repo root. Timeouts are routine on the Windows\n * target (cold disk, AV scanning git.exe, OneDrive-synced repos), so this is\n * not a hypothetical.\n *\n * `repoFingerprint` is not memoized at all — see the note on it below.\n *\n * The memo stores the PROMISE, so concurrent callers share one spawn.\n */\nconst repoRootMemo = new Map<string, Promise<string>>()\n\n/** Resolve the git repo root for `cwd`, falling back to `cwd` when not a repo. */\nexport async function repoRoot(cwd: string): Promise<string> {\n const key = nodePath.resolve(cwd)\n const hit = repoRootMemo.get(key)\n if (hit) return hit\n const pending = (async () => {\n const r = await runCommandCapture([\"git\", \"rev-parse\", \"--show-toplevel\"], {\n cwd,\n timeoutMs: 5_000,\n }).catch(() => undefined)\n const top = r?.stdout?.trim()\n if (top && top.length > 0) return top\n // Fallback: evict so the next call re-probes instead of inheriting a\n // transient failure for the rest of the session.\n repoRootMemo.delete(key)\n return cwd\n })().catch((err: unknown) => {\n repoRootMemo.delete(key)\n throw err\n })\n repoRootMemo.set(key, pending)\n return pending\n}\n\nfunction trustFileFor(root: string): string {\n const key = createHash(\"sha256\").update(nodePath.resolve(root)).digest(\"hex\").slice(0, 32)\n return nodePath.join(trustDir(), key)\n}\n\n/**\n * A stable identity for the repo at `root`: the first (root) commit SHA. It\n * survives normal history growth but differs across distinct repositories, so a\n * DIFFERENT repo later appearing at the same filesystem path is not silently\n * trusted (codex review #2). Empty string when unavailable (no git / no commits)\n * — trust then falls back to path-only, the best we can do.\n *\n * NOT memoized, deliberately. This is the freshness half of a SECURITY control:\n * `isRepoTrusted` compares the stored fingerprint against the LIVE one to\n * detect a repo swap at a trusted path. A per-process memo defeats exactly\n * that — verified by reproduction: init a repo, fingerprint it, then\n * `rm -rf .git && git init` with a new commit at the same path, and a memoized\n * lookup keeps returning the OLD root commit, so the comparison matches and\n * the swapped-in repo is auto-trusted. The proxy is long-lived, so that window\n * is a whole session. The ~42ms per spawn this would save is not worth\n * widening trust.\n */\nexport async function repoFingerprint(root: string): Promise<string> {\n const r = await runCommandCapture(\n [\"git\", \"rev-list\", \"--max-parents=0\", \"HEAD\"],\n { cwd: root, timeoutMs: 5_000 },\n ).catch(() => undefined)\n return (\n r?.stdout\n ?.split(/\\r?\\n/)\n .map((s) => s.trim())\n .filter(Boolean)[0] ?? \"\"\n )\n}\n\n/**\n * True iff the user has consented to run the gate in this repo AND the repo's\n * identity still matches what was trusted. The trust file stores `root\\nfp\\n`;\n * a present fingerprint is verified against the live one (deny on mismatch, and\n * deny if we pinned one but can't recompute it — fail closed). A legacy file\n * with no fingerprint is path-only trust.\n */\nexport async function isRepoTrusted(cwd: string): Promise<boolean> {\n const root = await repoRoot(cwd)\n let stored: string\n try {\n stored = await fs.readFile(trustFileFor(root), \"utf8\")\n } catch {\n return false\n }\n const storedFp = (stored.split(/\\r?\\n/)[1] ?? \"\").trim()\n if (storedFp.length === 0) return true // legacy / no-fingerprint -> path-only.\n const currentFp = await repoFingerprint(root)\n if (currentFp.length === 0) return false // pinned a fp but can't verify -> deny.\n return currentFp === storedFp\n}\n\n/** Record consent for this repo (consent once → automatic thereafter), pinning\n * the repo's root-commit fingerprint so a later repo swap at the same path is\n * not auto-trusted. */\nexport async function trustRepo(cwd: string): Promise<string> {\n const root = await repoRoot(cwd)\n const fp = await repoFingerprint(root)\n await fs.mkdir(trustDir(), { recursive: true })\n await fs.writeFile(trustFileFor(root), `${root}\\n${fp}\\n`, { mode: 0o600 })\n return root\n}\n\n/**\n * Repo-aware gate enable: `GH_ROUTER_DISABLE_STOP_GATE` force-off wins;\n * `GH_ROUTER_ENABLE_STOP_GATE` force-on next; otherwise default to OFF unless the\n * repo is trusted. This is the load-bearing security gate — the default is OFF,\n * so an untrusted repo's scripts are never auto-run.\n */\nexport async function stopGateEnabledForRepo(\n cwd: string,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<boolean> {\n if (parseBoolEnv(env.GH_ROUTER_DISABLE_STOP_GATE) === true) return false\n if (parseBoolEnv(env.GH_ROUTER_ENABLE_STOP_GATE) === true) return true\n return isRepoTrusted(cwd)\n}\n\n// ─── Harness detection ───────────────────────────────────────────────────────\n// Pick a sealed gate whose commands are actually runnable: `bun` present AND the\n// package.json scripts the gate invokes exist. Every sealed gate runs `bun run\n// typecheck`, so a `typecheck` script is the floor; `bun test` is the bun\n// built-in (always runnable); `bun run lint` needs a `lint` script. Returns null\n// when nothing safe matches (→ the gate stays off rather than false-red).\n\nasync function readScripts(root: string): Promise<Record<string, string>> {\n try {\n const raw = await fs.readFile(nodePath.join(root, \"package.json\"), \"utf8\")\n const pkg: unknown = JSON.parse(raw)\n const scripts =\n pkg && typeof pkg === \"object\" ? (pkg as { scripts?: unknown }).scripts : undefined\n if (scripts && typeof scripts === \"object\") {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(scripts as Record<string, unknown>)) {\n if (typeof v === \"string\") out[k] = v\n }\n return out\n }\n } catch {\n /* no package.json / unparseable → no scripts */\n }\n return {}\n}\n\n/** Returns the sealed gate id to run for `cwd`, or null when none is safe. */\nexport async function detectHarnessGateId(cwd: string): Promise<string | null> {\n if (!resolveExecutable(\"bun\", { env: process.env })) return null\n const root = await repoRoot(cwd)\n const scripts = await readScripts(root)\n const has = (k: string): boolean => typeof scripts[k] === \"string\"\n // Every sealed gate runs `bun run typecheck`; without that script it would\n // false-red, so it is the floor.\n if (!has(\"typecheck\")) return null\n if (has(\"lint\")) return \"default-ci\" // typecheck + test + lint\n return \"typecheck-test\" // typecheck + test\n}\n\n// ─── Baseline isolation ──────────────────────────────────────────────────────\n// Block only on checks the agent's diff REGRESSED, never on failures that\n// pre-date the session. v1: the first gate eval of a session records the then-\n// failing checks as the baseline and does not block on them (it still blocks on\n// gate-weakening); later evals block only on (currentFailed \\ baseline).\n\n/** Persistent per-session baseline: the set of check ids failing at first eval. */\nexport interface BaselineStore {\n /** Recorded baseline for a session, or null if none recorded yet. */\n get: (sessionId: string) => Promise<ReadonlySet<string> | null>\n /** Record the baseline failed-check set for a session (first eval only). */\n set: (sessionId: string, failed: ReadonlyArray<string>) => Promise<void>\n}\n\n/**\n * Given the current failed checks and the recorded baseline, return the checks\n * that REGRESSED (failing now, not failing at baseline). A null baseline (first\n * eval) yields an empty regression set — nothing is blamed on the agent yet.\n */\nexport function regressions(\n currentFailed: ReadonlyArray<string>,\n baseline: ReadonlySet<string> | null,\n): string[] {\n if (baseline === null) return []\n return currentFailed.filter((id) => !baseline.has(id))\n}\n\n/** File-backed `BaselineStore` under `stateDir`, keyed by sha256(session_id). */\nexport function fileBaselineStore(stateDir: string): BaselineStore {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `baseline-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n return {\n async get(sid) {\n try {\n const raw = await fs.readFile(fileFor(sid), \"utf8\")\n const arr: unknown = JSON.parse(raw)\n if (Array.isArray(arr)) return new Set(arr.filter((x): x is string => typeof x === \"string\"))\n return new Set<string>()\n } catch {\n return null // no baseline recorded yet\n }\n },\n async set(sid, failed) {\n await fs.mkdir(stateDir, { recursive: true })\n await fs.writeFile(fileFor(sid), JSON.stringify([...failed]), { mode: 0o600 })\n },\n }\n}\n\n// ─── Advisory review: debounce + findings stores (hook V2) ───────────────────\n// The Stop hook runs a background advisory review only when the diff CHANGED\n// since the last review (debounce), and the review writes its findings to a\n// per-session file that the next UserPromptSubmit reads + clears (so the Stop\n// review's notes reach Claude non-authoritatively on the next turn).\n\n/** Per-session \"last reviewed diff hash\" so an unchanged tree isn't re-reviewed. */\nexport interface ReviewDebounce {\n /** True iff `diffHash` differs from the last reviewed hash for this session. */\n shouldReview: (sessionId: string, diffHash: string) => Promise<boolean>\n /** Record `diffHash` as the last reviewed hash for this session. */\n markReviewed: (sessionId: string, diffHash: string) => Promise<void>\n}\n\nexport function fileReviewDebounce(stateDir: string): ReviewDebounce {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `review-hash-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n const readLast = async (sid: string): Promise<string> => {\n try {\n return (await fs.readFile(fileFor(sid), \"utf8\")).trim()\n } catch {\n return \"\"\n }\n }\n return {\n async shouldReview(sid, diffHash) {\n // Never re-review the identical tree; an empty diffHash (no diff) is a no-op.\n if (diffHash.length === 0) return false\n return (await readLast(sid)) !== diffHash\n },\n async markReviewed(sid, diffHash) {\n await fs.mkdir(stateDir, { recursive: true })\n await fs.writeFile(fileFor(sid), diffHash, { mode: 0o600 })\n },\n }\n}\n\n/** Per-session pending advisory findings: the review WRITES, the next\n * UserPromptSubmit READS then CLEARS (one-shot delivery, non-authoritative). */\nexport interface FindingsStore {\n read: (sessionId: string) => Promise<string | null>\n write: (sessionId: string, findings: string) => Promise<void>\n clear: (sessionId: string) => Promise<void>\n}\n\nexport function fileFindingsStore(stateDir: string): FindingsStore {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `findings-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n return {\n async read(sid) {\n try {\n const raw = await fs.readFile(fileFor(sid), \"utf8\")\n return raw.length > 0 ? raw : null\n } catch {\n return null\n }\n },\n async write(sid, findings) {\n await fs.mkdir(stateDir, { recursive: true })\n // Atomic temp+rename so a concurrent reader never sees a half-written file.\n const tmp = `${fileFor(sid)}.${process.pid}.tmp`\n await fs.writeFile(tmp, findings, { mode: 0o600 })\n await fs.rename(tmp, fileFor(sid))\n },\n async clear(sid) {\n await fs.unlink(fileFor(sid)).catch(() => {})\n },\n }\n}\n\n/**\n * The single canonical state dir for the advisory-review layer (hook V2): the\n * Stop hook's review debounce, the background review's findings file, and the\n * UserPromptSubmit hook's last-user-prompt store all live here, keyed by\n * sha256(session_id). One dir so the three independent subcommand processes\n * (`internal-stop-hook`, `internal-stop-review`, `internal-prompt-submit`)\n * agree on where to read/write without threading a path through env. Distinct\n * from the deterministic gate's `gh-router-stopgate*` dirs (block budget +\n * baseline) so the advisory layer can be wiped independently.\n */\nexport function stopReviewStateDir(): string {\n return nodePath.join(tmpdir(), \"gh-router-stop-review\")\n}\n\n/**\n * Per-session \"last user prompt\": the UserPromptSubmit hook WRITES the current\n * prompt; the Stop hook READS it to give the background reviewer the user's\n * actual ask (the Stop payload itself carries no prompt). Plain overwrite — only\n * the latest prompt matters, and the reviewer judges the diff against it.\n */\nexport interface LastPromptStore {\n read: (sessionId: string) => Promise<string | null>\n write: (sessionId: string, prompt: string) => Promise<void>\n}\n\nexport function fileLastPromptStore(stateDir: string): LastPromptStore {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `last-prompt-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n return {\n async read(sid) {\n try {\n const raw = await fs.readFile(fileFor(sid), \"utf8\")\n return raw.length > 0 ? raw : null\n } catch {\n return null\n }\n },\n async write(sid, prompt) {\n await fs.mkdir(stateDir, { recursive: true })\n const tmp = `${fileFor(sid)}.${process.pid}.tmp`\n await fs.writeFile(tmp, prompt, { mode: 0o600 })\n await fs.rename(tmp, fileFor(sid))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,kBAAkB,SAAwD;CAMxF,MAAM,WAAW,MAAwB,MAAM,KAAA,KAAa,MAAM;CAClE,OAAO,QAAQ,SAAS,UAAU,KAAK,QAAQ,SAAS,QAAQ;AAClE;;AASA,SAAS,WAAmB;CAC1B,OAAOA,KAAS,KAAK,MAAM,SAAS,aAAa,OAAO;AAC1D;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,+BAAe,IAAI,IAA6B;;AAGtD,eAAsB,SAAS,KAA8B;CAC3D,MAAM,MAAMA,KAAS,QAAQ,GAAG;CAChC,MAAM,MAAM,aAAa,IA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,QAAQ,GAAG,EAAE,GAAG,QAAQ,IAAI;GAC3C,MAAMA,SAAG,UAAU,KAAK,UAAU,EAAE,MAAM,IAAM,CAAC;GACjD,MAAMA,SAAG,OAAO,KAAK,QAAQ,GAAG,CAAC;EACnC;EACA,MAAM,MAAM,KAAK;GACf,MAAMA,SAAG,OAAO,QAAQ,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;EAC9C;CACF;AACF;;;;;;;;;;;AAYA,SAAgB,qBAA6B;CAC3C,OAAOD,KAAS,KAAK,OAAO,GAAG,uBAAuB;AACxD;AAaA,SAAgB,oBAAoB,UAAmC;CACrE,MAAM,WAAW,QACfA,KAAS,KAAK,UAAU,eAAe,WAAW,QAAQ,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE,GAAG;CACtG,OAAO;EACL,MAAM,KAAK,KAAK;GACd,IAAI;IACF,MAAM,MAAM,MAAMC,SAAG,SAAS,QAAQ,GAAG,GAAG,MAAM;IAClD,OAAO,IAAI,SAAS,IAAI,MAAM;GAChC,QAAQ;IACN,OAAO;GACT;EACF;EACA,MAAM,MAAM,KAAK,QAAQ;GACvB,MAAMA,SAAG,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;GAC5C,MAAM,MAAM,GAAG,QAAQ,GAAG,EAAE,GAAG,QAAQ,IAAI;GAC3C,MAAMA,SAAG,UAAU,KAAK,QAAQ,EAAE,MAAM,IAAM,CAAC;GAC/C,MAAMA,SAAG,OAAO,KAAK,QAAQ,GAAG,CAAC;EACnC;CACF;AACF"}
1
+ {"version":3,"file":"stop-gate-policy-Gd_cNT9-.js","names":["nodePath","fs"],"sources":["../src/lib/orchestration/stop-gate-policy.ts"],"sourcesContent":["/**\n * Pure + thin-IO policy helpers for the consent-gated, top-level-only structural\n * Stop-gate. Split out of `stop-gate-hook.ts` so the security-critical decisions\n * (is this a subagent? is this repo trusted? which checks regressed?) are small,\n * named, and unit-testable.\n *\n * Verified against the official Claude Code hooks reference\n * (https://code.claude.com/docs/en/hooks), 2026-06:\n * - `Stop` fires for the MAIN agent; subagents fire `SubagentStop`, and a\n * `Stop`-registered hook is converted to `SubagentStop` in a subagent\n * context — so the hook command CAN run for a subagent. The payload carries\n * `agent_id` / `agent_type` ONLY inside a subagent/teammate context, so that\n * is the reliable top-level-vs-sub discriminator (NOT an env var, which the\n * proxy cannot set on Claude-spawned subagents).\n * - `UserPromptSubmit` fires only for human prompts to the main agent.\n * - `stop_hook_active` is NOT in the current documented payload, so the\n * per-prompt block budget — not that flag — must be the termination guard.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { promises as fs } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport nodePath from \"node:path\"\n\nimport { parseBoolEnv, resolveExecutable, runCommandCapture } from \"~/lib/exec\"\nimport { PATHS } from \"~/lib/paths\"\n\n/** Minimal shape of the hook payload fields these helpers read. */\nexport interface HookPayloadCommon {\n cwd?: unknown\n session_id?: unknown\n agent_id?: unknown\n agent_type?: unknown\n}\n\n/**\n * True when the hook is firing inside a subagent / teammate context (NOT the\n * top-level user session). Claude Code adds `agent_id` + `agent_type` to the\n * payload only there, so their presence is the discriminator. The Stop-gate and\n * the prompt-steer hook both stand down when this is true, scoping them to the\n * top-level session.\n */\nexport function isSubagentContext(payload: HookPayloadCommon | null | undefined): boolean {\n // Fail CLOSED: ANY present, non-null agent marker means \"not the top-level\n // session\" -> stand down. Main-agent payloads omit these keys entirely\n // (undefined), so this never disables the gate for the top-level session; but\n // a numeric / empty-string / null marker (malformed or future shape) still\n // scopes us OUT, which is the safe direction for the top-level-only invariant.\n const present = (v: unknown): boolean => v !== undefined && v !== null\n return present(payload?.agent_type) || present(payload?.agent_id)\n}\n\n// ─── Per-repo trust (consent once) ───────────────────────────────────────────\n// The gate executes the repo's own `bun run typecheck` / `bun test` / `bun run\n// lint` scripts, which are arbitrary shell. It must NEVER run them in a repo the\n// user has not explicitly trusted. Trust is recorded once per repo in a STABLE\n// dir (survives across launches), keyed by the resolved git repo root.\n\n/** Stable trust dir (NOT the per-launch mirror — trust must persist). */\nfunction trustDir(): string {\n return nodePath.join(PATHS.APP_DIR, \"stop-gate\", \"trust\")\n}\n\n/**\n * Per-process memo for `repoRoot` ONLY.\n *\n * `repoRoot` re-spawned `git rev-parse --show-toplevel` on every call — three\n * times per `github-router claude` launch (via `repoRoot`, `trustRepo` and\n * `stopGateEnabledForRepo`), ~35ms per spawn on Windows. The repo root of a\n * fixed cwd does not change inside a launch, so memoizing a SUCCESSFUL lookup\n * is sound.\n *\n * A FALLBACK result is never memoized. `runCommandCapture` is `.catch`ed to\n * `undefined`, so a git failure or 5s timeout RESOLVES with `cwd` rather than\n * rejecting — which a naive memo would then pin for the life of the process.\n * That matters because the fallback feeds a trust decision: `trustFileFor`\n * keys on the returned root, so a pinned `cwd` would key trust on a\n * subdirectory instead of the repo root. Timeouts are routine on the Windows\n * target (cold disk, AV scanning git.exe, OneDrive-synced repos), so this is\n * not a hypothetical.\n *\n * `repoFingerprint` is not memoized at all — see the note on it below.\n *\n * The memo stores the PROMISE, so concurrent callers share one spawn.\n */\nconst repoRootMemo = new Map<string, Promise<string>>()\n\n/** Resolve the git repo root for `cwd`, falling back to `cwd` when not a repo. */\nexport async function repoRoot(cwd: string): Promise<string> {\n const key = nodePath.resolve(cwd)\n const hit = repoRootMemo.get(key)\n if (hit) return hit\n const pending = (async () => {\n const r = await runCommandCapture([\"git\", \"rev-parse\", \"--show-toplevel\"], {\n cwd,\n timeoutMs: 5_000,\n }).catch(() => undefined)\n const top = r?.stdout?.trim()\n if (top && top.length > 0) return top\n // Fallback: evict so the next call re-probes instead of inheriting a\n // transient failure for the rest of the session.\n repoRootMemo.delete(key)\n return cwd\n })().catch((err: unknown) => {\n repoRootMemo.delete(key)\n throw err\n })\n repoRootMemo.set(key, pending)\n return pending\n}\n\nfunction trustFileFor(root: string): string {\n const key = createHash(\"sha256\").update(nodePath.resolve(root)).digest(\"hex\").slice(0, 32)\n return nodePath.join(trustDir(), key)\n}\n\n/**\n * A stable identity for the repo at `root`: the first (root) commit SHA. It\n * survives normal history growth but differs across distinct repositories, so a\n * DIFFERENT repo later appearing at the same filesystem path is not silently\n * trusted (codex review #2). Empty string when unavailable (no git / no commits)\n * — trust then falls back to path-only, the best we can do.\n *\n * NOT memoized, deliberately. This is the freshness half of a SECURITY control:\n * `isRepoTrusted` compares the stored fingerprint against the LIVE one to\n * detect a repo swap at a trusted path. A per-process memo defeats exactly\n * that — verified by reproduction: init a repo, fingerprint it, then\n * `rm -rf .git && git init` with a new commit at the same path, and a memoized\n * lookup keeps returning the OLD root commit, so the comparison matches and\n * the swapped-in repo is auto-trusted. The proxy is long-lived, so that window\n * is a whole session. The ~42ms per spawn this would save is not worth\n * widening trust.\n */\nexport async function repoFingerprint(root: string): Promise<string> {\n const r = await runCommandCapture(\n [\"git\", \"rev-list\", \"--max-parents=0\", \"HEAD\"],\n { cwd: root, timeoutMs: 5_000 },\n ).catch(() => undefined)\n return (\n r?.stdout\n ?.split(/\\r?\\n/)\n .map((s) => s.trim())\n .filter(Boolean)[0] ?? \"\"\n )\n}\n\n/**\n * True iff the user has consented to run the gate in this repo AND the repo's\n * identity still matches what was trusted. The trust file stores `root\\nfp\\n`;\n * a present fingerprint is verified against the live one (deny on mismatch, and\n * deny if we pinned one but can't recompute it — fail closed). A legacy file\n * with no fingerprint is path-only trust.\n */\nexport async function isRepoTrusted(cwd: string): Promise<boolean> {\n const root = await repoRoot(cwd)\n let stored: string\n try {\n stored = await fs.readFile(trustFileFor(root), \"utf8\")\n } catch {\n return false\n }\n const storedFp = (stored.split(/\\r?\\n/)[1] ?? \"\").trim()\n if (storedFp.length === 0) return true // legacy / no-fingerprint -> path-only.\n const currentFp = await repoFingerprint(root)\n if (currentFp.length === 0) return false // pinned a fp but can't verify -> deny.\n return currentFp === storedFp\n}\n\n/** Record consent for this repo (consent once → automatic thereafter), pinning\n * the repo's root-commit fingerprint so a later repo swap at the same path is\n * not auto-trusted. */\nexport async function trustRepo(cwd: string): Promise<string> {\n const root = await repoRoot(cwd)\n const fp = await repoFingerprint(root)\n await fs.mkdir(trustDir(), { recursive: true })\n await fs.writeFile(trustFileFor(root), `${root}\\n${fp}\\n`, { mode: 0o600 })\n return root\n}\n\n/**\n * Repo-aware gate enable: `GH_ROUTER_DISABLE_STOP_GATE` force-off wins;\n * `GH_ROUTER_ENABLE_STOP_GATE` force-on next; otherwise default to OFF unless the\n * repo is trusted. This is the load-bearing security gate — the default is OFF,\n * so an untrusted repo's scripts are never auto-run.\n */\nexport async function stopGateEnabledForRepo(\n cwd: string,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<boolean> {\n if (parseBoolEnv(env.GH_ROUTER_DISABLE_STOP_GATE) === true) return false\n if (parseBoolEnv(env.GH_ROUTER_ENABLE_STOP_GATE) === true) return true\n return isRepoTrusted(cwd)\n}\n\n// ─── Harness detection ───────────────────────────────────────────────────────\n// Pick a sealed gate whose commands are actually runnable: `bun` present AND the\n// package.json scripts the gate invokes exist. Every sealed gate runs `bun run\n// typecheck`, so a `typecheck` script is the floor; `bun test` is the bun\n// built-in (always runnable); `bun run lint` needs a `lint` script. Returns null\n// when nothing safe matches (→ the gate stays off rather than false-red).\n\nasync function readScripts(root: string): Promise<Record<string, string>> {\n try {\n const raw = await fs.readFile(nodePath.join(root, \"package.json\"), \"utf8\")\n const pkg: unknown = JSON.parse(raw)\n const scripts =\n pkg && typeof pkg === \"object\" ? (pkg as { scripts?: unknown }).scripts : undefined\n if (scripts && typeof scripts === \"object\") {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(scripts as Record<string, unknown>)) {\n if (typeof v === \"string\") out[k] = v\n }\n return out\n }\n } catch {\n /* no package.json / unparseable → no scripts */\n }\n return {}\n}\n\n/** Returns the sealed gate id to run for `cwd`, or null when none is safe. */\nexport async function detectHarnessGateId(cwd: string): Promise<string | null> {\n if (!resolveExecutable(\"bun\", { env: process.env })) return null\n const root = await repoRoot(cwd)\n const scripts = await readScripts(root)\n const has = (k: string): boolean => typeof scripts[k] === \"string\"\n // Every sealed gate runs `bun run typecheck`; without that script it would\n // false-red, so it is the floor.\n if (!has(\"typecheck\")) return null\n if (has(\"lint\")) return \"default-ci\" // typecheck + test + lint\n return \"typecheck-test\" // typecheck + test\n}\n\n// ─── Baseline isolation ──────────────────────────────────────────────────────\n// Block only on checks the agent's diff REGRESSED, never on failures that\n// pre-date the session. v1: the first gate eval of a session records the then-\n// failing checks as the baseline and does not block on them (it still blocks on\n// gate-weakening); later evals block only on (currentFailed \\ baseline).\n\n/** Persistent per-session baseline: the set of check ids failing at first eval. */\nexport interface BaselineStore {\n /** Recorded baseline for a session, or null if none recorded yet. */\n get: (sessionId: string) => Promise<ReadonlySet<string> | null>\n /** Record the baseline failed-check set for a session (first eval only). */\n set: (sessionId: string, failed: ReadonlyArray<string>) => Promise<void>\n}\n\n/**\n * Given the current failed checks and the recorded baseline, return the checks\n * that REGRESSED (failing now, not failing at baseline). A null baseline (first\n * eval) yields an empty regression set — nothing is blamed on the agent yet.\n */\nexport function regressions(\n currentFailed: ReadonlyArray<string>,\n baseline: ReadonlySet<string> | null,\n): string[] {\n if (baseline === null) return []\n return currentFailed.filter((id) => !baseline.has(id))\n}\n\n/** File-backed `BaselineStore` under `stateDir`, keyed by sha256(session_id). */\nexport function fileBaselineStore(stateDir: string): BaselineStore {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `baseline-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n return {\n async get(sid) {\n try {\n const raw = await fs.readFile(fileFor(sid), \"utf8\")\n const arr: unknown = JSON.parse(raw)\n if (Array.isArray(arr)) return new Set(arr.filter((x): x is string => typeof x === \"string\"))\n return new Set<string>()\n } catch {\n return null // no baseline recorded yet\n }\n },\n async set(sid, failed) {\n await fs.mkdir(stateDir, { recursive: true })\n await fs.writeFile(fileFor(sid), JSON.stringify([...failed]), { mode: 0o600 })\n },\n }\n}\n\n// ─── Advisory review: debounce + findings stores (hook V2) ───────────────────\n// The Stop hook runs a background advisory review only when the diff CHANGED\n// since the last review (debounce), and the review writes its findings to a\n// per-session file that the next UserPromptSubmit reads + clears (so the Stop\n// review's notes reach Claude non-authoritatively on the next turn).\n\n/** Per-session \"last reviewed diff hash\" so an unchanged tree isn't re-reviewed. */\nexport interface ReviewDebounce {\n /** True iff `diffHash` differs from the last reviewed hash for this session. */\n shouldReview: (sessionId: string, diffHash: string) => Promise<boolean>\n /** Record `diffHash` as the last reviewed hash for this session. */\n markReviewed: (sessionId: string, diffHash: string) => Promise<void>\n}\n\nexport function fileReviewDebounce(stateDir: string): ReviewDebounce {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `review-hash-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n const readLast = async (sid: string): Promise<string> => {\n try {\n return (await fs.readFile(fileFor(sid), \"utf8\")).trim()\n } catch {\n return \"\"\n }\n }\n return {\n async shouldReview(sid, diffHash) {\n // Never re-review the identical tree; an empty diffHash (no diff) is a no-op.\n if (diffHash.length === 0) return false\n return (await readLast(sid)) !== diffHash\n },\n async markReviewed(sid, diffHash) {\n await fs.mkdir(stateDir, { recursive: true })\n await fs.writeFile(fileFor(sid), diffHash, { mode: 0o600 })\n },\n }\n}\n\n/** Per-session pending advisory findings: the review WRITES, the next\n * UserPromptSubmit READS then CLEARS (one-shot delivery, non-authoritative). */\nexport interface FindingsStore {\n read: (sessionId: string) => Promise<string | null>\n write: (sessionId: string, findings: string) => Promise<void>\n clear: (sessionId: string) => Promise<void>\n}\n\nexport function fileFindingsStore(stateDir: string): FindingsStore {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `findings-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n return {\n async read(sid) {\n try {\n const raw = await fs.readFile(fileFor(sid), \"utf8\")\n return raw.length > 0 ? raw : null\n } catch {\n return null\n }\n },\n async write(sid, findings) {\n await fs.mkdir(stateDir, { recursive: true })\n // Atomic temp+rename so a concurrent reader never sees a half-written file.\n const tmp = `${fileFor(sid)}.${process.pid}.tmp`\n await fs.writeFile(tmp, findings, { mode: 0o600 })\n await fs.rename(tmp, fileFor(sid))\n },\n async clear(sid) {\n await fs.unlink(fileFor(sid)).catch(() => {})\n },\n }\n}\n\n/**\n * The single canonical state dir for the advisory-review layer (hook V2): the\n * Stop hook's review debounce, the background review's findings file, and the\n * UserPromptSubmit hook's last-user-prompt store all live here, keyed by\n * sha256(session_id). One dir so the three independent subcommand processes\n * (`internal-stop-hook`, `internal-stop-review`, `internal-prompt-submit`)\n * agree on where to read/write without threading a path through env. Distinct\n * from the deterministic gate's `gh-router-stopgate*` dirs (block budget +\n * baseline) so the advisory layer can be wiped independently.\n */\nexport function stopReviewStateDir(): string {\n return nodePath.join(tmpdir(), \"gh-router-stop-review\")\n}\n\n/**\n * Per-session \"last user prompt\": the UserPromptSubmit hook WRITES the current\n * prompt; the Stop hook READS it to give the background reviewer the user's\n * actual ask (the Stop payload itself carries no prompt). Plain overwrite — only\n * the latest prompt matters, and the reviewer judges the diff against it.\n */\nexport interface LastPromptStore {\n read: (sessionId: string) => Promise<string | null>\n write: (sessionId: string, prompt: string) => Promise<void>\n}\n\nexport function fileLastPromptStore(stateDir: string): LastPromptStore {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `last-prompt-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n return {\n async read(sid) {\n try {\n const raw = await fs.readFile(fileFor(sid), \"utf8\")\n return raw.length > 0 ? raw : null\n } catch {\n return null\n }\n },\n async write(sid, prompt) {\n await fs.mkdir(stateDir, { recursive: true })\n const tmp = `${fileFor(sid)}.${process.pid}.tmp`\n await fs.writeFile(tmp, prompt, { mode: 0o600 })\n await fs.rename(tmp, fileFor(sid))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,kBAAkB,SAAwD;CAMxF,MAAM,WA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AE,MAAM,IAAM,CAAC;GAC/C,MAAMA,SAAG,OAAO,KAAK,QAAQ,GAAG,CAAC;EACnC;CACF;AACF"}
@@ -1,5 +1,6 @@
1
- import { t as PATHS } from "./paths-P5ajjpzU.js";
2
- import { t as state } from "./state-BlMpEFAt.js";
1
+ import { t as PATHS } from "./paths-CpbTHKeP.js";
2
+ import { t as state } from "./state-CVp30CBF.js";
3
+ import { i as sanitizeTransportText, r as fetchWithTransientRetry, t as TransportExhaustionError } from "./upstream-retry-i1k1Xai2.js";
3
4
  import consola from "consola";
4
5
  import path from "node:path";
5
6
  import { createHash, randomBytes, randomUUID } from "node:crypto";
@@ -68,385 +69,6 @@ const githubAgentGraphQLHeaders = (state, features) => ({
68
69
  ...features ? { "GraphQL-Features": features } : {}
69
70
  });
70
71
  //#endregion
71
- //#region src/lib/upstream-retry.ts
72
- /**
73
- * Shared transient-failure retry for upstream calls (`src/lib/upstream-retry.ts`).
74
- *
75
- * Retries ONLY on transient conditions — never on success, never on a
76
- * deterministic 4xx (400/401/403/404…), so a malformed request or auth
77
- * failure fails fast instead of being hammered. 401 is intentionally NOT
78
- * retried here: it stays with the existing token-refresh path so the
79
- * 401→503 forwardError invariant is preserved.
80
- *
81
- * Retryable:
82
- * - HTTP 429 + 5xx (500/502/503/504) — the "upstream is sick" class.
83
- * - network errors (ECONNRESET / "fetch failed" / "terminated" / EPIPE …).
84
- * - upstream TIMEOUT aborts: an AbortError thrown while the CALLER'S
85
- * `signal` is NOT aborted (a user cancel aborts the caller's signal
86
- * and is rethrown immediately, never retried).
87
- *
88
- * Exponential backoff + FULL jitter, capped, honoring `Retry-After`. The
89
- * inter-attempt sleep is abortable so a user cancel during backoff
90
- * returns promptly. Bounded `attempts` keep a single call from holding an
91
- * inflight slot indefinitely (robust AND fast).
92
- *
93
- * Streaming note: the user-facing passthrough and the worker loop must
94
- * only retry in the PRE-FIRST-BYTE window — a retry after bytes have
95
- * streamed would duplicate output. Callers there pass a `doFetch` that
96
- * has not yet handed its body to the consumer.
97
- */
98
- const DEFAULT_RETRY_STATUSES = [
99
- 429,
100
- 500,
101
- 502,
102
- 503,
103
- 504
104
- ];
105
- const TRANSPORT_MESSAGE_MAX = 512;
106
- const TRANSIENT_CODES = /* @__PURE__ */ new Set([
107
- "ECONNRESET",
108
- "ETIMEDOUT",
109
- "EPIPE",
110
- "EAI_AGAIN",
111
- "UND_ERR_CONNECT_TIMEOUT",
112
- "UND_ERR_HEADERS_TIMEOUT",
113
- "UND_ERR_SOCKET",
114
- "UND_ERR_CLOSED",
115
- "ERR_HTTP2_INVALID_SESSION",
116
- "ERR_HTTP2_GOAWAY_SESSION",
117
- "ERR_HTTP2_STREAM_CANCEL"
118
- ]);
119
- /**
120
- * TLS faults that are genuinely permanent: a protocol/version/cipher mismatch,
121
- * or a certificate this client cannot validate. Retrying any of these buys
122
- * three times the latency before the identical failure.
123
- *
124
- * Deliberately NOT the blanket `"ssl routines"` match this replaces. Every
125
- * OpenSSL error carries that string, so the catch-all also swallowed alert 20
126
- * (`bad record mac`) — an integrity fault a fresh connection routinely clears.
127
- * See TRANSIENT_TLS_MESSAGES.
128
- *
129
- * Each entry must stay disjoint from TRANSIENT_TLS_MESSAGES. The bucket order
130
- * in `classifyTransportError` checks the narrower transient alert first, so an
131
- * overlap would resolve as transient; `tests/upstream-retry.test.ts` pins that
132
- * no error matches two buckets.
133
- */
134
- const DETERMINISTIC_TLS_MESSAGES = [
135
- "self signed certificate",
136
- "certificate has expired",
137
- "unable to verify the first certificate",
138
- "unable to get local issuer certificate",
139
- "hostname/ip does not match certificate",
140
- "certificate verify failed",
141
- "unknown ca",
142
- "wrong version number",
143
- "unsupported protocol",
144
- "no protocols available",
145
- "alert handshake failure",
146
- "alert protocol version",
147
- "alert insufficient security",
148
- "tls handshake"
149
- ];
150
- /**
151
- * TLS alert 20 (`bad_record_mac`) ONLY — a record failed AEAD authentication
152
- * somewhere on the path. The connection is unusable, but the next one is
153
- * typically fine, which is exactly what a bounded retry is for.
154
- *
155
- * This also matches OpenSSL's local-detection wording ("decryption failed or
156
- * bad record mac", reason 281) as well as the received-alert wording ("ssl/tls
157
- * alert bad record mac", reason 1020). Both are integrity faults and both
158
- * warrant the same one-bounded-replay policy.
159
- *
160
- * An earlier revision promoted four alert phrases; three were wrong and stay
161
- * deterministic on purpose. Alert 10 (`unexpected message`) is protocol state,
162
- * alert 21 (`decryption failed`) is legacy-server incompatibility, and alert 22
163
- * (`record overflow`) is a malformed or desynchronised stream. Promoting those
164
- * converts fail-fast configuration errors into 3x latency.
165
- */
166
- const TRANSIENT_TLS_MESSAGES = ["bad record mac"];
167
- const DETERMINISTIC_CODES = /* @__PURE__ */ new Set([
168
- "ENOTFOUND",
169
- "ECONNREFUSED",
170
- "DEPTH_ZERO_SELF_SIGNED_CERT",
171
- "SELF_SIGNED_CERT_IN_CHAIN",
172
- "UNABLE_TO_GET_ISSUER_CERT",
173
- "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
174
- "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
175
- "CERT_HAS_EXPIRED",
176
- "CERT_NOT_YET_VALID",
177
- "ERR_TLS_CERT_ALTNAME_INVALID",
178
- "ERR_TLS_CERT_SIGNATURE_ALGORITHM_UNSUPPORTED",
179
- "ERR_SSL_WRONG_VERSION_NUMBER"
180
- ]);
181
- const CREDENTIAL_RE = /\b(eyJ[A-Za-z0-9_-]{20,}(?:\.[A-Za-z0-9_-]+){0,2}|gh[opsu]_[A-Za-z0-9_]{20,}|Bearer\s+\S{20,})\b/gi;
182
- const SECRET_ASSIGNMENT_RE = /\b(authorization|api[_-]?key|access[_-]?token|token|password)\s*[:=]\s*([^\s,;]+)/gi;
183
- const REQUEST_BODY_RE = /\b(request\s+body|body)\s*[:=]\s*.*$/gi;
184
- var TransportExhaustionError = class extends Error {
185
- endpoint;
186
- label;
187
- attempts;
188
- classification;
189
- lastError;
190
- constructor(metadata, cause) {
191
- const target = metadata.endpoint ?? metadata.label ?? "upstream";
192
- const lastError = {
193
- name: sanitizeTransportText(metadata.lastError.name),
194
- message: sanitizeTransportText(metadata.lastError.message),
195
- code: metadata.lastError.code ? sanitizeTransportText(metadata.lastError.code) : void 0,
196
- causeCode: metadata.lastError.causeCode ? sanitizeTransportText(metadata.lastError.causeCode) : void 0
197
- };
198
- const code = lastError.causeCode ?? lastError.code;
199
- const suffix = code ? ` (${code})` : "";
200
- super(`Upstream transport ${metadata.classification === "transient" ? "failed" : "is unreachable"} at ${sanitizeTransportText(target)} after ${metadata.attempts} attempt${metadata.attempts === 1 ? "" : "s"}: ${lastError.name}: ${lastError.message}${suffix}`, { cause });
201
- this.name = "TransportExhaustionError";
202
- this.endpoint = metadata.endpoint ? sanitizeTransportText(metadata.endpoint) : void 0;
203
- this.label = metadata.label ? sanitizeTransportText(metadata.label) : void 0;
204
- this.attempts = metadata.attempts;
205
- this.classification = metadata.classification;
206
- this.lastError = lastError;
207
- }
208
- };
209
- function readStringProperty(value, key) {
210
- if (typeof value !== "object" && typeof value !== "function" || value === null) return;
211
- try {
212
- const property = value[key];
213
- return typeof property === "string" ? property : void 0;
214
- } catch {
215
- return;
216
- }
217
- }
218
- function readCause(value) {
219
- if (typeof value !== "object" && typeof value !== "function" || value === null) return;
220
- try {
221
- return value.cause;
222
- } catch {
223
- return;
224
- }
225
- }
226
- function safeString(value) {
227
- try {
228
- return String(value);
229
- } catch {
230
- return "[unserializable error]";
231
- }
232
- }
233
- function sanitizeTransportText(value) {
234
- const sanitized = value.replace(/\r\n|\r|\n/g, " ").replace(CREDENTIAL_RE, "[REDACTED]").replace(SECRET_ASSIGNMENT_RE, "$1=[REDACTED]").replace(REQUEST_BODY_RE, "$1=[REDACTED]");
235
- return sanitized.length > TRANSPORT_MESSAGE_MAX ? `${sanitized.slice(0, TRANSPORT_MESSAGE_MAX)}…` : sanitized;
236
- }
237
- /**
238
- * Classify errors thrown before the first response byte. Deterministic
239
- * connectivity/configuration signals win over generic runtime wording such as
240
- * TypeError("fetch failed"), because the nested cause is more specific.
241
- *
242
- * Buckets are evaluated in a stated total order, narrowest first, and the first
243
- * match wins — so no error can land in two of them:
244
- *
245
- * 1. caller cancel
246
- * 2. TLS alert 20 (`bad record mac`) — integrity, retryable
247
- * 3. deterministic cert/config codes and messages, plus refused/DNS-miss
248
- * 4. transient codes (incl. HTTP/2 session death) and generic transport text
249
- * 5. everything else — `non_transport`, rethrown raw
250
- */
251
- function classifyTransportError(error, opts = {}) {
252
- const name = readStringProperty(error, "name") ?? "Error";
253
- const rawMessage = readStringProperty(error, "message") ?? (typeof error === "string" ? error : safeString(error));
254
- const message = sanitizeTransportText(rawMessage);
255
- const code = readStringProperty(error, "code");
256
- const causes = [];
257
- const seen = /* @__PURE__ */ new Set();
258
- let current = readCause(error);
259
- for (let depth = 0; current !== void 0 && depth < 4; depth++) {
260
- if ((typeof current === "object" || typeof current === "function") && current !== null) {
261
- if (seen.has(current)) break;
262
- seen.add(current);
263
- }
264
- causes.push(current);
265
- current = readCause(current);
266
- }
267
- const causeCode = causes.map((cause) => readStringProperty(cause, "code")).find((value) => value !== void 0);
268
- const codes = [code, ...causes.map((cause) => readStringProperty(cause, "code"))].filter((value) => value !== void 0).map((value) => value.toUpperCase());
269
- const messages = [rawMessage, ...causes.map((cause) => readStringProperty(cause, "message") ?? "")].join(" ").toLowerCase();
270
- if (opts.callerCancelled) return {
271
- classification: "cancelled",
272
- name,
273
- message,
274
- code,
275
- causeCode
276
- };
277
- if (TRANSIENT_TLS_MESSAGES.some((phrase) => messages.includes(phrase))) return {
278
- classification: "transient",
279
- name,
280
- message,
281
- code,
282
- causeCode
283
- };
284
- if (codes.some((value) => DETERMINISTIC_CODES.has(value)) || DETERMINISTIC_TLS_MESSAGES.some((phrase) => messages.includes(phrase)) || messages.includes("ssl routines") || messages.includes("econnrefused") || messages.includes("enotfound")) return {
285
- classification: "deterministic",
286
- name,
287
- message,
288
- code,
289
- causeCode
290
- };
291
- if (name === "AbortError" || name === "TimeoutError" || name === "InactivityTimeout" || codes.some((value) => TRANSIENT_CODES.has(value)) || messages.includes("terminated") || messages.includes("fetch failed") || messages.includes("network error") || messages.includes("socket hang up") || messages.includes("socket closed") || messages.includes("econnreset") || messages.includes("etimedout") || messages.includes("epipe") || messages.includes("eai_again")) return {
292
- classification: "transient",
293
- name,
294
- message,
295
- code,
296
- causeCode
297
- };
298
- return {
299
- classification: "non_transport",
300
- name,
301
- message,
302
- code,
303
- causeCode
304
- };
305
- }
306
- function transportExhaustion(error, attempts, opts, details) {
307
- if (details.classification !== "transient" && details.classification !== "deterministic") throw new TypeError("transportExhaustion requires a transport error");
308
- return new TransportExhaustionError({
309
- endpoint: opts.endpoint ?? opts.label,
310
- label: opts.label,
311
- attempts,
312
- classification: details.classification,
313
- lastError: {
314
- name: details.name,
315
- message: details.message,
316
- code: details.code,
317
- causeCode: details.causeCode
318
- }
319
- }, error);
320
- }
321
- function parseRetryAfter(headerValue) {
322
- if (!headerValue) return void 0;
323
- const secs = Number(headerValue);
324
- if (Number.isFinite(secs)) return Math.max(0, secs * 1e3);
325
- const dateMs = Date.parse(headerValue);
326
- if (Number.isFinite(dateMs)) return Math.max(0, dateMs - Date.now());
327
- }
328
- /** Sleep that resolves early (does not reject) when `signal` aborts — the
329
- * retry loop re-checks `signal.aborted` at the top and throws there. */
330
- function abortableSleep(ms, signal) {
331
- if (ms <= 0) return Promise.resolve();
332
- return new Promise((resolve) => {
333
- let settled = false;
334
- const done = () => {
335
- if (settled) return;
336
- settled = true;
337
- clearTimeout(timer);
338
- signal?.removeEventListener("abort", done);
339
- resolve();
340
- };
341
- const timer = setTimeout(done, ms);
342
- if (signal) {
343
- if (signal.aborted) {
344
- done();
345
- return;
346
- }
347
- signal.addEventListener("abort", done, { once: true });
348
- }
349
- });
350
- }
351
- /**
352
- * Run `doFetch` with bounded transient-failure retries. `doFetch` is a
353
- * thunk so each attempt issues a FRESH request (bodies can't be replayed
354
- * from a consumed stream). Returns the final `Response` — which may still
355
- * carry a retryable status if all attempts are exhausted (the caller
356
- * handles that as it would a single-shot failure).
357
- */
358
- async function fetchWithTransientRetry(doFetch, opts = {}) {
359
- const attempts = Math.max(1, opts.attempts ?? 3);
360
- const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES;
361
- const baseDelayMs = opts.baseDelayMs ?? 250;
362
- const maxDelayMs = opts.maxDelayMs ?? 4e3;
363
- const { signal, label } = opts;
364
- for (let attempt = 1;; attempt++) {
365
- if (signal?.aborted) throw new DOMException("This operation was aborted", "AbortError");
366
- let res;
367
- let caught;
368
- try {
369
- res = await doFetch(attempt);
370
- } catch (err) {
371
- caught = err;
372
- }
373
- if (res && !retryStatuses.includes(res.status)) return res;
374
- if (caught !== void 0) {
375
- if (signal?.aborted) throw caught;
376
- const details = classifyTransportError(caught);
377
- if (details.classification === "deterministic") throw transportExhaustion(caught, attempt, opts, details);
378
- if (details.classification !== "transient") throw caught;
379
- }
380
- if (attempt >= attempts) {
381
- if (res) return res;
382
- const details = classifyTransportError(caught);
383
- throw transportExhaustion(caught, attempt, opts, details);
384
- }
385
- const retryAfterMs = res ? parseRetryAfter(res.headers.get("retry-after")) : void 0;
386
- if (res?.body) try {
387
- await res.body.cancel();
388
- } catch {}
389
- const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
390
- const delay = Math.min(maxDelayMs, retryAfterMs ?? Math.round(Math.random() * expCap));
391
- if (label) {
392
- const why = res ? `HTTP ${res.status}` : caught?.name ?? "error";
393
- consola.debug(`[upstream-retry] ${label}: attempt ${attempt}/${attempts} failed (${why}); retrying in ${delay}ms`);
394
- }
395
- await abortableSleep(delay, signal);
396
- }
397
- }
398
- /** Extract an HTTP status from a thrown error (HTTPError carries
399
- * `.response.status`; others may carry `.status`/`.statusCode`; last
400
- * resort parses `"HTTP <code>"` from the message). */
401
- function errorStatus(err) {
402
- const e = err;
403
- for (const v of [
404
- e?.status,
405
- e?.statusCode,
406
- e?.response?.status
407
- ]) if (typeof v === "number") return v;
408
- const m = /\bHTTP (\d{3})\b/.exec(e?.message ?? "");
409
- return m ? Number(m[1]) : void 0;
410
- }
411
- /**
412
- * Generic transient-retry for a non-`Response`-returning call (e.g. the
413
- * Copilot service clients, which throw `HTTPError` on non-OK and throw on
414
- * network errors). Retries `fn()` when it throws a transient error — an
415
- * `HTTPError`-like with a retryable status (429/5xx) OR a transient
416
- * network/timeout error — using the same backoff + abort semantics as
417
- * `fetchWithTransientRetry`. Never retries a deterministic 4xx (incl.
418
- * 401), a non-transient throw, or a user cancel.
419
- */
420
- async function withTransientRetry(fn, opts = {}) {
421
- const attempts = Math.max(1, opts.attempts ?? 3);
422
- const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES;
423
- const baseDelayMs = opts.baseDelayMs ?? 250;
424
- const maxDelayMs = opts.maxDelayMs ?? 4e3;
425
- const { signal, label } = opts;
426
- for (let attempt = 1;; attempt++) {
427
- if (signal?.aborted) throw new DOMException("This operation was aborted", "AbortError");
428
- try {
429
- return await fn(attempt);
430
- } catch (err) {
431
- if (signal?.aborted) throw err;
432
- const status = errorStatus(err);
433
- const details = classifyTransportError(err);
434
- if (status !== void 0) {
435
- if (!retryStatuses.includes(status) || attempt >= attempts) throw err;
436
- } else {
437
- if (details.classification === "deterministic") throw transportExhaustion(err, attempt, opts, details);
438
- if (details.classification !== "transient") throw err;
439
- if (attempt >= attempts) throw transportExhaustion(err, attempt, opts, details);
440
- }
441
- const retryAfterMs = parseRetryAfter(err?.response?.headers?.get?.("retry-after") ?? null);
442
- const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
443
- const delay = Math.min(maxDelayMs, retryAfterMs ?? Math.round(Math.random() * expCap));
444
- if (label) consola.debug(`[upstream-retry] ${label}: attempt ${attempt}/${attempts} threw (${status !== void 0 ? `HTTP ${status}` : err?.name ?? "error"}); retrying in ${delay}ms`);
445
- await abortableSleep(delay, signal);
446
- }
447
- }
448
- }
449
- //#endregion
450
72
  //#region src/lib/error.ts
451
73
  var HTTPError = class extends Error {
452
74
  response;
@@ -1758,6 +1380,6 @@ async function warnIfAgentScopesInsufficient() {
1758
1380
  }
1759
1381
  }
1760
1382
  //#endregion
1761
- export { GITHUB_GRAPHQL_URL as C, githubAgentGraphQLHeaders as D, copilotVersion as E, githubAgentHeaders as O, GITHUB_API_BASE_URL as S, copilotHeaders as T, forwardError as _, cacheCopilotVersion as a, sanitizeTransportText as b, filterBetaHeader as c, resolveModel as d, sleep as f, HTTPError as g, isAllowedCopilotHost as h, tryRefreshAndRetry as i, githubHeaders as k, isNullish as l, getGitHubUser as m, setupGitHubAgentToken as n, cacheModels as o, getModels as p, setupGitHubToken as r, cacheVSCodeVersion as s, setupCopilotToken as t, resolveCodexModel as u, classifyTransportError as v, copilotBaseUrl as w, withTransientRetry as x, fetchWithTransientRetry as y };
1383
+ export { githubAgentGraphQLHeaders as C, copilotVersion as S, githubHeaders as T, forwardError as _, cacheCopilotVersion as a, copilotBaseUrl as b, filterBetaHeader as c, resolveModel as d, sleep as f, HTTPError as g, isAllowedCopilotHost as h, tryRefreshAndRetry as i, isNullish as l, getGitHubUser as m, setupGitHubAgentToken as n, cacheModels as o, getModels as p, setupGitHubToken as r, cacheVSCodeVersion as s, setupCopilotToken as t, resolveCodexModel as u, GITHUB_API_BASE_URL as v, githubAgentHeaders as w, copilotHeaders as x, GITHUB_GRAPHQL_URL as y };
1762
1384
 
1763
- //# sourceMappingURL=token-Dlb_84hW.js.map
1385
+ //# sourceMappingURL=token-DATA_OQK.js.map