github-router 0.3.355 → 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-N48QlHu2.js → attribution-settings-CnmV9MSv.js} +11 -11
  7. package/dist/{attribution-settings-N48QlHu2.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-BAKFTVqA.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-CspHNGZA.js → codex-DQpSPjpQ.js} +9 -9
  21. package/dist/{codex-CspHNGZA.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-JeKibE14.js → gate-discovery-B2x_8hNL.js} +5 -5
  28. package/dist/{gate-discovery-JeKibE14.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-Dz6mdfcL.js → internal-stop-hook-Dm-m8RoA.js} +5 -5
  58. package/dist/{internal-stop-hook-Dz6mdfcL.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-Ch4VWo40.js → peer-mcp-personas-CVxXq1Q-.js} +2836 -150
  84. package/dist/peer-mcp-personas-CVxXq1Q-.js.map +1 -0
  85. package/dist/{pi-Cwj383nc.js → pi-D-BgxVhx.js} +22 -16
  86. package/dist/{pi-Cwj383nc.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-PodfFQu-.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-D-OuW7kz.js → serve-DfxxKLFl.js} +25 -17
  94. package/dist/serve-DfxxKLFl.js.map +1 -0
  95. package/dist/{server-setup-DDZxJgl0.js → server-setup-VYf8ptCH.js} +161 -27
  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-CZZ0cTV9.js → start-BsY1d26G.js} +4 -4
  100. package/dist/{start-CZZ0cTV9.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 +10 -1
  114. package/package.json +1 -1
  115. package/dist/ado-tools-B5TCtnlQ.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-BAKFTVqA.js.map +0 -1
  119. package/dist/engine-YvnWaTnR.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-Ch4VWo40.js.map +0 -1
  125. package/dist/provision-PodfFQu-.js.map +0 -1
  126. package/dist/serve-D-OuW7kz.js.map +0 -1
  127. package/dist/server-setup-DDZxJgl0.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"internal-max-dispatch-guard-D7ByWH4v.js","names":[],"sources":["../src/lib/max-dispatch-acl.ts","../src/internal-max-dispatch-guard.ts"],"sourcesContent":["import {\n MAX_PROFILE_NATIVE_AGENT_NAMES,\n MAX_PROFILE_NATIVE_EFFORTS,\n MAX_PROFILE_NATIVE_MODELS,\n type MaxProfileNativeAgentName,\n} from \"./max-profile-contract\"\nimport type { Effort } from \"./reasoning-effort\"\n\nexport const MAX_DISPATCH_TOOL_MATCHER = \"^(Task|Agent)$\"\n\nexport const MAX_BROWSE_DISPATCH_AGENT = \"worker-browse\" as const\n\nconst MAX_NATIVE_AGENT_SET = new Set<string>([\n ...MAX_PROFILE_NATIVE_AGENT_NAMES,\n MAX_BROWSE_DISPATCH_AGENT,\n])\n\n/** Assert max launches never start without their native Task/Agent ACL. */\nexport class MaxDispatchGuardInstallError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"MaxDispatchGuardInstallError\"\n }\n}\n\nexport function assertMaxDispatchGuardInstalled(\n maxProfile: boolean,\n installationSucceeded: boolean,\n): void {\n if (maxProfile && !installationSucceeded) {\n throw new MaxDispatchGuardInstallError(\n \"max profile requires the native Task/Agent ACL hook, but it could not be installed; refusing to start an unguarded max session.\",\n )\n }\n}\n\nconst MAX_ALLOWED_MODEL_BASES = new Set([\"gpt-6-luna\", \"gpt-5.6-luna\", \"gemini-3.8-flash\", \"grok-4.6\"])\n\n/**\n * Claude Code's public Agent schema currently requires one of these built-in\n * model aliases even when the selected custom agent already owns its model in\n * frontmatter. They are transport placeholders in max, not model overrides.\n * Strip them so the role's catalog-validated max model remains authoritative.\n * Case and a trailing `[1m]` are ignored deliberately: neither can turn a\n * client-owned placeholder into an Opus override in the closed max roster.\n */\nexport const MAX_AGENT_SCHEMA_MODEL_ALIASES = Object.freeze([\n \"sonnet\",\n \"opus\",\n \"haiku\",\n \"fable\",\n] as const)\n\nconst MAX_AGENT_SCHEMA_MODEL_ALIAS_SET = new Set<string>(\n MAX_AGENT_SCHEMA_MODEL_ALIASES,\n)\n\nfunction isMaxAgentSchemaModelAlias(model: unknown): boolean {\n if (typeof model !== \"string\") return false\n return MAX_AGENT_SCHEMA_MODEL_ALIAS_SET.has(baseModel(model.trim()).toLowerCase())\n}\n\nexport interface MaxDispatchGuardOptions {\n /** Catalog-resolved reviewer model for this launch (Sonnet 5 1M/xhigh). */\n reviewerModel?: string\n reviewerEffort?: Extract<Effort, \"high\" | \"xhigh\" | \"max\">\n}\n\nexport interface MaxDispatchDecision {\n allowed: boolean\n reason?: string\n updatedInput?: Record<string, unknown>\n target?: string\n effort?: Effort\n verdict: \"allow\" | \"deny\" | \"allow-non-dispatch\"\n}\n\nfunction stringField(input: Record<string, unknown>, ...keys: string[]): string | undefined {\n const values = keys\n .filter((key) => Object.prototype.hasOwnProperty.call(input, key))\n .map((key) => input[key])\n .filter((value) => value !== undefined && value !== null)\n if (values.length === 0) return undefined\n if (values.some((value) => typeof value !== \"string\" || value.trim().length === 0)) return undefined\n const distinct = [...new Set((values as string[]).map((value) => value.trim()))]\n return distinct.length === 1 ? distinct[0] : undefined\n}\n\nfunction baseModel(model: string): string {\n return model.replace(/(?:\\[1m\\])+$/i, \"\")\n}\n\nexport function normalizeMaxDispatchModel(model: unknown): string | undefined {\n if (typeof model !== \"string\" || model.trim().length === 0) return undefined\n const trimmed = model.trim()\n const base = baseModel(trimmed)\n return MAX_ALLOWED_MODEL_BASES.has(base)\n ? base === \"grok-4.6\" ? base : `${base}[1m]`\n : undefined\n}\n\nexport function normalizeMaxDispatchEffort(\n model: string,\n effort: unknown,\n): Effort | undefined {\n if (effort === undefined || effort === null) return undefined\n if (typeof effort !== \"string\") return undefined\n const allowed: ReadonlyArray<Effort> = model === \"gpt-5.6-sol\" || model === \"gpt-6-sol\"\n ? [\"high\", \"xhigh\", \"max\"]\n : model === \"gpt-6-luna\"\n ? [\"none\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"]\n : model === \"claude-sonnet-5\" || model === \"claude-opus-5.5\" || model === \"claude-opus-5.5\"\n ? [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"]\n : model === \"grok-4.6\" || model === \"gemini-3.8-flash\"\n ? [\"low\", \"medium\", \"high\"]\n : []\n if (allowed.includes(effort as Effort)) return effort as Effort\n return undefined\n}\n\n/**\n * Native max Task/Agent ACL. Role frontmatter owns the fixed model. Required\n * public-schema aliases are stripped as transport placeholders; a client that\n * can express custom ids may override only to Luna, Gemini, or Grok with a\n * live-ladder effort. Sol/Codex/unknown/private ids are rejected. The lead may\n * target any emitted max role; role-to-role edges are unrestricted here.\n */\nexport function decideMaxDispatchGuard(\n stdin: string | unknown,\n opts: MaxDispatchGuardOptions = {},\n): MaxDispatchDecision {\n let parsed: unknown\n try {\n parsed = typeof stdin === \"string\" ? JSON.parse(stdin) : stdin\n } catch {\n return { allowed: false, reason: \"max dispatch denied: malformed hook payload\", verdict: \"deny\" }\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return { allowed: false, reason: \"max dispatch denied: hook payload must be an object\", verdict: \"deny\" }\n }\n const payload = parsed as Record<string, unknown>\n if (typeof payload.tool_name !== \"string\") {\n return { allowed: false, reason: \"max dispatch denied: hook payload has no tool_name\", verdict: \"deny\" }\n }\n if (!/^(Task|Agent)$/.test(payload.tool_name)) {\n return { allowed: true, verdict: \"allow-non-dispatch\" }\n }\n if (!payload.tool_input || typeof payload.tool_input !== \"object\" || Array.isArray(payload.tool_input)) {\n return { allowed: false, reason: `max dispatch denied: ${payload.tool_name} payload has malformed tool_input`, verdict: \"deny\" }\n }\n const toolInput = payload.tool_input as Record<string, unknown>\n const target = stringField(toolInput, \"subagent_type\", \"subagentType\")\n if (!target || !MAX_NATIVE_AGENT_SET.has(target)) {\n return { allowed: false, reason: `max dispatch denied: target must be one of ${[...MAX_PROFILE_NATIVE_AGENT_NAMES, MAX_BROWSE_DISPATCH_AGENT].join(\", \")}`, verdict: \"deny\" }\n }\n const nativeTarget = target as MaxProfileNativeAgentName | typeof MAX_BROWSE_DISPATCH_AGENT\n const modelValue = toolInput.model\n const schemaAlias = isMaxAgentSchemaModelAlias(modelValue)\n const normalizedModel = modelValue === undefined || schemaAlias\n ? undefined\n : normalizeMaxDispatchModel(modelValue)\n if (modelValue !== undefined && !schemaAlias && !normalizedModel) {\n return { allowed: false, reason: \"max dispatch denied: model must be a Claude Code Agent schema alias, Luna[1m], Gemini 3.8 Flash[1m], or bare Grok 4.6\", target, verdict: \"deny\" }\n }\n const requestedEffort = toolInput.thinking ?? toolInput.effort\n const effectiveModel = normalizedModel\n ? baseModel(normalizedModel)\n : nativeTarget === MAX_BROWSE_DISPATCH_AGENT\n // Keep this aligned with BROWSE_DEFAULT_MODEL. Importing worker-agent/engine\n // here would pull the worker runtime into the small hook bundle.\n ? \"gpt-6-luna\"\n : nativeTarget === \"reviewer\" && opts.reviewerModel\n ? baseModel(opts.reviewerModel)\n : MAX_PROFILE_NATIVE_MODELS[nativeTarget]\n const effort = normalizeMaxDispatchEffort(effectiveModel, requestedEffort)\n if ((toolInput.thinking !== undefined || toolInput.effort !== undefined) && !effort) {\n return { allowed: false, reason: \"max dispatch denied: reasoning override is not supported by the selected model\", target, verdict: \"deny\" }\n }\n const fixedReviewerEffort = nativeTarget === \"reviewer\"\n && !normalizedModel\n && opts.reviewerModel\n ? opts.reviewerEffort ?? MAX_PROFILE_NATIVE_EFFORTS.reviewer\n : undefined\n const effectiveEffort = fixedReviewerEffort ?? effort\n const updatedInput = { ...toolInput }\n if (normalizedModel) updatedInput.model = normalizedModel\n else delete updatedInput.model\n if (effectiveEffort) {\n // Claude Code's native Agent payload uses `model` and `effort`; preserve\n // an explicit field when possible, and emit the launch-resolved reviewer\n // effort so the dispatch cannot drift from the generated frontmatter.\n if (toolInput.thinking !== undefined) updatedInput.thinking = effectiveEffort\n else updatedInput.effort = effectiveEffort\n }\n if (toolInput.thinking !== undefined && toolInput.effort !== undefined) {\n delete updatedInput.effort\n }\n if (toolInput.model === undefined && normalizedModel === undefined) delete updatedInput.model\n return { allowed: true, target, effort: effectiveEffort, updatedInput, verdict: \"allow\" }\n}\n\nexport function maxDispatchAllowOutput(updatedInput: Record<string, unknown>): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"allow\",\n updatedInput,\n },\n })\n}\n\nexport function maxDispatchDenyOutput(reason: string): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: reason,\n },\n })\n}\n","import { defineCommand } from \"citty\"\nimport { readFileSync } from \"node:fs\"\n\nimport {\n decideMaxDispatchGuard,\n maxDispatchAllowOutput,\n maxDispatchDenyOutput,\n} from \"./lib/max-dispatch-acl\"\nimport { buildSelfCommand, type SelfInvocation } from \"./lib/hook-launcher/self-invocation\"\n\nfunction readStdinSync(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nexport const internalMaxDispatchGuard = defineCommand({\n meta: {\n name: \"internal-max-dispatch-guard\",\n description: \"Internal: PreToolUse guard enforcing the max-profile native Task/Agent policy.\",\n },\n args: {\n reviewerModel: {\n type: \"string\",\n description: \"Catalog-resolved Max reviewer model for this launch.\",\n },\n reviewerEffort: {\n type: \"string\",\n description: \"Fixed Max reviewer effort for this launch.\",\n },\n },\n run({ args }) {\n const reviewerEffort = args.reviewerEffort === \"max\"\n ? \"max\"\n : args.reviewerEffort === \"xhigh\"\n ? \"xhigh\"\n : \"high\"\n const decision = decideMaxDispatchGuard(readStdinSync(), {\n reviewerModel: args.reviewerModel,\n reviewerEffort,\n })\n if (!decision.allowed && decision.reason) {\n process.stdout.write(maxDispatchDenyOutput(decision.reason))\n } else if (decision.verdict === \"allow\" && decision.updatedInput) {\n process.stdout.write(maxDispatchAllowOutput(decision.updatedInput))\n }\n process.exitCode = 0\n },\n})\n\nexport function buildMaxDispatchGuardHookCommand(\n invocation: SelfInvocation,\n opts: { reviewerModel?: string; reviewerEffort?: \"high\" | \"xhigh\" | \"max\" } = {},\n): string {\n const flags: string[] = []\n if (opts.reviewerModel) flags.push(`--reviewerModel \"${opts.reviewerModel}\"`)\n if (opts.reviewerEffort) flags.push(`--reviewerEffort ${opts.reviewerEffort}`)\n return buildSelfCommand(\n invocation,\n [\"internal-max-dispatch-guard\", ...flags].join(\" \"),\n )\n}\n"],"mappings":";;;;;AAQA,MAAa,4BAA4B;AAEzC,MAAa,4BAA4B;AAEzC,MAAM,uCAAuB,IAAI,IAAY,CAC3C,GAAG,gCACH,yBACF,CAAC;;AAGD,IAAa,+BAAb,cAAkD,MAAM;CACtD,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,gCACd,YACA,uBACM;CACN,IAAI,cAAc,CAAC,uBACjB,MAAM,IAAI,6BACR,iIACF;AAEJ;AAEA,MAAM,0CAA0B,IAAI,IAAI;CAAC;CAAc;CAAgB;CAAoB;AAAU,CAAC;;;;;;;;;AAUtG,MAAa,iCAAiC,OAAO,OAAO;CAC1D;CACA;CACA;CACA;AACF,CAAU;AAEV,MAAM,mCAAmC,IAAI,IAC3C,8BACF;AAEA,SAAS,2BAA2B,OAAyB;CAC3D,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO,iCAAiC,IAAI,UAAU,MAAM,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC;AACnF;AAiBA,SAAS,YAAY,OAAgC,GAAG,MAAoC;CAC1F,MAAM,SAAS,KACZ,QAAQ,QAAQ,OAAO,UAAU,eAAe,KAAK,OAAO,GAAG,CAAC,CAAC,CACjE,KAAK,QAAQ,MAAM,IAAI,CAAC,CACxB,QAAQ,UAAU,UAAU,KAAA,KAAa,UAAU,IAAI;CAC1D,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,IAAI,OAAO,MAAM,UAAU,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,WAAW,CAAC,GAAG,OAAO,KAAA;CAC3F,MAAM,WAAW,CAAC,GAAG,IAAI,IAAK,OAAoB,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CA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AS,YAAY,CAAC;EAEpE,QAAQ,WAAW;CACrB;AACF,CAAC;AAED,SAAgB,iCACd,YACA,OAA8E,CAAC,GACvE;CACR,MAAM,QAAkB,CAAC;CACzB,IAAI,KAAK,eAAe,MAAM,KAAK,oBAAoB,KAAK,cAAc,EAAE;CAC5E,IAAI,KAAK,gBAAgB,MAAM,KAAK,oBAAoB,KAAK,gBAAgB;CAC7E,OAAO,iBACL,YACA,CAAC,+BAA+B,GAAG,KAAK,CAAC,CAAC,KAAK,GAAG,CACpD;AACF"}
1
+ {"version":3,"file":"internal-max-dispatch-guard-CY8l9SDw.js","names":[],"sources":["../src/lib/max-dispatch-acl.ts","../src/internal-max-dispatch-guard.ts"],"sourcesContent":["import {\n MAX_PROFILE_NATIVE_AGENT_NAMES,\n MAX_PROFILE_NATIVE_EFFORTS,\n MAX_PROFILE_NATIVE_MODELS,\n type MaxProfileNativeAgentName,\n} from \"./max-profile-contract\"\nimport type { Effort } from \"./reasoning-effort\"\n\nexport const MAX_DISPATCH_TOOL_MATCHER = \"^(Task|Agent)$\"\n\nexport const MAX_BROWSE_DISPATCH_AGENT = \"worker-browse\" as const\n\nconst MAX_NATIVE_AGENT_SET = new Set<string>([\n ...MAX_PROFILE_NATIVE_AGENT_NAMES,\n MAX_BROWSE_DISPATCH_AGENT,\n])\n\n/** Assert max launches never start without their native Task/Agent ACL. */\nexport class MaxDispatchGuardInstallError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"MaxDispatchGuardInstallError\"\n }\n}\n\nexport function assertMaxDispatchGuardInstalled(\n maxProfile: boolean,\n installationSucceeded: boolean,\n): void {\n if (maxProfile && !installationSucceeded) {\n throw new MaxDispatchGuardInstallError(\n \"max profile requires the native Task/Agent ACL hook, but it could not be installed; refusing to start an unguarded max session.\",\n )\n }\n}\n\nconst MAX_ALLOWED_MODEL_BASES = new Set([\"gpt-6-luna\", \"gpt-5.6-luna\", \"gemini-3.8-flash\", \"grok-4.6\"])\n\n/**\n * Claude Code's public Agent schema currently requires one of these built-in\n * model aliases even when the selected custom agent already owns its model in\n * frontmatter. They are transport placeholders in max, not model overrides.\n * Strip them so the role's catalog-validated max model remains authoritative.\n * Case and a trailing `[1m]` are ignored deliberately: neither can turn a\n * client-owned placeholder into an Opus override in the closed max roster.\n */\nexport const MAX_AGENT_SCHEMA_MODEL_ALIASES = Object.freeze([\n \"sonnet\",\n \"opus\",\n \"haiku\",\n \"fable\",\n] as const)\n\nconst MAX_AGENT_SCHEMA_MODEL_ALIAS_SET = new Set<string>(\n MAX_AGENT_SCHEMA_MODEL_ALIASES,\n)\n\nfunction isMaxAgentSchemaModelAlias(model: unknown): boolean {\n if (typeof model !== \"string\") return false\n return MAX_AGENT_SCHEMA_MODEL_ALIAS_SET.has(baseModel(model.trim()).toLowerCase())\n}\n\nexport interface MaxDispatchGuardOptions {\n /** Catalog-resolved reviewer model for this launch (Sonnet 5 1M/xhigh). */\n reviewerModel?: string\n reviewerEffort?: Extract<Effort, \"high\" | \"xhigh\" | \"max\">\n}\n\nexport interface MaxDispatchDecision {\n allowed: boolean\n reason?: string\n updatedInput?: Record<string, unknown>\n target?: string\n effort?: Effort\n verdict: \"allow\" | \"deny\" | \"allow-non-dispatch\"\n}\n\nfunction stringField(input: Record<string, unknown>, ...keys: string[]): string | undefined {\n const values = keys\n .filter((key) => Object.prototype.hasOwnProperty.call(input, key))\n .map((key) => input[key])\n .filter((value) => value !== undefined && value !== null)\n if (values.length === 0) return undefined\n if (values.some((value) => typeof value !== \"string\" || value.trim().length === 0)) return undefined\n const distinct = [...new Set((values as string[]).map((value) => value.trim()))]\n return distinct.length === 1 ? distinct[0] : undefined\n}\n\nfunction baseModel(model: string): string {\n return model.replace(/(?:\\[1m\\])+$/i, \"\")\n}\n\nexport function normalizeMaxDispatchModel(model: unknown): string | undefined {\n if (typeof model !== \"string\" || model.trim().length === 0) return undefined\n const trimmed = model.trim()\n const base = baseModel(trimmed)\n return MAX_ALLOWED_MODEL_BASES.has(base)\n ? base === \"grok-4.6\" ? base : `${base}[1m]`\n : undefined\n}\n\nexport function normalizeMaxDispatchEffort(\n model: string,\n effort: unknown,\n): Effort | undefined {\n if (effort === undefined || effort === null) return undefined\n if (typeof effort !== \"string\") return undefined\n const allowed: ReadonlyArray<Effort> = model === \"gpt-5.6-sol\" || model === \"gpt-6-sol\"\n ? [\"high\", \"xhigh\", \"max\"]\n : model === \"gpt-6-luna\"\n ? [\"none\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"]\n : model === \"claude-sonnet-5\" || model === \"claude-opus-5.5\" || model === \"claude-opus-5.5\"\n ? [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"]\n : model === \"grok-4.6\" || model === \"gemini-3.8-flash\"\n ? [\"low\", \"medium\", \"high\"]\n : []\n if (allowed.includes(effort as Effort)) return effort as Effort\n return undefined\n}\n\n/**\n * Native max Task/Agent ACL. Role frontmatter owns the fixed model. Required\n * public-schema aliases are stripped as transport placeholders; a client that\n * can express custom ids may override only to Luna, Gemini, or Grok with a\n * live-ladder effort. Sol/Codex/unknown/private ids are rejected. The lead may\n * target any emitted max role; role-to-role edges are unrestricted here.\n */\nexport function decideMaxDispatchGuard(\n stdin: string | unknown,\n opts: MaxDispatchGuardOptions = {},\n): MaxDispatchDecision {\n let parsed: unknown\n try {\n parsed = typeof stdin === \"string\" ? JSON.parse(stdin) : stdin\n } catch {\n return { allowed: false, reason: \"max dispatch denied: malformed hook payload\", verdict: \"deny\" }\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return { allowed: false, reason: \"max dispatch denied: hook payload must be an object\", verdict: \"deny\" }\n }\n const payload = parsed as Record<string, unknown>\n if (typeof payload.tool_name !== \"string\") {\n return { allowed: false, reason: \"max dispatch denied: hook payload has no tool_name\", verdict: \"deny\" }\n }\n if (!/^(Task|Agent)$/.test(payload.tool_name)) {\n return { allowed: true, verdict: \"allow-non-dispatch\" }\n }\n if (!payload.tool_input || typeof payload.tool_input !== \"object\" || Array.isArray(payload.tool_input)) {\n return { allowed: false, reason: `max dispatch denied: ${payload.tool_name} payload has malformed tool_input`, verdict: \"deny\" }\n }\n const toolInput = payload.tool_input as Record<string, unknown>\n const target = stringField(toolInput, \"subagent_type\", \"subagentType\")\n if (!target || !MAX_NATIVE_AGENT_SET.has(target)) {\n return { allowed: false, reason: `max dispatch denied: target must be one of ${[...MAX_PROFILE_NATIVE_AGENT_NAMES, MAX_BROWSE_DISPATCH_AGENT].join(\", \")}`, verdict: \"deny\" }\n }\n const nativeTarget = target as MaxProfileNativeAgentName | typeof MAX_BROWSE_DISPATCH_AGENT\n const modelValue = toolInput.model\n const schemaAlias = isMaxAgentSchemaModelAlias(modelValue)\n const normalizedModel = modelValue === undefined || schemaAlias\n ? undefined\n : normalizeMaxDispatchModel(modelValue)\n if (modelValue !== undefined && !schemaAlias && !normalizedModel) {\n return { allowed: false, reason: \"max dispatch denied: model must be a Claude Code Agent schema alias, Luna[1m], Gemini 3.8 Flash[1m], or bare Grok 4.6\", target, verdict: \"deny\" }\n }\n const requestedEffort = toolInput.thinking ?? toolInput.effort\n const effectiveModel = normalizedModel\n ? baseModel(normalizedModel)\n : nativeTarget === MAX_BROWSE_DISPATCH_AGENT\n // Keep this aligned with BROWSE_DEFAULT_MODEL. Importing worker-agent/engine\n // here would pull the worker runtime into the small hook bundle.\n ? \"gpt-6-luna\"\n : nativeTarget === \"reviewer\" && opts.reviewerModel\n ? baseModel(opts.reviewerModel)\n : MAX_PROFILE_NATIVE_MODELS[nativeTarget]\n const effort = normalizeMaxDispatchEffort(effectiveModel, requestedEffort)\n if ((toolInput.thinking !== undefined || toolInput.effort !== undefined) && !effort) {\n return { allowed: false, reason: \"max dispatch denied: reasoning override is not supported by the selected model\", target, verdict: \"deny\" }\n }\n const fixedReviewerEffort = nativeTarget === \"reviewer\"\n && !normalizedModel\n && opts.reviewerModel\n ? opts.reviewerEffort ?? MAX_PROFILE_NATIVE_EFFORTS.reviewer\n : undefined\n const effectiveEffort = fixedReviewerEffort ?? effort\n const updatedInput = { ...toolInput }\n if (normalizedModel) updatedInput.model = normalizedModel\n else delete updatedInput.model\n if (effectiveEffort) {\n // Claude Code's native Agent payload uses `model` and `effort`; preserve\n // an explicit field when possible, and emit the launch-resolved reviewer\n // effort so the dispatch cannot drift from the generated frontmatter.\n if (toolInput.thinking !== undefined) updatedInput.thinking = effectiveEffort\n else updatedInput.effort = effectiveEffort\n }\n if (toolInput.thinking !== undefined && toolInput.effort !== undefined) {\n delete updatedInput.effort\n }\n if (toolInput.model === undefined && normalizedModel === undefined) delete updatedInput.model\n return { allowed: true, target, effort: effectiveEffort, updatedInput, verdict: \"allow\" }\n}\n\nexport function maxDispatchAllowOutput(updatedInput: Record<string, unknown>): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"allow\",\n updatedInput,\n },\n })\n}\n\nexport function maxDispatchDenyOutput(reason: string): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: reason,\n },\n })\n}\n","import { defineCommand } from \"citty\"\nimport { readFileSync } from \"node:fs\"\n\nimport {\n decideMaxDispatchGuard,\n maxDispatchAllowOutput,\n maxDispatchDenyOutput,\n} from \"./lib/max-dispatch-acl\"\nimport { buildSelfCommand, type SelfInvocation } from \"./lib/hook-launcher/self-invocation\"\n\nfunction readStdinSync(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nexport const internalMaxDispatchGuard = defineCommand({\n meta: {\n name: \"internal-max-dispatch-guard\",\n description: \"Internal: PreToolUse guard enforcing the max-profile native Task/Agent policy.\",\n },\n args: {\n reviewerModel: {\n type: \"string\",\n description: \"Catalog-resolved Max reviewer model for this launch.\",\n },\n reviewerEffort: {\n type: \"string\",\n description: \"Fixed Max reviewer effort for this launch.\",\n },\n },\n run({ args }) {\n const reviewerEffort = args.reviewerEffort === \"max\"\n ? \"max\"\n : args.reviewerEffort === \"xhigh\"\n ? \"xhigh\"\n : \"high\"\n const decision = decideMaxDispatchGuard(readStdinSync(), {\n reviewerModel: args.reviewerModel,\n reviewerEffort,\n })\n if (!decision.allowed && decision.reason) {\n process.stdout.write(maxDispatchDenyOutput(decision.reason))\n } else if (decision.verdict === \"allow\" && decision.updatedInput) {\n process.stdout.write(maxDispatchAllowOutput(decision.updatedInput))\n }\n process.exitCode = 0\n },\n})\n\nexport function buildMaxDispatchGuardHookCommand(\n invocation: SelfInvocation,\n opts: { reviewerModel?: string; reviewerEffort?: \"high\" | \"xhigh\" | \"max\" } = {},\n): string {\n const flags: string[] = []\n if (opts.reviewerModel) flags.push(`--reviewerModel \"${opts.reviewerModel}\"`)\n if (opts.reviewerEffort) flags.push(`--reviewerEffort ${opts.reviewerEffort}`)\n return buildSelfCommand(\n invocation,\n [\"internal-max-dispatch-guard\", ...flags].join(\" \"),\n )\n}\n"],"mappings":";;;;;AAQA,MAAa,4BAA4B;AAEzC,MAAa,4BAA4B;AAEzC,MAAM,uCAAuB,IAAI,IAAY,CAC3C,GAAG,gCACH,yBACF,CAAC;;AAGD,IAAa,+BAAb,cAAkD,MAAM;CACtD,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,gCACd,YACA,uBACM;CACN,IAAI,cAAc,CAAC,uBACjB,MAAM,IAAI,6BACR,iIACF;AAEJ;AAEA,MAAM,0CAA0B,IAAI,IAAI;CAAC;CAAc;CAAgB;CAAoB;AAAU,CAAC;;;;;;;;;AAUtG,MAAa,iCAAiC,OAAO,OAAO;CAC1D;CACA;CACA;CACA;AACF,CAAU;AAEV,MAAM,mCAAmC,IAAI,IAC3C,8BACF;AAEA,SAAS,2BAA2B,OAAyB;CAC3D,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO,iCAAiC,IAAI,UAAU,MAAM,KAAK,CAAC,CAAC,CAAC,YAAY,CAAC;AACnF;AA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J,MAAM;EACN,aAAa;CACf;CACA,MAAM;EACJ,eAAe;GACb,MAAM;GACN,aAAa;EACf;EACA,gBAAgB;GACd,MAAM;GACN,aAAa;EACf;CACF;CACA,IAAI,EAAE,QAAQ;EACZ,MAAM,iBAAiB,KAAK,mBAAmB,QAC3C,QACA,KAAK,mBAAmB,UACtB,UACA;EACN,MAAM,WAAW,uBAAuB,cAAc,GAAG;GACvD,eAAe,KAAK;GACpB;EACF,CAAC;EACD,IAAI,CAAC,SAAS,WAAW,SAAS,QAChC,QAAQ,OAAO,MAAM,sBAAsB,SAAS,MAAM,CAAC;OACtD,IAAI,SAAS,YAAY,WAAW,SAAS,cAClD,QAAQ,OAAO,MAAM,uBAAuB,SAAS,YAAY,CAAC;EAEpE,QAAQ,WAAW;CACrB;AACF,CAAC;AAED,SAAgB,iCACd,YACA,OAA8E,CAAC,GACvE;CACR,MAAM,QAAkB,CAAC;CACzB,IAAI,KAAK,eAAe,MAAM,KAAK,oBAAoB,KAAK,cAAc,EAAE;CAC5E,IAAI,KAAK,gBAAgB,MAAM,KAAK,oBAAoB,KAAK,gBAAgB;CAC7E,OAAO,iBACL,YACA,CAAC,+BAA+B,GAAG,KAAK,CAAC,CAAC,KAAK,GAAG,CACpD;AACF"}
@@ -1 +1 @@
1
- export { n as internalMaxDispatchGuard } from "./internal-max-dispatch-guard-D7ByWH4v.js";
1
+ export { n as internalMaxDispatchGuard } from "./internal-max-dispatch-guard-CY8l9SDw.js";
@@ -1,7 +1,7 @@
1
1
  import { n as explicitPackageRoot, t as PACKAGE_ROOT_FLAG } from "./package-root-B-osctCk.js";
2
- import { f as stopReviewStateDir, n as fileFindingsStore } from "./stop-gate-policy-FGAfpfc-.js";
2
+ import { f as stopReviewStateDir, n as fileFindingsStore } from "./stop-gate-policy-CoR8xKNQ.js";
3
3
  import { r as hookMcpRuntimeFromEnv } from "./hook-mcp-client-DERIkeR7.js";
4
- import { a as runPlanReview, n as decidePlanReviewHook, r as filePlanReviewDebounce } from "./plan-review-hook-BQ29WGv7.js";
4
+ import { a as runPlanReview, n as decidePlanReviewHook, r as filePlanReviewDebounce } from "./plan-review-hook-CHK1wL3-.js";
5
5
  import { defineCommand } from "citty";
6
6
  import { mkdirSync, promises, readFileSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import path from "node:path";
@@ -118,4 +118,4 @@ const internalPlanReview = defineCommand({
118
118
  //#endregion
119
119
  export { internalPlanReview };
120
120
 
121
- //# sourceMappingURL=internal-plan-review-DIvaBBUd.js.map
121
+ //# sourceMappingURL=internal-plan-review-2OHTs8Nk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal-plan-review-DIvaBBUd.js","names":["fs"],"sources":["../src/internal-plan-review.ts"],"sourcesContent":["/**\n * The internal `internal-plan-review` subcommand: a PostToolUse(ExitPlanMode)\n * hook that spawns a bounded advisory critic review when the main agent finalizes\n * a substantive plan.\n *\n * It never blocks ExitPlanMode: the hook process exits 0 quickly after deciding\n * whether to spawn a detached reviewer. The detached child calls a cross-lab plan\n * critic and writes material findings to the SAME per-session findings store used\n * by the Stop review, so the next UserPromptSubmit surfaces them with the existing\n * non-authoritative findings path.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { spawn } from \"node:child_process\"\nimport { randomBytes } from \"node:crypto\"\nimport { mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\"\nimport { promises as fs } from \"node:fs\"\nimport path from \"node:path\"\n\nimport { PACKAGE_ROOT_FLAG, explicitPackageRoot } from \"./lib/package-root\"\n\nimport { hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n decidePlanReviewHook,\n filePlanReviewDebounce,\n runPlanReview,\n type PlanReviewSpawnContext,\n} from \"./lib/orchestration/plan-review-hook\"\nimport { fileFindingsStore, stopReviewStateDir } from \"./lib/orchestration/stop-gate-policy\"\n\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nasync function readDetachedPayload(): Promise<PlanReviewSpawnContext | undefined> {\n const payloadPath = (process.env.GH_ROUTER_PLAN_REVIEW_PAYLOAD ?? \"\").trim()\n if (payloadPath.length === 0) return undefined\n try {\n const raw = await fs.readFile(payloadPath, \"utf8\")\n await fs.unlink(payloadPath).catch(() => {})\n const parsed: unknown = JSON.parse(raw)\n if (!parsed || typeof parsed !== \"object\") return undefined\n const p = parsed as Partial<PlanReviewSpawnContext>\n if (!p.sessionId || !p.cwd || !p.plan || !p.planHash) return undefined\n return { sessionId: p.sessionId, cwd: p.cwd, plan: p.plan, planHash: p.planHash }\n } catch {\n await fs.unlink(payloadPath).catch(() => {})\n return undefined\n }\n}\n\nfunction spawnDetachedPlanReview(ctx: PlanReviewSpawnContext): void {\n let payloadPath: string | undefined\n try {\n const dir = stopReviewStateDir()\n mkdirSync(dir, { recursive: true })\n payloadPath = path.join(dir, `plan-review-${process.pid}-${randomBytes(4).toString(\"hex\")}.json`)\n writeFileSync(payloadPath, JSON.stringify(ctx), { mode: 0o600 })\n const scriptArgs = process.argv[1] && process.argv[1] !== process.execPath ? [process.argv[1]] : []\n const root = explicitPackageRoot()\n const packageRootArgs = root ? [PACKAGE_ROOT_FLAG, root] : []\n const child = spawn(process.execPath, [...scriptArgs, ...packageRootArgs, \"internal-plan-review\"], {\n detached: true,\n windowsHide: true,\n stdio: \"ignore\",\n env: { ...process.env, GH_ROUTER_PLAN_REVIEW_PAYLOAD: payloadPath },\n })\n const orphan = payloadPath\n child.on(\"error\", () => {\n if (orphan) {\n try {\n unlinkSync(orphan)\n } catch {\n /* best-effort */\n }\n }\n })\n child.unref()\n } catch {\n if (payloadPath) {\n try {\n unlinkSync(payloadPath)\n } catch {\n /* best-effort */\n }\n }\n }\n}\n\nexport const internalPlanReview = defineCommand({\n meta: {\n name: \"internal-plan-review\",\n description:\n \"Internal: advisory ExitPlanMode plan reviewer. Spawns a bounded detached critic review \"\n + \"for substantive plans and writes findings for the next prompt. Always exit 0.\",\n },\n async run() {\n try {\n const runtime = hookMcpRuntimeFromEnv()\n if (!runtime) return\n\n const detached = await readDetachedPayload()\n if (detached) {\n await runPlanReview({\n runtime,\n sessionId: detached.sessionId,\n cwd: detached.cwd,\n plan: detached.plan,\n findingsStore: fileFindingsStore(stopReviewStateDir()),\n })\n return\n }\n\n const decision = await decidePlanReviewHook({\n stdin: readStdin(),\n runtimeAvailable: true,\n debounce: filePlanReviewDebounce(stopReviewStateDir()),\n fallbackCwd: process.cwd(),\n })\n if (decision.kind === \"spawn\") spawnDetachedPlanReview(decision)\n } catch {\n /* side-effect only: never block ExitPlanMode */\n }\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,sBAAmE;CAChF,MAAM,eAAe,QAAQ,IAAI,iCAAiC,GAAA,CAAI,KAAK;CAC3E,IAAI,YAAY,WAAW,GAAG,OAAO,KAAA;CACrC,IAAI;EACF,MAAM,MAAM,MAAMA,SAAG,SAAS,aAAa,MAAM;EACjD,MAAMA,SAAG,OAAO,WAAW,CAAC,CAAC,YAAY,CAAC,CAAC;EAC3C,MAAM,SAAkB,KAAK,MAAM,GAAG;EACtC,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAO,KAAA;EAClD,MAAM,IAAI;EACV,IAAI,CAAC,EAAE,aAAa,CAAC,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,EAAE,UAAU,OAAO,KAAA;EAC7D,OAAO;GAAE,WAAW,EAAE;GAAW,KAAK,EAAE;GAAK,MAAM,EAAE;GAAM,UAAU,EAAE;EAAS;CAClF,QAAQ;EACN,MAAMA,SAAG,OAAO,WAAW,CAAC,CAAC,YAAY,CAAC,CAAC;EAC3C;CACF;AACF;AAEA,SAAS,wBAAwB,KA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jB,kBAAkB;IAClB,UAAU,uBAAuB,mBAAmB,CAAC;IACrD,aAAa,QAAQ,IAAI;GAC3B,CAAC;GACD,IAAI,SAAS,SAAS,SAAS,wBAAwB,QAAQ;EACjE,QAAQ,CAER;EACA,QAAQ,WAAW;CACrB;AACF,CAAC"}
1
+ {"version":3,"file":"internal-plan-review-2OHTs8Nk.js","names":["fs"],"sources":["../src/internal-plan-review.ts"],"sourcesContent":["/**\n * The internal `internal-plan-review` subcommand: a PostToolUse(ExitPlanMode)\n * hook that spawns a bounded advisory critic review when the main agent finalizes\n * a substantive plan.\n *\n * It never blocks ExitPlanMode: the hook process exits 0 quickly after deciding\n * whether to spawn a detached reviewer. The detached child calls a cross-lab plan\n * critic and writes material findings to the SAME per-session findings store used\n * by the Stop review, so the next UserPromptSubmit surfaces them with the existing\n * non-authoritative findings path.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { spawn } from \"node:child_process\"\nimport { randomBytes } from \"node:crypto\"\nimport { mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\"\nimport { promises as fs } from \"node:fs\"\nimport path from \"node:path\"\n\nimport { PACKAGE_ROOT_FLAG, explicitPackageRoot } from \"./lib/package-root\"\n\nimport { hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n decidePlanReviewHook,\n filePlanReviewDebounce,\n runPlanReview,\n type PlanReviewSpawnContext,\n} from \"./lib/orchestration/plan-review-hook\"\nimport { fileFindingsStore, stopReviewStateDir } from \"./lib/orchestration/stop-gate-policy\"\n\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nasync function readDetachedPayload(): Promise<PlanReviewSpawnContext | undefined> {\n const payloadPath = (process.env.GH_ROUTER_PLAN_REVIEW_PAYLOAD ?? \"\").trim()\n if (payloadPath.length === 0) return undefined\n try {\n const raw = await fs.readFile(payloadPath, \"utf8\")\n await fs.unlink(payloadPath).catch(() => {})\n const parsed: unknown = JSON.parse(raw)\n if (!parsed || typeof parsed !== \"object\") return undefined\n const p = parsed as Partial<PlanReviewSpawnContext>\n if (!p.sessionId || !p.cwd || !p.plan || !p.planHash) return undefined\n return { sessionId: p.sessionId, cwd: p.cwd, plan: p.plan, planHash: p.planHash }\n } catch {\n await fs.unlink(payloadPath).catch(() => {})\n return undefined\n }\n}\n\nfunction spawnDetachedPlanReview(ctx: PlanReviewSpawnContext): void {\n let payloadPath: string | undefined\n try {\n const dir = stopReviewStateDir()\n mkdirSync(dir, { recursive: true })\n payloadPath = path.join(dir, `plan-review-${process.pid}-${randomBytes(4).toString(\"hex\")}.json`)\n writeFileSync(payloadPath, JSON.stringify(ctx), { mode: 0o600 })\n const scriptArgs = process.argv[1] && process.argv[1] !== process.execPath ? [process.argv[1]] : []\n const root = explicitPackageRoot()\n const packageRootArgs = root ? [PACKAGE_ROOT_FLAG, root] : []\n const child = spawn(process.execPath, [...scriptArgs, ...packageRootArgs, \"internal-plan-review\"], {\n detached: true,\n windowsHide: true,\n stdio: \"ignore\",\n env: { ...process.env, GH_ROUTER_PLAN_REVIEW_PAYLOAD: payloadPath },\n })\n const orphan = payloadPath\n child.on(\"error\", () => {\n if (orphan) {\n try {\n unlinkSync(orphan)\n } catch {\n /* best-effort */\n }\n }\n })\n child.unref()\n } catch {\n if (payloadPath) {\n try {\n unlinkSync(payloadPath)\n } catch {\n /* best-effort */\n }\n }\n }\n}\n\nexport const internalPlanReview = defineCommand({\n meta: {\n name: \"internal-plan-review\",\n description:\n \"Internal: advisory ExitPlanMode plan reviewer. Spawns a bounded detached critic review \"\n + \"for substantive plans and writes findings for the next prompt. Always exit 0.\",\n },\n async run() {\n try {\n const runtime = hookMcpRuntimeFromEnv()\n if (!runtime) return\n\n const detached = await readDetachedPayload()\n if (detached) {\n await runPlanReview({\n runtime,\n sessionId: detached.sessionId,\n cwd: detached.cwd,\n plan: detached.plan,\n findingsStore: fileFindingsStore(stopReviewStateDir()),\n })\n return\n }\n\n const decision = await decidePlanReviewHook({\n stdin: readStdin(),\n runtimeAvailable: true,\n debounce: filePlanReviewDebounce(stopReviewStateDir()),\n fallbackCwd: process.cwd(),\n })\n if (decision.kind === \"spawn\") spawnDetachedPlanReview(decision)\n } catch {\n /* side-effect only: never block ExitPlanMode */\n }\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,sBAAmE;CAChF,MAAM,eAAe,QAAQ,IAAI,iCAAiC,GAAA,CAAI,KAAK;CAC3E,IAAI,YAAY,WAAW,GAAG,OAAO,KAAA;CACrC,IAAI;EACF,MAAM,MAAM,MAAMA,SAAG,SAAS,aAAa,MAAM;EACjD,MAAMA,SAAG,OAAO,WAAW,CAAC,CAAC,YAAY,CAAC,CAAC;EAC3C,MAAM,SAAkB,KAAK,MAAM,GAAG;EACtC,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAO,KAAA;EAClD,MAAM,IAAI;EACV,IAAI,CAAC,EAAE,aAAa,CAAC,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,EAAE,UAAU,OAAO,KAAA;EAC7D,OAAO;GAAE,WAAW,EAAE;GAAW,KAAK,EAAE;GAAK,MAAM,EAAE;GAAM,UAAU,EAAE;EAAS;CAClF,QAAQ;EACN,MAAMA,SAAG,OAAO,WAAW,CAAC,CAAC,YAAY,CAAC,CAAC;EAC3C;CACF;AACF;AAEA,SAAS,wBAAwB,KAAmC;CAClE,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,mBAAmB;EAC/B,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;EAClC,cAAc,KAAK,KAAK,KAAK,eAAe,QAAQ,IAAI,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,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-1,7 +1,7 @@
1
1
  import { a as parseBoolEnv } from "./exec-Bf8g_bIR.js";
2
- import { a as decidePromptSubmitV2, c as CHEAPEST_REWRITE_EFFORT, h as cheapestRewriteModelFor, i as decidePromptSubmit, t as buildStaticPack, u as isCheapestRewriteDisabledEnv } from "./static-context-pack-BRqt4ajJ.js";
3
- import { f as stopReviewStateDir, i as fileRebriefBindingStore, n as fileFindingsStore, o as fileRewriteFlagStore, r as fileLastPromptStore } from "./stop-gate-policy-FGAfpfc-.js";
4
- import { o as fileBlockBudget } from "./stop-gate-hook-BYd0NruJ.js";
2
+ import { a as decidePromptSubmitV2, c as CHEAPEST_REWRITE_EFFORT, h as cheapestRewriteModelFor, i as decidePromptSubmit, t as buildStaticPack, u as isCheapestRewriteDisabledEnv } from "./static-context-pack-dKrzbfIN.js";
3
+ import { f as stopReviewStateDir, i as fileRebriefBindingStore, n as fileFindingsStore, o as fileRewriteFlagStore, r as fileLastPromptStore } from "./stop-gate-policy-CoR8xKNQ.js";
4
+ import { o as fileBlockBudget } from "./stop-gate-hook-CC7VWkZM.js";
5
5
  import { n as callMcpTool, r as hookMcpRuntimeFromEnv, t as callInference } from "./hook-mcp-client-DERIkeR7.js";
6
6
  import { defineCommand } from "citty";
7
7
  import { readFileSync } from "node:fs";
@@ -191,4 +191,4 @@ const internalPromptSubmit = defineCommand({
191
191
  //#endregion
192
192
  export { internalPromptSubmit as t };
193
193
 
194
- //# sourceMappingURL=internal-prompt-submit-C77GnEaW.js.map
194
+ //# sourceMappingURL=internal-prompt-submit-CkfUcu34.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal-prompt-submit-C77GnEaW.js","names":[],"sources":["../src/internal-prompt-submit.ts"],"sourcesContent":["/**\n * The internal `internal-prompt-submit` subcommand: the executable a spawned\n * Claude Code session's `UserPromptSubmit` hook invokes (registered into the\n * mirrored settings.json by the launcher). It serves the front-end of the\n * floor-raising surface on one event:\n * 1. resets the Stop-gate's per-session block budget (making `maxBlocks`\n * per-prompt);\n * 2. stashes the prompt + surfaces the prior turn's advisory review findings;\n * 3. for a non-trivial prompt, injects a GROUNDED, user-derived scope/goal\n * note (one gpt-6-luna call at high effort over the prompt + grounding\n * code search — local ColBERT when --search is on, Bluebird when\n * --bluebird is on, lexical-only otherwise) — or, when the proxy URL/nonce\n * isn't wired or anything errors,\n * falls open to the v1 regex goal.\n * 4. on a cheapest-profile launch only, tries FIRST a Sol (gpt-5.6-sol,\n * medium) rewrite of the prompt into a short structured EXECUTION BRIEF over\n * the prompt + AGENTS.md/CLAUDE.md + repo structure + ecosystem's verify\n * command + grounding search\n * (adaptive 3 turns, up to 5 on Sol's deep-grounding flag) — additive,\n * never replacing the user prompt — and falls back to (3) on any miss.\n * One-shot per session (first non-trivial prompt only, marked on\n * attempt even if Sol fails open). Opt out with\n * GH_ROUTER_DISABLE_CHEAPEST_REWRITE=1.\n *\n * ALWAYS exits 0 (never blocks the prompt): the steer is additive context, and a\n * UserPromptSubmit hook that exit-2'd would refuse the user's prompt. The pure\n * v1 path (`decidePromptSubmit`) is the fail-open fallback; V2\n * (`decidePromptSubmitV2`) layers the grounded enrichment on top via injected IO.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { readFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport {\n CHEAPEST_REWRITE_EFFORT,\n isCheapestRewriteDisabledEnv,\n} from \"./lib/cheapest-prompt-rewrite\"\nimport { cheapestRewriteModelFor } from \"./lib/profile-family\"\nimport { parseBoolEnv } from \"./lib/exec\"\n// The verify-command ladder moved to `lib/static-context-pack` so the\n// server-side `prompt_brief` tool shares one implementation with this hook.\n// Re-exported because `internal-rebrief` and the buildStaticPack suites still\n// import it from this module.\nexport { buildStaticPack } from \"./lib/static-context-pack\"\nimport { buildStaticPack } from \"./lib/static-context-pack\"\nimport { callInference, callMcpTool, hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport { fileBlockBudget } from \"./lib/orchestration/stop-gate-hook\"\nimport {\n decidePromptSubmit,\n decidePromptSubmitV2,\n type PromptSubmitDecision,\n} from \"./lib/orchestration/prompt-submit-hook\"\nimport {\n fileFindingsStore,\n fileLastPromptStore,\n fileRebriefBindingStore,\n fileRewriteFlagStore,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\n\n/**\n * Read the hook payload from stdin SYNCHRONOUSLY (`readFileSync(0)`). An async\n * stdin read leaves an in-flight libuv FS request that, on Windows, races the\n * process teardown and trips a `uv_async_send` assertion; a synchronous read has\n * no such handle. Hooks always receive piped/redirected stdin, so this never\n * blocks (guarded against an interactive TTY, and any error -> \"\").\n */\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\n/** Parse the session cwd from the payload — the workspace the grounding search\n * runs in. Falls back to the process cwd. */\nfunction workspaceFromStdin(stdin: string): string {\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const cwd = (p as { cwd?: unknown }).cwd\n if (typeof cwd === \"string\" && cwd.length > 0) return cwd\n }\n } catch {\n /* fall through */\n }\n return process.cwd()\n}\n\n/** Per-call timeout for the grounding search (short — it must not stall the prompt). */\nconst SEARCH_TIMEOUT_MS = 8_000\n/** Per-call timeout for a single Sol/Luna inference. */\nconst INFER_TIMEOUT_MS = 25_000\n/**\n * Overall budget for the cheapest Sol rewrite (search + Sol, 3 turns default\n * with one adaptive extension to 5). The hook is registered with a 90s host\n * timeout. A rewrite timeout is TERMINAL — the orchestrator falls open to the\n * cheap regex goal and does NOT then run the Luna scope path — so the worst\n * case is one rewrite (≤30s) OR one Luna scope (≤22s), never both.\n */\nconst REWRITE_TIMEOUT_MS = 30_000\n\n\nexport const internalPromptSubmit = defineCommand({\n meta: {\n name: \"internal-prompt-submit\",\n description:\n \"Internal: the UserPromptSubmit hook. Resets the Stop-gate per-prompt block \"\n + \"budget, surfaces prior-turn review findings, and injects a grounded advisory goal \"\n + \"for non-trivial prompts. Always exit 0.\",\n },\n async run() {\n try {\n const stdin = readStdin()\n const steerEnabled = parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROMPT_STEER) !== true\n // Search capability for tip/enrichment text. The launcher exports\n // GH_ROUTER_SEARCH_ENABLED (\"1\"/\"0\") from its resolved\n // `state.searchEnabled` before spawning the session, so this\n // short-lived hook process inherits the launch's capability even when\n // the opt-in came from the `--search` CLI flag (which otherwise would\n // not survive the process boundary). Falls back to the raw opt-in env\n // for standalone invocations.\n const searchEnabled = process.env.GH_ROUTER_SEARCH_ENABLED !== undefined\n ? process.env.GH_ROUTER_SEARCH_ENABLED === \"1\"\n : process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === \"1\"\n const bluebirdEnabled = process.env.GH_ROUTER_BLUEBIRD_ENABLED === \"1\"\n const runtime = hookMcpRuntimeFromEnv()\n\n let decision: PromptSubmitDecision\n if (runtime) {\n const workspace = workspaceFromStdin(stdin)\n // Cheapest-family Sol rewrite identity: the launcher exports\n // GH_ROUTER_PROFILE; either family alias enables the rewrite branch\n // (checked again inside decidePromptSubmitV2), and each sibling\n // rewrites with its own advisor-tier Sol.\n const profile = (process.env.GH_ROUTER_PROFILE ?? \"\").trim().toLowerCase()\n const rewriteDisabled = isCheapestRewriteDisabledEnv()\n decision = await decidePromptSubmitV2({\n stdin,\n steerEnabled,\n searchEnabled,\n bluebirdEnabled,\n profile,\n rewriteDisabled,\n rewrite: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n inferSol: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: cheapestRewriteModelFor(profile),\n instructions: system,\n input: user,\n effort: CHEAPEST_REWRITE_EFFORT,\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n // Lazy: fs reads run only when the cheapest branch actually fires.\n staticPack: async () => buildStaticPack(workspace),\n // Session-keyed one-shot flag: first non-trivial prompt per\n // session spends the rewrite; later prompts use the Luna path.\n hasRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).hasRun(sid),\n markRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).markRun(sid),\n timeoutMs: REWRITE_TIMEOUT_MS,\n },\n io: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n infer: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: \"gpt-6-luna\",\n instructions: system,\n input: user,\n effort: \"high\",\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n readFindings: (sid) => fileFindingsStore(stopReviewStateDir()).read(sid),\n clearFindings: (sid) => fileFindingsStore(stopReviewStateDir()).clear(sid),\n storePrompt: (sid, prompt) => fileLastPromptStore(stopReviewStateDir()).write(sid, prompt),\n },\n })\n } else {\n // Proxy URL/nonce not wired -> the LLM layer is off; use the pure v1 path.\n decision = decidePromptSubmit({ stdin, steerEnabled })\n }\n\n // Per-workspace rebrief binding: the only way skill-spawned\n // internal-rebrief (no hook stdin) can locate the live transcript, the\n // session id (for findings), and the stored prompt. Refreshed on EVERY\n // prompt so it always tracks the current session, surviving /resume and\n // /clear within the session (same cwd key).\n try {\n const parsed = JSON.parse(stdin) as Record<string, unknown>\n const sid = typeof parsed.session_id === \"string\" ? parsed.session_id : \"\"\n const tp = typeof parsed.transcript_path === \"string\" ? parsed.transcript_path : \"\"\n if (sid && tp) {\n const ws = workspaceFromStdin(stdin)\n await fileRebriefBindingStore(stopReviewStateDir()).write({\n sessionId: sid,\n transcriptPath: tp,\n cwd: ws,\n atMs: Date.now(),\n }).catch(() => {})\n }\n } catch {\n /* binding refresh is best-effort */\n }\n\n if (decision.resetSession) {\n // Same budget store the Stop hook uses, so a new prompt clears its count.\n await fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\"))\n .reset(decision.resetSession)\n .catch(() => {})\n }\n if (decision.inject.length > 0) {\n await new Promise<void>((resolve) => process.stdout.write(`${decision.inject}\\n`, () => resolve()))\n }\n } catch {\n /* never let the front-end hook disrupt a prompt */\n }\n // Natural exit (exit code 0): a hard process.exit() races libuv stdio teardown\n // on Windows. No handles are kept alive once the (aborted) enrichment settles,\n // so returning lets the process exit cleanly with code 0.\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,SAAS,mBAAmB,OAAuB;CACjD,IAAI;EACF,MAAM,IAAa,KAAK,MAAM,KAAK;EACnC,IAAI,KAAK,OAAO,MAAM,UAAU;GAC9B,MAAM,MAAO,EAAwB;GACrC,IAAI,OAAO,QAAQ,YAAY,IAAI,SAAS,GAAG,OAAO;EACxD;CACF,QAAQ,CAER;CACA,OAAO,QAAQ,IAAI;AACrB;;AAGA,MAAM,oBAAoB;;AAE1B,MAAM,mBAAmB;;;;;;;;AAQzB,MAAM,qBAAqB;AAG3B,MAAa,uBAAuB,cAAc;CAChD,MAAM;EACJ,MAAM;EACN,aACE;CAGJ;CACA,MAAM,MAAM;EACV,IAAI;GACF,MAAM,QAAQ,UAAU;GACxB,MAAM,eAAe,aAAa,QAAQ,IAAI,8BAA8B,MAAM;GAQlF,MAAM,gBAAgB,QAAQ,IAAI,6BAA6B,KAAA,IAC3D,QAAQ,IAAI,6BAA6B,MACzC,QAAQ,IAAI,qCAAqC;GACrD,MAAM,kBAAkB,QAAQ,IAAI,+BAA+B;G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AC,KAAK,GAAG;MACvE,gBAAgB,QAAQ,kBAAkB,mBAAmB,CAAC,CAAC,CAAC,MAAM,GAAG;MACzE,cAAc,KAAK,WAAW,oBAAoB,mBAAmB,CAAC,CAAC,CAAC,MAAM,KAAK,MAAM;KAC3F;IACF,CAAC;GACH,OAEE,WAAW,mBAAmB;IAAE;IAAO;GAAa,CAAC;GAQvD,IAAI;IACF,MAAM,SAAS,KAAK,MAAM,KAAK;IAC/B,MAAM,MAAM,OAAO,OAAO,eAAe,WAAW,OAAO,aAAa;IACxE,MAAM,KAAK,OAAO,OAAO,oBAAoB,WAAW,OAAO,kBAAkB;IACjF,IAAI,OAAO,IAAI;KACb,MAAM,KAAK,mBAAmB,KAAK;KACnC,MAAM,wBAAwB,mBAAmB,CAAC,CAAC,CAAC,MAAM;MACxD,WAAW;MACX,gBAAgB;MAChB,KAAK;MACL,MAAM,KAAK,IAAI;KACjB,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;IACnB;GACF,QAAQ,CAER;GAEA,IAAI,SAAS,cAEX,MAAM,gBAAgB,KAAK,KAAK,OAAO,GAAG,oBAAoB,CAAC,CAAC,CAC7D,MAAM,SAAS,YAAY,CAAC,CAC5B,YAAY,CAAC,CAAC;GAEnB,IAAI,SAAS,OAAO,SAAS,GAC3B,MAAM,IAAI,SAAe,YAAY,QAAQ,OAAO,MAAM,GAAG,SAAS,OAAO,WAAW,QAAQ,CAAC,CAAC;EAEtG,QAAQ,CAER;EAIA,QAAQ,WAAW;CACrB;AACF,CAAC"}
1
+ {"version":3,"file":"internal-prompt-submit-CkfUcu34.js","names":[],"sources":["../src/internal-prompt-submit.ts"],"sourcesContent":["/**\n * The internal `internal-prompt-submit` subcommand: the executable a spawned\n * Claude Code session's `UserPromptSubmit` hook invokes (registered into the\n * mirrored settings.json by the launcher). It serves the front-end of the\n * floor-raising surface on one event:\n * 1. resets the Stop-gate's per-session block budget (making `maxBlocks`\n * per-prompt);\n * 2. stashes the prompt + surfaces the prior turn's advisory review findings;\n * 3. for a non-trivial prompt, injects a GROUNDED, user-derived scope/goal\n * note (one gpt-6-luna call at high effort over the prompt + grounding\n * code search — local ColBERT when --search is on, Bluebird when\n * --bluebird is on, lexical-only otherwise) — or, when the proxy URL/nonce\n * isn't wired or anything errors,\n * falls open to the v1 regex goal.\n * 4. on a cheapest-profile launch only, tries FIRST a Sol (gpt-5.6-sol,\n * medium) rewrite of the prompt into a short structured EXECUTION BRIEF over\n * the prompt + AGENTS.md/CLAUDE.md + repo structure + ecosystem's verify\n * command + grounding search\n * (adaptive 3 turns, up to 5 on Sol's deep-grounding flag) — additive,\n * never replacing the user prompt — and falls back to (3) on any miss.\n * One-shot per session (first non-trivial prompt only, marked on\n * attempt even if Sol fails open). Opt out with\n * GH_ROUTER_DISABLE_CHEAPEST_REWRITE=1.\n *\n * ALWAYS exits 0 (never blocks the prompt): the steer is additive context, and a\n * UserPromptSubmit hook that exit-2'd would refuse the user's prompt. The pure\n * v1 path (`decidePromptSubmit`) is the fail-open fallback; V2\n * (`decidePromptSubmitV2`) layers the grounded enrichment on top via injected IO.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { readFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport {\n CHEAPEST_REWRITE_EFFORT,\n isCheapestRewriteDisabledEnv,\n} from \"./lib/cheapest-prompt-rewrite\"\nimport { cheapestRewriteModelFor } from \"./lib/profile-family\"\nimport { parseBoolEnv } from \"./lib/exec\"\n// The verify-command ladder moved to `lib/static-context-pack` so the\n// server-side `prompt_brief` tool shares one implementation with this hook.\n// Re-exported because `internal-rebrief` and the buildStaticPack suites still\n// import it from this module.\nexport { buildStaticPack } from \"./lib/static-context-pack\"\nimport { buildStaticPack } from \"./lib/static-context-pack\"\nimport { callInference, callMcpTool, hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport { fileBlockBudget } from \"./lib/orchestration/stop-gate-hook\"\nimport {\n decidePromptSubmit,\n decidePromptSubmitV2,\n type PromptSubmitDecision,\n} from \"./lib/orchestration/prompt-submit-hook\"\nimport {\n fileFindingsStore,\n fileLastPromptStore,\n fileRebriefBindingStore,\n fileRewriteFlagStore,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\n\n/**\n * Read the hook payload from stdin SYNCHRONOUSLY (`readFileSync(0)`). An async\n * stdin read leaves an in-flight libuv FS request that, on Windows, races the\n * process teardown and trips a `uv_async_send` assertion; a synchronous read has\n * no such handle. Hooks always receive piped/redirected stdin, so this never\n * blocks (guarded against an interactive TTY, and any error -> \"\").\n */\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\n/** Parse the session cwd from the payload — the workspace the grounding search\n * runs in. Falls back to the process cwd. */\nfunction workspaceFromStdin(stdin: string): string {\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const cwd = (p as { cwd?: unknown }).cwd\n if (typeof cwd === \"string\" && cwd.length > 0) return cwd\n }\n } catch {\n /* fall through */\n }\n return process.cwd()\n}\n\n/** Per-call timeout for the grounding search (short — it must not stall the prompt). */\nconst SEARCH_TIMEOUT_MS = 8_000\n/** Per-call timeout for a single Sol/Luna inference. */\nconst INFER_TIMEOUT_MS = 25_000\n/**\n * Overall budget for the cheapest Sol rewrite (search + Sol, 3 turns default\n * with one adaptive extension to 5). The hook is registered with a 90s host\n * timeout. A rewrite timeout is TERMINAL — the orchestrator falls open to the\n * cheap regex goal and does NOT then run the Luna scope path — so the worst\n * case is one rewrite (≤30s) OR one Luna scope (≤22s), never both.\n */\nconst REWRITE_TIMEOUT_MS = 30_000\n\n\nexport const internalPromptSubmit = defineCommand({\n meta: {\n name: \"internal-prompt-submit\",\n description:\n \"Internal: the UserPromptSubmit hook. Resets the Stop-gate per-prompt block \"\n + \"budget, surfaces prior-turn review findings, and injects a grounded advisory goal \"\n + \"for non-trivial prompts. Always exit 0.\",\n },\n async run() {\n try {\n const stdin = readStdin()\n const steerEnabled = parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROMPT_STEER) !== true\n // Search capability for tip/enrichment text. The launcher exports\n // GH_ROUTER_SEARCH_ENABLED (\"1\"/\"0\") from its resolved\n // `state.searchEnabled` before spawning the session, so this\n // short-lived hook process inherits the launch's capability even when\n // the opt-in came from the `--search` CLI flag (which otherwise would\n // not survive the process boundary). Falls back to the raw opt-in env\n // for standalone invocations.\n const searchEnabled = process.env.GH_ROUTER_SEARCH_ENABLED !== undefined\n ? process.env.GH_ROUTER_SEARCH_ENABLED === \"1\"\n : process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === \"1\"\n const bluebirdEnabled = process.env.GH_ROUTER_BLUEBIRD_ENABLED === \"1\"\n const runtime = hookMcpRuntimeFromEnv()\n\n let decision: PromptSubmitDecision\n if (runtime) {\n const workspace = workspaceFromStdin(stdin)\n // Cheapest-family Sol rewrite identity: the launcher exports\n // GH_ROUTER_PROFILE; either family alias enables the rewrite branch\n // (checked again inside decidePromptSubmitV2), and each sibling\n // rewrites with its own advisor-tier Sol.\n const profile = (process.env.GH_ROUTER_PROFILE ?? \"\").trim().toLowerCase()\n const rewriteDisabled = isCheapestRewriteDisabledEnv()\n decision = await decidePromptSubmitV2({\n stdin,\n steerEnabled,\n searchEnabled,\n bluebirdEnabled,\n profile,\n rewriteDisabled,\n rewrite: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n inferSol: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: cheapestRewriteModelFor(profile),\n instructions: system,\n input: user,\n effort: CHEAPEST_REWRITE_EFFORT,\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n // Lazy: fs reads run only when the cheapest branch actually fires.\n staticPack: async () => buildStaticPack(workspace),\n // Session-keyed one-shot flag: first non-trivial prompt per\n // session spends the rewrite; later prompts use the Luna path.\n hasRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).hasRun(sid),\n markRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).markRun(sid),\n timeoutMs: REWRITE_TIMEOUT_MS,\n },\n io: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n infer: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: \"gpt-6-luna\",\n instructions: system,\n input: user,\n effort: \"high\",\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n readFindings: (sid) => fileFindingsStore(stopReviewStateDir()).read(sid),\n clearFindings: (sid) => fileFindingsStore(stopReviewStateDir()).clear(sid),\n storePrompt: (sid, prompt) => fileLastPromptStore(stopReviewStateDir()).write(sid, prompt),\n },\n })\n } else {\n // Proxy URL/nonce not wired -> the LLM layer is off; use the pure v1 path.\n decision = decidePromptSubmit({ stdin, steerEnabled })\n }\n\n // Per-workspace rebrief binding: the only way skill-spawned\n // internal-rebrief (no hook stdin) can locate the live transcript, the\n // session id (for findings), and the stored prompt. Refreshed on EVERY\n // prompt so it always tracks the current session, surviving /resume and\n // /clear within the session (same cwd key).\n try {\n const parsed = JSON.parse(stdin) as Record<string, unknown>\n const sid = typeof parsed.session_id === \"string\" ? parsed.session_id : \"\"\n const tp = typeof parsed.transcript_path === \"string\" ? parsed.transcript_path : \"\"\n if (sid && tp) {\n const ws = workspaceFromStdin(stdin)\n await fileRebriefBindingStore(stopReviewStateDir()).write({\n sessionId: sid,\n transcriptPath: tp,\n cwd: ws,\n atMs: Date.now(),\n }).catch(() => {})\n }\n } catch {\n /* binding refresh is best-effort */\n }\n\n if (decision.resetSession) {\n // Same budget store the Stop hook uses, so a new prompt clears its count.\n await fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\"))\n .reset(decision.resetSession)\n .catch(() => {})\n }\n if (decision.inject.length > 0) {\n await new Promise<void>((resolve) => process.stdout.write(`${decision.inject}\\n`, () => resolve()))\n }\n } catch {\n /* never let the front-end hook disrupt a prompt */\n }\n // Natural exit (exit code 0): a hard process.exit() races libuv stdio teardown\n // on Windows. No handles are kept alive once the (aborted) enrichment settles,\n // so returning lets the process exit cleanly with code 0.\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,SAAS,mBAAmB,OAAuB;CACjD,IAAI;EACF,MAAM,IAAa,KAAK,MAAM,KAAK;EACnC,IAAI,KAAK,OAAO,MAAM,UAAU;GAC9B,MAAM,MAAO,EAAwB;GACrC,IAAI,OAAO,QAAQ,YAAY,IAAI,SAAS,GAAG,OAAO;EACxD;CACF,QAAQ,CAER;CACA,OAAO,QAAQ,IAAI;AACrB;;AAGA,MAAM,oBAAoB;;AAE1B,MAAM,mBAAmB;;;;;;;;AAQzB,MAAM,qBAAqB;AAG3B,MAAa,uBAAuB,cAAc;CAChD,MAAM;EACJ,MAAM;EACN,aACE;CAGJ;CACA,MAAM,MAAM;EACV,IAAI;GACF,MAAM,QAAQ,UAAU;GACxB,MAAM,eAAe,aAAa,QAAQ,IAAI,8BAA8B,MAAM;GAQlF,MAAM,gBAAgB,QAAQ,IAAI,6BAA6B,KAAA,IAC3D,QAAQ,IAAI,6BAA6B,MACzC,QAAQ,IAAI,qCAAqC;GACrD,MAAM,kBAAkB,QAAQ,IAAI,+BAA+B;GACnE,MAAM,UAAU,sBAAsB;GAEtC,I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Q,kBAAkB,mBAAmB,CAAC,CAAC,CAAC,MAAM,GAAG;MACzE,cAAc,KAAK,WAAW,oBAAoB,mBAAmB,CAAC,CAAC,CAAC,MAAM,KAAK,MAAM;KAC3F;IACF,CAAC;GACH,OAEE,WAAW,mBAAmB;IAAE;IAAO;GAAa,CAAC;GAQvD,IAAI;IACF,MAAM,SAAS,KAAK,MAAM,KAAK;IAC/B,MAAM,MAAM,OAAO,OAAO,eAAe,WAAW,OAAO,aAAa;IACxE,MAAM,KAAK,OAAO,OAAO,oBAAoB,WAAW,OAAO,kBAAkB;IACjF,IAAI,OAAO,IAAI;KACb,MAAM,KAAK,mBAAmB,KAAK;KACnC,MAAM,wBAAwB,mBAAmB,CAAC,CAAC,CAAC,MAAM;MACxD,WAAW;MACX,gBAAgB;MAChB,KAAK;MACL,MAAM,KAAK,IAAI;KACjB,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;IACnB;GACF,QAAQ,CAER;GAEA,IAAI,SAAS,cAEX,MAAM,gBAAgB,KAAK,KAAK,OAAO,GAAG,oBAAoB,CAAC,CAAC,CAC7D,MAAM,SAAS,YAAY,CAAC,CAC5B,YAAY,CAAC,CAAC;GAEnB,IAAI,SAAS,OAAO,SAAS,GAC3B,MAAM,IAAI,SAAe,YAAY,QAAQ,OAAO,MAAM,GAAG,SAAS,OAAO,WAAW,QAAQ,CAAC,CAAC;EAEtG,QAAQ,CAER;EAIA,QAAQ,WAAW;CACrB;AACF,CAAC"}
@@ -1,2 +1,2 @@
1
- import "./static-context-pack-BRqt4ajJ.js";
2
- export { t as internalPromptSubmit } from "./internal-prompt-submit-C77GnEaW.js";
1
+ import "./static-context-pack-dKrzbfIN.js";
2
+ export { t as internalPromptSubmit } from "./internal-prompt-submit-CkfUcu34.js";
@@ -1,8 +1,8 @@
1
1
  import { a as parseBoolEnv } from "./exec-Bf8g_bIR.js";
2
- import { c as CHEAPEST_REWRITE_EFFORT, f as runCheapestRewrite, h as cheapestRewriteModelFor, l as buildRebriefSystem, n as PROMPT_STEER_GOAL, o as getPromptSearchTip, s as isNonTrivialPrompt, t as buildStaticPack, u as isCheapestRewriteDisabledEnv, v as isCheapestFamily } from "./static-context-pack-BRqt4ajJ.js";
3
- import { f as stopReviewStateDir, i as fileRebriefBindingStore, n as fileFindingsStore, r as fileLastPromptStore, s as isSubagentContext } from "./stop-gate-policy-FGAfpfc-.js";
2
+ import { c as CHEAPEST_REWRITE_EFFORT, f as runCheapestRewrite, h as cheapestRewriteModelFor, l as buildRebriefSystem, n as PROMPT_STEER_GOAL, o as getPromptSearchTip, s as isNonTrivialPrompt, t as buildStaticPack, u as isCheapestRewriteDisabledEnv, v as isCheapestFamily } from "./static-context-pack-dKrzbfIN.js";
3
+ import { f as stopReviewStateDir, i as fileRebriefBindingStore, n as fileFindingsStore, r as fileLastPromptStore, s as isSubagentContext } from "./stop-gate-policy-CoR8xKNQ.js";
4
4
  import { n as callMcpTool, r as hookMcpRuntimeFromEnv, t as callInference } from "./hook-mcp-client-DERIkeR7.js";
5
- import "./internal-prompt-submit-C77GnEaW.js";
5
+ import "./internal-prompt-submit-CkfUcu34.js";
6
6
  import { defineCommand } from "citty";
7
7
  import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from "node:fs";
8
8
  /** Char fallback when no tokenizer is available (~4 chars/token). */
@@ -545,4 +545,4 @@ const internalRebrief = defineCommand({
545
545
  //#endregion
546
546
  export { internalRebrief };
547
547
 
548
- //# sourceMappingURL=internal-rebrief-DZygfGHp.js.map
548
+ //# sourceMappingURL=internal-rebrief-EhBHAHsz.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal-rebrief-DZygfGHp.js","names":[],"sources":["../src/lib/cheapest-rebrief-context.ts","../src/internal-rebrief.ts"],"sourcesContent":["/**\n * On-demand cheapest rebrief context (`/gh-rebrief`): extractive, 4K-capped\n * recent-session excerpt for the Sol rewriter.\n *\n * Design (research-grounded, see docs/gh-rebrief.md):\n * - EXTRACTIVE ONLY: select verbatim spans, never rephrase or summarize.\n * Rephrasing breaks identifiers/paths/numbers and compounds drift across\n * compactions (CliffCompaction: truncate/drop, never rewrite; Paritok-4B:\n * 96% identifier fidelity via extraction).\n * - Never compact-a-compaction: each rebrief reads the live transcript tail,\n * never a prior brief.\n * - Priority order until the budget fills: operator focus (original ask,\n * pinned verbatim) > caller context (refined ask / last assistant brief)\n * > error tool results > Task/Agent/WebFetch summaries > last turns raw >\n * file:line cites.\n * - Pure + dependency-free so tests run with zero IO; the command layer\n * (`internal-rebrief`) owns file reads.\n */\n\n/** Token budget for the rebrief session excerpt (tokens, o200k heuristic). */\nexport const REBRIEF_MAX_TOKENS = 4_000 as const\n/** Char fallback when no tokenizer is available (~4 chars/token). */\nexport const REBRIEF_MAX_CHARS = 16_000 as const\n/** Max transcript JSONL lines scanned from the tail (bounded scan). */\nexport const REBRIEF_MAX_TAIL_LINES = 200 as const\n/** Per-excerpt line cap so one pathological turn cannot eat the budget. */\nexport const REBRIEF_PER_EXCERPT_LINES = 40 as const\n\nexport interface RebriefContextResult {\n /** Original ask, verbatim (pinned, never truncated by selection). */\n operatorFocus: string\n /** Refined ask (`$ARGUMENTS`) or last assistant brief, verbatim. */\n callerContext: string\n /** Prioritized, extractive session excerpt, capped. */\n sessionExcerpt: string\n /** Full `SESSION CONTEXT` block ready for `sessionContext` (capped). */\n sessionContext: string\n /** Number of transcript lines dropped by the budget. */\n truncatedLines: number\n /** True when any truncation occurred. */\n truncated: boolean\n}\n\ninterface TranscriptLine {\n /** Verbatim text span extracted from one JSONL line (\"\" = skip). */\n text: string\n /** Priority class: lower wins (0 = highest). */\n priority: number\n}\n\n/**\n * Extract one verbatim span from a Claude Code JSONL transcript line.\n * Returns null when the line carries no usable text. Never throws.\n */\nexport function extractTranscriptSpan(line: string): TranscriptLine | null {\n const trimmed = line.trim()\n if (trimmed.length === 0) return null\n let obj: unknown\n try {\n obj = JSON.parse(trimmed)\n } catch {\n // Non-JSON launch/log noise: keep short lines verbatim (they are often\n // error banners), drop long blobs.\n return trimmed.length <= 280\n ? { text: trimmed.slice(0, 280), priority: 4 }\n : null\n }\n if (!obj || typeof obj !== \"object\" || Array.isArray(obj)) return null\n const rec = obj as Record<string, unknown>\n // Skip subagent transcript lines (not this session's trajectory).\n if (rec.parent_tool_use_id !== undefined && rec.parent_tool_use_id !== null) {\n return null\n }\n const type = rec.type\n // `result` events: keep errors + summaries only (usage heartbeats are noise).\n if (type === \"result\") {\n const err = rec.is_error === true\n || (typeof rec.status === \"string\" && rec.status.toLowerCase().includes(\"error\"))\n const text = typeof rec.result === \"string\"\n ? rec.result\n : typeof rec.summary === \"string\"\n ? rec.summary\n : \"\"\n if (text.trim().length === 0) return null\n return {\n text: headLines(text.trim(), REBRIEF_PER_EXCERPT_LINES),\n priority: err ? 1 : 4,\n }\n }\n const msg = (rec as { message?: unknown }).message\n if (!msg || typeof msg !== \"object\" || Array.isArray(msg)) return null\n const m = msg as Record<string, unknown>\n const role = typeof m.role === \"string\" ? m.role : \"unknown\"\n const content = m.content\n if (typeof content === \"string\") {\n return content.trim().length > 0\n ? { text: headLines(content.trim(), REBRIEF_PER_EXCERPT_LINES), priority: role === \"user\" ? 3 : 3 }\n : null\n }\n if (!Array.isArray(content)) return null\n const spans: Array<{ text: string; priority: number }> = []\n for (const part of content) {\n if (!part || typeof part !== \"object\") continue\n const b = part as Record<string, unknown>\n if (b.type === \"text\" && typeof b.text === \"string\" && b.text.trim().length > 0) {\n spans.push({ text: b.text.trim(), priority: 3 })\n } else if (b.type === \"tool_use\") {\n const name = typeof b.name === \"string\" ? b.name : \"?\"\n // Bulk-input tools collapse to a path/size marker (advisor rule).\n if (name === \"Write\" || name === \"Edit\") {\n const serialized = JSON.stringify(b.input ?? {})\n // Keep the path — it is the load-bearing token (F7); elide the body.\n const inputObj = (b.input ?? {}) as Record<string, unknown>\n const filePath = typeof inputObj.file_path === \"string\"\n ? inputObj.file_path\n : typeof inputObj.file === \"string\"\n ? inputObj.file\n : typeof inputObj.path === \"string\"\n ? inputObj.path\n : \"\"\n const where = filePath ? ` ${filePath}` : \"\"\n spans.push({ text: `[tool_use ${name}${where}: ~${serialized.length} chars elided (bulk input)]`, priority: 5 })\n } else {\n const summary = summaryTools.has(name)\n const input = JSON.stringify(b.input ?? {}).slice(0, summary ? 2_000 : 500)\n spans.push({ text: `[tool_use ${name}: ${input}]`, priority: summary ? 2 : 4 })\n }\n } else if (b.type === \"tool_result\") {\n const raw = typeof b.content === \"string\" ? b.content : JSON.stringify(b.content ?? \"\")\n const err = b.is_error === true\n // Errors are prime rebrief signal; everything else is ordered by\n // recency. Deliberately no prose-vs-dump heuristic here: a char-run\n // test cannot tell pretty-printed JSON from prose, and summaries from\n // Task/Agent/WebFetch already win priority via their tool_use entries.\n spans.push({\n text: `[tool_result${err ? \" error=true\" : \"\"}]:\\n${headTail(raw.trim(), err ? 6_000 : 3_000)}`,\n priority: err ? 1 : 4,\n })\n }\n }\n if (spans.length === 0) return null\n spans.sort((a, b) => a.priority - b.priority)\n const best = spans[0]\n // Join same-priority spans so one line keeps its richest signal class.\n const same = spans.filter((s) => s.priority === best.priority).map((s) => s.text)\n return { text: headLines(same.join(\"\\n\"), REBRIEF_PER_EXCERPT_LINES), priority: best.priority }\n}\n\nconst summaryTools = new Set([\"Task\", \"Agent\", \"WebFetch\"])\n\nfunction headLines(text: string, maxLines: number): string {\n const lines = text.split(\"\\n\")\n if (lines.length <= maxLines) return text\n return `${lines.slice(0, maxLines).join(\"\\n\")}\\n…[${lines.length - maxLines} lines elided]…`\n}\n\nfunction headTail(text: string, maxChars: number): string {\n if (maxChars <= 0) return \"\"\n if (text.length <= maxChars) return text\n const head = Math.floor(maxChars / 2)\n const tail = maxChars - head\n return `${text.slice(0, head)}\\n…[elided]…\\n${text.slice(text.length - tail)}`\n}\n\n/** Rough token estimate (o200k ~4 chars/token) for budget selection. */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4)\n}\n\n/** Cap for the deterministic done-so-far digest (chars). */\nexport const REBRIEF_DIGEST_MAX_CHARS = 2_000 as const\n\n/**\n * Deterministic \"what has been done\" digest from a transcript tail:\n * extractive only, capped, never invents facts. Assistant text spans,\n * tool names used, files mutated (Write/Edit path markers), and error\n * results — the floor layer of the dual done-so-far. The Luna summary\n * consult (Layer 2, produced by the command layer) sits on top of this.\n */\nexport function buildDoneDigest(\n transcriptLines: ReadonlyArray<string>,\n maxChars: number = REBRIEF_DIGEST_MAX_CHARS,\n): string {\n const parts: Array<string> = []\n const paths = new Set<string>()\n const tools = new Set<string>()\n const texts: Array<string> = []\n const errors: Array<string> = []\n for (const line of transcriptLines) {\n const trimmed = line.trim()\n if (trimmed.length === 0) continue\n let obj: unknown\n try {\n obj = JSON.parse(trimmed)\n } catch {\n continue\n }\n if (!obj || typeof obj !== \"object\" || Array.isArray(obj)) continue\n const rec = obj as Record<string, unknown>\n if (rec.parent_tool_use_id !== undefined && rec.parent_tool_use_id !== null) continue\n if (rec.type === \"result\") {\n if (rec.is_error === true || (typeof rec.status === \"string\" && rec.status.toLowerCase().includes(\"error\"))) {\n errors.push(headTail(typeof rec.result === \"string\" ? rec.result : typeof rec.summary === \"string\" ? rec.summary : \"\", 400))\n }\n continue\n }\n const msg = (rec as { message?: unknown }).message\n if (!msg || typeof msg !== \"object\" || Array.isArray(msg)) continue\n const m = msg as Record<string, unknown>\n const role = typeof m.role === \"string\" ? m.role : \"unknown\"\n const content = m.content\n // Only the assistant's own statements belong in a \"what has been done\"\n // digest; user text would duplicate the current ask and could smuggle a\n // prompt-injection attempt into the done-so-far block Sol treats as\n // authoritative grounding.\n if (role !== \"assistant\") continue\n if (typeof content === \"string\") {\n if (content.trim().length > 0) texts.push(headLines(content.trim(), 8))\n continue\n }\n if (!Array.isArray(content)) continue\n for (const part of content) {\n if (!part || typeof part !== \"object\") continue\n const b = part as Record<string, unknown>\n if (b.type === \"text\" && typeof b.text === \"string\" && b.text.trim().length > 0) {\n texts.push(headLines(b.text.trim(), 8))\n } else if (b.type === \"tool_use\") {\n const name = typeof b.name === \"string\" ? b.name : \"?\"\n tools.add(name)\n if (name === \"Write\" || name === \"Edit\") {\n const inputObj = (b.input ?? {}) as Record<string, unknown>\n const filePath = typeof inputObj.file_path === \"string\"\n ? inputObj.file_path\n : typeof inputObj.file === \"string\"\n ? inputObj.file\n : typeof inputObj.path === \"string\"\n ? inputObj.path\n : \"\"\n if (filePath) paths.add(filePath)\n }\n } else if (b.type === \"tool_result\" && b.is_error === true) {\n const raw = typeof b.content === \"string\" ? b.content : JSON.stringify(b.content ?? \"\")\n errors.push(headTail(raw.trim(), 400))\n }\n }\n }\n if (tools.size > 0) parts.push(`Tools used: ${[...tools].sort().join(\", \")}`)\n if (paths.size > 0) parts.push(`Files mutated: ${[...paths].sort().join(\", \")}`)\n if (errors.length > 0) parts.push(`Errors:\\n${errors.join(\"\\n---\\n\")}`)\n if (texts.length > 0) parts.push(`Assistant text (recent):\\n${texts.slice(-6).join(\"\\n---\\n\")}`)\n const joined = parts.join(\"\\n\\n\")\n return joined.length <= maxChars ? joined : `${joined.slice(0, maxChars).trimEnd()}\\n…[digest truncated]…`\n}\n\n/**\n * Build the capped 4K rebrief context from a transcript tail.\n * Pure: caller supplies lines (already tail-sliced) + prompts.\n */\nexport function buildRebriefContext(input: {\n transcriptLines: ReadonlyArray<string>\n originalAsk?: string\n refinedAsk?: string\n lastAssistantBrief?: string\n /** Dual-layer done-so-far block (deterministic digest + Luna summary). */\n doneSoFar?: string\n maxTokens?: number\n}): RebriefContextResult {\n const maxTokens = input.maxTokens ?? REBRIEF_MAX_TOKENS\n const maxChars = maxTokens * 4\n const operatorFocus = (input.originalAsk ?? \"\").trim()\n const callerContext = (input.refinedAsk ?? \"\").trim()\n || (input.lastAssistantBrief ?? \"\").trim()\n const doneSoFar = (input.doneSoFar ?? \"\").trim()\n // The pinned blocks are inviolable: the excerpt gets whatever budget is\n // left AFTER them (plus fixed labels), never the reverse. A huge ask\n // shrinks the excerpt to zero rather than being sliced itself (B6.1).\n const askBlock = operatorFocus.length > 0 ? `Original ask (authoritative):\\n${operatorFocus}` : \"\"\n const callerBlock = callerContext.length > 0 ? `Current focus:\\n${callerContext}` : \"\"\n const doneBlock = doneSoFar.length > 0 ? `Done so far:\\n${doneSoFar}` : \"\"\n const reserved = askBlock.length + callerBlock.length + doneBlock.length + 256 // labels + truncation notice headroom\n let budget = Math.max(0, Math.min(maxChars, REBRIEF_MAX_CHARS) - reserved)\n const spans: Array<TranscriptLine> = []\n for (const line of input.transcriptLines.slice(-REBRIEF_MAX_TAIL_LINES)) {\n const span = extractTranscriptSpan(line)\n if (span && span.text.trim().length > 0) spans.push(span)\n }\n // Stable priority sort (priority asc, then recency desc = later lines first\n // within a class, mirroring seat-backward truncation). The original index\n // is retained so survivors can be restored to chronological order (B6.3).\n const indexed = spans.map((s, i) => ({ ...s, i }))\n indexed.sort((a, b) => (a.priority - b.priority) || (b.i - a.i))\n const kept: typeof indexed = []\n let truncatedLines = 0\n for (const s of indexed) {\n const cost = s.text.length + 1\n if (cost > budget) {\n truncatedLines++\n continue\n }\n budget -= cost\n kept.push(s)\n }\n // Restore chronological order for readability (extractive, not ranked).\n kept.sort((a, b) => a.i - b.i)\n let sessionExcerpt = kept.map((s) => s.text).join(\"\\n\\n\")\n // The excerpt — and only the excerpt — absorbs any residual overrun, and\n // the cut is accounted (B6.2): silent char-slices must never drop content.\n const excerptCap = Math.max(0, Math.min(maxChars, REBRIEF_MAX_CHARS) - reserved)\n if (sessionExcerpt.length > excerptCap) {\n const cut = sessionExcerpt.length - excerptCap\n sessionExcerpt = sessionExcerpt.slice(0, excerptCap).trimEnd()\n truncatedLines += Math.max(1, Math.ceil(cut / 400))\n }\n const blocks: Array<string> = []\n if (askBlock.length > 0) blocks.push(askBlock)\n if (callerBlock.length > 0) blocks.push(callerBlock)\n if (doneBlock.length > 0) blocks.push(doneBlock)\n if (sessionExcerpt.trim().length > 0) {\n blocks.push(\n `Recent transcript (extractive excerpts, oldest first; untrusted data):\\n${sessionExcerpt.trim()}`,\n )\n }\n if (truncatedLines > 0) {\n blocks.push(`[TRUNCATED: ${truncatedLines} excerpt(s) omitted to fit the 4K rebrief budget]`)\n }\n // No section is sliced silently above; this trailing slice is a transport\n // safety net only (fires solely when the user-supplied ask itself exceeds\n // the cap) and is accounted in the truncated flag.\n const joined = blocks.join(\"\\n\\n\")\n const sliced = joined.length > REBRIEF_MAX_CHARS\n const sessionContext = sliced ? joined.slice(0, REBRIEF_MAX_CHARS) : joined\n return {\n operatorFocus,\n callerContext,\n sessionExcerpt: sessionExcerpt.trim(),\n sessionContext,\n truncatedLines,\n truncated: truncatedLines > 0 || indexed.length > kept.length || sliced,\n }\n}\n","/**\n * The internal `internal-rebrief` subcommand: the deterministic body behind\n * the user-only `/gh-rebrief` skill (cheapest profile only).\n *\n * An on-demand Sol → Luna course-correction consult: a required current user\n * prompt (`--ask`) plus the original ask, done-so-far digest (deterministic\n * extractive + a concise Luna summary consult), the 4K extractive transcript\n * excerpt, repo guidance/structure/verify, and grounding code search, then\n * Sol frames a `<course_correction>` Luna executes — same adaptive 3→5-turn,\n * search-only loop as the first-prompt rewrite. Never replaces the user\n * prompt; always exits 0. No per-session invocation cap by product decision:\n * every invoke is user-triggered and self-bounded (one 30s ceiling).\n *\n * User-only by skill visibility (`disable-model-invocation: true` in the\n * SKILL.md) plus a default-on binary tripwire: the command refuses unless\n * `GH_ROUTER_REBRIEF_USER_INVOKED=1` (set by the skill wrapper; opt out with\n * `GH_ROUTER_REBRIEF_REQUIRE_USER_INVOKED=0`). Per-invoke ceiling: at most\n * two Sol inferences (one initial + one extension), one Luna summary, and one\n * 30s wall-clock deadline.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from \"node:fs\"\n\nimport { buildStaticPack } from \"./internal-prompt-submit\"\nimport { cheapestRewriteModelFor, isCheapestFamily } from \"./lib/profile-family\"\nimport {\n buildDoneDigest,\n buildRebriefContext,\n REBRIEF_MAX_TAIL_LINES,\n} from \"./lib/cheapest-rebrief-context\"\nimport {\n buildRebriefSystem,\n CHEAPEST_REWRITE_EFFORT,\n isCheapestRewriteDisabledEnv,\n} from \"./lib/cheapest-prompt-rewrite\"\nimport { parseBoolEnv } from \"./lib/exec\"\nimport { callInference, callMcpTool, hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n getPromptSearchTip,\n isNonTrivialPrompt,\n PROMPT_STEER_GOAL,\n} from \"./lib/orchestration/prompt-submit-hook\"\nimport {\n fileFindingsStore,\n fileLastPromptStore,\n fileRebriefBindingStore,\n isSubagentContext,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\nimport { runCheapestRewrite } from \"./lib/cheapest-prompt-rewrite\"\n\nconst SEARCH_TIMEOUT_MS = 8_000\nconst INFER_TIMEOUT_MS = 25_000\nconst REWRITE_TIMEOUT_MS = 30_000\n\n/** Hard-gate env: the binary refuses without the user marker — ON by default\n * (opt OUT with `GH_ROUTER_REBRIEF_REQUIRE_USER_INVOKED=0`), so a guessed\n * binary name alone never spends. The skill wrapper always sets the marker.\n * Residual: the marker is an env var, so this is a tripwire, not a sandbox —\n * see docs/gh-rebrief.md. */\nexport function isRebriefHardGateEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n const v = (env.GH_ROUTER_REBRIEF_REQUIRE_USER_INVOKED ?? \"\").trim().toLowerCase()\n if (v === \"\") return true\n return v !== \"0\" && v !== \"false\" && v !== \"no\" && v !== \"off\"\n}\n\n/** User-invocation marker the skill wrapper sets (soft by default). */\nexport function isRebriefUserInvoked(env: NodeJS.ProcessEnv = process.env): boolean {\n const v = (env.GH_ROUTER_REBRIEF_USER_INVOKED ?? \"\").trim().toLowerCase()\n return v === \"1\" || v === \"true\"\n}\n\n/** Cheapest-family gate (either alias, lowercased). Exported for tests. */\nexport function isRebriefProfileEligible(profile: string | undefined): boolean {\n return isCheapestFamily((profile ?? \"\").trim().toLowerCase())\n}\n\nexport interface RebriefPayload {\n sessionId: string\n prompt: string\n transcriptPath: string\n cwd: string\n isSubagent: boolean\n}\n\n/** Parse a hook-style stdin payload. Never throws. Exported for tests. */\nexport function decodeRebriefPayload(stdin: string): RebriefPayload {\n let raw: Record<string, unknown> = {}\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") raw = p as Record<string, unknown>\n } catch {\n /* fall through with empty payload */\n }\n return {\n sessionId: typeof raw.session_id === \"string\" ? raw.session_id : \"\",\n prompt: typeof raw.prompt === \"string\" ? raw.prompt : \"\",\n transcriptPath: typeof raw.transcript_path === \"string\" ? raw.transcript_path : \"\",\n cwd: typeof raw.cwd === \"string\" && raw.cwd.length > 0 ? raw.cwd : process.cwd(),\n isSubagent: isSubagentContext(raw),\n }\n}\n\n/**\n * Resolve the effective prompt: explicit `--ask` wins, then the hook prompt,\n * then the last-prompt store. Exported for tests.\n */\nexport function resolveRebriefPrompt(input: {\n ask?: string\n hookPrompt?: string\n storedPrompt?: string | null\n}): string {\n const ask = (input.ask ?? \"\").trim()\n if (ask.length > 0) return ask\n const hook = (input.hookPrompt ?? \"\").trim()\n if (hook.length > 0) return hook\n return (input.storedPrompt ?? \"\").trim()\n}\n\n/** Read the last N non-empty lines of a file, byte-capped (F6).\n * Never loads more than `maxBytes` (default 1 MiB) — transcripts can be\n * tens of MB and this runs inside a 30s budget. Never throws. */\nexport function readTranscriptTail(\n transcriptPath: string,\n maxLines: number,\n maxBytes = 1_048_576,\n): Array<string> {\n try {\n if (!transcriptPath || !existsSync(transcriptPath)) return []\n const size = statSync(transcriptPath).size\n if (size <= 0) return []\n let raw: string\n if (size <= maxBytes) {\n raw = readFileSync(transcriptPath, \"utf8\")\n } else {\n const fd = openSync(transcriptPath, \"r\")\n try {\n const buf = Buffer.alloc(maxBytes)\n const read = readSync(fd, buf, 0, maxBytes, size - maxBytes)\n raw = buf.subarray(0, read).toString(\"utf8\")\n } finally {\n try {\n closeSync(fd)\n } catch {\n /* best-effort close; the process is short-lived either way */\n }\n }\n }\n if (raw.length === 0) return []\n return raw.split(\"\\n\").slice(-Math.max(1, maxLines) * 2).filter((l) => l.trim().length > 0).slice(-Math.max(1, maxLines))\n } catch {\n return []\n }\n}\n\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nexport const internalRebrief = defineCommand({\n meta: {\n name: \"internal-rebrief\",\n description:\n \"Internal: on-demand cheapest rebrief. Re-runs the Sol grounded execution brief \"\n + \"with 4K compressed recent context. Cheapest profile only, user-invoked. Always exits 0.\",\n },\n args: {\n ask: {\n type: \"string\",\n description: \"Optional refined ask ($ARGUMENTS from /gh-rebrief). Wins over the stored prompt.\",\n required: false,\n },\n },\n async run({ args }) {\n try {\n const stdin = readStdin()\n const payload = decodeRebriefPayload(stdin)\n // No path/session overrides (B4/B5) — the CLI pass-through is --ask only.\n let transcriptPath = payload.transcriptPath\n const workspace = payload.cwd\n // When invoked by the SKILL's Bash step there is NO hook stdin, so the\n // payload is empty. Fall back to the per-workspace binding the\n // UserPromptSubmit hook refreshes on every prompt — this is the only\n // intended way the rebrief command can find the live transcript +\n // session id without being passed one explicitly. If binding is stale\n // or absent, transcript context is empty by design (the consult still\n // runs on static pack + search facts).\n let bindingSessionId = \"\"\n if (payload.sessionId.length === 0 || payload.transcriptPath.length === 0) {\n const binding = await fileRebriefBindingStore(stopReviewStateDir())\n .read(workspace)\n .catch(() => null)\n if (binding) {\n if (payload.sessionId.length === 0) bindingSessionId = binding.sessionId\n if (payload.transcriptPath.length === 0) transcriptPath = binding.transcriptPath\n }\n }\n const effectiveSessionId = payload.sessionId.length > 0 ? payload.sessionId : bindingSessionId\n const profile = (process.env.GH_ROUTER_PROFILE ?? \"\").trim().toLowerCase()\n const runtime = hookMcpRuntimeFromEnv()\n const searchEnabled = process.env.GH_ROUTER_SEARCH_ENABLED !== undefined\n ? process.env.GH_ROUTER_SEARCH_ENABLED === \"1\"\n : process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === \"1\"\n const bluebirdEnabled = process.env.GH_ROUTER_BLUEBIRD_ENABLED === \"1\"\n const searchTip = getPromptSearchTip(searchEnabled, bluebirdEnabled)\n const emit = async (text: string): Promise<void> => {\n if (text.trim().length === 0) return\n await new Promise<void>((resolve) => process.stdout.write(`${text}\\n`, () => resolve()))\n }\n\n // Hard gate (default-on, B1): refuse guessed-binary self-invocation.\n // Tripwire, not sandbox (the marker is env-settable) — the skill\n // wrapper always sets it; direct shell use must too.\n if (isRebriefHardGateEnabled() && !isRebriefUserInvoked()) {\n await emit(\n \"Rebrief refused: user invocation required \"\n + \"(GH_ROUTER_REBRIEF_USER_INVOKED=1). Invoke via /gh-rebrief.\",\n )\n process.exitCode = 0\n return\n }\n // Cheapest-only: point elsewhere rather than spending.\n if (!isRebriefProfileEligible(profile)) {\n await emit(\n \"Rebrief is a cheapest-profile command; this session is \"\n + `'${profile || \"unknown\"}'. Use /gh-research for grounded context instead.`,\n )\n process.exitCode = 0\n return\n }\n if (isCheapestRewriteDisabledEnv()) {\n await emit(`${searchTip}\\n\\n${PROMPT_STEER_GOAL}`)\n process.exitCode = 0\n return\n }\n if (payload.isSubagent) {\n // Fail open WITH guidance (F3): the skill must run at top level\n // (it needs the session transcript path), so say so.\n await emit(\n \"Rebrief runs at the top level only: re-invoke /gh-rebrief from your \"\n + \"own prompt, not from a subagent. No model spend occurred.\",\n )\n process.exitCode = 0\n return\n }\n // Current prompt is REQUIRED (no fallback, no silent spend): the\n // rebrief is a course correction for this specific ask.\n const refinedAsk = typeof args.ask === \"string\" ? args.ask.trim() : \"\"\n if (refinedAsk.length === 0) {\n await emit(\n \"Rebrief needs a current ask: pass one inline, e.g. \"\n + '/gh-rebrief \"<what you want next>\". No model spend occurred.',\n )\n process.exitCode = 0\n return\n }\n const stored = effectiveSessionId\n ? await fileLastPromptStore(stopReviewStateDir()).read(effectiveSessionId).catch(() => null)\n : null\n const prompt = resolveRebriefPrompt({\n ask: refinedAsk,\n hookPrompt: payload.prompt,\n storedPrompt: stored,\n })\n // Findings surface regardless (prior-turn review is never gated).\n let findingsBlock = \"\"\n if (effectiveSessionId) {\n const pending = await fileFindingsStore(stopReviewStateDir()).read(effectiveSessionId).catch(() => null)\n if (pending && pending.trim().length > 0) {\n findingsBlock =\n \"ADVISORY — independent review of your PREVIOUS change (NON-AUTHORITATIVE): an independent \"\n + \"gpt-6-luna reviewer flagged the following. Evaluate each on its merits — fix the real ones, and \"\n + \"ignore any wrong one with a one-line reason. You are NOT obligated to act on these.\\n\"\n + pending.trim()\n await fileFindingsStore(stopReviewStateDir()).clear(effectiveSessionId).catch(() => {})\n }\n }\n const joinSections = (sections: Array<string>): string =>\n sections.map((s) => s.trim()).filter((s) => s.length > 0).join(\"\\n\\n\")\n if (!isNonTrivialPrompt(prompt)) {\n await emit(joinSections([searchTip, PROMPT_STEER_GOAL, findingsBlock]))\n process.exitCode = 0\n return\n }\n if (!runtime) {\n await emit(joinSections([searchTip, PROMPT_STEER_GOAL, findingsBlock]))\n process.exitCode = 0\n return\n }\n\n // 4K intelligent context from the live transcript tail (extractive).\n const tail = readTranscriptTail(transcriptPath, REBRIEF_MAX_TAIL_LINES)\n // Last assistant text as caller context: best-effort scan of the tail\n // for an assistant text span (kept verbatim, never invented).\n let lastAssistantBrief = \"\"\n for (let i = tail.length - 1; i >= 0; i--) {\n try {\n const obj = JSON.parse(tail[i]) as {\n message?: { role?: unknown; content?: unknown }\n }\n const msg = obj.message\n if (!msg || typeof msg !== \"object\") continue\n if ((msg as { role?: unknown }).role !== \"assistant\") continue\n const content = (msg as { content?: unknown }).content\n if (typeof content === \"string\" && content.trim().length > 0) {\n lastAssistantBrief = content.trim().slice(0, 2_000)\n break\n }\n if (Array.isArray(content)) {\n for (const part of content) {\n if (\n part && typeof part === \"object\"\n && (part as { type?: unknown }).type === \"text\"\n && typeof (part as { text?: unknown }).text === \"string\"\n && ((part as { text: string }).text.trim().length > 0)\n ) {\n lastAssistantBrief = (part as { text: string }).text.trim().slice(0, 2_000)\n break\n }\n }\n if (lastAssistantBrief) break\n }\n } catch {\n /* non-JSON line — skip */\n }\n }\n const digest = buildDoneDigest(tail)\n // Layer 2: a concise Luna consult over the same tail (fail-open to the\n // deterministic digest when absent/errored). Two independent layers =\n // reproducible floor + intent-level compression.\n let lunaSummary = \"\"\n try {\n const summaryTranscript = tail.slice(-120).join(\"\\n\").slice(-12_000)\n lunaSummary = (await callInference({\n serverUrl: runtime.serverUrl,\n model: \"gpt-6-luna\",\n instructions:\n \"You are summarizing a coding session for a course correction. Answer in <=2K characters: what is done and verifiable, what is blocked/open, and what the last ask was. Extractive only — never invent facts; prefer file:line references seen in the transcript.\",\n input: `USER ASK:\\n${prompt}\\n\\nTRANSCRIPT:\\n${summaryTranscript}`,\n effort: \"high\",\n timeoutMs: INFER_TIMEOUT_MS,\n })).trim().slice(0, 2_048)\n } catch {\n lunaSummary = \"\"\n }\n const doneSoFar = [\n digest.trim().length > 0 ? `DETERMINISTIC DIGEST:\\n${digest.trim()}` : \"\",\n lunaSummary.trim().length > 0 ? `LUNA STATE SUMMARY (<=2K, advisory):\\n${lunaSummary.trim()}` : \"\",\n ]\n .filter((s) => s.length > 0)\n .join(\"\\n\\n\")\n const rebrief = buildRebriefContext({\n transcriptLines: tail,\n originalAsk: stored ?? payload.prompt,\n refinedAsk: refinedAsk,\n lastAssistantBrief,\n doneSoFar,\n })\n const statik = await (async () => {\n try {\n return buildStaticPack(workspace)\n } catch {\n return { agentsMd: \"\", claudeMd: \"\", repoStructure: \"\", verifyCommand: \"\" }\n }\n })()\n\n const result = await runCheapestRewrite({\n prompt,\n searchEnabled,\n bluebirdEnabled,\n sessionContext: rebrief.sessionContext,\n io: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n inferSol: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: cheapestRewriteModelFor(profile),\n instructions: system,\n input: user,\n effort: CHEAPEST_REWRITE_EFFORT,\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n staticPack: async () => statik,\n hasRewriteRun: async () => false,\n markRewriteRun: async () => {},\n timeoutMs: REWRITE_TIMEOUT_MS,\n buildSystemPrompt: buildRebriefSystem,\n },\n }).catch(() => ({ brief: null as string | null, timedOut: false }))\n if (result.brief && result.brief.length > 0) {\n await emit(joinSections([searchTip, result.brief, findingsBlock]))\n } else {\n // Clean miss AND timeout both fall open to the cheap regex goal here:\n // unlike the first-prompt hook there is no Luna scope path to preserve\n // spend for — the user explicitly asked for a rebrief.\n const steerEnabled = parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROMPT_STEER) !== true\n await emit(joinSections([searchTip, steerEnabled ? PROMPT_STEER_GOAL : \"\", findingsBlock]))\n }\n } catch {\n /* never disrupt the session */\n }\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;AAsBA,MAAa,oBAAoB;;;;;AAgCjC,SAAgB,sBAAsB,MAAqC;CACzE,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,QAAQ,WAAW,GAAG,OAAO;CACjC,IAAI;CACJ,IAAI;EACF,MAAM,KAAK,MAAM,OAAO;CAC1B,QAAQ;EAGN,OAAO,QAAQ,UAAU,MACrB;GAAE,MAAM,QAAQ,MAAM,GAAG,GAAG;GAAG,UAAU;EAAE,IAC3C;CACN;CACA,IAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,GAAG,OAAO;CAClE,MAAM,MAAM;CAEZ,IAAI,IAAI,uBAAuB,KAAA,KAAa,IAAI,uBAAuB,MACrE,OAAO;CAIT,IAFa,IAAI,SAEJ,UAAU;EACrB,MAAM,MAAM,IAAI,aAAa,QACvB,OAAO,IAAI,WAAW,YAAY,IAAI,OAAO,YAAY,CAAC,CAAC,SAAS,OAAO;EAC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AY;IAChC,IAAI;KACF,OAAO,gBAAgB,SAAS;IAClC,QAAQ;KACN,OAAO;MAAE,UAAU;MAAI,UAAU;MAAI,eAAe;MAAI,eAAe;KAAG;IAC5E;GACF,EAAA,CAAG;GAEH,MAAM,SAAS,MAAM,mBAAmB;IACtC;IACA;IACA;IACA,gBAAgB,QAAQ;IACxB,IAAI;KACF,YAAY,OAAO,OAAO,MAAM,WAAW;MACzC,MAAM,IAAI,MAAM,YAAY;OAC1B;OACA,OAAO;OACP,MAAM;OACN,MAAM;QAAE;QAAO;QAAW;QAAM,OAAO;QAAI,SAAS;OAAM;OAC1D,WAAW;OACX;MACF,CAAC;MACD,OAAO,EAAE,UAAU,KAAK,EAAE;KAC5B;KACA,WAAW,QAAQ,MAAM,WACvB,cAAc;MACZ,WAAW,QAAQ;MACnB,OAAO,wBAAwB,OAAO;MACtC,cAAc;MACd,OAAO;MACP,QAAQ;MACR,WAAW;MACX;KACF,CAAC;KACH,YAAY,YAAY;KACxB,eAAe,YAAY;KAC3B,gBAAgB,YAAY,CAAC;KAC7B,WAAW;KACX,mBAAmB;IACrB;GACF,CAAC,CAAC,CAAC,aAAa;IAAE,OAAO;IAAuB,UAAU;GAAM,EAAE;GAClE,IAAI,OAAO,SAAS,OAAO,MAAM,SAAS,GACxC,MAAM,KAAK,aAAa;IAAC;IAAW,OAAO;IAAO;GAAa,CAAC,CAAC;QAMjE,MAAM,KAAK,aAAa;IAAC;IADJ,aAAa,QAAQ,IAAI,8BAA8B,MAAM,OAC/B,oBAAoB;IAAI;GAAa,CAAC,CAAC;EAE9F,QAAQ,CAER;EACA,QAAQ,WAAW;CACrB;AACF,CAAC"}
1
+ {"version":3,"file":"internal-rebrief-EhBHAHsz.js","names":[],"sources":["../src/lib/cheapest-rebrief-context.ts","../src/internal-rebrief.ts"],"sourcesContent":["/**\n * On-demand cheapest rebrief context (`/gh-rebrief`): extractive, 4K-capped\n * recent-session excerpt for the Sol rewriter.\n *\n * Design (research-grounded, see docs/gh-rebrief.md):\n * - EXTRACTIVE ONLY: select verbatim spans, never rephrase or summarize.\n * Rephrasing breaks identifiers/paths/numbers and compounds drift across\n * compactions (CliffCompaction: truncate/drop, never rewrite; Paritok-4B:\n * 96% identifier fidelity via extraction).\n * - Never compact-a-compaction: each rebrief reads the live transcript tail,\n * never a prior brief.\n * - Priority order until the budget fills: operator focus (original ask,\n * pinned verbatim) > caller context (refined ask / last assistant brief)\n * > error tool results > Task/Agent/WebFetch summaries > last turns raw >\n * file:line cites.\n * - Pure + dependency-free so tests run with zero IO; the command layer\n * (`internal-rebrief`) owns file reads.\n */\n\n/** Token budget for the rebrief session excerpt (tokens, o200k heuristic). */\nexport const REBRIEF_MAX_TOKENS = 4_000 as const\n/** Char fallback when no tokenizer is available (~4 chars/token). */\nexport const REBRIEF_MAX_CHARS = 16_000 as const\n/** Max transcript JSONL lines scanned from the tail (bounded scan). */\nexport const REBRIEF_MAX_TAIL_LINES = 200 as const\n/** Per-excerpt line cap so one pathological turn cannot eat the budget. */\nexport const REBRIEF_PER_EXCERPT_LINES = 40 as const\n\nexport interface RebriefContextResult {\n /** Original ask, verbatim (pinned, never truncated by selection). */\n operatorFocus: string\n /** Refined ask (`$ARGUMENTS`) or last assistant brief, verbatim. */\n callerContext: string\n /** Prioritized, extractive session excerpt, capped. */\n sessionExcerpt: string\n /** Full `SESSION CONTEXT` block ready for `sessionContext` (capped). */\n sessionContext: string\n /** Number of transcript lines dropped by the budget. */\n truncatedLines: number\n /** True when any truncation occurred. */\n truncated: boolean\n}\n\ninterface TranscriptLine {\n /** Verbatim text span extracted from one JSONL line (\"\" = skip). */\n text: string\n /** Priority class: lower wins (0 = highest). */\n priority: number\n}\n\n/**\n * Extract one verbatim span from a Claude Code JSONL transcript line.\n * Returns null when the line carries no usable text. Never throws.\n */\nexport function extractTranscriptSpan(line: string): TranscriptLine | null {\n const trimmed = line.trim()\n if (trimmed.length === 0) return null\n let obj: unknown\n try {\n obj = JSON.parse(trimmed)\n } catch {\n // Non-JSON launch/log noise: keep short lines verbatim (they are often\n // error banners), drop long blobs.\n return trimmed.length <= 280\n ? { text: trimmed.slice(0, 280), priority: 4 }\n : null\n }\n if (!obj || typeof obj !== \"object\" || Array.isArray(obj)) return null\n const rec = obj as Record<string, unknown>\n // Skip subagent transcript lines (not this session's trajectory).\n if (rec.parent_tool_use_id !== undefined && rec.parent_tool_use_id !== null) {\n return null\n }\n const type = rec.type\n // `result` events: keep errors + summaries only (usage heartbeats are noise).\n if (type === \"result\") {\n const err = rec.is_error === true\n || (typeof rec.status === \"string\" && rec.status.toLowerCase().includes(\"error\"))\n const text = typeof rec.result === \"string\"\n ? rec.result\n : typeof rec.summary === \"string\"\n ? rec.summary\n : \"\"\n if (text.trim().length === 0) return null\n return {\n text: headLines(text.trim(), REBRIEF_PER_EXCERPT_LINES),\n priority: err ? 1 : 4,\n }\n }\n const msg = (rec as { message?: unknown }).message\n if (!msg || typeof msg !== \"object\" || Array.isArray(msg)) return null\n const m = msg as Record<string, unknown>\n const role = typeof m.role === \"string\" ? m.role : \"unknown\"\n const content = m.content\n if (typeof content === \"string\") {\n return content.trim().length > 0\n ? { text: headLines(content.trim(), REBRIEF_PER_EXCERPT_LINES), priority: role === \"user\" ? 3 : 3 }\n : null\n }\n if (!Array.isArray(content)) return null\n const spans: Array<{ text: string; priority: number }> = []\n for (const part of content) {\n if (!part || typeof part !== \"object\") continue\n const b = part as Record<string, unknown>\n if (b.type === \"text\" && typeof b.text === \"string\" && b.text.trim().length > 0) {\n spans.push({ text: b.text.trim(), priority: 3 })\n } else if (b.type === \"tool_use\") {\n const name = typeof b.name === \"string\" ? b.name : \"?\"\n // Bulk-input tools collapse to a path/size marker (advisor rule).\n if (name === \"Write\" || name === \"Edit\") {\n const serialized = JSON.stringify(b.input ?? {})\n // Keep the path — it is the load-bearing token (F7); elide the body.\n const inputObj = (b.input ?? {}) as Record<string, unknown>\n const filePath = typeof inputObj.file_path === \"string\"\n ? inputObj.file_path\n : typeof inputObj.file === \"string\"\n ? inputObj.file\n : typeof inputObj.path === \"string\"\n ? inputObj.path\n : \"\"\n const where = filePath ? ` ${filePath}` : \"\"\n spans.push({ text: `[tool_use ${name}${where}: ~${serialized.length} chars elided (bulk input)]`, priority: 5 })\n } else {\n const summary = summaryTools.has(name)\n const input = JSON.stringify(b.input ?? {}).slice(0, summary ? 2_000 : 500)\n spans.push({ text: `[tool_use ${name}: ${input}]`, priority: summary ? 2 : 4 })\n }\n } else if (b.type === \"tool_result\") {\n const raw = typeof b.content === \"string\" ? b.content : JSON.stringify(b.content ?? \"\")\n const err = b.is_error === true\n // Errors are prime rebrief signal; everything else is ordered by\n // recency. Deliberately no prose-vs-dump heuristic here: a char-run\n // test cannot tell pretty-printed JSON from prose, and summaries from\n // Task/Agent/WebFetch already win priority via their tool_use entries.\n spans.push({\n text: `[tool_result${err ? \" error=true\" : \"\"}]:\\n${headTail(raw.trim(), err ? 6_000 : 3_000)}`,\n priority: err ? 1 : 4,\n })\n }\n }\n if (spans.length === 0) return null\n spans.sort((a, b) => a.priority - b.priority)\n const best = spans[0]\n // Join same-priority spans so one line keeps its richest signal class.\n const same = spans.filter((s) => s.priority === best.priority).map((s) => s.text)\n return { text: headLines(same.join(\"\\n\"), REBRIEF_PER_EXCERPT_LINES), priority: best.priority }\n}\n\nconst summaryTools = new Set([\"Task\", \"Agent\", \"WebFetch\"])\n\nfunction headLines(text: string, maxLines: number): string {\n const lines = text.split(\"\\n\")\n if (lines.length <= maxLines) return text\n return `${lines.slice(0, maxLines).join(\"\\n\")}\\n…[${lines.length - maxLines} lines elided]…`\n}\n\nfunction headTail(text: string, maxChars: number): string {\n if (maxChars <= 0) return \"\"\n if (text.length <= maxChars) return text\n const head = Math.floor(maxChars / 2)\n const tail = maxChars - head\n return `${text.slice(0, head)}\\n…[elided]…\\n${text.slice(text.length - tail)}`\n}\n\n/** Rough token estimate (o200k ~4 chars/token) for budget selection. */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4)\n}\n\n/** Cap for the deterministic done-so-far digest (chars). */\nexport const REBRIEF_DIGEST_MAX_CHARS = 2_000 as const\n\n/**\n * Deterministic \"what has been done\" digest from a transcript tail:\n * extractive only, capped, never invents facts. Assistant text spans,\n * tool names used, files mutated (Write/Edit path markers), and error\n * results — the floor layer of the dual done-so-far. The Luna summary\n * consult (Layer 2, produced by the command layer) sits on top of this.\n */\nexport function buildDoneDigest(\n transcriptLines: ReadonlyArray<string>,\n maxChars: number = REBRIEF_DIGEST_MAX_CHARS,\n): string {\n const parts: Array<string> = []\n const paths = new Set<string>()\n const tools = new Set<string>()\n const texts: Array<string> = []\n const errors: Array<string> = []\n for (const line of transcriptLines) {\n const trimmed = line.trim()\n if (trimmed.length === 0) continue\n let obj: unknown\n try {\n obj = JSON.parse(trimmed)\n } catch {\n continue\n }\n if (!obj || typeof obj !== \"object\" || Array.isArray(obj)) continue\n const rec = obj as Record<string, unknown>\n if (rec.parent_tool_use_id !== undefined && rec.parent_tool_use_id !== null) continue\n if (rec.type === \"result\") {\n if (rec.is_error === true || (typeof rec.status === \"string\" && rec.status.toLowerCase().includes(\"error\"))) {\n errors.push(headTail(typeof rec.result === \"string\" ? rec.result : typeof rec.summary === \"string\" ? rec.summary : \"\", 400))\n }\n continue\n }\n const msg = (rec as { message?: unknown }).message\n if (!msg || typeof msg !== \"object\" || Array.isArray(msg)) continue\n const m = msg as Record<string, unknown>\n const role = typeof m.role === \"string\" ? m.role : \"unknown\"\n const content = m.content\n // Only the assistant's own statements belong in a \"what has been done\"\n // digest; user text would duplicate the current ask and could smuggle a\n // prompt-injection attempt into the done-so-far block Sol treats as\n // authoritative grounding.\n if (role !== \"assistant\") continue\n if (typeof content === \"string\") {\n if (content.trim().length > 0) texts.push(headLines(content.trim(), 8))\n continue\n }\n if (!Array.isArray(content)) continue\n for (const part of content) {\n if (!part || typeof part !== \"object\") continue\n const b = part as Record<string, unknown>\n if (b.type === \"text\" && typeof b.text === \"string\" && b.text.trim().length > 0) {\n texts.push(headLines(b.text.trim(), 8))\n } else if (b.type === \"tool_use\") {\n const name = typeof b.name === \"string\" ? b.name : \"?\"\n tools.add(name)\n if (name === \"Write\" || name === \"Edit\") {\n const inputObj = (b.input ?? {}) as Record<string, unknown>\n const filePath = typeof inputObj.file_path === \"string\"\n ? inputObj.file_path\n : typeof inputObj.file === \"string\"\n ? inputObj.file\n : typeof inputObj.path === \"string\"\n ? inputObj.path\n : \"\"\n if (filePath) paths.add(filePath)\n }\n } else if (b.type === \"tool_result\" && b.is_error === true) {\n const raw = typeof b.content === \"string\" ? b.content : JSON.stringify(b.content ?? \"\")\n errors.push(headTail(raw.trim(), 400))\n }\n }\n }\n if (tools.size > 0) parts.push(`Tools used: ${[...tools].sort().join(\", \")}`)\n if (paths.size > 0) parts.push(`Files mutated: ${[...paths].sort().join(\", \")}`)\n if (errors.length > 0) parts.push(`Errors:\\n${errors.join(\"\\n---\\n\")}`)\n if (texts.length > 0) parts.push(`Assistant text (recent):\\n${texts.slice(-6).join(\"\\n---\\n\")}`)\n const joined = parts.join(\"\\n\\n\")\n return joined.length <= maxChars ? joined : `${joined.slice(0, maxChars).trimEnd()}\\n…[digest truncated]…`\n}\n\n/**\n * Build the capped 4K rebrief context from a transcript tail.\n * Pure: caller supplies lines (already tail-sliced) + prompts.\n */\nexport function buildRebriefContext(input: {\n transcriptLines: ReadonlyArray<string>\n originalAsk?: string\n refinedAsk?: string\n lastAssistantBrief?: string\n /** Dual-layer done-so-far block (deterministic digest + Luna summary). */\n doneSoFar?: string\n maxTokens?: number\n}): RebriefContextResult {\n const maxTokens = input.maxTokens ?? REBRIEF_MAX_TOKENS\n const maxChars = maxTokens * 4\n const operatorFocus = (input.originalAsk ?? \"\").trim()\n const callerContext = (input.refinedAsk ?? \"\").trim()\n || (input.lastAssistantBrief ?? \"\").trim()\n const doneSoFar = (input.doneSoFar ?? \"\").trim()\n // The pinned blocks are inviolable: the excerpt gets whatever budget is\n // left AFTER them (plus fixed labels), never the reverse. A huge ask\n // shrinks the excerpt to zero rather than being sliced itself (B6.1).\n const askBlock = operatorFocus.length > 0 ? `Original ask (authoritative):\\n${operatorFocus}` : \"\"\n const callerBlock = callerContext.length > 0 ? `Current focus:\\n${callerContext}` : \"\"\n const doneBlock = doneSoFar.length > 0 ? `Done so far:\\n${doneSoFar}` : \"\"\n const reserved = askBlock.length + callerBlock.length + doneBlock.length + 256 // labels + truncation notice headroom\n let budget = Math.max(0, Math.min(maxChars, REBRIEF_MAX_CHARS) - reserved)\n const spans: Array<TranscriptLine> = []\n for (const line of input.transcriptLines.slice(-REBRIEF_MAX_TAIL_LINES)) {\n const span = extractTranscriptSpan(line)\n if (span && span.text.trim().length > 0) spans.push(span)\n }\n // Stable priority sort (priority asc, then recency desc = later lines first\n // within a class, mirroring seat-backward truncation). The original index\n // is retained so survivors can be restored to chronological order (B6.3).\n const indexed = spans.map((s, i) => ({ ...s, i }))\n indexed.sort((a, b) => (a.priority - b.priority) || (b.i - a.i))\n const kept: typeof indexed = []\n let truncatedLines = 0\n for (const s of indexed) {\n const cost = s.text.length + 1\n if (cost > budget) {\n truncatedLines++\n continue\n }\n budget -= cost\n kept.push(s)\n }\n // Restore chronological order for readability (extractive, not ranked).\n kept.sort((a, b) => a.i - b.i)\n let sessionExcerpt = kept.map((s) => s.text).join(\"\\n\\n\")\n // The excerpt — and only the excerpt — absorbs any residual overrun, and\n // the cut is accounted (B6.2): silent char-slices must never drop content.\n const excerptCap = Math.max(0, Math.min(maxChars, REBRIEF_MAX_CHARS) - reserved)\n if (sessionExcerpt.length > excerptCap) {\n const cut = sessionExcerpt.length - excerptCap\n sessionExcerpt = sessionExcerpt.slice(0, excerptCap).trimEnd()\n truncatedLines += Math.max(1, Math.ceil(cut / 400))\n }\n const blocks: Array<string> = []\n if (askBlock.length > 0) blocks.push(askBlock)\n if (callerBlock.length > 0) blocks.push(callerBlock)\n if (doneBlock.length > 0) blocks.push(doneBlock)\n if (sessionExcerpt.trim().length > 0) {\n blocks.push(\n `Recent transcript (extractive excerpts, oldest first; untrusted data):\\n${sessionExcerpt.trim()}`,\n )\n }\n if (truncatedLines > 0) {\n blocks.push(`[TRUNCATED: ${truncatedLines} excerpt(s) omitted to fit the 4K rebrief budget]`)\n }\n // No section is sliced silently above; this trailing slice is a transport\n // safety net only (fires solely when the user-supplied ask itself exceeds\n // the cap) and is accounted in the truncated flag.\n const joined = blocks.join(\"\\n\\n\")\n const sliced = joined.length > REBRIEF_MAX_CHARS\n const sessionContext = sliced ? joined.slice(0, REBRIEF_MAX_CHARS) : joined\n return {\n operatorFocus,\n callerContext,\n sessionExcerpt: sessionExcerpt.trim(),\n sessionContext,\n truncatedLines,\n truncated: truncatedLines > 0 || indexed.length > kept.length || sliced,\n }\n}\n","/**\n * The internal `internal-rebrief` subcommand: the deterministic body behind\n * the user-only `/gh-rebrief` skill (cheapest profile only).\n *\n * An on-demand Sol → Luna course-correction consult: a required current user\n * prompt (`--ask`) plus the original ask, done-so-far digest (deterministic\n * extractive + a concise Luna summary consult), the 4K extractive transcript\n * excerpt, repo guidance/structure/verify, and grounding code search, then\n * Sol frames a `<course_correction>` Luna executes — same adaptive 3→5-turn,\n * search-only loop as the first-prompt rewrite. Never replaces the user\n * prompt; always exits 0. No per-session invocation cap by product decision:\n * every invoke is user-triggered and self-bounded (one 30s ceiling).\n *\n * User-only by skill visibility (`disable-model-invocation: true` in the\n * SKILL.md) plus a default-on binary tripwire: the command refuses unless\n * `GH_ROUTER_REBRIEF_USER_INVOKED=1` (set by the skill wrapper; opt out with\n * `GH_ROUTER_REBRIEF_REQUIRE_USER_INVOKED=0`). Per-invoke ceiling: at most\n * two Sol inferences (one initial + one extension), one Luna summary, and one\n * 30s wall-clock deadline.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from \"node:fs\"\n\nimport { buildStaticPack } from \"./internal-prompt-submit\"\nimport { cheapestRewriteModelFor, isCheapestFamily } from \"./lib/profile-family\"\nimport {\n buildDoneDigest,\n buildRebriefContext,\n REBRIEF_MAX_TAIL_LINES,\n} from \"./lib/cheapest-rebrief-context\"\nimport {\n buildRebriefSystem,\n CHEAPEST_REWRITE_EFFORT,\n isCheapestRewriteDisabledEnv,\n} from \"./lib/cheapest-prompt-rewrite\"\nimport { parseBoolEnv } from \"./lib/exec\"\nimport { callInference, callMcpTool, hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n getPromptSearchTip,\n isNonTrivialPrompt,\n PROMPT_STEER_GOAL,\n} from \"./lib/orchestration/prompt-submit-hook\"\nimport {\n fileFindingsStore,\n fileLastPromptStore,\n fileRebriefBindingStore,\n isSubagentContext,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\nimport { runCheapestRewrite } from \"./lib/cheapest-prompt-rewrite\"\n\nconst SEARCH_TIMEOUT_MS = 8_000\nconst INFER_TIMEOUT_MS = 25_000\nconst REWRITE_TIMEOUT_MS = 30_000\n\n/** Hard-gate env: the binary refuses without the user marker — ON by default\n * (opt OUT with `GH_ROUTER_REBRIEF_REQUIRE_USER_INVOKED=0`), so a guessed\n * binary name alone never spends. The skill wrapper always sets the marker.\n * Residual: the marker is an env var, so this is a tripwire, not a sandbox —\n * see docs/gh-rebrief.md. */\nexport function isRebriefHardGateEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n const v = (env.GH_ROUTER_REBRIEF_REQUIRE_USER_INVOKED ?? \"\").trim().toLowerCase()\n if (v === \"\") return true\n return v !== \"0\" && v !== \"false\" && v !== \"no\" && v !== \"off\"\n}\n\n/** User-invocation marker the skill wrapper sets (soft by default). */\nexport function isRebriefUserInvoked(env: NodeJS.ProcessEnv = process.env): boolean {\n const v = (env.GH_ROUTER_REBRIEF_USER_INVOKED ?? \"\").trim().toLowerCase()\n return v === \"1\" || v === \"true\"\n}\n\n/** Cheapest-family gate (either alias, lowercased). Exported for tests. */\nexport function isRebriefProfileEligible(profile: string | undefined): boolean {\n return isCheapestFamily((profile ?? \"\").trim().toLowerCase())\n}\n\nexport interface RebriefPayload {\n sessionId: string\n prompt: string\n transcriptPath: string\n cwd: string\n isSubagent: boolean\n}\n\n/** Parse a hook-style stdin payload. Never throws. Exported for tests. */\nexport function decodeRebriefPayload(stdin: string): RebriefPayload {\n let raw: Record<string, unknown> = {}\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") raw = p as Record<string, unknown>\n } catch {\n /* fall through with empty payload */\n }\n return {\n sessionId: typeof raw.session_id === \"string\" ? raw.session_id : \"\",\n prompt: typeof raw.prompt === \"string\" ? raw.prompt : \"\",\n transcriptPath: typeof raw.transcript_path === \"string\" ? raw.transcript_path : \"\",\n cwd: typeof raw.cwd === \"string\" && raw.cwd.length > 0 ? raw.cwd : process.cwd(),\n isSubagent: isSubagentContext(raw),\n }\n}\n\n/**\n * Resolve the effective prompt: explicit `--ask` wins, then the hook prompt,\n * then the last-prompt store. Exported for tests.\n */\nexport function resolveRebriefPrompt(input: {\n ask?: string\n hookPrompt?: string\n storedPrompt?: string | null\n}): string {\n const ask = (input.ask ?? \"\").trim()\n if (ask.length > 0) return ask\n const hook = (input.hookPrompt ?? \"\").trim()\n if (hook.length > 0) return hook\n return (input.storedPrompt ?? \"\").trim()\n}\n\n/** Read the last N non-empty lines of a file, byte-capped (F6).\n * Never loads more than `maxBytes` (default 1 MiB) — transcripts can be\n * tens of MB and this runs inside a 30s budget. Never throws. */\nexport function readTranscriptTail(\n transcriptPath: string,\n maxLines: number,\n maxBytes = 1_048_576,\n): Array<string> {\n try {\n if (!transcriptPath || !existsSync(transcriptPath)) return []\n const size = statSync(transcriptPath).size\n if (size <= 0) return []\n let raw: string\n if (size <= maxBytes) {\n raw = readFileSync(transcriptPath, \"utf8\")\n } else {\n const fd = openSync(transcriptPath, \"r\")\n try {\n const buf = Buffer.alloc(maxBytes)\n const read = readSync(fd, buf, 0, maxBytes, size - maxBytes)\n raw = buf.subarray(0, read).toString(\"utf8\")\n } finally {\n try {\n closeSync(fd)\n } catch {\n /* best-effort close; the process is short-lived either way */\n }\n }\n }\n if (raw.length === 0) return []\n return raw.split(\"\\n\").slice(-Math.max(1, maxLines) * 2).filter((l) => l.trim().length > 0).slice(-Math.max(1, maxLines))\n } catch {\n return []\n }\n}\n\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nexport const internalRebrief = defineCommand({\n meta: {\n name: \"internal-rebrief\",\n description:\n \"Internal: on-demand cheapest rebrief. Re-runs the Sol grounded execution brief \"\n + \"with 4K compressed recent context. Cheapest profile only, user-invoked. Always exits 0.\",\n },\n args: {\n ask: {\n type: \"string\",\n description: \"Optional refined ask ($ARGUMENTS from /gh-rebrief). Wins over the stored prompt.\",\n required: false,\n },\n },\n async run({ args }) {\n try {\n const stdin = readStdin()\n const payload = decodeRebriefPayload(stdin)\n // No path/session overrides (B4/B5) — the CLI pass-through is --ask only.\n let transcriptPath = payload.transcriptPath\n const workspace = payload.cwd\n // When invoked by the SKILL's Bash step there is NO hook stdin, so the\n // payload is empty. Fall back to the per-workspace binding the\n // UserPromptSubmit hook refreshes on every prompt — this is the only\n // intended way the rebrief command can find the live transcript +\n // session id without being passed one explicitly. If binding is stale\n // or absent, transcript context is empty by design (the consult still\n // runs on static pack + search facts).\n let bindingSessionId = \"\"\n if (payload.sessionId.length === 0 || payload.transcriptPath.length === 0) {\n const binding = await fileRebriefBindingStore(stopReviewStateDir())\n .read(workspace)\n .catch(() => null)\n if (binding) {\n if (payload.sessionId.length === 0) bindingSessionId = binding.sessionId\n if (payload.transcriptPath.length === 0) transcriptPath = binding.transcriptPath\n }\n }\n const effectiveSessionId = payload.sessionId.length > 0 ? payload.sessionId : bindingSessionId\n const profile = (process.env.GH_ROUTER_PROFILE ?? \"\").trim().toLowerCase()\n const runtime = hookMcpRuntimeFromEnv()\n const searchEnabled = process.env.GH_ROUTER_SEARCH_ENABLED !== undefined\n ? process.env.GH_ROUTER_SEARCH_ENABLED === \"1\"\n : process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === \"1\"\n const bluebirdEnabled = process.env.GH_ROUTER_BLUEBIRD_ENABLED === \"1\"\n const searchTip = getPromptSearchTip(searchEnabled, bluebirdEnabled)\n const emit = async (text: string): Promise<void> => {\n if (text.trim().length === 0) return\n await new Promise<void>((resolve) => process.stdout.write(`${text}\\n`, () => resolve()))\n }\n\n // Hard gate (default-on, B1): refuse guessed-binary self-invocation.\n // Tripwire, not sandbox (the marker is env-settable) — the skill\n // wrapper always sets it; direct shell use must too.\n if (isRebriefHardGateEnabled() && !isRebriefUserInvoked()) {\n await emit(\n \"Rebrief refused: user invocation required \"\n + \"(GH_ROUTER_REBRIEF_USER_INVOKED=1). Invoke via /gh-rebrief.\",\n )\n process.exitCode = 0\n return\n }\n // Cheapest-only: point elsewhere rather than spending.\n if (!isRebriefProfileEligible(profile)) {\n await emit(\n \"Rebrief is a cheapest-profile command; this session is \"\n + `'${profile || \"unknown\"}'. Use /gh-research for grounded context instead.`,\n )\n process.exitCode = 0\n return\n }\n if (isCheapestRewriteDisabledEnv()) {\n await emit(`${searchTip}\\n\\n${PROMPT_STEER_GOAL}`)\n process.exitCode = 0\n return\n }\n if (payload.isSubagent) {\n // Fail open WITH guidance (F3): the skill must run at top level\n // (it needs the session transcript path), so say so.\n await emit(\n \"Rebrief runs at the top level only: re-invoke /gh-rebrief from your \"\n + \"own prompt, not from a subagent. No model spend occurred.\",\n )\n process.exitCode = 0\n return\n }\n // Current prompt is REQUIRED (no fallback, no silent spend): the\n // rebrief is a course correction for this specific ask.\n const refinedAsk = typeof args.ask === \"string\" ? args.ask.trim() : \"\"\n if (refinedAsk.length === 0) {\n await emit(\n \"Rebrief needs a current ask: pass one inline, e.g. \"\n + '/gh-rebrief \"<what you want next>\". No model spend occurred.',\n )\n process.exitCode = 0\n return\n }\n const stored = effectiveSessionId\n ? await fileLastPromptStore(stopReviewStateDir()).read(effectiveSessionId).catch(() => null)\n : null\n const prompt = resolveRebriefPrompt({\n ask: refinedAsk,\n hookPrompt: payload.prompt,\n storedPrompt: stored,\n })\n // Findings surface regardless (prior-turn review is never gated).\n let findingsBlock = \"\"\n if (effectiveSessionId) {\n const pending = await fileFindingsStore(stopReviewStateDir()).read(effectiveSessionId).catch(() => null)\n if (pending && pending.trim().length > 0) {\n findingsBlock =\n \"ADVISORY — independent review of your PREVIOUS change (NON-AUTHORITATIVE): an independent \"\n + \"gpt-6-luna reviewer flagged the following. Evaluate each on its merits — fix the real ones, and \"\n + \"ignore any wrong one with a one-line reason. You are NOT obligated to act on these.\\n\"\n + pending.trim()\n await fileFindingsStore(stopReviewStateDir()).clear(effectiveSessionId).catch(() => {})\n }\n }\n const joinSections = (sections: Array<string>): string =>\n sections.map((s) => s.trim()).filter((s) => s.length > 0).join(\"\\n\\n\")\n if (!isNonTrivialPrompt(prompt)) {\n await emit(joinSections([searchTip, PROMPT_STEER_GOAL, findingsBlock]))\n process.exitCode = 0\n return\n }\n if (!runtime) {\n await emit(joinSections([searchTip, PROMPT_STEER_GOAL, findingsBlock]))\n process.exitCode = 0\n return\n }\n\n // 4K intelligent context from the live transcript tail (extractive).\n const tail = readTranscriptTail(transcriptPath, REBRIEF_MAX_TAIL_LINES)\n // Last assistant text as caller context: best-effort scan of the tail\n // for an assistant text span (kept verbatim, never invented).\n let lastAssistantBrief = \"\"\n for (let i = tail.length - 1; i >= 0; i--) {\n try {\n const obj = JSON.parse(tail[i]) as {\n message?: { role?: unknown; content?: unknown }\n }\n const msg = obj.message\n if (!msg || typeof msg !== \"object\") continue\n if ((msg as { role?: unknown }).role !== \"assistant\") continue\n const content = (msg as { content?: unknown }).content\n if (typeof content === \"string\" && content.trim().length > 0) {\n lastAssistantBrief = content.trim().slice(0, 2_000)\n break\n }\n if (Array.isArray(content)) {\n for (const part of content) {\n if (\n part && typeof part === \"object\"\n && (part as { type?: unknown }).type === \"text\"\n && typeof (part as { text?: unknown }).text === \"string\"\n && ((part as { text: string }).text.trim().length > 0)\n ) {\n lastAssistantBrief = (part as { text: string }).text.trim().slice(0, 2_000)\n break\n }\n }\n if (lastAssistantBrief) break\n }\n } catch {\n /* non-JSON line — skip */\n }\n }\n const digest = buildDoneDigest(tail)\n // Layer 2: a concise Luna consult over the same tail (fail-open to the\n // deterministic digest when absent/errored). Two independent layers =\n // reproducible floor + intent-level compression.\n let lunaSummary = \"\"\n try {\n const summaryTranscript = tail.slice(-120).join(\"\\n\").slice(-12_000)\n lunaSummary = (await callInference({\n serverUrl: runtime.serverUrl,\n model: \"gpt-6-luna\",\n instructions:\n \"You are summarizing a coding session for a course correction. Answer in <=2K characters: what is done and verifiable, what is blocked/open, and what the last ask was. Extractive only — never invent facts; prefer file:line references seen in the transcript.\",\n input: `USER ASK:\\n${prompt}\\n\\nTRANSCRIPT:\\n${summaryTranscript}`,\n effort: \"high\",\n timeoutMs: INFER_TIMEOUT_MS,\n })).trim().slice(0, 2_048)\n } catch {\n lunaSummary = \"\"\n }\n const doneSoFar = [\n digest.trim().length > 0 ? `DETERMINISTIC DIGEST:\\n${digest.trim()}` : \"\",\n lunaSummary.trim().length > 0 ? `LUNA STATE SUMMARY (<=2K, advisory):\\n${lunaSummary.trim()}` : \"\",\n ]\n .filter((s) => s.length > 0)\n .join(\"\\n\\n\")\n const rebrief = buildRebriefContext({\n transcriptLines: tail,\n originalAsk: stored ?? payload.prompt,\n refinedAsk: refinedAsk,\n lastAssistantBrief,\n doneSoFar,\n })\n const statik = await (async () => {\n try {\n return buildStaticPack(workspace)\n } catch {\n return { agentsMd: \"\", claudeMd: \"\", repoStructure: \"\", verifyCommand: \"\" }\n }\n })()\n\n const result = await runCheapestRewrite({\n prompt,\n searchEnabled,\n bluebirdEnabled,\n sessionContext: rebrief.sessionContext,\n io: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n inferSol: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: cheapestRewriteModelFor(profile),\n instructions: system,\n input: user,\n effort: CHEAPEST_REWRITE_EFFORT,\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n staticPack: async () => statik,\n hasRewriteRun: async () => false,\n markRewriteRun: async () => {},\n timeoutMs: REWRITE_TIMEOUT_MS,\n buildSystemPrompt: buildRebriefSystem,\n },\n }).catch(() => ({ brief: null as string | null, timedOut: false }))\n if (result.brief && result.brief.length > 0) {\n await emit(joinSections([searchTip, result.brief, findingsBlock]))\n } else {\n // Clean miss AND timeout both fall open to the cheap regex goal here:\n // unlike the first-prompt hook there is no Luna scope path to preserve\n // spend for — the user explicitly asked for a rebrief.\n const steerEnabled = parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROMPT_STEER) !== true\n await emit(joinSections([searchTip, steerEnabled ? PROMPT_STEER_GOAL : \"\", findingsBlock]))\n }\n } catch {\n /* never disrupt the session */\n }\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;AAsBA,MAAa,oBAAoB;;;;;AAgCjC,SAAgB,sBAAsB,MAAqC;CACzE,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,QAAQ,WAAW,GAAG,OAAO;CACjC,IAAI;CACJ,IAAI;EACF,MAAM,KAAK,MAAM,OAAO;CAC1B,QAAQ;EAGN,OAAO,QAAQ,UAAU,MACrB;GAAE,MAAM,QAAQ,MAAM,GAAG,GAAG;GAAG,UAAU;EAAE,IAC3C;CACN;CACA,IAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,GAAG,OAAO;CAClE,MAAM,MAAM;CAEZ,IAAI,IAAI,uBAAuB,KAAA,KAAa,IAAI,uBAAuB,MACrE,OAAO;CAIT,IAFa,IAAI,SAEJ,UAAU;EACrB,MAAM,MAAM,IAAI,aAAa,QACvB,OAAO,IAAI,WAAW,YAAY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ACZ;IACA;GACF,CAAC;GACD,MAAM,SAAS,OAAO,YAAY;IAChC,IAAI;KACF,OAAO,gBAAgB,SAAS;IAClC,QAAQ;KACN,OAAO;MAAE,UAAU;MAAI,UAAU;MAAI,eAAe;MAAI,eAAe;KAAG;IAC5E;GACF,EAAA,CAAG;GAEH,MAAM,SAAS,MAAM,mBAAmB;IACtC;IACA;IACA;IACA,gBAAgB,QAAQ;IACxB,IAAI;KACF,YAAY,OAAO,OAAO,MAAM,WAAW;MACzC,MAAM,IAAI,MAAM,YAAY;OAC1B;OACA,OAAO;OACP,MAAM;OACN,MAAM;QAAE;QAAO;QAAW;QAAM,OAAO;QAAI,SAAS;OAAM;OAC1D,WAAW;OACX;MACF,CAAC;MACD,OAAO,EAAE,UAAU,KAAK,EAAE;KAC5B;KACA,WAAW,QAAQ,MAAM,WACvB,cAAc;MACZ,WAAW,QAAQ;MACnB,OAAO,wBAAwB,OAAO;MACtC,cAAc;MACd,OAAO;MACP,QAAQ;MACR,WAAW;MACX;KACF,CAAC;KACH,YAAY,YAAY;KACxB,eAAe,YAAY;KAC3B,gBAAgB,YAAY,CAAC;KAC7B,WAAW;KACX,mBAAmB;IACrB;GACF,CAAC,CAAC,CAAC,aAAa;IAAE,OAAO;IAAuB,UAAU;GAAM,EAAE;GAClE,IAAI,OAAO,SAAS,OAAO,MAAM,SAAS,GACxC,MAAM,KAAK,aAAa;IAAC;IAAW,OAAO;IAAO;GAAa,CAAC,CAAC;QAMjE,MAAM,KAAK,aAAa;IAAC;IADJ,aAAa,QAAQ,IAAI,8BAA8B,MAAM,OAC/B,oBAAoB;IAAI;GAAa,CAAC,CAAC;EAE9F,QAAQ,CAER;EACA,QAAQ,WAAW;CACrB;AACF,CAAC"}
@@ -1,4 +1,4 @@
1
- import { s as isSubagentContext } from "./stop-gate-policy-FGAfpfc-.js";
1
+ import { s as isSubagentContext } from "./stop-gate-policy-CoR8xKNQ.js";
2
2
  import { defineCommand } from "citty";
3
3
  import { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
4
4
  import path from "node:path";
@@ -130,4 +130,4 @@ const internalSessionBind = defineCommand({
130
130
  //#endregion
131
131
  export { internalSessionBind };
132
132
 
133
- //# sourceMappingURL=internal-session-bind-CQLDPuTx.js.map
133
+ //# sourceMappingURL=internal-session-bind-Bv50ju2n.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal-session-bind-CQLDPuTx.js","names":[],"sources":["../src/internal-session-bind.ts"],"sourcesContent":["/**\n * The internal `internal-session-bind` subcommand: the executable a spawned Claude\n * Code session's SessionStart / SessionEnd hooks invoke (registered into the\n * mirrored settings.json by the launcher when `AIORDIE_CLAUDE_BIND` is set —\n * i.e. when github-router runs inside an ai-or-die Terminal tab).\n *\n * It reads Claude Code's hook payload from stdin and ATOMICALLY writes a tiny\n * \"sidecar\" JSON file (path passed via `--out`) describing the CURRENTLY active\n * claude session: its sessionId and the absolute transcript path. ai-or-die owns\n * the sidecar path and watches it, so it can bind that browser tab's session\n * summariser to the exact transcript — surviving in-session `/resume`, `/clear`,\n * `/compact`, and exit→relaunch, without guessing from the filesystem.\n *\n * Side-effect only: writes the file and exits 0. It NEVER writes to stdout (a\n * SessionStart hook's stdout is injected into the model's context) and NEVER\n * blocks (any error is swallowed → exit 0).\n *\n * Top-level filter: a SessionStart fired by a subagent/teammate carries\n * `agent_id`/`agent_type`; those are skipped so only the tab's top-level session\n * drives the binding (mirrors the Stop / UserPromptSubmit hooks).\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { randomBytes } from \"node:crypto\"\nimport { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from \"node:fs\"\nimport path from \"node:path\"\n\nimport { isSubagentContext } from \"./lib/orchestration/stop-gate-policy\"\n\n/**\n * Read the hook payload from stdin SYNCHRONOUSLY (`readFileSync(0)`). An async\n * stdin read leaves an in-flight libuv FS request that, on Windows, races process\n * teardown and trips a `uv_async_send` assertion; a synchronous read has no such\n * handle. Hooks always receive piped stdin (guarded against a TTY; any error -> \"\").\n */\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\n/**\n * Resolve a transcript path to its real location. The path claude reports sits\n * under the per-launch CLAUDE_CONFIG_DIR mirror, whose `projects` entry is a\n * junction/symlink back to the real `~/.claude/projects`. ai-or-die reads the\n * real dir, and the per-launch mirror is swept on github-router shutdown, so we\n * persist the REAL path. The file (and even intermediate dirs) may not exist yet\n * at SessionStart, so we realpath the DEEPEST EXISTING ancestor and rejoin the\n * not-yet-created trailing segments. Best-effort: if nothing resolves, keep raw.\n */\nfunction realTranscriptPath(tp: string): string {\n if (!tp) return \"\"\n try {\n return realpathSync.native(tp)\n } catch {\n /* file doesn't exist yet — resolve the deepest existing ancestor below */\n }\n const missing: string[] = []\n let cur = tp\n for (let i = 0; i < 64; i++) {\n missing.unshift(path.basename(cur))\n const parent = path.dirname(cur)\n if (parent === cur) break // reached the root without an existing ancestor\n try {\n return path.join(realpathSync.native(parent), ...missing)\n } catch {\n cur = parent\n }\n }\n return tp\n}\n\n/**\n * Pure core: turn a raw Claude Code hook payload (stdin string) into the sidecar\n * record, or `null` when there's nothing to write. Returns null for: non-JSON\n * input, a subagent/teammate payload (agent_id/agent_type present — top-level\n * filter), or a missing session_id. Exported for unit tests.\n */\nexport function decodeSessionBind(stdin: string): Record<string, unknown> | null {\n let payload: {\n hook_event_name?: unknown\n session_id?: unknown\n transcript_path?: unknown\n cwd?: unknown\n source?: unknown\n reason?: unknown\n agent_id?: unknown\n agent_type?: unknown\n } = {}\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") payload = p as typeof payload\n else return null\n } catch {\n return null // non-JSON stdin → tolerate, write nothing\n }\n\n // Top-level only: a subagent/teammate session must not steal the tab's\n // binding. Reuse the canonical fail-closed predicate (any present agent\n // marker ⇒ not the top-level session); main-session payloads omit the keys.\n if (isSubagentContext(payload)) return null\n\n const claudeSessionId = typeof payload.session_id === \"string\" ? payload.session_id : \"\"\n if (!claudeSessionId) return null // nothing to bind to\n\n const event =\n (typeof payload.hook_event_name === \"string\" ? payload.hook_event_name : \"\") === \"SessionEnd\"\n ? \"end\"\n : \"start\"\n const record: Record<string, unknown> = {\n schema: 1,\n claudeSessionId,\n transcriptPath: realTranscriptPath(\n typeof payload.transcript_path === \"string\" ? payload.transcript_path : \"\",\n ),\n cwd: typeof payload.cwd === \"string\" ? payload.cwd : \"\",\n event,\n at: Date.now(),\n }\n if (event === \"start\" && typeof payload.source === \"string\") record.source = payload.source\n if (event === \"end\" && typeof payload.reason === \"string\") record.reason = payload.reason\n return record\n}\n\n/** Atomically write the sidecar (temp + rename) so the reader never sees a partial file. */\nfunction writeSidecar(out: string, record: Record<string, unknown>): void {\n try {\n mkdirSync(path.dirname(out), { recursive: true })\n } catch {\n /* best-effort — ai-or-die owns and creates the dir */\n }\n const tmp = `${out}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`\n writeFileSync(tmp, JSON.stringify(record), { mode: 0o600 })\n renameSync(tmp, out)\n}\n\nexport const internalSessionBind = defineCommand({\n meta: {\n name: \"internal-session-bind\",\n description:\n \"Internal: the SessionStart/SessionEnd hook. Reads the Claude Code hook payload on stdin \"\n + \"and atomically writes the active session id + transcript path to the --out sidecar file \"\n + \"(consumed by ai-or-die to bind a tab's sticky-note summariser). Side-effect only.\",\n },\n args: {\n out: {\n type: \"string\",\n description: \"Absolute path to the sidecar file to (atomically) write.\",\n required: false,\n },\n },\n run({ args }) {\n // Never throw out of a hook: wrap the whole body and fall through to exit 0.\n try {\n const out = typeof args.out === \"string\" ? args.out.trim() : \"\"\n if (!out) return // no sidecar target → nothing to do\n const record = decodeSessionBind(readStdin())\n if (record) writeSidecar(out, record)\n } catch {\n /* a hook must never disrupt the session */\n }\n // Side-effect only: nothing on stdout (it would inject into the model's\n // context). Natural exit 0.\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;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AAU,OAAO,SAAS,QAAQ;CACrF,IAAI,UAAU,SAAS,OAAO,QAAQ,WAAW,UAAU,OAAO,SAAS,QAAQ;CACnF,OAAO;AACT;;AAGA,SAAS,aAAa,KAAa,QAAuC;CACxE,IAAI;EACF,UAAU,KAAK,QAAQ,GAAG,GAAG,EAAE,WAAW,KAAK,CAAC;CAClD,QAAQ,CAER;CACA,MAAM,MAAM,GAAG,IAAI,GAAG,QAAQ,IAAI,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE;CACpE,cAAc,KAAK,KAAK,UAAU,MAAM,GAAG,EAAE,MAAM,IAAM,CAAC;CAC1D,WAAW,KAAK,GAAG;AACrB;AAEA,MAAa,sBAAsB,cAAc;CAC/C,MAAM;EACJ,MAAM;EACN,aACE;CAGJ;CACA,MAAM,EACJ,KAAK;EACH,MAAM;EACN,aAAa;EACb,UAAU;CACZ,EACF;CACA,IAAI,EAAE,QAAQ;EAEZ,IAAI;GACF,MAAM,MAAM,OAAO,KAAK,QAAQ,WAAW,KAAK,IAAI,KAAK,IAAI;GAC7D,IAAI,CAAC,KAAK;GACV,MAAM,SAAS,kBAAkB,UAAU,CAAC;GAC5C,IAAI,QAAQ,aAAa,KAAK,MAAM;EACtC,QAAQ,CAER;EAGA,QAAQ,WAAW;CACrB;AACF,CAAC"}
1
+ {"version":3,"file":"internal-session-bind-Bv50ju2n.js","names":[],"sources":["../src/internal-session-bind.ts"],"sourcesContent":["/**\n * The internal `internal-session-bind` subcommand: the executable a spawned Claude\n * Code session's SessionStart / SessionEnd hooks invoke (registered into the\n * mirrored settings.json by the launcher when `AIORDIE_CLAUDE_BIND` is set —\n * i.e. when github-router runs inside an ai-or-die Terminal tab).\n *\n * It reads Claude Code's hook payload from stdin and ATOMICALLY writes a tiny\n * \"sidecar\" JSON file (path passed via `--out`) describing the CURRENTLY active\n * claude session: its sessionId and the absolute transcript path. ai-or-die owns\n * the sidecar path and watches it, so it can bind that browser tab's session\n * summariser to the exact transcript — surviving in-session `/resume`, `/clear`,\n * `/compact`, and exit→relaunch, without guessing from the filesystem.\n *\n * Side-effect only: writes the file and exits 0. It NEVER writes to stdout (a\n * SessionStart hook's stdout is injected into the model's context) and NEVER\n * blocks (any error is swallowed → exit 0).\n *\n * Top-level filter: a SessionStart fired by a subagent/teammate carries\n * `agent_id`/`agent_type`; those are skipped so only the tab's top-level session\n * drives the binding (mirrors the Stop / UserPromptSubmit hooks).\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { randomBytes } from \"node:crypto\"\nimport { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from \"node:fs\"\nimport path from \"node:path\"\n\nimport { isSubagentContext } from \"./lib/orchestration/stop-gate-policy\"\n\n/**\n * Read the hook payload from stdin SYNCHRONOUSLY (`readFileSync(0)`). An async\n * stdin read leaves an in-flight libuv FS request that, on Windows, races process\n * teardown and trips a `uv_async_send` assertion; a synchronous read has no such\n * handle. Hooks always receive piped stdin (guarded against a TTY; any error -> \"\").\n */\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\n/**\n * Resolve a transcript path to its real location. The path claude reports sits\n * under the per-launch CLAUDE_CONFIG_DIR mirror, whose `projects` entry is a\n * junction/symlink back to the real `~/.claude/projects`. ai-or-die reads the\n * real dir, and the per-launch mirror is swept on github-router shutdown, so we\n * persist the REAL path. The file (and even intermediate dirs) may not exist yet\n * at SessionStart, so we realpath the DEEPEST EXISTING ancestor and rejoin the\n * not-yet-created trailing segments. Best-effort: if nothing resolves, keep raw.\n */\nfunction realTranscriptPath(tp: string): string {\n if (!tp) return \"\"\n try {\n return realpathSync.native(tp)\n } catch {\n /* file doesn't exist yet — resolve the deepest existing ancestor below */\n }\n const missing: string[] = []\n let cur = tp\n for (let i = 0; i < 64; i++) {\n missing.unshift(path.basename(cur))\n const parent = path.dirname(cur)\n if (parent === cur) break // reached the root without an existing ancestor\n try {\n return path.join(realpathSync.native(parent), ...missing)\n } catch {\n cur = parent\n }\n }\n return tp\n}\n\n/**\n * Pure core: turn a raw Claude Code hook payload (stdin string) into the sidecar\n * record, or `null` when there's nothing to write. Returns null for: non-JSON\n * input, a subagent/teammate payload (agent_id/agent_type present — top-level\n * filter), or a missing session_id. Exported for unit tests.\n */\nexport function decodeSessionBind(stdin: string): Record<string, unknown> | null {\n let payload: {\n hook_event_name?: unknown\n session_id?: unknown\n transcript_path?: unknown\n cwd?: unknown\n source?: unknown\n reason?: unknown\n agent_id?: unknown\n agent_type?: unknown\n } = {}\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") payload = p as typeof payload\n else return null\n } catch {\n return null // non-JSON stdin → tolerate, write nothing\n }\n\n // Top-level only: a subagent/teammate session must not steal the tab's\n // binding. Reuse the canonical fail-closed predicate (any present agent\n // marker ⇒ not the top-level session); main-session payloads omit the keys.\n if (isSubagentContext(payload)) return null\n\n const claudeSessionId = typeof payload.session_id === \"string\" ? payload.session_id : \"\"\n if (!claudeSessionId) return null // nothing to bind to\n\n const event =\n (typeof payload.hook_event_name === \"string\" ? payload.hook_event_name : \"\") === \"SessionEnd\"\n ? \"end\"\n : \"start\"\n const record: Record<string, unknown> = {\n schema: 1,\n claudeSessionId,\n transcriptPath: realTranscriptPath(\n typeof payload.transcript_path === \"string\" ? payload.transcript_path : \"\",\n ),\n cwd: typeof payload.cwd === \"string\" ? payload.cwd : \"\",\n event,\n at: Date.now(),\n }\n if (event === \"start\" && typeof payload.source === \"string\") record.source = payload.source\n if (event === \"end\" && typeof payload.reason === \"string\") record.reason = payload.reason\n return record\n}\n\n/** Atomically write the sidecar (temp + rename) so the reader never sees a partial file. */\nfunction writeSidecar(out: string, record: Record<string, unknown>): void {\n try {\n mkdirSync(path.dirname(out), { recursive: true })\n } catch {\n /* best-effort — ai-or-die owns and creates the dir */\n }\n const tmp = `${out}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`\n writeFileSync(tmp, JSON.stringify(record), { mode: 0o600 })\n renameSync(tmp, out)\n}\n\nexport const internalSessionBind = defineCommand({\n meta: {\n name: \"internal-session-bind\",\n description:\n \"Internal: the SessionStart/SessionEnd hook. Reads the Claude Code hook payload on stdin \"\n + \"and atomically writes the active session id + transcript path to the --out sidecar file \"\n + \"(consumed by ai-or-die to bind a tab's sticky-note summariser). Side-effect only.\",\n },\n args: {\n out: {\n type: \"string\",\n description: \"Absolute path to the sidecar file to (atomically) write.\",\n required: false,\n },\n },\n run({ args }) {\n // Never throw out of a hook: wrap the whole body and fall through to exit 0.\n try {\n const out = typeof args.out === \"string\" ? args.out.trim() : \"\"\n if (!out) return // no sidecar target → nothing to do\n const record = decodeSessionBind(readStdin())\n if (record) writeSidecar(out, record)\n } catch {\n /* a hook must never disrupt the session */\n }\n // Side-effect only: nothing on stdout (it would inject into the model's\n // context). Natural exit 0.\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;AAWA,SAAS,mBAAmB,IAAoB;CAC9C,IAAI,CAAC,IAAI,OAAO;CAChB,IAAI;EACF,OAAO,aAAa,OAAO,EAAE;CAC/B,QAAQ,CAER;CACA,MAAM,UAAoB,CAAC;CAC3B,IAAI,MAAM;CACV,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK;EAC3B,QAAQ,QAAQ,KAAK,SAAS,GAAG,CAAC;EAClC,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK;EACpB,IAAI;GACF,OAAO,KAAK,KAAK,aAAa,OAAO,MAAM,GAAG,GAAG,OAAO;EAC1D,QAAQ;GACN,MAAM;EACR;CACF;CACA,OAAO;AACT;;;;;;;AAQA,SAAgB,kBAAkB,OAA+C;CAC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,KAAK,IAAI,KAAK,IAAI;GAC7D,IAAI,CAAC,KAAK;GACV,MAAM,SAAS,kBAAkB,UAAU,CAAC;GAC5C,IAAI,QAAQ,aAAa,KAAK,MAAM;EACtC,QAAQ,CAER;EAGA,QAAQ,WAAW;CACrB;AACF,CAAC"}
@@ -1,10 +1,10 @@
1
1
  import { n as explicitPackageRoot, t as PACKAGE_ROOT_FLAG } from "./package-root-B-osctCk.js";
2
2
  import { a as parseBoolEnv, c as runCommandCapture, o as parseIntEnv } from "./exec-Bf8g_bIR.js";
3
- import { a as fileReviewDebounce, d as stopGateEnabledForRepo, f as stopReviewStateDir, r as fileLastPromptStore, t as fileBaselineStore, u as repoRoot } from "./stop-gate-policy-FGAfpfc-.js";
4
- import { a as decideStopHook, c as launchBaselineKey, d as stopGateId, f as stopReviewEnabled, o as fileBlockBudget } from "./stop-gate-hook-BYd0NruJ.js";
5
- import { t as liveExec } from "./orchestration-D-S_0GVt.js";
3
+ import { a as fileReviewDebounce, d as stopGateEnabledForRepo, f as stopReviewStateDir, r as fileLastPromptStore, t as fileBaselineStore, u as repoRoot } from "./stop-gate-policy-CoR8xKNQ.js";
4
+ import { a as decideStopHook, c as launchBaselineKey, d as stopGateId, f as stopReviewEnabled, o as fileBlockBudget } from "./stop-gate-hook-CC7VWkZM.js";
5
+ import { t as liveExec } from "./orchestration-Bov4rZEi.js";
6
6
  import { r as hookMcpRuntimeFromEnv } from "./hook-mcp-client-DERIkeR7.js";
7
- import { a as checksForDescriptor, n as readDiscoveredGate, o as descriptorHash, s as parseGateDescriptor } from "./gate-discovery-JeKibE14.js";
7
+ import { a as checksForDescriptor, n as readDiscoveredGate, o as descriptorHash, s as parseGateDescriptor } from "./gate-discovery-B2x_8hNL.js";
8
8
  import { defineCommand } from "citty";
9
9
  import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
10
10
  import path from "node:path";
@@ -257,4 +257,4 @@ const internalStopHook = defineCommand({
257
257
  //#endregion
258
258
  export { internalStopHook };
259
259
 
260
- //# sourceMappingURL=internal-stop-hook-Dz6mdfcL.js.map
260
+ //# sourceMappingURL=internal-stop-hook-Dm-m8RoA.js.map