github-router 0.3.350 → 0.3.352

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 (146) hide show
  1. package/NOTICE +72 -0
  2. package/README.md +19 -0
  3. package/dist/ado-tools-xbuVU7YN.js +1 -0
  4. package/dist/{aic-ledger-D4oMcg7c.js → aic-ledger-BdvCgRmx.js} +3 -3
  5. package/dist/{aic-ledger-D4oMcg7c.js.map → aic-ledger-BdvCgRmx.js.map} +1 -1
  6. package/dist/{aic-statusline-settings-DCFywz3N.js → aic-statusline-settings-LnoxjBPe.js} +2 -2
  7. package/dist/{aic-statusline-settings-DCFywz3N.js.map → aic-statusline-settings-LnoxjBPe.js.map} +1 -1
  8. package/dist/{attribution-settings-B9T-EsEs.js → attribution-settings-ul6VU6iP.js} +11 -650
  9. package/dist/attribution-settings-ul6VU6iP.js.map +1 -0
  10. package/dist/{auth-Cgsy2T0s.js → auth-a_1lXYZ1.js} +4 -4
  11. package/dist/{auth-Cgsy2T0s.js.map → auth-a_1lXYZ1.js.map} +1 -1
  12. package/dist/{bluebird-client-DpYl1YmJ.js → bluebird-client-ltPIiyJU.js} +1103 -499
  13. package/dist/bluebird-client-ltPIiyJU.js.map +1 -0
  14. package/dist/bluebird-client-mr3M67k-.js +1 -0
  15. package/dist/browser-bridge/index.js +116 -98
  16. package/dist/browser-ext/manifest.json +1 -1
  17. package/dist/{check-usage-26G2hw_F.js → check-usage-Bsbc-Sn6.js} +4 -4
  18. package/dist/{check-usage-26G2hw_F.js.map → check-usage-Bsbc-Sn6.js.map} +1 -1
  19. package/dist/claude-md-injection-BoXOsg7h.js +669 -0
  20. package/dist/claude-md-injection-BoXOsg7h.js.map +1 -0
  21. package/dist/{claude-BY4e9ueE.js → claude-xO1XW-Nn.js} +79 -51
  22. package/dist/claude-xO1XW-Nn.js.map +1 -0
  23. package/dist/{codex-BOugL-uX.js → codex-DzUR40JA.js} +10 -8
  24. package/dist/{codex-BOugL-uX.js.map → codex-DzUR40JA.js.map} +1 -1
  25. package/dist/{copilot-discount-CilBhKQW.js → copilot-discount-C3jfysK-.js} +2 -2
  26. package/dist/{copilot-discount-CilBhKQW.js.map → copilot-discount-C3jfysK-.js.map} +1 -1
  27. package/dist/{debug-CigFsS-h.js → debug-BtqbflcL.js} +2 -2
  28. package/dist/{debug-CigFsS-h.js.map → debug-BtqbflcL.js.map} +1 -1
  29. package/dist/engine-DwLIk1Zn.js +1 -0
  30. package/dist/{exec-MCU1H-KZ.js → exec-Bf8g_bIR.js} +27 -2
  31. package/dist/exec-Bf8g_bIR.js.map +1 -0
  32. package/dist/{gate-discovery-BFqulsWz.js → gate-discovery-Cvdko01z.js} +6 -6
  33. package/dist/{gate-discovery-BFqulsWz.js.map → gate-discovery-Cvdko01z.js.map} +1 -1
  34. package/dist/{get-copilot-usage-C_6ast5h.js → get-copilot-usage-0_S8pRWJ.js} +3 -3
  35. package/dist/{get-copilot-usage-C_6ast5h.js.map → get-copilot-usage-0_S8pRWJ.js.map} +1 -1
  36. package/dist/{hook-mcp-client-BRL_y-bz.js → hook-mcp-client-DERIkeR7.js} +5 -3
  37. package/dist/{hook-mcp-client-BRL_y-bz.js.map → hook-mcp-client-DERIkeR7.js.map} +1 -1
  38. package/dist/hooks.mjs +10998 -6840
  39. package/dist/hooks.sha256 +1 -1
  40. package/dist/{index-cmd-DXYWgKS6.js → index-cmd-CJXUOH4q.js} +5 -5
  41. package/dist/{index-cmd-DXYWgKS6.js.map → index-cmd-CJXUOH4q.js.map} +1 -1
  42. package/dist/{internal-aic-status-lM0YNDaH.js → internal-aic-status-Dmi2bCsR.js} +4 -4
  43. package/dist/{internal-aic-status-lM0YNDaH.js.map → internal-aic-status-Dmi2bCsR.js.map} +1 -1
  44. package/dist/{internal-artifact-open-DErO3WpR.js → internal-artifact-open-C67gDjKo.js} +2 -2
  45. package/dist/{internal-artifact-open-DErO3WpR.js.map → internal-artifact-open-C67gDjKo.js.map} +1 -1
  46. package/dist/{internal-fast-dispatch-guard-DRsZJ-Rg.js → internal-fast-dispatch-guard-BQm1MI9d.js} +2 -2
  47. package/dist/{internal-fast-dispatch-guard-DRsZJ-Rg.js.map → internal-fast-dispatch-guard-BQm1MI9d.js.map} +1 -1
  48. package/dist/internal-fast-dispatch-guard-Cv7zf0ZI.js +1 -0
  49. package/dist/{internal-first-mate-guard-BEwDjHfX.js → internal-first-mate-guard-BJvCsVlU.js} +3 -3
  50. package/dist/{internal-first-mate-guard-BEwDjHfX.js.map → internal-first-mate-guard-BJvCsVlU.js.map} +1 -1
  51. package/dist/internal-first-mate-guard-D-IQGiTs.js +1 -0
  52. package/dist/{internal-max-dispatch-guard-DSjJwVH2.js → internal-max-dispatch-guard-DkJixDmG.js} +7 -5
  53. package/dist/{internal-max-dispatch-guard-DSjJwVH2.js.map → internal-max-dispatch-guard-DkJixDmG.js.map} +1 -1
  54. package/dist/internal-max-dispatch-guard-T-M7DRIW.js +1 -0
  55. package/dist/{internal-plan-review-DbX-mr9i.js → internal-plan-review-DIvaBBUd.js} +4 -4
  56. package/dist/{internal-plan-review-DbX-mr9i.js.map → internal-plan-review-DIvaBBUd.js.map} +1 -1
  57. package/dist/internal-prompt-submit-6OXEdQCK.js +2 -0
  58. package/dist/internal-prompt-submit-B9MJxc3K.js +194 -0
  59. package/dist/internal-prompt-submit-B9MJxc3K.js.map +1 -0
  60. package/dist/{internal-rebrief-BH9PMJhF.js → internal-rebrief-zIdunX3R.js} +6 -6
  61. package/dist/{internal-rebrief-BH9PMJhF.js.map → internal-rebrief-zIdunX3R.js.map} +1 -1
  62. package/dist/{internal-session-bind-DxdVbJ7x.js → internal-session-bind-CQLDPuTx.js} +2 -2
  63. package/dist/{internal-session-bind-DxdVbJ7x.js.map → internal-session-bind-CQLDPuTx.js.map} +1 -1
  64. package/dist/{internal-stop-hook-DlGc9WwJ.js → internal-stop-hook-DGcRVh_2.js} +7 -7
  65. package/dist/{internal-stop-hook-DlGc9WwJ.js.map → internal-stop-hook-DGcRVh_2.js.map} +1 -1
  66. package/dist/{internal-stop-review-CORT3UGr.js → internal-stop-review-X7zRRhyc.js} +3 -3
  67. package/dist/{internal-stop-review-CORT3UGr.js.map → internal-stop-review-X7zRRhyc.js.map} +1 -1
  68. package/dist/{internal-worker-guard-C0FJ4b29.js → internal-worker-guard-wP3UN-3D.js} +2 -2
  69. package/dist/{internal-worker-guard-C0FJ4b29.js.map → internal-worker-guard-wP3UN-3D.js.map} +1 -1
  70. package/dist/{internal-workspace-header-tvJVAXpv.js → internal-workspace-header-DiUnkUeU.js} +2 -2
  71. package/dist/{internal-workspace-header-tvJVAXpv.js.map → internal-workspace-header-DiUnkUeU.js.map} +1 -1
  72. package/dist/lib/tree-sitter-pool/worker.js +1 -2
  73. package/dist/{lifecycle-BqWTXaeC.js → lifecycle-BJ83L0tz.js} +3 -3
  74. package/dist/{lifecycle-BqWTXaeC.js.map → lifecycle-BJ83L0tz.js.map} +1 -1
  75. package/dist/lifecycle-CVg2-zQ3.js +1 -0
  76. package/dist/lifecycle-Dk_BHtfz.js +1 -0
  77. package/dist/{lifecycle-kpLzHUgD.js → lifecycle-aApO0hZW.js} +2 -2
  78. package/dist/{lifecycle-kpLzHUgD.js.map → lifecycle-aApO0hZW.js.map} +1 -1
  79. package/dist/main.js +23 -23
  80. package/dist/{max-profile-contract--dAYkEG1.js → max-profile-contract-DQDEDCsR.js} +2 -2
  81. package/dist/{max-profile-contract--dAYkEG1.js.map → max-profile-contract-DQDEDCsR.js.map} +1 -1
  82. package/dist/{mcp-workspace-header-B77WqVFw.js → mcp-workspace-header-DBQugQlQ.js} +2 -2
  83. package/dist/{mcp-workspace-header-B77WqVFw.js.map → mcp-workspace-header-DBQugQlQ.js.map} +1 -1
  84. package/dist/{models-BGCeGVXl.js → models-JIvKAGn0.js} +3 -3
  85. package/dist/{models-BGCeGVXl.js.map → models-JIvKAGn0.js.map} +1 -1
  86. package/dist/{orchestration-Dkqv-iv0.js → orchestration-D-S_0GVt.js} +3 -3
  87. package/dist/{orchestration-Dkqv-iv0.js.map → orchestration-D-S_0GVt.js.map} +1 -1
  88. package/dist/paths-C9x5U3dO.js +1 -0
  89. package/dist/{paths-CpbTHKeP.js → paths-xTSEAWfN.js} +115 -22
  90. package/dist/paths-xTSEAWfN.js.map +1 -0
  91. package/dist/{peer-mcp-personas-BwwSNnBC.js → peer-mcp-personas-DDMKRFFG.js} +2350 -836
  92. package/dist/peer-mcp-personas-DDMKRFFG.js.map +1 -0
  93. package/dist/{pi-Dpw8Otxw.js → pi-jVNeQXWf.js} +362 -37
  94. package/dist/pi-jVNeQXWf.js.map +1 -0
  95. package/dist/{plan-review-hook-LfG01VMp.js → plan-review-hook-BQ29WGv7.js} +5 -5
  96. package/dist/{plan-review-hook-LfG01VMp.js.map → plan-review-hook-BQ29WGv7.js.map} +1 -1
  97. package/dist/{provision-9TAIgyL7.js → provision-BtYRtvrj.js} +26 -18
  98. package/dist/provision-BtYRtvrj.js.map +1 -0
  99. package/dist/{self-invocation-DIUyoRgL.js → self-invocation-Dr5zlbpM.js} +2 -2
  100. package/dist/{self-invocation-DIUyoRgL.js.map → self-invocation-Dr5zlbpM.js.map} +1 -1
  101. package/dist/{serve-BRKRWkd1.js → serve-CmgmxigM.js} +35 -17
  102. package/dist/serve-CmgmxigM.js.map +1 -0
  103. package/dist/{server-setup-DXVFE7bf.js → server-setup-DinOFWiC.js} +393 -42
  104. package/dist/server-setup-DinOFWiC.js.map +1 -0
  105. package/dist/{service-backend-7SPDLUB9.js → service-backend-DV1u5x0Q.js} +51 -23
  106. package/dist/service-backend-DV1u5x0Q.js.map +1 -0
  107. package/dist/{start-CoR3jqUR.js → start-Dgsaz0HM.js} +4 -4
  108. package/dist/{start-CoR3jqUR.js.map → start-Dgsaz0HM.js.map} +1 -1
  109. package/dist/{state-CVp30CBF.js → state-CfEVoqBM.js} +8 -1
  110. package/dist/{state-CVp30CBF.js.map → state-CfEVoqBM.js.map} +1 -1
  111. package/dist/{prompt-submit-hook-DzhmQRs_.js → static-context-pack-CyucviRD.js} +402 -4
  112. package/dist/static-context-pack-CyucviRD.js.map +1 -0
  113. package/dist/{stop-gate-hook-C9VNxmt1.js → stop-gate-hook-BYd0NruJ.js} +4 -4
  114. package/dist/{stop-gate-hook-C9VNxmt1.js.map → stop-gate-hook-BYd0NruJ.js.map} +1 -1
  115. package/dist/{stop-gate-policy-DQsfjnsx.js → stop-gate-policy-FGAfpfc-.js} +3 -3
  116. package/dist/{stop-gate-policy-DQsfjnsx.js.map → stop-gate-policy-FGAfpfc-.js.map} +1 -1
  117. package/dist/{token-s5Wd-Kwr.js → token-CTf5jCmP.js} +7 -5
  118. package/dist/{token-s5Wd-Kwr.js.map → token-CTf5jCmP.js.map} +1 -1
  119. package/dist/{worker-dispatch-lRhno09M.js → worker-dispatch-BjfROaic.js} +2 -2
  120. package/dist/{worker-dispatch-lRhno09M.js.map → worker-dispatch-BjfROaic.js.map} +1 -1
  121. package/docs/azure-mcp.md +453 -0
  122. package/docs/bluebird-search.md +96 -7
  123. package/package.json +22 -22
  124. package/dist/attribution-settings-B9T-EsEs.js.map +0 -1
  125. package/dist/bluebird-client-DpYl1YmJ.js.map +0 -1
  126. package/dist/bluebird-client-bn9Yv6Cb.js +0 -2
  127. package/dist/claude-BY4e9ueE.js.map +0 -1
  128. package/dist/engine-DZfLaVcf.js +0 -2
  129. package/dist/exec-MCU1H-KZ.js.map +0 -1
  130. package/dist/internal-fast-dispatch-guard-DeZ6KilC.js +0 -2
  131. package/dist/internal-first-mate-guard-CAefr6Ce.js +0 -2
  132. package/dist/internal-max-dispatch-guard-KmbYwh7h.js +0 -2
  133. package/dist/internal-prompt-submit-CA5Y4DWM.js +0 -2
  134. package/dist/internal-prompt-submit-UhfnM_qG.js +0 -573
  135. package/dist/internal-prompt-submit-UhfnM_qG.js.map +0 -1
  136. package/dist/lifecycle-DMRZswwc.js +0 -2
  137. package/dist/lifecycle-FT75ohVw.js +0 -2
  138. package/dist/paths-CpbTHKeP.js.map +0 -1
  139. package/dist/paths-Dfivvq21.js +0 -2
  140. package/dist/peer-mcp-personas-BwwSNnBC.js.map +0 -1
  141. package/dist/pi-Dpw8Otxw.js.map +0 -1
  142. package/dist/prompt-submit-hook-DzhmQRs_.js.map +0 -1
  143. package/dist/provision-9TAIgyL7.js.map +0 -1
  144. package/dist/serve-BRKRWkd1.js.map +0 -1
  145. package/dist/server-setup-DXVFE7bf.js.map +0 -1
  146. package/dist/service-backend-7SPDLUB9.js.map +0 -1
@@ -0,0 +1,669 @@
1
+ import { a as isUnderClaudeConfigMirror, t as PATHS } from "./paths-xTSEAWfN.js";
2
+ import { C as MAX_PARALLELISM_RULE } from "./max-profile-contract-DQDEDCsR.js";
3
+ import consola from "consola";
4
+ import path from "node:path";
5
+ import { randomBytes } from "node:crypto";
6
+ import fs from "node:fs/promises";
7
+ //#region src/lib/claude-md-injection.ts
8
+ /**
9
+ * Marker fences for each injection block. The literal text of each
10
+ * fence is intentionally specific enough that a content collision with
11
+ * user prose is implausible. Each block's parser only matches its own
12
+ * marker pair, so blocks operate independently.
13
+ *
14
+ * Writer-side guard: the injector refuses to write a snippet that
15
+ * itself contains its own marker literals (that would create
16
+ * ambiguous state on the next launch where the inner literal would
17
+ * parse as a new open or close marker).
18
+ */
19
+ const PEER_MARKER_OPEN = "<!-- gh-router peer-mcp awareness — auto-injected, regenerated per launch -->";
20
+ const PEER_MARKER_CLOSE = "<!-- /gh-router peer-mcp awareness -->";
21
+ const STYLE_MARKER_OPEN = "<!-- gh-router style directive — auto-injected, regenerated per launch -->";
22
+ const STYLE_MARKER_CLOSE = "<!-- /gh-router style directive -->";
23
+ const OPERATING_MARKER_OPEN = "<!-- gh-router operating defaults — auto-injected, regenerated per launch -->";
24
+ const OPERATING_MARKER_CLOSE = "<!-- /gh-router operating defaults -->";
25
+ const TOOLBELT_MARKER_OPEN = "<!-- gh-router toolbelt awareness — auto-injected, regenerated per launch -->";
26
+ const TOOLBELT_MARKER_CLOSE = "<!-- /gh-router toolbelt awareness -->";
27
+ const ARTIFACT_MARKER_OPEN = "<!-- gh-router artifact-panel directive — auto-injected when in an ai-or-die tab -->";
28
+ const ARTIFACT_MARKER_CLOSE = "<!-- /gh-router artifact-panel directive -->";
29
+ function ARTIFACT_PANEL_DIRECTIVE(peersKey = "peers") {
30
+ const toolPrefix = `mcp__${peersKey}__artifact_`;
31
+ return `## Review in the artifact panel (HTML by default)
32
+
33
+ You are running inside an ai-or-die tab, so the \`${toolPrefix}*\` tools drive a live human-review panel. 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. Plan-mode plans are auto-rendered to HTML and opened for you; skip the panel only for trivial one-line answers. 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.`;
34
+ }
35
+ /**
36
+ * Writing / communication style directive injected at the TOP of the
37
+ * mirrored CLAUDE.md so every spawned agent (main, Agent-tool subagent,
38
+ * agent-teams teammate) reads it before the user's own CLAUDE.md body.
39
+ *
40
+ * Self-referentially compliant: the directive itself uses no em
41
+ * dashes and does not mention any Claude / Anthropic attribution.
42
+ */
43
+ const STYLE_DIRECTIVE = "Write concisely without losing detail. Use a natural human voice. Avoid em dashes. Do not attribute work to Claude, AI, LLM, or Anthropic anywhere (commits, PRs, issues, code, comments, docs).";
44
+ /**
45
+ * Operating-defaults directive injected at the TOP of the mirrored CLAUDE.md.
46
+ * The main agent's system prompt (`--append-system-prompt`) gets
47
+ * OPERATING_DEFAULTS_DIGEST instead, with this full statement available through
48
+ * CLAUDE.md. Three defaults, layered under the user's own
49
+ * direction and the domain's standards as addons (on a direct conflict the
50
+ * user's direction wins, then the domain standard, then the default below):
51
+ *
52
+ * 1. Orchestrate (strong default): delegate the heavy / parallel /
53
+ * context-heavy work to the right subagent / worker / model, keeping the
54
+ * main context free to reason and collaborate with the user, while still
55
+ * doing trivial / surgical / last-mile work directly (delegating that
56
+ * would only add relay-fidelity loss + latency).
57
+ * 2. Adversarial review: WHEN a peer critic earns its keep and, equally
58
+ * important, when reaching for one is ritual rather than review. Same
59
+ * failure shape the delegation default had: "consult a critic for
60
+ * non-trivial changes" is unfalsifiable in advance, so it collapses into
61
+ * either never (four of four unprimed agents) or always (worse than
62
+ * never). The discriminator is whether the conclusion still turns on
63
+ * judgment once the direct evidence is in: a consequential recommendation
64
+ * cannot be run, which is exactly where confabulation hides, while a
65
+ * tracing question a search already proved gains nothing from a second
66
+ * model re-deriving it. The roster, the lens-to-artifact match, the
67
+ * advisor-complements-rather-than-substitutes distinction, and the
68
+ * do-not-anchor-the-critic rule live here; the digest carries only the
69
+ * trigger and the ritual exclusion.
70
+ * 3. Excellence lens: the principles stated plainly and concretely (radical
71
+ * simplicity + real-user focus; whole-system first-principles thinking that
72
+ * anticipates scale; work back from the customer outcome). Named exemplars
73
+ * were dropped per the injected-surface review: a named entity is a dense,
74
+ * high-variance vector that pulls in persona mannerisms at top salience, and
75
+ * the guidance favors specific functional framing over comparison, so
76
+ * specificity carries the vividness instead.
77
+ * 4. Engineering excellence: quality / robustness / maintainability over
78
+ * development cost; reproduce a bug end-to-end (as a real user hits it)
79
+ * before fixing so the fix targets the real cause; a pixel-perfect UI bar;
80
+ * and fix any lint error / test failure / flake on sight, whoever caused it,
81
+ * folded into the current work rather than derailing the user's task (the
82
+ * scope guardrail keeps proactive quality from becoming yak-shaving). The
83
+ * digest carries a one-line form; the full statement lives here so it does
84
+ * not cost the context window every turn.
85
+ *
86
+ * Self-referentially compliant with the style directive: no em dashes, no
87
+ * Claude / Anthropic attribution.
88
+ *
89
+ * Availability-aware: four of the natives (`scout`, `implementer-fast`,
90
+ * `reviewer-fast`, and `general-purpose-fast`) are DROPPED rather than
91
+ * downgraded when no model in
92
+ * their chain resolves, so naming them unconditionally here would tell the lead to delegate
93
+ * to an agent that has no `.md` file and is absent from the Task
94
+ * `subagent_type` enum. Build the directive with
95
+ * `buildOperatingDefaultsDirective` and the same availability booleans used for
96
+ * the `.md` generation and the awareness snippet; the exported const below is
97
+ * the all-available form, kept for callers and tests that do not model a thin
98
+ * catalog.
99
+ */
100
+ /**
101
+ * Pipeline skills (`/gh-gather-context`, `/gh-plan`, `/gh-implement`,
102
+ * `/gh-swe-pipeline`) injected ONLY for `--swe` launches on pinned profiles
103
+ * (fast, max, cheap, cheap1m, cheapest, balanced). Standard is intentionally
104
+ * excluded. Without `--swe` the skill files are not written and this text is
105
+ * not referenced. Stages dispatch ONLY native subagents present on the
106
+ * profile roster (Explore, Plan where the profile provides one,
107
+ * General-Purpose, reviewer, implementer where provided), never worker-*
108
+ * MCP dispatchers. All roles run at the
109
+ * 200K default window (bare slugs, no 1M accounting) with advisory budgets:
110
+ * gather ~3 min per round (3 rounds max, 6 Explore per round); plan ~5 min
111
+ * via the profile-pinned Plan subagent where the profile provides one
112
+ * (the lead plans directly on cheapest/balanced; trivial asks exit
113
+ * planless);
114
+ * implement ~10 min per task (8 concurrent max, worktree:true only when
115
+ * parallel tasks need isolation); reviewer only on low-confidence or complex
116
+ * and risky changes, plus a General-Purpose fix pass for major reviewer
117
+ * findings.
118
+ */
119
+ const PIPELINE_SKILLS_AWARENESS = "Pipeline skills (all 200K default context, native subagents only, never worker-*). Prefer `/gh-swe-pipeline`: strict sequence, each stage completing before the next starts, user approval before implementation. Stages in order: (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; (2) `/gh-plan` AFTER context and BEFORE implementation: native Plan subagent plans non-trivial asks (trivial exits planless), ordered plan.md (~5 min), open questions, waits for user approval; (3) `/gh-implement` AFTER plan approval: bounded parallel General-Purpose subagents (implementer first on max; worktree:true if parallel tasks need isolation), reviewer only on low-confidence or risky changes, plus fix pass for major findings. Skip for trivial work. Never implement without an approved plan. Never overlap stages.";
120
+ /**
121
+ * Pipeline-skills awareness for the profiles without a `Plan` role
122
+ * (cheapest, balanced): the lead plans directly, so `/gh-plan` names the
123
+ * lead instead of a Plan dispatch. Every other stage is identical.
124
+ */
125
+ const PIPELINE_SKILLS_AWARENESS_NO_PLAN_AGENT = "Pipeline skills (all 200K default context, native subagents only, never worker-*). Prefer `/gh-swe-pipeline`: strict sequence, each stage completing before the next starts, user approval before implementation. Stages in order: (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; (2) `/gh-plan` AFTER context and BEFORE implementation: the lead plans directly (no Plan subagent on this profile; trivial exits planless), ordered plan.md (~5 min), open questions, waits for user approval; (3) `/gh-implement` AFTER plan approval: bounded parallel General-Purpose subagents (worktree:true if parallel tasks need isolation), reviewer only on low-confidence or risky changes, plus fix pass for major findings. Skip for trivial work. Never implement without an approved plan. Never overlap stages.";
126
+ /** Oxford-comma join: "a", "a and b", "a, b, and c". */
127
+ function joinClauses(parts) {
128
+ if (parts.length <= 1) return parts[0] ?? "";
129
+ if (parts.length === 2) return `${parts[0]} and ${parts[1]}`;
130
+ return `${parts.slice(0, -1).join(", ")}, and ${parts[parts.length - 1]}`;
131
+ }
132
+ /** The "Reach for X when Y" list, omitting any agent this launch did not emit.
133
+ *
134
+ * On a budget lead the coding AND review clauses swap order so the cheap tier
135
+ * leads and the frontier tier is named as the complexity escalation. Choosing a
136
+ * lighter lead is a decision to spend less while holding quality, and a roster
137
+ * that names the expensive `implementer` / `reviewer` first works against
138
+ * exactly that. This is ORDERING AND WORDING ONLY: no agent's model changes,
139
+ * and both frontier tiers stay named so work beyond the fast tier still has
140
+ * somewhere to go.
141
+ *
142
+ * Review gets the same treatment as implementation because the cost gap is the
143
+ * same shape: `reviewer` runs the pro tier (200/1200 per 1M) against
144
+ * `reviewer-fast`'s flash tier (75/375), and measured 2026-08-13 the flash
145
+ * model was also the FASTER of the two on every axis (tool-call p50 ~1.2s vs
146
+ * ~2.8s, TTFT ~1.9s vs ~3.7s, decode ~326 vs ~165 tok/s). So on a budget lead
147
+ * there is no quality-for-cost trade being hidden by leading with the cheap
148
+ * tier; reserve `reviewer` for the higher-stakes assessment it is there for. */
149
+ function buildNativeReachClauses(opts) {
150
+ if (opts.profile === "fast" || opts.profile === "cheap" || opts.profile === "cheap1m" || opts.profile === "cheapest" || opts.profile === "balanced") {
151
+ if (opts.profile === "cheapest") return joinClauses([
152
+ "`Explore` (Luna/high, cheap breadth) for discovery, dependency mapping, and convention tracking spanning more than a couple of files",
153
+ "`General-Purpose` (Luna/max, the heavy execution tier) for mixed, iterative, or multi-step execution",
154
+ "`reviewer` (Luna/max, the heavy verification tier) for independent adversarial verification, reproduction, and root-causing"
155
+ ]) + ". Delegate by value — cheap breadth to `Explore`, heavy execution to `General-Purpose`, verification to `reviewer`. All roles run at a 200K context window — prefer targeted reads (search, Grep, Read specific files) over full file reads";
156
+ if (opts.profile === "balanced") return joinClauses([
157
+ "`Explore` for broad repository discovery, dependency mapping, and convention tracking (launch in parallel)",
158
+ "`General-Purpose` for mixed, iterative, or multi-step execution tasks (delegate freely)",
159
+ "`reviewer` for independent adversarial verification, reproduction, and root-causing ONLY when genuinely behavior-changing (lead owns verification by default)"
160
+ ]) + ". All roles run at a 200K context window — prefer targeted reads (search, Grep, Read specific files) over full file reads";
161
+ const shared = joinClauses([
162
+ "`Explore` for broad repository discovery, dependency mapping, and convention tracking (launch in parallel)",
163
+ "`Plan` for architectural sequencing, interface contracts, migration risk, and runnable acceptance criteria (delegates discovery to `Explore`)",
164
+ "`General-Purpose` for mixed, iterative, or multi-step execution tasks (follows a Plan handoff when one exists)",
165
+ "`reviewer` for independent adversarial verification, reproduction, and root-causing after non-trivial changes"
166
+ ]);
167
+ if (opts.profile === "cheap") return `${shared}. All roles run at a 200K context window — prefer targeted reads (search, Grep, Read specific files) over full file reads`;
168
+ if (opts.profile === "cheap1m") return `${shared}. Subagents run at a 200K context window — brief them with targeted evidence and prefer targeted reads over full file reads`;
169
+ return shared;
170
+ }
171
+ const clauses = [];
172
+ const implementerFast = opts.implementerFastAvailable !== false;
173
+ const reviewerFast = opts.reviewerFastAvailable !== false;
174
+ if (opts.budgetLead === true && implementerFast) clauses.push("`implementer-fast` first for coding changes, since it is the cheaper and faster tier and this session is running a lighter lead", "`implementer` when the change needs judgment, its scope is ambiguous, or its complexity is beyond what the fast tier can carry");
175
+ else {
176
+ clauses.push("`implementer` for coding changes that need judgment or have ambiguous scope");
177
+ if (implementerFast) clauses.push("`implementer-fast` for well-specified, mechanical coding changes");
178
+ }
179
+ if (opts.budgetLead === true && reviewerFast) clauses.push("`reviewer-fast` first when something exists and you want it assessed, since it is the cheaper and faster review tier", "`reviewer` when the assessment is higher-stakes or needs deeper reproduction and root-causing than the fast tier can carry");
180
+ else {
181
+ clauses.push("`reviewer` when something exists and you want it assessed (including reproducing and root-causing a failure)");
182
+ if (reviewerFast) clauses.push("`reviewer-fast` for lower-stakes assessments");
183
+ }
184
+ clauses.push("`brainstorm` when you do not yet know which approach to take");
185
+ if (opts.scoutAvailable !== false) clauses.push("`scout` to find or understand something in the repo");
186
+ clauses.push("`scribe` for docs and ADRs that trail the code");
187
+ if (opts.generalPurposeFastAvailable !== false) clauses.push(opts.budgetLead === true ? "`general-purpose-fast` for work no specialist fits, in preference to carrying it inline yourself" : "`general-purpose-fast` for work no specialist fits");
188
+ return joinClauses(clauses);
189
+ }
190
+ /**
191
+ * Cheapest-only consult contract for the Luna lead (the FULL "when/how" copy,
192
+ * mirrored into CLAUDE.md).
193
+ *
194
+ * Lives in the injected operating-defaults prose rather than the advisor tool
195
+ * description (the "what"), per OpenAI guidance. Outcome-first decision rules,
196
+ * not a step procedure. Covers the four things a weak, over-confident model
197
+ * needs to place consults well:
198
+ * 1. a small, stated budget (8-10 calls) so each feels costly;
199
+ * 2. ANCHORS (when to spend) — genuine uncertainty, before committing, before
200
+ * presenting a plan;
201
+ * 3. DISQUALIFIERS (never spend) — anything evidence settles, or a moment
202
+ * owned by reviewer/oracle;
203
+ * 4. a DISCRIMINATOR assigning each moment to the right consultant.
204
+ * The digest carries only a short pointer (`CHEAPEST_CONSULT_CONTRACT_POINTER`)
205
+ * so the always-resident copy does not duplicate this block every turn.
206
+ */
207
+ const CHEAPEST_CONSULT_CONTRACT = "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";
208
+ /**
209
+ * Build the operating-defaults directive for one launch, naming only the
210
+ * natives that launch actually emitted.
211
+ *
212
+ * Callers must pass the SAME availability booleans they used for the `.md`
213
+ * generation and `buildPeerAwarenessSnippet`, so the three surfaces cannot
214
+ * disagree about which agents exist.
215
+ */
216
+ function buildOperatingDefaultsDirective(opts = {}) {
217
+ if (opts.profile === "max") {
218
+ const peersKey = opts.peersKey ?? opts.groupKeys?.peers ?? "peers";
219
+ const artifactClause = opts.artifactAvailable ? ` Live human review is available in the artifact panel via \`mcp__${peersKey}__artifact_*\`.` : "";
220
+ const pipelineClause = opts.sweEnabled === false ? "" : `\n\n${PIPELINE_SKILLS_AWARENESS}`;
221
+ return "## 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\nMax 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. " + MAX_PARALLELISM_RULE + " 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." + artifactClause + pipelineClause;
222
+ }
223
+ if (opts.profile === "fast" || opts.profile === "cheap" || opts.profile === "cheap1m" || opts.profile === "cheapest" || opts.profile === "balanced") {
224
+ const isCheap = opts.profile === "cheap" || opts.profile === "cheap1m";
225
+ const isCheapest = opts.profile === "cheapest";
226
+ const isBalanced = opts.profile === "balanced";
227
+ const profileLabel = isCheapest ? "Cheapest" : isCheap ? "Cheap" : isBalanced ? "Balanced" : "Fast";
228
+ const oracleDescriptor = isCheapest ? "GPT-6 Sol (200K/high)" : isCheap || isBalanced ? "Grok 4.6 (200K/medium)" : "exact Opus 5.5 (1M/high)";
229
+ const astraDescriptor = isCheap && !isCheapest ? "200K/medium" : "200K/high";
230
+ const expensiveModels = isCheapest || isBalanced ? "(reviewer, Oracle)" : "(Plan, reviewer, Oracle)";
231
+ const searchGuidance = opts.bluebirdEnabled === true ? "Search strategy: use Bluebird `code` search in `lexical` mode for indexed keyword queries and `semantic` mode for intent/concept questions. Bluebird failures remain visible and never fall back locally; `exact`, `regex`, and `ast` stay on the local live tree. `Explore` subagents read the narrowed files and return file:line conclusions; expensive models " + expensiveModels + " see only the synthesized subset, never raw search output. " : opts.semanticSearchAvailable === true ? "Search strategy (cheapest first): (1) LOCAL LEXICAL `code` search (mode:\"lexical\"/\"exact\", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys; (2) local ColBERT SEMANTIC `code` search for intent/concept questions where literal keywords may not appear, with lexical fallback while its index is unavailable; (3) `Explore` subagents read the narrowed files and return file:line conclusions — expensive models " + expensiveModels + " see only the synthesized subset, never raw search output. " : "Search strategy (cheapest first): LOCAL LEXICAL `code` search (mode:\"lexical\"/\"exact\", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys. `Explore` subagents read the narrowed files and return file:line conclusions — expensive models " + expensiveModels + " see only the synthesized subset, never raw search output. ";
232
+ if (opts.fastRuntimeAvailable === false) return `## 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)
233
+
234
+ ${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.`;
235
+ const peersKey = opts.peersKey ?? opts.groupKeys?.peers ?? "peers";
236
+ const searchKey = opts.groupKeys?.search ?? "search";
237
+ const browserKey = opts.groupKeys?.browser ?? "browser";
238
+ const workersKey = opts.groupKeys?.workers ?? "workers";
239
+ const browserClause = opts.browserToolsAvailable ?? opts.browseAvailable ? ` \`mcp__${browserKey}__*\` provides direct browser control.` : "";
240
+ const workerBrowseClause = opts.browseAvailable ? ` \`worker-browse\` runs delegated autonomous browsing tasks through \`mcp__${workersKey}__browse\`.` : "";
241
+ const artifactClause = opts.artifactAvailable ? ` \`mcp__${peersKey}__artifact_*\` provides human review in the artifact panel with auto-open on plan completion.` : "";
242
+ const astraClause = opts.astraAvailable && (opts.profile === "fast" || opts.profile === "cheap1m") ? ` \`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).` : "";
243
+ const pipeline = isCheapest ? `${profileLabel} launch profile. The lead owns the outcome and handles straightforward work directly. ` + buildNativeReachClauses(opts) + ". Handle trivial, surgical, single-file, or single-command tasks directly; you do not need to justify skipping delegation. `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. In plan mode, produce the plan and acceptance criteria directly and do not edit files; before presenting the final plan to the user, consult `advisor` once for a framing check. Work to your strengths as a fast, cost-efficient model: verify by execution rather than memory; before a non-trivial task, write a short plan (steps, files involved, the check settling each step) and execute it; persist through tool failures with a rephrased attempt before asking the user; stop searching when further results stop changing the answer; tag claims verified, inferred, or unverified — never state that something passes, compiles, or is covered without observed output. Delegation graph: the lead may invoke all three; `General-Purpose` may invoke `reviewer`; `Explore`, `reviewer`, and `worker-browse` cannot invoke native subagents.\n\nConsulting `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" : isBalanced ? `${profileLabel} launch profile. The lead coordinates execution across specialized native roles: ` + buildNativeReachClauses(opts) + ". Lead owns planning, implementation, and verification by default: in plan mode, produce the plan and acceptance criteria directly and do not edit files. Phase pipeline (budget gather, budget execution, expensive verification). GATHER: narrow scope first with `code_search` (lexical, then semantic when available) and `web` search to rule out hypotheses — cheapest, always first. Delegate to `Explore` only when search is insufficient: launch one or more `Explore` subagents in parallel with scoped evidence questions and let them return file:line citations; read directly only the small subset you must touch to decide or edit. PLAN: lead owns planning: sequence interfaces, invariants, and acceptance criteria directly. 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. 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. Handle trivial, surgical, single-file, or single-command tasks directly; you do not need to justify skipping delegation. `Explore` is cheap and may be launched in parallel across independent discovery questions. Send independent subagent calls in parallel within a single turn. Delegation graph: the lead may invoke all three; `General-Purpose` may invoke `reviewer`; `reviewer` may invoke `Explore` for targeted discovery; `Explore` and `worker-browse` cannot invoke native subagents.\n\n" : `${profileLabel} launch profile. The lead coordinates execution across specialized native roles: ` + buildNativeReachClauses(opts) + ". 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). Phase pipeline (budget gather, expensive plan, budget execution, expensive verification). 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. 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. 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. VERIFY: after behavior-changing, cross-boundary, or risk-sensitive implementation, run relevant build/tests then invoke `reviewer` before declaring done. Handle trivial, surgical, single-file, or single-command tasks directly; you do not need to justify skipping delegation. `Explore` is cheap and may be launched in parallel across independent discovery questions. Send independent subagent calls in parallel within a single turn. Delegation graph: the lead may invoke all four; `Plan` may invoke `Explore` and `reviewer`; `General-Purpose` may invoke `reviewer`; `Explore`, `reviewer`, and `worker-browse` cannot invoke native subagents.\n\n";
244
+ const windowNote = isCheapest || isBalanced ? "All roles run at a 200K context window — use targeted reads (search, Grep, Read specific files) over full file reads.\n\n" : isCheap ? "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" : "";
245
+ const swePipelineClause = opts.sweEnabled === false ? "" : `${isCheapest || isBalanced ? PIPELINE_SKILLS_AWARENESS_NO_PLAN_AGENT : PIPELINE_SKILLS_AWARENESS}\n\n`;
246
+ const consultation = isBalanced ? `Consultation guidance: funnel unknowns cheapest-first. (1) \`code_search\` and \`web\` search narrow scope and rule out hypotheses — always first. (2) \`Explore\` subagents for targeted breadth only when search is insufficient. \`mcp__${peersKey}__oracle\` is ${oracleDescriptor}, a second opinion for precise, self-contained architectural/spec trade-offs that search and \`Explore\` cannot settle; available to the lead; \`reviewer\` and other subagents cannot call Oracle. Optimize for accuracy, intelligence, and correctness at the lowest cost — prefer direct evidence over delegation when the question is narrow. ` : `Consultation guidance: Follow an evidence-first escalation ladder. Direct empirical evidence (search, code, tests, builds) settles factual questions first. Advisor is an optional, non-binding, lead-only transcript-aware sounding board for trajectory guidance or framing checks (direction, not dictation), and never use it for routine progress, waiting, directly verifiable facts, or completion ritual. \`mcp__${peersKey}__oracle\` is ${oracleDescriptor}, an expert consultant ${isCheapest || isBalanced ? "available to the lead" : "available to the lead and `Plan`"}, preferred over advisor for difficult conceptual, algorithmic, spec/protocol, or architectural tradeoffs evaluated in a self-contained brief; \`reviewer\` and other subagents cannot call Oracle. Discriminator: transcript-aware trajectory/framing/momentum → advisor; a self-contained technical/architectural trade-off → Oracle.${isCheapest ? "" : " `Plan` may consult Oracle on unresolved trade-offs, and reports any remaining tie-breaking gap to the lead."}${astraClause} `;
247
+ return "## 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" + pipeline + windowNote + consultation + searchGuidance + `\`mcp__${searchKey}__web\` provides citable sources.${browserClause}${workerBrowseClause}${artifactClause}\n\n` + swePipelineClause + "Verify claims with concrete repository evidence and tests before declaring work done. User instructions outrank delegation triggers. Stop named teammates when finished.";
248
+ }
249
+ return "## 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\nOrchestrate. Delegate research, implementation, review, and large reads to the right subagent, worker, or model. Reach for " + buildNativeReachClauses(opts) + "; worker-* agents for background non-blocking runs; Task subagents for parallel work; peer critics for review. That keeps your own context free to reason and collaborate with the user. Launch independent agents concurrently in a single message rather than serially. Delegation pays when the work is WIDE (many files or sources to sweep) or SLOW, and you need only the conclusion: the main thread is where you think with and respond to the user, and its context window is a finite shared resource. It does NOT pay merely because a sub-question is separable. A narrow, deep question whose whole value is file:line fidelity loses exactly that through a summarization layer, and a sub-question you could answer in one command is cheaper done directly than paying a subagent's startup. Do trivial, surgical, and last-mile work yourself. A named teammate persists after it reports so you can send it follow-ups, and nothing reaps it for you: its idle notice means available, not finished. Stop it once you are done with it.\n\nAdversarial review. The peer critics (`codex_critic` and `codex_reviewer`, `gemini_critic` and `gemini_reviewer`, `opus_critic`, and the `peer-review-coordinator` that fans out to several of them) are fresh-context models, so what they add is a blind spot that whoever produced the work cannot reach by thinking harder about it; prefer a critic from a different lab than the producer, since blind spots correlate within a lab. The `advisor` is a complement and not a substitute: it sees your transcript, so it catches your own drift and momentum, but it inherits your framing, which is exactly what a fresh-context critic does not. They earn their keep on consequential design choices, recommendations, and hard-to-reverse decisions: the cases where plausible alternatives remain and the conclusion rests on judgment rather than on something you can verify directly. That is where confabulation hides, so budget the wait even under delivery pressure. Always consult one when the change touches auth, user input, database queries, crypto, or serialization. They do NOT pay for read-only tracing, ordinary repository lookup, or a conclusion that a focused test, a direct reproduction, or unambiguous code evidence already settles. Asking a critic to re-derive a proven fact returns a confident answer either way, which is ritual skepticism rather than review, and skipping them there is the right call and not a shortcut. Match the lens to the artifact: a strategic critic for plans and trade-offs, a code reviewer for a concrete diff, the coordinator only when the risk warrants several independent lenses. Give whichever you pick the artifact and the constraints and not your rationale, since justification anchors the review and dulls it.\n\nAim high. Default to radical simplicity and a relentless focus on the user's real experience: design for the person and the job to be done, not the demo. Reason about the whole system from first principles, anticipating scale and the long arc rather than patching the surface. Work backwards from the outcome the user actually needs. Question every assumption and prefer what you can derive, reproduce, or test.\n\nEngineering excellence. When making technical decisions, give little weight to development cost; prefer quality, simplicity, robustness, scalability, and long-term maintainability. Fix a bug by first reproducing it end to end, as close to how a real user hits it as you can, so you solve the real problem and not a symptom. When testing a product end to end, be picky about the UI and obsessed with pixel perfection: if something clearly looks off, even when it is unrelated to your task, get it fixed along the way. Hold that same bar for the codebase itself: a lint error, a failing test, or a flaky test is worth fixing the moment you see it, whoever introduced it. Fold it into your current work rather than letting it derail the task the user actually asked for.";
250
+ }
251
+ /** The all-available form of the directive. Prefer
252
+ * `buildOperatingDefaultsDirective` on any path that knows which natives
253
+ * resolved; this const is the default for callers and tests that do not model
254
+ * a thin catalog. */
255
+ const OPERATING_DEFAULTS_DIRECTIVE = buildOperatingDefaultsDirective();
256
+ const STANDARD_OPERATING_DEFAULTS_DIGEST = "## 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\nDelegate when the work is WIDE (many files or sources to sweep) or SLOW and you need only the conclusion, to protect the main thread's finite context and keep it free for reasoning and interacting with the user; prefer parallel delegation for independent work. Do NOT delegate merely because a sub-question is separable: a narrow, deep question whose value is file:line fidelity loses exactly that through a summarization layer, and one answerable in a single command is cheaper done directly. Do trivial, surgical, and last-mile work yourself. Stop a named teammate once you are done with it: it persists for follow-ups, its idle notice means available rather than finished, and nothing reaps it for you.\n\nVerify, do not assert. Run the code, read the file, check the exit code. A claim in prose is worth nothing against state you did not check, and a check that cannot fail proves nothing. Reproduce a bug end to end, the way a real user hits it, before fixing it. Fix a lint error, failing test, or flake the moment you see it, whoever introduced it, without letting it derail the task at hand. Prefer quality and long-term maintainability over development cost.\n\nVerification has a blind spot: a consequential recommendation, a design or trade-off call, or a hard-to-reverse decision that still turns on judgment among plausible alternatives once the direct evidence is in. That is where confabulation hides, so put it past a peer critic before you ship it and budget the wait even under delivery pressure. When a test, a run, a reproduction, or a search would settle the claim, settle it that way instead; a critic asked to re-derive what you can already prove is ritual, not review.\n\nThe agent roster, the tool surface, and the reasoning behind these defaults are in your CLAUDE.md project instructions. Read them when choosing HOW to work; the rules above apply without a lookup.";
257
+ function buildOperatingDefaultsDigest(opts = {}) {
258
+ const digestPipelineSentence = opts.sweEnabled === false ? "" : opts.profile === "cheapest" || opts.profile === "balanced" ? "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" : "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";
259
+ if (opts.profile === "max") return "## 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\nMax 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. " + MAX_PARALLELISM_RULE + " Give delegated workstreams non-overlapping scopes and state the outcome, constraints, evidence, and verification expected.\n\n" + digestPipelineSentence + "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.";
260
+ if (opts.profile === "fast" || opts.profile === "cheap" || opts.profile === "cheap1m" || opts.profile === "cheapest" || opts.profile === "balanced") {
261
+ const isCheap = opts.profile === "cheap" || opts.profile === "cheap1m";
262
+ const isCheapest = opts.profile === "cheapest";
263
+ const isBalanced = opts.profile === "balanced";
264
+ const profileLabel = isCheapest ? "Cheapest" : isCheap ? "Cheap" : isBalanced ? "Balanced" : "Fast";
265
+ const oracleDescriptor = isCheapest ? "(GPT-6 Sol 200K/high, lead-only)" : isBalanced ? "(Grok 4.6 200K/medium, lead-only)" : isCheap ? "(Grok 4.6 200K/medium, lead and Plan)" : "(Opus 5 1M/high, lead and Plan)";
266
+ const advisorDescriptor = isCheapest ? "(Sol/medium, lead-only)" : "(Sol/high, lead-only)";
267
+ const astraStep = opts.astraAvailable && (opts.profile === "fast" || opts.profile === "cheap1m") ? `; (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).` : ".";
268
+ const delegation = isCheapest ? `${profileLabel} launch profile. The lead owns the outcome and handles straightforward work directly: use \`Explore\` for discovery spanning more than a couple of files, \`General-Purpose\` for mixed multi-step execution, and \`reviewer\` for behavior-changing or risk-sensitive changes. In plan mode, produce the plan and acceptance criteria directly; before presenting the final plan to the user, consult \`advisor\` once for a framing check. Plan briefly before non-trivial acts, verify by execution, tag unverified claims, and stop searching when results stop changing the answer. Handle trivial and surgical edits directly. Stop named teammates when finished.\n\nConsulting \`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.
269
+
270
+ ` : isBalanced ? `${profileLabel} launch profile. The lead owns planning, implementation, and verification by default: narrow scope first with \`code_search\` and \`web\` search to rule out hypotheses (cheapest, always first); delegate to \`Explore\` in parallel only when search is insufficient (read directly only files you will act on); delegate to \`General-Purpose\` FREELY for multi-step work combining investigation, tool workflows, and code changes; invoke \`reviewer\` ONLY when the change is genuinely behavior-changing, cross-boundary, or risk-sensitive (\`reviewer\` narrows scope with search first and may invoke \`Explore\` for targeted discovery); handle trivial and surgical edits directly. Send independent subagent calls in parallel within a single turn. Stop named teammates when finished.\n\n` : `${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`;
271
+ const consultationLadder = isBalanced ? "Verify claims against real evidence: run relevant commands and tests. Funnel unknowns cheapest-first: (1) `code_search` + `web` search narrow scope and rule out hypotheses first; (2) `Explore` for targeted breadth when search is insufficient; (3) `oracle` " + oracleDescriptor + " as a second opinion for precise, self-contained technical/architectural trade-offs that search and `Explore` cannot settle. Optimize for accuracy, intelligence, and correctness at the lowest cost." : "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` " + advisorDescriptor + " for transcript-aware framing checks or trajectory guidance (session momentum/trajectory); (3) `oracle` " + oracleDescriptor + " for self-contained technical/architectural trade-offs" + astraStep;
272
+ const digestWindowNote = isCheapest || isBalanced ? "All roles run at a 200K context window — use targeted reads over full file reads.\n\n" : isCheap ? "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" : "";
273
+ return "## 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" + delegation + digestPipelineSentence + digestWindowNote + consultationLadder;
274
+ }
275
+ return STANDARD_OPERATING_DEFAULTS_DIGEST;
276
+ }
277
+ /**
278
+ * Skip the helper if the user's `~/.claude/CLAUDE.md` (or, equivalently,
279
+ * the would-be post-write file) has grown past this size.
280
+ * Read-modify-write becomes pathological at very large sizes; CLAUDE.md
281
+ * should never legitimately be a database. The main agent still gets
282
+ * the awareness via `--append-system-prompt`, so skipping here only
283
+ * loses descendant-reach.
284
+ */
285
+ const MAX_CLAUDE_MD_BYTES = 1048576;
286
+ /**
287
+ * Bounded retry budget for the temp → rename step on Windows where
288
+ * `fs.rename` can transiently fail with EBUSY / EPERM / EACCES when
289
+ * CLAUDE.md is open in an editor, scanned by AV, or indexed by the
290
+ * search service. Mirrors the verify-on-rename-fail pattern at
291
+ * `paths.ts:795-818`. POSIX renames almost never fail this way; the
292
+ * cost on Linux/macOS is one extra `lstat` in the unhappy path.
293
+ */
294
+ const RENAME_RETRY_DELAYS_MS = [
295
+ 50,
296
+ 200,
297
+ 500
298
+ ];
299
+ /**
300
+ * Grep-able error-code prefix. Every warn-and-continue path here
301
+ * starts its message with this token so a Windows user who never sees
302
+ * a fresh marker block in their mirror can `grep CLAUDE_MD_WRITE` in
303
+ * the launcher output and land on the actionable line directly.
304
+ */
305
+ const ERROR_CODE = "CLAUDE_MD_WRITE";
306
+ /**
307
+ * Find every well-formed marker block matching the given `markerOpen`
308
+ * + `markerClose` pair. A well-formed block is an exact `markerOpen`
309
+ * line followed somewhere later (any number of intervening lines) by
310
+ * an exact `markerClose` line, with no intervening `markerOpen`.
311
+ * Multiple stale blocks all surface here so the caller can remove
312
+ * all of them.
313
+ *
314
+ * Malformed state (open without close, or close without open) is
315
+ * reported separately via the second return value so the caller can
316
+ * `warn` and leave user prose untouched. We never try to "fix"
317
+ * malformed marker state — that risks corrupting user content.
318
+ */
319
+ function findMarkerBlocks(lines, markerOpen = PEER_MARKER_OPEN, markerClose = PEER_MARKER_CLOSE) {
320
+ const blocks = [];
321
+ let pendingOpen = null;
322
+ let malformed = false;
323
+ for (let i = 0; i < lines.length; i++) {
324
+ const line = lines[i];
325
+ if (line === markerOpen) {
326
+ if (pendingOpen !== null) malformed = true;
327
+ pendingOpen = i;
328
+ } else if (line === markerClose) {
329
+ if (pendingOpen === null) malformed = true;
330
+ else {
331
+ blocks.push({
332
+ openLineIndex: pendingOpen,
333
+ closeLineIndex: i
334
+ });
335
+ pendingOpen = null;
336
+ }
337
+ }
338
+ }
339
+ if (pendingOpen !== null) malformed = true;
340
+ return {
341
+ blocks,
342
+ malformed
343
+ };
344
+ }
345
+ /**
346
+ * Detect line-ending style of `content`. Returns `"\r\n"` if `\r\n`
347
+ * sequences outnumber bare `\n`; otherwise `"\n"`. Empty content
348
+ * defaults to `\n` (POSIX-style new file).
349
+ *
350
+ * Preserves CRLF on Windows users' existing CLAUDE.md — flipping their
351
+ * line endings under them would be a regression even though Claude
352
+ * Code itself reads either style.
353
+ */
354
+ function detectLineEnding(content) {
355
+ if (content.length === 0) return "\n";
356
+ const crlf = (content.match(/\r\n/g) ?? []).length;
357
+ return crlf > (content.match(/\n/g) ?? []).length - crlf ? "\r\n" : "\n";
358
+ }
359
+ /**
360
+ * Strip a leading UTF-8 BOM (`U+FEFF`) if present so the first line's
361
+ * marker comparison is byte-exact. CLAUDE.md authored on Windows in
362
+ * Notepad / VS Code sometimes carries a BOM; without this strip the
363
+ * first marker line would never match (`<BOM><!--...` !== `<!--...`)
364
+ * and successive launches would loop into malformed-state warn paths.
365
+ */
366
+ function stripLeadingBom(content) {
367
+ return content.charCodeAt(0) === 65279 ? content.slice(1) : content;
368
+ }
369
+ /**
370
+ * Split `content` into lines without losing the line-ending style.
371
+ * The split is done on `\n`; trailing `\r` (from CRLF) is stripped
372
+ * from each line for marker comparison, but the original ending is
373
+ * reconstructed via `detectLineEnding` + `joinLines`.
374
+ */
375
+ function splitLines(content) {
376
+ if (content.length === 0) return [];
377
+ return content.split("\n").map((l) => l.endsWith("\r") ? l.slice(0, -1) : l);
378
+ }
379
+ function joinLines(lines, eol) {
380
+ return lines.join(eol);
381
+ }
382
+ /**
383
+ * Containment check that defeats symlink/junction tricks (peer-review
384
+ * C3). `isUnderClaudeConfigMirror` is purely lexical via
385
+ * `path.resolve()` — it does NOT dereference symlinks, so an attacker
386
+ * (or an unfortunate `~/.claude` symlinked into Dropbox) could escape
387
+ * the mirror while passing the lexical guard. This helper resolves
388
+ * BOTH paths to their canonical form via `fs.realpath()` first.
389
+ *
390
+ * **Fail-closed semantics (advisor follow-up):**
391
+ *
392
+ * - If the mirror root itself is a symlink (`lstat` reports
393
+ * `isSymbolicLink() === true`), refuse. A symlinked mirror root
394
+ * means writes flow through the link to whatever the user (or an
395
+ * attacker) targeted — the boundary's whole point is to never
396
+ * mutate real `~/.claude/`, so accepting any symlinked root
397
+ * undermines it.
398
+ * - If `realpath` fails on the mirror root OR the target parent,
399
+ * refuse. The mirror dir is provisioned by `ensureClaudeConfigMirror`
400
+ * before this helper runs (documented ordering invariant); a
401
+ * `realpath` failure here signals an unexpected state, and after
402
+ * the root check has already succeeded a missing parent means the
403
+ * root vanished between checks (TOCTOU race).
404
+ */
405
+ async function isUnderClaudeConfigMirrorRealpath(target) {
406
+ if (!isUnderClaudeConfigMirror(target)) return false;
407
+ const mirrorRoot = PATHS.CLAUDE_CONFIG_DIR;
408
+ try {
409
+ if ((await fs.lstat(mirrorRoot)).isSymbolicLink()) {
410
+ consola.warn(`${ERROR_CODE}: mirror root is a symlink (${mirrorRoot}); refusing to write through it`);
411
+ return false;
412
+ }
413
+ } catch (err) {
414
+ consola.warn(`${ERROR_CODE}: cannot lstat mirror root ${mirrorRoot}: ${err instanceof Error ? err.message : String(err)}`);
415
+ return false;
416
+ }
417
+ let resolvedRoot;
418
+ try {
419
+ resolvedRoot = await fs.realpath(mirrorRoot);
420
+ } catch (err) {
421
+ consola.warn(`${ERROR_CODE}: realpath failed on mirror root ${mirrorRoot}: ${err instanceof Error ? err.message : String(err)}`);
422
+ return false;
423
+ }
424
+ const targetParent = path.dirname(target);
425
+ let resolvedTargetParent;
426
+ try {
427
+ resolvedTargetParent = await fs.realpath(targetParent);
428
+ } catch (err) {
429
+ consola.warn(`${ERROR_CODE}: realpath failed on target parent ${targetParent} after root check (TOCTOU?): ${err instanceof Error ? err.message : String(err)}`);
430
+ return false;
431
+ }
432
+ if (resolvedTargetParent === resolvedRoot) return true;
433
+ return resolvedTargetParent.startsWith(resolvedRoot + path.sep);
434
+ }
435
+ /**
436
+ * Try `fs.rename(temp, target)` with bounded retry + verify-on-fail.
437
+ * Mirrors `injectSyntheticClaudeJsonFields` in `paths.ts`. Windows
438
+ * `fs.rename` can transiently fail with EBUSY / EPERM / EACCES when
439
+ * the destination is held by another process (editor, AV, search
440
+ * indexer). Returns `true` on eventual success, `false` after all
441
+ * retries are exhausted (caller will warn-and-continue).
442
+ *
443
+ * On final failure we read the destination back and check whether it
444
+ * already matches `desiredContent` — a concurrent racer may have
445
+ * landed the same bytes (the snippet is deterministic per launch).
446
+ * In that case treat as success.
447
+ *
448
+ * **No `copyFile` fallback** (peer-review codex-critic C2). `fs.copyFile`
449
+ * follows the destination path — if `target` was replaced with a
450
+ * symlink/junction between our earlier `lstat` and now (TOCTOU), or
451
+ * if `target` is a hardlink to the real `~/.claude/CLAUDE.md`,
452
+ * `copyFile` would mutate user files through the link. The boundary
453
+ * we are defending says "never mutate the real `~/.claude/`". Rename
454
+ * is safe because replacing a path entry doesn't follow the link; the
455
+ * `copyFile` degradation reintroduces the escape. Fail-closed instead.
456
+ */
457
+ async function renameWithRetry(tempPath, target, desiredContent) {
458
+ let lastErr;
459
+ for (let attempt = 0; attempt <= RENAME_RETRY_DELAYS_MS.length; attempt++) try {
460
+ await fs.rename(tempPath, target);
461
+ return true;
462
+ } catch (err) {
463
+ lastErr = err;
464
+ if (attempt < RENAME_RETRY_DELAYS_MS.length) await new Promise((resolve) => setTimeout(resolve, RENAME_RETRY_DELAYS_MS[attempt]));
465
+ }
466
+ try {
467
+ if (await fs.readFile(target, "utf8") === desiredContent) {
468
+ await fs.unlink(tempPath).catch(() => {});
469
+ consola.debug(`${ERROR_CODE}: rename failed but target already holds expected content (racer-won-race): ${lastErr instanceof Error ? lastErr.message : String(lastErr)}`);
470
+ return true;
471
+ }
472
+ } catch {}
473
+ await fs.unlink(tempPath).catch(() => {});
474
+ consola.warn(`${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: ${lastErr instanceof Error ? lastErr.message : String(lastErr)}`);
475
+ return false;
476
+ }
477
+ async function injectMarkerBlock(opts) {
478
+ const { snippet, markerOpen, markerClose, position, label } = opts;
479
+ if (snippet.includes(markerOpen) || snippet.includes(markerClose)) {
480
+ consola.warn(`${ERROR_CODE}: refusing to inject ${label} snippet that contains marker literal; this would corrupt idempotency on the next launch`);
481
+ return;
482
+ }
483
+ const target = path.join(PATHS.CLAUDE_CONFIG_DIR, "CLAUDE.md");
484
+ if (!await isUnderClaudeConfigMirrorRealpath(target)) {
485
+ consola.warn(`${ERROR_CODE}: refusing to write outside resolved mirror dir (target=${target}, mirror=${PATHS.CLAUDE_CONFIG_DIR}) [${label}]`);
486
+ return;
487
+ }
488
+ let existingContent;
489
+ let targetExists;
490
+ try {
491
+ const linkStat = await fs.lstat(target);
492
+ if (linkStat.isSymbolicLink()) {
493
+ consola.warn(`${ERROR_CODE}: refusing to write through symlinked CLAUDE.md (target=${target}) [${label}]`);
494
+ return;
495
+ }
496
+ if (!linkStat.isFile()) {
497
+ consola.warn(`${ERROR_CODE}: refusing to write non-regular target (target=${target}, mode=${linkStat.mode.toString(8)}) [${label}]`);
498
+ return;
499
+ }
500
+ if (linkStat.size > MAX_CLAUDE_MD_BYTES) {
501
+ consola.warn(`${ERROR_CODE}: skipping oversized CLAUDE.md (${linkStat.size} bytes > ${MAX_CLAUDE_MD_BYTES}) [${label}]; descendant-reach disabled this launch`);
502
+ return;
503
+ }
504
+ if (linkStat.nlink > 1) {
505
+ consola.warn(`${ERROR_CODE}: refusing to write to hardlinked CLAUDE.md (nlink=${linkStat.nlink}) [${label}]; would mutate shared inode`);
506
+ return;
507
+ }
508
+ targetExists = true;
509
+ existingContent = await fs.readFile(target, "utf8");
510
+ } catch (err) {
511
+ if (typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT") {
512
+ existingContent = "";
513
+ targetExists = false;
514
+ } else {
515
+ consola.warn(`${ERROR_CODE}: failed to stat/read target (${target}) [${label}]: ${err instanceof Error ? err.message : String(err)}`);
516
+ return;
517
+ }
518
+ }
519
+ const hadBom = existingContent.charCodeAt(0) === 65279;
520
+ const normalizedContent = stripLeadingBom(existingContent);
521
+ const eol = detectLineEnding(normalizedContent);
522
+ const lines = splitLines(normalizedContent);
523
+ const { blocks, malformed } = findMarkerBlocks(lines, markerOpen, markerClose);
524
+ if (malformed) {
525
+ consola.warn(`${ERROR_CODE}: malformed marker state in ${target} (open without close or vice versa) [${label}]; leaving file untouched`);
526
+ return;
527
+ }
528
+ const cleanedLines = [...lines];
529
+ for (let i = blocks.length - 1; i >= 0; i--) {
530
+ const block = blocks[i];
531
+ cleanedLines.splice(block.openLineIndex, block.closeLineIndex - block.openLineIndex + 1);
532
+ if (position === "bottom") while (block.openLineIndex - 1 >= 0 && cleanedLines[block.openLineIndex - 1] === "" && cleanedLines.slice(0, block.openLineIndex - 1).some((l) => l !== "")) cleanedLines.splice(block.openLineIndex - 1, 1);
533
+ else while (block.openLineIndex < cleanedLines.length && cleanedLines[block.openLineIndex] === "" && cleanedLines.slice(block.openLineIndex + 1).some((l) => l !== "")) cleanedLines.splice(block.openLineIndex, 1);
534
+ }
535
+ if (position === "bottom") while (cleanedLines.length > 0 && cleanedLines[cleanedLines.length - 1] === "") cleanedLines.pop();
536
+ else while (cleanedLines.length > 0 && cleanedLines[0] === "") cleanedLines.shift();
537
+ const markerBlockLines = [
538
+ markerOpen,
539
+ ...snippet.split("\n").map((l) => l.endsWith("\r") ? l.slice(0, -1) : l),
540
+ markerClose
541
+ ];
542
+ let finalLines;
543
+ if (cleanedLines.length === 0) finalLines = [...markerBlockLines, ""];
544
+ else if (position === "bottom") finalLines = [
545
+ ...cleanedLines,
546
+ "",
547
+ ...markerBlockLines,
548
+ ""
549
+ ];
550
+ else finalLines = [
551
+ ...markerBlockLines,
552
+ "",
553
+ ...cleanedLines,
554
+ ""
555
+ ];
556
+ const bodyContent = joinLines(finalLines, eol);
557
+ const finalContent = hadBom ? "" + bodyContent : bodyContent;
558
+ if (Buffer.byteLength(finalContent, "utf8") > MAX_CLAUDE_MD_BYTES) {
559
+ consola.warn(`${ERROR_CODE}: post-build content exceeds ${MAX_CLAUDE_MD_BYTES} bytes [${label}]; skipping update (descendant-reach disabled this launch)`);
560
+ return;
561
+ }
562
+ const tempPath = `${target}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
563
+ try {
564
+ await fs.writeFile(tempPath, finalContent, {
565
+ encoding: "utf8",
566
+ flag: "wx"
567
+ });
568
+ } catch (err) {
569
+ await fs.unlink(tempPath).catch(() => {});
570
+ consola.warn(`${ERROR_CODE}: temp-file write failed for ${tempPath} [${label}]: ${err instanceof Error ? err.message : String(err)}`);
571
+ return;
572
+ }
573
+ if (!await renameWithRetry(tempPath, target, finalContent)) return;
574
+ consola.debug(`${ERROR_CODE}: ${targetExists ? "updated" : "created"} ${target} [${label}] (${finalContent.length} bytes, eol=${eol === "\r\n" ? "CRLF" : "LF"})`);
575
+ }
576
+ /**
577
+ * Append the peer-MCP awareness `snippet` to the mirrored
578
+ * `<CLAUDE_CONFIG_DIR>/CLAUDE.md`. Idempotent across launches: prior
579
+ * well-formed peer-marker blocks are removed before appending a fresh
580
+ * one at the bottom. The original user content is preserved
581
+ * byte-for-byte at the top (modulo line-ending normalization to the
582
+ * file's detected style; leading UTF-8 BOM is preserved).
583
+ *
584
+ * Failures `warn` and return — this surface is the descendant-reach
585
+ * enhancement; the main agent still gets the awareness via
586
+ * `--append-system-prompt`. Every warn message starts with
587
+ * `CLAUDE_MD_WRITE` so users can grep launcher output.
588
+ */
589
+ async function appendPeerAwarenessToMirroredClaudeMd(snippet) {
590
+ await injectMarkerBlock({
591
+ snippet,
592
+ markerOpen: PEER_MARKER_OPEN,
593
+ markerClose: PEER_MARKER_CLOSE,
594
+ position: "bottom",
595
+ label: "peer-mcp-awareness"
596
+ });
597
+ }
598
+ /**
599
+ * Prepend a writing / communication style directive to the TOP of the
600
+ * mirrored `<CLAUDE_CONFIG_DIR>/CLAUDE.md` so every spawned agent
601
+ * reads it first. The directive itself is hard-coded to
602
+ * `STYLE_DIRECTIVE` above; the parameter exists for tests / future
603
+ * configurability. Idempotent across launches via the
604
+ * style-marker fence (separate from the peer-awareness fence, so the
605
+ * two blocks coexist without colliding).
606
+ */
607
+ async function prependStyleDirectiveToMirroredClaudeMd(directive = STYLE_DIRECTIVE) {
608
+ await injectMarkerBlock({
609
+ snippet: directive,
610
+ markerOpen: STYLE_MARKER_OPEN,
611
+ markerClose: STYLE_MARKER_CLOSE,
612
+ position: "top",
613
+ label: "style-directive"
614
+ });
615
+ }
616
+ /**
617
+ * Prepend the operating-defaults directive (orchestrator posture + hybrid
618
+ * excellence lens; `OPERATING_DEFAULTS_DIRECTIVE` above) to the TOP of the
619
+ * mirrored CLAUDE.md so the main agent and descendant agents (Agent subagents,
620
+ * agent-teams teammates) inherit the full statement. The main agent also gets
621
+ * OPERATING_DEFAULTS_DIGEST at higher salience via `--append-system-prompt`.
622
+ * Separate marker fence from the style / peer blocks so all coexist;
623
+ * best-effort (warn-and-continue) like its siblings.
624
+ */
625
+ async function prependOperatingDefaultsToMirroredClaudeMd(directive = OPERATING_DEFAULTS_DIRECTIVE) {
626
+ await injectMarkerBlock({
627
+ snippet: directive,
628
+ markerOpen: OPERATING_MARKER_OPEN,
629
+ markerClose: OPERATING_MARKER_CLOSE,
630
+ position: "top",
631
+ label: "operating-defaults"
632
+ });
633
+ }
634
+ /**
635
+ * Append the toolbelt awareness one-liner (which CLI tools are on PATH)
636
+ * to the bottom of the mirrored CLAUDE.md so descendant agents (Agent
637
+ * subagents, agent-teams teammates) and the main agent learn about the
638
+ * provisioned tools via the mirrored CLAUDE.md. This line is not sent via
639
+ * `--append-system-prompt`.
640
+ * Separate marker fence from the peer-awareness / style blocks.
641
+ */
642
+ async function appendToolbeltAwarenessToMirroredClaudeMd(snippet) {
643
+ await injectMarkerBlock({
644
+ snippet,
645
+ markerOpen: TOOLBELT_MARKER_OPEN,
646
+ markerClose: TOOLBELT_MARKER_CLOSE,
647
+ position: "bottom",
648
+ label: "toolbelt-awareness"
649
+ });
650
+ }
651
+ /**
652
+ * Prepend the artifact-panel review directive to the TOP of the mirrored
653
+ * CLAUDE.md so plans/artifacts are reviewed in the ai-or-die panel by default.
654
+ * Gated by the caller on AIORDIE_SESSION_ID (only useful inside a tab). Separate
655
+ * marker fence; best-effort like the style/peer blocks.
656
+ */
657
+ async function prependArtifactPanelDirectiveToMirroredClaudeMd(peersKey = "peers") {
658
+ await injectMarkerBlock({
659
+ snippet: ARTIFACT_PANEL_DIRECTIVE(peersKey),
660
+ markerOpen: ARTIFACT_MARKER_OPEN,
661
+ markerClose: ARTIFACT_MARKER_CLOSE,
662
+ position: "top",
663
+ label: "artifact-panel-directive"
664
+ });
665
+ }
666
+ //#endregion
667
+ export { buildOperatingDefaultsDirective as a, prependOperatingDefaultsToMirroredClaudeMd as c, buildOperatingDefaultsDigest as i, prependStyleDirectiveToMirroredClaudeMd as l, appendPeerAwarenessToMirroredClaudeMd as n, isUnderClaudeConfigMirrorRealpath as o, appendToolbeltAwarenessToMirroredClaudeMd as r, prependArtifactPanelDirectiveToMirroredClaudeMd as s, CHEAPEST_CONSULT_CONTRACT as t, renameWithRetry as u };
668
+
669
+ //# sourceMappingURL=claude-md-injection-BoXOsg7h.js.map