github-router 0.3.357 → 0.3.367

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/dist/ado-tools-rysFZDws.js +1 -0
  2. package/dist/{aic-ledger-BuFrsGur.js → aic-ledger-_mvGW2Ev.js} +42 -7
  3. package/dist/aic-ledger-_mvGW2Ev.js.map +1 -0
  4. package/dist/{aic-statusline-settings-DBS9sEGC.js → aic-statusline-settings-B5EMMSFC.js} +2 -2
  5. package/dist/{aic-statusline-settings-DBS9sEGC.js.map → aic-statusline-settings-B5EMMSFC.js.map} +1 -1
  6. package/dist/{attribution-settings-D9PxJxkL.js → attribution-settings-wVzQvIdL.js} +188 -64
  7. package/dist/attribution-settings-wVzQvIdL.js.map +1 -0
  8. package/dist/{auth-DFawaLJU.js → auth-B3UvYB2r.js} +3 -3
  9. package/dist/{auth-DFawaLJU.js.map → auth-B3UvYB2r.js.map} +1 -1
  10. package/dist/browser-ext/manifest.json +1 -1
  11. package/dist/{check-usage-BkVEl-Su.js → check-usage-45vyaLfl.js} +4 -4
  12. package/dist/{check-usage-BkVEl-Su.js.map → check-usage-45vyaLfl.js.map} +1 -1
  13. package/dist/{claude-BTYQjK-K.js → claude-B3pIageM.js} +89 -41
  14. package/dist/claude-B3pIageM.js.map +1 -0
  15. package/dist/{claude-md-injection-Cpzolxin.js → claude-md-injection-BV4tPUWo.js} +126 -35
  16. package/dist/claude-md-injection-BV4tPUWo.js.map +1 -0
  17. package/dist/{codex-TdsG6C9K.js → codex-B_AMB6JM.js} +7 -7
  18. package/dist/{codex-TdsG6C9K.js.map → codex-B_AMB6JM.js.map} +1 -1
  19. package/dist/{copilot-discount-Bsmv_3OX.js → copilot-discount-BuDbQOHq.js} +2 -2
  20. package/dist/{copilot-discount-Bsmv_3OX.js.map → copilot-discount-BuDbQOHq.js.map} +1 -1
  21. package/dist/{debug-DkNTuErv.js → debug-DL2JsRqY.js} +2 -2
  22. package/dist/{debug-DkNTuErv.js.map → debug-DL2JsRqY.js.map} +1 -1
  23. package/dist/engine-D3oNrF6Z.js +1 -0
  24. package/dist/{gate-discovery-NNQg0t0H.js → gate-discovery-CXE-7VcM.js} +5 -5
  25. package/dist/{gate-discovery-NNQg0t0H.js.map → gate-discovery-CXE-7VcM.js.map} +1 -1
  26. package/dist/{get-copilot-usage-P9chc-X2.js → get-copilot-usage-BbGmK03C.js} +2 -2
  27. package/dist/{get-copilot-usage-P9chc-X2.js.map → get-copilot-usage-BbGmK03C.js.map} +1 -1
  28. package/dist/hooks.mjs +200 -117
  29. package/dist/hooks.sha256 +1 -1
  30. package/dist/{index-cmd-BkfYr9FH.js → index-cmd-CjRcmYk3.js} +4 -4
  31. package/dist/{index-cmd-BkfYr9FH.js.map → index-cmd-CjRcmYk3.js.map} +1 -1
  32. package/dist/{internal-aic-status-C6L4-ncP.js → internal-aic-status-BAVomi5A.js} +4 -4
  33. package/dist/{internal-aic-status-C6L4-ncP.js.map → internal-aic-status-BAVomi5A.js.map} +1 -1
  34. package/dist/{internal-artifact-open-DgJ3PCtt.js → internal-artifact-open-NAGn9Mgt.js} +2 -2
  35. package/dist/{internal-artifact-open-DgJ3PCtt.js.map → internal-artifact-open-NAGn9Mgt.js.map} +1 -1
  36. package/dist/{internal-fast-dispatch-guard-CicGz6oM.js → internal-fast-dispatch-guard-DP25L_Bx.js} +1 -1
  37. package/dist/{internal-fast-dispatch-guard-CgBtUsQI.js → internal-fast-dispatch-guard-DbrgO9Ab.js} +2 -2
  38. package/dist/{internal-fast-dispatch-guard-CgBtUsQI.js.map → internal-fast-dispatch-guard-DbrgO9Ab.js.map} +1 -1
  39. package/dist/{internal-first-mate-guard-DTXPT7JW.js → internal-first-mate-guard-C8GwLbaX.js} +1 -1
  40. package/dist/{internal-first-mate-guard-BfWYN6Jb.js → internal-first-mate-guard-GufCUMl3.js} +3 -3
  41. package/dist/{internal-first-mate-guard-BfWYN6Jb.js.map → internal-first-mate-guard-GufCUMl3.js.map} +1 -1
  42. package/dist/{internal-max-dispatch-guard-mNl9CCir.js → internal-max-dispatch-guard-BB0vwiPx.js} +1 -1
  43. package/dist/{internal-max-dispatch-guard-CY8l9SDw.js → internal-max-dispatch-guard-BodVFHRC.js} +2 -2
  44. package/dist/{internal-max-dispatch-guard-CY8l9SDw.js.map → internal-max-dispatch-guard-BodVFHRC.js.map} +1 -1
  45. package/dist/{internal-plan-review-2OHTs8Nk.js → internal-plan-review-ChFx8wTX.js} +3 -3
  46. package/dist/{internal-plan-review-2OHTs8Nk.js.map → internal-plan-review-ChFx8wTX.js.map} +1 -1
  47. package/dist/{internal-prompt-submit-CkfUcu34.js → internal-prompt-submit-BaccW_CC.js} +4 -4
  48. package/dist/{internal-prompt-submit-CkfUcu34.js.map → internal-prompt-submit-BaccW_CC.js.map} +1 -1
  49. package/dist/{internal-prompt-submit-DZ_-2A6a.js → internal-prompt-submit-DPUBQZtG.js} +2 -2
  50. package/dist/{internal-rebrief-EhBHAHsz.js → internal-rebrief-NjSlx5QY.js} +4 -4
  51. package/dist/{internal-rebrief-EhBHAHsz.js.map → internal-rebrief-NjSlx5QY.js.map} +1 -1
  52. package/dist/{internal-session-bind-Bv50ju2n.js → internal-session-bind-dsUOcKxU.js} +2 -2
  53. package/dist/{internal-session-bind-Bv50ju2n.js.map → internal-session-bind-dsUOcKxU.js.map} +1 -1
  54. package/dist/{internal-stop-hook-Iz8XXE07.js → internal-stop-hook-B2TTl6Zp.js} +5 -5
  55. package/dist/{internal-stop-hook-Iz8XXE07.js.map → internal-stop-hook-B2TTl6Zp.js.map} +1 -1
  56. package/dist/{internal-stop-review-K6f8xsCh.js → internal-stop-review-D_KEV_04.js} +2 -2
  57. package/dist/{internal-stop-review-K6f8xsCh.js.map → internal-stop-review-D_KEV_04.js.map} +1 -1
  58. package/dist/{internal-worker-guard-GVhTjVlR.js → internal-worker-guard-DB6shBIn.js} +2 -2
  59. package/dist/{internal-worker-guard-GVhTjVlR.js.map → internal-worker-guard-DB6shBIn.js.map} +1 -1
  60. package/dist/{internal-workspace-header-d2hFf9Jy.js → internal-workspace-header-DBg5Y7oN.js} +2 -2
  61. package/dist/{internal-workspace-header-d2hFf9Jy.js.map → internal-workspace-header-DBg5Y7oN.js.map} +1 -1
  62. package/dist/{lifecycle-C6cxM_Nk.js → lifecycle-9nX09dBl.js} +2 -2
  63. package/dist/{lifecycle-C6cxM_Nk.js.map → lifecycle-9nX09dBl.js.map} +1 -1
  64. package/dist/lifecycle-C_CT13c9.js +1 -0
  65. package/dist/lifecycle-DibiH857.js +1 -0
  66. package/dist/{lifecycle-pl9QpvqD.js → lifecycle-Gge2Dadd.js} +2 -2
  67. package/dist/{lifecycle-pl9QpvqD.js.map → lifecycle-Gge2Dadd.js.map} +1 -1
  68. package/dist/main.js +23 -23
  69. package/dist/{mcp-workspace-header-Su8uUxJg.js → mcp-workspace-header-Xw9B1W6T.js} +2 -2
  70. package/dist/{mcp-workspace-header-Su8uUxJg.js.map → mcp-workspace-header-Xw9B1W6T.js.map} +1 -1
  71. package/dist/{models-D8v8OTbN.js → models-BR6i348u.js} +3 -3
  72. package/dist/{models-D8v8OTbN.js.map → models-BR6i348u.js.map} +1 -1
  73. package/dist/{orchestration-Bov4rZEi.js → orchestration-D3-2ulhX.js} +2 -2
  74. package/dist/{orchestration-Bov4rZEi.js.map → orchestration-D3-2ulhX.js.map} +1 -1
  75. package/dist/{paths-BSI_EtDT.js → paths-C5477RGC.js} +48 -4
  76. package/dist/paths-C5477RGC.js.map +1 -0
  77. package/dist/paths-CEswtFj5.js +1 -0
  78. package/dist/{peer-mcp-personas-GANlrtNR.js → peer-mcp-personas-BOgR46nM.js} +519 -169
  79. package/dist/peer-mcp-personas-BOgR46nM.js.map +1 -0
  80. package/dist/{pi-TKFwPyLA.js → pi-DcWp83mx.js} +377 -602
  81. package/dist/pi-DcWp83mx.js.map +1 -0
  82. package/dist/{plan-review-hook-CHK1wL3-.js → plan-review-hook-C9K-em4D.js} +3 -3
  83. package/dist/{plan-review-hook-CHK1wL3-.js.map → plan-review-hook-C9K-em4D.js.map} +1 -1
  84. package/dist/{provision-BNN6yRk8.js → provision-DkWR9B6I.js} +5 -5
  85. package/dist/{provision-BNN6yRk8.js.map → provision-DkWR9B6I.js.map} +1 -1
  86. package/dist/{self-invocation-Dk_UHD_v.js → self-invocation-BtcGj-lY.js} +2 -2
  87. package/dist/{self-invocation-Dk_UHD_v.js.map → self-invocation-BtcGj-lY.js.map} +1 -1
  88. package/dist/{serve-BaeLm9Um.js → serve-BGwEVDdc.js} +14 -14
  89. package/dist/{serve-BaeLm9Um.js.map → serve-BGwEVDdc.js.map} +1 -1
  90. package/dist/{server-setup-BcUQv5ac.js → server-setup-DVPL9iph.js} +911 -100
  91. package/dist/server-setup-DVPL9iph.js.map +1 -0
  92. package/dist/{service-backend-DHyd9vjW.js → service-backend-B6D_DY1Z.js} +3 -3
  93. package/dist/{service-backend-DHyd9vjW.js.map → service-backend-B6D_DY1Z.js.map} +1 -1
  94. package/dist/{start-BdoGJc36.js → start-BUWx3nSr.js} +4 -4
  95. package/dist/{start-BdoGJc36.js.map → start-BUWx3nSr.js.map} +1 -1
  96. package/dist/{static-context-pack-dKrzbfIN.js → static-context-pack-ChHuxBpk.js} +232 -61
  97. package/dist/static-context-pack-ChHuxBpk.js.map +1 -0
  98. package/dist/{stop-gate-hook-CC7VWkZM.js → stop-gate-hook-DnLC09Lg.js} +3 -3
  99. package/dist/{stop-gate-hook-CC7VWkZM.js.map → stop-gate-hook-DnLC09Lg.js.map} +1 -1
  100. package/dist/{stop-gate-policy-CoR8xKNQ.js → stop-gate-policy-Dx9c98_d.js} +2 -2
  101. package/dist/{stop-gate-policy-CoR8xKNQ.js.map → stop-gate-policy-Dx9c98_d.js.map} +1 -1
  102. package/dist/{token-CA2s70qj.js → token-OTb61rOC.js} +2 -2
  103. package/dist/{token-CA2s70qj.js.map → token-OTb61rOC.js.map} +1 -1
  104. package/dist/{worker-dispatch-B_rriT7z.js → worker-dispatch-B1w2qfjX.js} +2 -2
  105. package/dist/{worker-dispatch-B_rriT7z.js.map → worker-dispatch-B1w2qfjX.js.map} +1 -1
  106. package/docs/azure-mcp.md +29 -31
  107. package/package.json +1 -1
  108. package/dist/ado-tools-DqLJ-u19.js +0 -1
  109. package/dist/aic-ledger-BuFrsGur.js.map +0 -1
  110. package/dist/attribution-settings-D9PxJxkL.js.map +0 -1
  111. package/dist/claude-BTYQjK-K.js.map +0 -1
  112. package/dist/claude-md-injection-Cpzolxin.js.map +0 -1
  113. package/dist/engine-CmhUwYI5.js +0 -1
  114. package/dist/lifecycle-BU_d2QMs.js +0 -1
  115. package/dist/lifecycle-ByFyew_w.js +0 -1
  116. package/dist/paths-BSI_EtDT.js.map +0 -1
  117. package/dist/paths-BYxX9DfA.js +0 -1
  118. package/dist/peer-mcp-personas-GANlrtNR.js.map +0 -1
  119. package/dist/pi-TKFwPyLA.js.map +0 -1
  120. package/dist/server-setup-BcUQv5ac.js.map +0 -1
  121. package/dist/static-context-pack-dKrzbfIN.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-md-injection-BV4tPUWo.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\"\nimport {\n balancedContractFor,\n cheapestContractFor,\n displayModelName,\n isBalancedFamily,\n isCheapestFamily,\n isLocalFamily,\n isPinnedLaunchProfile,\n local2AdvisorContract,\n localContractFor,\n} from \"./profile-family\"\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/local; 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 */\n/** One builder for every profile's pipeline-skills block: only the Plan stage\n * wording and the dispatcher contrast vary, so the shared stages cannot drift\n * between the exported constants. */\nfunction pipelineSkillsAwareness(opts: { planAgent: boolean; workersAvailable: boolean }): string {\n // A local launch carries no `workers` group, so contrasting its dispatchers\n // would name a tool the mode does not expose.\n const boundary = opts.workersAvailable\n ? \", native subagents only, never worker-*\"\n : \", native subagents only\"\n const planStage = opts.planAgent\n ? \"native Plan subagent plans non-trivial asks (trivial exits planless)\"\n : \"the lead plans directly (no separate planning subagent on this profile; trivial exits planless)\"\n const implementStage = opts.planAgent\n ? \"(implementer first on max; worktree:true if parallel tasks need isolation)\"\n : \"(worktree:true if parallel tasks need isolation)\"\n return `Pipeline skills (all 200K default context${boundary}). `\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: ${planStage}, ordered plan.md (~5 min), open questions, waits for user approval; `\n + `(3) \\`/gh-implement\\` AFTER plan approval: bounded parallel General-Purpose subagents ${implementStage}, 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\nexport const PIPELINE_SKILLS_AWARENESS = pipelineSkillsAwareness({ planAgent: true, workersAvailable: true })\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 lead\n * instead of a Plan dispatch. Every other stage is identical.\n */\nexport const PIPELINE_SKILLS_AWARENESS_NO_PLAN_AGENT = pipelineSkillsAwareness({ planAgent: false, workersAvailable: true })\n\n/** Local is the no-Plan form without the `worker-*` contrast, which names a\n * dispatcher the profile does not inject. */\nexport const PIPELINE_SKILLS_AWARENESS_LOCAL = pipelineSkillsAwareness({ planAgent: false, workersAvailable: false })\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). The cheapest family\n * (`\"cheapest\"`/`\"cheapest2\"`) selects the same restricted roster prose\n * with its contracted identities (Luna lead and reviewer, the family's\n * Sol Advisor/Oracle; never astra) minus the `Plan` role (the lead plans\n * directly). The balanced family (`\"balanced\"`/`\"balanced2\"`) selects the\n * same restricted roster prose Sol-led with its Grok Oracle (never astra),\n * likewise without a `Plan` role. The local pair (`\"local\"`/`\"local2\"`)\n * selects the cheapest-shaped restricted roster, because the local endpoint\n * serves its own `opus`/`sonnet`/`haiku` tiers and inherits the cheapest\n * prompts; the model labels are the tier names, and Oracle stays the\n * Copilot-served `gpt-6.1-sol` consult. `\"local\"` has no Advisor at all, so\n * no local clause may name one. 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\" | \"cheapest2\" | \"balanced\" | \"balanced2\" | \"local\" | \"local2\" | \"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 (isPinnedLaunchProfile(opts.profile)) {\n if (isCheapestFamily(opts.profile)) {\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`\"\n }\n // Local: same three-role roster and the same split of duty as cheapest, but\n // the model labels are the local endpoint's OWN tier ids rather than Copilot\n // slugs. Those ids are whatever the server maps them to, so the clause names\n // the tier and what it is for, never a model family. It also drops\n // cheapest's `heavy … tier` appositives: with three different ids those read\n // as a strength ordering across tiers, and only the server knows what its\n // ids map to. `Plan` is deliberately absent: the local roster does not emit\n // it.\n if (isLocalFamily(opts.profile)) {\n const models = localContractFor(opts.profile).nativeModels\n return joinClauses([\n `\\`Explore\\` (${models.Explore} tier) for discovery, dependency mapping, and convention tracking spanning more than a couple of files`,\n `\\`General-Purpose\\` (${models[\"General-Purpose\"]} tier) for mixed, iterative, or multi-step execution`,\n `\\`reviewer\\` (${models.reviewer} tier) for independent adversarial verification, reproduction, and root-causing`,\n ]) + \". Delegate by value — wide breadth to `Explore`, execution to `General-Purpose`, verification to `reviewer`\"\n }\n // Balanced: lead owns planning, implementation, verification by default —\n // only the reviewer is gated behind genuine need.\n if (isBalancedFamily(opts.profile)) {\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 ])\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. The window statement itself lives in\n // `windowNote`, which every pinned directive appends right after this\n // clause, so restating it here would print it twice in one paragraph pair.\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 * Transport sibling of `CHEAPEST_CONSULT_CONTRACT` for a front-end whose\n * consultant receives no transcript at all.\n *\n * The body is the cheapest contract's, with the one transport sentence\n * replaced: instead of \"Sol reads a curated view of this session\", the lead is\n * told to make the brief self-contained because the Advisor reads only what\n * the lead writes. Everything else — budget, anchors, disqualifiers,\n * discriminator — is identical, so the consult policy cannot drift between\n * the two front-ends.\n *\n * Used by the Pi launcher, whose `advisor` subagent is `defaultContext:\n * fresh` with a read-only toolset: it never sees the lead's conversation, so\n * the curated-view sentence would be false there. The Claude launcher keeps\n * `CHEAPEST_CONSULT_CONTRACT`, which describes what its curated path really\n * sends.\n */\nexport const FRESH_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: make the brief self-contained — the Advisor reads only what you write — so state 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 * Oracle-only sibling of `CHEAPEST_CONSULT_CONTRACT` for a launch that carries\n * an Oracle but no Advisor: the `balanced` family, whose consultant ladder\n * exposes `oracle` alone.\n *\n * Naming the Advisor there would point the lead at a tool the session cannot\n * reach, so the budget, the anchors and the disqualifiers are restated against\n * `oracle` alone. Everything that is not about the Advisor is the cheapest\n * contract's wording, and a launch that carries both keeps the original.\n */\nexport const ORACLE_ONLY_CONSULT_CONTRACT =\n \"Consulting `oracle` (a small budget — choose wisely): you have roughly 8-10 oracle calls for this session, and each costs real time and money, so spend them only where direction changes the outcome. Oracle gives you COUNSEL on HOW — and sometimes WHAT — to do: the shortest path, what to consider or look at, planning, strategy, and direction. It never replaces 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). Make the brief self-contained: Oracle reads only what you write, so state 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/** Short, always-resident pointer to `ORACLE_ONLY_CONSULT_CONTRACT`. */\nexport const ORACLE_ONLY_CONSULT_CONTRACT_POINTER =\n \"Consulting `oracle` (small budget, ~8-10 calls — choose wisely): use it 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` owns the moment. Full how-to (when to spend, the call brief) is in your CLAUDE.md project instructions.\\n\\n\"\n\n/**\n * Contract for a launch that carries neither consultant.\n *\n * `-m local` exposes no `peers` group at all, so neither the Advisor nor the\n * Oracle exists on its surface. Both siblings above are written around a budget\n * of consults and a discriminator between the two roles, and naming either role\n * here would point the lead at a tool the session cannot reach. What survives\n * is the part that was never about them: settle what evidence can settle, and\n * make the reasoning explicit where it cannot.\n */\nexport const DIRECT_EVIDENCE_CONTRACT =\n \"Consultation budget: this launch has no consultant, so every unresolved question is settled by direct evidence: a search, a read, a build, a test, or a run. Where you would otherwise want a second opinion, state the competing hypotheses explicitly, choose the one the evidence supports, and record your confidence and what being wrong would cost so the user can correct course early. Counsel is never a substitute for verification you can perform yourself.\\n\\n\"\n\n/** Short, always-resident pointer to `DIRECT_EVIDENCE_CONTRACT`. */\nexport const DIRECT_EVIDENCE_CONTRACT_POINTER =\n \"This launch has no consultant: settle unresolved questions with direct evidence (search, read, build, test, or run) and state competing hypotheses explicitly before choosing. Full how-to 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 (isPinnedLaunchProfile(opts.profile)) {\n const isCheap = opts.profile === \"cheap\" || opts.profile === \"cheap1m\"\n const isCheapest = isCheapestFamily(opts.profile)\n const isBalanced = isBalancedFamily(opts.profile)\n const isLocal = isLocalFamily(opts.profile)\n // `local` is Advisor-free; only `local2` carries one.\n const hasAdvisor = !isBalanced && !(isLocal && opts.profile !== \"local2\")\n // `local` runs no Copilot model, so it has no Oracle either: its `peers`\n // group, when the artifact panel publishes it, carries the human-review\n // tools only, and nothing else on that launch could answer a consult.\n const hasOracle = !(isLocal && opts.profile === \"local\")\n // The cheapest family and `local2` grant `reviewer` a capped Advisor\n // (at most 5 rounds per review), so \"lead-only\" is false on those\n // launches; the surfaces below say who else may consult instead.\n const advisorReviewerGranted = hasAdvisor && (isCheapest || isLocal)\n const profileLabel = isLocal\n ? \"Local\"\n : isCheapest\n ? \"Cheapest\"\n : isCheap\n ? \"Cheap\"\n : isBalanced\n ? \"Balanced\"\n : \"Fast\"\n // The family contract names the Oracle identity, so `balanced` renders\n // Grok 4.6 and `balanced2` Grok 4.7 without a parallel literal here. Local\n // resolves through its own contract: `cheapestContractFor` hands back a\n // Copilot lead/reviewer identity for a launch that must never name one.\n const familyContract = isCheapest\n ? cheapestContractFor(opts.profile)\n : isBalanced\n ? balancedContractFor(opts.profile)\n : isLocal\n ? localContractFor(opts.profile)\n : undefined\n const oracleDescriptor = familyContract\n ? `${displayModelName(familyContract.oracleModel)} (200K/${familyContract.oracleEffort})`\n : isCheap\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/local have no Plan role; fast/cheap/cheap1m still do.\n const expensiveModels = isCheapest || isBalanced || isLocal\n ? \"(reviewer, Oracle)\"\n : \"(Plan, reviewer, Oracle)\"\n // A local launch must not price the roles it delegates to: `reviewer` runs\n // on the operator's own endpoint, on a tier the profile knows nothing\n // about, so the only defensible subject is the role names themselves.\n // With no Oracle on the launch the only delegate left is `reviewer`, so\n // the sentence carries its own verb rather than a shared plural one.\n const subsetTail = isLocal && !hasOracle\n ? \"`reviewer` sees only the synthesized subset, never raw search output.\"\n : `${isLocal ? \"`reviewer` and Oracle\" : `expensive models ${expensiveModels}`} see only the synthesized subset, never raw search output.`\n // Same reasoning for the ladder's cost framing. \"Most direct first\" keeps\n // the ordering advice (search before fan-out) without asserting that\n // searching is cheaper than the model answering.\n const strategyOpener = isLocal\n ? \"Search strategy (most direct first): \"\n : \"Search strategy (cheapest first): \"\n // \"LOCAL\" here means in-process, but inside a `local` launch that reads as\n // \"the local model\". Drop the qualifier there rather than re-scope the\n // word; the mode names still carry the meaning.\n const lexicalLabel = isLocal ? \"LEXICAL\" : \"LOCAL LEXICAL\"\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; \" + subsetTail + \" \"\n : opts.semanticSearchAvailable === true\n ? strategyOpener + \"(1) \" + lexicalLabel + \" `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 — \" + subsetTail + \" \"\n : strategyOpener + lexicalLabel + \" `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 — \" + subsetTail + \" \"\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 // `worker-browse` is a Pi worker, so it only exists where the workers group\n // does. Both local profiles drop that group (every subagent there is meant\n // to run on the local model), so naming it would point the lead at an agent\n // the session cannot reach. The launcher already reports `browseAvailable`\n // false for them; this keeps the prose true even for a caller that does not.\n const workerBrowseAvailable = opts.browseAvailable && !isLocal\n const workerBrowseClause = workerBrowseAvailable\n ? ` \\`worker-browse\\` runs delegated autonomous browsing tasks through \\`mcp__${workersKey}__browse\\`.`\n : \"\"\n // Artifact rows live in the `peers` group, which both local profiles\n // register while the artifact panel is available even though neither admits\n // a Copilot persona: human review is not model inference. Without that\n // panel the group holds nothing and the launcher drops it.\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 // `worker-browse` is emitted only when browse is on AND the launch carries\n // the workers group, so a delegation graph must not name it otherwise; same\n // predicate as the adjacent `workerBrowseClause`.\n const leadLeaf = workerBrowseAvailable\n ? \"`Explore`, `reviewer`, and `worker-browse`\"\n : \"`Explore` and `reviewer`\"\n const balancedLeaf = workerBrowseAvailable\n ? \"`Explore` and `worker-browse`\"\n : \"`Explore`\"\n // A local lead runs on an endpoint whose model and speed the profile knows\n // nothing about, so only the opener differs; the behavioural tail is\n // model-neutral and stays verbatim.\n const disciplineOpener = isLocal\n ? \"Execution discipline: \"\n : \"Work to your strengths as a fast, cost-efficient model: \"\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 || isLocal\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\"\n // `local` has no Advisor, and naming one would point the lead at a tool\n // this session cannot reach.\n + (hasAdvisor ? \"; before presenting the final plan to the user, consult `advisor` once for a framing check. \" : \". \")\n + disciplineOpener\n + \"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`; \" + leadLeaf + \" cannot invoke native subagents.\\n\\n\"\n + (hasAdvisor\n ? CHEAPEST_CONSULT_CONTRACT\n : hasOracle\n ? ORACLE_ONLY_CONSULT_CONTRACT\n : DIRECT_EVIDENCE_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` (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; \" + balancedLeaf + \" 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`; \" + leadLeaf + \" 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 || isLocal\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 : `${isLocal\n ? PIPELINE_SKILLS_AWARENESS_LOCAL\n : isCheapest || isBalanced\n ? PIPELINE_SKILLS_AWARENESS_NO_PLAN_AGENT\n : PIPELINE_SKILLS_AWARENESS}\\n\\n`\n // Balanced has no Advisor, so Oracle is its only consultant, framed as a\n // second opinion on a precise question — never a discovery tool. `local`\n // has neither consultant and never reaches this branch. For unknowns, only\n // search (then Explore) helps. Cheapest, balanced, and local have no Plan\n // role, so Oracle is lead-only there; fast/cheap/cheap1m keep lead-and-Plan\n // Oracle access.\n const oracleLeadOnly = isCheapest || isBalanced || isLocal\n // Cost framing is a claim about the endpoint being billed. A local launch\n // bills the operator's own endpoint at a rate this profile knows nothing\n // about, so both halves drop the cost vocabulary while keeping the\n // ordering advice intact.\n const consultOpener = isLocal\n ? \"Consultation guidance: verify claims against real evidence first. \"\n : \"Consultation guidance: funnel unknowns cheapest-first. \"\n const consultCostTail = isLocal\n ? \"Prefer direct evidence over delegation when the question is narrow. \"\n : \"Optimize for accuracy, intelligence, and correctness at the lowest cost — prefer direct evidence over delegation when the question is narrow. \"\n const consultation = !hasAdvisor\n ? consultOpener\n + \"(1) `code` and `web` search narrow scope and rule out hypotheses — always first. (2) `Explore` subagents for targeted breadth only when search is insufficient. \"\n + (hasOracle\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. `\n : \"\")\n + consultCostTail\n : \"Consultation guidance: Follow an evidence-first escalation ladder. Direct empirical evidence (search, code, tests, builds) settles factual questions first. \"\n + (advisorReviewerGranted\n ? \"Advisor is an optional, non-binding, transcript-aware sounding board available to the lead and `reviewer` (at most 5 rounds per review) for trajectory guidance or framing checks (direction, not dictation), and never use it for routine progress, waiting, directly verifiable facts, or completion ritual. \"\n : \"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 || isLocal ? \"\" : \" `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\" | \"cheapest2\" | \"balanced\" | \"balanced2\" | \"local\" | \"local2\" | \"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/local have no Plan\n // role, so their sentence names lead-direct planning instead of a Plan\n // dispatch.\n const digestPipelineSentence = opts.sweEnabled === false\n ? \"\"\n : isCheapestFamily(opts.profile) || isBalancedFamily(opts.profile) || isLocalFamily(opts.profile)\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 (isPinnedLaunchProfile(opts.profile)) {\n const isCheap = opts.profile === \"cheap\" || opts.profile === \"cheap1m\"\n const isCheapest = isCheapestFamily(opts.profile)\n const isBalanced = isBalancedFamily(opts.profile)\n const isLocal = isLocalFamily(opts.profile)\n // `local` is Advisor-free; only `local2` carries one.\n const hasAdvisor = !isBalanced && !(isLocal && opts.profile !== \"local2\")\n // `local` runs no Copilot model, so it has no Oracle either: its `peers`\n // group, when the artifact panel publishes it, carries the human-review\n // tools only, and nothing else on that launch could answer a consult.\n const hasOracle = !(isLocal && opts.profile === \"local\")\n // The cheapest family and `local2` grant `reviewer` a capped Advisor\n // (at most 5 rounds per review), so \"lead-only\" is false on those\n // launches; the surfaces below say who else may consult instead.\n const advisorReviewerGranted = hasAdvisor && (isCheapest || isLocal)\n const profileLabel = isLocal\n ? \"Local\"\n : isCheapest\n ? \"Cheapest\"\n : isCheap\n ? \"Cheap\"\n : isBalanced\n ? \"Balanced\"\n : \"Fast\"\n const familyContract = isCheapest\n ? cheapestContractFor(opts.profile)\n : isBalanced\n ? balancedContractFor(opts.profile)\n : isLocal\n ? localContractFor(opts.profile)\n : undefined\n // Every family here is lead-only on Oracle (none has a Plan role), so one\n // contract-derived form serves them all: `balanced` Grok 4.6 →\n // `balanced2` Grok 4.7, `cheapest` GPT-5.6 Sol → `cheapest2` GPT-6.1 Sol,\n // and local's contract keeps Oracle on the same Copilot slug.\n const oracleDescriptor = familyContract\n ? `(${displayModelName(familyContract.oracleModel)} 200K/${familyContract.oracleEffort}, lead-only)`\n : isCheap\n ? \"(Grok 4.6 200K/medium, lead and Plan)\"\n : \"(Opus 5 1M/high, lead and Plan)\"\n // Only the two Advisor-carrying contracts describe the Advisor step. The\n // base local contract has no advisor fields at the type level and balanced\n // has no Advisor at all, so neither can be read here: `local` renders this\n // descriptor nowhere, because `hasAdvisor` routes it down the Oracle-only\n // ladder below.\n const advisorContract:\n | { advisorModel: string; advisorEffort: string }\n | undefined = isCheapest\n ? cheapestContractFor(opts.profile)\n : opts.profile === \"local2\"\n ? local2AdvisorContract()\n : undefined\n const advisorScope = advisorReviewerGranted ? \"lead and `reviewer`, capped\" : \"lead-only\"\n const advisorDescriptor = advisorContract\n ? `(${displayModelName(advisorContract.advisorModel)}/${advisorContract.advisorEffort}, ${advisorScope})`\n : `(Sol/high, ${advisorScope})`\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 || isLocal\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${hasAdvisor ? \"; 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 + (hasAdvisor\n ? CHEAPEST_CONSULT_CONTRACT_POINTER\n : hasOracle\n ? ORACLE_ONLY_CONSULT_CONTRACT_POINTER\n : DIRECT_EVIDENCE_CONTRACT_POINTER)\n : isBalanced\n ? `${profileLabel} launch profile. The lead owns planning, implementation, and verification by default: narrow scope first with \\`code\\` 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 and `local` have no Advisor: the ladder is search → Explore →\n // Oracle (second opinion on a framed question, never discovery).\n // The cost vocabulary is gated the same way as the directive's: `local`\n // bills the operator's own endpoint, so neither \"cheapest-first\" nor\n // \"lowest cost\" is a claim this profile can make.\n const digestLadderOpener = isLocal\n ? \"Verify claims against real evidence: run relevant commands and tests. (1) \"\n : \"Verify claims against real evidence: run relevant commands and tests. Funnel unknowns cheapest-first: (1) \"\n const digestLadderTail = isLocal\n ? \"Prefer direct evidence over delegation when the question is narrow.\"\n : \"Optimize for accuracy, intelligence, and correctness at the lowest cost.\"\n const consultationLadder = !hasAdvisor\n ? !hasOracle\n ? digestLadderOpener\n + \"`code` + `web` search narrow scope and rule out hypotheses first; (2) `Explore` for targeted breadth when search is insufficient. \" + digestLadderTail\n : digestLadderOpener\n + \"`code` + `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. \" + digestLadderTail\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 || isLocal\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 detectLineEnding,\n stripLeadingBom,\n splitLines,\n joinLines,\n isUnderClaudeConfigMirrorRealpath,\n renameWithRetry,\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+BA,MAAM,mBACJ;AACF,MAAM,oBAAoB;AAE1B,MAAM,oBACJ;A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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,9 +1,9 @@
1
- import { P as warmTreeSitterPool } from "./service-backend-DHyd9vjW.js";
1
+ import { P as warmTreeSitterPool } from "./service-backend-B6D_DY1Z.js";
2
2
  import { t as state } from "./state-CiwCLVDZ.js";
3
- import { d as resolveModel, u as resolveCodexModel } from "./token-CA2s70qj.js";
4
- import { B as runSelfUpdate, a as setupAndServe, c as startKeepAwake, d as listModelsForEndpoint, f as enableFileLogging, i as parseSharedArgs, l as stopKeepAwake, n as getCodexEnvVars, o as sharedServerArgs } from "./server-setup-BcUQv5ac.js";
5
- import { D as toolbeltEnabled, On as DEFAULT_CODEX_MODEL, bn as provisionAndIndexColbert, kn as DEFAULT_CODEX_MODEL_FALLBACKS, mn as hasSupportedBrowserInstalled, pn as provisionBrowserAssets, yn as colbertDegradedWarning } from "./peer-mcp-personas-GANlrtNR.js";
6
- import { i as launchChild, t as provisionToolbelt } from "./provision-BNN6yRk8.js";
3
+ import { d as resolveModel, u as resolveCodexModel } from "./token-OTb61rOC.js";
4
+ import { $ as runSelfUpdate, C as listModelsForEndpoint, a as setupAndServe, b as startKeepAwake, i as parseSharedArgs, n as getCodexEnvVars, o as sharedServerArgs, w as enableFileLogging, x as stopKeepAwake } from "./server-setup-DVPL9iph.js";
5
+ import { D as toolbeltEnabled, En as provisionAndIndexColbert, Fn as DEFAULT_CODEX_MODEL_FALLBACKS, Pn as DEFAULT_CODEX_MODEL, Tn as colbertDegradedWarning, bn as hasSupportedBrowserInstalled, yn as provisionBrowserAssets } from "./peer-mcp-personas-BOgR46nM.js";
6
+ import { i as launchChild, t as provisionToolbelt } from "./provision-DkWR9B6I.js";
7
7
  import { c as disposeBluebirdClients } from "./bluebird-client-C29-JOkG.js";
8
8
  import { defineCommand } from "citty";
9
9
  import consola from "consola";
@@ -83,7 +83,7 @@ const codex = defineCommand({
83
83
  serverUrl
84
84
  }, server, { onShutdown: async () => {
85
85
  await stopKeepAwake();
86
- const { disposeAdoClients } = await import("./ado-tools-DqLJ-u19.js");
86
+ const { disposeAdoClients } = await import("./ado-tools-rysFZDws.js");
87
87
  await disposeBluebirdClients();
88
88
  await disposeAdoClients();
89
89
  } });
@@ -92,4 +92,4 @@ const codex = defineCommand({
92
92
  //#endregion
93
93
  export { codex };
94
94
 
95
- //# sourceMappingURL=codex-TdsG6C9K.js.map
95
+ //# sourceMappingURL=codex-B_AMB6JM.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"codex-TdsG6C9K.js","names":[],"sources":["../src/codex.ts"],"sourcesContent":["import process from \"node:process\"\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { enableFileLogging } from \"./lib/file-log-reporter\"\nimport { launchChild } from \"./lib/launch\"\nimport { listModelsForEndpoint } from \"./lib/model-validation\"\nimport {\n DEFAULT_CODEX_MODEL,\n DEFAULT_CODEX_MODEL_FALLBACKS,\n} from \"./lib/port\"\nimport {\n getCodexEnvVars,\n parseSharedArgs,\n setupAndServe,\n sharedServerArgs,\n} from \"./lib/server-setup\"\nimport { runSelfUpdate } from \"./lib/self-update\"\nimport { state } from \"./lib/state\"\nimport { toolbeltEnabled } from \"./lib/toolbelt\"\nimport { provisionToolbelt } from \"./lib/toolbelt/provision\"\nimport { colbertDegradedWarning, provisionAndIndexColbert } from \"./lib/colbert\"\nimport { startKeepAwake, stopKeepAwake } from \"./lib/keep-awake\"\nimport { warmTreeSitterPool } from \"./lib/tree-sitter-pool/pool\"\nimport { provisionBrowserAssets } from \"./lib/browser-mcp/provision\"\nimport { hasSupportedBrowserInstalled } from \"./lib/browser-mcp/browser-detect\"\nimport { disposeBluebirdClients } from \"./lib/bluebird-client\"\nimport { resolveCodexModel, resolveModel } from \"./lib/utils\"\n\nexport const codex = defineCommand({\n meta: {\n name: \"codex\",\n description: \"Start the proxy server and launch Codex CLI\",\n },\n args: {\n ...sharedServerArgs,\n model: {\n alias: \"m\",\n type: \"string\",\n description: \"Override the default model for Codex CLI\",\n },\n },\n async run({ args }) {\n if (!process.stdout.isTTY) {\n consola.error(\"The codex subcommand requires a TTY (interactive terminal).\")\n process.exit(1)\n }\n\n const parsed = parseSharedArgs(args as unknown as Record<string, unknown>)\n\n let server: Awaited<ReturnType<typeof setupAndServe>>[\"server\"]\n let serverUrl: string\n try {\n const result = await setupAndServe({\n ...parsed,\n port: parsed.port, // undefined = random port\n silent: true,\n })\n server = result.server\n serverUrl = result.serverUrl\n } catch (error) {\n consola.error(\"Failed to start server:\", error instanceof Error ? error.message : error)\n process.exit(1)\n }\n\n // Best-effort self-update (detached, applies next launch).\n void runSelfUpdate({ selfUpdate: args[\"self-update\"] !== false })\n\n // Materialize the LLM toolbelt in the background (PATH prepend is in\n // getCodexEnvVars). Best-effort; never blocks launch.\n if (toolbeltEnabled()) {\n void provisionToolbelt().catch(() => {})\n }\n\n // Best-effort ColBERT semantic-search provision + background index of\n // the launch cwd. Opt-IN via --search (no-op otherwise); never blocks\n // launch, never throws.\n void provisionAndIndexColbert()\n\n // Surface a terminally-failed semantic index to the HUMAN (see the note\n // in claude.ts). Fire-and-forget; lexical search still works.\n void colbertDegradedWarning(undefined, { logsToFile: true })\n .then((warning) => {\n if (warning) process.stderr.write(`${warning}\\n`)\n })\n .catch(() => {})\n\n // Best-effort, bounded launch warm-up: ready one tree-sitter worker.\n // Opt out with GH_ROUTER_DISABLE_TS_POOL_WARMUP=1.\n void warmTreeSitterPool()\n\n // Best-effort: keep the machine awake while the proxy/Codex session\n // runs (win32 default-on; opt out GH_ROUTER_DISABLE_KEEP_AWAKE=1).\n // Self-registered SIGINT/SIGTERM/exit reaper releases the assertion.\n startKeepAwake()\n\n // Best-effort: materialize the browser extension + bridge into the\n // stable app-dir and stamp the running version. Gated inline (browse\n // opt-in + a supported browser) rather than via browserToolsEnabled()\n // so the codex command path doesn't eagerly pull the compressor /\n // worker-agent graph. Never blocks launch, never throws.\n const browseOptIn =\n state.browseEnabled || process.env.GH_ROUTER_ENABLE_BROWSE === \"1\"\n if (browseOptIn && hasSupportedBrowserInstalled()) {\n void provisionBrowserAssets().catch((err) =>\n consola.debug(\"Browser extension provisioning failed:\", err),\n )\n }\n\n const usingDefault = !args.model\n const requestedModel = args.model ?? DEFAULT_CODEX_MODEL\n\n // Resolve model before printing success message (so we show the actual model)\n // but enable file logging first so resolution warnings go to file, not terminal\n enableFileLogging()\n\n let codexModel = resolveCodexModel(requestedModel)\n if (codexModel !== requestedModel) {\n consola.info(`Model \"${requestedModel}\" resolved to \"${codexModel}\"`)\n }\n\n // For the implicit-default path only: honor the explicit fallback order\n // (DEFAULT_CODEX_MODEL, then DEFAULT_CODEX_MODEL_FALLBACKS led by gpt-5.5)\n // by cache presence BEFORE resolveCodexModel's codex-slug-preferring\n // \"best /responses model\" safety net. `resolveModel` (NOT resolveCodexModel)\n // walks the chain, so the codex-slug preference can't shadow an\n // earlier-in-chain named fallback (e.g. gpt-5.5) that IS present. The\n // resolveCodexModel result above stays as the FINAL safety net, used only\n // when none of the named chain entries is in the catalog.\n if (usingDefault && state.models) {\n const inCache = (id: string) =>\n state.models?.data.some((m) => m.id === id) ?? false\n const firstPresent = [DEFAULT_CODEX_MODEL, ...DEFAULT_CODEX_MODEL_FALLBACKS]\n .map((id) => resolveModel(id))\n .find((id) => inCache(id))\n if (firstPresent) {\n if (firstPresent !== codexModel) {\n consola.info(\n `Default model \"${DEFAULT_CODEX_MODEL}\" not in your Copilot model list; falling back to \"${firstPresent}\".`,\n )\n }\n codexModel = firstPresent\n }\n }\n\n // Validate model exists in Copilot model list\n const modelEntry = state.models?.data.find((m) => m.id === codexModel)\n if (!modelEntry) {\n const available = listModelsForEndpoint(\"/responses\")\n consola.warn(\n `Model \"${codexModel}\" not found. Available codex models: ${available.join(\", \")}`,\n )\n } else {\n const ctx = modelEntry.capabilities?.limits?.max_context_window_tokens\n if (ctx) consola.info(`Model context window: ${ctx.toLocaleString()} tokens`)\n }\n\n // Print to stderr directly — consola's terminal reporter is already gone\n process.stderr.write(`Server ready on ${serverUrl}, launching Codex CLI (${codexModel})...\\n`)\n\n const envVars = getCodexEnvVars(serverUrl)\n const extraArgs = ((args as unknown as Record<string, unknown>)._ as string[]) ?? []\n\n launchChild(\n {\n kind: \"codex\",\n envVars,\n extraArgs,\n model: codexModel,\n serverUrl,\n },\n server,\n {\n onShutdown: async () => {\n await stopKeepAwake()\n // Dynamic, like `claude.ts` and `pi.ts` do for the same call: a\n // static import of `ado-tools` would pull the whole non-persona MCP\n // registry (and the worker/orchestration modules behind it) into the\n // Codex CLI's import graph for one shutdown-time call. The client\n // module has a second, static importer in `serve.ts`, which already\n // loads that registry — this import is the one that would be pure\n // weight.\n const { disposeAdoClients } = await import(\"./lib/ado-tools\")\n await disposeBluebirdClients()\n await disposeAdoClients()\n },\n },\n )\n },\n})\n"],"mappings":";;;;;;;;;;;AA8BA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;EACJ,GAAG;EACH,OAAO;GACL,OAAO;GACP,MAAM;GACN,aAAa;EACf;CACF;CACA,MAAM,IAAI,EAAE,QAAQ;EAClB,IAAI,CAAC,QAAQ,OAAO,OAAO;GACzB,QAAQ,MAAM,6DAA6D;GAC3E,QAAQ,KAAK,CAAC;EAChB;EAEA,MAAM,SAAS,gBAAgB,IAA0C;EAEzE,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,MAAM,SAAS,MAAM,cAAc;IACjC,GAAG;IACH,MAAM,OAAO;IACb,QAAQ;GACV,CAAC;GACD,SAAS,OAAO;GAChB,YAAY,OAAO;EACrB,SAAS,OAAO;GACd,QAAQ,MAAM,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,KA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,GACjF;EACF,OAAO;GACL,MAAM,MAAM,WAAW,cAAc,QAAQ;GAC7C,IAAI,KAAK,QAAQ,KAAK,yBAAyB,IAAI,eAAe,EAAE,QAAQ;EAC9E;EAGA,QAAQ,OAAO,MAAM,mBAAmB,UAAU,yBAAyB,WAAW,OAAO;EAE7F,MAAM,UAAU,gBAAgB,SAAS;EACzC,MAAM,YAAc,KAA4C,KAAkB,CAAC;EAEnF,YACE;GACE,MAAM;GACN;GACA;GACA,OAAO;GACP;EACF,GACA,QACA,EACE,YAAY,YAAY;GACtB,MAAM,cAAc;GAQpB,MAAM,EAAE,sBAAsB,MAAM,OAAO;GAC3C,MAAM,uBAAuB;GAC7B,MAAM,kBAAkB;EAC1B,EACF,CACF;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"codex-B_AMB6JM.js","names":[],"sources":["../src/codex.ts"],"sourcesContent":["import process from \"node:process\"\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\n\nimport { enableFileLogging } from \"./lib/file-log-reporter\"\nimport { launchChild } from \"./lib/launch\"\nimport { listModelsForEndpoint } from \"./lib/model-validation\"\nimport {\n DEFAULT_CODEX_MODEL,\n DEFAULT_CODEX_MODEL_FALLBACKS,\n} from \"./lib/port\"\nimport {\n getCodexEnvVars,\n parseSharedArgs,\n setupAndServe,\n sharedServerArgs,\n} from \"./lib/server-setup\"\nimport { runSelfUpdate } from \"./lib/self-update\"\nimport { state } from \"./lib/state\"\nimport { toolbeltEnabled } from \"./lib/toolbelt\"\nimport { provisionToolbelt } from \"./lib/toolbelt/provision\"\nimport { colbertDegradedWarning, provisionAndIndexColbert } from \"./lib/colbert\"\nimport { startKeepAwake, stopKeepAwake } from \"./lib/keep-awake\"\nimport { warmTreeSitterPool } from \"./lib/tree-sitter-pool/pool\"\nimport { provisionBrowserAssets } from \"./lib/browser-mcp/provision\"\nimport { hasSupportedBrowserInstalled } from \"./lib/browser-mcp/browser-detect\"\nimport { disposeBluebirdClients } from \"./lib/bluebird-client\"\nimport { resolveCodexModel, resolveModel } from \"./lib/utils\"\n\nexport const codex = defineCommand({\n meta: {\n name: \"codex\",\n description: \"Start the proxy server and launch Codex CLI\",\n },\n args: {\n ...sharedServerArgs,\n model: {\n alias: \"m\",\n type: \"string\",\n description: \"Override the default model for Codex CLI\",\n },\n },\n async run({ args }) {\n if (!process.stdout.isTTY) {\n consola.error(\"The codex subcommand requires a TTY (interactive terminal).\")\n process.exit(1)\n }\n\n const parsed = parseSharedArgs(args as unknown as Record<string, unknown>)\n\n let server: Awaited<ReturnType<typeof setupAndServe>>[\"server\"]\n let serverUrl: string\n try {\n const result = await setupAndServe({\n ...parsed,\n port: parsed.port, // undefined = random port\n silent: true,\n })\n server = result.server\n serverUrl = result.serverUrl\n } catch (error) {\n consola.error(\"Failed to start server:\", error instanceof Error ? error.message : error)\n process.exit(1)\n }\n\n // Best-effort self-update (detached, applies next launch).\n void runSelfUpdate({ selfUpdate: args[\"self-update\"] !== false })\n\n // Materialize the LLM toolbelt in the background (PATH prepend is in\n // getCodexEnvVars). Best-effort; never blocks launch.\n if (toolbeltEnabled()) {\n void provisionToolbelt().catch(() => {})\n }\n\n // Best-effort ColBERT semantic-search provision + background index of\n // the launch cwd. Opt-IN via --search (no-op otherwise); never blocks\n // launch, never throws.\n void provisionAndIndexColbert()\n\n // Surface a terminally-failed semantic index to the HUMAN (see the note\n // in claude.ts). Fire-and-forget; lexical search still works.\n void colbertDegradedWarning(undefined, { logsToFile: true })\n .then((warning) => {\n if (warning) process.stderr.write(`${warning}\\n`)\n })\n .catch(() => {})\n\n // Best-effort, bounded launch warm-up: ready one tree-sitter worker.\n // Opt out with GH_ROUTER_DISABLE_TS_POOL_WARMUP=1.\n void warmTreeSitterPool()\n\n // Best-effort: keep the machine awake while the proxy/Codex session\n // runs (win32 default-on; opt out GH_ROUTER_DISABLE_KEEP_AWAKE=1).\n // Self-registered SIGINT/SIGTERM/exit reaper releases the assertion.\n startKeepAwake()\n\n // Best-effort: materialize the browser extension + bridge into the\n // stable app-dir and stamp the running version. Gated inline (browse\n // opt-in + a supported browser) rather than via browserToolsEnabled()\n // so the codex command path doesn't eagerly pull the compressor /\n // worker-agent graph. Never blocks launch, never throws.\n const browseOptIn =\n state.browseEnabled || process.env.GH_ROUTER_ENABLE_BROWSE === \"1\"\n if (browseOptIn && hasSupportedBrowserInstalled()) {\n void provisionBrowserAssets().catch((err) =>\n consola.debug(\"Browser extension provisioning failed:\", err),\n )\n }\n\n const usingDefault = !args.model\n const requestedModel = args.model ?? DEFAULT_CODEX_MODEL\n\n // Resolve model before printing success message (so we show the actual model)\n // but enable file logging first so resolution warnings go to file, not terminal\n enableFileLogging()\n\n let codexModel = resolveCodexModel(requestedModel)\n if (codexModel !== requestedModel) {\n consola.info(`Model \"${requestedModel}\" resolved to \"${codexModel}\"`)\n }\n\n // For the implicit-default path only: honor the explicit fallback order\n // (DEFAULT_CODEX_MODEL, then DEFAULT_CODEX_MODEL_FALLBACKS led by gpt-5.5)\n // by cache presence BEFORE resolveCodexModel's codex-slug-preferring\n // \"best /responses model\" safety net. `resolveModel` (NOT resolveCodexModel)\n // walks the chain, so the codex-slug preference can't shadow an\n // earlier-in-chain named fallback (e.g. gpt-5.5) that IS present. The\n // resolveCodexModel result above stays as the FINAL safety net, used only\n // when none of the named chain entries is in the catalog.\n if (usingDefault && state.models) {\n const inCache = (id: string) =>\n state.models?.data.some((m) => m.id === id) ?? false\n const firstPresent = [DEFAULT_CODEX_MODEL, ...DEFAULT_CODEX_MODEL_FALLBACKS]\n .map((id) => resolveModel(id))\n .find((id) => inCache(id))\n if (firstPresent) {\n if (firstPresent !== codexModel) {\n consola.info(\n `Default model \"${DEFAULT_CODEX_MODEL}\" not in your Copilot model list; falling back to \"${firstPresent}\".`,\n )\n }\n codexModel = firstPresent\n }\n }\n\n // Validate model exists in Copilot model list\n const modelEntry = state.models?.data.find((m) => m.id === codexModel)\n if (!modelEntry) {\n const available = listModelsForEndpoint(\"/responses\")\n consola.warn(\n `Model \"${codexModel}\" not found. Available codex models: ${available.join(\", \")}`,\n )\n } else {\n const ctx = modelEntry.capabilities?.limits?.max_context_window_tokens\n if (ctx) consola.info(`Model context window: ${ctx.toLocaleString()} tokens`)\n }\n\n // Print to stderr directly — consola's terminal reporter is already gone\n process.stderr.write(`Server ready on ${serverUrl}, launching Codex CLI (${codexModel})...\\n`)\n\n const envVars = getCodexEnvVars(serverUrl)\n const extraArgs = ((args as unknown as Record<string, unknown>)._ as string[]) ?? []\n\n launchChild(\n {\n kind: \"codex\",\n envVars,\n extraArgs,\n model: codexModel,\n serverUrl,\n },\n server,\n {\n onShutdown: async () => {\n await stopKeepAwake()\n // Dynamic, like `claude.ts` and `pi.ts` do for the same call: a\n // static import of `ado-tools` would pull the whole non-persona MCP\n // registry (and the worker/orchestration modules behind it) into the\n // Codex CLI's import graph for one shutdown-time call. The client\n // module has a second, static importer in `serve.ts`, which already\n // loads that registry — this import is the one that would be pure\n // weight.\n const { disposeAdoClients } = await import(\"./lib/ado-tools\")\n await disposeBluebirdClients()\n await disposeAdoClients()\n },\n },\n )\n },\n})\n"],"mappings":";;;;;;;;;;;AA8BA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;EACJ,GAAG;EACH,OAAO;GACL,OAAO;GACP,MAAM;GACN,aAAa;EACf;CACF;CACA,MAAM,IAAI,EAAE,QAAQ;EAClB,IAAI,CAAC,QAAQ,OAAO,OAAO;GACzB,QAAQ,MAAM,6DAA6D;GAC3E,QAAQ,KAAK,CAAC;EAChB;EAEA,MAAM,SAAS,gBAAgB,IAA0C;EAEzE,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,MAAM,SAAS,MAAM,cAAc;IACjC,GAAG;IACH,MAAM,OAAO;IACb,QAAQ;GACV,CAAC;GACD,SAAS,OAAO;GAChB,YAAY,OAAO;EACrB,SAAS,OAAO;GACd,QAAQ,MAAM,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,KAAK;G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F;EACF,OAAO;GACL,MAAM,MAAM,WAAW,cAAc,QAAQ;GAC7C,IAAI,KAAK,QAAQ,KAAK,yBAAyB,IAAI,eAAe,EAAE,QAAQ;EAC9E;EAGA,QAAQ,OAAO,MAAM,mBAAmB,UAAU,yBAAyB,WAAW,OAAO;EAE7F,MAAM,UAAU,gBAAgB,SAAS;EACzC,MAAM,YAAc,KAA4C,KAAkB,CAAC;EAEnF,YACE;GACE,MAAM;GACN;GACA;GACA,OAAO;GACP;EACF,GACA,QACA,EACE,YAAY,YAAY;GACtB,MAAM,cAAc;GAQpB,MAAM,EAAE,sBAAsB,MAAM,OAAO;GAC3C,MAAM,uBAAuB;GAC7B,MAAM,kBAAkB;EAC1B,EACF,CACF;CACF;AACF,CAAC"}
@@ -1,4 +1,4 @@
1
- import { r as aicTotalCredits } from "./aic-ledger-BuFrsGur.js";
1
+ import { r as aicTotalCredits } from "./aic-ledger-_mvGW2Ev.js";
2
2
  //#region src/lib/copilot-discount.ts
3
3
  /** USD value of one AI credit (GitHub's published conversion). */
4
4
  const USD_PER_AIC_CREDIT = .01;
@@ -222,4 +222,4 @@ function formatCount(n) {
222
222
  //#endregion
223
223
  export { formatDiscountedCostTable as n, discountedUsdForSnapshot as t };
224
224
 
225
- //# sourceMappingURL=copilot-discount-Bsmv_3OX.js.map
225
+ //# sourceMappingURL=copilot-discount-BuDbQOHq.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-discount-Bsmv_3OX.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-6.1-sol\": row(1.0, \"unmeasured: default no discount (do not carry 0.28 without spend data)\"),\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 \"grok-4.7\": row(1.0, \"portal default, carried from grok-4.6\"),\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,GAAK,wEAAwE;CAChG,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,YAAY,IAAI,GAAK,uCAAuC;CAC5D,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;;;;;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;CACzD,IAAI,KAAK,KAAM,OAAO,IAAI,IAAI,IAAA,CAAM,QAAQ,CAAC,EAAE;CAC/C,OAAO,GAAG;AACZ"}
1
+ {"version":3,"file":"copilot-discount-BuDbQOHq.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-6.1-sol\": row(1.0, \"unmeasured: default no discount (do not carry 0.28 without spend data)\"),\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 \"grok-4.7\": row(1.0, \"portal default, carried from grok-4.6\"),\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,GAAK,wEAAwE;CAChG,eAAe,IAAI,KAAM,wDAAwD;CACjF,mBAAmB,IAAI,KAAM,2CAA2C;CACxE,iBAAiB,IAAI,KAAM,oEAAoE;CAC/F,mBAAmB,IAAI,KAAM,0BAA0B;CACvD,iBAAiB,IAAI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,UAAU,GACpC,IAAI,KAAK,IAAI,GAAG,IAAI,EAAE,CAAC,KAAK,MAAM;EAEpC,OAAO;CACT,CAAC;CACD,MAAM,UAAU,UACd,MACG,KAAK,GAAG,MACP,EAAE,UAAU,SAAS,EAAE,KAAK,OAAO,OAAO,EAAE,IAAI,EAAE,KAAK,SAAS,OAAO,EAAE,CAC3E,CAAC,CACA,KAAK,IAAI;CAOd,OAAO;EALL;EACA,OAAO,MAAM;EACb,GAAG,KAAK,IAAI,MAAM;EAClB,OAAO,UAAU;CAER,CAAC,CAAC,KAAK,IAAI;AACxB;;AAGA,SAAS,YAAY,GAAmB;CACtC,IAAI,KAAK,KAAW,OAAO,IAAI,IAAI,IAAA,CAAW,QAAQ,CAAC,EAAE;CACzD,IAAI,KAAK,KAAM,OAAO,IAAI,IAAI,IAAA,CAAM,QAAQ,CAAC,EAAE;CAC/C,OAAO,GAAG;AACZ"}
@@ -1,4 +1,4 @@
1
- import { t as PATHS } from "./paths-BSI_EtDT.js";
1
+ import { t as PATHS } from "./paths-C5477RGC.js";
2
2
  import { defineCommand } from "citty";
3
3
  import consola from "consola";
4
4
  import fs from "node:fs/promises";
@@ -78,4 +78,4 @@ const debug = defineCommand({
78
78
  //#endregion
79
79
  export { debug };
80
80
 
81
- //# sourceMappingURL=debug-DkNTuErv.js.map
81
+ //# sourceMappingURL=debug-DL2JsRqY.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"debug-DkNTuErv.js","names":[],"sources":["../src/debug.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\n\nimport { PATHS } from \"./lib/paths\"\n\ninterface DebugInfo {\n version: string\n runtime: {\n name: string\n version: string\n platform: string\n arch: string\n }\n paths: {\n APP_DIR: string\n GITHUB_TOKEN_PATH: string\n }\n tokenExists: boolean\n}\n\ninterface RunDebugOptions {\n json: boolean\n}\n\nasync function getPackageVersion(): Promise<string> {\n try {\n const packageJsonPath = new URL(\"../package.json\", import.meta.url).pathname\n // @ts-expect-error https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v59.0.1/docs/rules/prefer-json-parse-buffer.md\n // JSON.parse() can actually parse buffers\n const packageJson = JSON.parse(await fs.readFile(packageJsonPath)) as {\n version: string\n }\n return packageJson.version\n } catch {\n return \"unknown\"\n }\n}\n\nfunction getRuntimeInfo() {\n const isBun = typeof Bun !== \"undefined\"\n\n return {\n name: isBun ? \"bun\" : \"node\",\n version: isBun ? Bun.version : process.version.slice(1),\n platform: os.platform(),\n arch: os.arch(),\n }\n}\n\nasync function checkTokenExists(): Promise<boolean> {\n try {\n const stats = await fs.stat(PATHS.GITHUB_TOKEN_PATH)\n if (!stats.isFile()) return false\n\n const content = await fs.readFile(PATHS.GITHUB_TOKEN_PATH, \"utf8\")\n return content.trim().length > 0\n } catch {\n return false\n }\n}\n\nasync function getDebugInfo(): Promise<DebugInfo> {\n const [version, tokenExists] = await Promise.all([\n getPackageVersion(),\n checkTokenExists(),\n ])\n\n return {\n version,\n runtime: getRuntimeInfo(),\n paths: {\n APP_DIR: PATHS.APP_DIR,\n GITHUB_TOKEN_PATH: PATHS.GITHUB_TOKEN_PATH,\n },\n tokenExists,\n }\n}\n\nfunction printDebugInfoPlain(info: DebugInfo): void {\n consola.info(`github-router debug\n\nVersion: ${info.version}\nRuntime: ${info.runtime.name} ${info.runtime.version} (${info.runtime.platform} ${info.runtime.arch})\n\nPaths:\n- APP_DIR: ${info.paths.APP_DIR}\n- GITHUB_TOKEN_PATH: ${info.paths.GITHUB_TOKEN_PATH}\n\nToken exists: ${info.tokenExists ? \"Yes\" : \"No\"}`)\n}\n\nfunction printDebugInfoJson(info: DebugInfo): void {\n console.log(JSON.stringify(info, null, 2))\n}\n\nexport async function runDebug(options: RunDebugOptions): Promise<void> {\n const debugInfo = await getDebugInfo()\n\n if (options.json) {\n printDebugInfoJson(debugInfo)\n } else {\n printDebugInfoPlain(debugInfo)\n }\n}\n\nexport const debug = defineCommand({\n meta: {\n name: \"debug\",\n description: \"Print debug information about the application\",\n },\n args: {\n json: {\n type: \"boolean\",\n default: false,\n description: \"Output debug information as JSON\",\n },\n },\n run({ args }) {\n return runDebug({\n json: args.json,\n })\n },\n})\n"],"mappings":";;;;;;AA4BA,eAAe,oBAAqC;CAClD,IAAI;EACF,MAAM,kBAAkB,IAAI,IAAI,mBAAmB,YAAY,GAAG,CAAC,CAAC;EAMpE,OAHoB,KAAK,MAAM,MAAM,GAAG,SAAS,eAAe,CAG/C,CAAC,CAAC;CACrB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,iBAAiB;CACxB,MAAM,QAAQ,OAAO,QAAQ;CAE7B,OAAO;EACL,MAAM,QAAQ,QAAQ;EACtB,SAAS,QAAQ,IAAI,UAAU,QAAQ,QAAQ,MAAM,CAAC;EACtD,UAAU,GAAG,SAAS;EACtB,MAAM,GAAG,KAAK;CAChB;AACF;AAEA,eAAe,mBAAqC;CAClD,IAAI;EAEF,IAAI,EAAC,MADe,GAAG,KAAK,MAAM,iBAAiB,EAAA,CACxC,OAAO,GAAG,OAAO;EAG5B,QAAO,MADe,GAAG,SAAS,MAAM,mBAAmB,MAAM,EAAA,CAClD,KAAK,CAAC,CAAC,SAAS;CACjC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,eAAmC;CAChD,MAAM,CAAC,SAAS,eAAe,MAAM,QAAQ,IAAI,CAC/C,kBAAkB,GAClB,iBAAiB,CACnB,CAAC;CAED,OAAO;EACL;EACA,SAAS,eAAe;EACxB,OAAO;GACL,SAAS,MAAM;GACf,mBAAmB,MAAM;EAC3B;EACA;CACF;AACF;AAEA,SAAS,oBAAoB,MAAuB;CAClD,QAAQ,KAAK;;WAEJ,KAAK,QAAQ;WACb,KAAK,QAAQ,KAAK,GAAG,KAAK,QAAQ,QAAQ,IAAI,KAAK,QAAQ,SAAS,GAAG,KAAK,QAAQ,KAAK;;;aAGvF,KAAK,MAAM,QAAQ;uBACT,KAAK,MAAM,kBAAkB;;gBAEpC,KAAK,cAAc,QAAQ,MAAM;AACjD;AAEA,SAAS,mBAAmB,MAAuB;CACjD,QAAQ,IAAI,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAC3C;AAEA,eAAsB,SAAS,SAAyC;CACtE,MAAM,YAAY,MAAM,aAAa;CAErC,IAAI,QAAQ,MACV,mBAAmB,SAAS;MAE5B,oBAAoB,SAAS;AAEjC;AAEA,MAAa,QAAQ,cAAc;CACjC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM,EACJ,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;CACf,EACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,SAAS,EACd,MAAM,KAAK,KACb,CAAC;CACH;AACF,CAAC"}
1
+ {"version":3,"file":"debug-DL2JsRqY.js","names":[],"sources":["../src/debug.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { defineCommand } from \"citty\"\nimport consola from \"consola\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\n\nimport { PATHS } from \"./lib/paths\"\n\ninterface DebugInfo {\n version: string\n runtime: {\n name: string\n version: string\n platform: string\n arch: string\n }\n paths: {\n APP_DIR: string\n GITHUB_TOKEN_PATH: string\n }\n tokenExists: boolean\n}\n\ninterface RunDebugOptions {\n json: boolean\n}\n\nasync function getPackageVersion(): Promise<string> {\n try {\n const packageJsonPath = new URL(\"../package.json\", import.meta.url).pathname\n // @ts-expect-error https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v59.0.1/docs/rules/prefer-json-parse-buffer.md\n // JSON.parse() can actually parse buffers\n const packageJson = JSON.parse(await fs.readFile(packageJsonPath)) as {\n version: string\n }\n return packageJson.version\n } catch {\n return \"unknown\"\n }\n}\n\nfunction getRuntimeInfo() {\n const isBun = typeof Bun !== \"undefined\"\n\n return {\n name: isBun ? \"bun\" : \"node\",\n version: isBun ? Bun.version : process.version.slice(1),\n platform: os.platform(),\n arch: os.arch(),\n }\n}\n\nasync function checkTokenExists(): Promise<boolean> {\n try {\n const stats = await fs.stat(PATHS.GITHUB_TOKEN_PATH)\n if (!stats.isFile()) return false\n\n const content = await fs.readFile(PATHS.GITHUB_TOKEN_PATH, \"utf8\")\n return content.trim().length > 0\n } catch {\n return false\n }\n}\n\nasync function getDebugInfo(): Promise<DebugInfo> {\n const [version, tokenExists] = await Promise.all([\n getPackageVersion(),\n checkTokenExists(),\n ])\n\n return {\n version,\n runtime: getRuntimeInfo(),\n paths: {\n APP_DIR: PATHS.APP_DIR,\n GITHUB_TOKEN_PATH: PATHS.GITHUB_TOKEN_PATH,\n },\n tokenExists,\n }\n}\n\nfunction printDebugInfoPlain(info: DebugInfo): void {\n consola.info(`github-router debug\n\nVersion: ${info.version}\nRuntime: ${info.runtime.name} ${info.runtime.version} (${info.runtime.platform} ${info.runtime.arch})\n\nPaths:\n- APP_DIR: ${info.paths.APP_DIR}\n- GITHUB_TOKEN_PATH: ${info.paths.GITHUB_TOKEN_PATH}\n\nToken exists: ${info.tokenExists ? \"Yes\" : \"No\"}`)\n}\n\nfunction printDebugInfoJson(info: DebugInfo): void {\n console.log(JSON.stringify(info, null, 2))\n}\n\nexport async function runDebug(options: RunDebugOptions): Promise<void> {\n const debugInfo = await getDebugInfo()\n\n if (options.json) {\n printDebugInfoJson(debugInfo)\n } else {\n printDebugInfoPlain(debugInfo)\n }\n}\n\nexport const debug = defineCommand({\n meta: {\n name: \"debug\",\n description: \"Print debug information about the application\",\n },\n args: {\n json: {\n type: \"boolean\",\n default: false,\n description: \"Output debug information as JSON\",\n },\n },\n run({ args }) {\n return runDebug({\n json: args.json,\n })\n },\n})\n"],"mappings":";;;;;;AA4BA,eAAe,oBAAqC;CAClD,IAAI;EACF,MAAM,kBAAkB,IAAI,IAAI,mBAAmB,YAAY,GAAG,CAAC,CAAC;EAMpE,OAHoB,KAAK,MAAM,MAAM,GAAG,SAAS,eAAe,CAG/C,CAAC,CAAC;CACrB,Q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AM,EACJ,MAAM;EACJ,MAAM;EACN,SAAS;EACT,aAAa;CACf,EACF;CACA,IAAI,EAAE,QAAQ;EACZ,OAAO,SAAS,EACd,MAAM,KAAK,KACb,CAAC;CACH;AACF,CAAC"}
@@ -0,0 +1 @@
1
+ export { C as runWorkerAgent } from "./peer-mcp-personas-BOgR46nM.js";
@@ -1,7 +1,7 @@
1
- import { t as PATHS } from "./paths-BSI_EtDT.js";
1
+ import { t as PATHS } from "./paths-C5477RGC.js";
2
2
  import { s as resolveExecutable } from "./exec-Bf8g_bIR.js";
3
- import { l as repoFingerprint, u as repoRoot } from "./stop-gate-policy-CoR8xKNQ.js";
4
- import { p as resolveSealedGate } from "./stop-gate-hook-CC7VWkZM.js";
3
+ import { l as repoFingerprint, u as repoRoot } from "./stop-gate-policy-Dx9c98_d.js";
4
+ import { p as resolveSealedGate } from "./stop-gate-hook-DnLC09Lg.js";
5
5
  import { existsSync, promises } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { createHash } from "node:crypto";
@@ -606,7 +606,7 @@ async function discoverGateCommands(cwd, opts) {
606
606
  if (files.length === 0) return null;
607
607
  let result;
608
608
  try {
609
- const { runWorkerAgent } = await import("./engine-CmhUwYI5.js");
609
+ const { runWorkerAgent } = await import("./engine-D3oNrF6Z.js");
610
610
  result = await runWorkerAgent({
611
611
  mode: "explore",
612
612
  workspace: root,
@@ -632,4 +632,4 @@ async function discoverGateCommands(cwd, opts) {
632
632
  //#endregion
633
633
  export { checksForDescriptor as a, writeDiscoveredGate as i, readDiscoveredGate as n, descriptorHash as o, sourcesHash as r, parseGateDescriptor as s, discoverGateCommands as t };
634
634
 
635
- //# sourceMappingURL=gate-discovery-NNQg0t0H.js.map
635
+ //# sourceMappingURL=gate-discovery-CXE-7VcM.js.map