github-router 0.3.353 → 0.3.355
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-B5TCtnlQ.js +1 -0
- package/dist/{aic-statusline-settings-LnoxjBPe.js → aic-statusline-settings-EdsV1gzY.js} +6 -4
- package/dist/aic-statusline-settings-EdsV1gzY.js.map +1 -0
- package/dist/{attribution-settings-7cbLvuiE.js → attribution-settings-N48QlHu2.js} +51 -39
- package/dist/{attribution-settings-7cbLvuiE.js.map → attribution-settings-N48QlHu2.js.map} +1 -1
- package/dist/balanced-profile-contract-DtnTIBjL.js +105 -0
- package/dist/balanced-profile-contract-DtnTIBjL.js.map +1 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{claude-CugVz_lo.js → claude-BAKFTVqA.js} +68 -59
- package/dist/claude-BAKFTVqA.js.map +1 -0
- package/dist/{claude-md-injection-BoXOsg7h.js → claude-md-injection-CDOoGNEJ.js} +20 -15
- package/dist/claude-md-injection-CDOoGNEJ.js.map +1 -0
- package/dist/{codex-pfFa6vPh.js → codex-CspHNGZA.js} +5 -5
- package/dist/{codex-pfFa6vPh.js.map → codex-CspHNGZA.js.map} +1 -1
- package/dist/{copilot-discount-C3jfysK-.js → copilot-discount-kpOLluHm.js} +3 -1
- package/dist/copilot-discount-kpOLluHm.js.map +1 -0
- package/dist/engine-YvnWaTnR.js +1 -0
- package/dist/fast-profile-contract-JOnZBgFB.js +61 -0
- package/dist/fast-profile-contract-JOnZBgFB.js.map +1 -0
- package/dist/{gate-discovery-Cvdko01z.js → gate-discovery-JeKibE14.js} +2 -2
- package/dist/{gate-discovery-Cvdko01z.js.map → gate-discovery-JeKibE14.js.map} +1 -1
- package/dist/hooks.mjs +193 -12
- package/dist/hooks.sha256 +1 -1
- package/dist/{internal-aic-status-Dmi2bCsR.js → internal-aic-status-wYPsCG4r.js} +2 -2
- package/dist/{internal-aic-status-Dmi2bCsR.js.map → internal-aic-status-wYPsCG4r.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-Cv7zf0ZI.js → internal-fast-dispatch-guard-A8teEib4.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-BQm1MI9d.js → internal-fast-dispatch-guard-D_TCtJhQ.js} +3 -2
- package/dist/{internal-fast-dispatch-guard-BQm1MI9d.js.map → internal-fast-dispatch-guard-D_TCtJhQ.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-T-M7DRIW.js → internal-max-dispatch-guard-BM_B15EH.js} +1 -1
- package/dist/{internal-max-dispatch-guard-DkJixDmG.js → internal-max-dispatch-guard-D7ByWH4v.js} +2 -2
- package/dist/{internal-max-dispatch-guard-DkJixDmG.js.map → internal-max-dispatch-guard-D7ByWH4v.js.map} +1 -1
- package/dist/{internal-prompt-submit-B9MJxc3K.js → internal-prompt-submit-C77GnEaW.js} +3 -3
- package/dist/internal-prompt-submit-C77GnEaW.js.map +1 -0
- package/dist/{internal-prompt-submit-6OXEdQCK.js → internal-prompt-submit-CDTwamkW.js} +2 -2
- package/dist/{internal-rebrief-zIdunX3R.js → internal-rebrief-DZygfGHp.js} +6 -6
- package/dist/internal-rebrief-DZygfGHp.js.map +1 -0
- package/dist/{internal-stop-hook-DGcRVh_2.js → internal-stop-hook-Dz6mdfcL.js} +2 -2
- package/dist/{internal-stop-hook-DGcRVh_2.js.map → internal-stop-hook-Dz6mdfcL.js.map} +1 -1
- package/dist/main.js +11 -11
- package/dist/{max-profile-contract-DQDEDCsR.js → max-profile-contract-CMvzKSsg.js} +2 -2
- package/dist/max-profile-contract-CMvzKSsg.js.map +1 -0
- package/dist/{peer-mcp-personas-DDMKRFFG.js → peer-mcp-personas-Ch4VWo40.js} +165 -185
- package/dist/peer-mcp-personas-Ch4VWo40.js.map +1 -0
- package/dist/{pi-BNpaiwEF.js → pi-Cwj383nc.js} +61 -62
- package/dist/pi-Cwj383nc.js.map +1 -0
- package/dist/{provision-BtYRtvrj.js → provision-PodfFQu-.js} +2 -2
- package/dist/{provision-BtYRtvrj.js.map → provision-PodfFQu-.js.map} +1 -1
- package/dist/{serve-BQ0spYrs.js → serve-D-OuW7kz.js} +7 -7
- package/dist/{serve-BQ0spYrs.js.map → serve-D-OuW7kz.js.map} +1 -1
- package/dist/{server-setup-COrhtCdv.js → server-setup-DDZxJgl0.js} +197 -133
- package/dist/server-setup-DDZxJgl0.js.map +1 -0
- package/dist/{start-Dd7O3bB9.js → start-CZZ0cTV9.js} +3 -3
- package/dist/{start-Dd7O3bB9.js.map → start-CZZ0cTV9.js.map} +1 -1
- package/dist/{static-context-pack-CyucviRD.js → static-context-pack-BRqt4ajJ.js} +313 -6
- package/dist/static-context-pack-BRqt4ajJ.js.map +1 -0
- package/docs/azure-mcp.md +28 -24
- package/package.json +1 -1
- package/dist/ado-tools-xbuVU7YN.js +0 -1
- package/dist/aic-statusline-settings-LnoxjBPe.js.map +0 -1
- package/dist/balanced-profile-contract-XiIj4O1U.js +0 -127
- package/dist/balanced-profile-contract-XiIj4O1U.js.map +0 -1
- package/dist/claude-CugVz_lo.js.map +0 -1
- package/dist/claude-md-injection-BoXOsg7h.js.map +0 -1
- package/dist/copilot-discount-C3jfysK-.js.map +0 -1
- package/dist/engine-DwLIk1Zn.js +0 -1
- package/dist/internal-prompt-submit-B9MJxc3K.js.map +0 -1
- package/dist/internal-rebrief-zIdunX3R.js.map +0 -1
- package/dist/max-profile-contract-DQDEDCsR.js.map +0 -1
- package/dist/peer-mcp-personas-DDMKRFFG.js.map +0 -1
- package/dist/pi-BNpaiwEF.js.map +0 -1
- package/dist/server-setup-COrhtCdv.js.map +0 -1
- package/dist/static-context-pack-CyucviRD.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"claude-md-injection-BoXOsg7h.js","names":[],"sources":["../src/lib/claude-md-injection.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport { MAX_PARALLELISM_RULE } from \"./max-profile-prompts\"\nimport { isUnderClaudeConfigMirror, PATHS } from \"./paths\"\n\n/**\n * Marker fences for each injection block. The literal text of each\n * fence is intentionally specific enough that a content collision with\n * user prose is implausible. Each block's parser only matches its own\n * marker pair, so blocks operate independently.\n *\n * Writer-side guard: the injector refuses to write a snippet that\n * itself contains its own marker literals (that would create\n * ambiguous state on the next launch where the inner literal would\n * parse as a new open or close marker).\n */\nconst PEER_MARKER_OPEN =\n \"<!-- gh-router peer-mcp awareness — auto-injected, regenerated per launch -->\"\nconst PEER_MARKER_CLOSE = \"<!-- /gh-router peer-mcp awareness -->\"\n\nconst STYLE_MARKER_OPEN =\n \"<!-- gh-router style directive — auto-injected, regenerated per launch -->\"\nconst STYLE_MARKER_CLOSE = \"<!-- /gh-router style directive -->\"\n\nconst OPERATING_MARKER_OPEN =\n \"<!-- gh-router operating defaults — auto-injected, regenerated per launch -->\"\nconst OPERATING_MARKER_CLOSE = \"<!-- /gh-router operating defaults -->\"\n\nconst TOOLBELT_MARKER_OPEN =\n \"<!-- gh-router toolbelt awareness — auto-injected, regenerated per launch -->\"\nconst TOOLBELT_MARKER_CLOSE = \"<!-- /gh-router toolbelt awareness -->\"\n\nconst ARTIFACT_MARKER_OPEN =\n \"<!-- gh-router artifact-panel directive — auto-injected when in an ai-or-die tab -->\"\nconst ARTIFACT_MARKER_CLOSE = \"<!-- /gh-router artifact-panel directive -->\"\n\n// Default-on review in the panel: when running inside an ai-or-die tab the\n// artifact_* tools reach a real review panel, so steer the agent to use it.\n// Lever split: this directive is the SOFT steer for the model-judgment cases\n// (show a comparison/table/diagram mid-conversation, which no hook can detect).\n// The one DETERMINISTIC artifact-open is the PostToolUse(ExitPlanMode) hook\n// (buildArtifactOpenHookCommand in claude.ts) that auto-opens a finalized plan.\n// A Stop / UserPromptSubmit hook is deliberately NOT added: it would either\n// mis-fire on ordinary turns or merely duplicate this soft steer.\n//\n// Scope: this block carries ONLY the trigger + the HTML-by-default steer + the\n// tool entry points + a pointer. The full authoring/review-loop playbook (HTML\n// conventions, design-system choice, per-type cheatsheet, the data-aod-*\n// controls, honest limits) lives in the materialized `gh-artifact-review`\n// skill, so it is not restated here every turn (per the injected-surface\n// review: CLAUDE.md holds the steer, the skill holds the procedure).\nfunction ARTIFACT_PANEL_DIRECTIVE(peersKey = \"peers\"): string {\n const toolPrefix = `mcp__${peersKey}__artifact_`\n return \"## Review in the artifact panel (HTML by default)\\n\\n\"\n + `You are running inside an ai-or-die tab, so the \\`${toolPrefix}*\\` tools drive a live human-review panel. `\n + \"Default to opening a self-contained HTML artifact for anything the user should review before you proceed: plans, design proposals, comparisons / trade-offs, decisions that need their input, diagrams, tables, code diffs, and reports. \"\n + \"Plan-mode plans are auto-rendered to HTML and opened for you; skip the panel only for trivial one-line answers. \"\n + `Run the \\`gh-artifact-review\\` skill for the full playbook: HTML + design conventions, the \\`${toolPrefix}open\\` / \\`${toolPrefix}await\\` (pass back the \\`cursor\\`) / \\`${toolPrefix}reply\\` / \\`${toolPrefix}end\\` loop, and the \\`data-aod-*\\` interactive controls.`\n}\n\n// Back-compat aliases used by existing tests. The peer block's\n// markers remain the \"default\" pair surfaced through __testExports.\nconst MARKER_OPEN = PEER_MARKER_OPEN\nconst MARKER_CLOSE = PEER_MARKER_CLOSE\n\n/**\n * Writing / communication style directive injected at the TOP of the\n * mirrored CLAUDE.md so every spawned agent (main, Agent-tool subagent,\n * agent-teams teammate) reads it before the user's own CLAUDE.md body.\n *\n * Self-referentially compliant: the directive itself uses no em\n * dashes and does not mention any Claude / Anthropic attribution.\n */\nconst STYLE_DIRECTIVE =\n \"Write concisely without losing detail. \"\n + \"Use a natural human voice. \"\n + \"Avoid em dashes. \"\n + \"Do not attribute work to Claude, AI, LLM, or Anthropic anywhere \"\n + \"(commits, PRs, issues, code, comments, docs).\"\n\n/**\n * Operating-defaults directive injected at the TOP of the mirrored CLAUDE.md.\n * The main agent's system prompt (`--append-system-prompt`) gets\n * OPERATING_DEFAULTS_DIGEST instead, with this full statement available through\n * CLAUDE.md. Three defaults, layered under the user's own\n * direction and the domain's standards as addons (on a direct conflict the\n * user's direction wins, then the domain standard, then the default below):\n *\n * 1. Orchestrate (strong default): delegate the heavy / parallel /\n * context-heavy work to the right subagent / worker / model, keeping the\n * main context free to reason and collaborate with the user, while still\n * doing trivial / surgical / last-mile work directly (delegating that\n * would only add relay-fidelity loss + latency).\n * 2. Adversarial review: WHEN a peer critic earns its keep and, equally\n * important, when reaching for one is ritual rather than review. Same\n * failure shape the delegation default had: \"consult a critic for\n * non-trivial changes\" is unfalsifiable in advance, so it collapses into\n * either never (four of four unprimed agents) or always (worse than\n * never). The discriminator is whether the conclusion still turns on\n * judgment once the direct evidence is in: a consequential recommendation\n * cannot be run, which is exactly where confabulation hides, while a\n * tracing question a search already proved gains nothing from a second\n * model re-deriving it. The roster, the lens-to-artifact match, the\n * advisor-complements-rather-than-substitutes distinction, and the\n * do-not-anchor-the-critic rule live here; the digest carries only the\n * trigger and the ritual exclusion.\n * 3. Excellence lens: the principles stated plainly and concretely (radical\n * simplicity + real-user focus; whole-system first-principles thinking that\n * anticipates scale; work back from the customer outcome). Named exemplars\n * were dropped per the injected-surface review: a named entity is a dense,\n * high-variance vector that pulls in persona mannerisms at top salience, and\n * the guidance favors specific functional framing over comparison, so\n * specificity carries the vividness instead.\n * 4. Engineering excellence: quality / robustness / maintainability over\n * development cost; reproduce a bug end-to-end (as a real user hits it)\n * before fixing so the fix targets the real cause; a pixel-perfect UI bar;\n * and fix any lint error / test failure / flake on sight, whoever caused it,\n * folded into the current work rather than derailing the user's task (the\n * scope guardrail keeps proactive quality from becoming yak-shaving). The\n * digest carries a one-line form; the full statement lives here so it does\n * not cost the context window every turn.\n *\n * Self-referentially compliant with the style directive: no em dashes, no\n * Claude / Anthropic attribution.\n *\n * Availability-aware: four of the natives (`scout`, `implementer-fast`,\n * `reviewer-fast`, and `general-purpose-fast`) are DROPPED rather than\n * downgraded when no model in\n * their chain resolves, so naming them unconditionally here would tell the lead to delegate\n * to an agent that has no `.md` file and is absent from the Task\n * `subagent_type` enum. Build the directive with\n * `buildOperatingDefaultsDirective` and the same availability booleans used for\n * the `.md` generation and the awareness snippet; the exported const below is\n * the all-available form, kept for callers and tests that do not model a thin\n * catalog.\n */\n\n/**\n * Pipeline skills (`/gh-gather-context`, `/gh-plan`, `/gh-implement`,\n * `/gh-swe-pipeline`) injected ONLY for `--swe` launches on pinned profiles\n * (fast, max, cheap, cheap1m, cheapest, balanced). Standard is intentionally\n * excluded. Without `--swe` the skill files are not written and this text is\n * not referenced. Stages dispatch ONLY native subagents present on the\n * profile roster (Explore, Plan where the profile provides one,\n * General-Purpose, reviewer, implementer where provided), never worker-*\n * MCP dispatchers. All roles run at the\n * 200K default window (bare slugs, no 1M accounting) with advisory budgets:\n * gather ~3 min per round (3 rounds max, 6 Explore per round); plan ~5 min\n * via the profile-pinned Plan subagent where the profile provides one\n * (the lead plans directly on cheapest/balanced; trivial asks exit\n * planless);\n * implement ~10 min per task (8 concurrent max, worktree:true only when\n * parallel tasks need isolation); reviewer only on low-confidence or complex\n * and risky changes, plus a General-Purpose fix pass for major reviewer\n * findings.\n */\nexport const PIPELINE_SKILLS_AWARENESS =\n \"Pipeline skills (all 200K default context, native subagents only, never worker-*). \"\n + \"Prefer `/gh-swe-pipeline`: strict sequence, each stage completing before the next starts, user approval before implementation. Stages in order: \"\n + \"(1) `/gh-gather-context` BEFORE planning when grounded context is needed: lexical search plus bounded Explore subagents (~3 min each, 3 rounds max), writes context.md plus context.compact.md; \"\n + \"(2) `/gh-plan` AFTER context and BEFORE implementation: native Plan subagent plans non-trivial asks (trivial exits planless), ordered plan.md (~5 min), open questions, waits for user approval; \"\n + \"(3) `/gh-implement` AFTER plan approval: bounded parallel General-Purpose subagents (implementer first on max; worktree:true if parallel tasks need isolation), reviewer only on low-confidence or risky changes, plus fix pass for major findings. \"\n + \"Skip for trivial work. Never implement without an approved plan. Never overlap stages.\"\n\n/**\n * Pipeline-skills awareness for the profiles without a `Plan` role\n * (cheapest, balanced): the lead plans directly, so `/gh-plan` names the\n * lead instead of a Plan dispatch. Every other stage is identical.\n */\nexport const PIPELINE_SKILLS_AWARENESS_NO_PLAN_AGENT =\n \"Pipeline skills (all 200K default context, native subagents only, never worker-*). \"\n + \"Prefer `/gh-swe-pipeline`: strict sequence, each stage completing before the next starts, user approval before implementation. Stages in order: \"\n + \"(1) `/gh-gather-context` BEFORE planning when grounded context is needed: lexical search plus bounded Explore subagents (~3 min each, 3 rounds max), writes context.md plus context.compact.md; \"\n + \"(2) `/gh-plan` AFTER context and BEFORE implementation: the lead plans directly (no Plan subagent on this profile; trivial exits planless), ordered plan.md (~5 min), open questions, waits for user approval; \"\n + \"(3) `/gh-implement` AFTER plan approval: bounded parallel General-Purpose subagents (worktree:true if parallel tasks need isolation), reviewer only on low-confidence or risky changes, plus fix pass for major findings. \"\n + \"Skip for trivial work. Never implement without an approved plan. Never overlap stages.\"\n\n/** Which of the conditionally-emitted natives this launch actually wrote.\n * `undefined` means available, matching `buildPeerAwarenessSnippet`'s\n * `scoutAvailable` convention, so an existing caller that passes nothing keeps\n * the previous full-roster text. */\nexport interface NativeAgentAvailability {\n scoutAvailable?: boolean\n implementerFastAvailable?: boolean\n reviewerFastAvailable?: boolean\n generalPurposeFastAvailable?: boolean\n /** True when this launch's LEAD is a lighter Claude tier (sonnet, haiku)\n * rather than an Opus. Reorders the delegation clauses so the cheap tiers\n * lead; see `buildNativeReachClauses`. Absent/false keeps the Opus-lead\n * ordering, so existing callers are unaffected.\n *\n * Unlike the advisor's lead-awareness, this is resolved ONCE per launch and\n * baked into the mirrored CLAUDE.md, so it cannot follow a mid-session\n * `/model` switch. Acceptable for prose that biases a choice; it would not\n * be for anything that routes a request. */\n budgetLead?: boolean\n /** `\"fast\"` selects the fast launch profile's roster-restricted prose: a\n * hard restriction (not a catalog-availability signal, unlike every\n * `*Available` flag above). `\"cheap\"`/`\"cheap1m\"` select the same\n * restricted roster prose with the cheap family's oracle identities\n * (`\"cheap1m\"` additionally wires the astra peer). `\"cheapest\"` selects\n * the same restricted roster prose with the cheapest identities\n * (Luna lead and reviewer, Sol Advisor/Oracle; never astra) minus the\n * `Plan` role (the lead plans directly).\n * `\"balanced\"` selects the same restricted roster prose Sol-led with the\n * Grok Oracle (never astra), likewise without a `Plan` role. When set,\n * `buildNativeReachClauses` and\n * `buildOperatingDefaultsDirective` return a short, self-contained\n * rendering naming only the profile's own natives\n * (`Explore`/`Plan`/`General-Purpose`/`reviewer` on fast/cheap/cheap1m;\n * `Explore`/`General-Purpose`/`reviewer` on cheapest/balanced),\n * Advisor, Oracle, and — only when `sweEnabled !== false` — the pipeline\n * skills (`/gh-gather-context`, `/gh-plan`, `/gh-implement`,\n * `/gh-swe-pipeline`); it must never name the standard-only\n * `*-fast`/`brainstorm`/`scribe`/`general-purpose-fast`,\n * `peer-review-coordinator`, `worker-*`/`orchestrate` tools or skills,\n * or `stand_in`, since none of those are registered in this profile\n * regardless of catalog state.\n * Absent/`\"standard\"` is today's catalog-driven full roster. */\n profile?: \"standard\" | \"fast\" | \"cheap\" | \"cheap1m\" | \"cheapest\" | \"balanced\" | \"max\"\n /** False when a fast launch disabled or failed its MCP/native runtime wiring.\n * The fallback directive must not advertise agents/tools that do not exist. */\n fastRuntimeAvailable?: boolean\n browseAvailable?: boolean\n browserToolsAvailable?: boolean\n workerToolsAvailable?: boolean\n standInAvailable?: boolean\n fleetAvailable?: boolean\n agentToolsAvailable?: boolean\n artifactAvailable?: boolean\n astraAvailable?: boolean\n /** Whether local ColBERT semantic search or Bluebird semantic routing is\n * available for this launch. When false/absent the `code` tool is lexical-only. */\n semanticSearchAvailable?: boolean\n /** Whether Bluebird owns semantic and lexical modes for this launch. */\n bluebirdEnabled?: boolean\n groupKeys?: Partial<Record<string, string>>\n peersKey?: string\n /**\n * Whether the `--swe` flag was supplied for this launch. Pass `false` to\n * omit every pipeline-skill reference (the `claude` launcher does this\n * whenever `--swe` is absent, since it also skips writing the skill\n * files). Absent/true keeps the legacy text for callers without a flag\n * concept (e.g. the `serve` enhancements path, which still materializes\n * the skill files unconditionally).\n */\n sweEnabled?: boolean\n}\n\n/** Oxford-comma join: \"a\", \"a and b\", \"a, b, and c\". */\nfunction joinClauses(parts: ReadonlyArray<string>): string {\n if (parts.length <= 1) return parts[0] ?? \"\"\n if (parts.length === 2) return `${parts[0]} and ${parts[1]}`\n return `${parts.slice(0, -1).join(\", \")}, and ${parts[parts.length - 1]}`\n}\n\n/** The \"Reach for X when Y\" list, omitting any agent this launch did not emit.\n *\n * On a budget lead the coding AND review clauses swap order so the cheap tier\n * leads and the frontier tier is named as the complexity escalation. Choosing a\n * lighter lead is a decision to spend less while holding quality, and a roster\n * that names the expensive `implementer` / `reviewer` first works against\n * exactly that. This is ORDERING AND WORDING ONLY: no agent's model changes,\n * and both frontier tiers stay named so work beyond the fast tier still has\n * somewhere to go.\n *\n * Review gets the same treatment as implementation because the cost gap is the\n * same shape: `reviewer` runs the pro tier (200/1200 per 1M) against\n * `reviewer-fast`'s flash tier (75/375), and measured 2026-08-13 the flash\n * model was also the FASTER of the two on every axis (tool-call p50 ~1.2s vs\n * ~2.8s, TTFT ~1.9s vs ~3.7s, decode ~326 vs ~165 tok/s). So on a budget lead\n * there is no quality-for-cost trade being hidden by leading with the cheap\n * tier; reserve `reviewer` for the higher-stakes assessment it is there for. */\nfunction buildNativeReachClauses(opts: NativeAgentAvailability): string {\n if (opts.profile === \"fast\" || opts.profile === \"cheap\" || opts.profile === \"cheap1m\" || opts.profile === \"cheapest\" || opts.profile === \"balanced\") {\n if (opts.profile === \"cheapest\") {\n return joinClauses([\n \"`Explore` (Luna/high, cheap breadth) for discovery, dependency mapping, and convention tracking spanning more than a couple of files\",\n \"`General-Purpose` (Luna/max, the heavy execution tier) for mixed, iterative, or multi-step execution\",\n \"`reviewer` (Luna/max, the heavy verification tier) for independent adversarial verification, reproduction, and root-causing\",\n ]) + \". Delegate by value — cheap breadth to `Explore`, heavy execution to `General-Purpose`, verification to `reviewer`. All roles run at a 200K context window — prefer targeted reads (search, Grep, Read specific files) over full file reads\"\n }\n // Balanced: lead owns planning, implementation, verification by default —\n // only the reviewer is gated behind genuine need.\n if (opts.profile === \"balanced\") {\n return joinClauses([\n \"`Explore` for broad repository discovery, dependency mapping, and convention tracking (launch in parallel)\",\n \"`General-Purpose` for mixed, iterative, or multi-step execution tasks (delegate freely)\",\n \"`reviewer` for independent adversarial verification, reproduction, and root-causing ONLY when genuinely behavior-changing (lead owns verification by default)\",\n ]) + \". All roles run at a 200K context window — prefer targeted reads (search, Grep, Read specific files) over full file reads\"\n }\n const shared = joinClauses([\n \"`Explore` for broad repository discovery, dependency mapping, and convention tracking (launch in parallel)\",\n \"`Plan` for architectural sequencing, interface contracts, migration risk, and runnable acceptance criteria (delegates discovery to `Explore`)\",\n \"`General-Purpose` for mixed, iterative, or multi-step execution tasks (follows a Plan handoff when one exists)\",\n \"`reviewer` for independent adversarial verification, reproduction, and root-causing after non-trivial changes\",\n ])\n // 200K profiles only: fast keeps 1M throughout. cheap1m's lead is 1M\n // but every subagent is 200K, so it gets the subagent-scoped variant.\n if (opts.profile === \"cheap\") {\n return `${shared}. All roles run at a 200K context window — prefer targeted reads (search, Grep, Read specific files) over full file reads`\n }\n if (opts.profile === \"cheap1m\") {\n return `${shared}. Subagents run at a 200K context window — brief them with targeted evidence and prefer targeted reads over full file reads`\n }\n return shared\n }\n const clauses: Array<string> = []\n const implementerFast = opts.implementerFastAvailable !== false\n const reviewerFast = opts.reviewerFastAvailable !== false\n // The swap requires `implementer-fast` to actually exist this launch — on a\n // catalog where it was dropped, naming it first would point the lead at an\n // agent absent from the Task `subagent_type` enum.\n if (opts.budgetLead === true && implementerFast) {\n clauses.push(\n \"`implementer-fast` first for coding changes, since it is the cheaper and \"\n + \"faster tier and this session is running a lighter lead\",\n \"`implementer` when the change needs judgment, its scope is ambiguous, or \"\n + \"its complexity is beyond what the fast tier can carry\",\n )\n } else {\n clauses.push(\n \"`implementer` for coding changes that need judgment or have ambiguous scope\",\n )\n if (implementerFast) {\n clauses.push(\"`implementer-fast` for well-specified, mechanical coding changes\")\n }\n }\n // Same swap, same precondition, for the review pair.\n if (opts.budgetLead === true && reviewerFast) {\n clauses.push(\n \"`reviewer-fast` first when something exists and you want it assessed, \"\n + \"since it is the cheaper and faster review tier\",\n \"`reviewer` when the assessment is higher-stakes or needs deeper \"\n + \"reproduction and root-causing than the fast tier can carry\",\n )\n } else {\n clauses.push(\n \"`reviewer` when something exists and you want it assessed (including \"\n + \"reproducing and root-causing a failure)\",\n )\n if (reviewerFast) {\n clauses.push(\"`reviewer-fast` for lower-stakes assessments\")\n }\n }\n clauses.push(\n \"`brainstorm` when you do not yet know which approach to take\",\n )\n if (opts.scoutAvailable !== false) {\n clauses.push(\"`scout` to find or understand something in the repo\")\n }\n clauses.push(\"`scribe` for docs and ADRs that trail the code\")\n if (opts.generalPurposeFastAvailable !== false) {\n clauses.push(\n opts.budgetLead === true\n ? \"`general-purpose-fast` for work no specialist fits, in preference to \"\n + \"carrying it inline yourself\"\n : \"`general-purpose-fast` for work no specialist fits\",\n )\n }\n return joinClauses(clauses)\n}\n\n/** Everything after the orchestration paragraph's agent list. Unchanged by\n * availability, so it lives here once rather than in both branches. */\nconst OPERATING_DEFAULTS_TAIL =\n \"context free to reason and collaborate with the user. Launch independent \"\n + \"agents concurrently in a single message rather than serially. Delegation \"\n + \"pays when the work is WIDE \"\n + \"(many files or sources to sweep) or SLOW, and you need only the \"\n + \"conclusion: the main thread is where you think with and respond to the \"\n + \"user, and its context window is a finite shared resource. It does NOT pay \"\n + \"merely because a sub-question is separable. A narrow, deep question whose \"\n + \"whole value is file:line fidelity loses exactly that through a \"\n + \"summarization layer, and a sub-question you could answer in one command is \"\n + \"cheaper done directly than paying a subagent's startup. Do trivial, \"\n + \"surgical, and last-mile work yourself. A named teammate persists after it \"\n + \"reports so you can send it follow-ups, and nothing reaps it for you: its idle \"\n + \"notice means available, not finished. Stop it once you are done with it.\\n\\n\"\n + \"Adversarial review. The peer critics (`codex_critic` and `codex_reviewer`, \"\n + \"`gemini_critic` and `gemini_reviewer`, `opus_critic`, and the \"\n + \"`peer-review-coordinator` that fans out to several of them) are \"\n + \"fresh-context models, so what they add is a blind spot that whoever \"\n + \"produced the work cannot reach by thinking harder about it; prefer a \"\n + \"critic from a different lab than the producer, since blind spots \"\n + \"correlate within a lab. The `advisor` is a complement and not a \"\n + \"substitute: it sees your transcript, so it catches your own drift and \"\n + \"momentum, but it inherits your framing, which is exactly what a \"\n + \"fresh-context critic does not. They earn their keep on consequential design \"\n + \"choices, recommendations, and hard-to-reverse decisions: the cases where \"\n + \"plausible alternatives remain and the conclusion rests on judgment rather \"\n + \"than on something you can verify directly. That is where confabulation \"\n + \"hides, so budget the wait even under delivery pressure. Always consult one \"\n + \"when the change touches auth, user input, database queries, crypto, or \"\n + \"serialization. They do NOT pay for read-only tracing, ordinary repository \"\n + \"lookup, or a conclusion that a focused test, a direct reproduction, or \"\n + \"unambiguous code evidence already settles. Asking a critic to re-derive a \"\n + \"proven fact returns a confident answer either way, which is ritual \"\n + \"skepticism rather than review, and skipping them there is the right call \"\n + \"and not a shortcut. Match the lens to the artifact: a strategic critic for \"\n + \"plans and trade-offs, a code reviewer for a concrete diff, the coordinator \"\n + \"only when the risk warrants several independent lenses. Give whichever you \"\n + \"pick the artifact and the constraints and not your rationale, since \"\n + \"justification anchors the review and dulls it.\\n\\n\"\n + \"Aim high. Default to radical simplicity and a relentless focus on the user's \"\n + \"real experience: design for the person and the job to be done, not the demo. \"\n + \"Reason about the whole system from first principles, anticipating scale and the \"\n + \"long arc rather than patching the surface. Work backwards from the outcome the \"\n + \"user actually needs. Question every assumption and prefer what you can derive, \"\n + \"reproduce, or test.\\n\\n\"\n + \"Engineering excellence. When making technical decisions, give little weight to \"\n + \"development cost; prefer quality, simplicity, robustness, scalability, and \"\n + \"long-term maintainability. Fix a bug by first reproducing it end to end, as \"\n + \"close to how a real user hits it as you can, so you solve the real problem and \"\n + \"not a symptom. When testing a product end to end, be picky about the UI and \"\n + \"obsessed with pixel perfection: if something clearly looks off, even when it is \"\n + \"unrelated to your task, get it fixed along the way. Hold that same bar for the \"\n + \"codebase itself: a lint error, a failing test, or a flaky test is worth fixing \"\n + \"the moment you see it, whoever introduced it. Fold it into your current work \"\n + \"rather than letting it derail the task the user actually asked for.\"\n\n/**\n * Cheapest-only consult contract for the Luna lead (the FULL \"when/how\" copy,\n * mirrored into CLAUDE.md).\n *\n * Lives in the injected operating-defaults prose rather than the advisor tool\n * description (the \"what\"), per OpenAI guidance. Outcome-first decision rules,\n * not a step procedure. Covers the four things a weak, over-confident model\n * needs to place consults well:\n * 1. a small, stated budget (8-10 calls) so each feels costly;\n * 2. ANCHORS (when to spend) — genuine uncertainty, before committing, before\n * presenting a plan;\n * 3. DISQUALIFIERS (never spend) — anything evidence settles, or a moment\n * owned by reviewer/oracle;\n * 4. a DISCRIMINATOR assigning each moment to the right consultant.\n * The digest carries only a short pointer (`CHEAPEST_CONSULT_CONTRACT_POINTER`)\n * so the always-resident copy does not duplicate this block every turn.\n */\nexport const CHEAPEST_CONSULT_CONTRACT =\n \"Consulting `advisor` and `oracle` (a small budget — choose wisely): you have roughly 8-10 advisor calls for this session, and each costs real time and money, so spend them only where direction changes the outcome. Advisor and Oracle give you COUNSEL on HOW — and sometimes WHAT — to do: the shortest path, what to consider or look at, planning, strategy, and direction. They never replace evidence you can gather yourself: anything a search, read, build, test, or run can settle, settle it yourself — never spend a consult on it. Spend a consult on: (1) a pre-commit framing check, after you have oriented but before you lock an approach on a non-trivial task; (2) an unresolvable judgment call — conflicting evidence, or a stale-knowledge / high-consequence risk or severity call; (3) a pre-presentation framing check on the final plan. Do NOT spend one on routine progress, reassurance, completion ritual, or a moment that belongs to `reviewer` (verify/reproduce a change) or `oracle` (a self-contained technical/algorithmic/spec/architectural trade-off). Discriminator: session-trajectory / framing / momentum questions and how-to-approach go to `advisor`; self-contained technical/architectural trade-offs go to `oracle`; verification and reproduction go to `reviewer`; facts go to direct evidence. How to call: Sol reads a curated view of this session — the user's original ask, your most recent message text, and a bounded transcript that keeps your reasoning but truncates raw tool output — so before you call, write a short self-contained brief as your own message: the objective, your current job, what you verified / suspect is missing / ruled irrelevant, your confidence and what being wrong would cost, and one neutral question phrased with any competing hypotheses. Never paste raw tool output or ask it to \\\"review the whole thing\\\". State your confidence after you have committed to a position, not before, and weigh the reply against verified repository evidence — counsel is direction, not dictation, and you own the decision.\\n\\n\"\n\n/**\n * Short, always-resident pointer to the consult contract, injected into the\n * digest (`--append-system-prompt`) instead of the full block. Keeps the\n * trigger + budget visible at top salience without duplicating the ~250-word\n * contract every turn; the full how-to lives in the mirrored CLAUDE.md.\n */\nexport const CHEAPEST_CONSULT_CONTRACT_POINTER =\n \"Consulting `advisor`/`oracle` (small budget, ~8-10 calls — choose wisely): use them for how/what — shortest path, what to consider, planning, strategy, direction — never for anything a search, read, or run settles, nor for routine progress, reassurance, or completion ritual; do not spend one where `reviewer` (verification) or `oracle` (a self-contained technical trade-off) owns the moment. Full how-to (when to spend, the call brief, the discriminator) is in your CLAUDE.md project instructions.\\n\\n\"\n\n/**\n * Build the operating-defaults directive for one launch, naming only the\n * natives that launch actually emitted.\n *\n * Callers must pass the SAME availability booleans they used for the `.md`\n * generation and `buildPeerAwarenessSnippet`, so the three surfaces cannot\n * disagree about which agents exist.\n */\nexport function buildOperatingDefaultsDirective(\n opts: NativeAgentAvailability = {},\n): string {\n if (opts.profile === \"max\") {\n const peersKey = opts.peersKey ?? opts.groupKeys?.peers ?? \"peers\"\n const artifactClause = opts.artifactAvailable\n ? ` Live human review is available in the artifact panel via \\`mcp__${peersKey}__artifact_*\\`.`\n : \"\"\n // Pipeline awareness is --swe-gated: without the flag the skill files are\n // not written, so the directive must not name them. Absent keeps the\n // legacy text for callers without a flag concept (serve path).\n const pipelineClause = opts.sweEnabled === false ? \"\" : `\\n\\n${PIPELINE_SKILLS_AWARENESS}`\n return (\n \"## Operating defaults (these layer with the user's explicit direction and the domain's own standards as addons, not replacements: follow all three together; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + \"Max launch profile. The lead owns the outcome. Start with direct repository or runtime evidence. Handle narrow, obvious, surgical, and single-command work directly; delegate a bounded workstream when it is broad, slow, context-heavy, or benefits from a genuinely independent perspective. \"\n + MAX_PARALLELISM_RULE\n + \" Brief each role with the desired outcome, relevant context, constraints, expected evidence, and verification. Use the roster as complementary capabilities, never as a required Explore → Plan → implement → review sequence. Avoid overlapping assignments and do not ask several models the same generic question. Synthesize results against the repository and executable checks: model agreement is not verification. Use one fresh-context peer only when a consequential judgment remains after direct checks; use the coordinator only when several distinct lenses could change the decision. Advisor is optional, non-binding counsel for one focused consequential uncertainty that evidence and the appropriate roles cannot settle; it has no approval or workflow authority, and a further consultation requires materially new or conflicting evidence.\"\n + artifactClause\n + pipelineClause\n )\n }\n if (opts.profile === \"fast\" || opts.profile === \"cheap\" || opts.profile === \"cheap1m\" || opts.profile === \"cheapest\" || opts.profile === \"balanced\") {\n const isCheap = opts.profile === \"cheap\" || opts.profile === \"cheap1m\"\n const isCheapest = opts.profile === \"cheapest\"\n const isBalanced = opts.profile === \"balanced\"\n const profileLabel = isCheapest ? \"Cheapest\" : isCheap ? \"Cheap\" : isBalanced ? \"Balanced\" : \"Fast\"\n const oracleDescriptor = isCheapest\n ? \"GPT-6 Sol (200K/high)\"\n : isCheap || isBalanced\n ? \"Grok 4.6 (200K/medium)\"\n : \"exact Opus 5.5 (1M/high)\"\n const astraDescriptor = isCheap && !isCheapest ? \"200K/medium\" : \"200K/high\"\n // Cheapest/balanced have no Plan role; fast/cheap/cheap1m still do.\n const expensiveModels = isCheapest || isBalanced ? \"(reviewer, Oracle)\" : \"(Plan, reviewer, Oracle)\"\n const searchGuidance = opts.bluebirdEnabled === true\n ? \"Search strategy: use Bluebird `code` search in `lexical` mode for indexed keyword queries and `semantic` mode for intent/concept questions. Bluebird failures remain visible and never fall back locally; `exact`, `regex`, and `ast` stay on the local live tree. `Explore` subagents read the narrowed files and return file:line conclusions; expensive models \" + expensiveModels + \" see only the synthesized subset, never raw search output. \"\n : opts.semanticSearchAvailable === true\n ? \"Search strategy (cheapest first): (1) LOCAL LEXICAL `code` search (mode:\\\"lexical\\\"/\\\"exact\\\", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys; (2) local ColBERT SEMANTIC `code` search for intent/concept questions where literal keywords may not appear, with lexical fallback while its index is unavailable; (3) `Explore` subagents read the narrowed files and return file:line conclusions — expensive models \" + expensiveModels + \" see only the synthesized subset, never raw search output. \"\n : \"Search strategy (cheapest first): LOCAL LEXICAL `code` search (mode:\\\"lexical\\\"/\\\"exact\\\", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys. `Explore` subagents read the narrowed files and return file:line conclusions — expensive models \" + expensiveModels + \" see only the synthesized subset, never raw search output. \"\n if (opts.fastRuntimeAvailable === false) {\n return (\n \"## Operating defaults (these layer with the user's explicit direction and the domain's own standards as addons, not replacements: follow all three together; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + `${profileLabel} profile runtime wiring is unavailable. Work directly, use only tools actually listed in this session, verify with the repository's relevant build/tests before declaring done, report uncertainty, and do not invent unavailable capabilities.`\n )\n }\n const peersKey = opts.peersKey ?? opts.groupKeys?.peers ?? \"peers\"\n const searchKey = opts.groupKeys?.search ?? \"search\"\n const browserKey = opts.groupKeys?.browser ?? \"browser\"\n const workersKey = opts.groupKeys?.workers ?? \"workers\"\n const directBrowserAvailable = opts.browserToolsAvailable ?? opts.browseAvailable\n const browserClause = directBrowserAvailable ? ` \\`mcp__${browserKey}__*\\` provides direct browser control.` : \"\"\n const workerBrowseClause = opts.browseAvailable\n ? ` \\`worker-browse\\` runs delegated autonomous browsing tasks through \\`mcp__${workersKey}__browse\\`.`\n : \"\"\n const artifactClause = opts.artifactAvailable\n ? ` \\`mcp__${peersKey}__artifact_*\\` provides human review in the artifact panel with auto-open on plan completion.`\n : \"\"\n\n const astraClause = opts.astraAvailable && (opts.profile === \"fast\" || opts.profile === \"cheap1m\")\n ? ` \\`mcp__${peersKey}__astra\\` (GPT-6 Astra ${astraDescriptor}) is the terminal escalation consultant for the lead only, reserved strictly for the hardest dead ends when direct evidence, Advisor, and Oracle have all failed to produce a defensible path (consulted at most 1-2 times per decision with concise context and specific questions).`\n : \"\"\n\n // Cheapest is tuned for straightforward tasks: no proactive fan-out push,\n // so the lead handles simple work inline instead of paying handoff\n // overhead. The lead plans directly (no Plan role) and reviews the\n // final plan with the Advisor before presenting it. Balanced diverges\n // from the fast/cheap phase pipeline: search-first, and the lead owns\n // planning, implementation, and verification by default (reviewer ONLY\n // on genuine need; Explore/General-Purpose freely). The lead narrows\n // scope with code/web search before paying for Explore fan-out, and the\n // reviewer may invoke Explore for targeted discovery (see\n // BALANCED_PROFILE_DELEGATION_GRAPH).\n const pipeline = isCheapest\n ? `${profileLabel} launch profile. The lead owns the outcome and handles straightforward work directly. `\n + buildNativeReachClauses(opts)\n + \". Handle trivial, surgical, single-file, or single-command tasks directly; you do not need to justify skipping delegation. \"\n + \"`Explore` may be used for discovery spanning more than a couple of files; `General-Purpose` for mixed multi-step execution; `reviewer` for behavior-changing or risk-sensitive changes. \"\n + \"In plan mode, produce the plan and acceptance criteria directly and do not edit files; before presenting the final plan to the user, consult `advisor` once for a framing check. \"\n + \"Work to your strengths as a fast, cost-efficient model: verify by execution rather than memory; before a non-trivial task, write a short plan (steps, files involved, the check settling each step) and execute it; persist through tool failures with a rephrased attempt before asking the user; stop searching when further results stop changing the answer; tag claims verified, inferred, or unverified — never state that something passes, compiles, or is covered without observed output. \"\n + \"Delegation graph: the lead may invoke all three; `General-Purpose` may invoke `reviewer`; `Explore`, `reviewer`, and `worker-browse` cannot invoke native subagents.\\n\\n\"\n + CHEAPEST_CONSULT_CONTRACT\n : isBalanced\n ? `${profileLabel} launch profile. The lead coordinates execution across specialized native roles: `\n + buildNativeReachClauses(opts)\n + \". Lead owns planning, implementation, and verification by default: in plan mode, produce the plan and acceptance criteria directly and do not edit files. \"\n + \"Phase pipeline (budget gather, budget execution, expensive verification). \"\n + \"GATHER: narrow scope first with `code_search` (lexical, then semantic when available) and `web` search to rule out hypotheses — cheapest, always first. Delegate to `Explore` only when search is insufficient: launch one or more `Explore` subagents in parallel with scoped evidence questions and let them return file:line citations; read directly only the small subset you must touch to decide or edit. \"\n + \"PLAN: lead owns planning: sequence interfaces, invariants, and acceptance criteria directly. \"\n + \"EXECUTE: lead implements directly by default. Delegate to `General-Purpose` FREELY for multi-step work combining investigation, tool workflows, and code changes; brief with outcome, constraints, files in scope, and verification. \"\n + \"VERIFY: lead owns verification: run relevant build/tests, read the code, and reproduce before declaring done. Invoke `reviewer` ONLY when the change is genuinely behavior-changing, cross-boundary, or risk-sensitive; `reviewer` narrows scope with search first and may invoke `Explore` for targeted discovery. \"\n + \"Handle trivial, surgical, single-file, or single-command tasks directly; you do not need to justify skipping delegation. \"\n + \"`Explore` is cheap and may be launched in parallel across independent discovery questions. Send independent subagent calls in parallel within a single turn. \"\n + \"Delegation graph: the lead may invoke all three; `General-Purpose` may invoke `reviewer`; `reviewer` may invoke `Explore` for targeted discovery; `Explore` and `worker-browse` cannot invoke native subagents.\\n\\n\"\n : `${profileLabel} launch profile. The lead coordinates execution across specialized native roles: `\n + buildNativeReachClauses(opts)\n + \". In plan mode or when designing changes with complex sequencing, interface contracts, or acceptance criteria, delegate architectural planning to `Plan` (in plan mode, produce the plan and acceptance criteria; do not edit files). \"\n + \"Phase pipeline (budget gather, expensive plan, budget execution, expensive verification). \"\n + \"GATHER: delegate to `Explore` instead of exploring yourself. For any question spanning more than a couple of files, launch one or more `Explore` subagents in parallel with scoped evidence questions and let them return file:line citations; read directly only the small subset you must touch to decide or edit. `Plan` follows the same rule when it needs repository facts. \"\n + \"PLAN: `Plan` produces handoff-ready steps (ordered, file:line, done conditions, acceptance criteria) for a `General-Purpose` executor that cannot see its reasoning; `Plan` may consult Oracle on unresolved trade-offs and reports any remaining gap to the lead. \"\n + \"EXECUTE: delegate mixed multi-step work and Plan handoffs to `General-Purpose` in a fresh context to preserve lead context; brief with outcome, constraints, files in scope, and verification. \"\n + \"VERIFY: after behavior-changing, cross-boundary, or risk-sensitive implementation, run relevant build/tests then invoke `reviewer` before declaring done. \"\n + \"Handle trivial, surgical, single-file, or single-command tasks directly; you do not need to justify skipping delegation. \"\n + \"`Explore` is cheap and may be launched in parallel across independent discovery questions. Send independent subagent calls in parallel within a single turn. \"\n + \"Delegation graph: the lead may invoke all four; `Plan` may invoke `Explore` and `reviewer`; `General-Purpose` may invoke `reviewer`; `Explore`, `reviewer`, and `worker-browse` cannot invoke native subagents.\\n\\n\"\n\n // 200K profiles: every role the lead can reach runs at the 200K default\n // window (cheap1m's lead excepted at 1M), so the directive names targeted\n // reads once instead of repeating it per role.\n const windowNote = isCheapest || isBalanced\n ? \"All roles run at a 200K context window — use targeted reads (search, Grep, Read specific files) over full file reads.\\n\\n\"\n : isCheap\n ? \"The lead runs at a 200K context window on `-m cheap` (1M on `-m cheap1m`) and every subagent runs at 200K — use targeted reads (search, Grep, Read specific files) over full file reads.\\n\\n\"\n : \"\"\n\n // Pipeline awareness is --swe-gated: without the flag the skill files are\n // not written, so the directive must not name them. Absent keeps the\n // legacy text for callers without a flag concept (serve path).\n const swePipelineClause = opts.sweEnabled === false\n ? \"\"\n : `${isCheapest || isBalanced ? PIPELINE_SKILLS_AWARENESS_NO_PLAN_AGENT : PIPELINE_SKILLS_AWARENESS}\\n\\n`\n // Balanced has no Advisor: Oracle is the only consultant, framed as a\n // second opinion on a precise question — never a discovery tool. For\n // unknowns, only search (then Explore) helps. Cheapest and balanced have\n // no Plan role, so Oracle is lead-only there; fast/cheap/cheap1m keep\n // lead-and-Plan Oracle access.\n const oracleLeadOnly = isCheapest || isBalanced\n const consultation = isBalanced\n ? \"Consultation guidance: funnel unknowns cheapest-first. (1) `code_search` and `web` search narrow scope and rule out hypotheses — always first. (2) `Explore` subagents for targeted breadth only when search is insufficient. \"\n + `\\`mcp__${peersKey}__oracle\\` is ${oracleDescriptor}, a second opinion for precise, self-contained architectural/spec trade-offs that search and \\`Explore\\` cannot settle; available to the lead; \\`reviewer\\` and other subagents cannot call Oracle. Optimize for accuracy, intelligence, and correctness at the lowest cost — prefer direct evidence over delegation when the question is narrow. `\n : \"Consultation guidance: Follow an evidence-first escalation ladder. Direct empirical evidence (search, code, tests, builds) settles factual questions first. Advisor is an optional, non-binding, lead-only transcript-aware sounding board for trajectory guidance or framing checks (direction, not dictation), and never use it for routine progress, waiting, directly verifiable facts, or completion ritual. \"\n + `\\`mcp__${peersKey}__oracle\\` is ${oracleDescriptor}, an expert consultant ${oracleLeadOnly ? \"available to the lead\" : \"available to the lead and `Plan`\"}, preferred over advisor for difficult conceptual, algorithmic, spec/protocol, or architectural tradeoffs evaluated in a self-contained brief; \\`reviewer\\` and other subagents cannot call Oracle. Discriminator: transcript-aware trajectory/framing/momentum → advisor; a self-contained technical/architectural trade-off → Oracle.${isCheapest ? \"\" : \" `Plan` may consult Oracle on unresolved trade-offs, and reports any remaining tie-breaking gap to the lead.\"}${astraClause} `\n return (\n \"## Operating defaults (these layer with the user's explicit direction and the domain's own standards as addons, not replacements: follow all three together; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + pipeline\n + windowNote\n + consultation\n + searchGuidance\n + `\\`mcp__${searchKey}__web\\` provides citable sources.${browserClause}${workerBrowseClause}${artifactClause}\\n\\n`\n + swePipelineClause\n + \"Verify claims with concrete repository evidence and tests before declaring work done. User instructions outrank delegation triggers. Stop named teammates when finished.\"\n )\n }\n return (\n \"## Operating defaults (these layer with the user's explicit direction and the domain's own standards as addons, not replacements: follow all three together; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + \"Orchestrate. Delegate research, implementation, review, and large reads to the \"\n + \"right subagent, worker, or model. Reach for \"\n + buildNativeReachClauses(opts)\n + \"; worker-* agents for background \"\n + \"non-blocking runs; Task subagents for parallel work; peer critics for review. \"\n + \"That keeps your own \"\n + OPERATING_DEFAULTS_TAIL\n )\n}\n\n/** The all-available form of the directive. Prefer\n * `buildOperatingDefaultsDirective` on any path that knows which natives\n * resolved; this const is the default for callers and tests that do not model\n * a thin catalog. */\nexport const OPERATING_DEFAULTS_DIRECTIVE = buildOperatingDefaultsDirective()\n\nconst STANDARD_OPERATING_DEFAULTS_DIGEST =\n \"## Operating defaults (these layer with the user's direction and the domain's standards as addons: follow all three; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + \"Delegate when the work is WIDE (many files or sources to sweep) or SLOW and you need only the \"\n + \"conclusion, to protect the main thread's finite context and keep it free for reasoning and \"\n + \"interacting with the user; prefer parallel delegation for independent work. Do NOT delegate \"\n + \"merely because a sub-question is separable: a narrow, deep question whose value is file:line \"\n + \"fidelity loses exactly that through a summarization layer, and one answerable in a single \"\n + \"command is cheaper done directly. Do trivial, surgical, and last-mile work yourself. \"\n + \"Stop a named teammate once you are done with it: it persists for follow-ups, its idle \"\n + \"notice means available rather than finished, and nothing reaps it for you.\\n\\n\"\n + \"Verify, do not assert. Run the code, read the file, check the exit code. A claim in prose is \"\n + \"worth nothing against state you did not check, and a check that cannot fail proves nothing. \"\n + \"Reproduce a bug end to end, the way a real user hits it, before fixing it. Fix a lint error, \"\n + \"failing test, or flake the moment you see it, whoever introduced it, without letting it \"\n + \"derail the task at hand. Prefer quality and long-term maintainability over development cost.\\n\\n\"\n + \"Verification has a blind spot: a consequential recommendation, a design or trade-off call, or \"\n + \"a hard-to-reverse decision that still turns on judgment among plausible alternatives once the \"\n + \"direct evidence is in. That is where confabulation hides, so put it past a peer critic before \"\n + \"you ship it and budget the wait even under delivery pressure. When a test, a run, a \"\n + \"reproduction, or a search would settle the claim, settle it that way instead; a critic asked \"\n + \"to re-derive what you can already prove is ritual, not review.\\n\\n\"\n + \"The agent roster, the tool surface, and the reasoning behind these defaults are in your \"\n + \"CLAUDE.md project instructions. Read them when choosing HOW to work; the rules above apply \"\n + \"without a lookup.\"\n\nexport function buildOperatingDefaultsDigest(\n opts: { profile?: \"standard\" | \"fast\" | \"cheap\" | \"cheap1m\" | \"cheapest\" | \"balanced\" | \"max\"; astraAvailable?: boolean; sweEnabled?: boolean } = {},\n): string {\n // --swe-gated pipeline sentence: without the flag the skill files are not\n // written, so the digest must not name them. Absent keeps the legacy text\n // for callers without a flag concept. Cheapest/balanced have no Plan role,\n // so their sentence names lead-direct planning instead of a Plan dispatch.\n const digestPipelineSentence = opts.sweEnabled === false\n ? \"\"\n : opts.profile === \"cheapest\" || opts.profile === \"balanced\"\n ? \"Pipeline skills (all 200K default, native subagents only): `/gh-gather-context` before planning when context is needed, `/gh-plan` before implementation (the lead plans directly on this profile; trivial exits planless, waits for user approval), `/gh-implement` after approval with parallel subagents and conditional reviewer. Skip for trivial work.\\n\\n\"\n : \"Pipeline skills (all 200K default, native subagents only): `/gh-gather-context` before planning when context is needed, `/gh-plan` before implementation (trivial exits planless, waits for user approval), `/gh-implement` after approval with parallel subagents and conditional reviewer. Skip for trivial work.\\n\\n\"\n if (opts.profile === \"max\") {\n return (\n \"## Operating defaults (these layer with the user's direction and the domain's standards as addons: follow all three; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + \"Max launch profile. The lead owns the outcome. Start with direct repository or runtime evidence. Do narrow, obvious, surgical, and single-command work directly; delegate bounded work that is broad, slow, context-heavy, or independently valuable. \"\n + MAX_PARALLELISM_RULE\n + \" Give delegated workstreams non-overlapping scopes and state the outcome, constraints, evidence, and verification expected.\\n\\n\"\n + digestPipelineSentence\n + \"Synthesize and verify: run the code, inspect outputs, and check tests. Agent count and agreement are not evidence. Use a fresh-context peer only for consequential judgment that remains after direct checks, and use the coordinator only when several distinct lenses could change the decision. Advisor is optional, non-binding, primary-lead-only counsel for one focused consequential uncertainty; it is not an approval or completion gate.\"\n )\n }\n if (opts.profile === \"fast\" || opts.profile === \"cheap\" || opts.profile === \"cheap1m\" || opts.profile === \"cheapest\" || opts.profile === \"balanced\") {\n const isCheap = opts.profile === \"cheap\" || opts.profile === \"cheap1m\"\n const isCheapest = opts.profile === \"cheapest\"\n const isBalanced = opts.profile === \"balanced\"\n const profileLabel = isCheapest ? \"Cheapest\" : isCheap ? \"Cheap\" : isBalanced ? \"Balanced\" : \"Fast\"\n const oracleDescriptor = isCheapest\n ? \"(GPT-6 Sol 200K/high, lead-only)\"\n : isBalanced\n ? \"(Grok 4.6 200K/medium, lead-only)\"\n : isCheap\n ? \"(Grok 4.6 200K/medium, lead and Plan)\"\n : \"(Opus 5 1M/high, lead and Plan)\"\n // No balanced branch: balanced exposes Oracle but no Advisor, so its\n // ladder (consultationLadder below) never interpolates this descriptor.\n const advisorDescriptor = isCheapest ? \"(Sol/medium, lead-only)\" : \"(Sol/high, lead-only)\"\n const astraStep =\n opts.astraAvailable && (opts.profile === \"fast\" || opts.profile === \"cheap1m\")\n ? `; (4) \\`astra\\` (GPT-6 Astra 200K/${isCheap ? \"medium\" : \"high\"}, lead-only) only as a last resort when direct evidence, Advisor, and Oracle cannot produce a defensible path (at most 1-2 calls per decision).`\n : \".\"\n const delegation = isCheapest\n ? `${profileLabel} launch profile. The lead owns the outcome and handles straightforward work directly: use \\`Explore\\` for discovery spanning more than a couple of files, \\`General-Purpose\\` for mixed multi-step execution, and \\`reviewer\\` for behavior-changing or risk-sensitive changes. In plan mode, produce the plan and acceptance criteria directly; before presenting the final plan to the user, consult \\`advisor\\` once for a framing check. Plan briefly before non-trivial acts, verify by execution, tag unverified claims, and stop searching when results stop changing the answer. Handle trivial and surgical edits directly. Stop named teammates when finished.\\n\\n`\n + CHEAPEST_CONSULT_CONTRACT_POINTER\n : isBalanced\n ? `${profileLabel} launch profile. The lead owns planning, implementation, and verification by default: narrow scope first with \\`code_search\\` and \\`web\\` search to rule out hypotheses (cheapest, always first); delegate to \\`Explore\\` in parallel only when search is insufficient (read directly only files you will act on); delegate to \\`General-Purpose\\` FREELY for multi-step work combining investigation, tool workflows, and code changes; invoke \\`reviewer\\` ONLY when the change is genuinely behavior-changing, cross-boundary, or risk-sensitive (\\`reviewer\\` narrows scope with search first and may invoke \\`Explore\\` for targeted discovery); handle trivial and surgical edits directly. Send independent subagent calls in parallel within a single turn. Stop named teammates when finished.\\n\\n`\n : `${profileLabel} launch profile. The lead coordinates execution across specialized roles: delegate broad discovery to \\`Explore\\` in parallel and do not sweep the repo yourself (read directly only files you will act on); delegate to \\`Plan\\` in plan mode or when structuring complex multi-step sequencing (\\`Plan\\` is an advisory planning capability, not an approval gate, and writes handoff-ready steps for \\`General-Purpose\\`); delegate mixed multi-step execution and Plan handoffs to \\`General-Purpose\\` in a fresh context; delegate to \\`reviewer\\` after behavior-changing or risk-sensitive implementation to verify correctness before declaring done; handle trivial and surgical edits directly. Send independent subagent calls in parallel within a single turn. Stop named teammates when finished.\\n\\n`\n // Balanced has no Advisor: the ladder is search → Explore → Oracle\n // (second opinion on a framed question, never discovery).\n const consultationLadder = isBalanced\n ? \"Verify claims against real evidence: run relevant commands and tests. Funnel unknowns cheapest-first: (1) `code_search` + `web` search narrow scope and rule out hypotheses first; (2) `Explore` for targeted breadth when search is insufficient; (3) `oracle` \"\n + oracleDescriptor\n + \" as a second opinion for precise, self-contained technical/architectural trade-offs that search and `Explore` cannot settle. Optimize for accuracy, intelligence, and correctness at the lowest cost.\"\n : \"Verify claims against real evidence: run relevant commands and tests. Follow a disciplined consultation ladder for unresolved decisions: (1) direct code inspection, search, builds, and tests settle factual questions; (2) `advisor` \"\n + advisorDescriptor\n + \" for transcript-aware framing checks or trajectory guidance (session momentum/trajectory); (3) `oracle` \"\n + oracleDescriptor\n + \" for self-contained technical/architectural trade-offs\"\n + astraStep\n // Mirror of the directive's windowNote, condensed for the digest.\n const digestWindowNote = isCheapest || isBalanced\n ? \"All roles run at a 200K context window — use targeted reads over full file reads.\\n\\n\"\n : isCheap\n ? \"The lead runs at 200K on `-m cheap` (1M on `-m cheap1m`) and every subagent runs at 200K — use targeted reads over full file reads.\\n\\n\"\n : \"\"\n return (\n \"## Operating defaults (these layer with the user's direction and the domain's standards as addons: follow all three; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + delegation\n + digestPipelineSentence\n + digestWindowNote\n + consultationLadder\n )\n }\n return STANDARD_OPERATING_DEFAULTS_DIGEST\n}\n\n/**\n * Condensed digest of OPERATING_DEFAULTS_DIRECTIVE for the spawned session's\n * system prompt (--append-system-prompt). The FULL directive is prepended to\n * the mirrored CLAUDE.md (read by the main agent and descendants); this digest\n * keeps both behavioral directives at top salience without duplicating the full\n * ~310-token block in the context window every turn. Points to the full copy.\n *\n * The unverifiable-claim rule is here rather than in CLAUDE.md alone because it\n * fires at a moment that suppresses lookups: an agent racing to deliver a\n * recommendation is precisely the one that will not stop to consult its project\n * instructions, which is how the check got crowded out in the first place. It\n * also closes a hole in the rule above it, which only covers claims that direct\n * evidence CAN settle. The roster of critics, the lens-to-artifact match, and\n * the reasoning stay in the directive; the always-resident copy carries only\n * the trigger and the ritual exclusion.\n */\nexport const OPERATING_DEFAULTS_DIGEST = STANDARD_OPERATING_DEFAULTS_DIGEST\n\n/**\n * Skip the helper if the user's `~/.claude/CLAUDE.md` (or, equivalently,\n * the would-be post-write file) has grown past this size.\n * Read-modify-write becomes pathological at very large sizes; CLAUDE.md\n * should never legitimately be a database. The main agent still gets\n * the awareness via `--append-system-prompt`, so skipping here only\n * loses descendant-reach.\n */\nconst MAX_CLAUDE_MD_BYTES = 1 * 1024 * 1024 // 1 MiB\n\n/**\n * Bounded retry budget for the temp → rename step on Windows where\n * `fs.rename` can transiently fail with EBUSY / EPERM / EACCES when\n * CLAUDE.md is open in an editor, scanned by AV, or indexed by the\n * search service. Mirrors the verify-on-rename-fail pattern at\n * `paths.ts:795-818`. POSIX renames almost never fail this way; the\n * cost on Linux/macOS is one extra `lstat` in the unhappy path.\n */\nconst RENAME_RETRY_DELAYS_MS = [50, 200, 500] as const\n\n/**\n * Grep-able error-code prefix. Every warn-and-continue path here\n * starts its message with this token so a Windows user who never sees\n * a fresh marker block in their mirror can `grep CLAUDE_MD_WRITE` in\n * the launcher output and land on the actionable line directly.\n */\nconst ERROR_CODE = \"CLAUDE_MD_WRITE\"\n\ninterface MarkerBlock {\n openLineIndex: number\n closeLineIndex: number\n}\n\n/**\n * Find every well-formed marker block matching the given `markerOpen`\n * + `markerClose` pair. A well-formed block is an exact `markerOpen`\n * line followed somewhere later (any number of intervening lines) by\n * an exact `markerClose` line, with no intervening `markerOpen`.\n * Multiple stale blocks all surface here so the caller can remove\n * all of them.\n *\n * Malformed state (open without close, or close without open) is\n * reported separately via the second return value so the caller can\n * `warn` and leave user prose untouched. We never try to \"fix\"\n * malformed marker state — that risks corrupting user content.\n */\nexport function findMarkerBlocks(\n lines: ReadonlyArray<string>,\n markerOpen: string = PEER_MARKER_OPEN,\n markerClose: string = PEER_MARKER_CLOSE,\n): {\n blocks: Array<MarkerBlock>\n malformed: boolean\n} {\n const blocks: Array<MarkerBlock> = []\n let pendingOpen: number | null = null\n let malformed = false\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n if (line === markerOpen) {\n if (pendingOpen !== null) {\n // Two opens with no close between them — malformed.\n malformed = true\n }\n pendingOpen = i\n } else if (line === markerClose) {\n if (pendingOpen === null) {\n // Close with no preceding open — malformed.\n malformed = true\n } else {\n blocks.push({ openLineIndex: pendingOpen, closeLineIndex: i })\n pendingOpen = null\n }\n }\n }\n if (pendingOpen !== null) {\n // Open with no close — malformed.\n malformed = true\n }\n return { blocks, malformed }\n}\n\n/**\n * Detect line-ending style of `content`. Returns `\"\\r\\n\"` if `\\r\\n`\n * sequences outnumber bare `\\n`; otherwise `\"\\n\"`. Empty content\n * defaults to `\\n` (POSIX-style new file).\n *\n * Preserves CRLF on Windows users' existing CLAUDE.md — flipping their\n * line endings under them would be a regression even though Claude\n * Code itself reads either style.\n */\nfunction detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n if (content.length === 0) return \"\\n\"\n // Count CRLF occurrences. Bare `\\n` count is `\\n total - CRLF count`.\n const crlf = (content.match(/\\r\\n/g) ?? []).length\n const totalLf = (content.match(/\\n/g) ?? []).length\n const bareLf = totalLf - crlf\n return crlf > bareLf ? \"\\r\\n\" : \"\\n\"\n}\n\n/**\n * Strip a leading UTF-8 BOM (`U+FEFF`) if present so the first line's\n * marker comparison is byte-exact. CLAUDE.md authored on Windows in\n * Notepad / VS Code sometimes carries a BOM; without this strip the\n * first marker line would never match (`<BOM><!--...` !== `<!--...`)\n * and successive launches would loop into malformed-state warn paths.\n */\nfunction stripLeadingBom(content: string): string {\n return content.charCodeAt(0) === 0xfeff ? content.slice(1) : content\n}\n\n/**\n * Split `content` into lines without losing the line-ending style.\n * The split is done on `\\n`; trailing `\\r` (from CRLF) is stripped\n * from each line for marker comparison, but the original ending is\n * reconstructed via `detectLineEnding` + `joinLines`.\n */\nfunction splitLines(content: string): Array<string> {\n if (content.length === 0) return []\n const lines = content.split(\"\\n\").map((l) =>\n l.endsWith(\"\\r\") ? l.slice(0, -1) : l,\n )\n // If the file ends in `\\n`, the trailing element is `\"\"` — keep it\n // so we can detect \"trailing newline present\" when rebuilding.\n return lines\n}\n\nfunction joinLines(lines: ReadonlyArray<string>, eol: \"\\r\\n\" | \"\\n\"): string {\n return lines.join(eol)\n}\n\n/**\n * Containment check that defeats symlink/junction tricks (peer-review\n * C3). `isUnderClaudeConfigMirror` is purely lexical via\n * `path.resolve()` — it does NOT dereference symlinks, so an attacker\n * (or an unfortunate `~/.claude` symlinked into Dropbox) could escape\n * the mirror while passing the lexical guard. This helper resolves\n * BOTH paths to their canonical form via `fs.realpath()` first.\n *\n * **Fail-closed semantics (advisor follow-up):**\n *\n * - If the mirror root itself is a symlink (`lstat` reports\n * `isSymbolicLink() === true`), refuse. A symlinked mirror root\n * means writes flow through the link to whatever the user (or an\n * attacker) targeted — the boundary's whole point is to never\n * mutate real `~/.claude/`, so accepting any symlinked root\n * undermines it.\n * - If `realpath` fails on the mirror root OR the target parent,\n * refuse. The mirror dir is provisioned by `ensureClaudeConfigMirror`\n * before this helper runs (documented ordering invariant); a\n * `realpath` failure here signals an unexpected state, and after\n * the root check has already succeeded a missing parent means the\n * root vanished between checks (TOCTOU race).\n */\nexport async function isUnderClaudeConfigMirrorRealpath(\n target: string,\n): Promise<boolean> {\n // Fast lexical reject first: if even the lexical check fails the\n // path is clearly wrong and we never need to touch the filesystem.\n if (!isUnderClaudeConfigMirror(target)) return false\n\n const mirrorRoot = PATHS.CLAUDE_CONFIG_DIR\n\n // Reject a symlinked mirror root. realpath would happily follow it\n // and the resolved target would still appear \"under\" the resolved\n // root — masking the escape.\n try {\n const rootLink = await fs.lstat(mirrorRoot)\n if (rootLink.isSymbolicLink()) {\n consola.warn(\n `${ERROR_CODE}: mirror root is a symlink (${mirrorRoot}); refusing to write through it`,\n )\n return false\n }\n } catch (err) {\n consola.warn(\n `${ERROR_CODE}: cannot lstat mirror root ${mirrorRoot}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n return false\n }\n\n // Canonicalize the mirror root. Failure here is fail-closed — the\n // mirror should exist by the time this helper runs.\n let resolvedRoot: string\n try {\n resolvedRoot = await fs.realpath(mirrorRoot)\n } catch (err) {\n consola.warn(\n `${ERROR_CODE}: realpath failed on mirror root ${mirrorRoot}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n return false\n }\n\n // Canonicalize the target's parent. ENOENT here is fail-closed: the\n // mirror root has already been lstat'd and realpath'd successfully\n // above, so a missing parent at this point means the root vanished\n // between checks — exactly the race-window an attacker would use to\n // swap the mirror with a symlink/junction. Refuse rather than grant\n // access (peer-review codex-critic C1).\n const targetParent = path.dirname(target)\n let resolvedTargetParent: string\n try {\n resolvedTargetParent = await fs.realpath(targetParent)\n } catch (err) {\n consola.warn(\n `${ERROR_CODE}: realpath failed on target parent ${targetParent} after root check (TOCTOU?): ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n return false\n }\n\n if (resolvedTargetParent === resolvedRoot) return true\n return resolvedTargetParent.startsWith(resolvedRoot + path.sep)\n}\n\n/**\n * Try `fs.rename(temp, target)` with bounded retry + verify-on-fail.\n * Mirrors `injectSyntheticClaudeJsonFields` in `paths.ts`. Windows\n * `fs.rename` can transiently fail with EBUSY / EPERM / EACCES when\n * the destination is held by another process (editor, AV, search\n * indexer). Returns `true` on eventual success, `false` after all\n * retries are exhausted (caller will warn-and-continue).\n *\n * On final failure we read the destination back and check whether it\n * already matches `desiredContent` — a concurrent racer may have\n * landed the same bytes (the snippet is deterministic per launch).\n * In that case treat as success.\n *\n * **No `copyFile` fallback** (peer-review codex-critic C2). `fs.copyFile`\n * follows the destination path — if `target` was replaced with a\n * symlink/junction between our earlier `lstat` and now (TOCTOU), or\n * if `target` is a hardlink to the real `~/.claude/CLAUDE.md`,\n * `copyFile` would mutate user files through the link. The boundary\n * we are defending says \"never mutate the real `~/.claude/`\". Rename\n * is safe because replacing a path entry doesn't follow the link; the\n * `copyFile` degradation reintroduces the escape. Fail-closed instead.\n */\nexport async function renameWithRetry(\n tempPath: string,\n target: string,\n desiredContent: string,\n): Promise<boolean> {\n let lastErr: unknown\n for (let attempt = 0; attempt <= RENAME_RETRY_DELAYS_MS.length; attempt++) {\n try {\n await fs.rename(tempPath, target)\n return true\n } catch (err) {\n lastErr = err\n // Don't sleep after the final attempt.\n if (attempt < RENAME_RETRY_DELAYS_MS.length) {\n await new Promise<void>((resolve) =>\n setTimeout(resolve, RENAME_RETRY_DELAYS_MS[attempt]),\n )\n }\n }\n }\n\n // All retries exhausted. Verify-on-fail: did a racer land the same\n // bytes we wanted? (Matches the paths.ts:795-818 pattern.)\n try {\n const observed = await fs.readFile(target, \"utf8\")\n if (observed === desiredContent) {\n await fs.unlink(tempPath).catch(() => {})\n consola.debug(\n `${ERROR_CODE}: rename failed but target already holds expected content (racer-won-race): ${\n lastErr instanceof Error ? lastErr.message : String(lastErr)\n }`,\n )\n return true\n }\n } catch {\n // Fall through to final cleanup + caller-side warn.\n }\n\n // Fail-closed: no copyFile fallback (would follow symlinks/hardlinks\n // and bypass the never-mutate-user-files boundary). Better to lose\n // descendant-reach for this launch than to risk overwriting the\n // user's real CLAUDE.md.\n await fs.unlink(tempPath).catch(() => {})\n consola.warn(\n `${ERROR_CODE}: rename failed for ${target} after ${RENAME_RETRY_DELAYS_MS.length + 1} attempts (no copyFile fallback to avoid symlink/hardlink escape; descendant-reach via CLAUDE.md disabled this launch; main agent still has --append-system-prompt). rename err: ${\n lastErr instanceof Error ? lastErr.message : String(lastErr)\n }`,\n )\n return false\n}\n\n/**\n * Generic marker-block injection into the mirrored CLAUDE.md.\n * Parameterized on the marker pair (so independent blocks coexist\n * without colliding) and position (`\"top\"` = prepend, `\"bottom\"` =\n * append). Encapsulates all the safety invariants; the two exported\n * helpers (`appendPeerAwarenessToMirroredClaudeMd` and\n * `prependStyleDirectiveToMirroredClaudeMd`) are thin wrappers.\n */\ninterface InjectMarkerBlockOpts {\n snippet: string\n markerOpen: string\n markerClose: string\n position: \"top\" | \"bottom\"\n /** Logged in debug messages so the two callers are distinguishable. */\n label: string\n}\n\nasync function injectMarkerBlock(opts: InjectMarkerBlockOpts): Promise<void> {\n const { snippet, markerOpen, markerClose, position, label } = opts\n\n // Invariant 7: writer-side guard. Refuse to inject a snippet that\n // contains either marker literal — otherwise the next launch's\n // parser would see the inner literal as a new open/close and\n // either delete user content (the I5 footgun) or trip the\n // malformed-marker path indefinitely. The snippet body should\n // never legitimately contain these strings; failing fast here\n // catches a builder bug at the source.\n if (snippet.includes(markerOpen) || snippet.includes(markerClose)) {\n consola.warn(\n `${ERROR_CODE}: refusing to inject ${label} snippet that contains marker literal; this would corrupt idempotency on the next launch`,\n )\n return\n }\n\n const target = path.join(PATHS.CLAUDE_CONFIG_DIR, \"CLAUDE.md\")\n\n // Invariant 1: mirror-only safety guard (symlink-resolving).\n if (!(await isUnderClaudeConfigMirrorRealpath(target))) {\n consola.warn(\n `${ERROR_CODE}: refusing to write outside resolved mirror dir (target=${target}, mirror=${PATHS.CLAUDE_CONFIG_DIR}) [${label}]`,\n )\n return\n }\n\n // Invariant 2: refuse to follow symlinks on the leaf. lstat tells\n // us about the link itself; fs.readFile would silently follow.\n let existingContent: string\n let targetExists: boolean\n try {\n const linkStat = await fs.lstat(target)\n if (linkStat.isSymbolicLink()) {\n consola.warn(\n `${ERROR_CODE}: refusing to write through symlinked CLAUDE.md (target=${target}) [${label}]`,\n )\n return\n }\n if (!linkStat.isFile()) {\n // Directory or other non-regular entry sitting where CLAUDE.md\n // should be. Refuse rather than try to fix.\n consola.warn(\n `${ERROR_CODE}: refusing to write non-regular target (target=${target}, mode=${linkStat.mode.toString(8)}) [${label}]`,\n )\n return\n }\n // Early size guard (peer-review codex-critic suggestion #9) — skip\n // before paying the readFile cost. The post-build size guard below\n // catches the runaway-snippet case; this catches the runaway-file\n // case. nlink > 1 also caught here: hardlinked CLAUDE.md to the\n // real user file would otherwise be a path-following escape via\n // fs.writeFile, even with the symlink-refusal above.\n if (linkStat.size > MAX_CLAUDE_MD_BYTES) {\n consola.warn(\n `${ERROR_CODE}: skipping oversized CLAUDE.md (${linkStat.size} bytes > ${MAX_CLAUDE_MD_BYTES}) [${label}]; descendant-reach disabled this launch`,\n )\n return\n }\n if (linkStat.nlink > 1) {\n consola.warn(\n `${ERROR_CODE}: refusing to write to hardlinked CLAUDE.md (nlink=${linkStat.nlink}) [${label}]; would mutate shared inode`,\n )\n return\n }\n targetExists = true\n existingContent = await fs.readFile(target, \"utf8\")\n } catch (err) {\n if (\n typeof err === \"object\"\n && err !== null\n && \"code\" in err\n && (err as { code: string }).code === \"ENOENT\"\n ) {\n // No existing CLAUDE.md — start from empty content.\n existingContent = \"\"\n targetExists = false\n } else {\n consola.warn(\n `${ERROR_CODE}: failed to stat/read target (${target}) [${label}]: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n return\n }\n }\n\n // Invariant 4: detect line-ending style from the existing content\n // AND remember whether the file had a UTF-8 BOM so we can preserve\n // it (peer-review codex-critic I5).\n const hadBom = existingContent.charCodeAt(0) === 0xfeff\n const normalizedContent = stripLeadingBom(existingContent)\n const eol = detectLineEnding(normalizedContent)\n\n // Strip prior well-formed marker blocks of THIS pair only\n // (invariant 5: malformed state is warn-and-leave; we do not edit\n // through user prose). Other marker pairs in the file are untouched\n // so the peer-awareness block and the style block coexist without\n // interfering.\n const lines = splitLines(normalizedContent)\n const { blocks, malformed } = findMarkerBlocks(lines, markerOpen, markerClose)\n if (malformed) {\n consola.warn(\n `${ERROR_CODE}: malformed marker state in ${target} (open without close or vice versa) [${label}]; leaving file untouched`,\n )\n return\n }\n // Remove blocks in reverse order so earlier indices stay valid.\n // Also drop blank-line separators that were inserted around the\n // block on prior writes (loop until non-blank to handle accumulation).\n const cleanedLines = [...lines]\n for (let i = blocks.length - 1; i >= 0; i--) {\n const block = blocks[i]\n cleanedLines.splice(\n block.openLineIndex,\n block.closeLineIndex - block.openLineIndex + 1,\n )\n if (position === \"bottom\") {\n // Drop trailing blank lines BEFORE the (removed) block.\n while (\n block.openLineIndex - 1 >= 0\n && cleanedLines[block.openLineIndex - 1] === \"\"\n && cleanedLines.slice(0, block.openLineIndex - 1).some((l) => l !== \"\")\n ) {\n cleanedLines.splice(block.openLineIndex - 1, 1)\n }\n } else {\n // position === \"top\": drop leading blank lines AFTER the\n // (removed) block — they were the separator we inserted last\n // time between our prepended block and user content.\n while (\n block.openLineIndex < cleanedLines.length\n && cleanedLines[block.openLineIndex] === \"\"\n && cleanedLines.slice(block.openLineIndex + 1).some((l) => l !== \"\")\n ) {\n cleanedLines.splice(block.openLineIndex, 1)\n }\n }\n }\n\n // Trim trailing blank lines so the bottom-append block sits with\n // exactly one separator; for top-prepend, trim leading blanks\n // analogously.\n if (position === \"bottom\") {\n while (\n cleanedLines.length > 0\n && cleanedLines[cleanedLines.length - 1] === \"\"\n ) {\n cleanedLines.pop()\n }\n } else {\n while (cleanedLines.length > 0 && cleanedLines[0] === \"\") {\n cleanedLines.shift()\n }\n }\n\n // Build the final content. Position determines whether our block\n // sits at the top or bottom, with exactly one blank-line separator\n // between user content and our block.\n const snippetLines = snippet.split(\"\\n\").map((l) =>\n l.endsWith(\"\\r\") ? l.slice(0, -1) : l,\n )\n const markerBlockLines = [markerOpen, ...snippetLines, markerClose]\n let finalLines: Array<string>\n if (cleanedLines.length === 0) {\n finalLines = [...markerBlockLines, \"\"]\n } else if (position === \"bottom\") {\n finalLines = [...cleanedLines, \"\", ...markerBlockLines, \"\"]\n } else {\n finalLines = [...markerBlockLines, \"\", ...cleanedLines, \"\"]\n }\n const bodyContent = joinLines(finalLines, eol)\n const finalContent = hadBom ? \"\" + bodyContent : bodyContent\n\n // Invariant 3: size guard, measured on the post-build content so a\n // user fixture sitting just below the cap with a stale block can\n // still be cleaned up (peer-review I6).\n if (Buffer.byteLength(finalContent, \"utf8\") > MAX_CLAUDE_MD_BYTES) {\n consola.warn(\n `${ERROR_CODE}: post-build content exceeds ${MAX_CLAUDE_MD_BYTES} bytes [${label}]; skipping update (descendant-reach disabled this launch)`,\n )\n return\n }\n\n // Invariant 6: atomic temp + rename, with bounded retry + verify-\n // on-fail. No copyFile fallback (would defeat symlink boundary).\n const tempPath = `${target}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`\n try {\n await fs.writeFile(tempPath, finalContent, {\n encoding: \"utf8\",\n flag: \"wx\",\n })\n } catch (err) {\n await fs.unlink(tempPath).catch(() => {})\n consola.warn(\n `${ERROR_CODE}: temp-file write failed for ${tempPath} [${label}]: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n return\n }\n const ok = await renameWithRetry(tempPath, target, finalContent)\n if (!ok) return\n\n consola.debug(\n `${ERROR_CODE}: ${\n targetExists ? \"updated\" : \"created\"\n } ${target} [${label}] (${finalContent.length} bytes, eol=${eol === \"\\r\\n\" ? \"CRLF\" : \"LF\"})`,\n )\n}\n\n/**\n * Append the peer-MCP awareness `snippet` to the mirrored\n * `<CLAUDE_CONFIG_DIR>/CLAUDE.md`. Idempotent across launches: prior\n * well-formed peer-marker blocks are removed before appending a fresh\n * one at the bottom. The original user content is preserved\n * byte-for-byte at the top (modulo line-ending normalization to the\n * file's detected style; leading UTF-8 BOM is preserved).\n *\n * Failures `warn` and return — this surface is the descendant-reach\n * enhancement; the main agent still gets the awareness via\n * `--append-system-prompt`. Every warn message starts with\n * `CLAUDE_MD_WRITE` so users can grep launcher output.\n */\nexport async function appendPeerAwarenessToMirroredClaudeMd(\n snippet: string,\n): Promise<void> {\n await injectMarkerBlock({\n snippet,\n markerOpen: PEER_MARKER_OPEN,\n markerClose: PEER_MARKER_CLOSE,\n position: \"bottom\",\n label: \"peer-mcp-awareness\",\n })\n}\n\n/**\n * Prepend a writing / communication style directive to the TOP of the\n * mirrored `<CLAUDE_CONFIG_DIR>/CLAUDE.md` so every spawned agent\n * reads it first. The directive itself is hard-coded to\n * `STYLE_DIRECTIVE` above; the parameter exists for tests / future\n * configurability. Idempotent across launches via the\n * style-marker fence (separate from the peer-awareness fence, so the\n * two blocks coexist without colliding).\n */\nexport async function prependStyleDirectiveToMirroredClaudeMd(\n directive: string = STYLE_DIRECTIVE,\n): Promise<void> {\n await injectMarkerBlock({\n snippet: directive,\n markerOpen: STYLE_MARKER_OPEN,\n markerClose: STYLE_MARKER_CLOSE,\n position: \"top\",\n label: \"style-directive\",\n })\n}\n\n/**\n * Prepend the operating-defaults directive (orchestrator posture + hybrid\n * excellence lens; `OPERATING_DEFAULTS_DIRECTIVE` above) to the TOP of the\n * mirrored CLAUDE.md so the main agent and descendant agents (Agent subagents,\n * agent-teams teammates) inherit the full statement. The main agent also gets\n * OPERATING_DEFAULTS_DIGEST at higher salience via `--append-system-prompt`.\n * Separate marker fence from the style / peer blocks so all coexist;\n * best-effort (warn-and-continue) like its siblings.\n */\nexport async function prependOperatingDefaultsToMirroredClaudeMd(\n directive: string = OPERATING_DEFAULTS_DIRECTIVE,\n): Promise<void> {\n await injectMarkerBlock({\n snippet: directive,\n markerOpen: OPERATING_MARKER_OPEN,\n markerClose: OPERATING_MARKER_CLOSE,\n position: \"top\",\n label: \"operating-defaults\",\n })\n}\n\n/**\n * Append the toolbelt awareness one-liner (which CLI tools are on PATH)\n * to the bottom of the mirrored CLAUDE.md so descendant agents (Agent\n * subagents, agent-teams teammates) and the main agent learn about the\n * provisioned tools via the mirrored CLAUDE.md. This line is not sent via\n * `--append-system-prompt`.\n * Separate marker fence from the peer-awareness / style blocks.\n */\nexport async function appendToolbeltAwarenessToMirroredClaudeMd(\n snippet: string,\n): Promise<void> {\n await injectMarkerBlock({\n snippet,\n markerOpen: TOOLBELT_MARKER_OPEN,\n markerClose: TOOLBELT_MARKER_CLOSE,\n position: \"bottom\",\n label: \"toolbelt-awareness\",\n })\n}\n\n/**\n * Prepend the artifact-panel review directive to the TOP of the mirrored\n * CLAUDE.md so plans/artifacts are reviewed in the ai-or-die panel by default.\n * Gated by the caller on AIORDIE_SESSION_ID (only useful inside a tab). Separate\n * marker fence; best-effort like the style/peer blocks.\n */\nexport async function prependArtifactPanelDirectiveToMirroredClaudeMd(\n peersKey = \"peers\",\n): Promise<void> {\n await injectMarkerBlock({\n snippet: ARTIFACT_PANEL_DIRECTIVE(peersKey),\n markerOpen: ARTIFACT_MARKER_OPEN,\n markerClose: ARTIFACT_MARKER_CLOSE,\n position: \"top\",\n label: \"artifact-panel-directive\",\n })\n}\n\n/**\n * Test-only exports — internal helpers exposed so unit tests can\n * exercise marker handling and line-ending logic without writing\n * files. NOT part of the public API.\n */\nexport const __testExports = {\n MARKER_OPEN,\n MARKER_CLOSE,\n PEER_MARKER_OPEN,\n PEER_MARKER_CLOSE,\n STYLE_MARKER_OPEN,\n STYLE_MARKER_CLOSE,\n STYLE_DIRECTIVE,\n ARTIFACT_MARKER_OPEN,\n ARTIFACT_MARKER_CLOSE,\n ARTIFACT_PANEL_DIRECTIVE,\n PIPELINE_SKILLS_AWARENESS,\n MAX_CLAUDE_MD_BYTES,\n ERROR_CODE,\n RENAME_RETRY_DELAYS_MS,\n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AO,IAAI,MAAM,KAAK,aAAa,OAAO,cAAc,QAAQ,SAAS,SAAS,KAAK,EAC7F;AACF;;;;;;;;;;;;;;AAeA,eAAsB,sCACpB,SACe;CACf,MAAM,kBAAkB;EACtB;EACA,YAAY;EACZ,aAAa;EACb,UAAU;EACV,OAAO;CACT,CAAC;AACH;;;;;;;;;;AAWA,eAAsB,wCACpB,YAAoB,iBACL;CACf,MAAM,kBAAkB;EACtB,SAAS;EACT,YAAY;EACZ,aAAa;EACb,UAAU;EACV,OAAO;CACT,CAAC;AACH;;;;;;;;;;AAWA,eAAsB,2CACpB,YAAoB,8BACL;CACf,MAAM,kBAAkB;EACtB,SAAS;EACT,YAAY;EACZ,aAAa;EACb,UAAU;EACV,OAAO;CACT,CAAC;AACH;;;;;;;;;AAUA,eAAsB,0CACpB,SACe;CACf,MAAM,kBAAkB;EACtB;EACA,YAAY;EACZ,aAAa;EACb,UAAU;EACV,OAAO;CACT,CAAC;AACH;;;;;;;AAQA,eAAsB,gDACpB,WAAW,SACI;CACf,MAAM,kBAAkB;EACtB,SAAS,yBAAyB,QAAQ;EAC1C,YAAY;EACZ,aAAa;EACb,UAAU;EACV,OAAO;CACT,CAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-discount-C3jfysK-.js","names":[],"sources":["../src/lib/copilot-discount.ts"],"sourcesContent":["/**\n * Approximate discounted USD for a session, from static per-model discount\n * factors applied to the AIC ledger's billed nano-AIU.\n *\n * Background: GitHub's portal lists per-token rates, but the spend dashboard\n * bills several models well below portal (gpt-5.6-sol ≈ 0.28x, the Opus /\n * Sonnet / Codex cluster ≈ 0.6x, gemini-3.7-flash ≈ 0.29x since Sep 2026),\n * while Luna bills long-context portal tiers and Grok / 3.8-flash bill\n * portal-default exactly. No uniform per-lab factor exists (verified across\n * 28d / MTD / 7d / daily windows), so each model carries its own factor.\n *\n * The factors scale NANO-AIU, not tokens × portal rates: nano is already\n * tier-correct upstream (long-context tiers, cache writes), so no tier\n * engine or portal-rate table is needed here. Displayed total is capped:\n * `min(factored, totalCredits × $0.01)` — the cap can only ever lower the\n * number (all factors ≤ 1), so a typo like 2.8-instead-of-0.28 degrades to\n * the unfactored total rather than overstating spend.\n *\n * Staleness: rates move (3.7-flash flipped 1.00x → 0.29x overnight once\n * already). Re-derive monthly from the portal + spend dashboard; drift\n * degrades to cap-bound display, never to overstatement.\n */\n\nimport type { AicSnapshot } from \"./aic-ledger\"\nimport { aicTotalCredits } from \"./aic-ledger\"\n\n/** USD value of one AI credit (GitHub's published conversion). */\nexport const USD_PER_AIC_CREDIT = 0.01\n\nexport interface DiscountFactorRow {\n /** Multiply nano-implied USD by this. */\n factor: number\n /** Why this value: which snapshot window(s) it was derived from. */\n source: string\n}\n\nfunction row(factor: number, source: string): DiscountFactorRow {\n return { factor, source }\n}\n\n/**\n * Static per-model discount factors, keyed by resolved (Copilot-side) model\n * id — the same key the ledger's `perModel` uses. Derived Sep 2026 from the\n * 28d / MTD / 7d / daily spend-dashboard windows vs portal rates.\n */\nexport const DISCOUNT_FACTORS: Readonly<Record<string, DiscountFactorRow>> =\n Object.freeze({\n \"gpt-6-sol\": row(0.28, \"carried from gpt-5.6-sol; re-derive on refresh\"),\n \"gpt-5.6-sol\": row(0.28, \"0.27-0.29 across 28d/MTD/7d/pre/9-9; write-mix refuted\"),\n \"claude-opus-5.5\": row(0.62, \"carried from opus-5; re-derive on refresh\"),\n \"claude-opus-5\": row(0.62, \"0.61-0.64 across windows; 9/7 1.02 excluded as single-day artifact\"),\n \"claude-sonnet-5\": row(0.66, \"0.62-0.71 across windows\"),\n \"gpt-5.3-codex\": row(0.60, \"0.59-0.62 across windows\"),\n \"gpt-5.4\": row(0.60, \"single snapshot 0.598\"),\n // Regime break: billed 1.00x pre-Sep, 0.29x since. Recheck FIRST at\n // every refresh — likeliest row to have moved again.\n \"gemini-3.7-flash\": row(0.29, \"September regime; pre-Sep 1.00x — volatile\"),\n // No discount: Luna's heat is long-context tiers + ~2% cache writes\n // (both already in nano); Grok / 3.8-flash bill portal-default exactly.\n \"gpt-6-luna\": row(1.0, \"carried from gpt-5.6-luna; re-derive on refresh\"),\n \"gpt-5.6-luna\": row(1.0, \"long-tier portal + writes, no discount\"),\n \"grok-4.6\": row(1.0, \"portal default, six windows\"),\n \"gemini-3.8-flash\": row(1.0, \"portal exact, six windows to the dollar\"),\n })\n\n/** Discount factor for a model id; 1.0 (no discount) when unlisted. */\nexport function discountFactorFor(modelId: string): number {\n return sanitizeFactor(DISCOUNT_FACTORS[modelId]?.factor)\n}\n\n/**\n * Clamp a factor to usable range. Non-finite or negative factors (corrupt\n * table edit, bad injection) degrade to 1.0 — unfactored but never NaN,\n * never negative on screen.\n */\nfunction sanitizeFactor(raw: unknown): number {\n return typeof raw === \"number\" && Number.isFinite(raw) && raw >= 0 ? raw : 1.0\n}\n\nexport interface DiscountedUsd {\n /** Capped total actually displayed (`~$`). */\n total: number\n /** Per-model factored USD, scaled to the capped total when the cap binds. */\n byModel: Record<string, number>\n /** True when the cap (not the factors) decided the total. */\n capped: boolean\n}\n\n/**\n * Session discounted USD from a ledger snapshot. Total function: never\n * throws (guards non-finite/negative ledger values defensively — a corrupt\n * snapshot must degrade the status line, not crash the hook).\n */\nexport function discountedUsdForSnapshot(snapshot: AicSnapshot): DiscountedUsd {\n return discountedUsdWithFactors(snapshot, DISCOUNT_FACTORS)\n}\n\n/**\n * Factor-injectable core (exported for unit tests — e.g. proving a\n * fat-finger factor can never overstate spend). `factors` falls back to\n * 1.0 per model exactly like the table lookup.\n */\nexport function discountedUsdWithFactors(\n snapshot: AicSnapshot,\n factors: Readonly<Record<string, DiscountFactorRow>>,\n): DiscountedUsd {\n const byModel: Record<string, number> = {}\n let sum = 0\n for (const [model, entry] of Object.entries(snapshot.perModel)) {\n const nano =\n typeof entry.nanoAiu === \"number\" && Number.isFinite(entry.nanoAiu)\n ? Math.max(0, entry.nanoAiu)\n : 0\n const factor = sanitizeFactor(factors[model]?.factor)\n const usd = (nano / 1_000_000_000) * USD_PER_AIC_CREDIT * factor\n byModel[model] = usd\n sum += usd\n }\n const cap = aicTotalCredits(snapshot) * USD_PER_AIC_CREDIT\n // Relative epsilon: per-model float summation can exceed the cap by a\n // final-ulp hair without any factor being wrong — only bind on a real gap.\n if (!(sum > cap * (1 + 1e-9)) || sum <= 0) {\n return { total: sum, byModel, capped: false }\n }\n // Cap binds (fat-finger factor, volatile row, unknown-model overstatement):\n // scale rows down proportionally so the table still sums to its Total.\n const scale = cap / sum\n const scaled: Record<string, number> = {}\n for (const [model, usd] of Object.entries(byModel)) {\n scaled[model] = usd * scale\n }\n return { total: cap, byModel: scaled, capped: true }\n}\n\n/** Format table dollars: always cents (`~$` added by callers that want it). */\nexport function formatTableUsd(usd: number): string {\n return usd.toFixed(2)\n}\n\ninterface CostTableRow {\n model: string\n uncached: number\n cached: number\n writes: number\n output: number\n usd: number\n}\n\n/**\n * Beautiful per-model session cost table (plain text, no ANSI — it lands on\n * stderr / logs). Columns mirror the spend dashboard: Uncached / Cached /\n * [Write] / Cache% / Output / $. The Write column appears only when the\n * session actually wrote cache. `Cache% = cache_read / (cache_read + input)`;\n * writes are excluded (they are new tokens, not hits).\n */\nexport function formatDiscountedCostTable(\n snapshot: AicSnapshot,\n discounted: DiscountedUsd,\n): string {\n const tokens = snapshot.tokensByModel ?? {}\n const models = new Set([...Object.keys(snapshot.perModel), ...Object.keys(tokens)])\n const rows: Array<CostTableRow> = []\n for (const model of models) {\n const t = tokens[model]\n rows.push({\n model,\n uncached: t?.input ?? 0,\n cached: t?.cache_read ?? 0,\n writes: t?.cache_write ?? 0,\n output: t?.output ?? 0,\n usd: discounted.byModel[model] ?? 0,\n })\n }\n if (rows.length === 0) return \"\"\n rows.sort((a, b) => b.usd - a.usd || a.model.localeCompare(b.model))\n\n const showWrites = rows.some((r) => r.writes > 0)\n const cachePct = (cached: number, uncached: number): string => {\n const denom = cached + uncached\n if (denom <= 0) return \"—\"\n return `${((cached / denom) * 100).toFixed(1)}%`\n }\n\n type Cell = { text: string; align: \"left\" | \"right\" }\n const header: Array<Cell> = [\n { text: \"Model\", align: \"left\" },\n { text: \"Uncached\", align: \"right\" },\n { text: \"Cached\", align: \"right\" },\n ]\n if (showWrites) header.push({ text: \"Write\", align: \"right\" })\n header.push(\n { text: \"Cache%\", align: \"right\" },\n { text: \"Output\", align: \"right\" },\n { text: \"$\", align: \"right\" },\n )\n\n const body: Array<Array<Cell>> = rows.map((r) => {\n const cells: Array<Cell> = [\n { text: r.model, align: \"left\" },\n { text: formatCount(r.uncached), align: \"right\" },\n { text: formatCount(r.cached), align: \"right\" },\n ]\n if (showWrites) cells.push({ text: formatCount(r.writes), align: \"right\" })\n cells.push(\n { text: cachePct(r.cached, r.uncached), align: \"right\" },\n { text: formatCount(r.output), align: \"right\" },\n { text: `~$${formatTableUsd(r.usd)}`, align: \"right\" },\n )\n return cells\n })\n\n const totalUncached = rows.reduce((n, r) => n + r.uncached, 0)\n const totalCached = rows.reduce((n, r) => n + r.cached, 0)\n const totalWrites = rows.reduce((n, r) => n + r.writes, 0)\n const totalOutput = rows.reduce((n, r) => n + r.output, 0)\n const totalCells: Array<Cell> = [\n { text: \"Total\", align: \"left\" },\n { text: formatCount(totalUncached), align: \"right\" },\n { text: formatCount(totalCached), align: \"right\" },\n ]\n if (showWrites) {\n totalCells.push({ text: formatCount(totalWrites), align: \"right\" })\n }\n totalCells.push(\n { text: cachePct(totalCached, totalUncached), align: \"right\" },\n { text: formatCount(totalOutput), align: \"right\" },\n { text: `~$${formatTableUsd(discounted.total)}`, align: \"right\" },\n )\n\n const widths = header.map((h, i) => {\n let w = h.text.length\n for (const row of [...body, totalCells]) {\n w = Math.max(w, row[i].text.length)\n }\n return w\n })\n const render = (cells: Array<Cell>): string =>\n cells\n .map((c, i) =>\n c.align === \"left\" ? c.text.padEnd(widths[i]) : c.text.padStart(widths[i]),\n )\n .join(\" \")\n const lines = [\n \"Session cost (discounted actuals, ~$):\",\n render(header),\n ...body.map(render),\n render(totalCells),\n ]\n return lines.join(\"\\n\")\n}\n\n/** Compact count for table cells: `999` → `999`, `15234` → `15.2k`. */\nfunction formatCount(n: number): string {\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`\n if (n >= 1000) return `${(n / 1000).toFixed(1)}k`\n return `${n}`\n}\n"],"mappings":";;;AA2BA,MAAa,qBAAqB;AASlC,SAAS,IAAI,QAAgB,QAAmC;CAC9D,OAAO;EAAE;EAAQ;CAAO;AAC1B;;;;;;AAOA,MAAa,mBACX,OAAO,OAAO;CACZ,aAAa,IAAI,KAAM,gDAAgD;CACvE,eAAe,IAAI,KAAM,wDAAwD;CACjF,mBAAmB,IAAI,KAAM,2CAA2C;CACxE,iBAAiB,IAAI,KAAM,oEAAoE;CAC/F,mBAAmB,IAAI,KAAM,0BAA0B;CACvD,iBAAiB,IAAI,IAAM,0BAA0B;CACrD,WAAW,IAAI,IAAM,uBAAuB;CAG5C,oBAAoB,IAAI,KAAM,4CAA4C;CAG1E,cAAc,IAAI,GAAK,iDAAiD;CACxE,gBAAgB,IAAI,GAAK,wCAAwC;CACjE,YAAY,IAAI,GAAK,6BAA6B;CAClD,oBAAoB,IAAI,GAAK,yCAAyC;AACxE,CAAC;;;;;;AAYH,SAAS,eAAe,KAAsB;CAC5C,OAAO,OAAO,QAAQ,YAAY,OAAO,SAAS,GAAG,KAAK,OAAO,IAAI,MAAM;AAC7E;;;;;;AAgBA,SAAgB,yBAAyB,UAAsC;CAC7E,OAAO,yBAAyB,UAAU,gBAAgB;AAC5D;;;;;;AAOA,SAAgB,yBACd,UACA,SACe;CACf,MAAM,UAAkC,CAAC;CACzC,IAAI,MAAM;CACV,KAAK,MAAM,CAAC,OAAO,UAAU,OAAO,QAAQ,SAAS,QAAQ,GAAG;EAC9D,MAAM,OACJ,OAAO,MAAM,YAAY,YAAY,OAAO,SAAS,MAAM,OAAO,IAC9D,KAAK,IAAI,GAAG,MAAM,OAAO,IACzB;EACN,MAAM,SAAS,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ompt-submit-B9MJxc3K.js","names":[],"sources":["../src/internal-prompt-submit.ts"],"sourcesContent":["/**\n * The internal `internal-prompt-submit` subcommand: the executable a spawned\n * Claude Code session's `UserPromptSubmit` hook invokes (registered into the\n * mirrored settings.json by the launcher). It serves the front-end of the\n * floor-raising surface on one event:\n * 1. resets the Stop-gate's per-session block budget (making `maxBlocks`\n * per-prompt);\n * 2. stashes the prompt + surfaces the prior turn's advisory review findings;\n * 3. for a non-trivial prompt, injects a GROUNDED, user-derived scope/goal\n * note (one gpt-6-luna call at high effort over the prompt + grounding\n * code search — local ColBERT when --search is on, Bluebird when\n * --bluebird is on, lexical-only otherwise) — or, when the proxy URL/nonce\n * isn't wired or anything errors,\n * falls open to the v1 regex goal.\n * 4. on a cheapest-profile launch only, tries FIRST a Sol (gpt-5.6-sol,\n * medium) rewrite of the prompt into a short structured EXECUTION BRIEF over\n * the prompt + AGENTS.md/CLAUDE.md + repo structure + ecosystem's verify\n * command + grounding search\n * (adaptive 3 turns, up to 5 on Sol's deep-grounding flag) — additive,\n * never replacing the user prompt — and falls back to (3) on any miss.\n * One-shot per session (first non-trivial prompt only, marked on\n * attempt even if Sol fails open). Opt out with\n * GH_ROUTER_DISABLE_CHEAPEST_REWRITE=1.\n *\n * ALWAYS exits 0 (never blocks the prompt): the steer is additive context, and a\n * UserPromptSubmit hook that exit-2'd would refuse the user's prompt. The pure\n * v1 path (`decidePromptSubmit`) is the fail-open fallback; V2\n * (`decidePromptSubmitV2`) layers the grounded enrichment on top via injected IO.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { readFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport {\n CHEAPEST_REWRITE_EFFORT,\n CHEAPEST_REWRITE_MODEL,\n isCheapestRewriteDisabledEnv,\n} from \"./lib/cheapest-prompt-rewrite\"\nimport { parseBoolEnv } from \"./lib/exec\"\n// The verify-command ladder moved to `lib/static-context-pack` so the\n// server-side `prompt_brief` tool shares one implementation with this hook.\n// Re-exported because `internal-rebrief` and the buildStaticPack suites still\n// import it from this module.\nexport { buildStaticPack } from \"./lib/static-context-pack\"\nimport { buildStaticPack } from \"./lib/static-context-pack\"\nimport { callInference, callMcpTool, hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport { fileBlockBudget } from \"./lib/orchestration/stop-gate-hook\"\nimport {\n decidePromptSubmit,\n decidePromptSubmitV2,\n type PromptSubmitDecision,\n} from \"./lib/orchestration/prompt-submit-hook\"\nimport {\n fileFindingsStore,\n fileLastPromptStore,\n fileRebriefBindingStore,\n fileRewriteFlagStore,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\n\n/**\n * Read the hook payload from stdin SYNCHRONOUSLY (`readFileSync(0)`). An async\n * stdin read leaves an in-flight libuv FS request that, on Windows, races the\n * process teardown and trips a `uv_async_send` assertion; a synchronous read has\n * no such handle. Hooks always receive piped/redirected stdin, so this never\n * blocks (guarded against an interactive TTY, and any error -> \"\").\n */\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\n/** Parse the session cwd from the payload — the workspace the grounding search\n * runs in. Falls back to the process cwd. */\nfunction workspaceFromStdin(stdin: string): string {\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const cwd = (p as { cwd?: unknown }).cwd\n if (typeof cwd === \"string\" && cwd.length > 0) return cwd\n }\n } catch {\n /* fall through */\n }\n return process.cwd()\n}\n\n/** Per-call timeout for the grounding search (short — it must not stall the prompt). */\nconst SEARCH_TIMEOUT_MS = 8_000\n/** Per-call timeout for a single Sol/Luna inference. */\nconst INFER_TIMEOUT_MS = 25_000\n/**\n * Overall budget for the cheapest Sol rewrite (search + Sol, 3 turns default\n * with one adaptive extension to 5). The hook is registered with a 90s host\n * timeout. A rewrite timeout is TERMINAL — the orchestrator falls open to the\n * cheap regex goal and does NOT then run the Luna scope path — so the worst\n * case is one rewrite (≤30s) OR one Luna scope (≤22s), never both.\n */\nconst REWRITE_TIMEOUT_MS = 30_000\n\n\nexport const internalPromptSubmit = defineCommand({\n meta: {\n name: \"internal-prompt-submit\",\n description:\n \"Internal: the UserPromptSubmit hook. Resets the Stop-gate per-prompt block \"\n + \"budget, surfaces prior-turn review findings, and injects a grounded advisory goal \"\n + \"for non-trivial prompts. Always exit 0.\",\n },\n async run() {\n try {\n const stdin = readStdin()\n const steerEnabled = parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROMPT_STEER) !== true\n // Search capability for tip/enrichment text. The launcher exports\n // GH_ROUTER_SEARCH_ENABLED (\"1\"/\"0\") from its resolved\n // `state.searchEnabled` before spawning the session, so this\n // short-lived hook process inherits the launch's capability even when\n // the opt-in came from the `--search` CLI flag (which otherwise would\n // not survive the process boundary). Falls back to the raw opt-in env\n // for standalone invocations.\n const searchEnabled = process.env.GH_ROUTER_SEARCH_ENABLED !== undefined\n ? process.env.GH_ROUTER_SEARCH_ENABLED === \"1\"\n : process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === \"1\"\n const bluebirdEnabled = process.env.GH_ROUTER_BLUEBIRD_ENABLED === \"1\"\n const runtime = hookMcpRuntimeFromEnv()\n\n let decision: PromptSubmitDecision\n if (runtime) {\n const workspace = workspaceFromStdin(stdin)\n // Cheapest-only Sol rewrite identity: the launcher exports\n // GH_ROUTER_PROFILE; only the literal \"cheapest\" alias enables the\n // rewrite branch (checked again inside decidePromptSubmitV2).\n const profile = (process.env.GH_ROUTER_PROFILE ?? \"\").trim().toLowerCase()\n const rewriteDisabled = isCheapestRewriteDisabledEnv()\n decision = await decidePromptSubmitV2({\n stdin,\n steerEnabled,\n searchEnabled,\n bluebirdEnabled,\n profile,\n rewriteDisabled,\n rewrite: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n inferSol: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: CHEAPEST_REWRITE_MODEL,\n instructions: system,\n input: user,\n effort: CHEAPEST_REWRITE_EFFORT,\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n // Lazy: fs reads run only when the cheapest branch actually fires.\n staticPack: async () => buildStaticPack(workspace),\n // Session-keyed one-shot flag: first non-trivial prompt per\n // session spends the rewrite; later prompts use the Luna path.\n hasRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).hasRun(sid),\n markRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).markRun(sid),\n timeoutMs: REWRITE_TIMEOUT_MS,\n },\n io: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n infer: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: \"gpt-6-luna\",\n instructions: system,\n input: user,\n effort: \"high\",\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n readFindings: (sid) => fileFindingsStore(stopReviewStateDir()).read(sid),\n clearFindings: (sid) => fileFindingsStore(stopReviewStateDir()).clear(sid),\n storePrompt: (sid, prompt) => fileLastPromptStore(stopReviewStateDir()).write(sid, prompt),\n },\n })\n } else {\n // Proxy URL/nonce not wired -> the LLM layer is off; use the pure v1 path.\n decision = decidePromptSubmit({ stdin, steerEnabled })\n }\n\n // Per-workspace rebrief binding: the only way skill-spawned\n // internal-rebrief (no hook stdin) can locate the live transcript, the\n // session id (for findings), and the stored prompt. Refreshed on EVERY\n // prompt so it always tracks the current session, surviving /resume and\n // /clear within the session (same cwd key).\n try {\n const parsed = JSON.parse(stdin) as Record<string, unknown>\n const sid = typeof parsed.session_id === \"string\" ? parsed.session_id : \"\"\n const tp = typeof parsed.transcript_path === \"string\" ? parsed.transcript_path : \"\"\n if (sid && tp) {\n const ws = workspaceFromStdin(stdin)\n await fileRebriefBindingStore(stopReviewStateDir()).write({\n sessionId: sid,\n transcriptPath: tp,\n cwd: ws,\n atMs: Date.now(),\n }).catch(() => {})\n }\n } catch {\n /* binding refresh is best-effort */\n }\n\n if (decision.resetSession) {\n // Same budget store the Stop hook uses, so a new prompt clears its count.\n await fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\"))\n .reset(decision.resetSession)\n .catch(() => {})\n }\n if (decision.inject.length > 0) {\n await new Promise<void>((resolve) => process.stdout.write(`${decision.inject}\\n`, () => resolve()))\n }\n } catch {\n /* never let the front-end hook disrupt a prompt */\n }\n // Natural exit (exit code 0): a hard process.exit() races libuv stdio teardown\n // on Windows. No handles are kept alive once the (aborted) enrichment settles,\n // so returning lets the process exit cleanly with code 0.\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,SAAS,mBAAmB,OAAuB;CACjD,IAAI;EACF,MAAM,IAAa,KAAK,MAAM,KAAK;EACnC,IAAI,KAAK,OAAO,MAAM,UAAU;GAC9B,MAAM,MAAO,EAAwB;GACrC,IAAI,OAAO,QAAQ,YAAY,IAAI,SAAS,GAAG,OAAO;EACxD;CACF,QAAQ,CAER;CACA,OAAO,QAAQ,IAAI;AACrB;;AAGA,MAAM,oBAAoB;;AAE1B,MAAM,mBAAmB;;;;;;;;AAQzB,MAAM,qBAAqB;AAG3B,MAAa,uBAAuB,cAAc;CAChD,MAAM;EACJ,MAAM;EACN,aACE;CAGJ;CACA,MAAM,MAAM;EACV,IAAI;GACF,MAAM,QAAQ,UA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rief-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 {\n buildDoneDigest,\n buildRebriefContext,\n REBRIEF_MAX_TAIL_LINES,\n} from \"./lib/cheapest-rebrief-context\"\nimport {\n buildRebriefSystem,\n CHEAPEST_REWRITE_EFFORT,\n CHEAPEST_REWRITE_MODEL,\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-only gate (literal alias, lowercased). Exported for tests. */\nexport function isRebriefProfileEligible(profile: string | undefined): boolean {\n return (profile ?? \"\").trim().toLowerCase() === \"cheapest\"\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: CHEAPEST_REWRITE_MODEL,\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,K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EDCsR.js","names":[],"sources":["../src/lib/model-suffix.ts","../src/lib/fast-endpoint.ts","../src/lib/max-profile-prompts.ts","../src/lib/max-profile-contract.ts"],"sourcesContent":["/**\n * Normalize Claude Code's local 1M-context decoration at model boundaries.\n *\n * `[1m]` is a client-side accounting marker, not part of a Copilot catalog id.\n * Claude Code can append its own marker to a picker value that is already\n * decorated by the router, producing a reachable doubled suffix. Keep the\n * helper dependency-free so launch/profile code and request preprocessing use\n * exactly the same trailing-suffix rule without an import cycle.\n */\nexport interface TrailingOneMSuffix {\n base: string\n hadSuffix: boolean\n}\n\n/** Strip every trailing `[1m]` marker, case-insensitively. */\nexport function stripTrailingOneMSuffix(id: string): TrailingOneMSuffix {\n const match = id.match(/(?:\\[1m\\])+$/i)\n if (!match || match.index === undefined) {\n return { base: id, hadSuffix: false }\n }\n return { base: id.slice(0, match.index), hadSuffix: true }\n}\n\n/** Reapply at most one canonical `[1m]` marker when the input had one. */\nexport function normalizeTrailingOneMSuffix(id: string): string {\n const { base, hadSuffix } = stripTrailingOneMSuffix(id)\n return hadSuffix ? `${base}[1m]` : base\n}\n\n/** Append one marker without ever creating a doubled suffix. */\nexport function withTrailingOneMSuffix(id: string): string {\n const { base } = stripTrailingOneMSuffix(id)\n return `${base}[1m]`\n}\n","import type { Model } from \"~/services/copilot/get-models\"\n\n// Fast endpoint policy is intentionally kept separate from the standard\n// pickEndpoint() resolver. See fastEndpointRequirement below.\n\n/** Endpoint clients used by the fast profile's fixed roster. */\nexport type FastEndpoint = \"chat\" | \"responses\" | \"messages\"\n\nconst ENDPOINTS: Readonly<Record<FastEndpoint, ReadonlySet<string>>> = {\n chat: new Set([\"/chat/completions\", \"/v1/chat/completions\"]),\n responses: new Set([\"/responses\", \"/v1/responses\"]),\n messages: new Set([\"/messages\", \"/v1/messages\"]),\n}\n\n/**\n * Return the endpoint mandated by a fast-profile roster model.\n *\n * This is intentionally independent of the standard `pickEndpoint`: that\n * resolver prefers chat when a catalog entry advertises both clients, while\n * fast roles have a fixed provider contract. Gemini stays on chat; Luna, Sol,\n * and Grok stay on Responses; the Opus Oracle stays on native Messages.\n * Unknown ids return undefined so a fast caller cannot guess a transport.\n */\nexport function fastEndpointRequirement(modelId: string): FastEndpoint | undefined {\n const id = modelId.replace(/(?:\\[1m\\])+$/i, \"\")\n if (id === \"gemini-3.8-flash\") return \"chat\"\n if (id === \"gpt-6-luna\" || id === \"gpt-5.6-luna\" || id === \"gpt-6-sol\" || id === \"gpt-5.6-sol\" || id === \"grok-4.6\" || id === \"gpt-6-astra\") {\n return \"responses\"\n }\n if (id === \"claude-opus-5.5\" || id === \"claude-opus-5-5\" || id === \"claude-opus-5.5\" || id === \"claude-sonnet-5\") return \"messages\"\n return undefined\n}\n\n/**\n * Resolve the fixed fast transport only when the catalog explicitly advertises\n * the required endpoint. An entry that advertises both still resolves to the\n * policy endpoint, regardless of advertisement order.\n */\nexport function advertisesEndpoint(\n model: Model | undefined,\n endpoint: FastEndpoint,\n): boolean {\n const advertised = model?.supported_endpoints\n return Array.isArray(advertised)\n && advertised.some((value) => ENDPOINTS[endpoint].has(value))\n}\n\nexport function fastEndpointForModel(model: Model): FastEndpoint | undefined {\n const required = fastEndpointRequirement(model.id)\n if (!required) return undefined\n return advertisesEndpoint(model, required) ? required : undefined\n}\n\n/** Resolve a fast endpoint from a catalog id, without selecting a fallback. */\nexport function fastEndpointForCatalogId(\n modelId: string,\n catalog: ReadonlyArray<Model> | undefined,\n): FastEndpoint | undefined {\n const found = catalog?.find((model) => model.id === modelId)\n return found ? fastEndpointForModel(found) : undefined\n}\n\n/** Human-readable endpoint name for prerequisite diagnostics. */\nexport function fastEndpointLabel(endpoint: FastEndpoint): string {\n return endpoint === \"chat\"\n ? \"Chat Completions\"\n : endpoint === \"responses\"\n ? \"Responses\"\n : \"Messages\"\n}\n","import type { Effort } from \"./reasoning-effort\"\n\nexport const MAX_PARALLELISM_RULE =\n \"When two or more delegated workstreams are independent and non-overlapping, issue them together; sequence them when one needs another's result or their side effects can conflict.\"\n\nexport type MaxNativePromptRole =\n | \"Explore\"\n | \"Plan\"\n | \"general-purpose\"\n | \"implementer\"\n | \"reviewer\"\n | \"brainstorm\"\n\ninterface MaxNativePromptSpec {\n capability: string\n useWhen: string\n notFor: string\n returns: string\n prompt: string\n}\n\nconst MAX_NATIVE_PROMPT_SPECS: Record<MaxNativePromptRole, MaxNativePromptSpec> = {\n Explore: {\n capability: \"read-oriented repository exploration\",\n useWhen: \"the answer requires broad, multi-file or multi-source discovery and the caller needs conclusions rather than raw context\",\n notFor: \"a narrow lookup, implementation planning, or editing\",\n returns: \"concise conclusions, load-bearing file:line evidence, checks or sources consulted, and explicit gaps\",\n prompt: \"Explore the supplied question across the actual repository. Stay within discovery: do not plan the implementation or modify files. Return concise conclusions, load-bearing file:line evidence, checks or sources consulted, and explicit gaps. Stop when the question is supported or the missing evidence is identified. You do not have Advisor or native-agent delegation tools.\",\n },\n Plan: {\n capability: \"implementation planning\",\n useWhen: \"a non-trivial change crosses interfaces, has dependency or migration ordering, preserves important invariants, or needs explicit acceptance criteria\",\n notFor: \"routine decomposition, implementation, approval, or silently deciding unresolved product choices\",\n returns: \"affected files or symbols, ordered implementation slices, invariants, risks, open decisions, acceptance criteria, and runnable verification\",\n prompt: \"Turn the supplied goal, constraints, and evidence into an actionable implementation plan. Return affected files or symbols, ordered implementation slices with real dependencies identified, invariants, risks, open decisions, acceptance criteria, and runnable verification. Surface unresolved product or architecture choices instead of deciding them silently. Stop when another agent can implement the plan without rediscovering its structure; the lead owns acceptance and execution. You do not have Advisor or native-agent delegation tools.\",\n },\n \"general-purpose\": {\n capability: \"bounded mixed investigation and execution\",\n useWhen: \"one owner should carry a multi-step outcome across several narrower kinds of work\",\n notFor: \"a narrow direct action or a task cleanly owned by one specialist\",\n returns: \"the requested outcome, changed artifacts, verification evidence, blockers, and residual risks\",\n prompt: \"Own the supplied bounded outcome end to end. Return the requested outcome, changed artifacts, verification evidence, blockers, and residual risks. Stop at the requested scope and do not absorb adjacent cleanup. Do not re-delegate the core assignment merely to repeat it; any supporting delegation must be independent, non-overlapping, and integrated and verified by you.\",\n },\n implementer: {\n capability: \"bounded coding implementation\",\n useWhen: \"the desired behavior and constraints are settled but the implementation still needs coding judgment\",\n notFor: \"unresolved product behavior, architecture choices, or an unbounded investigation\",\n returns: \"a coherent scoped change, files changed, observable behavior, checks and results, blockers, and unresolved risks\",\n prompt: \"Implement the settled desired behavior within the supplied scope and repository conventions. Return the files changed, observable behavior, checks and results, blockers, and unresolved risks. Stop and report when ambiguity would materially change product behavior, architecture, or scope. Do not re-delegate the core assignment merely to repeat it; any supporting delegation must be independent, non-overlapping, and integrated and verified by you.\",\n },\n reviewer: {\n capability: \"repository-aware verification and reproduction\",\n useWhen: \"an implementation or failure already exists and assessment requires repository navigation, commands, tests, or runtime evidence\",\n notFor: \"a stateless review of an already self-contained artifact or authoring the fix\",\n returns: \"a calibrated verdict, severity-ranked findings, file:line evidence, concrete failure scenarios, checks and results, and unverified areas\",\n prompt: \"Assess the supplied artifact against its intent and the actual repository or runtime state. Return a calibrated verdict, severity-ranked findings, file:line evidence, concrete failure scenarios, checks and results, and unverified areas. Distinguish no findings from checks not run. Do not modify files or act as an approval gate. Stop when material claims have been tested to the available extent; the lead owns remediation and go/no-go. You do not have Advisor or native-agent delegation tools.\",\n },\n brainstorm: {\n capability: \"divergent repository-feasible option generation\",\n useWhen: \"materially different approaches remain credible before implementation planning\",\n notFor: \"a settled approach, proven fact, implementation plan, or code change\",\n returns: \"distinct options, trade-offs, assumptions, failure modes, discriminating evidence, and a recommendation only when supported\",\n prompt: \"Explore the useful design space for the supplied open decision. Return materially distinct repository-feasible options, trade-offs, assumptions, failure modes, discriminating evidence, and a recommendation only when the available evidence supports one. Do not turn the result into an implementation plan or modify files. Stop once the useful alternatives are covered or one option clearly dominates; the lead owns the decision. You do not have Advisor or native-agent delegation tools.\",\n },\n}\n\nexport function maxNativeDescription(\n role: MaxNativePromptRole,\n model: string,\n effort: Effort,\n): string {\n const spec = MAX_NATIVE_PROMPT_SPECS[role]\n return `Max-profile ${spec.capability} subagent running ${model} at ${effort} effort. Use when: ${spec.useWhen}. Not for: ${spec.notFor}. Returns: ${spec.returns}.`\n}\n\nexport function maxNativePrompt(role: MaxNativePromptRole): string {\n return MAX_NATIVE_PROMPT_SPECS[role].prompt\n}\n\nexport const MAX_COORDINATOR_DESCRIPTION =\n \"Max-profile peer-review coordinator running gpt-6-luna at maximum effort. Use when: a consequential self-contained plan, design, or diff has at least two distinct unresolved risk lenses for which independent fresh-context review could change the decision. Not for: routine second opinions, repository exploration or execution, facts a focused check can settle, or repeating one generic review across models. Returns: a provenance-preserving synthesis of material findings, disagreements, evidence gaps, and the cheapest checks that can settle them.\"\n\nexport const MAX_COORDINATOR_PROMPT =\n `Coordinate independent fresh-context review of the self-contained artifact and constraints supplied by the caller. You have peer tools only and cannot inspect the repository, transcript, or runtime, so identify missing material instead of guessing. Select the smallest sufficient peer set: use one peer when one lens is enough, and multiple peers only for distinct unresolved risk dimensions. Give every peer a non-overlapping lens; do not send one generic brief to several models or duplicate a same-family lens as a vote. ${MAX_PARALLELISM_RULE} Deduplicate findings while preserving provenance and genuine disagreement. Return severity-ranked material findings, concrete failure scenarios, confidence, evidence gaps, and the cheapest repository check or test that can settle each disagreement. Do not count votes or issue an evidence-free approval. Peer output is advisory; the lead owns go/no-go and remediation.`\n\nexport type MaxPeerKind = \"strategic critic\" | \"line-level reviewer\"\n\nexport interface MaxPeerPromptOptions {\n name: string\n model: string\n kind: MaxPeerKind\n lens: string\n useWhen: string\n notFor: string\n}\n\nexport function maxPeerDescription(opts: MaxPeerPromptOptions): string {\n return `Max-profile ${opts.kind} backed by ${opts.model}. Lens: ${opts.lens}. Use when: ${opts.useWhen}. Not for: ${opts.notFor}. Cold-start: it has no repository or transcript access and sees only the supplied prompt, context, and images. Returns: only material findings, or an explicit no material finding result.`\n}\n\nexport function maxPeerInstructions(opts: MaxPeerPromptOptions): string {\n const locationRule = opts.kind === \"line-level reviewer\"\n ? \"For each finding, cite a location from the supplied artifact, give severity and a concrete failure scenario, and suggest the smallest correction.\"\n : \"For each finding, identify the failed assumption or invariant, its consequence, and the cheapest evidence that would confirm or refute it.\"\n return `You are ${opts.name}, a fresh-context ${opts.kind} running on ${opts.model}. Apply this lens: ${opts.lens}. You have no repository or transcript access; use only the supplied artifact, constraints, and images. If material context is missing, identify it instead of guessing. ${locationRule} Treat supplied locations as citations to the artifact, not proof of repository state. Report only material findings; \"no material finding\" is a valid result. Stop when the requested lens is covered without padding or manufactured objections.`\n}\n\nexport const MAX_ADVISOR_TOOL_INSTRUCTIONS = `# Advisor Tool\n\nYou have access to an optional, primary-lead-only, transcript-aware Max Advisor. Transcript awareness makes it useful for detecting framing drift, changed assumptions, and a stuck strategy; it is not an independent repository verifier, supervisor, approver, workflow gate, or substitute for your own reasoning. You keep decision ownership.\n\nUse it for one precise consequential uncertainty that remains after proportionate direct investigation and cannot be settled by repository evidence, a focused command or test, Plan, reviewer, or a fresh-context peer. State the question, relevant evidence, credible alternatives, and what evidence would change the decision. Evidence-first does not require invoking every role before Advisor.\n\nDo not call it for initial investigation, routine progress, waiting, ordinary verification, planner approval, reviewer confirmation, reassurance, or completion ceremony. Treat its result as advice, not authority. Consult again only when materially new or conflicting evidence creates a different question.`\n\nexport const MAX_ADVISOR_SYSTEM_PROMPT =\n \"You are a non-binding, transcript-aware consultant to the primary lead. Answer the stated consequential question first, then give your recommendation and confidence, the transcript evidence and assumptions supporting it, the material risk, one credible alternative, and the evidence that would reverse your recommendation. The transcript may anchor you to the lead's framing, so identify any framing or assumption the session has stopped questioning. Stop after answering the focused question. Do not supervise, approve, veto, or redesign unrelated work; the lead weighs your advice against the user's intent and verified repository evidence.\"\n","import type { Model, ModelsResponse } from \"~/services/copilot/get-models\"\nimport type { Effort } from \"./reasoning-effort\"\nimport {\n advertisesEndpoint,\n fastEndpointForModel,\n} from \"./fast-endpoint\"\nimport { MAX_ADVISOR_TOOL_INSTRUCTIONS } from \"./max-profile-prompts\"\nimport { stripTrailingOneMSuffix } from \"./model-suffix\"\nimport { state } from \"./state\"\n\n// Max uses the same context threshold as Claude Code's `[1m]` accounting.\nexport const MAX_REQUIRED_CONTEXT_TOKENS = 1_000_000\n\nconst ONE_M_TOKENS = MAX_REQUIRED_CONTEXT_TOKENS\n\nfunction catalogModels(): Array<Model> {\n return state.models?.data ?? []\n}\n\nfunction catalogModel(id: string): Model | undefined {\n return catalogModels().find((model) => model.id === id)\n}\n\n\nexport const MAX_PROFILE_MODELS = Object.freeze({\n sol: \"gpt-5.6-sol\",\n luna: \"gpt-6-luna\",\n gemini: \"gemini-3.8-flash\",\n grok: \"grok-4.6\",\n opus: \"claude-opus-5.5\",\n sonnet: \"claude-sonnet-5\",\n codex: \"gpt-5.3-codex\",\n} as const)\n\nexport const MAX_PROFILE_NATIVE_AGENT_NAMES = [\n \"Explore\",\n \"Plan\",\n \"general-purpose\",\n \"implementer\",\n \"reviewer\",\n \"brainstorm\",\n \"peer-review-coordinator\",\n] as const\n\nexport type MaxProfileNativeAgentName =\n (typeof MAX_PROFILE_NATIVE_AGENT_NAMES)[number]\n\nexport const MAX_PROFILE_NATIVE_EFFORTS = Object.freeze({\n Explore: \"high\",\n Plan: \"high\",\n \"general-purpose\": \"max\",\n implementer: \"high\",\n reviewer: \"xhigh\",\n brainstorm: \"high\",\n \"peer-review-coordinator\": \"max\",\n} as const satisfies Record<MaxProfileNativeAgentName, Effort>)\n\n/** Default model family behind each native role's frontmatter. */\nexport const MAX_PROFILE_NATIVE_MODELS = Object.freeze({\n Explore: MAX_PROFILE_MODELS.luna,\n Plan: MAX_PROFILE_MODELS.sol,\n \"general-purpose\": MAX_PROFILE_MODELS.luna,\n implementer: MAX_PROFILE_MODELS.gemini,\n reviewer: MAX_PROFILE_MODELS.sonnet,\n brainstorm: MAX_PROFILE_MODELS.opus,\n \"peer-review-coordinator\": MAX_PROFILE_MODELS.luna,\n} as const satisfies Record<MaxProfileNativeAgentName, string>)\n\nexport const MAX_PROFILE_LEAD_MODEL = MAX_PROFILE_MODELS.sol\nexport const MAX_PROFILE_ADVISOR_MODEL = MAX_PROFILE_MODELS.opus\nexport const MAX_PROFILE_ADVISOR_EFFORT = \"high\" as const\nexport const MAX_PROFILE_ADVISOR_INSTRUCTIONS = MAX_ADVISOR_TOOL_INSTRUCTIONS\n\nexport function maxAdvisorModelFromPin(pinned: string | undefined, opusModel?: string): string {\n const trimmed = pinned?.trim()\n const base = trimmed ? stripTrailingOneMSuffix(trimmed).base : undefined\n if (base === MAX_PROFILE_MODELS.sol || base === \"gpt-6-sol\" || base === MAX_PROFILE_MODELS.opus) {\n return base\n }\n return opusModel ?? MAX_PROFILE_MODELS.opus\n}\n\nexport function maxAdvisorPinIsValid(pinned: string | undefined): boolean {\n const trimmed = pinned?.trim()\n const base = trimmed ? stripTrailingOneMSuffix(trimmed).base : trimmed\n return base === undefined\n || base === \"\"\n || base === MAX_PROFILE_MODELS.sol\n || base === \"gpt-6-sol\"\n || base === MAX_PROFILE_MODELS.opus\n}\n\nexport function maxAdvisorModelFromPinStrict(pinned: string | undefined, opusModel?: string): string {\n if (!maxAdvisorPinIsValid(pinned)) return opusModel ?? MAX_PROFILE_MODELS.opus\n return maxAdvisorModelFromPin(pinned, opusModel)\n}\n\nexport function maxStandInAvailable(): boolean {\n return usableSol(catalogModel(MAX_PROFILE_MODELS.sol))\n && maxOpusModel() !== undefined\n && (maxGrokHighModel() !== undefined || maxGeminiModel() !== undefined)\n}\nexport function maxAdvisorEffortForModel(_model: string): Effort {\n return MAX_PROFILE_ADVISOR_EFFORT\n}\n\nexport const MAX_PROFILE_NATIVE_MODEL_IDS = Object.freeze([\n MAX_PROFILE_MODELS.luna,\n MAX_PROFILE_MODELS.gemini,\n MAX_PROFILE_MODELS.grok,\n] as const)\n\nexport const MAX_PROFILE_ALLOWED_LEAD_MODEL_IDS = Object.freeze([\n MAX_PROFILE_MODELS.sol,\n \"gpt-6-sol\",\n MAX_PROFILE_MODELS.luna,\n MAX_PROFILE_MODELS.gemini,\n MAX_PROFILE_MODELS.opus,\n] as const)\n\nexport type MaxProfileAllowedLeadModel =\n (typeof MAX_PROFILE_ALLOWED_LEAD_MODEL_IDS)[number]\n\nexport interface MaxProfilePrerequisiteCheck {\n ok: boolean\n missing: ReadonlyArray<string>\n /** Resolved optional/third-lab assignments for the launch. */\n models: {\n sol?: Model\n luna?: Model\n gemini?: Model\n grok?: Model\n opus?: Model\n sonnet?: Model\n thirdLab?: \"gemini\" | \"grok\"\n }\n}\n\nfunction findModel(\n catalog: ModelsResponse | undefined,\n id: string,\n): Model | undefined {\n return catalog?.data?.find((model) => model.id === id)\n}\n\nfunction hasToolCalls(model: Model | undefined): boolean {\n return model?.capabilities?.supports?.tool_calls === true\n}\n\nfunction hasContextAtLeast(model: Model | undefined, tokens: number): boolean {\n return (model?.capabilities?.limits?.max_context_window_tokens ?? 0) >= tokens\n}\n\nfunction supportsEffort(model: Model | undefined, effort: Effort): boolean {\n const ladder = model?.capabilities?.supports?.reasoning_effort\n return Array.isArray(ladder) && ladder.includes(effort)\n}\n\nfunction hasUsableLimits(model: Model | undefined): boolean {\n const limits = model?.capabilities?.limits\n const prompt = limits?.max_prompt_tokens\n const output = limits?.max_output_tokens\n return (\n typeof prompt === \"number\"\n && Number.isFinite(prompt)\n && prompt > 0\n && typeof output === \"number\"\n && Number.isFinite(output)\n && output > 0\n && (limits?.max_context_window_tokens ?? 0) >= prompt\n )\n}\n\nfunction supportsEndpoint(\n model: Model | undefined,\n endpoint: \"chat\" | \"responses\" | \"messages\",\n): boolean {\n return model !== undefined && fastEndpointForModel(model) === endpoint\n}\n\nfunction validateRequiredModel(\n model: Model | undefined,\n id: string,\n requirements: ReadonlyArray<[string, boolean]>,\n missing: string[],\n): void {\n if (!model) {\n missing.push(`${id}: absent from the live catalog`)\n return\n }\n for (const [message, ok] of requirements) {\n if (!ok) missing.push(`${id}: ${message}`)\n }\n}\n\nfunction usableSol(model: Model | undefined): boolean {\n return Boolean(\n model\n && hasToolCalls(model)\n && hasContextAtLeast(model, ONE_M_TOKENS)\n && supportsEffort(model, \"high\")\n && supportsEndpoint(model, \"responses\")\n && hasUsableLimits(model)\n )\n}\n\nfunction usableGemini(model: Model | undefined): boolean {\n return Boolean(\n model\n && hasToolCalls(model)\n && hasContextAtLeast(model, ONE_M_TOKENS)\n && supportsEffort(model, \"high\")\n && supportsEndpoint(model, \"chat\")\n && hasUsableLimits(model),\n )\n}\n\nfunction usableGrok(model: Model | undefined): boolean {\n return Boolean(\n model\n && hasToolCalls(model)\n && supportsEffort(model, \"medium\")\n && supportsEndpoint(model, \"responses\")\n && hasUsableLimits(model),\n )\n}\n\nfunction usableGrokReviewer(model: Model | undefined): boolean {\n return Boolean(\n usableGrok(model)\n && supportsEffort(model, \"high\")\n && (model?.capabilities?.limits?.max_prompt_tokens ?? 0) >= 200_000,\n )\n}\n\n/**\n * Validate the fixed prerequisites for the raw `-m max` launch.\n *\n * Max is a deliberately strong, closed profile. Its lead, planning,\n * implementation, repository-review, brainstorm, and transcript-aware Advisor\n * paths must all be present before any runtime artifact is written: Sol, Luna,\n * Gemini 3.8 Flash, Sonnet 5, and Opus 5 are mandatory. Grok 4.6 is optional;\n * when present it supplies additional peer critic/reviewer coverage and the\n * preferred third-lab stand-in slot, but it is never a max lead and its sub-1M\n * context must remain undecorated.\n */\nexport function validateMaxProfilePrerequisites(\n catalog: ModelsResponse | undefined,\n): MaxProfilePrerequisiteCheck {\n const missing: string[] = []\n const sol = findModel(catalog, MAX_PROFILE_MODELS.sol)\n const luna = findModel(catalog, MAX_PROFILE_MODELS.luna)\n const gemini = findModel(catalog, MAX_PROFILE_MODELS.gemini)\n const grok = findModel(catalog, MAX_PROFILE_MODELS.grok)\n const opus = findModel(catalog, MAX_PROFILE_MODELS.opus)\n const sonnet = findModel(catalog, MAX_PROFILE_MODELS.sonnet)\n\n validateRequiredModel(\n sol,\n MAX_PROFILE_MODELS.sol,\n [\n [\"does not advertise tool_calls\", hasToolCalls(sol)],\n [\"advertised context window is below 1M\", hasContextAtLeast(sol, ONE_M_TOKENS)],\n [\"does not advertise a high reasoning effort\", supportsEffort(sol, \"high\")],\n [\"does not advertise a supported Responses endpoint\", supportsEndpoint(sol, \"responses\")],\n [\"has no usable max_prompt_tokens/max_output_tokens limits\", hasUsableLimits(sol)],\n ],\n missing,\n )\n validateRequiredModel(\n luna,\n MAX_PROFILE_MODELS.luna,\n [\n [\"does not advertise tool_calls\", hasToolCalls(luna)],\n [\"advertised context window is below 1M\", hasContextAtLeast(luna, ONE_M_TOKENS)],\n [\"does not advertise a high reasoning effort\", supportsEffort(luna, \"high\")],\n [\"does not advertise a max reasoning effort\", supportsEffort(luna, \"max\")],\n [\"does not advertise a supported Responses endpoint\", supportsEndpoint(luna, \"responses\")],\n [\"has no usable max_prompt_tokens/max_output_tokens limits\", hasUsableLimits(luna)],\n ],\n missing,\n )\n validateRequiredModel(\n gemini,\n MAX_PROFILE_MODELS.gemini,\n [\n [\"does not advertise tool_calls\", hasToolCalls(gemini)],\n [\"advertised context window is below 1M\", hasContextAtLeast(gemini, ONE_M_TOKENS)],\n [\"does not advertise a high reasoning effort\", supportsEffort(gemini, \"high\")],\n [\"does not advertise a supported Chat Completions endpoint\", supportsEndpoint(gemini, \"chat\")],\n [\"has no usable max_prompt_tokens/max_output_tokens limits\", hasUsableLimits(gemini)],\n ],\n missing,\n )\n validateRequiredModel(\n opus,\n MAX_PROFILE_MODELS.opus,\n [\n [\"does not advertise tool_calls\", hasToolCalls(opus)],\n [\"advertised context window is below 1M\", hasContextAtLeast(opus, ONE_M_TOKENS)],\n [\"does not advertise adaptive_thinking\", opus?.capabilities?.supports?.adaptive_thinking === true],\n [\"does not advertise a high reasoning effort\", supportsEffort(opus, \"high\")],\n [\"does not advertise a supported Messages endpoint\", supportsEndpoint(opus, \"messages\")],\n [\"has no usable max_prompt_tokens/max_output_tokens limits\", hasUsableLimits(opus)],\n ],\n missing,\n )\n validateRequiredModel(\n sonnet,\n MAX_PROFILE_MODELS.sonnet,\n [\n [\"does not advertise tool_calls\", hasToolCalls(sonnet)],\n [\"advertised context window is below 1M\", hasContextAtLeast(sonnet, ONE_M_TOKENS)],\n [\"does not advertise adaptive_thinking\", sonnet?.capabilities?.supports?.adaptive_thinking === true],\n [\"does not advertise an xhigh reasoning effort\", supportsEffort(sonnet, \"xhigh\")],\n [\"does not advertise a supported Messages endpoint\", supportsEndpoint(sonnet, \"messages\")],\n [\"has no usable max_prompt_tokens/max_output_tokens limits\", hasUsableLimits(sonnet)],\n ],\n missing,\n )\n\n // Grok is intentionally optional. A malformed optional entry is simply\n // omitted from the max projection; it must never make launch fail or be\n // decorated as a 1M model.\n const geminiUsable = usableGemini(gemini)\n const grokUsable = usableGrok(grok)\n\n return {\n ok: missing.length === 0,\n missing,\n models: {\n sol: sol && !missing.some((entry) => entry.startsWith(`${MAX_PROFILE_MODELS.sol}:`)) ? sol : undefined,\n luna: luna && !missing.some((entry) => entry.startsWith(`${MAX_PROFILE_MODELS.luna}:`)) ? luna : undefined,\n gemini: geminiUsable ? gemini : undefined,\n grok: grokUsable ? grok : undefined,\n opus: opus && !missing.some((entry) => entry.startsWith(`${MAX_PROFILE_MODELS.opus}:`)) ? opus : undefined,\n sonnet: sonnet && !missing.some((entry) => entry.startsWith(`${MAX_PROFILE_MODELS.sonnet}:`)) ? sonnet : undefined,\n thirdLab: grokUsable && supportsEffort(grok, \"high\")\n ? \"grok\"\n : geminiUsable\n ? \"gemini\"\n : undefined,\n },\n }\n}\n\nexport function formatMaxPrerequisiteFailure(\n missing: ReadonlyArray<string>,\n): string {\n return (\n \"github-router claude -m max requires the following live-catalog capabilities, \"\n + \"which this account's catalog does not fully provide:\\n\"\n + missing.map((entry) => ` - ${entry}`).join(\"\\n\")\n + \"\\n\\nMax launches do not fall back to arbitrary older models. \"\n + \"Use plain `github-router claude` for the standard profile.\"\n )\n}\n\nexport function maxModelIsOneM(\n model: Model | undefined,\n): boolean {\n return (\n (model?.capabilities?.limits?.max_context_window_tokens ?? 0) >= ONE_M_TOKENS\n )\n}\n\nexport function maxModelSupportsEffort(\n model: Model | undefined,\n effort: Effort,\n): boolean {\n return supportsEffort(model, effort)\n}\n\nexport function maxModelHasUsableLimits(model: Model | undefined): boolean {\n return hasUsableLimits(model)\n}\n\nexport function maxThirdLabModel(): string | undefined {\n const gemini = catalogModel(MAX_PROFILE_MODELS.gemini)\n if (usableGemini(gemini)) return MAX_PROFILE_MODELS.gemini\n const grok = catalogModel(MAX_PROFILE_MODELS.grok)\n return usableGrok(grok) ? MAX_PROFILE_MODELS.grok : undefined\n}\n\nexport function maxGeminiModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.gemini)\n return model && usableGemini(model) ? model.id : undefined\n}\n\nexport function maxGrokModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.grok)\n return model && usableGrok(model) ? model.id : undefined\n}\n\n/** Grok replacement for max-profile surfaces that require high effort. */\nexport function maxGrokHighModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.grok)\n return model && usableGrokReviewer(model) ? model.id : undefined\n}\n\n/** Max-only replacement for any standard Gemini Pro assignment. */\nexport function maxProReplacementModel():\n | typeof MAX_PROFILE_MODELS.grok\n | typeof MAX_PROFILE_MODELS.gemini\n | undefined {\n if (maxGrokHighModel()) return MAX_PROFILE_MODELS.grok\n if (maxGeminiModel()) return MAX_PROFILE_MODELS.gemini\n return undefined\n}\n\nexport function maxOpusModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.opus)\n return model && hasContextAtLeast(model, ONE_M_TOKENS)\n && model.capabilities?.supports?.adaptive_thinking === true\n && supportsEffort(model, \"high\")\n && supportsEndpoint(model, \"messages\")\n && hasUsableLimits(model)\n ? model.id\n : undefined\n}\n\nexport function maxLunaMaxModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.luna)\n return model\n && hasToolCalls(model)\n && hasContextAtLeast(model, ONE_M_TOKENS)\n && supportsEffort(model, \"max\")\n && supportsEndpoint(model, \"responses\")\n && hasUsableLimits(model)\n ? model.id\n : undefined\n}\n\nexport function maxSonnetModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.sonnet)\n return model && hasContextAtLeast(model, ONE_M_TOKENS)\n && model.capabilities?.supports?.tool_calls === true\n && model.capabilities?.supports?.adaptive_thinking === true\n && supportsEffort(model, \"xhigh\")\n && supportsEndpoint(model, \"messages\")\n && hasUsableLimits(model)\n ? model.id\n : undefined\n}\n\nexport function maxReviewerModel(): string | undefined {\n return maxSonnetModel()\n}\n\nexport function maxCodexReviewerModel(): string | undefined {\n const model = catalogModel(MAX_PROFILE_MODELS.codex)\n return model && hasToolCalls(model)\n && supportsEffort(model, \"xhigh\")\n && advertisesEndpoint(model, \"responses\")\n && hasUsableLimits(model)\n && (model.capabilities?.limits?.max_prompt_tokens ?? 0) >= 200_000\n ? model.id\n : undefined\n}\n\nexport function maxCatalogModel(id: string): Model | undefined {\n return catalogModel(id)\n}\n\nexport function maxCatalogModels(): ReadonlyArray<Model> {\n return catalogModels()\n}"],"mappings":";;;AAeA,SAAgB,wBAAwB,IAAgC;CACtE,MAAM,QAAQ,GAAG,MAAM,eAAe;CACtC,IAAI,CAAC,SAAS,MAAM,UAAU,KAAA,GAC5B,OAAO;EAAE,MAAM;EAAI,WAAW;CAAM;CAEtC,OAAO;EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,KAAK;EAAG,WAAW;CAAK;AAC3D;;AAGA,SAAgB,4BAA4B,IAAoB;CAC9D,MAAM,EAAE,MAAM,cAAc,wBAAwB,EAAE;CACtD,OAAO,YAAY,GAAG,KAAK,QAAQ;AACrC;;;ACnBA,MAAM,YAAiE;CACrE,sBAAM,IAAI,IAAI,CAAC,qBAAqB,sBAAsB,CAAC;CAC3D,2BAAW,IAAI,IAAI,CAAC,cAAc,eAAe,CAAC;CAClD,0BAAU,IAAI,IAAI,CAAC,aAAa,cAAc,CAAC;AACjD;;;;;;;;;;AA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