github-router 0.3.371 → 0.3.372
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/dist/ado-tools-CAtopk36.js +1 -0
- package/dist/{attribution-settings-Beer9wsJ.js → attribution-settings-HI_5bN_-.js} +6 -6
- package/dist/{attribution-settings-Beer9wsJ.js.map → attribution-settings-HI_5bN_-.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{claude-CAYTTiyt.js → claude-BBSsqwln.js} +10 -10
- package/dist/claude-BBSsqwln.js.map +1 -0
- package/dist/{claude-md-injection-D1aMjvb_.js → claude-md-injection-BMon6WUD.js} +19 -22
- package/dist/claude-md-injection-BMon6WUD.js.map +1 -0
- package/dist/{codex-CALX-qG4.js → codex-PRWoBiOH.js} +5 -5
- package/dist/{codex-CALX-qG4.js.map → codex-PRWoBiOH.js.map} +1 -1
- package/dist/engine-CDZdAx8N.js +1 -0
- package/dist/{gate-discovery-CITKjhsD.js → gate-discovery-BNy8GKsC.js} +2 -2
- package/dist/{gate-discovery-CITKjhsD.js.map → gate-discovery-BNy8GKsC.js.map} +1 -1
- package/dist/hooks.mjs +45 -10
- package/dist/hooks.sha256 +1 -1
- package/dist/{internal-prompt-submit-bi7F7pKk.js → internal-prompt-submit-BW5g3MjD.js} +2 -2
- package/dist/{internal-prompt-submit-bi7F7pKk.js.map → internal-prompt-submit-BW5g3MjD.js.map} +1 -1
- package/dist/{internal-prompt-submit-B-kKTl-8.js → internal-prompt-submit-C4uDwr7G.js} +2 -2
- package/dist/{internal-rebrief-B6ZJS6Mp.js → internal-rebrief-DvBS8myn.js} +3 -3
- package/dist/{internal-rebrief-B6ZJS6Mp.js.map → internal-rebrief-DvBS8myn.js.map} +1 -1
- package/dist/{internal-stop-hook-DT27bzH7.js → internal-stop-hook-CXlOsW63.js} +2 -2
- package/dist/{internal-stop-hook-DT27bzH7.js.map → internal-stop-hook-CXlOsW63.js.map} +1 -1
- package/dist/main.js +8 -8
- package/dist/{peer-mcp-personas-D7vaM-V5.js → peer-mcp-personas-Dxxw5X1g.js} +265 -242
- package/dist/peer-mcp-personas-Dxxw5X1g.js.map +1 -0
- package/dist/{pi-D4LrdubN.js → pi-IYAvKF50.js} +805 -68
- package/dist/pi-IYAvKF50.js.map +1 -0
- package/dist/{provision-DonGTIfK.js → provision-CIn6I4w_.js} +33 -2
- package/dist/provision-CIn6I4w_.js.map +1 -0
- package/dist/{serve-jzmQ8KEE.js → serve-CttHP8dJ.js} +7 -7
- package/dist/{serve-jzmQ8KEE.js.map → serve-CttHP8dJ.js.map} +1 -1
- package/dist/{server-setup-wWidNq5m.js → server-setup-D7XHUrhM.js} +20 -17
- package/dist/server-setup-D7XHUrhM.js.map +1 -0
- package/dist/{start-CTluQxu5.js → start-XU5HwLd9.js} +3 -3
- package/dist/{start-CTluQxu5.js.map → start-XU5HwLd9.js.map} +1 -1
- package/dist/{static-context-pack-DvwLWlbe.js → static-context-pack-CsOAC87F.js} +98 -18
- package/dist/static-context-pack-CsOAC87F.js.map +1 -0
- package/dist/{workiq-tools-CDLIrILp.js → workiq-tools-CMoDjrO0.js} +1 -1
- package/package.json +1 -1
- package/dist/ado-tools-512UGB6R.js +0 -1
- package/dist/claude-CAYTTiyt.js.map +0 -1
- package/dist/claude-md-injection-D1aMjvb_.js.map +0 -1
- package/dist/engine-CSAEqj2p.js +0 -1
- package/dist/peer-mcp-personas-D7vaM-V5.js.map +0 -1
- package/dist/pi-D4LrdubN.js.map +0 -1
- package/dist/provision-DonGTIfK.js.map +0 -1
- package/dist/server-setup-wWidNq5m.js.map +0 -1
- package/dist/static-context-pack-DvwLWlbe.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-rebrief-B6ZJS6Mp.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,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iBAAiB;IACjB,aAAa,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"}
|
|
1
|
+
{"version":3,"file":"internal-rebrief-DvBS8myn.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,OAA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ewSt
|
|
|
4
4
|
import { a as decideStopHook, c as launchBaselineKey, d as stopGateId, f as stopReviewEnabled, o as fileBlockBudget } from "./stop-gate-hook-DnLC09Lg.js";
|
|
5
5
|
import { t as liveExec } from "./orchestration-D3-2ulhX.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-BNy8GKsC.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-CXlOsW63.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-stop-hook-DT27bzH7.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,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AC,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"}
|
|
1
|
+
{"version":3,"file":"internal-stop-hook-CXlOsW63.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,KA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e,WAAW,IAAI,aAAa;IAClE,IAAI,KACF,aAAc,MAAM,oBAAoB,mBAAmB,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,21 +47,21 @@ const main = defineCommand({
|
|
|
47
47
|
},
|
|
48
48
|
subCommands: {
|
|
49
49
|
auth: () => import("./auth-B1egtvt4.js").then((m) => m.auth),
|
|
50
|
-
start: () => import("./start-
|
|
51
|
-
claude: () => import("./claude-
|
|
52
|
-
codex: () => import("./codex-
|
|
53
|
-
pi: () => import("./pi-
|
|
50
|
+
start: () => import("./start-XU5HwLd9.js").then((m) => m.start),
|
|
51
|
+
claude: () => import("./claude-BBSsqwln.js").then((m) => m.claude),
|
|
52
|
+
codex: () => import("./codex-PRWoBiOH.js").then((m) => m.codex),
|
|
53
|
+
pi: () => import("./pi-IYAvKF50.js").then((m) => m.pi),
|
|
54
54
|
workiq: () => import("./workiq-qnJR5_n2.js").then((m) => m.workiq),
|
|
55
|
-
serve: () => import("./serve-
|
|
55
|
+
serve: () => import("./serve-CttHP8dJ.js").then((m) => m.serve),
|
|
56
56
|
models: () => import("./models-Ca-HQTYi.js").then((m) => m.models),
|
|
57
57
|
"check-usage": () => import("./check-usage-T_z84Pgc.js").then((m) => m.checkUsage),
|
|
58
58
|
index: () => import("./index-cmd-CjRcmYk3.js").then((m) => m.indexCmd),
|
|
59
59
|
debug: () => import("./debug-DL2JsRqY.js").then((m) => m.debug),
|
|
60
|
-
"internal-stop-hook": () => import("./internal-stop-hook-
|
|
61
|
-
"internal-prompt-submit": () => import("./internal-prompt-submit-
|
|
60
|
+
"internal-stop-hook": () => import("./internal-stop-hook-CXlOsW63.js").then((m) => m.internalStopHook),
|
|
61
|
+
"internal-prompt-submit": () => import("./internal-prompt-submit-C4uDwr7G.js").then((m) => m.internalPromptSubmit),
|
|
62
62
|
"internal-stop-review": () => import("./internal-stop-review-D_KEV_04.js").then((m) => m.internalStopReview),
|
|
63
63
|
"internal-plan-review": () => import("./internal-plan-review-ChFx8wTX.js").then((m) => m.internalPlanReview),
|
|
64
|
-
"internal-rebrief": () => import("./internal-rebrief-
|
|
64
|
+
"internal-rebrief": () => import("./internal-rebrief-DvBS8myn.js").then((m) => m.internalRebrief),
|
|
65
65
|
"internal-session-bind": () => import("./internal-session-bind-dsUOcKxU.js").then((m) => m.internalSessionBind),
|
|
66
66
|
"internal-workspace-header": () => import("./internal-workspace-header-DBg5Y7oN.js").then((m) => m.internalWorkspaceHeader),
|
|
67
67
|
"internal-artifact-open": () => import("./internal-artifact-open-NAGn9Mgt.js").then((m) => m.internalArtifactOpen),
|