github-router 0.3.352 → 0.3.354
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -38
- package/dist/ado-tools-CN4i9OVl.js +1 -0
- package/dist/{aic-statusline-settings-LnoxjBPe.js → aic-statusline-settings-EdsV1gzY.js} +6 -4
- package/dist/aic-statusline-settings-EdsV1gzY.js.map +1 -0
- package/dist/{attribution-settings-ul6VU6iP.js → attribution-settings-8Uv97n9j.js} +51 -39
- package/dist/{attribution-settings-ul6VU6iP.js.map → attribution-settings-8Uv97n9j.js.map} +1 -1
- package/dist/balanced-profile-contract-DtnTIBjL.js +105 -0
- package/dist/balanced-profile-contract-DtnTIBjL.js.map +1 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{claude-xO1XW-Nn.js → claude-C_1OM7ce.js} +68 -59
- package/dist/claude-C_1OM7ce.js.map +1 -0
- package/dist/{claude-md-injection-BoXOsg7h.js → claude-md-injection-CDOoGNEJ.js} +20 -15
- package/dist/claude-md-injection-CDOoGNEJ.js.map +1 -0
- package/dist/{codex-DzUR40JA.js → codex-5eTmciDG.js} +5 -5
- package/dist/{codex-DzUR40JA.js.map → codex-5eTmciDG.js.map} +1 -1
- package/dist/{copilot-discount-C3jfysK-.js → copilot-discount-kpOLluHm.js} +3 -1
- package/dist/copilot-discount-kpOLluHm.js.map +1 -0
- package/dist/engine-CIAopp0h.js +1 -0
- package/dist/fast-profile-contract-JOnZBgFB.js +61 -0
- package/dist/fast-profile-contract-JOnZBgFB.js.map +1 -0
- package/dist/{gate-discovery-Cvdko01z.js → gate-discovery-CqJVzT_D.js} +2 -2
- package/dist/{gate-discovery-Cvdko01z.js.map → gate-discovery-CqJVzT_D.js.map} +1 -1
- package/dist/hooks.mjs +193 -12
- package/dist/hooks.sha256 +1 -1
- package/dist/{internal-aic-status-Dmi2bCsR.js → internal-aic-status-wYPsCG4r.js} +2 -2
- package/dist/{internal-aic-status-Dmi2bCsR.js.map → internal-aic-status-wYPsCG4r.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-Cv7zf0ZI.js → internal-fast-dispatch-guard-A8teEib4.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-BQm1MI9d.js → internal-fast-dispatch-guard-D_TCtJhQ.js} +3 -2
- package/dist/{internal-fast-dispatch-guard-BQm1MI9d.js.map → internal-fast-dispatch-guard-D_TCtJhQ.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-T-M7DRIW.js → internal-max-dispatch-guard-BM_B15EH.js} +1 -1
- package/dist/{internal-max-dispatch-guard-DkJixDmG.js → internal-max-dispatch-guard-D7ByWH4v.js} +2 -2
- package/dist/{internal-max-dispatch-guard-DkJixDmG.js.map → internal-max-dispatch-guard-D7ByWH4v.js.map} +1 -1
- package/dist/{internal-prompt-submit-B9MJxc3K.js → internal-prompt-submit-C77GnEaW.js} +3 -3
- package/dist/internal-prompt-submit-C77GnEaW.js.map +1 -0
- package/dist/{internal-prompt-submit-6OXEdQCK.js → internal-prompt-submit-CDTwamkW.js} +2 -2
- package/dist/{internal-rebrief-zIdunX3R.js → internal-rebrief-DZygfGHp.js} +6 -6
- package/dist/internal-rebrief-DZygfGHp.js.map +1 -0
- package/dist/{internal-stop-hook-DGcRVh_2.js → internal-stop-hook-Dn_AF0BF.js} +2 -2
- package/dist/{internal-stop-hook-DGcRVh_2.js.map → internal-stop-hook-Dn_AF0BF.js.map} +1 -1
- package/dist/main.js +11 -11
- package/dist/{max-profile-contract-DQDEDCsR.js → max-profile-contract-CMvzKSsg.js} +2 -2
- package/dist/max-profile-contract-CMvzKSsg.js.map +1 -0
- package/dist/{peer-mcp-personas-DDMKRFFG.js → peer-mcp-personas-DlF1dKCs.js} +142 -165
- package/dist/peer-mcp-personas-DlF1dKCs.js.map +1 -0
- package/dist/{pi-jVNeQXWf.js → pi-2m2IgZlm.js} +61 -62
- package/dist/pi-2m2IgZlm.js.map +1 -0
- package/dist/{provision-BtYRtvrj.js → provision-DLGlhu3a.js} +2 -2
- package/dist/{provision-BtYRtvrj.js.map → provision-DLGlhu3a.js.map} +1 -1
- package/dist/{serve-CmgmxigM.js → serve-8tXHVHOr.js} +7 -7
- package/dist/{serve-CmgmxigM.js.map → serve-8tXHVHOr.js.map} +1 -1
- package/dist/{server-setup-DinOFWiC.js → server-setup-BBSmse1J.js} +190 -127
- package/dist/server-setup-BBSmse1J.js.map +1 -0
- package/dist/{start-Dgsaz0HM.js → start-B7jTBpAc.js} +3 -3
- package/dist/{start-Dgsaz0HM.js.map → start-B7jTBpAc.js.map} +1 -1
- package/dist/{static-context-pack-CyucviRD.js → static-context-pack-BRqt4ajJ.js} +313 -6
- package/dist/static-context-pack-BRqt4ajJ.js.map +1 -0
- package/package.json +1 -1
- package/dist/ado-tools-xbuVU7YN.js +0 -1
- package/dist/aic-statusline-settings-LnoxjBPe.js.map +0 -1
- package/dist/balanced-profile-contract-XiIj4O1U.js +0 -127
- package/dist/balanced-profile-contract-XiIj4O1U.js.map +0 -1
- package/dist/claude-md-injection-BoXOsg7h.js.map +0 -1
- package/dist/claude-xO1XW-Nn.js.map +0 -1
- package/dist/copilot-discount-C3jfysK-.js.map +0 -1
- package/dist/engine-DwLIk1Zn.js +0 -1
- package/dist/internal-prompt-submit-B9MJxc3K.js.map +0 -1
- package/dist/internal-rebrief-zIdunX3R.js.map +0 -1
- package/dist/max-profile-contract-DQDEDCsR.js.map +0 -1
- package/dist/peer-mcp-personas-DDMKRFFG.js.map +0 -1
- package/dist/pi-jVNeQXWf.js.map +0 -1
- package/dist/server-setup-DinOFWiC.js.map +0 -1
- package/dist/static-context-pack-CyucviRD.js.map +0 -1
|
@@ -0,0 +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,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a,UAAU,QAAQ;IACnB;IACZ;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"}
|
|
@@ -4,7 +4,7 @@ import { a as fileReviewDebounce, d as stopGateEnabledForRepo, f as stopReviewSt
|
|
|
4
4
|
import { a as decideStopHook, c as launchBaselineKey, d as stopGateId, f as stopReviewEnabled, o as fileBlockBudget } from "./stop-gate-hook-BYd0NruJ.js";
|
|
5
5
|
import { t as liveExec } from "./orchestration-D-S_0GVt.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-
|
|
7
|
+
import { a as checksForDescriptor, n as readDiscoveredGate, o as descriptorHash, s as parseGateDescriptor } from "./gate-discovery-CqJVzT_D.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-
|
|
260
|
+
//# sourceMappingURL=internal-stop-hook-Dn_AF0BF.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-stop-hook-DGcRVh_2.js","names":[],"sources":["../src/internal-stop-hook.ts"],"sourcesContent":["/**\n * The internal `internal-stop-hook` subcommand: the executable a spawned Claude\n * Code session's Stop hook invokes (registered into the mirrored settings.json by\n * the launcher when `GH_ROUTER_ENABLE_STOP_GATE` is set). It reads Claude Code's\n * hook payload from stdin, runs the SEALED structural gate over the session's\n * working-tree diff, and maps the result to the hook exit contract: exit 2 (with\n * the reason on stderr) blocks the stop so the model fixes the failure; exit 0\n * allows it. The `stop_hook_active` loop guard (in `decideStopHook`) guarantees\n * it can never wedge the session.\n *\n * All decision logic lives in `decideStopHook` (pure, unit-tested); this wrapper\n * only does stdin read + the live `git diff` capture + the exit. The live firing\n * is verified by the gated E2E (it needs a real spawned session).\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 { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport { parseBoolEnv, runCommandCapture } from \"./lib/exec\"\nimport { PACKAGE_ROOT_FLAG, explicitPackageRoot } from \"./lib/package-root\"\nimport { liveExec } from \"./lib/orchestration\"\nimport { readDiscoveredGate } from \"./lib/orchestration/gate-discovery\"\nimport { checksForDescriptor, descriptorHash, parseGateDescriptor, type GateDescriptor } from \"./lib/orchestration/harness-parse\"\nimport { hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n decideStopHook,\n fileBlockBudget,\n launchBaselineKey,\n stopGateId,\n stopReviewEnabled,\n type StopReviewContext,\n} from \"./lib/orchestration/stop-gate-hook\"\nimport {\n fileBaselineStore,\n fileLastPromptStore,\n fileReviewDebounce,\n repoRoot,\n stopGateEnabledForRepo,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\nimport { parseIntEnv } from \"./lib/exec\"\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/** Max diff bytes scanned for gate-weakening: a hard cap so a huge generated diff\n * (e.g. a lockfile) can never OOM or stall the hook. */\nconst MAX_DIFF_BYTES = 2 * 1024 * 1024\n\n/** Build a tiny synthetic diff for untracked paths so the weakening scan sees\n * their contents too. No index mutation (`git add -N`) is needed. */\nasync function captureUntrackedDiff(cwd: string, paths: string[]): Promise<string> {\n const chunks: string[] = []\n let bytes = 0\n for (const untrackedPath of paths) {\n const result = await runCommandCapture(\n [\"git\", \"diff\", \"--no-index\", \"--\", \"/dev/null\", untrackedPath],\n { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES },\n )\n // `git diff --no-index` returns 1 when differences exist; anything else is an\n // actual failure. A truncated untracked diff is unknown, never \"no diff\".\n if (result.code !== 1 || result.truncated) throw new Error(`git diff for untracked file failed with exit ${result.code}`)\n bytes += Buffer.byteLength(result.stdout, \"utf8\")\n if (bytes > MAX_DIFF_BYTES) throw new Error(\"git working-tree capture exceeded its size limit\")\n chunks.push(result.stdout)\n }\n return chunks.join(\"\")\n}\n\n/** Capture every working-tree change WITHOUT mutating the user's index (no\n * `git add -N`). `git diff HEAD` covers staged + unstaged tracked changes;\n * `git ls-files --others` catches untracked files and each is diffed against an\n * empty file so gate-weakening in new tests is visible. Git failures/truncation\n * reject, so the decision layer runs the full checks instead of mistaking an\n * unknown tree for a no-diff turn. */\nexport async function captureStopGateDiff(cwd: string): Promise<string> {\n const [diffResult, untrackedResult] = await Promise.all([\n runCommandCapture([\"git\", \"diff\", \"HEAD\"], { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES }),\n runCommandCapture([\"git\", \"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"], {\n cwd,\n timeoutMs: 5_000,\n maxStdoutBytes: MAX_DIFF_BYTES,\n }),\n ])\n if (diffResult.code !== 0) throw new Error(`git diff failed with exit ${diffResult.code}`)\n if (untrackedResult.code !== 0) throw new Error(`git ls-files failed with exit ${untrackedResult.code}`)\n if (diffResult.truncated || untrackedResult.truncated) throw new Error(\"git working-tree capture exceeded its size limit\")\n\n const untrackedPaths = untrackedResult.stdout.split(\"\\0\").filter(Boolean)\n if (untrackedPaths.length === 0) return diffResult.stdout\n const untrackedDiff = await captureUntrackedDiff(cwd, untrackedPaths)\n if (Buffer.byteLength(diffResult.stdout, \"utf8\") + Buffer.byteLength(untrackedDiff, \"utf8\") > MAX_DIFF_BYTES) {\n throw new Error(\"git working-tree capture exceeded its size limit\")\n }\n return diffResult.stdout + untrackedDiff\n}\n\n/** Flush a message to stderr before exiting (process.exit can drop an unflushed\n * write; the model reads this stderr on a block). */\nasync function writeStderr(msg: string): Promise<void> {\n await new Promise<void>((resolve) => {\n process.stderr.write(msg, () => resolve())\n })\n}\n\n/**\n * Fire-and-forget spawn of the detached background reviewer. The payload (which\n * includes the up-to-2-MiB diff) is written to a temp file SYNCHRONOUSLY before\n * the spawn — a pipe to the child's stdin would race the parent's `process.exit`\n * and could deliver a truncated diff. The child reads the file (path passed via\n * `GH_ROUTER_STOP_REVIEW_PAYLOAD`), unlinks it, and inherits the proxy URL/nonce\n * env. Everything is swallowed: the advisory layer never affects the stop.\n */\nfunction spawnStopReview(ctx: StopReviewContext, extras: { prompt: string; transcriptPath: string }): void {\n let payloadPath: string | undefined\n try {\n const dir = stopReviewStateDir()\n mkdirSync(dir, { recursive: true })\n payloadPath = path.join(dir, `payload-${process.pid}-${randomBytes(4).toString(\"hex\")}.json`)\n writeFileSync(\n payloadPath,\n JSON.stringify({\n session_id: ctx.sessionId,\n cwd: ctx.cwd,\n diff: ctx.diff,\n prompt: extras.prompt,\n transcript_path: extras.transcriptPath,\n }),\n { mode: 0o600 },\n )\n // Invoke the same binary's `internal-stop-review` subcommand. Preserve the\n // package root when this hook itself runs from the relocated launcher.\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-stop-review\"], {\n detached: true,\n windowsHide: true,\n stdio: \"ignore\",\n env: { ...process.env, GH_ROUTER_STOP_REVIEW_PAYLOAD: payloadPath },\n })\n // A spawn failure (EAGAIN / EACCES / fork limit) is delivered ASYNCHRONOUSLY\n // via the child's 'error' event, AFTER this synchronous try block exits. With\n // no listener Node escalates it to an uncaughtException — which main.ts turns\n // into process.exit(1), corrupting the Stop hook's exit code. Swallow it here\n // (and drop the now-orphaned payload the child never read) so the advisory\n // spawn truly never affects the stop.\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 // Advisory spawn is best-effort; never disrupt the stop. If we wrote the\n // payload file but the spawn failed, drop it so it doesn't orphan (the\n // child — which would normally unlink it — never started).\n if (payloadPath) {\n try {\n unlinkSync(payloadPath)\n } catch {\n /* best-effort */\n }\n }\n }\n}\n\n/** The checks for a resolved descriptor: sealed descriptors resolve their sealed\n * command set; parsed/discovered carry their own. */\ntype ResolveChecks = NonNullable<Parameters<typeof decideStopHook>[0][\"resolveChecks\"]>\n\n/**\n * Build the dynamic `resolveChecks` for the live Stop hook, per the env the\n * launcher set:\n * - GH_ROUTER_STOP_GATE_PARSED → re-derive the deterministic parser at the\n * stop-time tree (stateless, no cache);\n * - GH_ROUTER_STOP_GATE_DISCOVERED → read the cached evidence-pinned record.\n * Both pin the checks to the descriptor's `workdir` (the repo root) and compute\n * the launch-stable baseline key so the launch-captured (pre-mutation) baseline\n * is read. Any miss → null → the hook fails OPEN.\n */\nfunction buildResolveChecks(mode: \"parsed\" | \"discovered\"): ResolveChecks {\n const includeTests = parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_RUN_TESTS) === true\n return async (cwd: string) => {\n const root = await repoRoot(cwd).catch(() => cwd)\n let descriptor: GateDescriptor | null = null\n if (mode === \"parsed\") {\n descriptor = await parseGateDescriptor(root, { includeTests }).catch(() => null)\n } else {\n const rec = await readDiscoveredGate(root).catch(() => null)\n if (rec) {\n descriptor = {\n kind: \"discovered\",\n checks: rec.checks,\n ecosystem: rec.ecosystem,\n workdir: root,\n evidence: rec.evidence,\n }\n }\n }\n if (!descriptor) return null\n const checks = checksForDescriptor(descriptor)\n if (checks.length === 0) return null\n const descriptorKey = descriptorHash(descriptor)\n const workdir = descriptor.workdir || root\n const token = process.env.GH_ROUTER_STOP_GATE_BASELINE_TOKEN || undefined\n return { checks, workdir, descriptorKey, baselineKey: launchBaselineKey(workdir, descriptorKey, token) }\n }\n}\n\n/** Which dynamic gate mode the launcher armed (sealed → undefined). */\nfunction dynamicMode(): \"parsed\" | \"discovered\" | undefined {\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_PARSED) === true) return \"parsed\"\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_DISCOVERED) === true) return \"discovered\"\n return undefined\n}\n\nexport const internalStopHook = defineCommand({\n meta: {\n name: \"internal-stop-hook\",\n description:\n \"Internal: the structural-gate Stop hook. Reads the Claude Code hook payload on stdin, \"\n + \"runs the sealed gate, exits 2 (blocks the stop) on a red gate or gate-weakening diff.\",\n },\n async run() {\n const stdin = readStdin()\n // The advisory review (hook V2) is wired only when it's enabled AND the\n // launcher injected the proxy URL/nonce. It is side-effect-only: the\n // deterministic gate below is unchanged and remains the only blocker.\n const reviewEnabled = stopReviewEnabled() && hookMcpRuntimeFromEnv() !== undefined\n let transcriptPath = \"\"\n let userPrompt = \"\"\n if (reviewEnabled) {\n // Parse the payload once for the transcript pointer + the session id used\n // to look up the user's last prompt (the Stop payload carries no prompt;\n // the UserPromptSubmit hook stashed it). Best-effort — a parse miss just\n // means the reviewer judges against the diff alone.\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const obj = p as { transcript_path?: unknown; session_id?: unknown }\n transcriptPath = typeof obj.transcript_path === \"string\" ? obj.transcript_path : \"\"\n const sid = typeof obj.session_id === \"string\" ? obj.session_id : \"\"\n if (sid) {\n userPrompt = (await fileLastPromptStore(stopReviewStateDir()).read(sid).catch(() => null)) ?? \"\"\n }\n }\n } catch {\n /* tolerate a non-JSON stdin */\n }\n }\n\n let decision: { exitCode: 0 | 2; stderr?: string }\n try {\n const timeoutEnv = parseIntEnv(process.env.GH_ROUTER_STOP_GATE_TIMEOUT_MS)\n const mode = dynamicMode()\n decision = await decideStopHook({\n stdin,\n gateId: stopGateId(),\n exec: liveExec,\n captureDiff: captureStopGateDiff,\n fallbackCwd: process.cwd(),\n budget: fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\")),\n baseline: fileBaselineStore(path.join(tmpdir(), \"gh-router-stopgate-baseline\")),\n isEnabledForRepo: (cwd) => stopGateEnabledForRepo(cwd),\n resolveChecks: mode ? buildResolveChecks(mode) : undefined,\n // parseIntEnv already rejects non-positive / non-integer / truncating\n // values, so undefined here means \"use the built-in default\".\n timeoutMs: timeoutEnv,\n reviewDebounce: reviewEnabled ? fileReviewDebounce(stopReviewStateDir()) : undefined,\n spawnReview: reviewEnabled\n ? (ctx) => spawnStopReview(ctx, { prompt: userPrompt, transcriptPath })\n : undefined,\n })\n } catch {\n // Fail OPEN on ANY unexpected error: a Stop hook must never wedge the\n // session, so an internal crash allows the stop (exit 0) rather than\n // surfacing a non-blocking error or a hang.\n process.exitCode = 0\n return\n }\n // Write any stderr the decision carries — both the exit-2 block reason AND\n // the LOUD exit-0 stand-down (max-block budget reached). A clean green stop\n // carries no stderr, so this stays silent on the common path.\n if (decision.stderr) {\n await writeStderr(`${decision.stderr}\\n`)\n }\n // Natural exit: set the code and return. A hard process.exit() races libuv's\n // stdio teardown on Windows (uv_async_send assertion) on the fast-return\n // paths. The detached review child is unref'd and the gate's children are\n // reaped, so no handle keeps the loop alive — the process exits with this\n // code. The exit-2 block contract is preserved (stderr is flushed above).\n process.exitCode = decision.exitCode\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,MAAM,iBAAiB;;;AAIvB,eAAe,qBAAqB,KAAa,OAAkC;CACjF,MAAM,SAAmB,CAAC;CAC1B,IAAI,QAAQ;CACZ,KAAK,MAAM,iBAAiB,OAAO;EACjC,MAAM,SAAS,MAAM,kBACnB;GAAC;GAAO;GA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F,QAAQ,CAER;EAGF,IAAI;EACJ,IAAI;GACF,MAAM,aAAa,YAAY,QAAQ,IAAI,8BAA8B;GACzE,MAAM,OAAO,YAAY;GACzB,WAAW,MAAM,eAAe;IAC9B;IACA,QAAQ,WAAW;IACnB,MAAM;IACN,aAAa;IACb,aAAa,QAAQ,IAAI;IACzB,QAAQ,gBAAgB,KAAK,KAAK,OAAO,GAAG,oBAAoB,CAAC;IACjE,UAAU,kBAAkB,KAAK,KAAK,OAAO,GAAG,6BAA6B,CAAC;IAC9E,mBAAmB,QAAQ,uBAAuB,GAAG;IACrD,eAAe,OAAO,mBAAmB,IAAI,IAAI,KAAA;IAGjD,WAAW;IACX,gBAAgB,gBAAgB,mBAAmB,mBAAmB,CAAC,IAAI,KAAA;IAC3E,aAAa,iBACR,QAAQ,gBAAgB,KAAK;KAAE,QAAQ;KAAY;IAAe,CAAC,IACpE,KAAA;GACN,CAAC;EACH,QAAQ;GAIN,QAAQ,WAAW;GACnB;EACF;EAIA,IAAI,SAAS,QACX,MAAM,YAAY,GAAG,SAAS,OAAO,GAAG;EAO1C,QAAQ,WAAW,SAAS;CAC9B;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"internal-stop-hook-Dn_AF0BF.js","names":[],"sources":["../src/internal-stop-hook.ts"],"sourcesContent":["/**\n * The internal `internal-stop-hook` subcommand: the executable a spawned Claude\n * Code session's Stop hook invokes (registered into the mirrored settings.json by\n * the launcher when `GH_ROUTER_ENABLE_STOP_GATE` is set). It reads Claude Code's\n * hook payload from stdin, runs the SEALED structural gate over the session's\n * working-tree diff, and maps the result to the hook exit contract: exit 2 (with\n * the reason on stderr) blocks the stop so the model fixes the failure; exit 0\n * allows it. The `stop_hook_active` loop guard (in `decideStopHook`) guarantees\n * it can never wedge the session.\n *\n * All decision logic lives in `decideStopHook` (pure, unit-tested); this wrapper\n * only does stdin read + the live `git diff` capture + the exit. The live firing\n * is verified by the gated E2E (it needs a real spawned session).\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 { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport { parseBoolEnv, runCommandCapture } from \"./lib/exec\"\nimport { PACKAGE_ROOT_FLAG, explicitPackageRoot } from \"./lib/package-root\"\nimport { liveExec } from \"./lib/orchestration\"\nimport { readDiscoveredGate } from \"./lib/orchestration/gate-discovery\"\nimport { checksForDescriptor, descriptorHash, parseGateDescriptor, type GateDescriptor } from \"./lib/orchestration/harness-parse\"\nimport { hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n decideStopHook,\n fileBlockBudget,\n launchBaselineKey,\n stopGateId,\n stopReviewEnabled,\n type StopReviewContext,\n} from \"./lib/orchestration/stop-gate-hook\"\nimport {\n fileBaselineStore,\n fileLastPromptStore,\n fileReviewDebounce,\n repoRoot,\n stopGateEnabledForRepo,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\nimport { parseIntEnv } from \"./lib/exec\"\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/** Max diff bytes scanned for gate-weakening: a hard cap so a huge generated diff\n * (e.g. a lockfile) can never OOM or stall the hook. */\nconst MAX_DIFF_BYTES = 2 * 1024 * 1024\n\n/** Build a tiny synthetic diff for untracked paths so the weakening scan sees\n * their contents too. No index mutation (`git add -N`) is needed. */\nasync function captureUntrackedDiff(cwd: string, paths: string[]): Promise<string> {\n const chunks: string[] = []\n let bytes = 0\n for (const untrackedPath of paths) {\n const result = await runCommandCapture(\n [\"git\", \"diff\", \"--no-index\", \"--\", \"/dev/null\", untrackedPath],\n { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES },\n )\n // `git diff --no-index` returns 1 when differences exist; anything else is an\n // actual failure. A truncated untracked diff is unknown, never \"no diff\".\n if (result.code !== 1 || result.truncated) throw new Error(`git diff for untracked file failed with exit ${result.code}`)\n bytes += Buffer.byteLength(result.stdout, \"utf8\")\n if (bytes > MAX_DIFF_BYTES) throw new Error(\"git working-tree capture exceeded its size limit\")\n chunks.push(result.stdout)\n }\n return chunks.join(\"\")\n}\n\n/** Capture every working-tree change WITHOUT mutating the user's index (no\n * `git add -N`). `git diff HEAD` covers staged + unstaged tracked changes;\n * `git ls-files --others` catches untracked files and each is diffed against an\n * empty file so gate-weakening in new tests is visible. Git failures/truncation\n * reject, so the decision layer runs the full checks instead of mistaking an\n * unknown tree for a no-diff turn. */\nexport async function captureStopGateDiff(cwd: string): Promise<string> {\n const [diffResult, untrackedResult] = await Promise.all([\n runCommandCapture([\"git\", \"diff\", \"HEAD\"], { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES }),\n runCommandCapture([\"git\", \"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"], {\n cwd,\n timeoutMs: 5_000,\n maxStdoutBytes: MAX_DIFF_BYTES,\n }),\n ])\n if (diffResult.code !== 0) throw new Error(`git diff failed with exit ${diffResult.code}`)\n if (untrackedResult.code !== 0) throw new Error(`git ls-files failed with exit ${untrackedResult.code}`)\n if (diffResult.truncated || untrackedResult.truncated) throw new Error(\"git working-tree capture exceeded its size limit\")\n\n const untrackedPaths = untrackedResult.stdout.split(\"\\0\").filter(Boolean)\n if (untrackedPaths.length === 0) return diffResult.stdout\n const untrackedDiff = await captureUntrackedDiff(cwd, untrackedPaths)\n if (Buffer.byteLength(diffResult.stdout, \"utf8\") + Buffer.byteLength(untrackedDiff, \"utf8\") > MAX_DIFF_BYTES) {\n throw new Error(\"git working-tree capture exceeded its size limit\")\n }\n return diffResult.stdout + untrackedDiff\n}\n\n/** Flush a message to stderr before exiting (process.exit can drop an unflushed\n * write; the model reads this stderr on a block). */\nasync function writeStderr(msg: string): Promise<void> {\n await new Promise<void>((resolve) => {\n process.stderr.write(msg, () => resolve())\n })\n}\n\n/**\n * Fire-and-forget spawn of the detached background reviewer. The payload (which\n * includes the up-to-2-MiB diff) is written to a temp file SYNCHRONOUSLY before\n * the spawn — a pipe to the child's stdin would race the parent's `process.exit`\n * and could deliver a truncated diff. The child reads the file (path passed via\n * `GH_ROUTER_STOP_REVIEW_PAYLOAD`), unlinks it, and inherits the proxy URL/nonce\n * env. Everything is swallowed: the advisory layer never affects the stop.\n */\nfunction spawnStopReview(ctx: StopReviewContext, extras: { prompt: string; transcriptPath: string }): void {\n let payloadPath: string | undefined\n try {\n const dir = stopReviewStateDir()\n mkdirSync(dir, { recursive: true })\n payloadPath = path.join(dir, `payload-${process.pid}-${randomBytes(4).toString(\"hex\")}.json`)\n writeFileSync(\n payloadPath,\n JSON.stringify({\n session_id: ctx.sessionId,\n cwd: ctx.cwd,\n diff: ctx.diff,\n prompt: extras.prompt,\n transcript_path: extras.transcriptPath,\n }),\n { mode: 0o600 },\n )\n // Invoke the same binary's `internal-stop-review` subcommand. Preserve the\n // package root when this hook itself runs from the relocated launcher.\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-stop-review\"], {\n detached: true,\n windowsHide: true,\n stdio: \"ignore\",\n env: { ...process.env, GH_ROUTER_STOP_REVIEW_PAYLOAD: payloadPath },\n })\n // A spawn failure (EAGAIN / EACCES / fork limit) is delivered ASYNCHRONOUSLY\n // via the child's 'error' event, AFTER this synchronous try block exits. With\n // no listener Node escalates it to an uncaughtException — which main.ts turns\n // into process.exit(1), corrupting the Stop hook's exit code. Swallow it here\n // (and drop the now-orphaned payload the child never read) so the advisory\n // spawn truly never affects the stop.\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 // Advisory spawn is best-effort; never disrupt the stop. If we wrote the\n // payload file but the spawn failed, drop it so it doesn't orphan (the\n // child — which would normally unlink it — never started).\n if (payloadPath) {\n try {\n unlinkSync(payloadPath)\n } catch {\n /* best-effort */\n }\n }\n }\n}\n\n/** The checks for a resolved descriptor: sealed descriptors resolve their sealed\n * command set; parsed/discovered carry their own. */\ntype ResolveChecks = NonNullable<Parameters<typeof decideStopHook>[0][\"resolveChecks\"]>\n\n/**\n * Build the dynamic `resolveChecks` for the live Stop hook, per the env the\n * launcher set:\n * - GH_ROUTER_STOP_GATE_PARSED → re-derive the deterministic parser at the\n * stop-time tree (stateless, no cache);\n * - GH_ROUTER_STOP_GATE_DISCOVERED → read the cached evidence-pinned record.\n * Both pin the checks to the descriptor's `workdir` (the repo root) and compute\n * the launch-stable baseline key so the launch-captured (pre-mutation) baseline\n * is read. Any miss → null → the hook fails OPEN.\n */\nfunction buildResolveChecks(mode: \"parsed\" | \"discovered\"): ResolveChecks {\n const includeTests = parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_RUN_TESTS) === true\n return async (cwd: string) => {\n const root = await repoRoot(cwd).catch(() => cwd)\n let descriptor: GateDescriptor | null = null\n if (mode === \"parsed\") {\n descriptor = await parseGateDescriptor(root, { includeTests }).catch(() => null)\n } else {\n const rec = await readDiscoveredGate(root).catch(() => null)\n if (rec) {\n descriptor = {\n kind: \"discovered\",\n checks: rec.checks,\n ecosystem: rec.ecosystem,\n workdir: root,\n evidence: rec.evidence,\n }\n }\n }\n if (!descriptor) return null\n const checks = checksForDescriptor(descriptor)\n if (checks.length === 0) return null\n const descriptorKey = descriptorHash(descriptor)\n const workdir = descriptor.workdir || root\n const token = process.env.GH_ROUTER_STOP_GATE_BASELINE_TOKEN || undefined\n return { checks, workdir, descriptorKey, baselineKey: launchBaselineKey(workdir, descriptorKey, token) }\n }\n}\n\n/** Which dynamic gate mode the launcher armed (sealed → undefined). */\nfunction dynamicMode(): \"parsed\" | \"discovered\" | undefined {\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_PARSED) === true) return \"parsed\"\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_DISCOVERED) === true) return \"discovered\"\n return undefined\n}\n\nexport const internalStopHook = defineCommand({\n meta: {\n name: \"internal-stop-hook\",\n description:\n \"Internal: the structural-gate Stop hook. Reads the Claude Code hook payload on stdin, \"\n + \"runs the sealed gate, exits 2 (blocks the stop) on a red gate or gate-weakening diff.\",\n },\n async run() {\n const stdin = readStdin()\n // The advisory review (hook V2) is wired only when it's enabled AND the\n // launcher injected the proxy URL/nonce. It is side-effect-only: the\n // deterministic gate below is unchanged and remains the only blocker.\n const reviewEnabled = stopReviewEnabled() && hookMcpRuntimeFromEnv() !== undefined\n let transcriptPath = \"\"\n let userPrompt = \"\"\n if (reviewEnabled) {\n // Parse the payload once for the transcript pointer + the session id used\n // to look up the user's last prompt (the Stop payload carries no prompt;\n // the UserPromptSubmit hook stashed it). Best-effort — a parse miss just\n // means the reviewer judges against the diff alone.\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const obj = p as { transcript_path?: unknown; session_id?: unknown }\n transcriptPath = typeof obj.transcript_path === \"string\" ? obj.transcript_path : \"\"\n const sid = typeof obj.session_id === \"string\" ? obj.session_id : \"\"\n if (sid) {\n userPrompt = (await fileLastPromptStore(stopReviewStateDir()).read(sid).catch(() => null)) ?? \"\"\n }\n }\n } catch {\n /* tolerate a non-JSON stdin */\n }\n }\n\n let decision: { exitCode: 0 | 2; stderr?: string }\n try {\n const timeoutEnv = parseIntEnv(process.env.GH_ROUTER_STOP_GATE_TIMEOUT_MS)\n const mode = dynamicMode()\n decision = await decideStopHook({\n stdin,\n gateId: stopGateId(),\n exec: liveExec,\n captureDiff: captureStopGateDiff,\n fallbackCwd: process.cwd(),\n budget: fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\")),\n baseline: fileBaselineStore(path.join(tmpdir(), \"gh-router-stopgate-baseline\")),\n isEnabledForRepo: (cwd) => stopGateEnabledForRepo(cwd),\n resolveChecks: mode ? buildResolveChecks(mode) : undefined,\n // parseIntEnv already rejects non-positive / non-integer / truncating\n // values, so undefined here means \"use the built-in default\".\n timeoutMs: timeoutEnv,\n reviewDebounce: reviewEnabled ? fileReviewDebounce(stopReviewStateDir()) : undefined,\n spawnReview: reviewEnabled\n ? (ctx) => spawnStopReview(ctx, { prompt: userPrompt, transcriptPath })\n : undefined,\n })\n } catch {\n // Fail OPEN on ANY unexpected error: a Stop hook must never wedge the\n // session, so an internal crash allows the stop (exit 0) rather than\n // surfacing a non-blocking error or a hang.\n process.exitCode = 0\n return\n }\n // Write any stderr the decision carries — both the exit-2 block reason AND\n // the LOUD exit-0 stand-down (max-block budget reached). A clean green stop\n // carries no stderr, so this stays silent on the common path.\n if (decision.stderr) {\n await writeStderr(`${decision.stderr}\\n`)\n }\n // Natural exit: set the code and return. A hard process.exit() races libuv's\n // stdio teardown on Windows (uv_async_send assertion) on the fast-return\n // paths. The detached review child is unref'd and the gate's children are\n // reaped, so no handle keeps the loop alive — the process exits with this\n // code. The exit-2 block contract is preserved (stderr is flushed above).\n process.exitCode = decision.exitCode\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,MAAM,iBAAiB;;;AAIvB,eAAe,qBAAqB,KAAa,OAAkC;CACjF,MAAM,SAAmB,CAAC;CAC1B,IAAI,QAAQ;CACZ,K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B,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,YAAY,IAAI,KAAM;GAElG;EACF,QAAQ,CAER;EAGF,IAAI;EACJ,IAAI;GACF,MAAM,aAAa,YAAY,QAAQ,IAAI,8BAA8B;GACzE,MAAM,OAAO,YAAY;GACzB,WAAW,MAAM,eAAe;IAC9B;IACA,QAAQ,WAAW;IACnB,MAAM;IACN,aAAa;IACb,aAAa,QAAQ,IAAI;IACzB,QAAQ,gBAAgB,KAAK,KAAK,OAAO,GAAG,oBAAoB,CAAC;IACjE,UAAU,kBAAkB,KAAK,KAAK,OAAO,GAAG,6BAA6B,CAAC;IAC9E,mBAAmB,QAAQ,uBAAuB,GAAG;IACrD,eAAe,OAAO,mBAAmB,IAAI,IAAI,KAAA;IAGjD,WAAW;IACX,gBAAgB,gBAAgB,mBAAmB,mBAAmB,CAAC,IAAI,KAAA;IAC3E,aAAa,iBACR,QAAQ,gBAAgB,KAAK;KAAE,QAAQ;KAAY;IAAe,CAAC,IACpE,KAAA;GACN,CAAC;EACH,QAAQ;GAIN,QAAQ,WAAW;GACnB;EACF;EAIA,IAAI,SAAS,QACX,MAAM,YAAY,GAAG,SAAS,OAAO,GAAG;EAO1C,QAAQ,WAAW,SAAS;CAC9B;AACF,CAAC"}
|
package/dist/main.js
CHANGED
|
@@ -47,28 +47,28 @@ const main = defineCommand({
|
|
|
47
47
|
},
|
|
48
48
|
subCommands: {
|
|
49
49
|
auth: () => import("./auth-a_1lXYZ1.js").then((m) => m.auth),
|
|
50
|
-
start: () => import("./start-
|
|
51
|
-
claude: () => import("./claude-
|
|
52
|
-
codex: () => import("./codex-
|
|
53
|
-
pi: () => import("./pi-
|
|
54
|
-
serve: () => import("./serve-
|
|
50
|
+
start: () => import("./start-B7jTBpAc.js").then((m) => m.start),
|
|
51
|
+
claude: () => import("./claude-C_1OM7ce.js").then((m) => m.claude),
|
|
52
|
+
codex: () => import("./codex-5eTmciDG.js").then((m) => m.codex),
|
|
53
|
+
pi: () => import("./pi-2m2IgZlm.js").then((m) => m.pi),
|
|
54
|
+
serve: () => import("./serve-8tXHVHOr.js").then((m) => m.serve),
|
|
55
55
|
models: () => import("./models-JIvKAGn0.js").then((m) => m.models),
|
|
56
56
|
"check-usage": () => import("./check-usage-Bsbc-Sn6.js").then((m) => m.checkUsage),
|
|
57
57
|
index: () => import("./index-cmd-CJXUOH4q.js").then((m) => m.indexCmd),
|
|
58
58
|
debug: () => import("./debug-BtqbflcL.js").then((m) => m.debug),
|
|
59
|
-
"internal-stop-hook": () => import("./internal-stop-hook-
|
|
60
|
-
"internal-prompt-submit": () => import("./internal-prompt-submit-
|
|
59
|
+
"internal-stop-hook": () => import("./internal-stop-hook-Dn_AF0BF.js").then((m) => m.internalStopHook),
|
|
60
|
+
"internal-prompt-submit": () => import("./internal-prompt-submit-CDTwamkW.js").then((m) => m.internalPromptSubmit),
|
|
61
61
|
"internal-stop-review": () => import("./internal-stop-review-X7zRRhyc.js").then((m) => m.internalStopReview),
|
|
62
62
|
"internal-plan-review": () => import("./internal-plan-review-DIvaBBUd.js").then((m) => m.internalPlanReview),
|
|
63
|
-
"internal-rebrief": () => import("./internal-rebrief-
|
|
63
|
+
"internal-rebrief": () => import("./internal-rebrief-DZygfGHp.js").then((m) => m.internalRebrief),
|
|
64
64
|
"internal-session-bind": () => import("./internal-session-bind-CQLDPuTx.js").then((m) => m.internalSessionBind),
|
|
65
65
|
"internal-workspace-header": () => import("./internal-workspace-header-DiUnkUeU.js").then((m) => m.internalWorkspaceHeader),
|
|
66
66
|
"internal-artifact-open": () => import("./internal-artifact-open-C67gDjKo.js").then((m) => m.internalArtifactOpen),
|
|
67
67
|
"internal-first-mate-guard": () => import("./internal-first-mate-guard-D-IQGiTs.js").then((m) => m.internalFirstMateGuard),
|
|
68
68
|
"internal-worker-guard": () => import("./internal-worker-guard-wP3UN-3D.js").then((m) => m.internalWorkerGuard),
|
|
69
|
-
"internal-fast-dispatch-guard": () => import("./internal-fast-dispatch-guard-
|
|
70
|
-
"internal-max-dispatch-guard": () => import("./internal-max-dispatch-guard-
|
|
71
|
-
"internal-aic-status": () => import("./internal-aic-status-
|
|
69
|
+
"internal-fast-dispatch-guard": () => import("./internal-fast-dispatch-guard-A8teEib4.js").then((m) => m.internalFastDispatchGuard),
|
|
70
|
+
"internal-max-dispatch-guard": () => import("./internal-max-dispatch-guard-BM_B15EH.js").then((m) => m.internalMaxDispatchGuard),
|
|
71
|
+
"internal-aic-status": () => import("./internal-aic-status-wYPsCG4r.js").then((m) => m.internalAicStatus)
|
|
72
72
|
}
|
|
73
73
|
});
|
|
74
74
|
/**
|
|
@@ -36,7 +36,7 @@ const ENDPOINTS = {
|
|
|
36
36
|
function fastEndpointRequirement(modelId) {
|
|
37
37
|
const id = modelId.replace(/(?:\[1m\])+$/i, "");
|
|
38
38
|
if (id === "gemini-3.8-flash") return "chat";
|
|
39
|
-
if (id === "gpt-6-luna" || id === "gpt-5.6-luna" || id === "gpt-6-sol" || id === "gpt-5.6-sol" || id === "grok-4.6" || id === "gpt-6-astra") return "responses";
|
|
39
|
+
if (id === "gpt-6-luna" || id === "gpt-5.6-luna" || id === "gpt-6-sol" || id === "gpt-5.6-sol" || id === "gpt-6.1-sol" || id === "grok-4.6" || id === "grok-4.7" || id === "gpt-6-astra") return "responses";
|
|
40
40
|
if (id === "claude-opus-5.5" || id === "claude-opus-5-5" || id === "claude-opus-5.5" || id === "claude-sonnet-5") return "messages";
|
|
41
41
|
}
|
|
42
42
|
/**
|
|
@@ -353,4 +353,4 @@ function maxCodexReviewerModel() {
|
|
|
353
353
|
//#endregion
|
|
354
354
|
export { normalizeTrailingOneMSuffix as A, MAX_PARALLELISM_RULE as C, maxPeerInstructions as D, maxPeerDescription as E, fastEndpointForCatalogId as O, MAX_COORDINATOR_PROMPT as S, maxNativePrompt as T, maxReviewerModel as _, MAX_PROFILE_NATIVE_AGENT_NAMES as a, MAX_ADVISOR_SYSTEM_PROMPT as b, formatMaxPrerequisiteFailure as c, maxAdvisorPinIsValid as d, maxCodexReviewerModel as f, maxProReplacementModel as g, maxOpusModel as h, MAX_PROFILE_MODELS as i, stripTrailingOneMSuffix as j, fastEndpointForModel as k, maxAdvisorEffortForModel as l, maxGrokModel as m, MAX_PROFILE_ALLOWED_LEAD_MODEL_IDS as n, MAX_PROFILE_NATIVE_EFFORTS as o, maxGeminiModel as p, MAX_PROFILE_LEAD_MODEL as r, MAX_PROFILE_NATIVE_MODELS as s, MAX_PROFILE_ADVISOR_INSTRUCTIONS as t, maxAdvisorModelFromPin as u, maxSonnetModel as v, maxNativeDescription as w, MAX_COORDINATOR_DESCRIPTION as x, validateMaxProfilePrerequisites as y };
|
|
355
355
|
|
|
356
|
-
//# sourceMappingURL=max-profile-contract-
|
|
356
|
+
//# sourceMappingURL=max-profile-contract-CMvzKSsg.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"max-profile-contract-CMvzKSsg.js","names":[],"sources":["../src/lib/model-suffix.ts","../src/lib/fast-endpoint.ts","../src/lib/max-profile-prompts.ts","../src/lib/max-profile-contract.ts"],"sourcesContent":["/**\n * Normalize Claude Code's local 1M-context decoration at model boundaries.\n *\n * `[1m]` is a client-side accounting marker, not part of a Copilot catalog id.\n * Claude Code can append its own marker to a picker value that is already\n * decorated by the router, producing a reachable doubled suffix. Keep the\n * helper dependency-free so launch/profile code and request preprocessing use\n * exactly the same trailing-suffix rule without an import cycle.\n */\nexport interface TrailingOneMSuffix {\n base: string\n hadSuffix: boolean\n}\n\n/** Strip every trailing `[1m]` marker, case-insensitively. */\nexport function stripTrailingOneMSuffix(id: string): TrailingOneMSuffix {\n const match = id.match(/(?:\\[1m\\])+$/i)\n if (!match || match.index === undefined) {\n return { base: id, hadSuffix: false }\n }\n return { base: id.slice(0, match.index), hadSuffix: true }\n}\n\n/** Reapply at most one canonical `[1m]` marker when the input had one. */\nexport function normalizeTrailingOneMSuffix(id: string): string {\n const { base, hadSuffix } = stripTrailingOneMSuffix(id)\n return hadSuffix ? `${base}[1m]` : base\n}\n\n/** Append one marker without ever creating a doubled suffix. */\nexport function withTrailingOneMSuffix(id: string): string {\n const { base } = stripTrailingOneMSuffix(id)\n return `${base}[1m]`\n}\n","import type { Model } from \"~/services/copilot/get-models\"\n\n// Fast endpoint policy is intentionally kept separate from the standard\n// pickEndpoint() resolver. See fastEndpointRequirement below.\n\n/** Endpoint clients used by the fast profile's fixed roster. */\nexport type FastEndpoint = \"chat\" | \"responses\" | \"messages\"\n\nconst ENDPOINTS: Readonly<Record<FastEndpoint, ReadonlySet<string>>> = {\n chat: new Set([\"/chat/completions\", \"/v1/chat/completions\"]),\n responses: new Set([\"/responses\", \"/v1/responses\"]),\n messages: new Set([\"/messages\", \"/v1/messages\"]),\n}\n\n/**\n * Return the endpoint mandated by a fast-profile roster model.\n *\n * This is intentionally independent of the standard `pickEndpoint`: that\n * resolver prefers chat when a catalog entry advertises both clients, while\n * fast roles have a fixed provider contract. Gemini stays on chat; Luna, Sol,\n * and Grok stay on Responses; the Opus Oracle stays on native Messages.\n * Unknown ids return undefined so a fast caller cannot guess a transport.\n */\nexport function fastEndpointRequirement(modelId: string): FastEndpoint | undefined {\n const id = modelId.replace(/(?:\\[1m\\])+$/i, \"\")\n if (id === \"gemini-3.8-flash\") return \"chat\"\n if (id === \"gpt-6-luna\" || id === \"gpt-5.6-luna\" || id === \"gpt-6-sol\" || id === \"gpt-5.6-sol\" || id === \"gpt-6.1-sol\" || id === \"grok-4.6\" || id === \"grok-4.7\" || id === \"gpt-6-astra\") {\n return \"responses\"\n }\n if (id === \"claude-opus-5.5\" || id === \"claude-opus-5-5\" || id === \"claude-opus-5.5\" || id === \"claude-sonnet-5\") return \"messages\"\n return undefined\n}\n\n/**\n * Resolve the fixed fast transport only when the catalog explicitly advertises\n * the required endpoint. An entry that advertises both still resolves to the\n * policy endpoint, regardless of advertisement order.\n */\nexport function advertisesEndpoint(\n model: Model | undefined,\n endpoint: FastEndpoint,\n): boolean {\n const advertised = model?.supported_endpoints\n return Array.isArray(advertised)\n && advertised.some((value) => ENDPOINTS[endpoint].has(value))\n}\n\nexport function fastEndpointForModel(model: Model): FastEndpoint | undefined {\n const required = fastEndpointRequirement(model.id)\n if (!required) return undefined\n return advertisesEndpoint(model, required) ? required : undefined\n}\n\n/** Resolve a fast endpoint from a catalog id, without selecting a fallback. */\nexport function fastEndpointForCatalogId(\n modelId: string,\n catalog: ReadonlyArray<Model> | undefined,\n): FastEndpoint | undefined {\n const found = catalog?.find((model) => model.id === modelId)\n return found ? fastEndpointForModel(found) : undefined\n}\n\n/** Human-readable endpoint name for prerequisite diagnostics. */\nexport function fastEndpointLabel(endpoint: FastEndpoint): string {\n return endpoint === \"chat\"\n ? \"Chat Completions\"\n : endpoint === \"responses\"\n ? \"Responses\"\n : \"Messages\"\n}\n","import type { Effort } from \"./reasoning-effort\"\n\nexport const MAX_PARALLELISM_RULE =\n \"When two or more delegated workstreams are independent and non-overlapping, issue them together; sequence them when one needs another's result or their side effects can conflict.\"\n\nexport type MaxNativePromptRole =\n | \"Explore\"\n | \"Plan\"\n | \"general-purpose\"\n | \"implementer\"\n | \"reviewer\"\n | \"brainstorm\"\n\ninterface MaxNativePromptSpec {\n capability: string\n useWhen: string\n notFor: string\n returns: string\n prompt: string\n}\n\nconst MAX_NATIVE_PROMPT_SPECS: Record<MaxNativePromptRole, MaxNativePromptSpec> = {\n Explore: {\n capability: \"read-oriented repository exploration\",\n useWhen: \"the answer requires broad, multi-file or multi-source discovery and the caller needs conclusions rather than raw context\",\n notFor: \"a narrow lookup, implementation planning, or editing\",\n returns: \"concise conclusions, load-bearing file:line evidence, checks or sources consulted, and explicit gaps\",\n prompt: \"Explore the supplied question across the actual repository. Stay within discovery: do not plan the implementation or modify files. Return concise conclusions, load-bearing file:line evidence, checks or sources consulted, and explicit gaps. Stop when the question is supported or the missing evidence is identified. You do not have Advisor or native-agent delegation tools.\",\n },\n Plan: {\n capability: \"implementation planning\",\n useWhen: \"a non-trivial change crosses interfaces, has dependency or migration ordering, preserves important invariants, or needs explicit acceptance criteria\",\n notFor: \"routine decomposition, implementation, approval, or silently deciding unresolved product choices\",\n returns: \"affected files or symbols, ordered implementation slices, invariants, risks, open decisions, acceptance criteria, and runnable verification\",\n prompt: \"Turn the supplied goal, constraints, and evidence into an actionable implementation plan. Return affected files or symbols, ordered implementation slices with real dependencies identified, invariants, risks, open decisions, acceptance criteria, and runnable verification. Surface unresolved product or architecture choices instead of deciding them silently. Stop when another agent can implement the plan without rediscovering its structure; the lead owns acceptance and execution. You do not have Advisor or native-agent delegation tools.\",\n },\n \"general-purpose\": {\n capability: \"bounded mixed investigation and execution\",\n useWhen: \"one owner should carry a multi-step outcome across several narrower kinds of work\",\n notFor: \"a narrow direct action or a task cleanly owned by one specialist\",\n returns: \"the requested outcome, changed artifacts, verification evidence, blockers, and residual risks\",\n prompt: \"Own the supplied bounded outcome end to end. Return the requested outcome, changed artifacts, verification evidence, blockers, and residual risks. Stop at the requested scope and do not absorb adjacent cleanup. Do not re-delegate the core assignment merely to repeat it; any supporting delegation must be independent, non-overlapping, and integrated and verified by you.\",\n },\n implementer: {\n capability: \"bounded coding implementation\",\n useWhen: \"the desired behavior and constraints are settled but the implementation still needs coding judgment\",\n notFor: \"unresolved product behavior, architecture choices, or an unbounded investigation\",\n returns: \"a coherent scoped change, files changed, observable behavior, checks and results, blockers, and unresolved risks\",\n prompt: \"Implement the settled desired behavior within the supplied scope and repository conventions. Return the files changed, observable behavior, checks and results, blockers, and unresolved risks. Stop and report when ambiguity would materially change product behavior, architecture, or scope. Do not re-delegate the core assignment merely to repeat it; any supporting delegation must be independent, non-overlapping, and integrated and verified by you.\",\n },\n reviewer: {\n capability: \"repository-aware verification and reproduction\",\n useWhen: \"an implementation or failure already exists and assessment requires repository navigation, commands, tests, or runtime evidence\",\n notFor: \"a stateless review of an already self-contained artifact or authoring the fix\",\n returns: \"a calibrated verdict, severity-ranked findings, file:line evidence, concrete failure scenarios, checks and results, and unverified areas\",\n prompt: \"Assess the supplied artifact against its intent and the actual repository or runtime state. Return a calibrated verdict, severity-ranked findings, file:line evidence, concrete failure scenarios, checks and results, and unverified areas. Distinguish no findings from checks not run. Do not modify files or act as an approval gate. Stop when material claims have been tested to the available extent; the lead owns remediation and go/no-go. You do not have Advisor or native-agent delegation tools.\",\n },\n brainstorm: {\n capability: \"divergent repository-feasible option generation\",\n useWhen: \"materially different approaches remain credible before implementation planning\",\n notFor: \"a settled approach, proven fact, implementation plan, or code change\",\n returns: \"distinct options, trade-offs, assumptions, failure modes, discriminating evidence, and a recommendation only when supported\",\n prompt: \"Explore the useful design space for the supplied open decision. Return materially distinct repository-feasible options, trade-offs, assumptions, failure modes, discriminating evidence, and a recommendation only when the available evidence supports one. Do not turn the result into an implementation plan or modify files. Stop once the useful alternatives are covered or one option clearly dominates; the lead owns the decision. You do not have Advisor or native-agent delegation tools.\",\n },\n}\n\nexport function maxNativeDescription(\n role: MaxNativePromptRole,\n model: string,\n effort: Effort,\n): string {\n const spec = MAX_NATIVE_PROMPT_SPECS[role]\n return `Max-profile ${spec.capability} subagent running ${model} at ${effort} effort. Use when: ${spec.useWhen}. Not for: ${spec.notFor}. Returns: ${spec.returns}.`\n}\n\nexport function maxNativePrompt(role: MaxNativePromptRole): string {\n return MAX_NATIVE_PROMPT_SPECS[role].prompt\n}\n\nexport const MAX_COORDINATOR_DESCRIPTION =\n \"Max-profile peer-review coordinator running gpt-6-luna at maximum effort. Use when: a consequential self-contained plan, design, or diff has at least two distinct unresolved risk lenses for which independent fresh-context review could change the decision. Not for: routine second opinions, repository exploration or execution, facts a focused check can settle, or repeating one generic review across models. Returns: a provenance-preserving synthesis of material findings, disagreements, evidence gaps, and the cheapest checks that can settle them.\"\n\nexport const MAX_COORDINATOR_PROMPT =\n `Coordinate independent fresh-context review of the self-contained artifact and constraints supplied by the caller. You have peer tools only and cannot inspect the repository, transcript, or runtime, so identify missing material instead of guessing. Select the smallest sufficient peer set: use one peer when one lens is enough, and multiple peers only for distinct unresolved risk dimensions. Give every peer a non-overlapping lens; do not send one generic brief to several models or duplicate a same-family lens as a vote. ${MAX_PARALLELISM_RULE} Deduplicate findings while preserving provenance and genuine disagreement. Return severity-ranked material findings, concrete failure scenarios, confidence, evidence gaps, and the cheapest repository check or test that can settle each disagreement. Do not count votes or issue an evidence-free approval. Peer output is advisory; the lead owns go/no-go and remediation.`\n\nexport type MaxPeerKind = \"strategic critic\" | \"line-level reviewer\"\n\nexport interface MaxPeerPromptOptions {\n name: string\n model: string\n kind: MaxPeerKind\n lens: string\n useWhen: string\n notFor: string\n}\n\nexport function maxPeerDescription(opts: MaxPeerPromptOptions): string {\n return `Max-profile ${opts.kind} backed by ${opts.model}. Lens: ${opts.lens}. Use when: ${opts.useWhen}. Not for: ${opts.notFor}. Cold-start: it has no repository or transcript access and sees only the supplied prompt, context, and images. Returns: only material findings, or an explicit no material finding result.`\n}\n\nexport function maxPeerInstructions(opts: MaxPeerPromptOptions): string {\n const locationRule = opts.kind === \"line-level reviewer\"\n ? \"For each finding, cite a location from the supplied artifact, give severity and a concrete failure scenario, and suggest the smallest correction.\"\n : \"For each finding, identify the failed assumption or invariant, its consequence, and the cheapest evidence that would confirm or refute it.\"\n return `You are ${opts.name}, a fresh-context ${opts.kind} running on ${opts.model}. Apply this lens: ${opts.lens}. You have no repository or transcript access; use only the supplied artifact, constraints, and images. If material context is missing, identify it instead of guessing. ${locationRule} Treat supplied locations as citations to the artifact, not proof of repository state. Report only material findings; \"no material finding\" is a valid result. Stop when the requested lens is covered without padding or manufactured objections.`\n}\n\nexport const MAX_ADVISOR_TOOL_INSTRUCTIONS = `# Advisor Tool\n\nYou have access to an optional, primary-lead-only, transcript-aware Max Advisor. Transcript awareness makes it useful for detecting framing drift, changed assumptions, and a stuck strategy; it is not an independent repository verifier, supervisor, approver, workflow gate, or substitute for your own reasoning. You keep decision ownership.\n\nUse it for one precise consequential uncertainty that remains after proportionate direct investigation and cannot be settled by repository evidence, a focused command or test, Plan, reviewer, or a fresh-context peer. State the question, relevant evidence, credible alternatives, and what evidence would change the decision. Evidence-first does not require invoking every role before Advisor.\n\nDo not call it for initial investigation, routine progress, waiting, ordinary verification, planner approval, reviewer confirmation, reassurance, or completion ceremony. Treat its result as advice, not authority. Consult again only when materially new or conflicting evidence creates a different question.`\n\nexport const MAX_ADVISOR_SYSTEM_PROMPT =\n \"You are a non-binding, transcript-aware consultant to the primary lead. Answer the stated consequential question first, then give your recommendation and confidence, the transcript evidence and assumptions supporting it, the material risk, one credible alternative, and the evidence that would reverse your recommendation. The transcript may anchor you to the lead's framing, so identify any framing or assumption the session has stopped questioning. Stop after answering the focused question. Do not supervise, approve, veto, or redesign unrelated work; the lead weighs your advice against the user's intent and verified repository evidence.\"\n","import type { Model, ModelsResponse } from \"~/services/copilot/get-models\"\nimport type { Effort } from \"./reasoning-effort\"\nimport {\n advertisesEndpoint,\n fastEndpointForModel,\n} from \"./fast-endpoint\"\nimport { MAX_ADVISOR_TOOL_INSTRUCTIONS } from \"./max-profile-prompts\"\nimport { stripTrailingOneMSuffix } from \"./model-suffix\"\nimport { state } from \"./state\"\n\n// Max uses the same context threshold as Claude Code's `[1m]` accounting.\nexport const MAX_REQUIRED_CONTEXT_TOKENS = 1_000_000\n\nconst ONE_M_TOKENS = MAX_REQUIRED_CONTEXT_TOKENS\n\nfunction catalogModels(): Array<Model> {\n return state.models?.data ?? []\n}\n\nfunction catalogModel(id: string): Model | undefined {\n return catalogModels().find((model) => model.id === id)\n}\n\n\nexport const MAX_PROFILE_MODELS = Object.freeze({\n sol: \"gpt-5.6-sol\",\n luna: \"gpt-6-luna\",\n gemini: \"gemini-3.8-flash\",\n grok: \"grok-4.6\",\n opus: \"claude-opus-5.5\",\n sonnet: \"claude-sonnet-5\",\n codex: \"gpt-5.3-codex\",\n} as const)\n\nexport const MAX_PROFILE_NATIVE_AGENT_NAMES = [\n \"Explore\",\n \"Plan\",\n \"general-purpose\",\n \"implementer\",\n \"reviewer\",\n \"brainstorm\",\n \"peer-review-coordinator\",\n] as const\n\nexport type MaxProfileNativeAgentName =\n (typeof MAX_PROFILE_NATIVE_AGENT_NAMES)[number]\n\nexport const MAX_PROFILE_NATIVE_EFFORTS = Object.freeze({\n Explore: \"high\",\n Plan: \"high\",\n \"general-purpose\": \"max\",\n implementer: \"high\",\n reviewer: \"xhigh\",\n brainstorm: \"high\",\n \"peer-review-coordinator\": \"max\",\n} as const satisfies Record<MaxProfileNativeAgentName, Effort>)\n\n/** Default model family behind each native role's frontmatter. */\nexport const MAX_PROFILE_NATIVE_MODELS = Object.freeze({\n Explore: MAX_PROFILE_MODELS.luna,\n Plan: MAX_PROFILE_MODELS.sol,\n \"general-purpose\": MAX_PROFILE_MODELS.luna,\n implementer: MAX_PROFILE_MODELS.gemini,\n reviewer: MAX_PROFILE_MODELS.sonnet,\n brainstorm: MAX_PROFILE_MODELS.opus,\n \"peer-review-coordinator\": MAX_PROFILE_MODELS.luna,\n} as const satisfies Record<MaxProfileNativeAgentName, string>)\n\nexport const MAX_PROFILE_LEAD_MODEL = MAX_PROFILE_MODELS.sol\nexport const MAX_PROFILE_ADVISOR_MODEL = MAX_PROFILE_MODELS.opus\nexport const MAX_PROFILE_ADVISOR_EFFORT = \"high\" as const\nexport const MAX_PROFILE_ADVISOR_INSTRUCTIONS = MAX_ADVISOR_TOOL_INSTRUCTIONS\n\nexport function maxAdvisorModelFromPin(pinned: string | undefined, opusModel?: string): string {\n const trimmed = pinned?.trim()\n const base = trimmed ? stripTrailingOneMSuffix(trimmed).base : undefined\n if (base === MAX_PROFILE_MODELS.sol || base === \"gpt-6-sol\" || base === MAX_PROFILE_MODELS.opus) {\n return base\n }\n return opusModel ?? MAX_PROFILE_MODELS.opus\n}\n\nexport function maxAdvisorPinIsValid(pinned: string | undefined): boolean {\n const trimmed = pinned?.trim()\n const base = trimmed ? stripTrailingOneMSuffix(trimmed).base : trimmed\n return base === undefined\n || base === \"\"\n || base === MAX_PROFILE_MODELS.sol\n || base === \"gpt-6-sol\"\n || base === MAX_PROFILE_MODELS.opus\n}\n\nexport function maxAdvisorModelFromPinStrict(pinned: string | undefined, opusModel?: string): string {\n if (!maxAdvisorPinIsValid(pinned)) return opusModel ?? MAX_PROFILE_MODELS.opus\n return maxAdvisorModelFromPin(pinned, opusModel)\n}\n\nexport function maxStandInAvailable(): boolean {\n return usableSol(catalogModel(MAX_PROFILE_MODELS.sol))\n && maxOpusModel() !== undefined\n && (maxGrokHighModel() !== undefined || maxGeminiModel() !== undefined)\n}\nexport function maxAdvisorEffortForModel(_model: string): Effort {\n return MAX_PROFILE_ADVISOR_EFFORT\n}\n\nexport const MAX_PROFILE_NATIVE_MODEL_IDS = Object.freeze([\n MAX_PROFILE_MODELS.luna,\n MAX_PROFILE_MODELS.gemini,\n MAX_PROFILE_MODELS.grok,\n] as const)\n\nexport const MAX_PROFILE_ALLOWED_LEAD_MODEL_IDS = Object.freeze([\n MAX_PROFILE_MODELS.sol,\n \"gpt-6-sol\",\n MAX_PROFILE_MODELS.luna,\n MAX_PROFILE_MODELS.gemini,\n MAX_PROFILE_MODELS.opus,\n] as const)\n\nexport type MaxProfileAllowedLeadModel =\n (typeof MAX_PROFILE_ALLOWED_LEAD_MODEL_IDS)[number]\n\nexport interface MaxProfilePrerequisiteCheck {\n ok: boolean\n missing: ReadonlyArray<string>\n /** Resolved optional/third-lab assignments for the launch. */\n models: {\n sol?: Model\n luna?: Model\n gemini?: Model\n grok?: Model\n opus?: Model\n sonnet?: Model\n thirdLab?: \"gemini\" | \"grok\"\n }\n}\n\nfunction findModel(\n catalog: ModelsResponse | undefined,\n id: string,\n): Model | undefined {\n return catalog?.data?.find((model) => model.id === id)\n}\n\nfunction hasToolCalls(model: Model | undefined): boolean {\n return model?.capabilities?.supports?.tool_calls === true\n}\n\nfunction hasContextAtLeast(model: Model | undefined, tokens: number): boolean {\n return (model?.capabilities?.limits?.max_context_window_tokens ?? 0) >= tokens\n}\n\nfunction supportsEffort(model: Model | undefined, effort: Effort): boolean {\n const ladder = model?.capabilities?.supports?.reasoning_effort\n return Array.isArray(ladder) && ladder.includes(effort)\n}\n\nfunction hasUsableLimits(model: Model | undefined): boolean {\n const limits = model?.capabilities?.limits\n const prompt = limits?.max_prompt_tokens\n const output = limits?.max_output_tokens\n return (\n typeof prompt === \"number\"\n && Number.isFinite(prompt)\n && prompt > 0\n && typeof output === \"number\"\n && Number.isFinite(output)\n && output > 0\n && (limits?.max_context_window_tokens ?? 0) >= prompt\n )\n}\n\nfunction supportsEndpoint(\n model: Model | undefined,\n endpoint: \"chat\" | \"responses\" | \"messages\",\n): boolean {\n return model !== undefined && fastEndpointForModel(model) === endpoint\n}\n\nfunction validateRequiredModel(\n model: Model | undefined,\n id: string,\n requirements: ReadonlyArray<[string, boolean]>,\n missing: string[],\n): void {\n if (!model) {\n missing.push(`${id}: absent from the live catalog`)\n return\n }\n for (const [message, ok] of requirements) {\n if (!ok) missing.push(`${id}: ${message}`)\n }\n}\n\nfunction usableSol(model: Model | undefined): boolean {\n return Boolean(\n model\n && hasToolCalls(model)\n && hasContextAtLeast(model, ONE_M_TOKENS)\n && supportsEffort(model, \"high\")\n && supportsEndpoint(model, \"responses\")\n && hasUsableLimits(model)\n )\n}\n\nfunction usableGemini(model: Model | undefined): boolean {\n return Boolean(\n model\n && hasToolCalls(model)\n && hasContextAtLeast(model, ONE_M_TOKENS)\n && supportsEffort(model, \"high\")\n && supportsEndpoint(model, \"chat\")\n && hasUsableLimits(model),\n )\n}\n\nfunction usableGrok(model: Model | undefined): boolean {\n return Boolean(\n model\n && hasToolCalls(model)\n && supportsEffort(model, \"medium\")\n && supportsEndpoint(model, \"responses\")\n && hasUsableLimits(model),\n )\n}\n\nfunction usableGrokReviewer(model: Model | undefined): boolean {\n return Boolean(\n usableGrok(model)\n && supportsEffort(model, \"high\")\n && (model?.capabilities?.limits?.max_prompt_tokens ?? 0) >= 200_000,\n )\n}\n\n/**\n * Validate the fixed prerequisites for the raw `-m max` launch.\n *\n * Max is a deliberately strong, closed profile. Its lead, planning,\n * implementation, repository-review, brainstorm, and transcript-aware Advisor\n * paths must all be present before any runtime artifact is written: Sol, Luna,\n * Gemini 3.8 Flash, Sonnet 5, and Opus 5 are mandatory. Grok 4.6 is optional;\n * when present it supplies additional peer critic/reviewer coverage and the\n * preferred third-lab stand-in slot, but it is never a max lead and its sub-1M\n * context must remain undecorated.\n */\nexport function validateMaxProfilePrerequisites(\n catalog: ModelsResponse | undefined,\n): MaxProfilePrerequisiteCheck {\n const missing: string[] = []\n const sol = findModel(catalog, MAX_PROFILE_MODELS.sol)\n const luna = findModel(catalog, MAX_PROFILE_MODELS.luna)\n const gemini = findModel(catalog, MAX_PROFILE_MODELS.gemini)\n const grok = findModel(catalog, MAX_PROFILE_MODELS.grok)\n const opus = findModel(catalog, MAX_PROFILE_MODELS.opus)\n const sonnet = findModel(catalog, MAX_PROFILE_MODELS.sonnet)\n\n validateRequiredModel(\n sol,\n MAX_PROFILE_MODELS.sol,\n [\n [\"does not advertise tool_calls\", hasToolCalls(sol)],\n [\"advertised context window is below 1M\", hasContextAtLeast(sol, ONE_M_TOKENS)],\n [\"does not advertise a high reasoning effort\", supportsEffort(sol, \"high\")],\n [\"does not advertise a supported Responses endpoint\", supportsEndpoint(sol, \"responses\")],\n [\"has no usable max_prompt_tokens/max_output_tokens limits\", hasUsableLimits(sol)],\n ],\n missing,\n )\n validateRequiredModel(\n luna,\n MAX_PROFILE_MODELS.luna,\n [\n [\"does not advertise tool_calls\", hasToolCalls(luna)],\n [\"advertised context window is below 1M\", hasContextAtLeast(luna, ONE_M_TOKENS)],\n [\"does not advertise a high reasoning effort\", supportsEffort(luna, \"high\")],\n [\"does not advertise a max reasoning effort\", supportsEffort(luna, \"max\")],\n [\"does not advertise a supported Responses endpoint\", supportsEndpoint(luna, \"responses\")],\n [\"has no usable max_prompt_tokens/max_output_tokens limits\", hasUsableLimits(luna)],\n ],\n missing,\n )\n validateRequiredModel(\n gemini,\n MAX_PROFILE_MODELS.gemini,\n [\n [\"does not advertise tool_calls\", hasToolCalls(gemini)],\n [\"advertised context window is below 1M\", hasContextAtLeast(gemini, ONE_M_TOKENS)],\n [\"does not advertise a high reasoning effort\", supportsEffort(gemini, \"high\")],\n [\"does not advertise a supported Chat Completions endpoint\", supportsEndpoint(gemini, \"chat\")],\n [\"has no usable max_prompt_tokens/max_output_tokens limits\", hasUsableLimits(gemini)],\n ],\n missing,\n )\n validateRequiredModel(\n opus,\n MAX_PROFILE_MODELS.opus,\n [\n [\"does not advertise tool_calls\", hasToolCalls(opus)],\n [\"advertised context window is below 1M\", hasContextAtLeast(opus, ONE_M_TOKENS)],\n [\"does not advertise adaptive_thinking\", opus?.capabilities?.supports?.adaptive_thinking === true],\n [\"does not advertise a high reasoning effort\", supportsEffort(opus, \"high\")],\n [\"does not advertise a supported Messages endpoint\", supportsEndpoint(opus, \"messages\")],\n [\"has no usable max_prompt_tokens/max_output_tokens limits\", hasUsableLimits(opus)],\n ],\n missing,\n )\n validateRequiredModel(\n sonnet,\n MAX_PROFILE_MODELS.sonnet,\n [\n [\"does not advertise tool_calls\", hasToolCalls(sonnet)],\n [\"advertised context window is below 1M\", hasContextAtLeast(sonnet, ONE_M_TOKENS)],\n [\"does not advertise adaptive_thinking\", sonnet?.capabilities?.supports?.adaptive_thinking === true],\n [\"does not advertise an xhigh reasoning effort\", supportsEffort(sonnet, \"xhigh\")],\n [\"does not advertise a supported Messages endpoint\", supportsEndpoint(sonnet, \"messages\")],\n [\"has no usable max_prompt_tokens/max_output_tokens limits\", hasUsableLimits(sonnet)],\n ],\n missing,\n )\n\n // Grok is intentionally optional. A malformed optional entry is simply\n // omitted from the max projection; it must never make launch fail or be\n // decorated as a 1M model.\n const geminiUsable = usableGemini(gemini)\n const grokUsable = usableGrok(grok)\n\n return {\n ok: missing.length === 0,\n missing,\n models: {\n sol: sol && !missing.some((entry) => entry.startsWith(`${MAX_PROFILE_MODELS.sol}:`)) ? sol : undefined,\n luna: luna && !missing.some((entry) => entry.startsWith(`${MAX_PROFILE_MODELS.luna}:`)) ? luna : undefined,\n gemini: geminiUsable ? gemini : undefined,\n grok: grokUsable ? grok : undefined,\n opus: opus && !missing.some((entry) => entry.startsWith(`${MAX_PROFILE_MODELS.opus}:`)) ? opus : undefined,\n sonnet: sonnet && !missing.some((entry) => entry.startsWith(`${MAX_PROFILE_MODELS.sonnet}:`)) ? sonnet : undefined,\n thirdLab: grokUsable && supportsEffort(grok, \"high\")\n ? \"grok\"\n : geminiUsable\n ? \"gemini\"\n : undefined,\n },\n }\n}\n\nexport function formatMaxPrerequisiteFailure(\n missing: ReadonlyArray<string>,\n): string {\n return (\n \"github-router claude -m max requires the following live-catalog capabilities, \"\n + \"which this account's catalog does not fully provide:\\n\"\n + missing.map((entry) => ` - ${entry}`).join(\"\\n\")\n + \"\\n\\nMax launches do not fall back to arbitrary older models. \"\n + \"Use plain `github-router claude` for the standard profile.\"\n )\n}\n\nexport function maxModelIsOneM(\n model: Model | undefined,\n): boolean {\n return (\n (model?.capabilities?.limits?.max_context_window_tokens ?? 0) >= ONE_M_TOKENS\n )\n}\n\nexport function maxModelSupportsEffort(\n model: Model | undefined,\n effort: Effort,\n): boolean {\n return supportsEffort(model, effort)\n}\n\nexport function maxModelHasUsableLimits(model: Model | undefined): boolean {\n return hasUsableLimits(model)\n}\n\nexport function maxThirdLabModel(): string | undefined {\n const gemini = catalogModel(MAX_PROFILE_MODELS.gemini)\n if (usableGemini(gemini)) return MAX_PROFILE_MODELS.gemini\n const grok = catalogModel(MAX_PROFILE_MODELS.grok)\n return usableGrok(grok) ? MAX_PROFILE_MODELS.grok : undefined\n}\n\nexport function maxGeminiModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.gemini)\n return model && usableGemini(model) ? model.id : undefined\n}\n\nexport function maxGrokModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.grok)\n return model && usableGrok(model) ? model.id : undefined\n}\n\n/** Grok replacement for max-profile surfaces that require high effort. */\nexport function maxGrokHighModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.grok)\n return model && usableGrokReviewer(model) ? model.id : undefined\n}\n\n/** Max-only replacement for any standard Gemini Pro assignment. */\nexport function maxProReplacementModel():\n | typeof MAX_PROFILE_MODELS.grok\n | typeof MAX_PROFILE_MODELS.gemini\n | undefined {\n if (maxGrokHighModel()) return MAX_PROFILE_MODELS.grok\n if (maxGeminiModel()) return MAX_PROFILE_MODELS.gemini\n return undefined\n}\n\nexport function maxOpusModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.opus)\n return model && hasContextAtLeast(model, ONE_M_TOKENS)\n && model.capabilities?.supports?.adaptive_thinking === true\n && supportsEffort(model, \"high\")\n && supportsEndpoint(model, \"messages\")\n && hasUsableLimits(model)\n ? model.id\n : undefined\n}\n\nexport function maxLunaMaxModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.luna)\n return model\n && hasToolCalls(model)\n && hasContextAtLeast(model, ONE_M_TOKENS)\n && supportsEffort(model, \"max\")\n && supportsEndpoint(model, \"responses\")\n && hasUsableLimits(model)\n ? model.id\n : undefined\n}\n\nexport function maxSonnetModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.sonnet)\n return model && hasContextAtLeast(model, ONE_M_TOKENS)\n && model.capabilities?.supports?.tool_calls === true\n && model.capabilities?.supports?.adaptive_thinking === true\n && supportsEffort(model, \"xhigh\")\n && supportsEndpoint(model, \"messages\")\n && hasUsableLimits(model)\n ? model.id\n : undefined\n}\n\nexport function maxReviewerModel(): string | undefined {\n return maxSonnetModel()\n}\n\nexport function maxCodexReviewerModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.codex)\n return model && hasToolCalls(model)\n && supportsEffort(model, \"xhigh\")\n && advertisesEndpoint(model, \"responses\")\n && hasUsableLimits(model)\n && (model.capabilities?.limits?.max_prompt_tokens ?? 0) >= 200_000\n ? model.id\n : undefined\n}\n\nexport function maxCatalogModel(id: string): Model | undefined {\n return catalogModel(id)\n}\n\nexport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