github-router 0.3.356 → 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.
- package/dist/ado-tools-rysFZDws.js +1 -0
- package/dist/{aic-ledger-BuFrsGur.js → aic-ledger-_mvGW2Ev.js} +42 -7
- package/dist/aic-ledger-_mvGW2Ev.js.map +1 -0
- package/dist/{aic-statusline-settings-DBS9sEGC.js → aic-statusline-settings-B5EMMSFC.js} +2 -2
- package/dist/{aic-statusline-settings-DBS9sEGC.js.map → aic-statusline-settings-B5EMMSFC.js.map} +1 -1
- package/dist/{attribution-settings-CnmV9MSv.js → attribution-settings-wVzQvIdL.js} +188 -64
- package/dist/attribution-settings-wVzQvIdL.js.map +1 -0
- package/dist/{auth-DFawaLJU.js → auth-B3UvYB2r.js} +3 -3
- package/dist/{auth-DFawaLJU.js.map → auth-B3UvYB2r.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-BkVEl-Su.js → check-usage-45vyaLfl.js} +4 -4
- package/dist/{check-usage-BkVEl-Su.js.map → check-usage-45vyaLfl.js.map} +1 -1
- package/dist/{claude-DvR3Y7fu.js → claude-B3pIageM.js} +89 -41
- package/dist/claude-B3pIageM.js.map +1 -0
- package/dist/{claude-md-injection-Cpzolxin.js → claude-md-injection-BV4tPUWo.js} +126 -35
- package/dist/claude-md-injection-BV4tPUWo.js.map +1 -0
- package/dist/{codex-DQpSPjpQ.js → codex-B_AMB6JM.js} +7 -7
- package/dist/{codex-DQpSPjpQ.js.map → codex-B_AMB6JM.js.map} +1 -1
- package/dist/{copilot-discount-Bsmv_3OX.js → copilot-discount-BuDbQOHq.js} +2 -2
- package/dist/{copilot-discount-Bsmv_3OX.js.map → copilot-discount-BuDbQOHq.js.map} +1 -1
- package/dist/{debug-DkNTuErv.js → debug-DL2JsRqY.js} +2 -2
- package/dist/{debug-DkNTuErv.js.map → debug-DL2JsRqY.js.map} +1 -1
- package/dist/engine-D3oNrF6Z.js +1 -0
- package/dist/{gate-discovery-B2x_8hNL.js → gate-discovery-CXE-7VcM.js} +5 -5
- package/dist/{gate-discovery-B2x_8hNL.js.map → gate-discovery-CXE-7VcM.js.map} +1 -1
- package/dist/{get-copilot-usage-P9chc-X2.js → get-copilot-usage-BbGmK03C.js} +2 -2
- package/dist/{get-copilot-usage-P9chc-X2.js.map → get-copilot-usage-BbGmK03C.js.map} +1 -1
- package/dist/hooks.mjs +200 -117
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-BkfYr9FH.js → index-cmd-CjRcmYk3.js} +4 -4
- package/dist/{index-cmd-BkfYr9FH.js.map → index-cmd-CjRcmYk3.js.map} +1 -1
- package/dist/{internal-aic-status-C6L4-ncP.js → internal-aic-status-BAVomi5A.js} +4 -4
- package/dist/{internal-aic-status-C6L4-ncP.js.map → internal-aic-status-BAVomi5A.js.map} +1 -1
- package/dist/{internal-artifact-open-DgJ3PCtt.js → internal-artifact-open-NAGn9Mgt.js} +2 -2
- package/dist/{internal-artifact-open-DgJ3PCtt.js.map → internal-artifact-open-NAGn9Mgt.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-CicGz6oM.js → internal-fast-dispatch-guard-DP25L_Bx.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-CgBtUsQI.js → internal-fast-dispatch-guard-DbrgO9Ab.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-CgBtUsQI.js.map → internal-fast-dispatch-guard-DbrgO9Ab.js.map} +1 -1
- package/dist/{internal-first-mate-guard-DTXPT7JW.js → internal-first-mate-guard-C8GwLbaX.js} +1 -1
- package/dist/{internal-first-mate-guard-BfWYN6Jb.js → internal-first-mate-guard-GufCUMl3.js} +3 -3
- package/dist/{internal-first-mate-guard-BfWYN6Jb.js.map → internal-first-mate-guard-GufCUMl3.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-mNl9CCir.js → internal-max-dispatch-guard-BB0vwiPx.js} +1 -1
- package/dist/{internal-max-dispatch-guard-CY8l9SDw.js → internal-max-dispatch-guard-BodVFHRC.js} +2 -2
- package/dist/{internal-max-dispatch-guard-CY8l9SDw.js.map → internal-max-dispatch-guard-BodVFHRC.js.map} +1 -1
- package/dist/{internal-plan-review-2OHTs8Nk.js → internal-plan-review-ChFx8wTX.js} +3 -3
- package/dist/{internal-plan-review-2OHTs8Nk.js.map → internal-plan-review-ChFx8wTX.js.map} +1 -1
- package/dist/{internal-prompt-submit-CkfUcu34.js → internal-prompt-submit-BaccW_CC.js} +4 -4
- package/dist/{internal-prompt-submit-CkfUcu34.js.map → internal-prompt-submit-BaccW_CC.js.map} +1 -1
- package/dist/{internal-prompt-submit-DZ_-2A6a.js → internal-prompt-submit-DPUBQZtG.js} +2 -2
- package/dist/{internal-rebrief-EhBHAHsz.js → internal-rebrief-NjSlx5QY.js} +4 -4
- package/dist/{internal-rebrief-EhBHAHsz.js.map → internal-rebrief-NjSlx5QY.js.map} +1 -1
- package/dist/{internal-session-bind-Bv50ju2n.js → internal-session-bind-dsUOcKxU.js} +2 -2
- package/dist/{internal-session-bind-Bv50ju2n.js.map → internal-session-bind-dsUOcKxU.js.map} +1 -1
- package/dist/{internal-stop-hook-Dm-m8RoA.js → internal-stop-hook-B2TTl6Zp.js} +5 -5
- package/dist/{internal-stop-hook-Dm-m8RoA.js.map → internal-stop-hook-B2TTl6Zp.js.map} +1 -1
- package/dist/{internal-stop-review-K6f8xsCh.js → internal-stop-review-D_KEV_04.js} +2 -2
- package/dist/{internal-stop-review-K6f8xsCh.js.map → internal-stop-review-D_KEV_04.js.map} +1 -1
- package/dist/{internal-worker-guard-GVhTjVlR.js → internal-worker-guard-DB6shBIn.js} +2 -2
- package/dist/{internal-worker-guard-GVhTjVlR.js.map → internal-worker-guard-DB6shBIn.js.map} +1 -1
- package/dist/{internal-workspace-header-d2hFf9Jy.js → internal-workspace-header-DBg5Y7oN.js} +2 -2
- package/dist/{internal-workspace-header-d2hFf9Jy.js.map → internal-workspace-header-DBg5Y7oN.js.map} +1 -1
- package/dist/{lifecycle-C6cxM_Nk.js → lifecycle-9nX09dBl.js} +2 -2
- package/dist/{lifecycle-C6cxM_Nk.js.map → lifecycle-9nX09dBl.js.map} +1 -1
- package/dist/lifecycle-C_CT13c9.js +1 -0
- package/dist/lifecycle-DibiH857.js +1 -0
- package/dist/{lifecycle-pl9QpvqD.js → lifecycle-Gge2Dadd.js} +2 -2
- package/dist/{lifecycle-pl9QpvqD.js.map → lifecycle-Gge2Dadd.js.map} +1 -1
- package/dist/main.js +23 -23
- package/dist/{mcp-workspace-header-Su8uUxJg.js → mcp-workspace-header-Xw9B1W6T.js} +2 -2
- package/dist/{mcp-workspace-header-Su8uUxJg.js.map → mcp-workspace-header-Xw9B1W6T.js.map} +1 -1
- package/dist/{models-D8v8OTbN.js → models-BR6i348u.js} +3 -3
- package/dist/{models-D8v8OTbN.js.map → models-BR6i348u.js.map} +1 -1
- package/dist/{orchestration-Bov4rZEi.js → orchestration-D3-2ulhX.js} +2 -2
- package/dist/{orchestration-Bov4rZEi.js.map → orchestration-D3-2ulhX.js.map} +1 -1
- package/dist/{paths-BSI_EtDT.js → paths-C5477RGC.js} +48 -4
- package/dist/paths-C5477RGC.js.map +1 -0
- package/dist/paths-CEswtFj5.js +1 -0
- package/dist/{peer-mcp-personas-CVxXq1Q-.js → peer-mcp-personas-BOgR46nM.js} +641 -270
- package/dist/peer-mcp-personas-BOgR46nM.js.map +1 -0
- package/dist/{pi-D-BgxVhx.js → pi-DcWp83mx.js} +377 -602
- package/dist/pi-DcWp83mx.js.map +1 -0
- package/dist/{plan-review-hook-CHK1wL3-.js → plan-review-hook-C9K-em4D.js} +3 -3
- package/dist/{plan-review-hook-CHK1wL3-.js.map → plan-review-hook-C9K-em4D.js.map} +1 -1
- package/dist/{provision-DYmZgZDr.js → provision-DkWR9B6I.js} +5 -5
- package/dist/{provision-DYmZgZDr.js.map → provision-DkWR9B6I.js.map} +1 -1
- package/dist/{self-invocation-Dk_UHD_v.js → self-invocation-BtcGj-lY.js} +2 -2
- package/dist/{self-invocation-Dk_UHD_v.js.map → self-invocation-BtcGj-lY.js.map} +1 -1
- package/dist/{serve-DfxxKLFl.js → serve-BGwEVDdc.js} +14 -14
- package/dist/{serve-DfxxKLFl.js.map → serve-BGwEVDdc.js.map} +1 -1
- package/dist/{server-setup-VYf8ptCH.js → server-setup-DVPL9iph.js} +911 -100
- package/dist/server-setup-DVPL9iph.js.map +1 -0
- package/dist/{service-backend-DHyd9vjW.js → service-backend-B6D_DY1Z.js} +3 -3
- package/dist/{service-backend-DHyd9vjW.js.map → service-backend-B6D_DY1Z.js.map} +1 -1
- package/dist/{start-BsY1d26G.js → start-BUWx3nSr.js} +4 -4
- package/dist/{start-BsY1d26G.js.map → start-BUWx3nSr.js.map} +1 -1
- package/dist/{static-context-pack-dKrzbfIN.js → static-context-pack-ChHuxBpk.js} +232 -61
- package/dist/static-context-pack-ChHuxBpk.js.map +1 -0
- package/dist/{stop-gate-hook-CC7VWkZM.js → stop-gate-hook-DnLC09Lg.js} +3 -3
- package/dist/{stop-gate-hook-CC7VWkZM.js.map → stop-gate-hook-DnLC09Lg.js.map} +1 -1
- package/dist/{stop-gate-policy-CoR8xKNQ.js → stop-gate-policy-Dx9c98_d.js} +2 -2
- package/dist/{stop-gate-policy-CoR8xKNQ.js.map → stop-gate-policy-Dx9c98_d.js.map} +1 -1
- package/dist/{token-CA2s70qj.js → token-OTb61rOC.js} +2 -2
- package/dist/{token-CA2s70qj.js.map → token-OTb61rOC.js.map} +1 -1
- package/dist/{worker-dispatch-B_rriT7z.js → worker-dispatch-B1w2qfjX.js} +2 -2
- package/dist/{worker-dispatch-B_rriT7z.js.map → worker-dispatch-B1w2qfjX.js.map} +1 -1
- package/docs/azure-mcp.md +29 -31
- package/package.json +1 -1
- package/dist/ado-tools-DokE2DbX.js +0 -1
- package/dist/aic-ledger-BuFrsGur.js.map +0 -1
- package/dist/attribution-settings-CnmV9MSv.js.map +0 -1
- package/dist/claude-DvR3Y7fu.js.map +0 -1
- package/dist/claude-md-injection-Cpzolxin.js.map +0 -1
- package/dist/engine-DgmsdkCe.js +0 -1
- package/dist/lifecycle-BU_d2QMs.js +0 -1
- package/dist/lifecycle-ByFyew_w.js +0 -1
- package/dist/paths-BSI_EtDT.js.map +0 -1
- package/dist/paths-BYxX9DfA.js +0 -1
- package/dist/peer-mcp-personas-CVxXq1Q-.js.map +0 -1
- package/dist/pi-D-BgxVhx.js.map +0 -1
- package/dist/server-setup-VYf8ptCH.js.map +0 -1
- package/dist/static-context-pack-dKrzbfIN.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"claude-md-injection-Cpzolxin.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 isPinnedLaunchProfile,\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; trivial asks exit\n * planless);\n * implement ~10 min per task (8 concurrent max, worktree:true only when\n * parallel tasks need isolation); reviewer only on low-confidence or complex\n * and risky changes, plus a General-Purpose fix pass for major reviewer\n * findings.\n */\nexport const PIPELINE_SKILLS_AWARENESS =\n \"Pipeline skills (all 200K default context, native subagents only, never worker-*). \"\n + \"Prefer `/gh-swe-pipeline`: strict sequence, each stage completing before the next starts, user approval before implementation. Stages in order: \"\n + \"(1) `/gh-gather-context` BEFORE planning when grounded context is needed: lexical search plus bounded Explore subagents (~3 min each, 3 rounds max), writes context.md plus context.compact.md; \"\n + \"(2) `/gh-plan` AFTER context and BEFORE implementation: native Plan subagent plans non-trivial asks (trivial exits planless), ordered plan.md (~5 min), open questions, waits for user approval; \"\n + \"(3) `/gh-implement` AFTER plan approval: bounded parallel General-Purpose subagents (implementer first on max; worktree:true if parallel tasks need isolation), reviewer only on low-confidence or risky changes, plus fix pass for major findings. \"\n + \"Skip for trivial work. Never implement without an approved plan. Never overlap stages.\"\n\n/**\n * Pipeline-skills awareness for the profiles without a `Plan` role\n * (cheapest, balanced): the lead plans directly, so `/gh-plan` names the\n * lead instead of a Plan dispatch. Every other stage is identical.\n */\nexport const PIPELINE_SKILLS_AWARENESS_NO_PLAN_AGENT =\n \"Pipeline skills (all 200K default context, native subagents only, never worker-*). \"\n + \"Prefer `/gh-swe-pipeline`: strict sequence, each stage completing before the next starts, user approval before implementation. Stages in order: \"\n + \"(1) `/gh-gather-context` BEFORE planning when grounded context is needed: lexical search plus bounded Explore subagents (~3 min each, 3 rounds max), writes context.md plus context.compact.md; \"\n + \"(2) `/gh-plan` AFTER context and BEFORE implementation: the lead plans directly (no Plan subagent on this profile; trivial exits planless), ordered plan.md (~5 min), open questions, waits for user approval; \"\n + \"(3) `/gh-implement` AFTER plan approval: bounded parallel General-Purpose subagents (worktree:true if parallel tasks need isolation), reviewer only on low-confidence or risky changes, plus fix pass for major findings. \"\n + \"Skip for trivial work. Never implement without an approved plan. Never overlap stages.\"\n\n/** Which of the conditionally-emitted natives this launch actually wrote.\n * `undefined` means available, matching `buildPeerAwarenessSnippet`'s\n * `scoutAvailable` convention, so an existing caller that passes nothing keeps\n * the previous full-roster text. */\nexport interface NativeAgentAvailability {\n scoutAvailable?: boolean\n implementerFastAvailable?: boolean\n reviewerFastAvailable?: boolean\n generalPurposeFastAvailable?: boolean\n /** True when this launch's LEAD is a lighter Claude tier (sonnet, haiku)\n * rather than an Opus. Reorders the delegation clauses so the cheap tiers\n * lead; see `buildNativeReachClauses`. Absent/false keeps the Opus-lead\n * ordering, so existing callers are unaffected.\n *\n * Unlike the advisor's lead-awareness, this is resolved ONCE per launch and\n * baked into the mirrored CLAUDE.md, so it cannot follow a mid-session\n * `/model` switch. Acceptable for prose that biases a choice; it would not\n * be for anything that routes a request. */\n budgetLead?: boolean\n /** `\"fast\"` selects the fast launch profile's roster-restricted prose: a\n * hard restriction (not a catalog-availability signal, unlike every\n * `*Available` flag above). `\"cheap\"`/`\"cheap1m\"` select the same\n * restricted roster prose with the cheap family's oracle identities\n * (`\"cheap1m\"` additionally wires the astra peer). 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. 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\" | \"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`. All roles run at a 200K context window — prefer targeted reads (search, Grep, Read specific files) over full file reads\"\n }\n // Balanced: lead owns planning, implementation, verification by default —\n // only the reviewer is gated behind genuine need.\n if (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 ]) + \". All roles run at a 200K context window — prefer targeted reads (search, Grep, Read specific files) over full file reads\"\n }\n const shared = joinClauses([\n \"`Explore` for broad repository discovery, dependency mapping, and convention tracking (launch in parallel)\",\n \"`Plan` for architectural sequencing, interface contracts, migration risk, and runnable acceptance criteria (delegates discovery to `Explore`)\",\n \"`General-Purpose` for mixed, iterative, or multi-step execution tasks (follows a Plan handoff when one exists)\",\n \"`reviewer` for independent adversarial verification, reproduction, and root-causing after non-trivial changes\",\n ])\n // 200K profiles only: fast keeps 1M throughout. cheap1m's lead is 1M\n // but every subagent is 200K, so it gets the subagent-scoped variant.\n if (opts.profile === \"cheap\") {\n return `${shared}. All roles run at a 200K context window — prefer targeted reads (search, Grep, Read specific files) over full file reads`\n }\n if (opts.profile === \"cheap1m\") {\n return `${shared}. Subagents run at a 200K context window — brief them with targeted evidence and prefer targeted reads over full file reads`\n }\n return shared\n }\n const clauses: Array<string> = []\n const implementerFast = opts.implementerFastAvailable !== false\n const reviewerFast = opts.reviewerFastAvailable !== false\n // The swap requires `implementer-fast` to actually exist this launch — on a\n // catalog where it was dropped, naming it first would point the lead at an\n // agent absent from the Task `subagent_type` enum.\n if (opts.budgetLead === true && implementerFast) {\n clauses.push(\n \"`implementer-fast` first for coding changes, since it is the cheaper and \"\n + \"faster tier and this session is running a lighter lead\",\n \"`implementer` when the change needs judgment, its scope is ambiguous, or \"\n + \"its complexity is beyond what the fast tier can carry\",\n )\n } else {\n clauses.push(\n \"`implementer` for coding changes that need judgment or have ambiguous scope\",\n )\n if (implementerFast) {\n clauses.push(\"`implementer-fast` for well-specified, mechanical coding changes\")\n }\n }\n // Same swap, same precondition, for the review pair.\n if (opts.budgetLead === true && reviewerFast) {\n clauses.push(\n \"`reviewer-fast` first when something exists and you want it assessed, \"\n + \"since it is the cheaper and faster review tier\",\n \"`reviewer` when the assessment is higher-stakes or needs deeper \"\n + \"reproduction and root-causing than the fast tier can carry\",\n )\n } else {\n clauses.push(\n \"`reviewer` when something exists and you want it assessed (including \"\n + \"reproducing and root-causing a failure)\",\n )\n if (reviewerFast) {\n clauses.push(\"`reviewer-fast` for lower-stakes assessments\")\n }\n }\n clauses.push(\n \"`brainstorm` when you do not yet know which approach to take\",\n )\n if (opts.scoutAvailable !== false) {\n clauses.push(\"`scout` to find or understand something in the repo\")\n }\n clauses.push(\"`scribe` for docs and ADRs that trail the code\")\n if (opts.generalPurposeFastAvailable !== false) {\n clauses.push(\n opts.budgetLead === true\n ? \"`general-purpose-fast` for work no specialist fits, in preference to \"\n + \"carrying it inline yourself\"\n : \"`general-purpose-fast` for work no specialist fits\",\n )\n }\n return joinClauses(clauses)\n}\n\n/** Everything after the orchestration paragraph's agent list. Unchanged by\n * availability, so it lives here once rather than in both branches. */\nconst OPERATING_DEFAULTS_TAIL =\n \"context free to reason and collaborate with the user. Launch independent \"\n + \"agents concurrently in a single message rather than serially. Delegation \"\n + \"pays when the work is WIDE \"\n + \"(many files or sources to sweep) or SLOW, and you need only the \"\n + \"conclusion: the main thread is where you think with and respond to the \"\n + \"user, and its context window is a finite shared resource. It does NOT pay \"\n + \"merely because a sub-question is separable. A narrow, deep question whose \"\n + \"whole value is file:line fidelity loses exactly that through a \"\n + \"summarization layer, and a sub-question you could answer in one command is \"\n + \"cheaper done directly than paying a subagent's startup. Do trivial, \"\n + \"surgical, and last-mile work yourself. A named teammate persists after it \"\n + \"reports so you can send it follow-ups, and nothing reaps it for you: its idle \"\n + \"notice means available, not finished. Stop it once you are done with it.\\n\\n\"\n + \"Adversarial review. The peer critics (`codex_critic` and `codex_reviewer`, \"\n + \"`gemini_critic` and `gemini_reviewer`, `opus_critic`, and the \"\n + \"`peer-review-coordinator` that fans out to several of them) are \"\n + \"fresh-context models, so what they add is a blind spot that whoever \"\n + \"produced the work cannot reach by thinking harder about it; prefer a \"\n + \"critic from a different lab than the producer, since blind spots \"\n + \"correlate within a lab. The `advisor` is a complement and not a \"\n + \"substitute: it sees your transcript, so it catches your own drift and \"\n + \"momentum, but it inherits your framing, which is exactly what a \"\n + \"fresh-context critic does not. They earn their keep on consequential design \"\n + \"choices, recommendations, and hard-to-reverse decisions: the cases where \"\n + \"plausible alternatives remain and the conclusion rests on judgment rather \"\n + \"than on something you can verify directly. That is where confabulation \"\n + \"hides, so budget the wait even under delivery pressure. Always consult one \"\n + \"when the change touches auth, user input, database queries, crypto, or \"\n + \"serialization. They do NOT pay for read-only tracing, ordinary repository \"\n + \"lookup, or a conclusion that a focused test, a direct reproduction, or \"\n + \"unambiguous code evidence already settles. Asking a critic to re-derive a \"\n + \"proven fact returns a confident answer either way, which is ritual \"\n + \"skepticism rather than review, and skipping them there is the right call \"\n + \"and not a shortcut. Match the lens to the artifact: a strategic critic for \"\n + \"plans and trade-offs, a code reviewer for a concrete diff, the coordinator \"\n + \"only when the risk warrants several independent lenses. Give whichever you \"\n + \"pick the artifact and the constraints and not your rationale, since \"\n + \"justification anchors the review and dulls it.\\n\\n\"\n + \"Aim high. Default to radical simplicity and a relentless focus on the user's \"\n + \"real experience: design for the person and the job to be done, not the demo. \"\n + \"Reason about the whole system from first principles, anticipating scale and the \"\n + \"long arc rather than patching the surface. Work backwards from the outcome the \"\n + \"user actually needs. Question every assumption and prefer what you can derive, \"\n + \"reproduce, or test.\\n\\n\"\n + \"Engineering excellence. When making technical decisions, give little weight to \"\n + \"development cost; prefer quality, simplicity, robustness, scalability, and \"\n + \"long-term maintainability. Fix a bug by first reproducing it end to end, as \"\n + \"close to how a real user hits it as you can, so you solve the real problem and \"\n + \"not a symptom. When testing a product end to end, be picky about the UI and \"\n + \"obsessed with pixel perfection: if something clearly looks off, even when it is \"\n + \"unrelated to your task, get it fixed along the way. Hold that same bar for the \"\n + \"codebase itself: a lint error, a failing test, or a flaky test is worth fixing \"\n + \"the moment you see it, whoever introduced it. Fold it into your current work \"\n + \"rather than letting it derail the task the user actually asked for.\"\n\n/**\n * Cheapest-only consult contract for the Luna lead (the FULL \"when/how\" copy,\n * mirrored into CLAUDE.md).\n *\n * Lives in the injected operating-defaults prose rather than the advisor tool\n * description (the \"what\"), per OpenAI guidance. Outcome-first decision rules,\n * not a step procedure. Covers the four things a weak, over-confident model\n * needs to place consults well:\n * 1. a small, stated budget (8-10 calls) so each feels costly;\n * 2. ANCHORS (when to spend) — genuine uncertainty, before committing, before\n * presenting a plan;\n * 3. DISQUALIFIERS (never spend) — anything evidence settles, or a moment\n * owned by reviewer/oracle;\n * 4. a DISCRIMINATOR assigning each moment to the right consultant.\n * The digest carries only a short pointer (`CHEAPEST_CONSULT_CONTRACT_POINTER`)\n * so the always-resident copy does not duplicate this block every turn.\n */\nexport const CHEAPEST_CONSULT_CONTRACT =\n \"Consulting `advisor` and `oracle` (a small budget — choose wisely): you have roughly 8-10 advisor calls for this session, and each costs real time and money, so spend them only where direction changes the outcome. Advisor and Oracle give you COUNSEL on HOW — and sometimes WHAT — to do: the shortest path, what to consider or look at, planning, strategy, and direction. They never replace evidence you can gather yourself: anything a search, read, build, test, or run can settle, settle it yourself — never spend a consult on it. Spend a consult on: (1) a pre-commit framing check, after you have oriented but before you lock an approach on a non-trivial task; (2) an unresolvable judgment call — conflicting evidence, or a stale-knowledge / high-consequence risk or severity call; (3) a pre-presentation framing check on the final plan. Do NOT spend one on routine progress, reassurance, completion ritual, or a moment that belongs to `reviewer` (verify/reproduce a change) or `oracle` (a self-contained technical/algorithmic/spec/architectural trade-off). Discriminator: session-trajectory / framing / momentum questions and how-to-approach go to `advisor`; self-contained technical/architectural trade-offs go to `oracle`; verification and reproduction go to `reviewer`; facts go to direct evidence. How to call: Sol reads a curated view of this session — the user's original ask, your most recent message text, and a bounded transcript that keeps your reasoning but truncates raw tool output — so before you call, write a short self-contained brief as your own message: the objective, your current job, what you verified / suspect is missing / ruled irrelevant, your confidence and what being wrong would cost, and one neutral question phrased with any competing hypotheses. Never paste raw tool output or ask it to \\\"review the whole thing\\\". State your confidence after you have committed to a position, not before, and weigh the reply against verified repository evidence — counsel is direction, not dictation, and you own the decision.\\n\\n\"\n\n/**\n * Short, always-resident pointer to the consult contract, injected into the\n * digest (`--append-system-prompt`) instead of the full block. Keeps the\n * trigger + budget visible at top salience without duplicating the ~250-word\n * contract every turn; the full how-to lives in the mirrored CLAUDE.md.\n */\nexport const CHEAPEST_CONSULT_CONTRACT_POINTER =\n \"Consulting `advisor`/`oracle` (small budget, ~8-10 calls — choose wisely): use them for how/what — shortest path, what to consider, planning, strategy, direction — never for anything a search, read, or run settles, nor for routine progress, reassurance, or completion ritual; do not spend one where `reviewer` (verification) or `oracle` (a self-contained technical trade-off) owns the moment. Full how-to (when to spend, the call brief, the discriminator) is in your CLAUDE.md project instructions.\\n\\n\"\n\n/**\n * Build the operating-defaults directive for one launch, naming only the\n * natives that launch actually emitted.\n *\n * Callers must pass the SAME availability booleans they used for the `.md`\n * generation and `buildPeerAwarenessSnippet`, so the three surfaces cannot\n * disagree about which agents exist.\n */\nexport function buildOperatingDefaultsDirective(\n opts: NativeAgentAvailability = {},\n): string {\n if (opts.profile === \"max\") {\n const peersKey = opts.peersKey ?? opts.groupKeys?.peers ?? \"peers\"\n const artifactClause = opts.artifactAvailable\n ? ` Live human review is available in the artifact panel via \\`mcp__${peersKey}__artifact_*\\`.`\n : \"\"\n // Pipeline awareness is --swe-gated: without the flag the skill files are\n // not written, so the directive must not name them. Absent keeps the\n // legacy text for callers without a flag concept (serve path).\n const pipelineClause = opts.sweEnabled === false ? \"\" : `\\n\\n${PIPELINE_SKILLS_AWARENESS}`\n return (\n \"## Operating defaults (these layer with the user's explicit direction and the domain's own standards as addons, not replacements: follow all three together; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + \"Max launch profile. The lead owns the outcome. Start with direct repository or runtime evidence. Handle narrow, obvious, surgical, and single-command work directly; delegate a bounded workstream when it is broad, slow, context-heavy, or benefits from a genuinely independent perspective. \"\n + MAX_PARALLELISM_RULE\n + \" Brief each role with the desired outcome, relevant context, constraints, expected evidence, and verification. Use the roster as complementary capabilities, never as a required Explore → Plan → implement → review sequence. Avoid overlapping assignments and do not ask several models the same generic question. Synthesize results against the repository and executable checks: model agreement is not verification. Use one fresh-context peer only when a consequential judgment remains after direct checks; use the coordinator only when several distinct lenses could change the decision. Advisor is optional, non-binding counsel for one focused consequential uncertainty that evidence and the appropriate roles cannot settle; it has no approval or workflow authority, and a further consultation requires materially new or conflicting evidence.\"\n + artifactClause\n + pipelineClause\n )\n }\n if (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 profileLabel = isCheapest ? \"Cheapest\" : isCheap ? \"Cheap\" : isBalanced ? \"Balanced\" : \"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.\n const familyContract = isCheapest\n ? cheapestContractFor(opts.profile)\n : isBalanced\n ? balancedContractFor(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 have no Plan role; fast/cheap/cheap1m still do.\n const expensiveModels = isCheapest || isBalanced ? \"(reviewer, Oracle)\" : \"(Plan, reviewer, Oracle)\"\n const searchGuidance = opts.bluebirdEnabled === true\n ? \"Search strategy: use Bluebird `code` search in `lexical` mode for indexed keyword queries and `semantic` mode for intent/concept questions. Bluebird failures remain visible and never fall back locally; `exact`, `regex`, and `ast` stay on the local live tree. `Explore` subagents read the narrowed files and return file:line conclusions; expensive models \" + expensiveModels + \" see only the synthesized subset, never raw search output. \"\n : opts.semanticSearchAvailable === true\n ? \"Search strategy (cheapest first): (1) LOCAL LEXICAL `code` search (mode:\\\"lexical\\\"/\\\"exact\\\", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys; (2) local ColBERT SEMANTIC `code` search for intent/concept questions where literal keywords may not appear, with lexical fallback while its index is unavailable; (3) `Explore` subagents read the narrowed files and return file:line conclusions — expensive models \" + expensiveModels + \" see only the synthesized subset, never raw search output. \"\n : \"Search strategy (cheapest first): LOCAL LEXICAL `code` search (mode:\\\"lexical\\\"/\\\"exact\\\", plus Grep/Glob) for symbols, filenames, errors, routes, flags, and config keys. `Explore` subagents read the narrowed files and return file:line conclusions — expensive models \" + expensiveModels + \" see only the synthesized subset, never raw search output. \"\n if (opts.fastRuntimeAvailable === false) {\n return (\n \"## Operating defaults (these layer with the user's explicit direction and the domain's own standards as addons, not replacements: follow all three together; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + `${profileLabel} profile runtime wiring is unavailable. Work directly, use only tools actually listed in this session, verify with the repository's relevant build/tests before declaring done, report uncertainty, and do not invent unavailable capabilities.`\n )\n }\n const peersKey = opts.peersKey ?? opts.groupKeys?.peers ?? \"peers\"\n const searchKey = opts.groupKeys?.search ?? \"search\"\n const browserKey = opts.groupKeys?.browser ?? \"browser\"\n const workersKey = opts.groupKeys?.workers ?? \"workers\"\n const directBrowserAvailable = opts.browserToolsAvailable ?? opts.browseAvailable\n const browserClause = directBrowserAvailable ? ` \\`mcp__${browserKey}__*\\` provides direct browser control.` : \"\"\n const workerBrowseClause = opts.browseAvailable\n ? ` \\`worker-browse\\` runs delegated autonomous browsing tasks through \\`mcp__${workersKey}__browse\\`.`\n : \"\"\n const artifactClause = opts.artifactAvailable\n ? ` \\`mcp__${peersKey}__artifact_*\\` provides human review in the artifact panel with auto-open on plan completion.`\n : \"\"\n\n const astraClause = opts.astraAvailable && (opts.profile === \"fast\" || opts.profile === \"cheap1m\")\n ? ` \\`mcp__${peersKey}__astra\\` (GPT-6 Astra ${astraDescriptor}) is the terminal escalation consultant for the lead only, reserved strictly for the hardest dead ends when direct evidence, Advisor, and Oracle have all failed to produce a defensible path (consulted at most 1-2 times per decision with concise context and specific questions).`\n : \"\"\n\n // Cheapest is tuned for straightforward tasks: no proactive fan-out push,\n // so the lead handles simple work inline instead of paying handoff\n // overhead. The lead plans directly (no Plan role) and reviews the\n // final plan with the Advisor before presenting it. Balanced diverges\n // from the fast/cheap phase pipeline: search-first, and the lead owns\n // planning, implementation, and verification by default (reviewer ONLY\n // on genuine need; Explore/General-Purpose freely). The lead narrows\n // scope with code/web search before paying for Explore fan-out, and the\n // reviewer may invoke Explore for targeted discovery (see\n // BALANCED_PROFILE_DELEGATION_GRAPH).\n const pipeline = isCheapest\n ? `${profileLabel} launch profile. The lead owns the outcome and handles straightforward work directly. `\n + buildNativeReachClauses(opts)\n + \". Handle trivial, surgical, single-file, or single-command tasks directly; you do not need to justify skipping delegation. \"\n + \"`Explore` may be used for discovery spanning more than a couple of files; `General-Purpose` for mixed multi-step execution; `reviewer` for behavior-changing or risk-sensitive changes. \"\n + \"In plan mode, produce the plan and acceptance criteria directly and do not edit files; before presenting the final plan to the user, consult `advisor` once for a framing check. \"\n + \"Work to your strengths as a fast, cost-efficient model: verify by execution rather than memory; before a non-trivial task, write a short plan (steps, files involved, the check settling each step) and execute it; persist through tool failures with a rephrased attempt before asking the user; stop searching when further results stop changing the answer; tag claims verified, inferred, or unverified — never state that something passes, compiles, or is covered without observed output. \"\n + \"Delegation graph: the lead may invoke all three; `General-Purpose` may invoke `reviewer`; `Explore`, `reviewer`, and `worker-browse` cannot invoke native subagents.\\n\\n\"\n + CHEAPEST_CONSULT_CONTRACT\n : isBalanced\n ? `${profileLabel} launch profile. The lead coordinates execution across specialized native roles: `\n + buildNativeReachClauses(opts)\n + \". Lead owns planning, implementation, and verification by default: in plan mode, produce the plan and acceptance criteria directly and do not edit files. \"\n + \"Phase pipeline (budget gather, budget execution, expensive verification). \"\n + \"GATHER: narrow scope first with `code_search` (lexical, then semantic when available) and `web` search to rule out hypotheses — cheapest, always first. Delegate to `Explore` only when search is insufficient: launch one or more `Explore` subagents in parallel with scoped evidence questions and let them return file:line citations; read directly only the small subset you must touch to decide or edit. \"\n + \"PLAN: lead owns planning: sequence interfaces, invariants, and acceptance criteria directly. \"\n + \"EXECUTE: lead implements directly by default. Delegate to `General-Purpose` FREELY for multi-step work combining investigation, tool workflows, and code changes; brief with outcome, constraints, files in scope, and verification. \"\n + \"VERIFY: lead owns verification: run relevant build/tests, read the code, and reproduce before declaring done. Invoke `reviewer` ONLY when the change is genuinely behavior-changing, cross-boundary, or risk-sensitive; `reviewer` narrows scope with search first and may invoke `Explore` for targeted discovery. \"\n + \"Handle trivial, surgical, single-file, or single-command tasks directly; you do not need to justify skipping delegation. \"\n + \"`Explore` is cheap and may be launched in parallel across independent discovery questions. Send independent subagent calls in parallel within a single turn. \"\n + \"Delegation graph: the lead may invoke all three; `General-Purpose` may invoke `reviewer`; `reviewer` may invoke `Explore` for targeted discovery; `Explore` and `worker-browse` cannot invoke native subagents.\\n\\n\"\n : `${profileLabel} launch profile. The lead coordinates execution across specialized native roles: `\n + buildNativeReachClauses(opts)\n + \". In plan mode or when designing changes with complex sequencing, interface contracts, or acceptance criteria, delegate architectural planning to `Plan` (in plan mode, produce the plan and acceptance criteria; do not edit files). \"\n + \"Phase pipeline (budget gather, expensive plan, budget execution, expensive verification). \"\n + \"GATHER: delegate to `Explore` instead of exploring yourself. For any question spanning more than a couple of files, launch one or more `Explore` subagents in parallel with scoped evidence questions and let them return file:line citations; read directly only the small subset you must touch to decide or edit. `Plan` follows the same rule when it needs repository facts. \"\n + \"PLAN: `Plan` produces handoff-ready steps (ordered, file:line, done conditions, acceptance criteria) for a `General-Purpose` executor that cannot see its reasoning; `Plan` may consult Oracle on unresolved trade-offs and reports any remaining gap to the lead. \"\n + \"EXECUTE: delegate mixed multi-step work and Plan handoffs to `General-Purpose` in a fresh context to preserve lead context; brief with outcome, constraints, files in scope, and verification. \"\n + \"VERIFY: after behavior-changing, cross-boundary, or risk-sensitive implementation, run relevant build/tests then invoke `reviewer` before declaring done. \"\n + \"Handle trivial, surgical, single-file, or single-command tasks directly; you do not need to justify skipping delegation. \"\n + \"`Explore` is cheap and may be launched in parallel across independent discovery questions. Send independent subagent calls in parallel within a single turn. \"\n + \"Delegation graph: the lead may invoke all four; `Plan` may invoke `Explore` and `reviewer`; `General-Purpose` may invoke `reviewer`; `Explore`, `reviewer`, and `worker-browse` cannot invoke native subagents.\\n\\n\"\n\n // 200K profiles: every role the lead can reach runs at the 200K default\n // window (cheap1m's lead excepted at 1M), so the directive names targeted\n // reads once instead of repeating it per role.\n const windowNote = isCheapest || isBalanced\n ? \"All roles run at a 200K context window — use targeted reads (search, Grep, Read specific files) over full file reads.\\n\\n\"\n : isCheap\n ? \"The lead runs at a 200K context window on `-m cheap` (1M on `-m cheap1m`) and every subagent runs at 200K — use targeted reads (search, Grep, Read specific files) over full file reads.\\n\\n\"\n : \"\"\n\n // Pipeline awareness is --swe-gated: without the flag the skill files are\n // not written, so the directive must not name them. Absent keeps the\n // legacy text for callers without a flag concept (serve path).\n const swePipelineClause = opts.sweEnabled === false\n ? \"\"\n : `${isCheapest || isBalanced ? PIPELINE_SKILLS_AWARENESS_NO_PLAN_AGENT : PIPELINE_SKILLS_AWARENESS}\\n\\n`\n // Balanced has no Advisor: Oracle is the only consultant, framed as a\n // second opinion on a precise question — never a discovery tool. For\n // unknowns, only search (then Explore) helps. Cheapest and balanced have\n // no Plan role, so Oracle is lead-only there; fast/cheap/cheap1m keep\n // lead-and-Plan Oracle access.\n const oracleLeadOnly = isCheapest || isBalanced\n const consultation = isBalanced\n ? \"Consultation guidance: funnel unknowns cheapest-first. (1) `code_search` and `web` search narrow scope and rule out hypotheses — always first. (2) `Explore` subagents for targeted breadth only when search is insufficient. \"\n + `\\`mcp__${peersKey}__oracle\\` is ${oracleDescriptor}, a second opinion for precise, self-contained architectural/spec trade-offs that search and \\`Explore\\` cannot settle; available to the lead; \\`reviewer\\` and other subagents cannot call Oracle. Optimize for accuracy, intelligence, and correctness at the lowest cost — prefer direct evidence over delegation when the question is narrow. `\n : \"Consultation guidance: Follow an evidence-first escalation ladder. Direct empirical evidence (search, code, tests, builds) settles factual questions first. Advisor is an optional, non-binding, lead-only transcript-aware sounding board for trajectory guidance or framing checks (direction, not dictation), and never use it for routine progress, waiting, directly verifiable facts, or completion ritual. \"\n + `\\`mcp__${peersKey}__oracle\\` is ${oracleDescriptor}, an expert consultant ${oracleLeadOnly ? \"available to the lead\" : \"available to the lead and `Plan`\"}, preferred over advisor for difficult conceptual, algorithmic, spec/protocol, or architectural tradeoffs evaluated in a self-contained brief; \\`reviewer\\` and other subagents cannot call Oracle. Discriminator: transcript-aware trajectory/framing/momentum → advisor; a self-contained technical/architectural trade-off → Oracle.${isCheapest ? \"\" : \" `Plan` may consult Oracle on unresolved trade-offs, and reports any remaining tie-breaking gap to the lead.\"}${astraClause} `\n return (\n \"## Operating defaults (these layer with the user's explicit direction and the domain's own standards as addons, not replacements: follow all three together; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + pipeline\n + windowNote\n + consultation\n + searchGuidance\n + `\\`mcp__${searchKey}__web\\` provides citable sources.${browserClause}${workerBrowseClause}${artifactClause}\\n\\n`\n + swePipelineClause\n + \"Verify claims with concrete repository evidence and tests before declaring work done. User instructions outrank delegation triggers. Stop named teammates when finished.\"\n )\n }\n return (\n \"## Operating defaults (these layer with the user's explicit direction and the domain's own standards as addons, not replacements: follow all three together; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + \"Orchestrate. Delegate research, implementation, review, and large reads to the \"\n + \"right subagent, worker, or model. Reach for \"\n + buildNativeReachClauses(opts)\n + \"; worker-* agents for background \"\n + \"non-blocking runs; Task subagents for parallel work; peer critics for review. \"\n + \"That keeps your own \"\n + OPERATING_DEFAULTS_TAIL\n )\n}\n\n/** The all-available form of the directive. Prefer\n * `buildOperatingDefaultsDirective` on any path that knows which natives\n * resolved; this const is the default for callers and tests that do not model\n * a thin catalog. */\nexport const OPERATING_DEFAULTS_DIRECTIVE = buildOperatingDefaultsDirective()\n\nconst STANDARD_OPERATING_DEFAULTS_DIGEST =\n \"## Operating defaults (these layer with the user's direction and the domain's standards as addons: follow all three; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + \"Delegate when the work is WIDE (many files or sources to sweep) or SLOW and you need only the \"\n + \"conclusion, to protect the main thread's finite context and keep it free for reasoning and \"\n + \"interacting with the user; prefer parallel delegation for independent work. Do NOT delegate \"\n + \"merely because a sub-question is separable: a narrow, deep question whose value is file:line \"\n + \"fidelity loses exactly that through a summarization layer, and one answerable in a single \"\n + \"command is cheaper done directly. Do trivial, surgical, and last-mile work yourself. \"\n + \"Stop a named teammate once you are done with it: it persists for follow-ups, its idle \"\n + \"notice means available rather than finished, and nothing reaps it for you.\\n\\n\"\n + \"Verify, do not assert. Run the code, read the file, check the exit code. A claim in prose is \"\n + \"worth nothing against state you did not check, and a check that cannot fail proves nothing. \"\n + \"Reproduce a bug end to end, the way a real user hits it, before fixing it. Fix a lint error, \"\n + \"failing test, or flake the moment you see it, whoever introduced it, without letting it \"\n + \"derail the task at hand. Prefer quality and long-term maintainability over development cost.\\n\\n\"\n + \"Verification has a blind spot: a consequential recommendation, a design or trade-off call, or \"\n + \"a hard-to-reverse decision that still turns on judgment among plausible alternatives once the \"\n + \"direct evidence is in. That is where confabulation hides, so put it past a peer critic before \"\n + \"you ship it and budget the wait even under delivery pressure. When a test, a run, a \"\n + \"reproduction, or a search would settle the claim, settle it that way instead; a critic asked \"\n + \"to re-derive what you can already prove is ritual, not review.\\n\\n\"\n + \"The agent roster, the tool surface, and the reasoning behind these defaults are in your \"\n + \"CLAUDE.md project instructions. Read them when choosing HOW to work; the rules above apply \"\n + \"without a lookup.\"\n\nexport function buildOperatingDefaultsDigest(\n opts: { profile?: \"standard\" | \"fast\" | \"cheap\" | \"cheap1m\" | \"cheapest\" | \"cheapest2\" | \"balanced\" | \"balanced2\" | \"max\"; astraAvailable?: boolean; sweEnabled?: boolean } = {},\n): string {\n // --swe-gated pipeline sentence: without the flag the skill files are not\n // written, so the digest must not name them. Absent keeps the legacy text\n // for callers without a flag concept. Cheapest/balanced have no Plan role,\n // so their sentence names lead-direct planning instead of a Plan dispatch.\n const digestPipelineSentence = opts.sweEnabled === false\n ? \"\"\n : isCheapestFamily(opts.profile) || isBalancedFamily(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 profileLabel = isCheapest ? \"Cheapest\" : isCheap ? \"Cheap\" : isBalanced ? \"Balanced\" : \"Fast\"\n const cheapestContract = isCheapest\n ? cheapestContractFor(opts.profile)\n : undefined\n const balancedContract = isBalanced\n ? balancedContractFor(opts.profile)\n : undefined\n const familyContract = cheapestContract ?? balancedContract\n // Both families are lead-only on Oracle (neither has a Plan role), so one\n // contract-derived form serves both: `balanced` Grok 4.6 →\n // `balanced2` Grok 4.7, `cheapest` GPT-5.6 Sol → `cheapest2` GPT-6.1 Sol.\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 // No balanced branch: balanced exposes Oracle but no Advisor, so its\n // ladder (consultationLadder below) never interpolates this descriptor.\n const advisorDescriptor = cheapestContract\n ? `(${displayModelName(cheapestContract.advisorModel)}/${cheapestContract.advisorEffort}, lead-only)`\n : \"(Sol/high, lead-only)\"\n const astraStep =\n opts.astraAvailable && (opts.profile === \"fast\" || opts.profile === \"cheap1m\")\n ? `; (4) \\`astra\\` (GPT-6 Astra 200K/${isCheap ? \"medium\" : \"high\"}, lead-only) only as a last resort when direct evidence, Advisor, and Oracle cannot produce a defensible path (at most 1-2 calls per decision).`\n : \".\"\n const delegation = isCheapest\n ? `${profileLabel} launch profile. The lead owns the outcome and handles straightforward work directly: use \\`Explore\\` for discovery spanning more than a couple of files, \\`General-Purpose\\` for mixed multi-step execution, and \\`reviewer\\` for behavior-changing or risk-sensitive changes. In plan mode, produce the plan and acceptance criteria directly; before presenting the final plan to the user, consult \\`advisor\\` once for a framing check. Plan briefly before non-trivial acts, verify by execution, tag unverified claims, and stop searching when results stop changing the answer. Handle trivial and surgical edits directly. Stop named teammates when finished.\\n\\n`\n + CHEAPEST_CONSULT_CONTRACT_POINTER\n : isBalanced\n ? `${profileLabel} launch profile. The lead owns planning, implementation, and verification by default: narrow scope first with \\`code_search\\` and \\`web\\` search to rule out hypotheses (cheapest, always first); delegate to \\`Explore\\` in parallel only when search is insufficient (read directly only files you will act on); delegate to \\`General-Purpose\\` FREELY for multi-step work combining investigation, tool workflows, and code changes; invoke \\`reviewer\\` ONLY when the change is genuinely behavior-changing, cross-boundary, or risk-sensitive (\\`reviewer\\` narrows scope with search first and may invoke \\`Explore\\` for targeted discovery); handle trivial and surgical edits directly. Send independent subagent calls in parallel within a single turn. Stop named teammates when finished.\\n\\n`\n : `${profileLabel} launch profile. The lead coordinates execution across specialized roles: delegate broad discovery to \\`Explore\\` in parallel and do not sweep the repo yourself (read directly only files you will act on); delegate to \\`Plan\\` in plan mode or when structuring complex multi-step sequencing (\\`Plan\\` is an advisory planning capability, not an approval gate, and writes handoff-ready steps for \\`General-Purpose\\`); delegate mixed multi-step execution and Plan handoffs to \\`General-Purpose\\` in a fresh context; delegate to \\`reviewer\\` after behavior-changing or risk-sensitive implementation to verify correctness before declaring done; handle trivial and surgical edits directly. Send independent subagent calls in parallel within a single turn. Stop named teammates when finished.\\n\\n`\n // Balanced has no Advisor: the ladder is search → Explore → Oracle\n // (second opinion on a framed question, never discovery).\n const consultationLadder = isBalanced\n ? \"Verify claims against real evidence: run relevant commands and tests. Funnel unknowns cheapest-first: (1) `code_search` + `web` search narrow scope and rule out hypotheses first; (2) `Explore` for targeted breadth when search is insufficient; (3) `oracle` \"\n + oracleDescriptor\n + \" as a second opinion for precise, self-contained technical/architectural trade-offs that search and `Explore` cannot settle. Optimize for accuracy, intelligence, and correctness at the lowest cost.\"\n : \"Verify claims against real evidence: run relevant commands and tests. Follow a disciplined consultation ladder for unresolved decisions: (1) direct code inspection, search, builds, and tests settle factual questions; (2) `advisor` \"\n + advisorDescriptor\n + \" for transcript-aware framing checks or trajectory guidance (session momentum/trajectory); (3) `oracle` \"\n + oracleDescriptor\n + \" for self-contained technical/architectural trade-offs\"\n + astraStep\n // Mirror of the directive's windowNote, condensed for the digest.\n const digestWindowNote = isCheapest || isBalanced\n ? \"All roles run at a 200K context window — use targeted reads over full file reads.\\n\\n\"\n : isCheap\n ? \"The lead runs at 200K on `-m cheap` (1M on `-m cheap1m`) and every subagent runs at 200K — use targeted reads over full file reads.\\n\\n\"\n : \"\"\n return (\n \"## Operating defaults (these layer with the user's direction and the domain's standards as addons: follow all three; on a direct conflict the user's direction wins, then the domain standard, then the default below)\\n\\n\"\n + delegation\n + digestPipelineSentence\n + digestWindowNote\n + consultationLadder\n )\n }\n return STANDARD_OPERATING_DEFAULTS_DIGEST\n}\n\n/**\n * Condensed digest of OPERATING_DEFAULTS_DIRECTIVE for the spawned session's\n * system prompt (--append-system-prompt). The FULL directive is prepended to\n * the mirrored CLAUDE.md (read by the main agent and descendants); this digest\n * keeps both behavioral directives at top salience without duplicating the full\n * ~310-token block in the context window every turn. Points to the full copy.\n *\n * The unverifiable-claim rule is here rather than in CLAUDE.md alone because it\n * fires at a moment that suppresses lookups: an agent racing to deliver a\n * recommendation is precisely the one that will not stop to consult its project\n * instructions, which is how the check got crowded out in the first place. It\n * also closes a hole in the rule above it, which only covers claims that direct\n * evidence CAN settle. The roster of critics, the lens-to-artifact match, and\n * the reasoning stay in the directive; the always-resident copy carries only\n * the trigger and the ritual exclusion.\n */\nexport const OPERATING_DEFAULTS_DIGEST = STANDARD_OPERATING_DEFAULTS_DIGEST\n\n/**\n * Skip the helper if the user's `~/.claude/CLAUDE.md` (or, equivalently,\n * the would-be post-write file) has grown past this size.\n * Read-modify-write becomes pathological at very large sizes; CLAUDE.md\n * should never legitimately be a database. The main agent still gets\n * the awareness via `--append-system-prompt`, so skipping here only\n * loses descendant-reach.\n */\nconst MAX_CLAUDE_MD_BYTES = 1 * 1024 * 1024 // 1 MiB\n\n/**\n * Bounded retry budget for the temp → rename step on Windows where\n * `fs.rename` can transiently fail with EBUSY / EPERM / EACCES when\n * CLAUDE.md is open in an editor, scanned by AV, or indexed by the\n * search service. Mirrors the verify-on-rename-fail pattern at\n * `paths.ts:795-818`. POSIX renames almost never fail this way; the\n * cost on Linux/macOS is one extra `lstat` in the unhappy path.\n */\nconst RENAME_RETRY_DELAYS_MS = [50, 200, 500] as const\n\n/**\n * Grep-able error-code prefix. Every warn-and-continue path here\n * starts its message with this token so a Windows user who never sees\n * a fresh marker block in their mirror can `grep CLAUDE_MD_WRITE` in\n * the launcher output and land on the actionable line directly.\n */\nconst ERROR_CODE = \"CLAUDE_MD_WRITE\"\n\ninterface MarkerBlock {\n openLineIndex: number\n closeLineIndex: number\n}\n\n/**\n * Find every well-formed marker block matching the given `markerOpen`\n * + `markerClose` pair. A well-formed block is an exact `markerOpen`\n * line followed somewhere later (any number of intervening lines) by\n * an exact `markerClose` line, with no intervening `markerOpen`.\n * Multiple stale blocks all surface here so the caller can remove\n * all of them.\n *\n * Malformed state (open without close, or close without open) is\n * reported separately via the second return value so the caller can\n * `warn` and leave user prose untouched. We never try to \"fix\"\n * malformed marker state — that risks corrupting user content.\n */\nexport function findMarkerBlocks(\n lines: ReadonlyArray<string>,\n markerOpen: string = PEER_MARKER_OPEN,\n markerClose: string = PEER_MARKER_CLOSE,\n): {\n blocks: Array<MarkerBlock>\n malformed: boolean\n} {\n const blocks: Array<MarkerBlock> = []\n let pendingOpen: number | null = null\n let malformed = false\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n if (line === markerOpen) {\n if (pendingOpen !== null) {\n // Two opens with no close between them — malformed.\n malformed = true\n }\n pendingOpen = i\n } else if (line === markerClose) {\n if (pendingOpen === null) {\n // Close with no preceding open — malformed.\n malformed = true\n } else {\n blocks.push({ openLineIndex: pendingOpen, closeLineIndex: i })\n pendingOpen = null\n }\n }\n }\n if (pendingOpen !== null) {\n // Open with no close — malformed.\n malformed = true\n }\n return { blocks, malformed }\n}\n\n/**\n * Detect line-ending style of `content`. Returns `\"\\r\\n\"` if `\\r\\n`\n * sequences outnumber bare `\\n`; otherwise `\"\\n\"`. Empty content\n * defaults to `\\n` (POSIX-style new file).\n *\n * Preserves CRLF on Windows users' existing CLAUDE.md — flipping their\n * line endings under them would be a regression even though Claude\n * Code itself reads either style.\n */\nfunction detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n if (content.length === 0) return \"\\n\"\n // Count CRLF occurrences. Bare `\\n` count is `\\n total - CRLF count`.\n const crlf = (content.match(/\\r\\n/g) ?? []).length\n const totalLf = (content.match(/\\n/g) ?? []).length\n const bareLf = totalLf - crlf\n return crlf > bareLf ? \"\\r\\n\" : \"\\n\"\n}\n\n/**\n * Strip a leading UTF-8 BOM (`U+FEFF`) if present so the first line's\n * marker comparison is byte-exact. CLAUDE.md authored on Windows in\n * Notepad / VS Code sometimes carries a BOM; without this strip the\n * first marker line would never match (`<BOM><!--...` !== `<!--...`)\n * and successive launches would loop into malformed-state warn paths.\n */\nfunction stripLeadingBom(content: string): string {\n return content.charCodeAt(0) === 0xfeff ? content.slice(1) : content\n}\n\n/**\n * Split `content` into lines without losing the line-ending style.\n * The split is done on `\\n`; trailing `\\r` (from CRLF) is stripped\n * from each line for marker comparison, but the original ending is\n * reconstructed via `detectLineEnding` + `joinLines`.\n */\nfunction splitLines(content: string): Array<string> {\n if (content.length === 0) return []\n const lines = content.split(\"\\n\").map((l) =>\n l.endsWith(\"\\r\") ? l.slice(0, -1) : l,\n )\n // If the file ends in `\\n`, the trailing element is `\"\"` — keep it\n // so we can detect \"trailing newline present\" when rebuilding.\n return lines\n}\n\nfunction joinLines(lines: ReadonlyArray<string>, eol: \"\\r\\n\" | \"\\n\"): string {\n return lines.join(eol)\n}\n\n/**\n * Containment check that defeats symlink/junction tricks (peer-review\n * C3). `isUnderClaudeConfigMirror` is purely lexical via\n * `path.resolve()` — it does NOT dereference symlinks, so an attacker\n * (or an unfortunate `~/.claude` symlinked into Dropbox) could escape\n * the mirror while passing the lexical guard. This helper resolves\n * BOTH paths to their canonical form via `fs.realpath()` first.\n *\n * **Fail-closed semantics (advisor follow-up):**\n *\n * - If the mirror root itself is a symlink (`lstat` reports\n * `isSymbolicLink() === true`), refuse. A symlinked mirror root\n * means writes flow through the link to whatever the user (or an\n * attacker) targeted — the boundary's whole point is to never\n * mutate real `~/.claude/`, so accepting any symlinked root\n * undermines it.\n * - If `realpath` fails on the mirror root OR the target parent,\n * refuse. The mirror dir is provisioned by `ensureClaudeConfigMirror`\n * before this helper runs (documented ordering invariant); a\n * `realpath` failure here signals an unexpected state, and after\n * the root check has already succeeded a missing parent means the\n * root vanished between checks (TOCTOU race).\n */\nexport async function isUnderClaudeConfigMirrorRealpath(\n target: string,\n): Promise<boolean> {\n // Fast lexical reject first: if even the lexical check fails the\n // path is clearly wrong and we never need to touch the filesystem.\n if (!isUnderClaudeConfigMirror(target)) return false\n\n const mirrorRoot = PATHS.CLAUDE_CONFIG_DIR\n\n // Reject a symlinked mirror root. realpath would happily follow it\n // and the resolved target would still appear \"under\" the resolved\n // root — masking the escape.\n try {\n const rootLink = await fs.lstat(mirrorRoot)\n if (rootLink.isSymbolicLink()) {\n consola.warn(\n `${ERROR_CODE}: mirror root is a symlink (${mirrorRoot}); refusing to write through it`,\n )\n return false\n }\n } catch (err) {\n consola.warn(\n `${ERROR_CODE}: cannot lstat mirror root ${mirrorRoot}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n return false\n }\n\n // Canonicalize the mirror root. Failure here is fail-closed — the\n // mirror should exist by the time this helper runs.\n let resolvedRoot: string\n try {\n resolvedRoot = await fs.realpath(mirrorRoot)\n } catch (err) {\n consola.warn(\n `${ERROR_CODE}: realpath failed on mirror root ${mirrorRoot}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n return false\n }\n\n // Canonicalize the target's parent. ENOENT here is fail-closed: the\n // mirror root has already been lstat'd and realpath'd successfully\n // above, so a missing parent at this point means the root vanished\n // between checks — exactly the race-window an attacker would use to\n // swap the mirror with a symlink/junction. Refuse rather than grant\n // access (peer-review codex-critic C1).\n const targetParent = path.dirname(target)\n let resolvedTargetParent: string\n try {\n resolvedTargetParent = await fs.realpath(targetParent)\n } catch (err) {\n consola.warn(\n `${ERROR_CODE}: realpath failed on target parent ${targetParent} after root check (TOCTOU?): ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n return false\n }\n\n if (resolvedTargetParent === resolvedRoot) return true\n return resolvedTargetParent.startsWith(resolvedRoot + path.sep)\n}\n\n/**\n * Try `fs.rename(temp, target)` with bounded retry + verify-on-fail.\n * Mirrors `injectSyntheticClaudeJsonFields` in `paths.ts`. Windows\n * `fs.rename` can transiently fail with EBUSY / EPERM / EACCES when\n * the destination is held by another process (editor, AV, search\n * indexer). Returns `true` on eventual success, `false` after all\n * retries are exhausted (caller will warn-and-continue).\n *\n * On final failure we read the destination back and check whether it\n * already matches `desiredContent` — a concurrent racer may have\n * landed the same bytes (the snippet is deterministic per launch).\n * In that case treat as success.\n *\n * **No `copyFile` fallback** (peer-review codex-critic C2). `fs.copyFile`\n * follows the destination path — if `target` was replaced with a\n * symlink/junction between our earlier `lstat` and now (TOCTOU), or\n * if `target` is a hardlink to the real `~/.claude/CLAUDE.md`,\n * `copyFile` would mutate user files through the link. The boundary\n * we are defending says \"never mutate the real `~/.claude/`\". Rename\n * is safe because replacing a path entry doesn't follow the link; the\n * `copyFile` degradation reintroduces the escape. Fail-closed instead.\n */\nexport async function renameWithRetry(\n tempPath: string,\n target: string,\n desiredContent: string,\n): Promise<boolean> {\n let lastErr: unknown\n for (let attempt = 0; attempt <= RENAME_RETRY_DELAYS_MS.length; attempt++) {\n try {\n await fs.rename(tempPath, target)\n return true\n } catch (err) {\n lastErr = err\n // Don't sleep after the final attempt.\n if (attempt < RENAME_RETRY_DELAYS_MS.length) {\n await new Promise<void>((resolve) =>\n setTimeout(resolve, RENAME_RETRY_DELAYS_MS[attempt]),\n )\n }\n }\n }\n\n // All retries exhausted. Verify-on-fail: did a racer land the same\n // bytes we wanted? (Matches the paths.ts:795-818 pattern.)\n try {\n const observed = await fs.readFile(target, \"utf8\")\n if (observed === desiredContent) {\n await fs.unlink(tempPath).catch(() => {})\n consola.debug(\n `${ERROR_CODE}: rename failed but target already holds expected content (racer-won-race): ${\n lastErr instanceof Error ? lastErr.message : String(lastErr)\n }`,\n )\n return true\n }\n } catch {\n // Fall through to final cleanup + caller-side warn.\n }\n\n // Fail-closed: no copyFile fallback (would follow symlinks/hardlinks\n // and bypass the never-mutate-user-files boundary). Better to lose\n // descendant-reach for this launch than to risk overwriting the\n // user's real CLAUDE.md.\n await fs.unlink(tempPath).catch(() => {})\n consola.warn(\n `${ERROR_CODE}: rename failed for ${target} after ${RENAME_RETRY_DELAYS_MS.length + 1} attempts (no copyFile fallback to avoid symlink/hardlink escape; descendant-reach via CLAUDE.md disabled this launch; main agent still has --append-system-prompt). rename err: ${\n lastErr instanceof Error ? lastErr.message : String(lastErr)\n }`,\n )\n return false\n}\n\n/**\n * Generic marker-block injection into the mirrored CLAUDE.md.\n * Parameterized on the marker pair (so independent blocks coexist\n * without colliding) and position (`\"top\"` = prepend, `\"bottom\"` =\n * append). Encapsulates all the safety invariants; the two exported\n * helpers (`appendPeerAwarenessToMirroredClaudeMd` and\n * `prependStyleDirectiveToMirroredClaudeMd`) are thin wrappers.\n */\ninterface InjectMarkerBlockOpts {\n snippet: string\n markerOpen: string\n markerClose: string\n position: \"top\" | \"bottom\"\n /** Logged in debug messages so the two callers are distinguishable. */\n label: string\n}\n\nasync function injectMarkerBlock(opts: InjectMarkerBlockOpts): Promise<void> {\n const { snippet, markerOpen, markerClose, position, label } = opts\n\n // Invariant 7: writer-side guard. Refuse to inject a snippet that\n // contains either marker literal — otherwise the next launch's\n // parser would see the inner literal as a new open/close and\n // either delete user content (the I5 footgun) or trip the\n // malformed-marker path indefinitely. The snippet body should\n // never legitimately contain these strings; failing fast here\n // catches a builder bug at the source.\n if (snippet.includes(markerOpen) || snippet.includes(markerClose)) {\n consola.warn(\n `${ERROR_CODE}: refusing to inject ${label} snippet that contains marker literal; this would corrupt idempotency on the next launch`,\n )\n return\n }\n\n const target = path.join(PATHS.CLAUDE_CONFIG_DIR, \"CLAUDE.md\")\n\n // Invariant 1: mirror-only safety guard (symlink-resolving).\n if (!(await isUnderClaudeConfigMirrorRealpath(target))) {\n consola.warn(\n `${ERROR_CODE}: refusing to write outside resolved mirror dir (target=${target}, mirror=${PATHS.CLAUDE_CONFIG_DIR}) [${label}]`,\n )\n return\n }\n\n // Invariant 2: refuse to follow symlinks on the leaf. lstat tells\n // us about the link itself; fs.readFile would silently follow.\n let existingContent: string\n let targetExists: boolean\n try {\n const linkStat = await fs.lstat(target)\n if (linkStat.isSymbolicLink()) {\n consola.warn(\n `${ERROR_CODE}: refusing to write through symlinked CLAUDE.md (target=${target}) [${label}]`,\n )\n return\n }\n if (!linkStat.isFile()) {\n // Directory or other non-regular entry sitting where CLAUDE.md\n // should be. Refuse rather than try to fix.\n consola.warn(\n `${ERROR_CODE}: refusing to write non-regular target (target=${target}, mode=${linkStat.mode.toString(8)}) [${label}]`,\n )\n return\n }\n // Early size guard (peer-review codex-critic suggestion #9) — skip\n // before paying the readFile cost. The post-build size guard below\n // catches the runaway-snippet case; this catches the runaway-file\n // case. nlink > 1 also caught here: hardlinked CLAUDE.md to the\n // real user file would otherwise be a path-following escape via\n // fs.writeFile, even with the symlink-refusal above.\n if (linkStat.size > MAX_CLAUDE_MD_BYTES) {\n consola.warn(\n `${ERROR_CODE}: skipping oversized CLAUDE.md (${linkStat.size} bytes > ${MAX_CLAUDE_MD_BYTES}) [${label}]; descendant-reach disabled this launch`,\n )\n return\n }\n if (linkStat.nlink > 1) {\n consola.warn(\n `${ERROR_CODE}: refusing to write to hardlinked CLAUDE.md (nlink=${linkStat.nlink}) [${label}]; would mutate shared inode`,\n )\n return\n }\n targetExists = true\n existingContent = await fs.readFile(target, \"utf8\")\n } catch (err) {\n if (\n typeof err === \"object\"\n && err !== null\n && \"code\" in err\n && (err as { code: string }).code === \"ENOENT\"\n ) {\n // No existing CLAUDE.md — start from empty content.\n existingContent = \"\"\n targetExists = false\n } else {\n consola.warn(\n `${ERROR_CODE}: failed to stat/read target (${target}) [${label}]: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n return\n }\n }\n\n // Invariant 4: detect line-ending style from the existing content\n // AND remember whether the file had a UTF-8 BOM so we can preserve\n // it (peer-review codex-critic I5).\n const hadBom = existingContent.charCodeAt(0) === 0xfeff\n const normalizedContent = stripLeadingBom(existingContent)\n const eol = detectLineEnding(normalizedContent)\n\n // Strip prior well-formed marker blocks of THIS pair only\n // (invariant 5: malformed state is warn-and-leave; we do not edit\n // through user prose). Other marker pairs in the file are untouched\n // so the peer-awareness block and the style block coexist without\n // interfering.\n const lines = splitLines(normalizedContent)\n const { blocks, malformed } = findMarkerBlocks(lines, markerOpen, markerClose)\n if (malformed) {\n consola.warn(\n `${ERROR_CODE}: malformed marker state in ${target} (open without close or vice versa) [${label}]; leaving file untouched`,\n )\n return\n }\n // Remove blocks in reverse order so earlier indices stay valid.\n // Also drop blank-line separators that were inserted around the\n // block on prior writes (loop until non-blank to handle accumulation).\n const cleanedLines = [...lines]\n for (let i = blocks.length - 1; i >= 0; i--) {\n const block = blocks[i]\n cleanedLines.splice(\n block.openLineIndex,\n block.closeLineIndex - block.openLineIndex + 1,\n )\n if (position === \"bottom\") {\n // Drop trailing blank lines BEFORE the (removed) block.\n while (\n block.openLineIndex - 1 >= 0\n && cleanedLines[block.openLineIndex - 1] === \"\"\n && cleanedLines.slice(0, block.openLineIndex - 1).some((l) => l !== \"\")\n ) {\n cleanedLines.splice(block.openLineIndex - 1, 1)\n }\n } else {\n // position === \"top\": drop leading blank lines AFTER the\n // (removed) block — they were the separator we inserted last\n // time between our prepended block and user content.\n while (\n block.openLineIndex < cleanedLines.length\n && cleanedLines[block.openLineIndex] === \"\"\n && cleanedLines.slice(block.openLineIndex + 1).some((l) => l !== \"\")\n ) {\n cleanedLines.splice(block.openLineIndex, 1)\n }\n }\n }\n\n // Trim trailing blank lines so the bottom-append block sits with\n // exactly one separator; for top-prepend, trim leading blanks\n // analogously.\n if (position === \"bottom\") {\n while (\n cleanedLines.length > 0\n && cleanedLines[cleanedLines.length - 1] === \"\"\n ) {\n cleanedLines.pop()\n }\n } else {\n while (cleanedLines.length > 0 && cleanedLines[0] === \"\") {\n cleanedLines.shift()\n }\n }\n\n // Build the final content. Position determines whether our block\n // sits at the top or bottom, with exactly one blank-line separator\n // between user content and our block.\n const snippetLines = snippet.split(\"\\n\").map((l) =>\n l.endsWith(\"\\r\") ? l.slice(0, -1) : l,\n )\n const markerBlockLines = [markerOpen, ...snippetLines, markerClose]\n let finalLines: Array<string>\n if (cleanedLines.length === 0) {\n finalLines = [...markerBlockLines, \"\"]\n } else if (position === \"bottom\") {\n finalLines = [...cleanedLines, \"\", ...markerBlockLines, \"\"]\n } else {\n finalLines = [...markerBlockLines, \"\", ...cleanedLines, \"\"]\n }\n const bodyContent = joinLines(finalLines, eol)\n const finalContent = hadBom ? \"\" + bodyContent : bodyContent\n\n // Invariant 3: size guard, measured on the post-build content so a\n // user fixture sitting just below the cap with a stale block can\n // still be cleaned up (peer-review I6).\n if (Buffer.byteLength(finalContent, \"utf8\") > MAX_CLAUDE_MD_BYTES) {\n consola.warn(\n `${ERROR_CODE}: post-build content exceeds ${MAX_CLAUDE_MD_BYTES} bytes [${label}]; skipping update (descendant-reach disabled this launch)`,\n )\n return\n }\n\n // Invariant 6: atomic temp + rename, with bounded retry + verify-\n // on-fail. No copyFile fallback (would defeat symlink boundary).\n const tempPath = `${target}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`\n try {\n await fs.writeFile(tempPath, finalContent, {\n encoding: \"utf8\",\n flag: \"wx\",\n })\n } catch (err) {\n await fs.unlink(tempPath).catch(() => {})\n consola.warn(\n `${ERROR_CODE}: temp-file write failed for ${tempPath} [${label}]: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n return\n }\n const ok = await renameWithRetry(tempPath, target, finalContent)\n if (!ok) return\n\n consola.debug(\n `${ERROR_CODE}: ${\n targetExists ? \"updated\" : \"created\"\n } ${target} [${label}] (${finalContent.length} bytes, eol=${eol === \"\\r\\n\" ? \"CRLF\" : \"LF\"})`,\n )\n}\n\n/**\n * Append the peer-MCP awareness `snippet` to the mirrored\n * `<CLAUDE_CONFIG_DIR>/CLAUDE.md`. Idempotent across launches: prior\n * well-formed peer-marker blocks are removed before appending a fresh\n * one at the bottom. The original user content is preserved\n * byte-for-byte at the top (modulo line-ending normalization to the\n * file's detected style; leading UTF-8 BOM is preserved).\n *\n * Failures `warn` and return — this surface is the descendant-reach\n * enhancement; the main agent still gets the awareness via\n * `--append-system-prompt`. Every warn message starts with\n * `CLAUDE_MD_WRITE` so users can grep launcher output.\n */\nexport async function appendPeerAwarenessToMirroredClaudeMd(\n snippet: string,\n): Promise<void> {\n await injectMarkerBlock({\n snippet,\n markerOpen: PEER_MARKER_OPEN,\n markerClose: PEER_MARKER_CLOSE,\n position: \"bottom\",\n label: \"peer-mcp-awareness\",\n })\n}\n\n/**\n * Prepend a writing / communication style directive to the TOP of the\n * mirrored `<CLAUDE_CONFIG_DIR>/CLAUDE.md` so every spawned agent\n * reads it first. The directive itself is hard-coded to\n * `STYLE_DIRECTIVE` above; the parameter exists for tests / future\n * configurability. Idempotent across launches via the\n * style-marker fence (separate from the peer-awareness fence, so the\n * two blocks coexist without colliding).\n */\nexport async function prependStyleDirectiveToMirroredClaudeMd(\n directive: string = STYLE_DIRECTIVE,\n): Promise<void> {\n await injectMarkerBlock({\n snippet: directive,\n markerOpen: STYLE_MARKER_OPEN,\n markerClose: STYLE_MARKER_CLOSE,\n position: \"top\",\n label: \"style-directive\",\n })\n}\n\n/**\n * Prepend the operating-defaults directive (orchestrator posture + hybrid\n * excellence lens; `OPERATING_DEFAULTS_DIRECTIVE` above) to the TOP of the\n * mirrored CLAUDE.md so the main agent and descendant agents (Agent subagents,\n * agent-teams teammates) inherit the full statement. The main agent also gets\n * OPERATING_DEFAULTS_DIGEST at higher salience via `--append-system-prompt`.\n * Separate marker fence from the style / peer blocks so all coexist;\n * best-effort (warn-and-continue) like its siblings.\n */\nexport async function prependOperatingDefaultsToMirroredClaudeMd(\n directive: string = OPERATING_DEFAULTS_DIRECTIVE,\n): Promise<void> {\n await injectMarkerBlock({\n snippet: directive,\n markerOpen: OPERATING_MARKER_OPEN,\n markerClose: OPERATING_MARKER_CLOSE,\n position: \"top\",\n label: \"operating-defaults\",\n })\n}\n\n/**\n * Append the toolbelt awareness one-liner (which CLI tools are on PATH)\n * to the bottom of the mirrored CLAUDE.md so descendant agents (Agent\n * subagents, agent-teams teammates) and the main agent learn about the\n * provisioned tools via the mirrored CLAUDE.md. This line is not sent via\n * `--append-system-prompt`.\n * Separate marker fence from the peer-awareness / style blocks.\n */\nexport async function appendToolbeltAwarenessToMirroredClaudeMd(\n snippet: string,\n): Promise<void> {\n await injectMarkerBlock({\n snippet,\n markerOpen: TOOLBELT_MARKER_OPEN,\n markerClose: TOOLBELT_MARKER_CLOSE,\n position: \"bottom\",\n label: \"toolbelt-awareness\",\n })\n}\n\n/**\n * Prepend the artifact-panel review directive to the TOP of the mirrored\n * CLAUDE.md so plans/artifacts are reviewed in the ai-or-die panel by default.\n * Gated by the caller on AIORDIE_SESSION_ID (only useful inside a tab). Separate\n * marker fence; best-effort like the style/peer blocks.\n */\nexport async function prependArtifactPanelDirectiveToMirroredClaudeMd(\n peersKey = \"peers\",\n): Promise<void> {\n await injectMarkerBlock({\n snippet: ARTIFACT_PANEL_DIRECTIVE(peersKey),\n markerOpen: ARTIFACT_MARKER_OPEN,\n markerClose: ARTIFACT_MARKER_CLOSE,\n position: \"top\",\n label: \"artifact-panel-directive\",\n })\n}\n\n/**\n * Test-only exports — internal helpers exposed so unit tests can\n * exercise marker handling and line-ending logic without writing\n * files. NOT part of the public API.\n */\nexport const __testExports = {\n MARKER_OPEN,\n MARKER_CLOSE,\n PEER_MARKER_OPEN,\n PEER_MARKER_CLOSE,\n STYLE_MARKER_OPEN,\n STYLE_MARKER_CLOSE,\n STYLE_DIRECTIVE,\n ARTIFACT_MARKER_OPEN,\n ARTIFACT_MARKER_CLOSE,\n ARTIFACT_PANEL_DIRECTIVE,\n PIPELINE_SKILLS_AWARENESS,\n MAX_CLAUDE_MD_BYTES,\n ERROR_CODE,\n RENAME_RETRY_DELAYS_MS,\n detectLineEnding,\n stripLeadingBom,\n splitLines,\n joinLines,\n isUnderClaudeConfigMirrorRealpath,\n renameWithRetry,\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4BA,MAAM,mBACJ;AACF,MAAM,oBAAoB;AAE1B,MAAM,oBACJ;AACF,MAAM,qBAAqB;AAE3B,MAAM,wBAC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AG,WAAW,IACZ,eAAe,YAAY,UAC5B,GAAG,OAAO,IAAI,MAAM,KAAK,aAAa,OAAO,cAAc,QAAQ,SAAS,SAAS,KAAK,EAC7F;AACF;;;;;;;;;;;;;;AAeA,eAAsB,sCACpB,SACe;CACf,MAAM,kBAAkB;EACtB;EACA,YAAY;EACZ,aAAa;EACb,UAAU;EACV,OAAO;CACT,CAAC;AACH;;;;;;;;;;AAWA,eAAsB,wCACpB,YAAoB,iBACL;CACf,MAAM,kBAAkB;EACtB,SAAS;EACT,YAAY;EACZ,aAAa;EACb,UAAU;EACV,OAAO;CACT,CAAC;AACH;;;;;;;;;;AAWA,eAAsB,2CACpB,YAAoB,8BACL;CACf,MAAM,kBAAkB;EACtB,SAAS;EACT,YAAY;EACZ,aAAa;EACb,UAAU;EACV,OAAO;CACT,CAAC;AACH;;;;;;;;;AAUA,eAAsB,0CACpB,SACe;CACf,MAAM,kBAAkB;EACtB;EACA,YAAY;EACZ,aAAa;EACb,UAAU;EACV,OAAO;CACT,CAAC;AACH;;;;;;;AAQA,eAAsB,gDACpB,WAAW,SACI;CACf,MAAM,kBAAkB;EACtB,SAAS,yBAAyB,QAAQ;EAC1C,YAAY;EACZ,aAAa;EACb,UAAU;EACV,OAAO;CACT,CAAC;AACH"}
|
package/dist/engine-DgmsdkCe.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { C as runWorkerAgent } from "./peer-mcp-personas-CVxXq1Q-.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { o as sweepStaleWorktreesAtBoot } from "./lifecycle-pl9QpvqD.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { o as sweepStaleColbertMetaAtBoot } from "./lifecycle-C6cxM_Nk.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"paths-BSI_EtDT.js","names":[],"sources":["../src/lib/cloudagent-hook-settings.ts","../src/lib/paths.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\nconst HTTP_EVENT_TIMEOUTS = new Map<string, number>([\n [\"PreToolUse\", 10],\n [\"PostToolUse\", 10],\n [\"PostToolUseFailure\", 10],\n [\"PermissionRequest\", 1800],\n [\"Stop\", 10],\n [\"Notification\", 10],\n [\"UserPromptSubmit\", 10],\n [\"SubagentStart\", 10],\n [\"SubagentStop\", 10],\n [\"PreCompact\", 10],\n [\"TeammateIdle\", 10],\n [\"TaskCompleted\", 10],\n [\"SessionEnd\", 10],\n])\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\nconst URL_IN_COMMAND_RE = /http:\\/\\/127\\.0\\.0\\.1:\\d+\\/hook\\/[0-9a-f-]+/gi\nconst RENAME_RETRY_DELAYS_MS = [25, 75, 200] as const\nconst PARSE_RETRY_DELAYS_MS = [10, 25, 75] as const\nconst RETRYABLE_RENAME_CODES = new Set([\"EACCES\", \"EBUSY\", \"EPERM\"])\n\ntype JsonObject = Record<string, unknown>\n\ninterface CloudAgentEndpoint {\n url: string\n port: number\n nonce: string\n key: string\n}\n\nexport interface CloudAgentHookSanitizeResult {\n written: boolean\n removed: number\n endpointCount: number\n invalid?: \"malformed-json\" | \"non-object\"\n}\n\nfunction isObject(value: unknown): value is JsonObject {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n}\n\nfunction parseCloudAgentEndpoint(raw: string): CloudAgentEndpoint | undefined {\n let parsed: URL\n try {\n parsed = new URL(raw)\n } catch {\n return undefined\n }\n if (\n parsed.protocol !== \"http:\"\n || parsed.hostname !== \"127.0.0.1\"\n || parsed.username !== \"\"\n || parsed.password !== \"\"\n || parsed.search !== \"\"\n || parsed.hash !== \"\"\n || parsed.port === \"\"\n ) {\n return undefined\n }\n const segments = parsed.pathname.split(\"/\").filter(Boolean)\n if (segments.length !== 2 || segments[0] !== \"hook\" || !UUID_RE.test(segments[1]!)) {\n return undefined\n }\n const port = Number.parseInt(parsed.port, 10)\n if (!Number.isInteger(port) || port <= 0 || port > 65_535) return undefined\n const nonce = segments[1]!.toLowerCase()\n const url = `http://127.0.0.1:${port}/hook/${segments[1]!}`\n return { url, port, nonce, key: `${port}/${nonce}` }\n}\n\nfunction singleHookConfig(value: unknown): JsonObject | undefined {\n if (!isObject(value) || value.matcher !== \"*\") return undefined\n const hooks = value.hooks\n if (!Array.isArray(hooks) || hooks.length !== 1 || !isObject(hooks[0])) return undefined\n return hooks[0]\n}\n\nfunction httpEndpoint(value: unknown, expectedTimeout?: number): CloudAgentEndpoint | undefined {\n const config = singleHookConfig(value)\n if (\n !config\n || config.type !== \"http\"\n || typeof config.url !== \"string\"\n || (expectedTimeout !== undefined && config.timeout !== expectedTimeout)\n ) {\n return undefined\n }\n return parseCloudAgentEndpoint(config.url)\n}\n\nfunction commandEndpoint(value: unknown): CloudAgentEndpoint | undefined {\n const config = singleHookConfig(value)\n if (!config || config.type !== \"command\" || typeof config.command !== \"string\") {\n return undefined\n }\n const urls = config.command.match(URL_IN_COMMAND_RE) ?? []\n if (urls.length !== 1) return undefined\n const endpoint = parseCloudAgentEndpoint(urls[0]!)\n if (!endpoint) return undefined\n const windows = `curl.exe -q -sS --noproxy \"*\" --connect-timeout 2 --max-time 5 -H \"Content-Type: application/json\" --data-binary @- \"${endpoint.url}\" 1>NUL 2>NUL`\n const posix = `curl -q -sS --noproxy '*' --connect-timeout 2 --max-time 5 -H 'Content-Type: application/json' --data-binary @- '${endpoint.url}' >/dev/null 2>&1 || true`\n return config.command === windows || config.command === posix ? endpoint : undefined\n}\n\nfunction cloudAgentPorts(hooks: JsonObject): Set<number> {\n const ports = new Set<number>()\n\n const starts = hooks.SessionStart\n if (Array.isArray(starts)) {\n for (const entry of starts) {\n const endpoint = commandEndpoint(entry)\n if (endpoint) ports.add(endpoint.port)\n }\n }\n\n const cohort = new Map<string, { endpoint: CloudAgentEndpoint; events: Set<string> }>()\n for (const [event, timeout] of HTTP_EVENT_TIMEOUTS) {\n const entries = hooks[event]\n if (!Array.isArray(entries)) continue\n for (const entry of entries) {\n const endpoint = httpEndpoint(entry, timeout)\n if (!endpoint) continue\n const seen = cohort.get(endpoint.key) ?? { endpoint, events: new Set<string>() }\n seen.events.add(event)\n cohort.set(endpoint.key, seen)\n }\n }\n for (const { endpoint, events } of cohort.values()) {\n if (events.size === HTTP_EVENT_TIMEOUTS.size) ports.add(endpoint.port)\n }\n return ports\n}\n\nfunction removeCloudAgentEntries(hooks: JsonObject, ports: ReadonlySet<number>): {\n hooks: JsonObject\n removed: number\n endpoints: Set<string>\n} {\n const nextHooks: JsonObject = { ...hooks }\n const endpoints = new Set<string>()\n let removed = 0\n for (const [event, rawEntries] of Object.entries(hooks)) {\n if (!Array.isArray(rawEntries)) continue\n const kept = rawEntries.filter((entry) => {\n const endpoint = httpEndpoint(entry) ?? commandEndpoint(entry)\n if (!endpoint || !ports.has(endpoint.port)) return true\n endpoints.add(endpoint.key)\n removed += 1\n return false\n })\n if (kept.length !== rawEntries.length) nextHooks[event] = kept\n }\n return { hooks: nextHooks, removed, endpoints }\n}\n\nasync function renameWithRetry(\n temp: string,\n target: string,\n desiredContent: string,\n): Promise<void> {\n let lastError: unknown\n for (let attempt = 0; attempt <= RENAME_RETRY_DELAYS_MS.length; attempt += 1) {\n try {\n await fs.rename(temp, target)\n return\n } catch (error) {\n lastError = error\n const retryable = RETRYABLE_RENAME_CODES.has(\n (error as NodeJS.ErrnoException).code ?? \"\",\n )\n if (!retryable || attempt === RENAME_RETRY_DELAYS_MS.length) break\n await new Promise<void>((resolve) =>\n setTimeout(resolve, RENAME_RETRY_DELAYS_MS[attempt]),\n )\n }\n }\n\n // A concurrent mirror provision may have won the rename race. Its transform\n // is deterministic, so identical destination bytes mean the requested state\n // already landed and this operation succeeded despite Windows reporting the\n // losing rename as EPERM/EBUSY.\n try {\n if (await fs.readFile(target, \"utf8\") === desiredContent) {\n await fs.rm(temp, { force: true }).catch(() => {})\n return\n }\n } catch {\n // Fall through and preserve the original rename error.\n }\n throw lastError\n}\n\n/**\n * Remove Microsoft Cloud Agent Hub's rotating localhost hooks from one router-owned\n * settings mirror. Cloud Agent replaces its per-daemon UUID on restart; retaining\n * those URLs in a one-way launch snapshot makes every later hook call return\n * 404. The operator's canonical settings file is never touched.\n */\nexport async function sanitizeCloudAgentHooksInSettingsFile(\n settingsPath: string,\n): Promise<CloudAgentHookSanitizeResult> {\n let parsed: unknown\n for (let attempt = 0; ; attempt += 1) {\n let raw: string\n try {\n raw = await fs.readFile(settingsPath, \"utf8\")\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code ?? \"\"\n if (code === \"ENOENT\") {\n return { written: false, removed: 0, endpointCount: 0 }\n }\n if (\n RETRYABLE_RENAME_CODES.has(code)\n && attempt < PARSE_RETRY_DELAYS_MS.length\n ) {\n await new Promise<void>((resolve) =>\n setTimeout(resolve, PARSE_RETRY_DELAYS_MS[attempt]),\n )\n continue\n }\n throw error\n }\n try {\n const json = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw\n parsed = JSON.parse(json)\n break\n } catch {\n // Concurrent mirror provisions can copy and sanitize the same destination.\n // Retry a torn read briefly; a persistently malformed file cannot contain\n // loadable hooks, so preserve it unchanged and let Claude Code apply its\n // existing invalid-settings behavior.\n if (attempt >= PARSE_RETRY_DELAYS_MS.length) {\n return {\n written: false,\n removed: 0,\n endpointCount: 0,\n invalid: \"malformed-json\",\n }\n }\n await new Promise<void>((resolve) =>\n setTimeout(resolve, PARSE_RETRY_DELAYS_MS[attempt]),\n )\n }\n }\n\n if (!isObject(parsed)) {\n return {\n written: false,\n removed: 0,\n endpointCount: 0,\n invalid: \"non-object\",\n }\n }\n if (!isObject(parsed.hooks)) {\n return { written: false, removed: 0, endpointCount: 0 }\n }\n\n const ports = cloudAgentPorts(parsed.hooks)\n if (ports.size === 0) {\n return { written: false, removed: 0, endpointCount: 0 }\n }\n const sanitized = removeCloudAgentEntries(parsed.hooks, ports)\n if (sanitized.removed === 0) {\n return { written: false, removed: 0, endpointCount: 0 }\n }\n\n const next = { ...parsed, hooks: sanitized.hooks }\n const content = `${JSON.stringify(next, null, 2)}\\n`\n const temp = `${settingsPath}.${process.pid}.${randomBytes(4).toString(\"hex\")}.cloudagent.tmp`\n await fs.mkdir(path.dirname(settingsPath), { recursive: true })\n try {\n await fs.writeFile(temp, content, { mode: 0o600, flag: \"wx\" })\n await renameWithRetry(temp, settingsPath, content)\n } catch (error) {\n await fs.rm(temp, { force: true }).catch(() => {})\n throw error\n }\n return {\n written: true,\n removed: sanitized.removed,\n endpointCount: sanitized.endpoints.size,\n }\n}\n","import { randomBytes } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nimport consola from \"consola\"\n\nimport { sanitizeCloudAgentHooksInSettingsFile } from \"./cloudagent-hook-settings\"\n\nfunction appDir(): string {\n return path.join(os.homedir(), \".local\", \"share\", \"github-router\")\n}\n\nexport const PATHS = {\n get APP_DIR() {\n return appDir()\n },\n get GITHUB_TOKEN_PATH() {\n return path.join(appDir(), \"github_token\")\n },\n /**\n * Second, WRITE-capable GitHub token for the first-mate\n * agent-orchestration surface (`--agents`), stored apart from\n * `github_token` (the Copilot App token). Minted by\n * `setupGitHubAgentToken()` via a device-flow login against the GitHub\n * CLI OAuth client. Mode 0o600.\n */\n get GITHUB_AGENT_TOKEN_PATH() {\n return path.join(appDir(), \"github_agent_token\")\n },\n /**\n * Root of the durable first-mate fleet registry (`--agents`): the\n * global `missions.json` mission index + per-repo `<owner>__<repo>.json`\n * unit ledgers + the decisions/approvals ledger. Cross-launch and\n * OUTSIDE the per-launch CLAUDE_CONFIG_DIR mirror (which is swept each\n * launch) — the first mate must survive proxy restarts / context\n * clears. Modeled on the worker-agent lifecycle ledger.\n */\n get FIRST_MATE_DIR() {\n return (\n process.env.GH_ROUTER_FIRST_MATE_DIR ?? path.join(appDir(), \"first-mate\")\n )\n },\n get ERROR_LOG_PATH() {\n return path.join(appDir(), \"error.log\")\n },\n /**\n * Durable, router-owned directory for worker OVERFLOW artifacts. Two\n * kinds land here, both kept OUT of the MCP result relay so they don't\n * overflow Claude Code's 25k-token cap:\n * - `<pid>-<8hex>.patch` — a `worker_implement`/`worker_test` worktree\n * diff larger than `PREVIEW_CAP` (worker-agent/worktree.ts): the FULL\n * `git diff --binary --full-index` patch, written BEFORE the worktree\n * is removed so the (possibly binary) change stays `git apply`-able.\n * - `<pid>-<8hex>.txt` — any worker result over the relay byte cap\n * (worker-agent/relay-cap.ts `relaySafeText`): the full result text,\n * with a bounded preview + this path returned in its place.\n * `sweepAgedWorkerDiffs()` reaps entries older than 7 days on each write.\n * Cross-launch cache (like TOOLBELT_BIN_DIR) — deliberately OUTSIDE the\n * per-launch CLAUDE_CONFIG_DIR mirror and OUTSIDE the user's repo.\n */\n get WORKER_DIFFS_DIR() {\n return path.join(appDir(), \"worker-diffs\")\n },\n /**\n * Stable home for the relocated hook launcher (`hooks-<sha256>.mjs`).\n *\n * Claude Code hook commands are persisted into a settings.json that outlives\n * the process that wrote them. Under `bunx` the package tree lives in\n * `$TMPDIR`, which macOS reaps — so a command pointing there dies on its\n * first bare import and every hook in the session fails. This directory is\n * under APP_DIR precisely because APP_DIR is neither a cache nor a temp dir\n * and is therefore never reaped. Entries are content-addressed and immutable,\n * so two proxies on different versions coexist and neither can delete a\n * launcher the other is still using.\n */\n get HOOK_LAUNCHER_DIR() {\n return path.join(appDir(), \"hooks\")\n },\n /**\n * Durable copy of the tree-sitter WASM runtime and the grammar subset used\n * by code search. The package tree can live under a reaped bunx temp dir;\n * APP_DIR is stable across launches, so structural ranking and outlines do\n * not silently disappear after the original install files are removed.\n */\n get TREE_SITTER_ASSETS_DIR() {\n return path.join(appDir(), \"tree-sitter\")\n },\n /**\n * Isolated CODEX_HOME for the spawned Codex CLI. Masks any cached\n * ChatGPT subscription login (openai/codex#2733 — cached login can\n * override OPENAI_API_KEY) so the proxy's dummy key is authoritative.\n */\n get CODEX_HOME() {\n return path.join(appDir(), \"codex-isolated\")\n },\n /**\n * Router-owned install + data dir for CloudCLI (the `serve` browser control\n * plane). Holds the pinned local `npm install` (node_modules/), an isolated\n * `auth.db` (so we never collide with a user's standalone CloudCLI DB), and\n * the persisted `.serve-secret.json` login. See docs/serve-control-plane.md.\n */\n get CLOUDCLI_HOME() {\n return path.join(appDir(), \"cloudcli\")\n },\n /**\n * Runtime tempfiles for the per-launch peer-MCP wiring (the\n * `--mcp-config` JSON and `--agents` JSON written before spawning\n * Claude Code). Mode 0o700 to match the security review's mandate;\n * cleaned on shutdown via the per-launch `cleanup()`, plus a\n * boot-time sweep of stale files (dead PIDs, >24h old).\n */\n get CLAUDE_RUNTIME_DIR() {\n return path.join(appDir(), \"runtime\")\n },\n /**\n * Router-owned CLAUDE_CONFIG_DIR. The spawned Claude Code (and any\n * teammates it spawns via the agent-teams primitive) reads its\n * config — including `.credentials.json` — from this dir. We\n * snapshot-copy the user's `~/.claude/` here at startup (excluding\n * `.credentials.json` and volatile state), then write our own\n * synthetic Console OAuth credential. The teammate-spawn allowlist\n * propagates `CLAUDE_CONFIG_DIR` to children, so teammates find the\n * synthetic credential and authenticate instead of falling into the\n * \"Not logged in · Run /login\" gate that would otherwise leave\n * them mute. See `ensureClaudeConfigMirror` below.\n *\n * Per-launch dir: `<appDir>/claude-config/<pid>-<8 hex>`. Two\n * concurrent `github-router claude` launches each get their own\n * isolated mirror, so per-launch state (synthetic credential,\n * snapshot copy of `~/.claude/`, future per-launch `.claude.json`\n * mutation with the peer-MCP entry) cannot cross-talk. The\n * per-launch suffix is cached on first access (see\n * `claudeConfigDirSuffix()`) so all callers within a single proxy\n * lifetime see the same value. Boot-time `sweepStaleClaudeConfigMirrors`\n * reaps mirrors from crashed prior PIDs.\n */\n get CLAUDE_CONFIG_DIR() {\n return path.join(appDir(), \"claude-config\", claudeConfigDirSuffix())\n },\n /**\n * Durable router-owned `bin/` for the LLM toolbelt — curated CLI\n * tools (rg/fd/jq/sd/sg/yq) materialized here and prepended to the\n * spawned agent's PATH. Intentionally OUTSIDE the per-launch\n * CLAUDE_CONFIG_DIR mirror (which is swept per launch): the toolbelt\n * is a cross-launch cache, like `last-update-check`.\n */\n get TOOLBELT_BIN_DIR() {\n return path.join(appDir(), \"bin\")\n },\n /**\n * Root of the github-router-managed ColBERT semantic-search sidecar\n * (the `--semantic-search` opt-in). Everything heavy that the\n * `colgrep` child needs is provisioned, SHA-verified, and stored here\n * by the router — never in the user's repo, never in colgrep's own\n * global `%APPDATA%\\colgrep` / `~/.config/colgrep`. Cross-launch cache\n * (like TOOLBELT_BIN_DIR), deliberately OUTSIDE the per-launch\n * CLAUDE_CONFIG_DIR mirror.\n *\n * Layout (see docs/research/colbert-sidecar-design.md §4):\n * colbert/\n * bin/colgrep[.exe] # provisioned binary\n * models/LateOn-Code-edge/<rev>/ # 5 model files\n * onnxruntime/1.23.0/cpu/<libname> # ORT dylib (ORT_DYLIB_PATH)\n * indices/ # === COLGREP_DATA_DIR ===\n * <project>-<xxh3(path|model)>/ # colgrep-owned per-(path,model)\n * .gh-router-meta/<hash>.json # router-owned sidecar metadata\n */\n get COLBERT_DIR() {\n return path.join(appDir(), \"colbert\")\n },\n get COLBERT_BIN_DIR() {\n return path.join(appDir(), \"colbert\", \"bin\")\n },\n get COLBERT_MODELS_DIR() {\n return path.join(appDir(), \"colbert\", \"models\")\n },\n get COLBERT_ORT_DIR() {\n return path.join(appDir(), \"colbert\", \"onnxruntime\")\n },\n /**\n * Value passed to colgrep as `COLGREP_DATA_DIR`. colgrep keys the\n * physical index dir by `xxh3(canonical_project_path | model)` under\n * here, so every distinct workspace gets its own index dir for free.\n * The router-owned freshness sidecar lives at\n * `<COLBERT_INDICES_DIR>/.gh-router-meta/<hash>.json`.\n */\n get COLBERT_INDICES_DIR() {\n return path.join(appDir(), \"colbert\", \"indices\")\n },\n get COLBERT_META_DIR() {\n return path.join(appDir(), \"colbert\", \"indices\", \".gh-router-meta\")\n },\n}\n\n/**\n * Per-launch suffix for `PATHS.CLAUDE_CONFIG_DIR`. Lazily generated on\n * first access and cached for the lifetime of the process so every\n * caller (env-var injection in `getClaudeCodeEnvVars`,\n * `ensureClaudeConfigMirror` provisioning, peer-agent `.md` writes\n * under `<dir>/agents/`, the shutdown cleanup) resolves the same path.\n *\n * Shape: `<pid>-<8 hex>`. The PID prefix is what\n * `sweepStaleClaudeConfigMirrors` keys off to drop orphans from\n * crashed prior sessions; the 8-hex random suffix prevents collision\n * if a future caller (tests, internal relaunch) ever clears the cache\n * within a single PID lifetime.\n *\n * NOT exported — every consumer should go through `PATHS.CLAUDE_CONFIG_DIR`\n * so the homedir-mock pattern used in the test suite keeps working.\n */\nlet _claudeConfigDirSuffix: string | undefined\nfunction claudeConfigDirSuffix(): string {\n if (_claudeConfigDirSuffix === undefined) {\n _claudeConfigDirSuffix = `${process.pid}-${randomBytes(4).toString(\"hex\")}`\n }\n return _claudeConfigDirSuffix\n}\n\n/**\n * Predicate: is `target` inside the current launch's `CLAUDE_CONFIG_DIR`?\n *\n * Used as a defence-in-depth safety guard by helpers that mutate files\n * under the mirror dir (e.g. `appendPeerAwarenessToMirroredClaudeMd`).\n * If `PATHS.CLAUDE_CONFIG_DIR` has somehow been pointed at the user's\n * real `~/.claude/` (configuration drift, future code regression), the\n * helper refuses to write — the proxy should never mutate user files.\n *\n * Pure-prefix `startsWith` is unsafe (`/a/foo` matches `/a/foobar`), so\n * this requires either equality or `<root><sep>...` strictly.\n * Synchronous because we don't need real-path resolution; symlink\n * refusal lives at the consuming helper.\n */\nexport function isUnderClaudeConfigMirror(target: string): boolean {\n const resolvedRoot = path.resolve(PATHS.CLAUDE_CONFIG_DIR)\n const resolvedTarget = path.resolve(target)\n if (resolvedTarget === resolvedRoot) return true\n return resolvedTarget.startsWith(resolvedRoot + path.sep)\n}\n\nexport async function ensurePaths(): Promise<void> {\n await fs.mkdir(PATHS.APP_DIR, { recursive: true })\n await fs.mkdir(PATHS.CODEX_HOME, { recursive: true })\n await fs.mkdir(PATHS.CLAUDE_RUNTIME_DIR, { recursive: true })\n // mkdir({recursive: true}) does NOT chmod an existing directory, so\n // explicitly tighten in case the dir was created by an older version.\n await chmodIfPossible(PATHS.CLAUDE_RUNTIME_DIR, 0o700)\n await ensureFile(PATHS.GITHUB_TOKEN_PATH)\n // Second (write-capable) GitHub token file for `--agents`. Always\n // ensured so the path exists; only populated by a device-flow login\n // when the agent surface is opted in. Tightened to 0o600 (it holds a\n // repo/workflow-scoped credential).\n await ensureFile(PATHS.GITHUB_AGENT_TOKEN_PATH)\n await chmodIfPossible(PATHS.GITHUB_AGENT_TOKEN_PATH, 0o600)\n await sweepStaleRuntimeFiles().catch((err) => {\n consola.debug(\"Runtime sweep skipped:\", err)\n })\n // Sweep stale per-launch CLAUDE_CONFIG_DIR mirrors left behind by\n // crashed prior proxy sessions BEFORE peer-agent .md sweep, since\n // the .md sweep is scoped to THIS launch's mirror and the per-launch\n // dir sweep is the parent cleanup for the same orphan class.\n await sweepStaleClaudeConfigMirrors().catch((err) => {\n consola.debug(\"Per-launch claude-config sweep skipped:\", err)\n })\n // Phase 2.5: also sweep stale peer-* subagent .md files from this\n // launch's CLAUDE_CONFIG_DIR/agents/ (defense-in-depth — should be\n // a no-op since the per-launch dir didn't exist before this PID\n // started; keeps the safety net in case a future change ever shares\n // an agents/ dir across launches).\n await sweepStalePeerAgentMdFiles().catch((err) => {\n consola.debug(\"Peer-agent .md sweep skipped:\", err)\n })\n // Worker-agent boot-time PID+instance safety net. Walks the\n // worker-repos.json ledger and removes any worktree dir whose\n // <pid> is dead OR whose <instance> UUID doesn't match this proxy.\n // Catches SIGKILL/OOM/host-crash escapees from prior sessions.\n // Lazy-imported so the worker-agent module doesn't get loaded by\n // every consumer of `paths.ts`.\n await (async () => {\n const mod = await import(\"./worker-agent/lifecycle\")\n await mod.sweepStaleWorktreesAtBoot()\n })().catch((err) => {\n consola.debug(\"Worker worktree boot sweep skipped:\", err)\n })\n // ColBERT sidecar boot sweep: reclassify any `.gh-router-meta/*.json`\n // entry stuck in `building` with a dead `buildPid` → `failed`, so the\n // next `code` semantic-mode call re-kicks a build instead of routing to\n // a never-finishing one. NEVER kills a PID from a prior boot. Lazy-\n // imported so paths.ts doesn't drag the colbert module into every\n // consumer.\n await (async () => {\n const mod = await import(\"./colbert/lifecycle\")\n await mod.sweepStaleColbertMetaAtBoot()\n })().catch((err) => {\n consola.debug(\"ColBERT meta boot sweep skipped:\", err)\n })\n}\n\n/**\n * Per-entry mirror policy. Every top-level entry under `~/.claude/` falls\n * into exactly one bucket; unlisted names default to `MIRRORED` so a future\n * Claude-Code-side addition flows through as a snapshot copy rather than\n * being silently lost.\n *\n * Three policies:\n *\n * - `ISOLATED` — not present in the mirror at all. The proxy owns its\n * own copy (synthetic `.credentials.json`, the `.github-router-managed`\n * marker) or the entry has no place in a proxy session\n * (`.credentials.json.lock`, `.oauth_refresh.lock` couple refresh loops\n * across sessions; `statsig/` is write-heavy and would constantly\n * re-copy; `cache/` and `logs/` are ephemeral; `paste-cache/` holds\n * sensitive clipboard extracts and shouldn't leak across sessions —\n * gemini-critic finding).\n *\n * - `SHARED` — symlink `<mirror>/<X>` → `~/.claude/<X>` so writes made\n * during the proxy session land in the user's real `~/.claude/` and\n * chat history is visible in both proxy and plain-`claude` sessions.\n * **Directories only.** Never use this for individual files: Claude\n * Code's atomic-write pattern (`fs.writeFile(temp); fs.rename(temp,\n * target)`) does NOT follow symlinks — a `rename` over the symlink\n * replaces it with a regular file, silently severing the connection\n * to `~/.claude/<X>`. Gemini-critic finding from the 3-lab review.\n *\n * - `MIRRORED` (default) — snapshot-copy with mtime skip. Use for static\n * or settings-shaped state where proxy-session writes should NOT flow\n * back to `~/.claude/` (e.g. `settings.json`, `.claude.json`,\n * `teams/`, `session-env/`) and for `agents/` — the proxy itself\n * writes per-launch `peer-<pid>-*.md` files into the mirror's `agents/`\n * and `sweepStalePeerAgentMdFiles` deletes them; a symlink would route\n * those writes/deletes into the user's real `~/.claude/agents/` and\n * destroy the user's own subagent files. **Hard regression test**:\n * `policyFor(\"agents\") === \"MIRRORED\"` is asserted in\n * `tests/isolated/lib-paths.test.ts` to prevent accidental reclassification.\n *\n * Sub-paths within MIRRORED dirs cascade recursively (existing behavior).\n */\ntype MirrorPolicy = \"ISOLATED\" | \"SHARED\" | \"MIRRORED\"\n\nconst CLAUDE_HOME_POLICY: ReadonlyMap<string, MirrorPolicy> = new Map<\n string,\n MirrorPolicy\n>([\n // ISOLATED\n [\".credentials.json\", \"ISOLATED\"],\n [\".credentials.json.lock\", \"ISOLATED\"],\n [\".oauth_refresh.lock\", \"ISOLATED\"],\n // Defense-in-depth: don't let a user-side file/symlink with the same\n // name as our marker collide with what we write. The marker write\n // logic also lstat-checks before writing (refuses if a non-regular\n // file exists at the path), but excluding it here removes the\n // attack vector entirely.\n [\".github-router-managed\", \"ISOLATED\"],\n [\"statsig\", \"ISOLATED\"],\n [\"cache\", \"ISOLATED\"],\n [\"logs\", \"ISOLATED\"],\n [\"paste-cache\", \"ISOLATED\"],\n [\"jobs\", \"ISOLATED\"],\n [\"daemon\", \"ISOLATED\"],\n [\"daemon.log\", \"ISOLATED\"],\n // SHARED — directories only (see policy doc above)\n [\"projects\", \"SHARED\"],\n [\"sessions\", \"SHARED\"],\n [\"tasks\", \"SHARED\"],\n [\"todos\", \"SHARED\"],\n [\"transcripts\", \"SHARED\"],\n [\"shell-snapshots\", \"SHARED\"],\n // The underscored variant is the historical exclude-list name; some\n // Claude Code versions may still use it. Classify SHARED so either\n // spelling resolves correctly.\n [\"shell_snapshots\", \"SHARED\"],\n [\"plans\", \"SHARED\"],\n [\"file-history\", \"SHARED\"],\n [\"backups\", \"SHARED\"],\n])\n\nfunction policyFor(name: string): MirrorPolicy {\n return CLAUDE_HOME_POLICY.get(name) ?? \"MIRRORED\"\n}\n\n/**\n * Test-only export: lets the test suite assert hard regression guards\n * such as `policyFor(\"agents\") === \"MIRRORED\"` (preventing accidental\n * reclassification that would let `sweepStalePeerAgentMdFiles` delete\n * files in the user's real `~/.claude/agents/`).\n */\nexport const __testing = {\n policyFor,\n ensureSharedSymlink,\n // The mirror walk runs concurrently under a bounded semaphore; both are\n // exposed so tests can prove the copy stays byte-identical to the serial\n // version and that the bound actually bounds.\n mirrorDirRecursive: (sourceDir: string, targetDir: string, relPath: string) =>\n mirrorDirRecursive(sourceDir, targetDir, relPath),\n createSemaphore,\n get MIRROR_COPY_CONCURRENCY() {\n return MIRROR_COPY_CONCURRENCY\n },\n}\n\n/**\n * Names with `SHARED` policy, materialized once for iteration in\n * `ensureClaudeConfigMirror`'s post-copy phase.\n */\nconst SHARED_TOPLEVEL_NAMES: ReadonlyArray<string> = Array.from(\n CLAUDE_HOME_POLICY.entries(),\n)\n .filter(([, kind]) => kind === \"SHARED\")\n .map(([name]) => name)\n\n/**\n * Marker file written into the router-owned CLAUDE_CONFIG_DIR so users\n * (and our own future sweeps) can identify that the dir is managed by\n * github-router. Content is informational only; no logic depends on\n * its presence.\n */\nconst MANAGED_MARKER_FILENAME = \".github-router-managed\"\n\n/**\n * Synthetic Console OAuth credential the router writes into its own\n * `CLAUDE_CONFIG_DIR/.credentials.json` so spawned Claude Code (and\n * any teammates it spawns) can authenticate without a real user\n * `/login`.\n *\n * Schema verified verbatim from `claude` v2.1.140 binary, function\n * `guH` (the credentials-save mutation). Fields:\n * - `accessToken` — sent as `Authorization: Bearer ...` to the\n * proxy. Proxy accepts any bearer (per CLAUDE.md \"doesn't enforce\n * auth\").\n * - `refreshToken` — only used by Claude Code's reactive refresh\n * path (function `nH8`), which fires on 401 from upstream. The\n * proxy maintains the no-401 invariant on the Anthropic-shape\n * boundary, so this is never invoked. Synthetic value is fine.\n * - `expiresAt` — far-future (2099-01-01 ms epoch). Sidesteps the\n * proactive refresh path (`R8H(expiresAt)` returns false).\n * - `scopes` — claude-ai-shaped so `tB(scopes)` returns true,\n * making `Hq()` true (full feature surface, not \"inference only\").\n * - `subscriptionType` — `\"max\"`. Pure client-side label\n * (`e7()` / `Zc_()` / `CZ1()`); no server validation since\n * `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` suppresses\n * subscription-validation calls. Picks the most-permissive gating.\n * - `rateLimitTier` — `\"default_claude_max_20x\"`. Paired with\n * `subscriptionType:\"max\"` this is the real Max-20x tier, so the\n * credential is internally consistent (vs the prior odd `max`+`null`).\n * Verified live (claude v2.1.158) call-sites are cosmetic billing /\n * upsell-suppression UI plus the `getPlanModeV2AgentCount` (`bGK`)\n * `max && 20x → 3` branch — which `CLAUDE_CODE_PLAN_V2_AGENT_COUNT`\n * (set to 7 in server-setup) already overrides, so this is\n * belt-and-suspenders for the natural code path. No client-side quota\n * enforcement keys off the tier (rate-limit UI reads server\n * `x-ratelimit-*` headers; the proxy holds the no-429 invariant).\n */\nconst SYNTHETIC_CREDENTIAL = {\n claudeAiOauth: {\n accessToken: \"github-router-synthetic\",\n refreshToken: \"github-router-synthetic\",\n expiresAt: 4_070_908_800_000,\n scopes: [\"user:inference\", \"user:profile\"],\n subscriptionType: \"max\",\n rateLimitTier: \"default_claude_max_20x\",\n clientId: \"github-router\",\n },\n} as const\n\n/**\n * Router-owned fields injected into `<CLAUDE_CONFIG_DIR>/.claude.json` so\n * Claude Code skips its first-launch onboarding wizard. The synthetic\n * `.credentials.json` covers the OAuth *token*, but on a fresh machine\n * the wizard runs anyway — and one of its steps is the browser-OAuth\n * \"Sign in to your Anthropic account\" prompt that the user sees today.\n *\n * Schema verified against `claude` v2.1.158 binary strings:\n *\n * - `hasCompletedOnboarding: true` — single load-bearing gate.\n * Binary code path: `if (!E_().hasCompletedOnboarding) { ... await\n * Onboarding.default(...) }`. Setting true causes the wizard\n * (including the OAuth login step) to be skipped entirely.\n *\n * - `bypassPermissionsModeAccepted: true` — skips the\n * `--dangerously-skip-permissions` trust disclaimer. Binary gate:\n * `K = Ip() || Boolean(E_().bypassPermissionsModeAccepted)`. The\n * proxy passes `--dangerously-skip-permissions` so `Ip()` typically\n * suffices, but pinning the field covers edge code paths (e.g.\n * `--bg --dangerously-skip-permissions`) that still consult it\n * directly and would otherwise throw \"requires accepting the\n * disclaimer first.\"\n *\n * - `oauthAccount` — nice-to-have for UI consistency. Claude Code\n * reads sub-fields with optional chaining (`oauthAccount?.accountUuid`,\n * `oauthAccount?.organizationUuid`, `oauthAccount?.organizationRole`)\n * so undefined doesn't trigger login — but populating gives any\n * \"logged in as X\" / status-line UI something deterministic and\n * obviously-synthetic to display. Values are intentionally\n * non-credible (`github-router@local`, all-zero UUIDs) so any\n * leak into logs is self-documenting, not impersonation.\n *\n * Merge semantics: the two boolean gates are **force-overridden** —\n * even an existing `false` is flipped to `true`. (A user logging out\n * via the Claude Code UI cannot defeat the proxy-session bypass.)\n * `oauthAccount` is overwritten only when the existing value isn't a\n * *structurally usable* one (presence-only would preserve `{}` or\n * `{foo:1}` shapes that defeat the fix); a real OAuth identity with\n * non-empty `accountUuid` and `organizationUuid` is preserved as-is.\n * Every OTHER top-level field the user brought in via the mirror walk\n * (settings, project history, user-side MCP entries, etc.) is preserved\n * verbatim. The mirror is a router-controlled view, not a faithful\n * copy — same trade-off the synthetic credential already makes.\n */\nconst SYNTHETIC_CLAUDE_JSON_FIELDS = {\n hasCompletedOnboarding: true,\n bypassPermissionsModeAccepted: true,\n oauthAccount: {\n accountUuid: \"00000000-0000-0000-0000-000000000000\",\n organizationUuid: \"00000000-0000-0000-0000-000000000000\",\n organizationRole: \"member\",\n emailAddress: \"github-router@local\",\n organizationName: \"github-router\",\n },\n} as const\n\n/**\n * Snapshot-copy the user's `~/.claude/` into the router-owned\n * CLAUDE_CONFIG_DIR (real files, not symlinks — symlinks don't isolate\n * writes), classifying each top-level entry per `CLAUDE_HOME_POLICY`:\n * ISOLATED entries are skipped, MIRRORED entries are copied, and\n * SHARED entries become directory symlinks back to `~/.claude/<X>` so\n * chat history (in `projects/<cwd-hash>/<session-uuid>.jsonl`) and\n * other durable user state flow between proxy and plain-`claude`\n * sessions. Then writes the synthetic `.credentials.json` so spawned\n * Claude Code (and teammates that inherit `CLAUDE_CONFIG_DIR`)\n * authenticate.\n *\n * Idempotent: only re-copies files whose source `mtime` is newer than\n * target; SHARED-symlink creation no-ops when the symlink already\n * points at the right target. Concurrent-safe: `mkdir({recursive:true})`\n * is idempotent; symlinks are created via atomic temp+rename so two\n * parallel github-router-claude startups can't race to EEXIST; the\n * credentials write uses temp-file + atomic rename so Claude Code's\n * `EZ1()` mtime watcher never sees a partial write. In-process callers\n * share one run via the single-flight below, which is what keeps the\n * `.claude.json` replace from racing itself; the cross-process case is\n * handled by that write's own lost-race judgment.\n *\n * Walks with `lstat` (does NOT follow symlinks during traversal — a\n * symlink-into-`/` would otherwise let the walk escape). Symlink leaves\n * in the source tree are skipped during the MIRRORED copy walk (per the\n * symlink-confused-deputy security finding); SHARED symlinks are\n * created on the mirror side only, pointing at predetermined targets\n * inside the user's real `~/.claude/`.\n *\n * Caller is expected to invoke this after `ensurePaths()` and before\n * spawning Claude Code (`launchChild`). The mirror must exist before\n * the child reads it. Currently called from the `claude` subcommand\n * entry point only; `start` and `codex` subcommands don't need it.\n */\nexport async function ensureClaudeConfigMirror(opts: {\n realHome?: string\n} = {}): Promise<void> {\n const realHome = opts.realHome ?? os.homedir()\n const targetDir = PATHS.CLAUDE_CONFIG_DIR\n\n // Single-flight, keyed on both paths. Concurrent callers in ONE process\n // (a `claude` launch whose two entry points prepare the same mirror, or\n // the 4-way shape the tests use) used to run the whole walk and the\n // `.claude.json` replace simultaneously. The walk is idempotent, but the\n // replace is not race-free on Windows: `fs.rename` over a destination\n // another writer is mid-replacing fails with EPERM/EBUSY, and that\n // failure then has to be told apart from a real write failure by\n // inspecting what the racer happened to leave behind. Serializing here\n // removes the in-process half of that problem at the source; the\n // cross-process half is what the rename tolerance below is for.\n //\n // The check and the publish must not be separated by an await (the same\n // rule token refresh follows): anything awaited in between yields the\n // event loop and lets a second caller walk in before the first call has\n // published its promise. No I/O happens before the publish.\n const key = `${targetDir}\\u0000${realHome}`\n const inflight = claudeConfigMirrorInflight.get(key)\n if (inflight) return inflight\n\n const run = async (): Promise<void> => {\n try {\n await runClaudeConfigMirror(realHome, targetDir)\n } finally {\n // Identity-checked release: an unconditional delete would let a\n // finished run evict a newer run's entry and re-open the overlap\n // this exists to close. `attempt` is assigned before any await\n // inside `run()` can settle, so it is always bound here.\n if (claudeConfigMirrorInflight.get(key) === attempt) {\n claudeConfigMirrorInflight.delete(key)\n }\n }\n }\n const attempt = run()\n claudeConfigMirrorInflight.set(key, attempt)\n return attempt\n}\n\n/**\n * The in-process single-flight map behind `ensureClaudeConfigMirror`.\n *\n * Entries are released as soon as a run settles, so a SEQUENTIAL caller\n * still gets a fresh walk — which matters because the mirror is re-walked\n * after callers change `~/.claude` (and because several tests do exactly\n * that between calls). Only overlapping calls share a run.\n */\nconst claudeConfigMirrorInflight = new Map<string, Promise<void>>()\n\nasync function runClaudeConfigMirror(\n realHome: string,\n targetDir: string,\n): Promise<void> {\n const sourceDir = path.join(realHome, \".claude\")\n\n // 1. Create our config dir (idempotent, mode 0o700)\n await fs.mkdir(targetDir, { recursive: true, mode: 0o700 })\n await chmodIfPossible(targetDir, 0o700)\n\n // 2. Snapshot-copy from ~/.claude if it exists. Only MIRRORED entries\n // flow through this walk; ISOLATED and SHARED entries are filtered\n // in `mirrorDirRecursive` and handled separately.\n let sourceExists = false\n try {\n const sourceStat = await fs.stat(sourceDir)\n sourceExists = sourceStat.isDirectory()\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n consola.debug(`ensureClaudeConfigMirror: cannot stat ${sourceDir}:`, err)\n }\n }\n if (sourceExists) {\n await mirrorDirRecursive(sourceDir, targetDir, \"\")\n }\n\n // Cloud Agent Hub installs localhost hooks with a UUID that changes whenever its\n // daemon restarts. A per-launch settings snapshot cannot follow that rotation,\n // so inherited URLs begin returning 404 on every prompt/tool/stop event. Strip\n // only Cloud Agent's generated cohort from this disposable mirror before adding any\n // router-owned hooks below. The operator's real settings remain untouched.\n const cloudAgentHooks = await sanitizeCloudAgentHooksInSettingsFile(\n path.join(targetDir, \"settings.json\"),\n )\n if (cloudAgentHooks.invalid) {\n consola.warn(\n `Could not inspect the isolated settings mirror for Cloud Agent Hub hooks (${cloudAgentHooks.invalid}); the file was preserved unchanged and Claude Code may ignore it as invalid.`,\n )\n } else if (cloudAgentHooks.removed > 0) {\n consola.info(\n `Excluded ${cloudAgentHooks.removed} Cloud Agent Hub hooks from this isolated launch; Cloud Agent session tracking and remote approvals remain available to non-proxied Claude sessions.`,\n )\n }\n\n // 3. Always ensure agents/ exists (even if user has none) so the\n // peer-agent .md emission has a place to write. Empty dir is fine.\n // agents/ is MIRRORED, not SHARED — the proxy writes per-launch\n // `peer-<pid>-*.md` files here and `sweepStalePeerAgentMdFiles`\n // deletes them; routing those operations into the user's real\n // `~/.claude/agents/` would destroy their custom subagent files.\n await fs.mkdir(path.join(targetDir, \"agents\"), { recursive: true })\n\n // 4. Create symlinks for SHARED entries so chat history (and other\n // durable user state) is visible in both proxy and plain-`claude`.\n for (const name of SHARED_TOPLEVEL_NAMES) {\n await ensureSharedSymlink(name, sourceDir, targetDir).catch((err) => {\n consola.debug(\n `ensureClaudeConfigMirror: SHARED symlink for ${name} skipped:`,\n err,\n )\n })\n }\n\n // 5. Write synthetic .credentials.json (only if content differs)\n const credentialsPath = path.join(targetDir, \".credentials.json\")\n const desiredJson = JSON.stringify(SYNTHETIC_CREDENTIAL, null, 2)\n let needsWrite = true\n try {\n const existing = await fs.readFile(credentialsPath, \"utf8\")\n needsWrite = existing.trim() !== desiredJson.trim()\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n consola.debug(`ensureClaudeConfigMirror: cannot read existing credentials:`, err)\n }\n }\n if (needsWrite) {\n // Atomic temp-file + rename so EZ1()'s mtime watcher doesn't see\n // a partial write. wx flag ensures we don't clobber a concurrent\n // writer's tempfile.\n const tempPath = `${credentialsPath}.${process.pid}.tmp`\n try {\n await fs.writeFile(tempPath, desiredJson + \"\\n\", { mode: 0o600, flag: \"wx\" })\n await fs.rename(tempPath, credentialsPath)\n } catch (err) {\n // EEXIST on the tempfile means another concurrent startup is\n // mid-write. Best-effort: skip — the other writer will produce\n // identical content (deterministic constant blob).\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n consola.debug(\n \"ensureClaudeConfigMirror: concurrent credentials-write detected, skipping\",\n )\n } else {\n await fs.unlink(tempPath).catch(() => {})\n throw err\n }\n }\n }\n await chmodIfPossible(credentialsPath, 0o600)\n\n // 6. Inject onboarding-skip fields into <CLAUDE_CONFIG_DIR>/.claude.json.\n // Runs AFTER the mirror walk (step 2) so a user's existing\n // .claude.json content (settings, projects, user-side mcpServers)\n // is preserved, and BEFORE `injectPeerMcpIntoMirror` (called later\n // from `src/claude.ts`) which read-merge-writes the same file and\n // will preserve our fields naturally.\n //\n // Without this step, on a brand-new machine where ~/.claude/.claude.json\n // doesn't exist, nothing lands in the mirror, Claude Code's\n // `hasCompletedOnboarding` gate defaults to falsy, and the\n // first-launch wizard runs — including the \"Sign in to your\n // Anthropic account\" OAuth step that defeats the synthetic\n // credential. See SYNTHETIC_CLAUDE_JSON_FIELDS for the gate\n // rationale + binary-verified field shape.\n await injectSyntheticClaudeJsonFields(targetDir, sourceDir, realHome)\n\n // 6a. Postcondition: verify the gate fields actually landed in the\n // mirror's .claude.json. The helper has several \"warn and\n // return\" branches (non-regular target, non-ENOENT read failure)\n // where falling through silently would let Claude Code's\n // first-launch wizard fire — the exact bug this whole\n // subsystem exists to prevent. Re-reading the file and\n // asserting the booleans converts every silent-fail path into a\n // fail-loud launch error, which `src/claude.ts` surfaces to the\n // user with `process.exit(1)`. Cheap (one extra readFile +\n // JSON.parse on a small file we just wrote) and gives the\n // no-silent-degradation invariant teeth even if a future\n // contributor adds a new bail-out branch.\n await assertOnboardingGateInjected(targetDir)\n\n // 7. Write/refresh marker file. Use lstat (not access) to detect\n // symlinks at the marker path — a previously-mirrored or\n // user-placed symlink could otherwise let our `fs.writeFile`\n // follow through to an arbitrary target. With the symlink-skip\n // policy in `mirrorDirRecursive` this is defense-in-depth, but\n // cheap and definitive.\n const markerPath = path.join(targetDir, MANAGED_MARKER_FILENAME)\n let markerExists = false\n try {\n const markerStat = await fs.lstat(markerPath)\n if (markerStat.isFile()) {\n markerExists = true\n } else {\n // Anything non-regular (symlink, dir, special file) is a red flag —\n // refuse to overwrite, log loudly. The user can investigate.\n consola.warn(\n `ensureClaudeConfigMirror: ${markerPath} exists but is not a regular file (mode=${markerStat.mode.toString(8)}); refusing to overwrite. Inspect and remove manually if safe.`,\n )\n markerExists = true\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n consola.debug(`ensureClaudeConfigMirror: cannot lstat marker:`, err)\n markerExists = true\n }\n }\n if (!markerExists) {\n const body = `Managed by github-router. Created ${new Date().toISOString()}. Safe to delete (will be recreated).\\n`\n // wx flag (O_CREAT | O_EXCL) refuses to clobber an existing\n // file or symlink (POSIX O_EXCL behavior) — additional protection\n // against the marker-symlink confused-deputy vector.\n await fs\n .writeFile(markerPath, body, { mode: 0o600, flag: \"wx\" })\n .catch((err) => {\n consola.debug(`ensureClaudeConfigMirror: marker write skipped:`, err)\n })\n }\n}\n\n/**\n * Read-merge-atomic-write the router-required onboarding-skip fields\n * (see `SYNTHETIC_CLAUDE_JSON_FIELDS`) into `<targetDir>/.claude.json`.\n *\n * Inputs:\n * - `targetDir` — the per-launch mirror dir we own.\n * - `sourceDir` — the user's `~/.claude/` (subdir-level legacy path).\n * - `realHome` — the user's `$HOME`. Used to locate the **canonical**\n * `~/.claude.json` (HOME level), which is what Claude Code's path\n * resolver `qG` actually reads when `CLAUDE_CONFIG_DIR` is unset:\n * `path.join(process.env.CLAUDE_CONFIG_DIR || homedir(),\n * \".claude.json\")`. The mirror walk operates on `~/.claude/` and\n * thus can only see the subdir-level `~/.claude/.claude.json`\n * (often a stale shadow); the canonical HOME-level file — where\n * `claude mcp add` writes and Claude Code reads on default\n * invocations — would otherwise be invisible to the proxy session.\n *\n * Behaviour:\n * - Mirror's `.claude.json` is a non-regular file (symlink, dir,\n * etc.) → log warn, refuse to touch. The postcondition check in\n * `ensureClaudeConfigMirror` then throws, blocking launch — the\n * user investigates the warn-flagged path rather than landing in\n * the OAuth wizard.\n * - Read existing content from the first VALID source, in priority\n * order:\n * (a) `~/.claude.json` HOME-level (canonical Claude Code path)\n * (b) The mirror file itself (snapshot-walk's product; only\n * consulted if it's a regular file per step 1)\n * (c) `~/.claude/.claude.json` subdir-level (legacy)\n * A candidate that's missing (ENOENT), too large (> 50 MiB cap),\n * or fails to parse as a non-empty object is **skipped** — the\n * loop falls through to the next candidate, so a malformed\n * higher-priority source can't drop valid lower-priority content\n * on the floor. HOME-level non-ENOENT read failures warn\n * (user-visible — corp perms / OneDrive). All other failures\n * debug-log. `fs.readFile` follows symlinks; reading user-owned\n * content into a per-launch user-owned dir is not a privilege\n * escalation (same uid).\n * - Merge: **force-override** all three synthetic fields\n * unconditionally — `hasCompletedOnboarding`,\n * `bypassPermissionsModeAccepted`, AND `oauthAccount`. A\n * within-proxy \"log out\" is impossible by design. `oauthAccount`\n * is overwritten even when the user has a real one, because\n * pairing the synthetic OAuth token (from `.credentials.json`)\n * with a real-user identity blob creates a split-brain auth\n * state that Claude Code's identity-vs-token cross-checks may\n * treat as session corruption (triggering re-login → defeats\n * the fix). The user's real identity remains intact in their\n * own `~/.claude.json`; only the proxy session sees synthetic.\n * `Object.assign(Object.create(null), existing)` instead of spread\n * defuses the `__proto__` prototype-pollution sink from JSON.parse.\n * - Idempotency: skip the write IFF the source we read FROM is the\n * mirror itself AND the current mirror content is byte-equivalent\n * to what we'd write. Bytes-on-disk comparison is robust against\n * filesystem mtime resolution (FAT/exFAT 2 s buckets) and the\n * source-presence-vs-mirror-presence conflation that broke\n * round-2's `needsWrite = !hadExisting` heuristic.\n *\n * Atomic write: tempfile (per-PID + 4-byte random suffix matching\n * `injectPeerMcpIntoMirror`'s pattern, so collision is effectively\n * impossible) + rename, mode 0o600. Pre-chmod the destination before\n * rename to defuse Windows read-only attribute issues. Any write\n * error throws to the caller — `src/claude.ts` fails the launch\n * loudly. Combined with the postcondition check, every silent-\n * degradation path is converted to a fail-loud launch error.\n */\nasync function injectSyntheticClaudeJsonFields(\n targetDir: string,\n sourceDir: string,\n realHome: string,\n): Promise<void> {\n const claudeJsonPath = path.join(targetDir, \".claude.json\")\n\n // 1. lstat the mirror path before touching it (defense-in-depth,\n // matching the marker-write at step 7). If something other than a\n // regular file occupies the slot, refuse — `fs.readFile` /\n // `chmodIfPossible` / `fs.rename` would otherwise follow / clobber\n // in surprising ways. The postcondition then throws.\n let mirrorIsRegularFile = false\n try {\n const mirrorStat = await fs.lstat(claudeJsonPath)\n if (mirrorStat.isFile()) {\n mirrorIsRegularFile = true\n } else {\n consola.warn(\n `ensureClaudeConfigMirror: ${claudeJsonPath} exists but is not a regular file (mode=${mirrorStat.mode.toString(8)}); refusing to inject synthetic fields. Inspect and remove manually if safe.`,\n )\n return\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n consola.warn(\n `ensureClaudeConfigMirror: cannot lstat ${claudeJsonPath}; refusing to inject synthetic fields (overwriting an unreadable file would risk destroying user content):`,\n err,\n )\n return\n }\n // ENOENT: mirror file doesn't exist yet — fine; step 2 skips the\n // mirror candidate and step 4 creates a new file.\n }\n\n // 2. Read existing content from the first VALID source. Priority:\n // (a) `~/.claude.json` HOME-level (canonical Claude Code path)\n // (b) Mirror file (the snapshot-walk's product; only if regular)\n // (c) `~/.claude/.claude.json` subdir-level (legacy)\n // A candidate that's missing (ENOENT) or fails to parse as a\n // non-empty object is SKIPPED — the loop falls through to the\n // next candidate. This is the load-bearing fix for \"corrupt HOME\n // blocks valid subdir\": a zero-byte or malformed HOME file no\n // longer drops the user's good subdir content on the floor.\n // Size cap (`MAX_CLAUDE_JSON_BYTES`) skips absurdly large files\n // that would risk OOM. HOME read failures (non-ENOENT) warn\n // loudly — the canonical path failing is user-visible. Mirror /\n // subdir read failures debug-log and fall through.\n // `fs.readFile` follows symlinks; reading user-owned content\n // into a per-launch user-owned dir is not a privilege escalation.\n let existing: Record<string, unknown> = {}\n let selectedSource: string | null = null\n const homeLevelClaudeJson = path.join(realHome, \".claude.json\")\n const subdirClaudeJson = path.join(sourceDir, \".claude.json\")\n const sourceCandidates: Array<string | null> = [\n homeLevelClaudeJson,\n mirrorIsRegularFile ? claudeJsonPath : null,\n subdirClaudeJson,\n ]\n for (const sourceCandidate of sourceCandidates) {\n if (sourceCandidate === null) continue\n try {\n const stat = await fs.stat(sourceCandidate)\n if (stat.size > MAX_CLAUDE_JSON_BYTES) {\n consola.warn(\n `ensureClaudeConfigMirror: ${sourceCandidate} is ${stat.size} bytes (> ${MAX_CLAUDE_JSON_BYTES} cap); skipping this source to avoid OOM. Inspect for accidental log/state accumulation.`,\n )\n continue\n }\n const raw = await fs.readFile(sourceCandidate, \"utf8\")\n const parsed = parseExistingClaudeJson(raw, sourceCandidate)\n if (parsed === null) {\n // Malformed (parse failure or non-object). Skip; try next candidate.\n continue\n }\n existing = parsed\n selectedSource = sourceCandidate\n consola.debug(\n `ensureClaudeConfigMirror: read .claude.json content from ${sourceCandidate}`,\n )\n break\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === \"ENOENT\") {\n // Normal case — skip silently.\n continue\n }\n // Non-ENOENT read/stat failure. Severity depends on which source:\n // - HOME-level (canonical): warn (user-visible — corp perms,\n // OneDrive cloud-only, EACCES, etc.). Fall through, since\n // the gate-injection still needs to happen.\n // - Mirror / subdir: debug. Mirror failures used to abort,\n // but that locked out the still-valid subdir-level fallback;\n // we can always re-create the mirror from any valid source.\n if (sourceCandidate === homeLevelClaudeJson) {\n consola.warn(\n `ensureClaudeConfigMirror: cannot read canonical ${homeLevelClaudeJson}; falling back to other sources. User-scope MCPs added via 'claude mcp add' may be invisible to the proxy session:`,\n err,\n )\n } else {\n consola.debug(\n `ensureClaudeConfigMirror: cannot read source ${sourceCandidate}:`,\n err,\n )\n }\n // Fall through to next candidate. If all miss/fail, proceed\n // with synthetic-only content (existing stays {}).\n }\n }\n\n // 3. Build merged content. `Object.assign(Object.create(null), ...)`\n // instead of `{...existing}` avoids the `__proto__` prototype-\n // pollution sink (`JSON.parse('{\"__proto__\":{...}}')` sets the\n // object's prototype via defineProperty; spreading then triggers\n // the standard `__proto__` setter and mutates merged's prototype\n // chain. Cheap defense, prevents the entire class.\n //\n // All three gate fields are FORCE-OVERRIDDEN regardless of\n // existing value:\n // - `hasCompletedOnboarding` and `bypassPermissionsModeAccepted`\n // are the load-bearing gates we exist to set; a within-proxy\n // \"log out\" is impossible by design.\n // - `oauthAccount` is overwritten unconditionally with the\n // synthetic identity (NOT preserved even when real). Pairing\n // the synthetic OAuth token (from `.credentials.json`) with\n // a real-user `accountUuid` / `organizationUuid` creates a\n // split-brain auth state where Claude Code's identity-vs-\n // token cross-checks (binary `oauthAccount?.accountUuid`\n // consumers) may treat the mismatch as session corruption\n // and trigger re-login — the exact bug we're preventing.\n // The user's real identity remains intact in their own\n // `~/.claude.json`; only the proxy session sees synthetic.\n const merged: Record<string, unknown> = Object.assign(\n Object.create(null) as Record<string, unknown>,\n existing,\n )\n merged.hasCompletedOnboarding = SYNTHETIC_CLAUDE_JSON_FIELDS.hasCompletedOnboarding\n merged.bypassPermissionsModeAccepted = SYNTHETIC_CLAUDE_JSON_FIELDS.bypassPermissionsModeAccepted\n merged.oauthAccount = SYNTHETIC_CLAUDE_JSON_FIELDS.oauthAccount\n\n // 4. Decide if a write is needed. Idempotency contract: skip the\n // write IFF we read FROM the mirror itself AND the current mirror\n // content is byte-equivalent to what we'd write. Bytes-on-disk\n // comparison (vs. inferring from source state) is robust against:\n // - source-presence ≠ mirror-presence (a fully-onboarded HOME\n // file with no mirror yet must still trigger a mirror write)\n // - HOME content newer than mirror (HOME wins → mirror is\n // always rewritten when source was HOME)\n // - filesystem mtime resolution (FAT/exFAT 2s buckets)\n const desiredJson = JSON.stringify(merged, null, 2) + \"\\n\"\n if (selectedSource === claudeJsonPath) {\n try {\n const currentMirrorJson = await fs.readFile(claudeJsonPath, \"utf8\")\n if (currentMirrorJson === desiredJson) {\n await chmodIfPossible(claudeJsonPath, 0o600).catch(() => {})\n return\n }\n } catch {\n // Mirror read failed between step 2's success and now — fall\n // through to write. Worst case we rewrite identical content.\n }\n }\n\n // 5. Atomic temp + rename. Mode 0o600. Per-PID + 4-byte random\n // suffix matches `injectPeerMcpIntoMirror`'s pattern. Any write\n // error throws to the caller — `src/claude.ts` exits the launch\n // with a loud error message rather than silently degrading to\n // the OAuth wizard.\n //\n // Pre-chmod the destination before rename to defuse Windows\n // read-only attribute issues (FAT/exFAT volumes, corp-managed\n // perms): `fs.rename` over a read-only file can fail with EPERM\n // on Windows even though POSIX would silently succeed.\n //\n // Concurrent-racer tolerance: two `github-router claude` startups can\n // replace this file at once (the single-flight in\n // `ensureClaudeConfigMirror` covers in-process callers only, since two\n // processes share nothing), and Windows `fs.rename` then fails with\n // EBUSY/EPERM/EACCES against a destination that is momentarily open.\n // Byte equality against `desiredJson` was the ORIGINAL acceptance test\n // here and it is the wrong one: the source-priority list above\n // INCLUDES this mirror file, so a racer whose `lstat` lands after\n // another racer's write merges from the mirror rather than from HOME\n // and legitimately computes different bytes. Byte inequality therefore\n // does not mean the write failed, and treating it as failure made a\n // benign lost race throw out of the launch.\n //\n // The gate postcondition ALONE is the other wrong acceptance test, and\n // it is this branch's previous shape. A mirror that already carries the\n // gate satisfies it with or without our write — that is precisely the\n // legacy `~/.claude/.claude.json` shadow the source list above accepts,\n // and any mirror an earlier launch already prepared. Accepting on that\n // evidence alone converts a real write failure (disk full, an antivirus\n // holding the file, a read-only profile) into a silent drop of the\n // merge: the user's user-scope MCPs and settings are in `desiredJson`\n // and never reach the mirror, with one `consola.debug` as the only\n // trace. So the pre-write state is captured here and handed to\n // `judgeLostClaudeJsonWrite`, which requires evidence that the\n // destination got BETTER, not merely that it is acceptable.\n const preWriteGateProblem = await onboardingGateProblem(claudeJsonPath)\n const tempPath = `${claudeJsonPath}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`\n try {\n await fs.writeFile(tempPath, desiredJson, { mode: 0o600, flag: \"wx\" })\n } catch (err) {\n // Not a race to lose: nobody else can have created OUR temp path, and a\n // failure here leaves the destination exactly as it was.\n await fs.unlink(tempPath).catch(() => {})\n throw err\n }\n try {\n if (mirrorIsRegularFile) {\n await chmodIfPossible(claudeJsonPath, 0o600).catch(() => {})\n }\n await fs.rename(tempPath, claudeJsonPath)\n } catch (err) {\n await fs.unlink(tempPath).catch(() => {})\n const reason = await judgeLostClaudeJsonWrite(\n claudeJsonPath,\n desiredJson,\n preWriteGateProblem,\n )\n if (reason !== null) {\n throw new Error(\n `ensureClaudeConfigMirror: replacing ${claudeJsonPath} failed (${(err as Error).message}) and the failure is not explained by a concurrent writer: ${reason}`,\n { cause: err },\n )\n }\n consola.debug(\n `ensureClaudeConfigMirror: the ${claudeJsonPath} replace did not land, but the destination already holds what this write intended (a concurrent writer won the race):`,\n err,\n )\n }\n await chmodIfPossible(claudeJsonPath, 0o600).catch(() => {})\n}\n\n/**\n * Size cap on candidate `.claude.json` reads in\n * `injectSyntheticClaudeJsonFields`. Real-world files are KB-MB scale;\n * if a `.claude.json` has grown to hundreds of MB (corruption, runaway\n * project history accumulation, accidental log redirect) reading it\n * blocks the event loop and risks OOM. 50 MiB is comfortably above\n * any legitimate Claude Code state and well below typical RSS budgets.\n */\nconst MAX_CLAUDE_JSON_BYTES = 50 * 1024 * 1024\n\n/**\n * Structural check for `oauthAccount`: must be a non-null, non-array\n * object whose `accountUuid` AND `organizationUuid` are non-empty\n * strings. Empty objects / partial blobs (missing UUIDs) do NOT count\n * as \"usable\" — preserving them would let Claude Code's various\n * \"logged in as X\" UIs read undefined sub-fields and (in some flows)\n * fall back to a re-login prompt that defeats the synthetic-credential\n * fix. Field names match the binary's optional-chain reads\n * (`oauthAccount?.accountUuid`, `oauthAccount?.organizationUuid`).\n */\nfunction isUsableOauthAccount(value: unknown): boolean {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false\n const obj = value as Record<string, unknown>\n const accountUuid = obj.accountUuid\n const organizationUuid = obj.organizationUuid\n return (\n typeof accountUuid === \"string\"\n && accountUuid.length > 0\n && typeof organizationUuid === \"string\"\n && organizationUuid.length > 0\n )\n}\n\n/**\n * Parse a JSON blob expected to be an object. Returns `null` on parse\n * failure or non-object/array value (so callers can SKIP this source\n * rather than treating an empty object as a successful read — a\n * round-1 finding from gemini-critic). Logs a warn so the user can\n * investigate. Used in `injectSyntheticClaudeJsonFields`'s source-\n * priority loop: a malformed HOME-level file falls through to the\n * mirror or subdir candidate instead of dropping valid lower-priority\n * content on the floor.\n */\nfunction parseExistingClaudeJson(\n raw: string,\n contextPath: string,\n): Record<string, unknown> | null {\n try {\n const parsed = JSON.parse(raw) as unknown\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>\n }\n consola.warn(\n `ensureClaudeConfigMirror: ${contextPath} parsed to non-object `\n + `(typeof=${typeof parsed}); skipping this source.`,\n )\n return null\n } catch (err) {\n consola.warn(\n `ensureClaudeConfigMirror: cannot parse ${contextPath} as JSON; `\n + `skipping this source:`,\n err,\n )\n return null\n }\n}\n\n/**\n * Postcondition for `ensureClaudeConfigMirror`: re-reads the mirror's\n * `.claude.json` and verifies that both boolean gate fields actually\n * landed. Converts every \"warn and return\" branch in\n * `injectSyntheticClaudeJsonFields` (non-regular target, non-ENOENT\n * read failure, postcondition lstat race) into a launch-failing\n * throw — `src/claude.ts:197`'s catch path turns it into a clear\n * `process.exit(1)` rather than silently spawning Claude Code into\n * the OAuth wizard. The whole point of this subsystem is preventing\n * that silent degradation; a warn that scrolls by in the launch log\n * is not enough.\n *\n * Cheap (one extra readFile + JSON.parse on a small file we just\n * wrote) and load-bearing: every future contributor who adds a new\n * bail-out branch in the helper above automatically gets fail-loud\n * for free instead of having to remember to thread the failure\n * upward by hand.\n */\n/**\n * Does the file at `claudeJsonPath` hold the synthetic onboarding gate?\n *\n * Returns `null` when the gate is satisfied, otherwise an actionable reason\n * (without the caller's prefix) plus the underlying error where one exists.\n *\n * Shared by BOTH sites that need the answer, which is the point of extracting\n * it: the write path uses it to decide whether a lost rename race is benign\n * (`injectSyntheticClaudeJsonFields` step 5) and `assertOnboardingGateInjected`\n * uses it to decide whether the launch may proceed. Two independent copies of\n * \"the gate is applied\" is exactly how a benign-race acceptance test and the\n * fail-loud postcondition drift apart.\n */\nasync function onboardingGateProblem(\n claudeJsonPath: string,\n): Promise<{ reason: string; cause?: unknown } | null> {\n // lstat first — never follow a symlink. A planted symlink at the mirror\n // path pointing at an attacker-controlled file with valid gate fields would\n // otherwise pass a plain readFile check and let the helper's \"non-regular\n // target\" warn-and-return slip through.\n let lst: import(\"node:fs\").Stats\n try {\n lst = await fs.lstat(claudeJsonPath)\n } catch (err) {\n return {\n reason: `cannot lstat ${claudeJsonPath} after injection (synthetic onboarding-skip fields are required to prevent Claude Code's first-launch wizard, which would defeat the synthetic credential): ${(err as Error).message}`,\n cause: err,\n }\n }\n if (!lst.isFile()) {\n return {\n reason: `${claudeJsonPath} exists but is not a regular file (mode=${lst.mode.toString(8)}). Check the preceding warn-level log lines for the underlying cause; without a regular file holding the gate fields, Claude Code's first-launch wizard fires and defeats the synthetic credential.`,\n }\n }\n\n let raw: string\n try {\n raw = await fs.readFile(claudeJsonPath, \"utf8\")\n } catch (err) {\n return {\n reason: `cannot read ${claudeJsonPath} after injection: ${(err as Error).message}`,\n cause: err,\n }\n }\n let parsed: Record<string, unknown>\n try {\n const json = JSON.parse(raw) as unknown\n if (!json || typeof json !== \"object\" || Array.isArray(json)) {\n throw new Error(`parsed to non-object (typeof=${typeof json})`)\n }\n parsed = json as Record<string, unknown>\n } catch (err) {\n return {\n reason: `${claudeJsonPath} is not a valid JSON object after injection: ${(err as Error).message}`,\n cause: err,\n }\n }\n if (\n parsed.hasCompletedOnboarding !== true\n || parsed.bypassPermissionsModeAccepted !== true\n ) {\n return {\n reason: `${claudeJsonPath} is missing required gate fields after injection (hasCompletedOnboarding=${String(parsed.hasCompletedOnboarding)}, bypassPermissionsModeAccepted=${String(parsed.bypassPermissionsModeAccepted)}). Check the preceding warn-level log lines for the underlying cause; without these fields Claude Code's first-launch wizard fires and defeats the synthetic credential.`,\n }\n }\n // Reuse `isUsableOauthAccount` so a future change to the structural\n // definition stays consistent across helper write-decision, the benign-race\n // acceptance test, and postcondition. The synthetic blob we always write\n // satisfies this by construction; a regression that drops oauthAccount\n // during the merge would otherwise slip past (per the round-2 codex/opus/\n // gemini-3-lab finding).\n if (!isUsableOauthAccount(parsed.oauthAccount)) {\n return {\n reason: `${claudeJsonPath} has invalid oauthAccount after injection (got ${JSON.stringify(parsed.oauthAccount)}). The synthetic identity blob is required so Claude Code's identity-vs-token cross-checks don't trigger a re-login that defeats the synthetic credential.`,\n }\n }\n return null\n}\n\nasync function assertOnboardingGateInjected(targetDir: string): Promise<void> {\n const claudeJsonPath = path.join(targetDir, \".claude.json\")\n const problem = await onboardingGateProblem(claudeJsonPath)\n if (problem === null) return\n throw new Error(\n `ensureClaudeConfigMirror: postcondition failed — ${problem.reason}`,\n problem.cause === undefined ? undefined : { cause: problem.cause },\n )\n}\n\n/**\n * May the launch proceed after a `.claude.json` replace failed?\n *\n * `null` means yes: the destination is in a state that accounts for the\n * failure, so it is a lost race rather than a lost write. A non-null string\n * is the reason it is NOT, for the caller to fold into the thrown error.\n *\n * Exactly two things account for a failed replace, and both are evidence\n * that the destination got BETTER while we were failing:\n *\n * 1. The bytes on disk are the bytes we intended to write. Whoever wrote\n * them, the merge this call exists to perform is the merge in place —\n * a strictly stronger statement than any gate check — so it is tested\n * first, and it is also what covers a racer that merged from a\n * different source than we did.\n * 2. The destination did NOT satisfy the gate before this write and does\n * now. Somebody applied the gate to this path while our rename was\n * failing, which is the same job this call does; the pre-write miss is\n * what makes the post-write hit evidence rather than coincidence.\n *\n * A destination that already carried the gate is deliberately NOT accepted.\n * That is the legacy `~/.claude/.claude.json` shadow (or any mirror a prior\n * launch prepared): it satisfies the gate on its own, so accepting it would\n * let a genuine write failure pass as a lost race while the merge silently\n * never lands. The gate is not the whole postcondition of this helper — the\n * merge is the reason a gate-valid mirror still gets rewritten.\n */\nasync function judgeLostClaudeJsonWrite(\n claudeJsonPath: string,\n desiredJson: string,\n preWriteGateProblem: { reason: string } | null,\n): Promise<string | null> {\n try {\n const current = await fs.readFile(claudeJsonPath, \"utf8\")\n if (current === desiredJson) return null\n } catch {\n // Unreadable or gone. Fall through: the gate check below reports the\n // state with its own reason, which is more specific than \"read failed\".\n }\n\n const postWriteGateProblem = await onboardingGateProblem(claudeJsonPath)\n if (postWriteGateProblem !== null) {\n return `the destination does not hold the onboarding gate either (${postWriteGateProblem.reason})`\n }\n if (preWriteGateProblem === null) {\n return \"the destination already held the onboarding gate before this write, so holding it afterwards proves nothing about this merge; the mirrored content this call adds (user-scope MCPs, settings) may be missing from the launch\"\n }\n return null\n}\n\n/**\n * Recursive snapshot-copy helper for `ensureClaudeConfigMirror`. Walks\n * `sourceDir/relPath` and mirrors each entry into `targetDir/relPath`.\n * - Top-level entries are dispatched on `policyFor(name)`:\n * - `ISOLATED` → skipped entirely (no presence in mirror).\n * - `SHARED` → skipped from the copy walk; handled by\n * `ensureSharedSymlink` in the post-copy phase.\n * - `MIRRORED` → copied as today.\n * - Symlinks are skipped (not recreated) so the walk never follows out\n * of `sourceDir` and we don't reintroduce a confused-deputy vector.\n * - Files copy only if source mtime > target mtime (idempotent).\n */\n/**\n * Max file operations in flight across the WHOLE mirror walk.\n *\n * The walk is I/O-bound over hundreds of independent small files, so it\n * parallelizes well: measured 1021ms serial vs 311ms at this limit for a real\n * 394-file / 4.7MB `~/.claude` (Windows 11, 16 cores). It must be BOUNDED\n * rather than a bare `Promise.all` over every entry — the mirror is re-copied\n * on every launch (the target is a fresh per-launch dir, so the mtime skip\n * below never fires across launches), and firing hundreds of simultaneous\n * `copyFile`s just trades one bottleneck for file-handle exhaustion.\n *\n * The limit is shared across the recursion via a semaphore rather than applied\n * per-directory: a per-directory bound would multiply with nesting depth and\n * stop being a bound at all.\n */\nconst MIRROR_COPY_CONCURRENCY = 16\n\n/** Counting semaphore. FIFO, so a deep subtree cannot starve a shallow one. */\nfunction createSemaphore(limit: number) {\n let active = 0\n const waiters: Array<() => void> = []\n return async function withSlot<T>(fn: () => Promise<T>): Promise<T> {\n if (active >= limit) {\n await new Promise<void>((resolve) => waiters.push(resolve))\n // Woken by a HAND-OFF: the releaser kept the slot counted on our behalf\n // rather than decrementing, so `active` is already correct here. Doing\n // `active++` would double-count — and worse, decrementing first would\n // open a window where a fresh caller sees a free slot and takes it too,\n // letting the pool exceed `limit`.\n } else {\n active++\n }\n try {\n return await fn()\n } finally {\n const next = waiters.shift()\n // Hand the slot straight to the next waiter (keeping `active` as-is), or\n // give it back to the pool when nobody is queued.\n if (next) next()\n else active--\n }\n }\n}\n\nasync function mirrorDirRecursive(\n sourceDir: string,\n targetDir: string,\n relPath: string,\n withSlot: <T>(fn: () => Promise<T>) => Promise<T> = createSemaphore(\n MIRROR_COPY_CONCURRENCY,\n ),\n): Promise<void> {\n const sourcePath = path.join(sourceDir, relPath)\n let entries: Array<string>\n try {\n // Through the semaphore like every other syscall here. Subdirectories are\n // traversed concurrently, so an unslotted readdir would let a wide or deep\n // tree dispatch hundreds at once — defeating the file-handle bound the\n // semaphore exists to enforce.\n entries = await withSlot(() => fs.readdir(sourcePath))\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return\n consola.debug(`mirrorDirRecursive: cannot readdir ${sourcePath}:`, err)\n return\n }\n // Entries within a directory are independent, so they run concurrently under\n // the shared slot budget. Semantics per entry are unchanged from the serial\n // version; only the scheduling differs.\n await Promise.all(\n entries.map(async (name) => {\n // Policy dispatch at top-level only. Sub-paths within MIRRORED\n // dirs always cascade as MIRRORED.\n if (relPath === \"\") {\n const policy = policyFor(name)\n if (policy === \"ISOLATED\" || policy === \"SHARED\") return\n }\n const childRel = relPath === \"\" ? name : path.join(relPath, name)\n // Never mirror a proxy-authored agent `.md` out of the user's real\n // `~/.claude/agents/`. A pre-mirror release wrote `peer-<pid>-<hex>-<name>.md`\n // files there; left alone they get copied into every new mirror and register\n // alongside the current launch's files under the SAME frontmatter `name:`,\n // so Claude Code resolves between a live definition and a dead one\n // nondeterministically. Filtering at the COPY step fixes that without\n // deleting anything we do not own: the user's directory is left exactly as\n // it is, and the current launch writes its own files into the mirror after\n // this walk. Deleting them instead would be unsound, because the filename\n // shape is evidence of provenance, not proof of it, and a user who copied a\n // generated file to customize it would lose it.\n if (relPath === \"agents\" && PEER_AGENT_MD_FILENAME.test(name)) {\n return\n }\n const childSource = path.join(sourceDir, childRel)\n const childTarget = path.join(targetDir, childRel)\n let stats: Awaited<ReturnType<typeof fs.lstat>>\n try {\n stats = await withSlot(() => fs.lstat(childSource))\n } catch (err) {\n consola.debug(`mirrorDirRecursive: cannot lstat ${childSource}:`, err)\n return\n }\n if (stats.isSymbolicLink()) {\n // Skip symlinks during mirror copy. gemini-critic security finding:\n // recreating user symlinks in our mirror creates a confused-deputy\n // vector — a previously prompt-injected process could place\n // `~/.claude/<X>` → `/some/sensitive/file`, our walker would mirror\n // it, and any subsequent write to `<mirror>/<X>` (by us or by\n // Claude Code) would follow the symlink and overwrite the target.\n // Snapshot-copy semantics make symlink preservation moot anyway:\n // a snapshot is a point-in-time content copy, and a symlink\n // recreated in the mirror points at exactly the same target as\n // the original would have — the user-side symlink is sufficient.\n // If a user has a legitimate need for a symlink to be visible\n // through the proxy session, they can create the equivalent\n // symlink in their `~/.claude/` directly and it'll be reachable\n // — they just won't see it in our mirror dir.\n consola.debug(`mirrorDirRecursive: skipping symlink ${childSource} (security policy)`)\n return\n }\n if (stats.isDirectory()) {\n await withSlot(() => fs.mkdir(childTarget, { recursive: true }))\n await mirrorDirRecursive(sourceDir, targetDir, childRel, withSlot)\n return\n }\n if (stats.isFile()) {\n // mtime-based skip — only copy if source is newer than target.\n let needsCopy = true\n try {\n const targetStat = await withSlot(() => fs.lstat(childTarget))\n if (targetStat.isFile() && targetStat.mtimeMs >= stats.mtimeMs) {\n needsCopy = false\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n consola.debug(`mirrorDirRecursive: lstat target ${childTarget}:`, err)\n }\n }\n if (!needsCopy) return\n try {\n await withSlot(() =>\n fs.copyFile(childSource, childTarget, fs.constants.COPYFILE_FICLONE),\n )\n } catch (err) {\n consola.debug(`mirrorDirRecursive: copy ${childSource} → ${childTarget}:`, err)\n }\n return\n }\n // Skip other inode types (sockets, devices, fifos) silently.\n }),\n )\n}\n\n/**\n * Create or refresh a directory symlink `<mirrorDir>/<name>` →\n * `<sourceDir>/<name>` (i.e. `~/.local/share/github-router/claude-config/<X>`\n * → `~/.claude/<X>`). Idempotent and concurrent-safe.\n *\n * Behavior depending on what's already at `<mirrorDir>/<name>`:\n * - Symlink with the correct target → no-op.\n * - Symlink with the wrong target → replace atomically.\n * - Empty real directory (legacy mirror leftover with no proxy-session\n * writes accumulated yet) → `rmdir` and replace with the symlink.\n * Safe by definition: `fs.rmdir` only succeeds on empty dirs (POSIX),\n * so there is nothing to lose. Smooths the upgrade path for users\n * whose legacy mirror dirs were never written to.\n * - Non-empty real directory or regular file → loud-warn and skip.\n * Auto-deleting would destroy proxy-session writes from the prior\n * version. The user is told the exact path and remediation.\n * - ENOENT → create symlink atomically.\n *\n * Atomic-creation: symlinks are first written at a unique side-path\n * (`<mirrorDir>/<name>.tmp.<pid>.<8 hex>`) and then `fs.rename()`d into\n * place. POSIX `rename` is atomic and replaces an existing symlink in\n * a single step, so two concurrent `github-router claude` startups can't\n * race to `EEXIST` — the loser's rename just overwrites the winner's\n * symlink with an identical one. Gemini-critic 3-lab-review finding.\n *\n * Pre-creates `~/.claude/<name>/` as a real directory if missing so\n * Claude Code's writes through the symlink don't fail with ENOENT.\n */\nasync function ensureSharedSymlink(\n name: string,\n sourceDir: string,\n mirrorDir: string,\n): Promise<void> {\n const sourcePath = path.join(sourceDir, name)\n const mirrorPath = path.join(mirrorDir, name)\n\n // 1. Ensure the source directory exists. Without this, Claude Code's\n // writes through the symlink (e.g. `projects/<hash>/foo.jsonl`)\n // fail with ENOENT on the parent dir.\n try {\n await fs.mkdir(sourcePath, { recursive: true })\n } catch (err) {\n // Escalated from debug → warn per the CLAUDE.md \"smoking gun\"\n // rule (consistent with the symlink and rename catches below):\n // if the source dir cannot be created (e.g. a stray regular file\n // sitting at `~/.claude/projects`, perms blocking mkdir on a\n // corp-managed Windows box, OneDrive cloud-only reparse point),\n // ensureSharedSymlink returns without creating a junction. The\n // spawned Claude Code child then writes to the REAL `~/.claude`\n // while the proxy reads from the mirror — exactly the split-brain\n // pattern this whole function exists to prevent. Silent debug-log\n // hid this from us once already; warn so the user sees the cause.\n consola.warn(\n `ensureSharedSymlink(${name}): cannot mkdir source ${sourcePath}:`,\n err,\n )\n return\n }\n\n // 2. Inspect the mirror-side slot.\n let existing: Awaited<ReturnType<typeof fs.lstat>> | null = null\n try {\n existing = await fs.lstat(mirrorPath)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n // Escalated from debug → warn per the CLAUDE.md \"smoking gun\"\n // rule (consistent with the other fs catches in this function):\n // ENOENT is the only expected-and-benign failure mode here\n // (slot doesn't exist yet — falls through to create). Any other\n // lstat failure (EACCES, ELOOP, EIO from a sketchy reparse\n // point) means we bail without creating the junction, which\n // silently leaves the proxy and child diverged. A visible warn\n // surfaces the root cause instead of a mysteriously missing\n // junction.\n consola.warn(\n `ensureSharedSymlink(${name}): cannot lstat ${mirrorPath}:`,\n err,\n )\n return\n }\n }\n\n if (existing?.isSymbolicLink()) {\n // Resolve both sides to their canonical absolute paths and compare.\n // We use `fs.realpath` rather than the raw `fs.readlink()` output\n // because Windows junctions resolve via readlink to `\\\\?\\`-prefixed\n // device-namespace paths (e.g. `\\\\?\\C:\\Users\\foo\\.claude\\projects`)\n // while we wrote the plain absolute `sourcePath` (e.g.\n // `C:\\Users\\foo\\.claude\\projects`) with `fs.symlink`. A literal\n // `===` on the raw readlink output never matched on Windows, so\n // the fast path silently failed and every startup tore down +\n // recreated all 9 SHARED junctions — masked locally because NTFS\n // File System Tunneling forges the creation timestamp for a name\n // deleted and recreated within 15 s (the per-startup churn was\n // real, the ctime-stable assertion was a false negative). The\n // realpath comparison canonicalizes both forms to the same string\n // on POSIX and Windows alike, and as a bonus handles drive-letter\n // casing / trailing-slash differences too. The extra two syscalls\n // per slot are negligible at proxy startup (runs once per launch).\n //\n // CRITICAL: sourceReal and currentReal are NOT treated symmetrically.\n // If `sourceReal` is null (we just mkdir'd it above, but realpath\n // failed — OneDrive cloud-only reparse point, EACCES on parent,\n // EXDEV mount oddity), we WARN AND RETURN rather than fall through.\n // Falling through would do unlink+symlink+rename with the same\n // failing realpath next launch — silent every-startup churn, the\n // exact bug class round-3 G2 fixed in a different code path.\n // `currentReal === null` is benign (broken/wrong slot — replace).\n const sourceReal = await fs.realpath(sourcePath).catch(() => null)\n if (sourceReal === null) {\n consola.warn(\n `ensureSharedSymlink(${name}): cannot resolve source ${sourcePath} ` +\n `— skipping junction creation to avoid silent every-startup churn. ` +\n `Inspect the source dir's permissions / OneDrive sync state and re-launch.`,\n )\n return\n }\n const currentReal = await fs.realpath(mirrorPath).catch(() => null)\n if (currentReal !== null && currentReal === sourceReal) {\n return\n }\n // Wrong target (or unresolvable mirror) — fall through to the\n // atomic-rename replace path.\n } else if (existing?.isDirectory()) {\n // Legacy real directory at the slot. Try `fs.rmdir` — on POSIX it\n // succeeds ONLY if the directory is empty, so there's nothing to\n // lose. If it's non-empty (ENOTEMPTY) or any other failure occurs,\n // fall back to the warn-and-skip path so we never auto-clobber\n // user data.\n try {\n await fs.rmdir(mirrorPath)\n // Empty dir reaped — fall through to the atomic-rename create path.\n } catch (err) {\n consola.warn(\n `ensureClaudeConfigMirror: ${mirrorPath} is a non-empty real directory ` +\n `from an older github-router version; refusing to clobber. ` +\n `If you want chat-history continuity for \"${name}\", move its ` +\n `contents into ${sourcePath}/ then delete ${mirrorPath}; the ` +\n `mirror will create a symlink (junction on Windows) on next launch. ` +\n `(rmdir error: ${(err as NodeJS.ErrnoException).code ?? \"unknown\"})`,\n )\n return\n }\n } else if (existing) {\n // Regular file (or special inode like a socket) — never auto-clobber.\n consola.warn(\n `ensureClaudeConfigMirror: ${mirrorPath} is a regular file at a ` +\n `SHARED symlink slot; refusing to clobber. Inspect and remove ` +\n `manually if safe; the mirror will create a symlink on next launch.`,\n )\n return\n }\n\n // 3. Atomic-rename creation: symlink to a unique temp path, then\n // rename over the slot. `fs.rename` replaces existing symlinks\n // atomically on POSIX and is safe against concurrent racers.\n // On Windows, MoveFileEx with MOVEFILE_REPLACE_EXISTING does NOT\n // replace an existing directory or junction destination\n // (npm/cli#9021), so when the slot already holds a wrong-target\n // junction we must explicitly unlink it first. The sub-millisecond\n // window of no-link is acceptable: ensureClaudeConfigMirror is\n // idempotent under concurrency and only runs at proxy startup,\n // before any spawned Claude Code child has been launched.\n const tempPath = `${mirrorPath}.tmp.${process.pid}.${randomBytes(4).toString(\"hex\")}`\n try {\n await fs.symlink(\n sourcePath,\n tempPath,\n process.platform === \"win32\" ? \"junction\" : \"dir\",\n )\n } catch (err) {\n // Escalated from debug → warn per the CLAUDE.md \"smoking gun\" rule:\n // the rule applies to ALL fs catches in this function, not just the\n // rename one. The temp path is per-pid + 8-hex random so EEXIST is\n // essentially impossible — any failure here (EPERM on Windows\n // without DevMode, EXDEV cross-volume, ENOSPC, …) is a real\n // operational problem the user needs to see.\n consola.warn(\n `ensureSharedSymlink(${name}): symlink ${tempPath} failed:`,\n err,\n )\n return\n }\n if (process.platform === \"win32\" && existing?.isSymbolicLink()) {\n // Windows-only: clear the wrong-target junction so the rename\n // below can land. Best-effort — if a concurrent racer already\n // unlinked it, the rename succeeds as a CREATE; if a concurrent\n // racer already replaced it with a fresh junction, the rename\n // hits the catch below, which now VERIFIES the slot rather than\n // assuming a rename failure means a wrong one.\n await fs.unlink(mirrorPath).catch(() => {})\n }\n try {\n await fs.rename(tempPath, mirrorPath)\n } catch (err) {\n // A lost race is not a failure. When two `github-router claude`\n // startups (or one startup and a stale sweeper) replace the same slot,\n // the sibling's rename can land first and ours then fails against a\n // destination that is momentarily open — by which point the slot is\n // already pointing at the source this function exists to install. Ask\n // the slot what it resolves to (the same question the fast path at the\n // top asks) and only shout when it is genuinely wrong: on Windows the\n // unlink-then-rename path emitted dozens of EPERM warns per contended\n // startup, and a warn stream that is usually expected noise is exactly\n // how a real rename failure hides (the bug class this warn was added\n // for). Escalated from debug → warn per the CLAUDE.md \"smoking gun\"\n // rule remains true for the genuine-failure branch below.\n const [slotReal, wantReal] = await Promise.all([\n fs.realpath(mirrorPath).catch(() => null),\n fs.realpath(sourcePath).catch(() => null),\n ])\n if (slotReal !== null && wantReal !== null && slotReal === wantReal) {\n consola.debug(\n `ensureSharedSymlink(${name}): rename ${tempPath} → ${mirrorPath} lost a race; the slot already resolves to the right source:`,\n err,\n )\n } else {\n consola.warn(\n `ensureSharedSymlink(${name}): rename ${tempPath} → ${mirrorPath} failed:`,\n err,\n )\n }\n await fs.unlink(tempPath).catch(() => {})\n }\n}\n\nasync function ensureFile(filePath: string): Promise<void> {\n try {\n await fs.access(filePath, fs.constants.W_OK)\n } catch {\n await fs.writeFile(filePath, \"\")\n await fs.chmod(filePath, 0o600)\n }\n}\n\nasync function chmodIfPossible(target: string, mode: number): Promise<void> {\n if (process.platform === \"win32\") return // Windows chmod is no-op-ish\n try {\n await fs.chmod(target, mode)\n } catch (err) {\n consola.debug(`chmod ${target} ${mode.toString(8)} failed:`, err)\n }\n}\n\n/**\n * Write a runtime tempfile securely.\n *\n * - Mode `0o600` so other local users (multi-tenant boxes, shared\n * dev containers) can't read the per-launch nonce or runtime URL.\n * - `flag: \"wx\"` (O_CREAT | O_EXCL | O_WRONLY) refuses to overwrite\n * an existing path. POSIX open(2) with O_EXCL also rejects\n * pre-placed symlinks, killing the symlink-clobber attack vector.\n * - The caller's responsibility to pick a path NOT yet in use.\n * We intentionally do NOT pre-unlink: an `lstat` + `unlink` +\n * `open(O_EXCL)` sequence still has a TOCTOU window where an\n * attacker can drop a symlink between unlink and open. Letting\n * `wx` fail is the safer behavior — surfaces the conflict\n * instead of silently following.\n */\nexport async function writeRuntimeFileSecure(\n filePath: string,\n content: string,\n): Promise<void> {\n await fs.writeFile(filePath, content, { mode: 0o600, flag: \"wx\" })\n}\n\n/**\n * Write the ai-or-die artifact creds (base/token/sessionId/insecureTLS) to a\n * mode-600 file in the per-launch mirror so the `internal-artifact-open` hook can\n * authenticate: AIORDIE_TOKEN is stripped from the spawned child env, and passing\n * a token via argv would leak it to `ps`. Insecure-TLS mirrors the artifact\n * client's loopback-only fail-closed policy. Best-effort; atomic temp+rename.\n */\nexport async function writeArtifactCredsToMirror(\n insecureTLS: boolean,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<void> {\n const baseUrl = env.AIORDIE_BASE_URL\n const token = env.AIORDIE_TOKEN\n const sessionId = env.AIORDIE_SESSION_ID\n if (!baseUrl || !token || !sessionId) return\n const target = path.join(PATHS.CLAUDE_CONFIG_DIR, \".aiordie-artifact.json\")\n const tempPath = `${target}.${process.pid}.tmp`\n const body = JSON.stringify({ baseUrl, token, sessionId, insecureTLS }) + \"\\n\"\n await fs.writeFile(tempPath, body, { mode: 0o600, flag: \"wx\" }).catch(async (err) => {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") return\n throw err\n })\n await fs.rename(tempPath, target).catch(() => {})\n await chmodIfPossible(target, 0o600)\n}\n\n/**\n * Sweep stale runtime tempfiles. Removes files whose embedded PID is no\n * longer a live process. A proxy crash (`kill -9`, OS reboot) leaves\n * orphans that would otherwise accumulate forever — and worse, a stale\n * config pointing at a now-recycled port could route MCP traffic to\n * whatever process bound that port next.\n *\n * Naming convention: `peer-mcp-<pid>.json` and `peer-agents-<pid>.json`.\n * Files not matching either pattern are left alone — this directory\n * is shared with future runtime artifacts.\n *\n * We deliberately do NOT age-prune files whose PID is alive. A\n * legitimately long-running proxy can have a tempfile older than any\n * arbitrary threshold; deleting it out from under the live process\n * breaks the spawned Claude Code child's MCP/agent wiring with no clean\n * recovery. PID-wraparound risk is mitigated by (a) PID reuse on Linux\n * being slow under typical loads, and (b) the file is only consulted by\n * github-router itself — an unrelated process that inherits the PID\n * never reads it.\n */\nexport async function sweepStaleRuntimeFiles(): Promise<void> {\n const dir = PATHS.CLAUDE_RUNTIME_DIR\n let entries: Array<string>\n try {\n entries = await fs.readdir(dir)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return\n throw err\n }\n\n for (const name of entries) {\n // Match both legacy `peer-mcp-<pid>.json` and current\n // `peer-mcp-<pid>-<rand>.json` filenames so we can clean up either.\n const match = /^peer-(?:mcp|agents)-(\\d+)(?:-[0-9a-f]+)?\\.json$/.exec(name)\n if (!match) continue\n const pid = Number.parseInt(match[1], 10)\n const filePath = path.join(dir, name)\n\n if (isPidAlive(pid)) continue\n\n await fs.unlink(filePath).catch(() => {\n // already gone or unreadable, fine\n })\n }\n}\n\nfunction isPidAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n // signal 0 = check existence without delivering a signal. EPERM\n // means the process exists but we can't signal it (which is still\n // \"alive\" for our purposes); ESRCH means it's gone.\n process.kill(pid, 0)\n return true\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === \"EPERM\") return true\n return false\n }\n}\n\n/**\n * Sweep stale peer-* subagent .md files from the router-owned\n * `CLAUDE_CONFIG_DIR/agents/`. Phase 2.5 writes one .md per peer agent\n * into Claude Code's agents directory (now our config dir's `agents/`\n * subdir, since `getClaudeCodeEnvVars` points `CLAUDE_CONFIG_DIR` at\n * `PATHS.CLAUDE_CONFIG_DIR`) so they appear in Claude Code's Task\n * `subagent_type` enum. Files are named `peer-<pid>-<rand>-<agentName>.md`\n * so this sweep can drop orphans from crashed prior proxy sessions\n * without touching the user's own .md files (which were copied into\n * the same dir during `ensureClaudeConfigMirror`).\n *\n * Same liveness rule as `sweepStaleRuntimeFiles`: only delete when the\n * file's embedded PID is no longer alive. Live PIDs keep their files —\n * a long-running proxy doesn't lose its agent registrations.\n *\n * Regex tightening (Phase 2.6, codex-critic + gemini-critic 2-lab finding):\n * the original sweep regex `^peer-(\\d+)(?:-[0-9a-f]+)?-.+\\.md$` was too\n * permissive — a user-authored `peer-12345-meeting-notes.md` matches\n * (`12345` = \"PID\", `-meeting-notes` = trailing `.+`) and would be\n * silently unlinked when 12345 happens to be a dead PID (overwhelmingly\n * likely). Tightened to require BOTH the 8-hex-char random suffix AND\n * an exact-match persona name suffix, eliminating the risk for any\n * realistic user filename.\n *\n * SCOPE IS THE MIRROR ONLY, deliberately. This deletes on filename shape plus\n * PID liveness, and neither establishes ownership: a user who copied a generated\n * file to customize it would have a file this cannot distinguish from ours. That\n * ambiguity is acceptable inside the router-owned mirror, where the worst case\n * is dropping a snapshot that the next launch regenerates. It would NOT be\n * acceptable in the user's real `~/.claude/agents/`, where the same false\n * positive is permanent data loss, which is exactly why `agents` is MIRRORED\n * rather than SHARED (see `policyFor`). Orphans a pre-mirror release left in the\n * user's directory are handled non-destructively at the copy step in\n * `mirrorDirRecursive`, which skips them so they never register.\n */\nexport async function sweepStalePeerAgentMdFiles(): Promise<void> {\n const dir = path.join(PATHS.CLAUDE_CONFIG_DIR, \"agents\")\n let entries: Array<string>\n try {\n entries = await fs.readdir(dir)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return\n throw err\n }\n for (const name of entries) {\n const match = PEER_AGENT_MD_FILENAME.exec(name)\n if (!match) continue\n const pid = Number.parseInt(match[1], 10)\n if (isPidAlive(pid)) continue\n await fs.unlink(path.join(dir, name)).catch(() => {\n // already gone or unreadable, fine\n })\n }\n}\n\n/**\n * Remove user-supplied subagent definitions from the router-owned mirror's\n * `agents/` dir on pinned-profile launches (fast/cheap/cheap1m/cheapest),\n * which run router-provided surfaces only. Deletes every `*.md` file that\n * does NOT match `PEER_AGENT_MD_FILENAME` — i.e. files the proxy could\n * never have written, which can only have arrived via the `~/.claude/`\n * snapshot copy. Router-shaped files are left alone (the PID-liveness\n * sweep above owns them, and this launch's own peer files are written\n * after this purge runs).\n *\n * SCOPE IS THE MIRROR ONLY: the operator's real `~/.claude/agents/`\n * is never touched. Returns the number of files removed (for launch\n * logging). Missing dir → 0.\n */\nexport async function purgeNonRouterAgentsFromMirror(): Promise<number> {\n const dir = path.join(PATHS.CLAUDE_CONFIG_DIR, \"agents\")\n let entries: Array<string>\n try {\n entries = await fs.readdir(dir)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return 0\n throw err\n }\n let removed = 0\n for (const name of entries) {\n if (!name.endsWith(\".md\")) continue\n if (PEER_AGENT_MD_FILENAME.exec(name)) continue\n await fs.unlink(path.join(dir, name)).catch(() => {\n // already gone or unreadable — treat as removed anyway so the\n // launch log reflects the attempt, not the race\n })\n removed += 1\n }\n return removed\n}\n\n/**\n * Strict regex matching only files this proxy writes:\n * peer-<pid>-<8 hex>-<exact persona/coordinator/native/dispatcher name>.md\n * The name allowlist is the load-bearing protection against deleting user\n * files. Update this list whenever a new persona is added to `PERSONAS_READ` /\n * `PERSONAS_WRITE` in `peer-mcp-personas.ts`, a new coordinator-style or native\n * subagent is added in `codex-mcp-config.ts`, or a new `worker-*` dispatcher mode\n * is added in `worker-dispatch.ts` (a drift test in tests/worker-dispatch pins\n * that the `ALL_DISPATCHER_AGENT_NAMES` are all covered here).\n *\n * NAMES ARE ADDED HERE, NEVER REMOVED — this alternation is a permanent superset\n * of every agent name the proxy has ever shipped. A name dropped on a rename\n * stops matching, so `.md` files left behind by a crashed session bearing the old\n * name are never swept: they survive every later launch and load as ghost\n * subagents with a stale prompt and a stale model. That outlives any release\n * window, so \"keep the old name for one version\" is not sufficient. `debugger`\n * and `qa-engineer` are retained for exactly this reason after being renamed to\n * `brainstorm` and `reviewer`.\n *\n * `general-purpose|Explore|Plan` are the serve-only `BUILTIN_SUBAGENT_DEFINITIONS`,\n * which are written through the same `peer-<suffix>-<name>.md` path and were\n * previously absent here, so their stale files never got reaped. Note the capitals:\n * the alternation is case-sensitive and those two are capitalized at the source.\n */\nexport const PEER_AGENT_MD_FILENAME =\n /^peer-(\\d+)-[0-9a-f]{8}-(?:codex-critic|codex-reviewer|sonnet-reviewer|gemini-critic|gemini-reviewer|opus-critic|sol-critic|luna-reviewer|grok-critic|grok-reviewer|codex-implementer|peer-review-coordinator|implementer-fast|implementer|planner|reviewer|reviewer-fast|brainstorm|scout|scribe|general-purpose-fast|critic|generic-fast|generic-cheap|generic|debugger|qa-engineer|general-purpose|General-Purpose|Explore|Plan|worker-explore|worker-implement|worker-review|worker-plan|worker-test|worker-browse)\\.md$/\n\n/**\n * Strict regex matching only per-launch claude-config mirror dirs this\n * proxy creates: `<pid>-<8 hex>`. Anchored to the entire entry name so\n * user-authored siblings under `<appDir>/claude-config/` (if any) are\n * untouchable. The PID prefix is what `sweepStaleClaudeConfigMirrors`\n * keys off; the 8-hex random suffix matches `randomBytes(4)` exactly\n * (no `?` — files created by a different shape are not ours).\n */\nconst CLAUDE_CONFIG_MIRROR_DIR = /^(\\d+)-[0-9a-f]{8}$/\n\n/**\n * Sweep stale per-launch CLAUDE_CONFIG_DIR mirrors left behind by\n * crashed prior proxy sessions. Symmetric to `sweepStalePeerAgentMdFiles`\n * — same liveness rule (only delete when the embedded PID is dead),\n * same strict regex (the dir-name allowlist is the load-bearing\n * protection against deleting user-authored siblings).\n *\n * Scans `<appDir>/claude-config/` (the parent of the per-launch dirs).\n * Each entry whose name matches `<pid>-<8 hex>` AND whose PID is no\n * longer alive is removed recursively. `fs.rm({recursive: true})`\n * walks the tree calling `unlink` on symlinks/junctions rather than\n * following them, so the SHARED junctions back to `~/.claude/<X>`\n * are removed without touching their targets.\n *\n * Tolerates missing parent dir (first-ever launch, or user wiped it).\n */\nexport async function sweepStaleClaudeConfigMirrors(): Promise<void> {\n const parent = path.join(appDir(), \"claude-config\")\n let entries: Array<string>\n try {\n entries = await fs.readdir(parent)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return\n throw err\n }\n for (const name of entries) {\n const match = CLAUDE_CONFIG_MIRROR_DIR.exec(name)\n if (!match) continue\n const pid = Number.parseInt(match[1], 10)\n if (isPidAlive(pid)) continue\n await fs\n .rm(path.join(parent, name), { recursive: true, force: true })\n .catch((err) => {\n // Best-effort: stale-dir cleanup must never block startup.\n // Common failure modes (worth surviving silently): an EBUSY/EPERM\n // on Windows if a leftover handle is still open, or a stray\n // root-owned file inside the dir from a previous run with\n // different permissions.\n consola.debug(\n `sweepStaleClaudeConfigMirrors: cannot rm ${name}:`,\n err,\n )\n })\n }\n}\n\n/**\n * Remove THIS launch's per-launch CLAUDE_CONFIG_DIR on shutdown.\n * Best-effort: a failure here must not block process exit (the caller\n * wraps this in a `.catch`-equivalent via `launchChild`'s onShutdown\n * try/catch). Symmetric to `writePeerMcpRuntimeFiles`'s `cleanup()`:\n * we own this dir for the lifetime of the proxy, so removing it on\n * normal shutdown is correct; the boot-time sweep handles the\n * abnormal-exit case.\n *\n * `fs.rm({recursive: true})` removes SHARED junctions via unlink\n * (does NOT follow them into the user's real `~/.claude/<X>`).\n */\nexport async function removeOwnClaudeConfigMirror(): Promise<void> {\n const dir = PATHS.CLAUDE_CONFIG_DIR\n await fs.rm(dir, { recursive: true, force: true }).catch((err) => {\n consola.debug(`removeOwnClaudeConfigMirror: rm ${dir} skipped:`, err)\n })\n}\n"],"mappings":";;;;;;AAIA,MAAM,sCAAsB,IAAI,IAAoB;CAClD,CAAC,cAAc,EAAE;CACjB,CAAC,eAAe,EAAE;CAClB,CAAC,sBAAsB,EAAE;CACzB,CAAC,qBAAqB,IAAI;CAC1B,CAAC,QAAQ,EAAE;CACX,CAAC,gBA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